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 |
|---|---|---|---|---|---|
RTGUI 0.6.1 Release Notes
This is mainly a bug fixing release. Now the window system can be used
intensively.
# Running Environment
In theory, new RTGUI can run on all the devices running old RTGUI. There is
a simulator which run on Windows to help evaluating the new RTGUI. The default
running environment is RealTouch. The simulator in RT-Thread could also be used.
Because RT-Thread has removed all the RTGUI components from the source tree, in
order to run RTGUI in the upstream RT-Thread, you have to copy the
`components/rtgui` to the `components` folder in RTT. If you need demo, files
in `demo/examples` should also be copied into `examples/gui`.
# Main Changes
0. Simplified the windows showing algorithm. Children window will always be
shown when parent window has been shown. 257589a
0. Move `calibration.c` in bsps into RTGUI. There is no need to write it's
own `calibration.c` for all the bsps. calibration in RTGUI provides
`calibration_set_restore` and `calibration_set_after` API, by which the user
could use to skip the calibration or save calibration data. The example is
in bsp/stm31f10x . bd7c6e4
# Bug fixes
- 3ce204d: fixed the children window of root window could not be modaled bug.
- 4d5564d: `rtgui_widget_update_clip` could not be used on window. Thanks to
xiao苦 for reporting the bug.
- dfb477e: repaint the whole window tree when one window in the tree has been activated.
- f42adc2: delete useless RTM\_EXPORT. Thanks to prife for bug reporting.
- cb3bf9a: fixed clip updating bug when hiding widgets. Thanks to xiao苦 for
bug reporting.
- 110e0c6: When file fonts has been enabled but the file could not be opened,
fire a warning on console. Thanks to prife, 文哥 and wnnwoo .
- 7611e37: fixed compiling error in demo\_view\_listctrl . Thanks to znfc2 .
- 3b1f698: added a underflow check on `ref_count` in `rtgui_app_exit`.
| RT-Thread/realboard-lpc4088 | software/rtthread_examples/rtgui/doc/ANNOUNCE.0.6.1.md | Markdown | gpl-2.0 | 1,891 |
<?php
/**
* Magento
*
* 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@magentocommerce.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade Magento to newer
* versions in the future. If you wish to customize Magento for your
* needs please refer to http://www.magentocommerce.com for more information.
*
* @category Mage
* @package Mage_Paypal
* @copyright Copyright (c) 2012 Magento Inc. (http://www.magentocommerce.com)
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
*/
/**
* PayPal Standard payment "form"
*/
class Mage_Paypal_Block_Express_Form extends Mage_Paypal_Block_Standard_Form
{
/**
* Payment method code
* @var string
*/
protected $_methodCode = Mage_Paypal_Model_Config::METHOD_WPP_EXPRESS;
/**
* Set template and redirect message
*/
protected function _construct()
{
$result = parent::_construct();
$this->setRedirectMessage(Mage::helper('paypal')->__('You will be redirected to the PayPal website.'));
return $result;
}
/**
* Set data to block
*
* @return Mage_Core_Block_Abstract
*/
protected function _beforeToHtml()
{
$customerId = Mage::getSingleton('customer/session')->getCustomerId();
if (Mage::helper('paypal')->shouldAskToCreateBillingAgreement($this->_config, $customerId)
&& $this->canCreateBillingAgreement()) {
$this->setCreateBACode(Mage_Paypal_Model_Express_Checkout::PAYMENT_INFO_TRANSPORT_BILLING_AGREEMENT);
}
return parent::_beforeToHtml();
}
}
| keegan2149/magento | sites/default/app/code/core/Mage/Paypal/Block/Express/Form.php | PHP | gpl-2.0 | 2,041 |
/*
Copyright (c) 2003-2014, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.md or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang( 'elementspath', 'si', {
eleLabel: 'මුලද්රව්ය මාර්ගය',
eleTitle: '%1 මුල'
} );
| gmuro/dolibarr | htdocs/includes/ckeditor/ckeditor/_source/plugins/elementspath/lang/si.js | JavaScript | gpl-3.0 | 291 |
/* *
* (c) 2010-2019 Torstein Honsi
*
* License: www.highcharts.com/license
*/
'use strict';
import H from './Globals.js';
import './Utilities.js';
import './Options.js';
import './Series.js';
var pick = H.pick,
seriesType = H.seriesType;
/**
* Spline series type.
*
* @private
* @class
* @name Highcharts.seriesTypes.spline
*
* @augments Highcarts.Series
*/
seriesType(
'spline',
'line',
/**
* A spline series is a special type of line series, where the segments
* between the data points are smoothed.
*
* @sample {highcharts} highcharts/demo/spline-irregular-time/
* Spline chart
* @sample {highstock} stock/demo/spline/
* Spline chart
*
* @extends plotOptions.series
* @excluding step
* @product highcharts highstock
* @optionparent plotOptions.spline
*/
{
},
/** @lends seriesTypes.spline.prototype */ {
/**
* Get the spline segment from a given point's previous neighbour to the
* given point.
*
* @private
* @function Highcharts.seriesTypes.spline#getPointSpline
*
* @param {Array<Highcharts.Point>}
*
* @param {Highcharts.Point} point
*
* @param {number} i
*
* @return {Highcharts.SVGPathArray}
*/
getPointSpline: function (points, point, i) {
var
// 1 means control points midway between points, 2 means 1/3
// from the point, 3 is 1/4 etc
smoothing = 1.5,
denom = smoothing + 1,
plotX = point.plotX,
plotY = point.plotY,
lastPoint = points[i - 1],
nextPoint = points[i + 1],
leftContX,
leftContY,
rightContX,
rightContY,
ret;
function doCurve(otherPoint) {
return otherPoint &&
!otherPoint.isNull &&
otherPoint.doCurve !== false &&
!point.isCliff; // #6387, area splines next to null
}
// Find control points
if (doCurve(lastPoint) && doCurve(nextPoint)) {
var lastX = lastPoint.plotX,
lastY = lastPoint.plotY,
nextX = nextPoint.plotX,
nextY = nextPoint.plotY,
correction = 0;
leftContX = (smoothing * plotX + lastX) / denom;
leftContY = (smoothing * plotY + lastY) / denom;
rightContX = (smoothing * plotX + nextX) / denom;
rightContY = (smoothing * plotY + nextY) / denom;
// Have the two control points make a straight line through main
// point
if (rightContX !== leftContX) { // #5016, division by zero
correction = (
((rightContY - leftContY) * (rightContX - plotX)) /
(rightContX - leftContX) + plotY - rightContY
);
}
leftContY += correction;
rightContY += correction;
// to prevent false extremes, check that control points are
// between neighbouring points' y values
if (leftContY > lastY && leftContY > plotY) {
leftContY = Math.max(lastY, plotY);
// mirror of left control point
rightContY = 2 * plotY - leftContY;
} else if (leftContY < lastY && leftContY < plotY) {
leftContY = Math.min(lastY, plotY);
rightContY = 2 * plotY - leftContY;
}
if (rightContY > nextY && rightContY > plotY) {
rightContY = Math.max(nextY, plotY);
leftContY = 2 * plotY - rightContY;
} else if (rightContY < nextY && rightContY < plotY) {
rightContY = Math.min(nextY, plotY);
leftContY = 2 * plotY - rightContY;
}
// record for drawing in next point
point.rightContX = rightContX;
point.rightContY = rightContY;
}
// Visualize control points for debugging
/*
if (leftContX) {
this.chart.renderer.circle(
leftContX + this.chart.plotLeft,
leftContY + this.chart.plotTop,
2
)
.attr({
stroke: 'red',
'stroke-width': 2,
fill: 'none',
zIndex: 9
})
.add();
this.chart.renderer.path(['M', leftContX + this.chart.plotLeft,
leftContY + this.chart.plotTop,
'L', plotX + this.chart.plotLeft, plotY + this.chart.plotTop])
.attr({
stroke: 'red',
'stroke-width': 2,
zIndex: 9
})
.add();
}
if (rightContX) {
this.chart.renderer.circle(
rightContX + this.chart.plotLeft,
rightContY + this.chart.plotTop,
2
)
.attr({
stroke: 'green',
'stroke-width': 2,
fill: 'none',
zIndex: 9
})
.add();
this.chart.renderer.path(['M', rightContX + this.chart.plotLeft,
rightContY + this.chart.plotTop,
'L', plotX + this.chart.plotLeft, plotY + this.chart.plotTop])
.attr({
stroke: 'green',
'stroke-width': 2,
zIndex: 9
})
.add();
}
// */
ret = [
'C',
pick(lastPoint.rightContX, lastPoint.plotX),
pick(lastPoint.rightContY, lastPoint.plotY),
pick(leftContX, plotX),
pick(leftContY, plotY),
plotX,
plotY
];
// reset for updating series later
lastPoint.rightContX = lastPoint.rightContY = null;
return ret;
}
}
);
/**
* A `spline` series. If the [type](#series.spline.type) option is
* not specified, it is inherited from [chart.type](#chart.type).
*
* @extends series,plotOptions.spline
* @excluding dataParser, dataURL, step
* @product highcharts highstock
* @apioption series.spline
*/
/**
* An array of data points for the series. For the `spline` series type,
* points can be given in the following ways:
*
* 1. An array of numerical values. In this case, the numerical values will be
* interpreted as `y` options. The `x` values will be automatically
* calculated, either starting at 0 and incremented by 1, or from
* `pointStart` and `pointInterval` given in the series options. If the axis
* has categories, these will be used. Example:
* ```js
* data: [0, 5, 3, 5]
* ```
*
* 2. An array of arrays with 2 values. In this case, the values correspond to
* `x,y`. If the first value is a string, it is applied as the name of the
* point, and the `x` value is inferred.
* ```js
* data: [
* [0, 9],
* [1, 2],
* [2, 8]
* ]
* ```
*
* 3. An array of objects with named values. The following snippet shows only a
* few settings, see the complete options set below. If the total number of
* data points exceeds the series'
* [turboThreshold](#series.spline.turboThreshold), this option is not
* available.
* ```js
* data: [{
* x: 1,
* y: 9,
* name: "Point2",
* color: "#00FF00"
* }, {
* x: 1,
* y: 0,
* name: "Point1",
* color: "#FF00FF"
* }]
* ```
*
* @sample {highcharts} highcharts/chart/reflow-true/
* Numerical values
* @sample {highcharts} highcharts/series/data-array-of-arrays/
* Arrays of numeric x and y
* @sample {highcharts} highcharts/series/data-array-of-arrays-datetime/
* Arrays of datetime x and y
* @sample {highcharts} highcharts/series/data-array-of-name-value/
* Arrays of point.name and y
* @sample {highcharts} highcharts/series/data-array-of-objects/
* Config objects
*
* @type {Array<number|Array<(number|string),number>|*>}
* @extends series.line.data
* @product highcharts highstock
* @apioption series.spline.data
*/
| blue-eyed-devil/testCMS | externals/highcharts/es-modules/parts/SplineSeries.js | JavaScript | gpl-3.0 | 8,806 |
#!/usr/bin/python
# -*- coding: utf-8 -*-
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
#
# Copyright (C) 2017 Lenovo, Inc.
#
# This file is part of Ansible
#
# Ansible 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.
#
# Ansible 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 Ansible. If not, see <http://www.gnu.org/licenses/>.
#
# Module to Reset to factory settings of Lenovo Switches
# Lenovo Networking
#
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
DOCUMENTATION = '''
---
module: cnos_factory
author: "Anil Kumar Muraleedharan (@amuraleedhar)"
short_description: Reset the switch's startup configuration to default (factory) on devices running Lenovo CNOS
description:
- This module allows you to reset a switch's startup configuration. The method provides a way to reset the
startup configuration to its factory settings. This is helpful when you want to move the switch to another
topology as a new network device.
This module uses SSH to manage network device configuration.
The results of the operation can be viewed in results directory.
For more information about this module from Lenovo and customizing it usage for your
use cases, please visit U(http://systemx.lenovofiles.com/help/index.jsp?topic=%2Fcom.lenovo.switchmgt.ansible.doc%2Fcnos_factory.html)
version_added: "2.3"
extends_documentation_fragment: cnos
options: {}
'''
EXAMPLES = '''
Tasks : The following are examples of using the module cnos_reload. These are written in the main.yml file of the tasks directory.
---
- name: Test Reset to factory
cnos_factory:
host: "{{ inventory_hostname }}"
username: "{{ hostvars[inventory_hostname]['ansible_ssh_user'] }}"
password: "{{ hostvars[inventory_hostname]['ansible_ssh_pass'] }}"
deviceType: "{{ hostvars[inventory_hostname]['deviceType'] }}"
outputfile: "./results/test_factory_{{ inventory_hostname }}_output.txt"
'''
RETURN = '''
msg:
description: Success or failure message
returned: always
type: string
sample: "Switch Startup Config is Reset to factory settings"
'''
import sys
try:
import paramiko
HAS_PARAMIKO = True
except ImportError:
HAS_PARAMIKO = False
import time
import socket
import array
import json
import time
import re
try:
from ansible.module_utils.network.cnos import cnos
HAS_LIB = True
except:
HAS_LIB = False
from ansible.module_utils.basic import AnsibleModule
from collections import defaultdict
def main():
module = AnsibleModule(
argument_spec=dict(
outputfile=dict(required=True),
host=dict(required=True),
username=dict(required=True),
password=dict(required=True, no_log=True),
enablePassword=dict(required=False, no_log=True),
deviceType=dict(required=True),),
supports_check_mode=False)
username = module.params['username']
password = module.params['password']
enablePassword = module.params['enablePassword']
cliCommand = "save erase \n"
outputfile = module.params['outputfile']
hostIP = module.params['host']
deviceType = module.params['deviceType']
output = ""
if not HAS_PARAMIKO:
module.fail_json(msg='paramiko is required for this module')
# Create instance of SSHClient object
remote_conn_pre = paramiko.SSHClient()
# Automatically add untrusted hosts (make sure okay for security policy in your environment)
remote_conn_pre.set_missing_host_key_policy(paramiko.AutoAddPolicy())
# initiate SSH connection with the switch
remote_conn_pre.connect(hostIP, username=username, password=password)
time.sleep(2)
# Use invoke_shell to establish an 'interactive session'
remote_conn = remote_conn_pre.invoke_shell()
time.sleep(2)
# Enable and enter configure terminal then send command
output = output + cnos.waitForDeviceResponse("\n", ">", 2, remote_conn)
output = output + cnos.enterEnableModeForDevice(enablePassword, 3, remote_conn)
# Make terminal length = 0
output = output + cnos.waitForDeviceResponse("terminal length 0\n", "#", 2, remote_conn)
# cnos.debugOutput(cliCommand)
# Send the CLi command
output = output + cnos.waitForDeviceResponse(cliCommand, "[n]", 2, remote_conn)
output = output + cnos.waitForDeviceResponse("y" + "\n", "#", 2, remote_conn)
# Save it into the file
file = open(outputfile, "a")
file.write(output)
file.close()
errorMsg = cnos.checkOutputForError(output)
if(errorMsg is None):
module.exit_json(changed=True, msg="Switch Startup Config is Reset to factory settings ")
else:
module.fail_json(msg=errorMsg)
if __name__ == '__main__':
main()
| hryamzik/ansible | lib/ansible/modules/network/cnos/cnos_factory.py | Python | gpl-3.0 | 5,299 |
/* -*- c++ -*- */
/*
* Copyright 2002 Free Software Foundation, Inc.
*
* This file is part of GNU Radio
*
* GNU Radio is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3, or (at your option)
* any later version.
*
* GNU Radio is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with GNU Radio; see the file COPYING. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street,
* Boston, MA 02110-1301, USA.
*/
#ifndef _QA_INTERLEAVER_FIFO_H_
#define _QA_INTERLEAVER_FIFO_H_
#include <cppunit/extensions/HelperMacros.h>
#include <cppunit/TestCase.h>
#include <interleaver_fifo.h>
class qa_interleaver_fifo : public CppUnit::TestCase {
private:
interleaver_fifo<int> *fifo;
public:
void tearDown (){
delete fifo;
fifo = 0;
}
CPPUNIT_TEST_SUITE (qa_interleaver_fifo);
CPPUNIT_TEST (t0);
CPPUNIT_TEST (t1);
CPPUNIT_TEST (t2);
CPPUNIT_TEST_SUITE_END ();
private:
void t0 ();
void t1 ();
void t2 ();
};
#endif /* _QA_INTERLEAVER_FIFO_H_ */
| tyc85/nwsdr-3.6.3-dsc | gr-atsc/src/lib/qa_interleaver_fifo.h | C | gpl-3.0 | 1,390 |
package org.zarroboogs.weibo.dao;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.zarroboogs.util.net.HttpUtility;
import org.zarroboogs.util.net.WeiboException;
import org.zarroboogs.util.net.HttpUtility.HttpMethod;
import org.zarroboogs.utils.ImageUtility;
import org.zarroboogs.utils.WeiBoURLs;
import org.zarroboogs.utils.file.FileLocationMethod;
import org.zarroboogs.utils.file.FileManager;
import org.zarroboogs.weibo.support.asyncdrawable.TaskCache;
import android.graphics.Bitmap;
import android.text.TextUtils;
import java.util.HashMap;
import java.util.Map;
public class MapDao {
public Bitmap getMap() throws WeiboException {
String url = WeiBoURLs.STATIC_MAP;
Map<String, String> map = new HashMap<String, String>();
map.put("access_token", access_token);
String coordinates = String.valueOf(lat) + "," + String.valueOf(lan);
map.put("center_coordinate", coordinates);
map.put("zoom", "14");
map.put("size", "600x380");
String jsonData = HttpUtility.getInstance().executeNormalTask(HttpMethod.Get, url, map);
String mapUrl = "";
try {
JSONObject jsonObject = new JSONObject(jsonData);
JSONArray array = jsonObject.optJSONArray("map");
jsonObject = array.getJSONObject(0);
mapUrl = jsonObject.getString("image_url");
} catch (JSONException e) {
}
if (TextUtils.isEmpty(mapUrl)) {
return null;
}
String filePath = FileManager.getFilePathFromUrl(mapUrl, FileLocationMethod.map);
boolean downloaded = TaskCache.waitForPictureDownload(mapUrl, null, filePath, FileLocationMethod.map);
if (!downloaded) {
return null;
}
Bitmap bitmap = ImageUtility.readNormalPic(FileManager.getFilePathFromUrl(mapUrl, FileLocationMethod.map), -1, -1);
return bitmap;
}
public MapDao(String token, double lan, double lat) {
this.access_token = token;
this.lan = lan;
this.lat = lat;
}
private String access_token;
private double lan;
private double lat;
}
| tsdl2013/iBeebo | app/src/main/java/org/zarroboogs/weibo/dao/MapDao.java | Java | gpl-3.0 | 2,199 |
/**
* Copyright (c) 2006-2015, JGraph Ltd
* Copyright (c) 2006-2015, Gaudenz Alder
*/
/**
* Class: mxHandle
*
* Implements a single custom handle for vertices.
*
* Constructor: mxHandle
*
* Constructs a new handle for the given state.
*
* Parameters:
*
* state - <mxCellState> of the cell to be handled.
*/
function mxHandle(state, cursor, image)
{
this.graph = state.view.graph;
this.state = state;
this.cursor = (cursor != null) ? cursor : this.cursor;
this.image = (image != null) ? image : this.image;
this.init();
};
/**
* Variable: cursor
*
* Specifies the cursor to be used for this handle. Default is 'default'.
*/
mxHandle.prototype.cursor = 'default';
/**
* Variable: image
*
* Specifies the <mxImage> to be used to render the handle. Default is null.
*/
mxHandle.prototype.image = null;
/**
* Variable: image
*
* Specifies the <mxImage> to be used to render the handle. Default is null.
*/
mxHandle.prototype.ignoreGrid = false;
/**
* Function: getPosition
*
* Hook for subclassers to return the current position of the handle.
*/
mxHandle.prototype.getPosition = function(bounds) { };
/**
* Function: setPosition
*
* Hooks for subclassers to update the style in the <state>.
*/
mxHandle.prototype.setPosition = function(bounds, pt, me) { };
/**
* Function: execute
*
* Hook for subclassers to execute the handle.
*/
mxHandle.prototype.execute = function() { };
/**
* Function: copyStyle
*
* Sets the cell style with the given name to the corresponding value in <state>.
*/
mxHandle.prototype.copyStyle = function(key)
{
this.graph.setCellStyles(key, this.state.style[key], [this.state.cell]);
};
/**
* Function: processEvent
*
* Processes the given <mxMouseEvent> and invokes <setPosition>.
*/
mxHandle.prototype.processEvent = function(me)
{
var scale = this.graph.view.scale;
var tr = this.graph.view.translate;
var pt = new mxPoint(me.getGraphX() / scale - tr.x, me.getGraphY() / scale - tr.y);
// Center shape on mouse cursor
if (this.shape != null && this.shape.bounds != null)
{
pt.x -= this.shape.bounds.width / scale / 4;
pt.y -= this.shape.bounds.height / scale / 4;
}
// Snaps to grid for the rotated position then applies the rotation for the direction after that
var alpha1 = -mxUtils.toRadians(this.getRotation());
var alpha2 = -mxUtils.toRadians(this.getTotalRotation()) - alpha1;
pt = this.flipPoint(this.rotatePoint(this.snapPoint(this.rotatePoint(pt, alpha1),
this.ignoreGrid || !this.graph.isGridEnabledEvent(me.getEvent())), alpha2));
this.setPosition(this.state.getPaintBounds(), pt, me);
this.positionChanged();
this.redraw();
};
/**
* Function: positionChanged
*
* Called after <setPosition> has been called in <processEvent>. This repaints
* the state using <mxCellRenderer>.
*/
mxHandle.prototype.positionChanged = function()
{
if (this.state.text != null)
{
this.state.text.apply(this.state);
}
if (this.state.shape != null)
{
this.state.shape.apply(this.state);
}
this.graph.cellRenderer.redraw(this.state, true);
};
/**
* Function: getRotation
*
* Returns the rotation defined in the style of the cell.
*/
mxHandle.prototype.getRotation = function()
{
if (this.state.shape != null)
{
return this.state.shape.getRotation();
}
return 0;
};
/**
* Function: getTotalRotation
*
* Returns the rotation from the style and the rotation from the direction of
* the cell.
*/
mxHandle.prototype.getTotalRotation = function()
{
if (this.state.shape != null)
{
return this.state.shape.getShapeRotation();
}
return 0;
};
/**
* Function: init
*
* Creates and initializes the shapes required for this handle.
*/
mxHandle.prototype.init = function()
{
var html = this.isHtmlRequired();
if (this.image != null)
{
this.shape = new mxImageShape(new mxRectangle(0, 0, this.image.width, this.image.height), this.image.src);
this.shape.preserveImageAspect = false;
}
else
{
this.shape = this.createShape(html);
}
this.initShape(html);
};
/**
* Function: createShape
*
* Creates and returns the shape for this handle.
*/
mxHandle.prototype.createShape = function(html)
{
var bounds = new mxRectangle(0, 0, mxConstants.HANDLE_SIZE, mxConstants.HANDLE_SIZE);
return new mxRectangleShape(bounds, mxConstants.HANDLE_FILLCOLOR, mxConstants.HANDLE_STROKECOLOR);
};
/**
* Function: initShape
*
* Initializes <shape> and sets its cursor.
*/
mxHandle.prototype.initShape = function(html)
{
if (html && this.shape.isHtmlAllowed())
{
this.shape.dialect = mxConstants.DIALECT_STRICTHTML;
this.shape.init(this.graph.container);
}
else
{
this.shape.dialect = (this.graph.dialect != mxConstants.DIALECT_SVG) ? mxConstants.DIALECT_MIXEDHTML : mxConstants.DIALECT_SVG;
if (this.cursor != null)
{
this.shape.init(this.graph.getView().getOverlayPane());
}
}
mxEvent.redirectMouseEvents(this.shape.node, this.graph, this.state);
this.shape.node.style.cursor = this.cursor;
};
/**
* Function: redraw
*
* Renders the shape for this handle.
*/
mxHandle.prototype.redraw = function()
{
if (this.shape != null && this.state.shape != null)
{
var pt = this.getPosition(this.state.getPaintBounds());
if (pt != null)
{
var alpha = mxUtils.toRadians(this.getTotalRotation());
pt = this.rotatePoint(this.flipPoint(pt), alpha);
var scale = this.graph.view.scale;
var tr = this.graph.view.translate;
this.shape.bounds.x = Math.floor((pt.x + tr.x) * scale - this.shape.bounds.width / 2);
this.shape.bounds.y = Math.floor((pt.y + tr.y) * scale - this.shape.bounds.height / 2);
// Needed to force update of text bounds
this.state.unscaledWidth = null;
this.shape.redraw();
}
}
};
/**
* Function: isHtmlRequired
*
* Returns true if this handle should be rendered in HTML. This returns true if
* the text node is in the graph container.
*/
mxHandle.prototype.isHtmlRequired = function()
{
return this.state.text != null && this.state.text.node.parentNode == this.graph.container;
};
/**
* Function: rotatePoint
*
* Rotates the point by the given angle.
*/
mxHandle.prototype.rotatePoint = function(pt, alpha)
{
var bounds = this.state.getCellBounds();
var cx = new mxPoint(bounds.getCenterX(), bounds.getCenterY());
var cos = Math.cos(alpha);
var sin = Math.sin(alpha);
return mxUtils.getRotatedPoint(pt, cos, sin, cx);
};
/**
* Function: flipPoint
*
* Flips the given point vertically and/or horizontally.
*/
mxHandle.prototype.flipPoint = function(pt)
{
if (this.state.shape != null)
{
var bounds = this.state.getCellBounds();
if (this.state.shape.flipH)
{
pt.x = 2 * bounds.x + bounds.width - pt.x;
}
if (this.state.shape.flipV)
{
pt.y = 2 * bounds.y + bounds.height - pt.y;
}
}
return pt;
};
/**
* Function: snapPoint
*
* Snaps the given point to the grid if ignore is false. This modifies
* the given point in-place and also returns it.
*/
mxHandle.prototype.snapPoint = function(pt, ignore)
{
if (!ignore)
{
pt.x = this.graph.snap(pt.x);
pt.y = this.graph.snap(pt.y);
}
return pt;
};
/**
* Function: setVisible
*
* Shows or hides this handle.
*/
mxHandle.prototype.setVisible = function(visible)
{
if (this.shape != null && this.shape.node != null)
{
this.shape.node.style.display = (visible) ? '' : 'none';
}
};
/**
* Function: reset
*
* Resets the state of this handle by setting its visibility to true.
*/
mxHandle.prototype.reset = function()
{
this.setVisible(true);
this.state.style = this.graph.getCellStyle(this.state.cell);
this.positionChanged();
};
/**
* Function: destroy
*
* Destroys this handle.
*/
mxHandle.prototype.destroy = function()
{
if (this.shape != null)
{
this.shape.destroy();
this.shape = null;
}
};
| kyro46/assMxGraphQuestion | templates/mxgraph/js/handler/mxHandle.js | JavaScript | gpl-3.0 | 7,788 |
# Deploy 64-bit Mac OS X standalones
You can now deploy both 32-bit and 64-bit standalones for Mac OS X,
and you can select which engines you'd like to include in the
standalone builder.
**This feature was sponsored by the community Feature Exchange.**
| PaulMcClernan/livecode | docs/notes/feature-mac64-deployment.md | Markdown | gpl-3.0 | 255 |
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html>
<head>
<title>[ 593705 ] Use of < comparison symbol confuses Tidy</title>
<script type="text/javascript">
function foo( bar, baz )
{
return ( bar < baz ? true : false );
}
</script>
</head>
<body>
<p>Does the script confuse Tidy?</p>
</body>
</html>
| GerHobbelt/htmltidy | test/input/in_593705.html | HTML | gpl-3.0 | 329 |
---
version: 8.0.0-dp-3
---
# LiveCode Builder Language
## Handler definitions
* The syntax for declaring the type of the return value from a handler
(or handler type) is now `[ 'returns' 'nothing' | 'returns' <Type> ]`.
# [14906] Change 'as <Type>' to 'returns nothing' or 'returns <Type>' in handler return type definitions.
# [14926] LCB-Language: Remove deprecated handler return type syntax.
| hwbehrens/livecode | docs/lcb/notes/14906.md | Markdown | gpl-3.0 | 402 |
#region License
// Copyright (c) 2013, ClearCanvas Inc.
// All rights reserved.
// http://www.clearcanvas.ca
//
// This file is part of the ClearCanvas RIS/PACS open source project.
//
// The ClearCanvas RIS/PACS open source project 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.
//
// The ClearCanvas RIS/PACS open source project 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
// the ClearCanvas RIS/PACS open source project. If not, see
// <http://www.gnu.org/licenses/>.
#endregion
using System;
using System.Collections;
using System.Collections.Generic;
using ClearCanvas.Common;
using ClearCanvas.Desktop;
using ClearCanvas.Enterprise.Common;
using ClearCanvas.Ris.Application.Common;
using ClearCanvas.Ris.Application.Common.Admin.LocationAdmin;
using ClearCanvas.Ris.Application.Common.Admin.FacilityAdmin;
using ClearCanvas.Desktop.Validation;
namespace ClearCanvas.Ris.Client.Admin
{
/// <summary>
/// Extension point for views onto <see cref="LocationEditorComponent"/>
/// </summary>
[ExtensionPoint]
public class LocationEditorComponentViewExtensionPoint : ExtensionPoint<IApplicationComponentView>
{
}
/// <summary>
/// LocationEditorComponent class
/// </summary>
[AssociateView(typeof(LocationEditorComponentViewExtensionPoint))]
public class LocationEditorComponent : ApplicationComponent
{
private List<FacilitySummary> _facilityChoices;
private LocationDetail _locationDetail;
private EntityRef _locationRef;
private readonly bool _isNew;
private LocationSummary _locationSummary;
/// <summary>
/// Constructor
/// </summary>
public LocationEditorComponent()
{
_isNew = true;
}
public LocationEditorComponent(EntityRef locationRef)
{
_isNew = false;
_locationRef = locationRef;
}
public LocationSummary LocationSummary
{
get { return _locationSummary; }
}
public override void Start()
{
if (_isNew)
{
_locationDetail = new LocationDetail();
}
else
{
Platform.GetService(
delegate(ILocationAdminService service)
{
var response = service.LoadLocationForEdit(new LoadLocationForEditRequest(_locationRef));
_locationRef = response.LocationDetail.LocationRef;
_locationDetail = response.LocationDetail;
});
}
Platform.GetService(
delegate(IFacilityAdminService service)
{
var response = service.ListAllFacilities(new ListAllFacilitiesRequest());
_facilityChoices = response.Facilities;
if (_isNew && _locationDetail.Facility == null && response.Facilities.Count > 0)
{
_locationDetail.Facility = response.Facilities[0];
}
});
base.Start();
}
public LocationDetail LocationDetail
{
get { return _locationDetail; }
set { _locationDetail = value; }
}
#region Presentation Model
[ValidateNotNull]
public string Id
{
get { return _locationDetail.Id; }
set
{
_locationDetail.Id = value;
this.Modified = true;
}
}
[ValidateNotNull]
public string Name
{
get { return _locationDetail.Name; }
set
{
_locationDetail.Name = value;
this.Modified = true;
}
}
public string Description
{
get { return _locationDetail.Description; }
set
{
_locationDetail.Description = value;
this.Modified = true;
}
}
public IList FacilityChoices
{
get { return _facilityChoices; }
}
[ValidateNotNull]
public FacilitySummary Facility
{
get { return _locationDetail.Facility; }
set
{
_locationDetail.Facility = value;
this.Modified = true;
}
}
public string FormatFacility(object item)
{
var f = (FacilitySummary) item;
return f.Name;
}
public string Building
{
get { return _locationDetail.Building; }
set
{
_locationDetail.Building = value;
this.Modified = true;
}
}
public string Floor
{
get { return _locationDetail.Floor; }
set
{
_locationDetail.Floor = value;
this.Modified = true;
}
}
public string PointOfCare
{
get { return _locationDetail.PointOfCare; }
set
{
_locationDetail.PointOfCare = value;
this.Modified = true;
}
}
public void Accept()
{
if (this.HasValidationErrors)
{
this.ShowValidation(true);
}
else
{
try
{
SaveChanges();
this.Exit(ApplicationComponentExitCode.Accepted);
}
catch (Exception e)
{
ExceptionHandler.Report(e, SR.ExceptionSaveLocation, this.Host.DesktopWindow,
delegate
{
this.ExitCode = ApplicationComponentExitCode.Error;
this.Host.Exit();
});
}
}
}
public void Cancel()
{
this.ExitCode = ApplicationComponentExitCode.None;
Host.Exit();
}
public bool AcceptEnabled
{
get { return this.Modified; }
}
#endregion
private void SaveChanges()
{
if (_isNew)
{
Platform.GetService(
delegate(ILocationAdminService service)
{
var response = service.AddLocation(new AddLocationRequest(_locationDetail));
_locationRef = response.Location.LocationRef;
_locationSummary = response.Location;
});
}
else
{
Platform.GetService(
delegate(ILocationAdminService service)
{
var response = service.UpdateLocation(new UpdateLocationRequest(_locationDetail));
_locationRef = response.Location.LocationRef;
_locationSummary = response.Location;
});
}
}
public event EventHandler AcceptEnabledChanged
{
add { this.ModifiedChanged += value; }
remove { this.ModifiedChanged -= value; }
}
}
}
| chinapacs/ImageViewer | Ris/Client/Admin/LocationEditorComponent.cs | C# | gpl-3.0 | 6,291 |
#region License
// Copyright (c) 2013, ClearCanvas Inc.
// All rights reserved.
// http://www.clearcanvas.ca
//
// This file is part of the ClearCanvas RIS/PACS open source project.
//
// The ClearCanvas RIS/PACS open source project 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.
//
// The ClearCanvas RIS/PACS open source project 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
// the ClearCanvas RIS/PACS open source project. If not, see
// <http://www.gnu.org/licenses/>.
#endregion
using System;
using System.Diagnostics;
using System.IO;
using ClearCanvas.Common;
using ClearCanvas.Common.Utilities;
using ClearCanvas.Dicom.Utilities.Command;
using ClearCanvas.ImageServer.Common;
using ClearCanvas.ImageServer.Common.Utilities;
using ClearCanvas.ImageServer.Core.Command;
using ClearCanvas.ImageServer.Core.Data;
using ClearCanvas.ImageServer.Core.Validation;
using ClearCanvas.ImageServer.Enterprise.Command;
using ClearCanvas.ImageServer.Model;
namespace ClearCanvas.ImageServer.Services.WorkQueue.CleanupReconcile
{
/// <summary>
/// For processing 'CleanupReconcile' WorkQueue items.
/// </summary>
[StudyIntegrityValidation(ValidationTypes = StudyIntegrityValidationModes.None)]
class CleanupReconcileItemProcessor : BaseItemProcessor
{
private ReconcileStudyWorkQueueData _reconcileQueueData;
protected override bool CanStart()
{
return true;
}
protected override void ProcessItem(Model.WorkQueue item)
{
Platform.CheckForNullReference(item, "item");
Platform.CheckForNullReference(item.Data, "item.Data");
_reconcileQueueData = XmlUtils.Deserialize<ReconcileStudyWorkQueueData>(WorkQueueItem.Data);
LoadUids(item);
if (WorkQueueUidList.Count == 0)
{
DirectoryUtility.DeleteIfEmpty(_reconcileQueueData.StoragePath);
Platform.Log(LogLevel.Info, "Reconcile Cleanup is completed. GUID={0}.", WorkQueueItem.GetKey());
PostProcessing(WorkQueueItem,
WorkQueueProcessorStatus.Complete,
WorkQueueProcessorDatabaseUpdate.ResetQueueState);
}
else
{
Platform.Log(LogLevel.Info,
"Starting Cleanup of Reconcile Queue item for study {0} for Patient {1} (PatientId:{2} A#:{3}) on Partition {4}, {5} objects",
Study.StudyInstanceUid, Study.PatientsName, Study.PatientId,
Study.AccessionNumber, ServerPartition.Description,
WorkQueueUidList.Count);
ProcessUidList();
Platform.Log(LogLevel.Info, "Successfully complete Reconcile Cleanup. GUID={0}. {0} uids processed.", WorkQueueItem.GetKey(), WorkQueueUidList.Count);
PostProcessing(WorkQueueItem,
WorkQueueProcessorStatus.Pending,
WorkQueueProcessorDatabaseUpdate.None);
}
}
private void ProcessUidList()
{
Platform.CheckForNullReference(WorkQueueUidList, "WorkQueueUidList");
foreach(WorkQueueUid uid in WorkQueueUidList)
{
ProcessUid(uid);
}
}
private void ProcessUid(WorkQueueUid uid)
{
Platform.CheckForNullReference(uid, "uid");
string imagePath = GetUidPath(uid);
using (ServerCommandProcessor processor = new ServerCommandProcessor(String.Format("Deleting {0}", uid.SopInstanceUid)))
{
// If the file for some reason doesn't exist, we just ignore it
if (File.Exists(imagePath))
{
Platform.Log(ServerPlatform.InstanceLogLevel, "Deleting {0}", imagePath);
FileDeleteCommand deleteFile = new FileDeleteCommand(imagePath, true);
processor.AddCommand(deleteFile);
}
else
{
Platform.Log(LogLevel.Warn, "WARNING {0} is missing.", imagePath);
}
DeleteWorkQueueUidCommand deleteUid = new DeleteWorkQueueUidCommand(uid);
processor.AddCommand(deleteUid);
if (!processor.Execute())
{
throw new Exception(String.Format("Unable to delete image {0}", uid.SopInstanceUid));
}
}
}
private string GetUidPath(WorkQueueUid sop)
{
string imagePath = Path.Combine(_reconcileQueueData.StoragePath, sop.SopInstanceUid + ServerPlatform.DicomFileExtension);
Debug.Assert(String.IsNullOrEmpty(imagePath)==false);
return imagePath;
}
}
}
| chinapacs/ImageViewer | ImageServer/Services/WorkQueue/CleanupReconcile/CleanupReconcileItemProcessor.cs | C# | gpl-3.0 | 5,141 |
/* -*- c++ -*- */
/*
* Copyright 2015,2016 Free Software Foundation, Inc.
*
* This is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3, or (at your option)
* any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this software; see the file COPYING. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street,
* Boston, MA 02110-1301, USA.
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include <gnuradio/io_signature.h>
#include "dvbt_reference_signals_impl.h"
#include <complex>
#include <gnuradio/expj.h>
#include <gnuradio/math.h>
namespace gr {
namespace dtv {
//Number of symbols in a frame
const int dvbt_pilot_gen::d_symbols_per_frame = SYMBOLS_PER_FRAME;
//Number of frames in a superframe
const int dvbt_pilot_gen::d_frames_per_superframe = FRAMES_PER_SUPERFRAME;
// 2k mode
// Scattered pilots # of carriers
const int dvbt_pilot_gen::d_spilot_carriers_size_2k = SCATTERED_PILOT_SIZE_2k;
// Continual pilots # of carriers and positions
const int dvbt_pilot_gen::d_cpilot_carriers_size_2k = CONTINUAL_PILOT_SIZE_2k;
const int dvbt_pilot_gen::d_cpilot_carriers_2k[dvbt_pilot_gen::d_cpilot_carriers_size_2k] = {
0, 48, 54, 87, 141, 156, 192, \
201, 255, 279, 282, 333, 432, 450, \
483, 525, 531, 618, 636, 714, 759, \
765, 780, 804, 873, 888, 918, 939, \
942, 969, 984, 1050, 1101, 1107, 1110, \
1137, 1140, 1146, 1206, 1269, 1323, 1377, \
1491, 1683, 1704
};
// TPS pilots # of carriers and positions
const int dvbt_pilot_gen::d_tps_carriers_size_2k = TPS_PILOT_SIZE_2k;
const int dvbt_pilot_gen::d_tps_carriers_2k[dvbt_pilot_gen::d_tps_carriers_size_2k] = {
34, 50, 209, 346, 413, \
569, 595, 688, 790, 901, \
1073, 1219, 1262, 1286, 1469, \
1594, 1687
};
// 8k mode
// Scattered pilots # of carriers
const int dvbt_pilot_gen::d_spilot_carriers_size_8k = SCATTERED_PILOT_SIZE_8k;
// Continual pilots # of carriers and positions
const int dvbt_pilot_gen::d_cpilot_carriers_size_8k = CONTINUAL_PILOT_SIZE_8k;
const int dvbt_pilot_gen::d_cpilot_carriers_8k[dvbt_pilot_gen::d_cpilot_carriers_size_8k] = {
0, 48, 54, 87, 141, 156, 192,
201, 255, 279, 282, 333, 432, 450,
483, 525, 531, 618, 636, 714, 759,
765, 780, 804, 873, 888, 918, 939,
942, 969, 984, 1050, 1101, 1107, 1110,
1137, 1140, 1146, 1206, 1269, 1323, 1377,
1491, 1683, 1704, 1752, 1758, 1791, 1845,
1860, 1896, 1905, 1959, 1983, 1986, 2037,
2136, 2154, 2187, 2229, 2235, 2322, 2340,
2418, 2463, 2469, 2484, 2508, 2577, 2592,
2622, 2643, 2646, 2673, 2688, 2754, 2805,
2811, 2814, 2841, 2844, 2850, 2910, 2973,
3027, 3081, 3195, 3387, 3408, 3456, 3462,
3495, 3549, 3564, 3600, 3609, 3663, 3687,
3690, 3741, 3840, 3858, 3891, 3933, 3939,
4026, 4044, 4122, 4167, 4173, 4188, 4212,
4281, 4296, 4326, 4347, 4350, 4377, 4392,
4458, 4509, 4515, 4518, 4545, 4548, 4554,
4614, 4677, 4731, 4785, 4899, 5091, 5112,
5160, 5166, 5199, 5253, 5268, 5304, 5313,
5367, 5391, 5394, 5445, 5544, 5562, 5595,
5637, 5643, 5730, 5748, 5826, 5871, 5877,
5892, 5916, 5985, 6000, 6030, 6051, 6054,
6081, 6096, 6162, 6213, 6219, 6222, 6249,
6252, 6258, 6318, 6381, 6435, 6489, 6603,
6795, 6816
};
// TPS pilots # of carriers and positions
const int dvbt_pilot_gen::d_tps_carriers_size_8k = TPS_PILOT_SIZE_8k;
const int dvbt_pilot_gen::d_tps_carriers_8k[dvbt_pilot_gen::d_tps_carriers_size_8k] = {
34, 50, 209, 346, 413, 569, 595, 688, \
790, 901, 1073, 1219, 1262, 1286, 1469, 1594, \
1687, 1738, 1754, 1913, 2050, 2117, 2273, 2299, \
2392, 2494, 2605, 2777, 2923, 2966, 2990, 3173, \
3298, 3391, 3442, 3458, 3617, 3754, 3821, 3977, \
4003, 4096, 4198, 4309, 4481, 4627, 4670, 4694, \
4877, 5002, 5095, 5146, 5162, 5321, 5458, 5525, \
5681, 5707, 5800, 5902, 6013, 6185, 6331, 6374, \
6398, 6581, 6706, 6799
};
// TPS sync sequence for odd and even frames
const int dvbt_pilot_gen::d_tps_sync_size = 16; // TODO
const int dvbt_pilot_gen::d_tps_sync_even[d_tps_sync_size] = {
0, 0, 1, 1, 0, 1, 0, 1, 1, 1, 1, 0, 1, 1, 1, 0
};
const int dvbt_pilot_gen::d_tps_sync_odd[d_tps_sync_size] = {
1, 1, 0, 0, 1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1
};
/*
* Constructor of class
*/
dvbt_pilot_gen::dvbt_pilot_gen(const dvbt_configure &c) : config(c),
d_spilot_index(0),
d_cpilot_index(0),
d_tpilot_index(0),
d_symbol_index(0),
d_symbol_index_known(0),
d_frame_index(0),
d_superframe_index(0),
d_freq_offset_max(8),
d_trigger_index(0),
d_payload_index(0),
d_chanestim_index(0),
d_prev_mod_symbol_index(0),
d_mod_symbol_index(0)
{
//Determine parameters from config file
d_Kmin = config.d_Kmin;
d_Kmax = config.d_Kmax;
d_fft_length = config.d_fft_length;
d_payload_length = config.d_payload_length;
d_zeros_on_left = config.d_zeros_on_left;
d_zeros_on_right = config.d_zeros_on_right;
d_cp_length = config.d_cp_length;
//Set-up pilot data depending on transmission mode
if (config.d_transmission_mode == T2k) {
d_spilot_carriers_size = d_spilot_carriers_size_2k;
d_cpilot_carriers_size = d_cpilot_carriers_size_2k;
d_cpilot_carriers = d_cpilot_carriers_2k;
d_tps_carriers_size = d_tps_carriers_size_2k;
d_tps_carriers = d_tps_carriers_2k;
}
else if (config.d_transmission_mode == T8k) {
d_spilot_carriers_size = d_spilot_carriers_size_8k;
d_cpilot_carriers_size = d_cpilot_carriers_size_8k;
d_cpilot_carriers = d_cpilot_carriers_8k;
d_tps_carriers_size = d_tps_carriers_size_8k;
d_tps_carriers = d_tps_carriers_8k;
}
else {
d_spilot_carriers_size = d_spilot_carriers_size_2k;
d_cpilot_carriers_size = d_cpilot_carriers_size_2k;
d_cpilot_carriers = d_cpilot_carriers_2k;
d_tps_carriers_size = d_tps_carriers_size_2k;
d_tps_carriers = d_tps_carriers_2k;
}
d_freq_offset = 0;
d_carrier_freq_correction = 0.0;
d_sampling_freq_correction = 0.0;
//allocate PRBS buffer
d_wk = new char[d_Kmax - d_Kmin + 1];
if (d_wk == NULL) {
std::cerr << "Reference Signals, cannot allocate memory for d_wk." << std::endl;
throw std::bad_alloc();
}
// Generate wk sequence
generate_prbs();
// allocate buffer for scattered pilots
d_spilot_carriers_val = new (std::nothrow) gr_complex[d_Kmax - d_Kmin + 1];
if (d_spilot_carriers_val == NULL) {
std::cerr << "Reference Signals, cannot allocate memory for d_spilot_carriers_val." << std::endl;
delete [] d_wk;
throw std::bad_alloc();
}
// allocate buffer for channel gains (for each useful carrier)
d_channel_gain = new (std::nothrow) gr_complex[d_Kmax - d_Kmin + 1];
if (d_channel_gain == NULL) {
std::cerr << "Reference Signals, cannot allocate memory for d_channel_gain." << std::endl;
delete [] d_spilot_carriers_val;
delete [] d_wk;
throw std::bad_alloc();
}
// Allocate buffer for continual pilots phase diffs
d_known_phase_diff = new (std::nothrow) float[d_cpilot_carriers_size - 1];
if (d_known_phase_diff == NULL) {
std::cerr << "Reference Signals, cannot allocate memory for d_known_phase_diff." << std::endl;
delete [] d_channel_gain;
delete [] d_spilot_carriers_val;
delete [] d_wk;
throw std::bad_alloc();
}
// Obtain phase diff for all continual pilots
for (int i = 0; i < (d_cpilot_carriers_size - 1); i++) {
d_known_phase_diff[i] = \
norm(get_cpilot_value(d_cpilot_carriers[i + 1]) - get_cpilot_value(d_cpilot_carriers[i]));
}
d_cpilot_phase_diff = new (std::nothrow) float[d_cpilot_carriers_size - 1];
if (d_cpilot_phase_diff == NULL) {
std::cerr << "Reference Signals, cannot allocate memory for d_cpilot_phase_diff." << std::endl;
delete [] d_known_phase_diff;
delete [] d_channel_gain;
delete [] d_spilot_carriers_val;
delete [] d_wk;
throw std::bad_alloc();
}
// Allocate buffer for derotated input symbol
d_derot_in = new (std::nothrow) gr_complex[d_fft_length];
if (d_derot_in == NULL) {
std::cerr << "Reference Signals, cannot allocate memory for d_derot_in." << std::endl;
delete [] d_cpilot_phase_diff;
delete [] d_known_phase_diff;
delete [] d_channel_gain;
delete [] d_spilot_carriers_val;
delete [] d_wk;
throw std::bad_alloc();
}
// allocate buffer for first tps symbol constellation
d_tps_carriers_val = new (std::nothrow) gr_complex[d_tps_carriers_size];
if (d_tps_carriers_val == NULL) {
std::cerr << "Reference Signals, cannot allocate memory for d_tps_carriers_val." << std::endl;
delete [] d_derot_in;
delete [] d_cpilot_phase_diff;
delete [] d_known_phase_diff;
delete [] d_channel_gain;
delete [] d_spilot_carriers_val;
delete [] d_wk;
throw std::bad_alloc();
}
// allocate tps data buffer
d_tps_data = new (std::nothrow) unsigned char[d_symbols_per_frame];
if (d_tps_data == NULL) {
std::cerr << "Reference Signals, cannot allocate memory for d_tps_data." << std::endl;
delete [] d_tps_carriers_val;
delete [] d_derot_in;
delete [] d_cpilot_phase_diff;
delete [] d_known_phase_diff;
delete [] d_channel_gain;
delete [] d_spilot_carriers_val;
delete [] d_wk;
throw std::bad_alloc();
}
d_prev_tps_symbol = new (std::nothrow) gr_complex[d_tps_carriers_size];
if (d_prev_tps_symbol == NULL) {
std::cerr << "Reference Signals, cannot allocate memory for d_prev_tps_symbol." << std::endl;
delete [] d_tps_data;
delete [] d_tps_carriers_val;
delete [] d_derot_in;
delete [] d_cpilot_phase_diff;
delete [] d_known_phase_diff;
delete [] d_channel_gain;
delete [] d_spilot_carriers_val;
delete [] d_wk;
throw std::bad_alloc();
}
memset(d_prev_tps_symbol, 0, d_tps_carriers_size * sizeof(gr_complex));
d_tps_symbol = new (std::nothrow) gr_complex[d_tps_carriers_size];
if (d_tps_symbol == NULL) {
std::cerr << "Reference Signals, cannot allocate memory for d_tps_symbol." << std::endl;
delete [] d_prev_tps_symbol;
delete [] d_tps_data;
delete [] d_tps_carriers_val;
delete [] d_derot_in;
delete [] d_cpilot_phase_diff;
delete [] d_known_phase_diff;
delete [] d_channel_gain;
delete [] d_spilot_carriers_val;
delete [] d_wk;
throw std::bad_alloc();
}
memset(d_tps_symbol, 0, d_tps_carriers_size * sizeof(gr_complex));
// Init receive TPS data vector
for (int i = 0; i < d_symbols_per_frame; i++) {
d_rcv_tps_data.push_back(0);
}
// Init TPS sync sequence
for (int i = 0; i < d_tps_sync_size; i++) {
d_tps_sync_evenv.push_back(d_tps_sync_even[i]);
d_tps_sync_oddv.push_back(d_tps_sync_odd[i]);
}
// Allocate buffer for channel estimation carriers
d_chanestim_carriers = new (std::nothrow) int[d_Kmax - d_Kmin + 1];
if (d_chanestim_carriers == NULL) {
std::cerr << "Reference Signals, cannot allocate memory for d_chanestim_carriers." << std::endl;
delete [] d_tps_symbol;
delete [] d_prev_tps_symbol;
delete [] d_tps_data;
delete [] d_tps_carriers_val;
delete [] d_derot_in;
delete [] d_cpilot_phase_diff;
delete [] d_known_phase_diff;
delete [] d_channel_gain;
delete [] d_spilot_carriers_val;
delete [] d_wk;
throw std::bad_alloc();
}
// Allocate buffer for payload carriers
d_payload_carriers = new (std::nothrow) int[d_Kmax - d_Kmin + 1];
if (d_payload_carriers == NULL) {
std::cerr << "Reference Signals, cannot allocate memory for d_payload_carriers." << std::endl;
delete [] d_chanestim_carriers;
delete [] d_tps_symbol;
delete [] d_prev_tps_symbol;
delete [] d_tps_data;
delete [] d_tps_carriers_val;
delete [] d_derot_in;
delete [] d_cpilot_phase_diff;
delete [] d_known_phase_diff;
delete [] d_channel_gain;
delete [] d_spilot_carriers_val;
delete [] d_wk;
throw std::bad_alloc();
}
// Reset the pilot generator
reset_pilot_generator();
// Format TPS data with current values
format_tps_data();
}
/*
* Destructor of class
*/
dvbt_pilot_gen::~dvbt_pilot_gen()
{
delete [] d_payload_carriers;
delete [] d_chanestim_carriers;
delete [] d_tps_symbol;
delete [] d_prev_tps_symbol;
delete [] d_tps_data;
delete [] d_tps_carriers_val;
delete [] d_derot_in;
delete [] d_cpilot_phase_diff;
delete [] d_known_phase_diff;
delete [] d_channel_gain;
delete [] d_spilot_carriers_val;
delete [] d_wk;
}
/*
* Generate PRBS sequence
* X^11 + X^2 + 1
* en 300 744 - section 4.5.2
*/
void
dvbt_pilot_gen::generate_prbs()
{
// init PRBS register with 1s
unsigned int reg_prbs = (1 << 11) - 1;
for (int k = 0; k < (d_Kmax - d_Kmin + 1); k++) {
d_wk[k] = (char)(reg_prbs & 0x01);
int new_bit = ((reg_prbs >> 2) ^ (reg_prbs >> 0)) & 0x01;
reg_prbs = (reg_prbs >> 1) | (new_bit << 10);
}
}
/*
* Generate shortened BCH(67, 53) codes from TPS data
* Extend the code with 60 bits and use BCH(127, 113)
*/
void
dvbt_pilot_gen::generate_bch_code()
{
//TODO
//DO other way: if (feedback == 1) reg = reg ^ polymomial
//else nothing
//(n, k) = (127, 113) = (60+67, 60+53)
unsigned int reg_bch = 0;
unsigned char data_in[113];
//fill in 60 zeros
memset(&data_in[0], 0, 60);
//fill in TPS data - start bit not included
memcpy(&data_in[60], &d_tps_data[1], 53);
//X^14+X^9+X^8+X^6+X^5+X^4+X^2+X+1
for (int i = 0; i < 113; i++) {
int feedback = 0x1 & (data_in[i] ^ reg_bch);
reg_bch = reg_bch >> 1;
reg_bch |= feedback << 13;
reg_bch = reg_bch \
^ (feedback << 12) ^ (feedback << 11) \
^ (feedback << 9) ^ (feedback << 8) \
^ (feedback << 7) ^ (feedback << 5) \
^ (feedback << 4);
}
for (int i = 0; i < 14; i++) {
d_tps_data[i + 54] = 0x1 & (reg_bch >> i);
}
}
int
dvbt_pilot_gen::verify_bch_code(std::deque<char> data)
{
int ret = 0;
//TODO
//DO other way: if (feedback == 1) reg = reg ^ polymomial
//else nothing
//(n, k) = (127, 113) = (60+67, 60+53)
unsigned int reg_bch = 0;
unsigned char data_in[113];
//fill in 60 zeros
memset(&data_in[0], 0, 60);
//fill in TPS data - start bit not included
//memcpy(&data_in[60], &data[1], 53);
for (int i = 0; i < 53; i++) {
data_in[60 + i] = data[1 + i];
}
//X^14+X^9+X^8+X^6+X^5+X^4+X^2+X+1
for (int i = 0; i < 113; i++) {
int feedback = 0x1 & (data_in[i] ^ reg_bch);
reg_bch = reg_bch >> 1;
reg_bch |= feedback << 13;
reg_bch = reg_bch \
^ (feedback << 12) ^ (feedback << 11) \
^ (feedback << 9) ^ (feedback << 8) \
^ (feedback << 7) ^ (feedback << 5) \
^ (feedback << 4);
}
for (int i = 0; i < 14; i++) {
if ((unsigned int)data[i + 54] != (0x1 & (reg_bch >> i))) {
ret = -1;
break;
}
}
return ret;
}
void
dvbt_pilot_gen::set_symbol_index(int sindex)
{
d_symbol_index = sindex;
}
int
dvbt_pilot_gen::get_symbol_index()
{
return d_symbol_index;
}
void
dvbt_pilot_gen::set_tps_data()
{
}
void
dvbt_pilot_gen::get_tps_data()
{
}
/*
* Reset pilot generator
*/
void
dvbt_pilot_gen::reset_pilot_generator()
{
d_spilot_index = 0; d_cpilot_index = 0; d_tpilot_index = 0;
d_payload_index = 0; d_chanestim_index = 0;
d_symbol_index = 0; d_frame_index = 0; d_superframe_index = 0;
d_symbol_index_known = 0;
d_equalizer_ready = 0;
}
/*
* Init scattered pilot generator
*/
int
dvbt_pilot_gen::get_current_spilot(int sindex) const
{
//TODO - can be optimized for same symbol_index
return (d_Kmin + 3 * (sindex % 4) + 12 * d_spilot_index);
}
gr_complex
dvbt_pilot_gen::get_spilot_value(int spilot)
{
// TODO - can be calculated at the beginning
return gr_complex(4 * 2 * (0.5 - d_wk[spilot]) / 3, 0);
}
void
dvbt_pilot_gen::set_spilot_value(int spilot, gr_complex val)
{
d_spilot_carriers_val[spilot] = val;
}
void
dvbt_pilot_gen::set_channel_gain(int spilot, gr_complex val)
{
// Gain gval=rxval/txval
d_channel_gain[spilot] = gr_complex((4 * 2 * (0.5 - d_wk[spilot]) / 3), 0) / val;
}
void
dvbt_pilot_gen::advance_spilot(int sindex)
{
//TODO - do in a simpler way?
int size = d_spilot_carriers_size;
if (sindex == 0) {
size = d_spilot_carriers_size + 1;
}
// TODO - fix this - what value should we use?
++d_spilot_index;
d_spilot_index = d_spilot_index % size;
}
int
dvbt_pilot_gen::get_first_spilot()
{
d_spilot_index = 0;
return (d_Kmin + 3 * (d_symbol_index % 4));
}
int
dvbt_pilot_gen::get_last_spilot() const
{
int size = d_spilot_carriers_size - 1;
if (d_symbol_index == 0) {
size = d_spilot_carriers_size;
}
return (d_Kmin + 3 * (d_symbol_index % 4) + 12 * size);
}
int
dvbt_pilot_gen::get_next_spilot()
{
int pilot = (d_Kmin + 3 * (d_symbol_index % 4) + 12 * (++d_spilot_index));
if (pilot > d_Kmax) {
pilot = d_Kmax;
}
return pilot;
}
int
dvbt_pilot_gen::process_spilot_data(const gr_complex * in)
{
// This is channel estimator
// Interpolate the gain between carriers to obtain
// gain for non pilot carriers - we use linear interpolation
/*************************************************************/
// Find out the OFDM symbol index (value 0 to 3) sent
// in current block by correlating scattered symbols with
// current block - result is (symbol index % 4)
/*************************************************************/
float max = 0; float sum = 0;
for (int scount = 0; scount < 4; scount++) {
d_spilot_index = 0; d_cpilot_index = 0;
d_chanestim_index = 0;
for (int k = 0; k < (d_Kmax - d_Kmin + 1); k++) {
// Keep data for channel estimation
if (k == get_current_spilot(scount)) {
set_chanestim_carrier(k);
advance_spilot(scount);
advance_chanestim();
}
}
gr_complex c = gr_complex(0.0, 0.0);
// This should be of range 0 to d_chanestim_index bit for now we use just a
// small number of spilots to obtain the symbol index
for (int j = 0; j < 10; j++) {
c += get_spilot_value(d_chanestim_carriers[j]) * conj(in[d_zeros_on_left + d_chanestim_carriers[j]]);
}
sum = norm(c);
if (sum > max) {
max = sum;
d_mod_symbol_index = scount;
}
}
/*************************************************************/
// Keep data for channel estimator
// This method interpolates scattered measurements across one OFDM symbol
// It does not use measurements from the previous OFDM symbols (does not use history)
// as it may have encountered a phase change for the current phase only
/*************************************************************/
d_spilot_index = 0; d_cpilot_index = 0;
d_chanestim_index = 0;
for (int k = 0; k < (d_Kmax - d_Kmin + 1); k++) {
// Keep data for channel estimation
if (k == get_current_spilot(d_mod_symbol_index)) {
set_chanestim_carrier(k);
advance_spilot(d_mod_symbol_index);
advance_chanestim();
}
// Keep data for channel estimation
if (k == get_current_cpilot()) {
set_chanestim_carrier(k);
advance_cpilot();
advance_chanestim();
}
}
// We use both scattered pilots and continual pilots
for (int i = 0, startk = d_chanestim_carriers[0]; i < d_chanestim_index; i++) {
// Get a carrier from the list of carriers
// used for channel estimation
int k = d_chanestim_carriers[i];
set_channel_gain(k, in[k + d_zeros_on_left]);
// Calculate tg(alpha) due to linear interpolation
gr_complex tg_alpha = (d_channel_gain[k] - d_channel_gain[startk]) / gr_complex(11.0, 0.0);
// Calculate interpolation for all intermediate values
for (int j = 1; j < (k - startk); j++) {
gr_complex current = d_channel_gain[startk] + tg_alpha * gr_complex(j, 0.0);
d_channel_gain[startk + j] = current;
}
startk = k;
}
// Signal that equalizer is ready
d_equalizer_ready = 1;
int diff_sindex = (d_mod_symbol_index - d_prev_mod_symbol_index + 4) % 4;
d_prev_mod_symbol_index = d_mod_symbol_index;
return diff_sindex;
}
/*
* Init continual pilot generator
*/
int
dvbt_pilot_gen::get_current_cpilot() const
{
return d_cpilot_carriers[d_cpilot_index];
}
gr_complex
dvbt_pilot_gen::get_cpilot_value(int cpilot)
{
//TODO - can be calculated at the beginning
return gr_complex((float)(4 * 2 * (0.5 - d_wk[cpilot])) / 3, 0);
}
void
dvbt_pilot_gen::advance_cpilot()
{
++d_cpilot_index;
d_cpilot_index = d_cpilot_index % d_cpilot_carriers_size;
}
void
dvbt_pilot_gen::process_cpilot_data(const gr_complex * in)
{
// Look for maximum correlation for cpilots
// in order to obtain post FFT integer frequency correction
float max = 0; float sum = 0;
int start = 0;
float phase;
for (int i = d_zeros_on_left - d_freq_offset_max; i < d_zeros_on_left + d_freq_offset_max; i++) {
sum = 0;
for (int j = 0; j < (d_cpilot_carriers_size - 1); j++) {
phase = norm(in[i + d_cpilot_carriers[j + 1]] - in[i + d_cpilot_carriers[j]]);
sum += d_known_phase_diff[j] * phase;
}
if (sum > max) {
max = sum;
start = i;
}
}
d_freq_offset = start - d_zeros_on_left;
}
void
dvbt_pilot_gen::compute_oneshot_csft(const gr_complex * in)
{
gr_complex left_corr_sum = 0.0; gr_complex right_corr_sum = 0.0;
int half_size = (d_cpilot_carriers_size - 1) / 2;
// TODO init this in constructor
float carrier_coeff = 1.0 / (2 * M_PI * (1 + float (d_cp_length) / float (d_fft_length)) * 2);
float sampling_coeff = 1.0 / (2 * M_PI * ((1 + float (d_cp_length) / float (d_fft_length)) * ((float)d_cpilot_carriers_size / 2.0)));
float left_angle, right_angle;
// Compute cpilots correlation between previous symbol and current symbol
// in both halves of the cpilots. The cpilots are distributed evenly
// on left and right sides of the center frequency.
for (int j = 0; j < half_size; j++) {
left_corr_sum += in[d_freq_offset + d_zeros_on_left + d_cpilot_carriers[j]] * \
std::conj(in[d_freq_offset + d_fft_length + d_zeros_on_left + d_cpilot_carriers[j]]);
}
for (int j = half_size + 1; j < d_cpilot_carriers_size; j++) {
right_corr_sum += in[d_freq_offset + d_zeros_on_left + d_cpilot_carriers[j]] * \
std::conj(in[d_freq_offset + d_fft_length + d_zeros_on_left + d_cpilot_carriers[j]]);
}
left_angle = std::arg(left_corr_sum);
right_angle = std::arg(right_corr_sum);
d_carrier_freq_correction = (right_angle + left_angle) * carrier_coeff;
d_sampling_freq_correction = (right_angle - left_angle) * sampling_coeff;
}
gr_complex *
dvbt_pilot_gen::frequency_correction(const gr_complex * in, gr_complex * out)
{
// TODO - use PI control loop to calculate tracking corrections
int symbol_count = 1;
for (int k = 0; k < d_fft_length; k++) {
// TODO - for 2k mode the continuous pilots are not split evenly
// between left/right center frequency. Probably the scattered
// pilots needs to be added.
float correction = (float)d_freq_offset + d_carrier_freq_correction;
gr_complex c = gr_expj(-2 * M_PI * correction * \
(d_fft_length + d_cp_length) / d_fft_length * symbol_count);
// TODO - vectorize this operation
out[k] = c * in[k + d_freq_offset];
}
return (out);
}
/*
* Init tps sequence, return values for first position
* If first symbol then init tps DBPSK data
*/
int
dvbt_pilot_gen::get_current_tpilot() const
{
return d_tps_carriers[d_tpilot_index];
}
gr_complex
dvbt_pilot_gen::get_tpilot_value(int tpilot)
{
//TODO - it can be calculated at the beginnning
if (d_symbol_index == 0) {
d_tps_carriers_val[d_tpilot_index] = gr_complex(2 * (0.5 - d_wk[tpilot]), 0);
}
else {
if (d_tps_data[d_symbol_index] == 1) {
d_tps_carriers_val[d_tpilot_index] = gr_complex(-d_tps_carriers_val[d_tpilot_index].real(), 0);
}
}
return d_tps_carriers_val[d_tpilot_index];
}
void
dvbt_pilot_gen::advance_tpilot()
{
++d_tpilot_index;
d_tpilot_index = d_tpilot_index % d_tps_carriers_size;
}
/*
* Set a number of bits to a specified value
*/
void
dvbt_pilot_gen::set_tps_bits(int start, int stop, unsigned int data)
{
for (int i = start; i >= stop; i--) {
d_tps_data[i] = data & 0x1;
data = data >> 1;
}
}
/*
* Clause 4.6
* Format data that will be sent with TPS signals
* en 300 744 - section 4.6.2
* s0 Initialization
* s1-s16 Synchronization word
* s17-s22 Length Indicator
* s23-s24 Frame Number
* S25-s26 Constellation
* s27, s28, s29 Hierarchy information
* s30, s31, s32 Code rate, HP stream
* s33, s34, s35 Code rate, LP stream
* s36, s37 Guard interval
* s38, s39 Transmission mode
* s40, s47 Cell identifier
* s48-s53 All set to "0"
* s54-s67 Error protection (BCH code)
*/
void
dvbt_pilot_gen::format_tps_data()
{
//Clause 4.6.3
set_tps_bits(0, 0, d_wk[0]);
//Clause 4.6.2.2
if (d_frame_index % 2) {
set_tps_bits(16, 1, 0xca11);
}
else {
set_tps_bits(16, 1, 0x35ee);
}
//Clause 4.6.2.3
if (config.d_include_cell_id) {
set_tps_bits(22, 17, 0x1f);
}
else {
set_tps_bits(22, 17, 0x17);
}
//Clause 4.6.2.4
set_tps_bits(24, 23, d_frame_index);
//Clause 4.6.2.5
set_tps_bits(26, 25, config.d_constellation);
//Clause 4.6.2.6
set_tps_bits(29, 27, config.d_hierarchy);
//Clause 4.6.2.7
switch (config.d_code_rate_HP) {
case C1_2:
set_tps_bits(32, 30, 0);
break;
case C2_3:
set_tps_bits(32, 30, 1);
break;
case C3_4:
set_tps_bits(32, 30, 2);
break;
case C5_6:
set_tps_bits(32, 30, 3);
break;
case C7_8:
set_tps_bits(32, 30, 4);
break;
default:
set_tps_bits(32, 30, 0);
break;
}
switch (config.d_code_rate_LP) {
case C1_2:
set_tps_bits(35, 33, 0);
break;
case C2_3:
set_tps_bits(35, 33, 1);
break;
case C3_4:
set_tps_bits(35, 33, 2);
break;
case C5_6:
set_tps_bits(35, 33, 3);
break;
case C7_8:
set_tps_bits(35, 33, 4);
break;
default:
set_tps_bits(35, 33, 0);
break;
}
//Clause 4.6.2.8
set_tps_bits(37, 36, config.d_guard_interval);
//Clause 4.6.2.9
set_tps_bits(39, 38, config.d_transmission_mode);
//Clause 4.6.2.10
set_tps_bits(47, 40, config.d_cell_id);
//These bits are set to zero
set_tps_bits(53, 48, 0);
//Clause 4.6.2.11
generate_bch_code();
}
int
dvbt_pilot_gen::process_tps_data(const gr_complex * in, const int diff_symbol_index)
{
int end_frame = 0;
// Look for TPS data only - demodulate DBPSK
// Calculate phase difference between previous symbol
// and current one to determine the current bit.
// Use majority voting for decision
int tps_majority_zero = 0;
for (int k = 0; k < d_tps_carriers_size; k++) {
// Use equalizer to correct data and frequency correction
gr_complex val = in[d_zeros_on_left + d_tps_carriers[k]] * d_channel_gain[d_tps_carriers[k]];
if (!d_symbol_index_known || (d_symbol_index != 0)) {
gr_complex phdiff = val * conj(d_prev_tps_symbol[k]);
if (phdiff.real() >= 0.0) {
tps_majority_zero++;
}
else {
tps_majority_zero--;
}
}
d_prev_tps_symbol[k] = val;
}
// Insert obtained TPS bit into FIFO
// Insert the same bit into FIFO in the case
// diff_symbol_index is more than one. This will happen
// in the case of losing 1 to 3 symbols.
// This could be corrected by BCH decoder afterwards.
for (int i = 0; i < diff_symbol_index; i++) {
// Take out the front entry first
d_rcv_tps_data.pop_front();
// Add data at tail
if (!d_symbol_index_known || (d_symbol_index != 0)) {
if (tps_majority_zero >= 0) {
d_rcv_tps_data.push_back(0);
}
else {
d_rcv_tps_data.push_back(1);
}
}
else {
d_rcv_tps_data.push_back(0);
}
}
// Match synchronization signatures
if (std::equal(d_rcv_tps_data.begin() + 1, d_rcv_tps_data.begin() + d_tps_sync_evenv.size(), d_tps_sync_evenv.begin())) {
// Verify parity for TPS data
if (!verify_bch_code(d_rcv_tps_data)) {
d_frame_index = (d_rcv_tps_data[23] << 1) | (d_rcv_tps_data[24]);
d_symbol_index_known = 1;
end_frame = 1;
}
else {
d_symbol_index_known = 0;
end_frame = 0;
}
// Clear up FIFO
for (int i = 0; i < d_symbols_per_frame; i++) {
d_rcv_tps_data[i] = 0;
}
}
else if (std::equal(d_rcv_tps_data.begin() + 1, d_rcv_tps_data.begin() + d_tps_sync_oddv.size(), d_tps_sync_oddv.begin())) {
// Verify parity for TPS data
if (!verify_bch_code(d_rcv_tps_data)) {
d_frame_index = (d_rcv_tps_data[23] << 1) | (d_rcv_tps_data[24]);
d_symbol_index_known = 1;
end_frame = 1;
}
else {
d_symbol_index_known = 0;
end_frame = 0;
}
// Clear up FIFO
for (int i = 0; i < d_symbols_per_frame; i++) {
d_rcv_tps_data[i] = 0;
}
}
return end_frame;
}
void
dvbt_pilot_gen::set_chanestim_carrier(int k)
{
d_chanestim_carriers[d_chanestim_index] = k;
}
void
dvbt_pilot_gen::advance_chanestim()
{
d_chanestim_index++;
}
int
dvbt_pilot_gen::get_current_payload()
{
return d_payload_carriers[d_payload_index];
}
void
dvbt_pilot_gen::set_payload_carrier(int k)
{
d_payload_carriers[d_payload_index] = k;
}
void
dvbt_pilot_gen::advance_payload()
{
d_payload_index++;
}
void
dvbt_pilot_gen::process_payload_data(const gr_complex *in, gr_complex *out)
{
//reset indexes
d_spilot_index = 0; d_cpilot_index = 0; d_tpilot_index = 0;
d_payload_index = 0;d_chanestim_index = 0;
int is_payload = 1;
//process one block - one symbol
for (int k = 0; k < (d_Kmax - d_Kmin + 1); k++) {
is_payload = 1;
// Keep data for channel estimation
// This depends on the symbol index
if (k == get_current_spilot(d_mod_symbol_index)) {
advance_spilot(d_mod_symbol_index);
is_payload = 0;
}
// Keep data for frequency correction
// and channel estimation
if (k == get_current_cpilot()) {
advance_cpilot();
is_payload = 0;
}
if (k == get_current_tpilot()) {
advance_tpilot();
is_payload = 0;
}
// Keep payload carrier number
// This depends on the symbol index
if (is_payload) {
set_payload_carrier(k);
advance_payload();
}
}
if (d_equalizer_ready) {
// Equalize payload data according to channel estimator
for (int i = 0; i < d_payload_index; i++) {
out[i] = in[d_zeros_on_left + d_payload_carriers[i]] * d_channel_gain[d_payload_carriers[i]];
}
}
else {
// If equ not ready, return 0
for (int i = 0; i < d_payload_length; i++) {
out[0] = gr_complex(0.0, 0.0);
}
}
}
void
dvbt_pilot_gen::update_output(const gr_complex *in, gr_complex *out)
{
int is_payload = 1;
int payload_count = 0;
//move to the next symbol
//re-genereate TPS data
format_tps_data();
//reset indexes
payload_count = 0;
d_spilot_index = 0; d_cpilot_index = 0; d_tpilot_index = 0;
for (int i = 0; i < d_zeros_on_left; i++) {
out[i] = gr_complex(0.0, 0.0);
}
//process one block - one symbol
for (int k = d_Kmin; k < (d_Kmax - d_Kmin + 1); k++) {
is_payload = 1;
if (k == get_current_spilot(d_symbol_index)) {
out[d_zeros_on_left + k] = get_spilot_value(k);
advance_spilot(d_symbol_index);
is_payload = 0;
}
if (k == get_current_cpilot()) {
out[d_zeros_on_left + k] = get_cpilot_value(k);
advance_cpilot();
is_payload = 0;
}
if (k == get_current_tpilot()) {
out[d_zeros_on_left + k] = get_tpilot_value(k);
advance_tpilot();
is_payload = 0;
}
if (is_payload == 1) {
out[d_zeros_on_left + k] = in[payload_count++];
}
}
// update indexes
if (++d_symbol_index == d_symbols_per_frame) {
d_symbol_index = 0;
if (++d_frame_index == d_frames_per_superframe) {
d_frame_index = 0;
d_superframe_index++;
}
}
for (int i = (d_fft_length - d_zeros_on_right); i < d_fft_length; i++) {
out[i] = gr_complex(0.0, 0.0);
}
}
int
dvbt_pilot_gen::parse_input(const gr_complex *in, gr_complex *out, int * symbol_index, int * frame_index)
{
d_trigger_index++;
// Obtain frequency correction based on cpilots.
// Obtain channel estimation based on both
// cpilots and spilots.
// We use spilot correlation for finding the symbol index modulo 4
// The diff between previous sym index and current index is used
// to advance the symbol index inside a frame (0 to 67)
// Then based on the TPS data we find out the start of a frame
// Process cpilot data
// This is post FFT integer frequency offset estimation
// This is called before all other processing
process_cpilot_data(in);
// Compute one shot Post-FFT Carrier and Sampling Frequency Tracking
// Obtain fractional Carrer and Sampling frequency corrections
// Before this moment it is assumed to have corrected this:
// - symbol timing (pre-FFT)
// - symbol frequency correction (pre-FFT)
// - integer frequency correction (post-FFT)
// TODO - call this just in the aquisition mode
compute_oneshot_csft(in);
// Gather all corrections and obtain a corrected OFDM symbol:
// - input symbol shift (post-FFT)
// - integer frequency correction (post-FFT)
// - fractional frequency (carrier and sampling) corrections (post-FFT)
// TODO - use PI to update the corrections
frequency_correction(in, d_derot_in);
// Process spilot data
// This is channel estimation function
int diff_symbol_index = process_spilot_data(d_derot_in);
// Correct symbol index so that all subsequent processing
// use correct symbol index
d_symbol_index = (d_symbol_index + diff_symbol_index) % d_symbols_per_frame;
// Symbol index is used in other modules too
*symbol_index = d_symbol_index;
// Frame index is used in other modules too
*frame_index = d_frame_index;
// Process TPS data
// If a frame is recognized then signal end of frame
int frame_end = process_tps_data(d_derot_in, diff_symbol_index);
// We are just at the end of a frame
if (frame_end) {
d_symbol_index = d_symbols_per_frame - 1;
}
// Process payload data with correct symbol index
process_payload_data(d_derot_in, out);
// noutput_items should be 1 in this case
return 1;
}
dvbt_reference_signals::sptr
dvbt_reference_signals::make(int itemsize, int ninput, int noutput, \
dvb_constellation_t constellation, dvbt_hierarchy_t hierarchy, \
dvb_code_rate_t code_rate_HP, dvb_code_rate_t code_rate_LP, \
dvb_guardinterval_t guard_interval, dvbt_transmission_mode_t transmission_mode, \
int include_cell_id, int cell_id)
{
return gnuradio::get_initial_sptr
(new dvbt_reference_signals_impl(itemsize, ninput, \
noutput, constellation, hierarchy, code_rate_HP, code_rate_LP, \
guard_interval, transmission_mode, include_cell_id, cell_id));
}
/*
* The private constructor
*/
dvbt_reference_signals_impl::dvbt_reference_signals_impl(int itemsize, int ninput, int noutput, \
dvb_constellation_t constellation, dvbt_hierarchy_t hierarchy, dvb_code_rate_t code_rate_HP,\
dvb_code_rate_t code_rate_LP, dvb_guardinterval_t guard_interval,\
dvbt_transmission_mode_t transmission_mode, int include_cell_id, int cell_id)
: block("dvbt_reference_signals",
io_signature::make(1, 1, itemsize * ninput),
io_signature::make(1, 1, itemsize * noutput)),
config(constellation, hierarchy, code_rate_HP, code_rate_LP, \
guard_interval, transmission_mode, include_cell_id, cell_id),
d_pg(config)
{
d_ninput = ninput;
d_noutput = noutput;
}
/*
* Our virtual destructor.
*/
dvbt_reference_signals_impl::~dvbt_reference_signals_impl()
{
}
void
dvbt_reference_signals_impl::forecast (int noutput_items, gr_vector_int &ninput_items_required)
{
ninput_items_required[0] = noutput_items;
}
int
dvbt_reference_signals_impl::general_work (int noutput_items,
gr_vector_int &ninput_items,
gr_vector_const_void_star &input_items,
gr_vector_void_star &output_items)
{
const gr_complex *in = (const gr_complex *) input_items[0];
gr_complex *out = (gr_complex *) output_items[0];
for (int i = 0; i < noutput_items; i++) {
d_pg.update_output(&in[i * d_ninput], &out[i * d_noutput]);
}
// Tell runtime system how many input items we consumed on
// each input stream.
consume_each (noutput_items);
// Tell runtime system how many output items we produced.
return noutput_items;
}
} /* namespace dtv */
} /* namespace gr */
| pinkavaj/gnuradio | gr-dtv/lib/dvbt/dvbt_reference_signals_impl.cc | C++ | gpl-3.0 | 41,320 |
/*
YUI 3.8.0 (build 5744)
Copyright 2012 Yahoo! Inc. All rights reserved.
Licensed under the BSD License.
http://yuilibrary.com/license/
*/
YUI.add('anim-scroll', function (Y, NAME) {
/**
* Adds support for the <code>scroll</code> property in <code>to</code>
* and <code>from</code> attributes.
* @module anim
* @submodule anim-scroll
*/
var NUM = Number;
//TODO: deprecate for scrollTop/Left properties?
Y.Anim.behaviors.scroll = {
set: function(anim, att, from, to, elapsed, duration, fn) {
var
node = anim._node,
val = ([
fn(elapsed, NUM(from[0]), NUM(to[0]) - NUM(from[0]), duration),
fn(elapsed, NUM(from[1]), NUM(to[1]) - NUM(from[1]), duration)
]);
if (val[0]) {
node.set('scrollLeft', val[0]);
}
if (val[1]) {
node.set('scrollTop', val[1]);
}
},
get: function(anim) {
var node = anim._node;
return [node.get('scrollLeft'), node.get('scrollTop')];
}
};
}, '3.8.0', {"requires": ["anim-base"]});
| relipse/cworklog | public_html/js/yui/3.8.0/build/anim-scroll/anim-scroll.js | JavaScript | gpl-3.0 | 1,067 |
/**
*
* Spacebrew Library for Javascript
* --------------------------------
*
* This library was designed to work on front-end (browser) envrionments, and back-end (server)
* environments. Please refer to the readme file, the documentation and examples to learn how to
* use this library.
*
* Spacebrew is an open, dynamically re-routable software toolkit for choreographing interactive
* spaces. Or, in other words, a simple way to connect interactive things to one another. Learn
* more about Spacebrew here: http://docs.spacebrew.cc/
*
* To import into your web apps, we recommend using the minimized version of this library.
*
* Latest Updates:
* - added blank "options" attribute to config message - for future use
* - caps number of messages sent to 60 per second
* - reconnect to spacebrew if connection lost
* - enable client apps to extend libs with admin functionality.
* - added close method to close Spacebrew connection.
*
* @author Brett Renfer and Julio Terra from LAB @ Rockwell Group
* @filename sb-1.3.0.js
* @version 1.3.0
* @date May 7, 2013
*
*/
/**
* Check if Bind method exists in current enviroment. If not, it creates an implementation of
* this useful method.
*/
if (!Function.prototype.bind) {
Function.prototype.bind = function (oThis) {
if (typeof this !== "function") {
// closest thing possible to the ECMAScript 5 internal IsCallable function
throw new TypeError("Function.prototype.bind - what is trying to be bound is not callable");
}
var aArgs = Array.prototype.slice.call(arguments, 1),
fToBind = this,
fNOP = function () {},
fBound = function () {
return fToBind.apply(this instanceof fNOP
? this
: oThis || window,
aArgs.concat(Array.prototype.slice.call(arguments)));
};
fNOP.prototype = this.prototype;
fBound.prototype = new fNOP();
return fBound;
};
}
/**
* @namespace for Spacebrew library
*/
var Spacebrew = Spacebrew || {};
/**
* create placeholder var for WebSocket object, if it does not already exist
*/
var WebSocket = WebSocket || {};
/**
* Check if Running in Browser or Server (Node) Environment *
*/
// check if window object already exists to determine if running browswer
var window = window || undefined;
// check if module object already exists to determine if this is a node application
var module = module || undefined;
// if app is running in a browser, then define the getQueryString method
if (window) {
if (!window['getQueryString']){
/**
* Get parameters from a query string
* @param {String} name Name of query string to parse (w/o '?' or '&')
* @return {String} value of parameter (or empty string if not found)
*/
window.getQueryString = function( name ) {
if (!window.location) return;
name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
var regexS = "[\\?&]"+name+"=([^&#]*)";
var regex = new RegExp( regexS );
var results = regex.exec( window.location.href );
if( results == null ) return "";
else return results[1];
}
}
}
// if app is running in a node server environment then package Spacebrew library as a module.
// WebSocket module (ws) needs to be saved in a node_modules so that it can be imported.
if (!window && module) {
WebSocket = require("ws");
module.exports = {
Spacebrew: Spacebrew
}
}
/**
* Define the Spacebrew Library *
*/
/**
* Spacebrew client!
* @constructor
* @param {String} server (Optional) Base address of Spacebrew server. This server address is overwritten if server defined in query string; defaults to localhost.
* @param {String} name (Optional) Base name of app. Base name is overwritten if "name" is defined in query string; defaults to window.location.href.
* @param {String} description (Optional) Base description of app. Description name is overwritten if "description" is defined in query string;
* @param {Object} options (Optional) An object that holds the optional parameters described below
* port (Optional) Port number for the Spacebrew server
* admin (Optional) Flag that identifies when app should register for admin privileges with server
* debug (Optional) Debug flag that turns on info and debug messaging (limited use)
*/
Spacebrew.Client = function( server, name, description, options ){
var options = options || {};
// check if the server variable is an object that holds all config values
if (server != undefined) {
if (toString.call(server) !== '[object String]') {
options.port = server.port || undefined;
options.debug = server.debug || false;
options.reconnect = server.reconnect || false;
description = server.description || undefined;
name = server.name || undefined;
server = server.server || undefined;
}
}
this.debug = (window.getQueryString('debug') === "true" ? true : (options.debug || false));
this.reconnect = options.reconnect || true;
this.reconnect_timer = undefined;
this.send_interval = 16;
this.send_blocked = false;
this.msg = {};
/**
* Name of app
* @type {String}
*/
this._name = name || "javascript client #";
if (window) {
this._name = (window.getQueryString('name') !== "" ? unescape(window.getQueryString('name')) : this._name);
}
/**
* Description of your app
* @type {String}
*/
this._description = description || "spacebrew javascript client";
if (window) {
this._description = (window.getQueryString('description') !== "" ? unescape(window.getQueryString('description')) : this._description);
}
/**
* Spacebrew server to which the app will connect
* @type {String}
*/
this.server = server || "sandbox.spacebrew.cc";
if (window) {
this.server = (window.getQueryString('server') !== "" ? unescape(window.getQueryString('server')) : this.server);
}
/**
* Port number on which Spacebrew server is running
* @type {Integer}
*/
this.port = options.port || 9000;
if (window) {
port = window.getQueryString('port');
if (port !== "" && !isNaN(port)) {
this.port = port;
}
}
/**
* Reference to WebSocket
* @type {WebSocket}
*/
this.socket = null;
/**
* Configuration file for Spacebrew
* @type {Object}
*/
this.client_config = {
name: this._name,
description: this._description,
publish:{
messages:[]
},
subscribe:{
messages:[]
},
options:{}
};
this.admin = {}
/**
* Are we connected to a Spacebrew server?
* @type {Boolean}
*/
this._isConnected = false;
}
/**
* Connect to Spacebrew
* @memberOf Spacebrew.Client
*/
Spacebrew.Client.prototype.connect = function(){
try {
this.socket = new WebSocket("ws://" + this.server + ":" + this.port);
this.socket.onopen = this._onOpen.bind(this);
this.socket.onmessage = this._onMessage.bind(this);
this.socket.onclose = this._onClose.bind(this);
} catch(e){
this._isConnected = false;
console.log("[connect:Spacebrew] connection attempt failed")
}
}
/**
* Close Spacebrew connection
* @memberOf Spacebrew.Client
*/
Spacebrew.Client.prototype.close = function(){
try {
if (this._isConnected) {
this.socket.close();
this._isConnected = false;
console.log("[close:Spacebrew] closing websocket connection")
}
} catch (e) {
this._isConnected = false;
}
}
/**
* Override in your app to receive on open event for connection
* @memberOf Spacebrew.Client
* @public
*/
Spacebrew.Client.prototype.onOpen = function( name, value ){}
/**
* Override in your app to receive on close event for connection
* @memberOf Spacebrew.Client
* @public
*/
Spacebrew.Client.prototype.onClose = function( name, value ){}
/**
* Override in your app to receive "range" messages, e.g. sb.onRangeMessage = yourRangeFunction
* @param {String} name Name of incoming route
* @param {String} value [description]
* @memberOf Spacebrew.Client
* @public
*/
Spacebrew.Client.prototype.onRangeMessage = function( name, value ){}
/**
* Override in your app to receive "boolean" messages, e.g. sb.onBooleanMessage = yourBoolFunction
* @param {String} name Name of incoming route
* @param {String} value [description]
* @memberOf Spacebrew.Client
* @public
*/
Spacebrew.Client.prototype.onBooleanMessage = function( name, value ){}
/**
* Override in your app to receive "string" messages, e.g. sb.onStringMessage = yourStringFunction
* @param {String} name Name of incoming route
* @param {String} value [description]
* @memberOf Spacebrew.Client
* @public
*/
Spacebrew.Client.prototype.onStringMessage = function( name, value ){}
/**
* Override in your app to receive "custom" messages, e.g. sb.onCustomMessage = yourStringFunction
* @param {String} name Name of incoming route
* @param {String} value [description]
* @memberOf Spacebrew.Client
* @public
*/
Spacebrew.Client.prototype.onCustomMessage = function( name, value, type ){}
/**
* Add a route you are publishing on
* @param {String} name Name of incoming route
* @param {String} type "boolean", "range", or "string"
* @param {String} def default value
* @memberOf Spacebrew.Client
* @public
*/
Spacebrew.Client.prototype.addPublish = function( name, type, def ){
this.client_config.publish.messages.push({"name":name, "type":type, "default":def});
this.updatePubSub();
}
/**
* [addSubscriber description]
* @param {String} name Name of outgoing route
* @param {String} type "boolean", "range", or "string"
* @memberOf Spacebrew.Client
* @public
*/
Spacebrew.Client.prototype.addSubscribe = function( name, type ){
this.client_config.subscribe.messages.push({"name":name, "type":type });
this.updatePubSub();
}
/**
* Update publishers and subscribers
* @memberOf Spacebrew.Client
* @private
*/
Spacebrew.Client.prototype.updatePubSub = function(){
if (this._isConnected) {
this.socket.send(JSON.stringify({"config": this.client_config}));
}
}
/**
* Send a route to Spacebrew
* @param {String} name Name of outgoing route (must match something in addPublish)
* @param {String} type "boolean", "range", or "string"
* @param {String} value Value to send
* @memberOf Spacebrew.Client
* @public
*/
Spacebrew.Client.prototype.send = function( name, type, value ){
var self = this;
this.msg = {
"message": {
"clientName":this._name,
"name": name,
"type": type,
"value": value
}
}
// if send block is not active then send message
if (!this.send_blocked) {
this.socket.send(JSON.stringify(this.msg));
this.send_blocked = true;
this.msg = undefined;
// set the timer to unblock message sending
setTimeout(function() {
self.send_blocked = false; // remove send block
if (self.msg != undefined) { // if message exists then sent it
self.send(self.msg.message.name, self.msg.message.type, self.msg.message.value);
}
}, self.send_interval);
}
}
/**
* Called on WebSocket open
* @private
* @memberOf Spacebrew.Client
*/
Spacebrew.Client.prototype._onOpen = function() {
console.log("[_onOpen:Spacebrew] Spacebrew connection opened, client name is: " + this._name);
this._isConnected = true;
if (this.admin.active) this.connectAdmin();
// if reconnect functionality is activated then clear interval timer when connection succeeds
if (this.reconnect_timer) {
console.log("[_onOpen:Spacebrew] tearing down reconnect timer")
this.reconnect_timer = clearInterval(this.reconnect_timer);
this.reconnect_timer = undefined;
}
// send my config
this.updatePubSub();
this.onOpen();
}
/**
* Called on WebSocket message
* @private
* @param {Object} e
* @memberOf Spacebrew.Client
*/
Spacebrew.Client.prototype._onMessage = function( e ){
var data = JSON.parse(e.data)
, name
, type
, value
;
// handle client messages
if (data["message"]) {
// check to make sure that this is not an admin message
if (!data.message["clientName"]) {
name = data.message.name;
type = data.message.type;
value = data.message.value;
switch( type ){
case "boolean":
this.onBooleanMessage( name, value == "true" );
break;
case "string":
this.onStringMessage( name, value );
break;
case "range":
this.onRangeMessage( name, Number(value) );
break;
default:
this.onCustomMessage( name, value, type );
}
}
}
// handle admin messages
else {
if (this.admin.active) {
this._handleAdminMessages( data );
}
}
}
/**
* Called on WebSocket close
* @private
* @memberOf Spacebrew.Client
*/
Spacebrew.Client.prototype._onClose = function() {
var self = this;
console.log("[_onClose:Spacebrew] Spacebrew connection closed");
this._isConnected = false;
if (this.admin.active) this.admin.remoteAddress = undefined;
// if reconnect functionality is activated set interval timer if connection dies
if (this.reconnect && !this.reconnect_timer) {
console.log("[_onClose:Spacebrew] setting up reconnect timer");
this.reconnect_timer = setInterval(function () {
if (self.isConnected != false) {
self.connect();
console.log("[reconnect:Spacebrew] attempting to reconnect to spacebrew");
}
}, 5000);
}
this.onClose();
};
/**
* name Method that sets or gets the spacebrew app name. If parameter is provided then it sets the name, otherwise
* it just returns the current app name.
* @param {String} newName New name of the spacebrew app
* @return {String} Returns the name of the spacebrew app if called as a getter function. If called as a
* setter function it will return false if the method is called after connecting to spacebrew,
* because the name must be configured before connection is made.
*/
Spacebrew.Client.prototype.name = function (newName){
if (newName) { // if a name has been passed in then update it
if (this._isConnected) return false; // if already connected we can't update name
this._name = newName;
if (window) {
this._name = (window.getQueryString('name') !== "" ? unescape(window.getQueryString('name')) : this._name);
}
this.client_config.name = this._name; // update spacebrew config file
}
return this._name;
};
/**
* name Method that sets or gets the spacebrew app description. If parameter is provided then it sets the description,
* otherwise it just returns the current app description.
* @param {String} newDesc New description of the spacebrew app
* @return {String} Returns the description of the spacebrew app if called as a getter function. If called as a
* setter function it will return false if the method is called after connecting to spacebrew,
* because the description must be configured before connection is made.
*/
Spacebrew.Client.prototype.description = function (newDesc){
if (newDesc) { // if a description has been passed in then update it
if (this._isConnected) return false; // if already connected we can't update description
this._description = newDesc || "spacebrew javascript client";
if (window) {
this._description = (window.getQueryString('description') !== "" ? unescape(window.getQueryString('description')) : this._description);
}
this.client_config.description = this._description; // update spacebrew config file
}
return this._description;
};
/**
* isConnected Method that returns current connection state of the spacebrew client.
* @return {Boolean} Returns true if currently connected to Spacebrew
*/
Spacebrew.Client.prototype.isConnected = function (){
return this._isConnected;
};
Spacebrew.Client.prototype.extend = function ( mixin ) {
for (var prop in mixin) {
if (mixin.hasOwnProperty(prop)) {
this[prop] = mixin[prop];
}
}
};
| RyanteckLTD/RTK-000-001-Controller | touchClient/js/sb-1.3.0.js | JavaScript | gpl-3.0 | 15,832 |
#!/bin/bash
# ----------------------------------------------------------------------
# Numenta Platform for Intelligent Computing (NuPIC)
# Copyright (C) 2013, Numenta, Inc. Unless you have an agreement
# with Numenta, Inc., for a separate license for this software code, the
# following terms and conditions apply:
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 3 as
# published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
# See the GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see http://www.gnu.org/licenses.
#
# http://numenta.org/licenses/
# ----------------------------------------------------------------------
echo
echo Running before_install-osx.sh...
echo
# Get Darwin64 libs for OSX
echo ">>> Cloning nupic-darwin64 at 40eee5d8b4f79fe52b282c393c8e1a1f5ba7a906..."
git clone https://github.com/numenta/nupic-darwin64.git
(cd nupic-darwin64 && git reset --hard 40eee5d8b4f79fe52b282c393c8e1a1f5ba7a906) || exit
echo ">>> Activating nupic-darwin64..."
source nupic-darwin64/bin/activate
# Install and start MySQL on OSX
echo ">>> brew install mysql"
brew install mysql
echo ">>> mysql.server start"
mysql.server start | oxtopus/nupic | ci/travis/before_install-osx.sh | Shell | gpl-3.0 | 1,501 |
/*
* Unix SMB/CIFS implementation.
* collected prototypes header
*
* frozen from "make proto" in May 2008
*
* Copyright (C) Michael Adam 2008
*
* 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/>.
*/
#ifndef _NTLM_AUTH_PROTO_H_
#define _NTLM_AUTH_PROTO_H_
/* The following definitions come from utils/ntlm_auth.c */
const char *get_winbind_domain(void);
const char *get_winbind_netbios_name(void);
DATA_BLOB get_challenge(void) ;
NTSTATUS contact_winbind_auth_crap(const char *username,
const char *domain,
const char *workstation,
const DATA_BLOB *challenge,
const DATA_BLOB *lm_response,
const DATA_BLOB *nt_response,
uint32_t flags,
uint32_t extra_logon_parameters,
uint8_t lm_key[8],
uint8_t user_session_key[16],
uint8_t *pauthoritative,
char **error_string,
char **unix_name);
/* The following definitions come from utils/ntlm_auth_diagnostics.c */
bool diagnose_ntlm_auth(void);
int get_pam_winbind_config(void);
#endif /* _NTLM_AUTH_PROTO_H_ */
| sathieu/samba | source3/utils/ntlm_auth_proto.h | C | gpl-3.0 | 1,648 |
#region License
// Copyright (c) 2013, ClearCanvas Inc.
// All rights reserved.
// http://www.clearcanvas.ca
//
// This file is part of the ClearCanvas RIS/PACS open source project.
//
// The ClearCanvas RIS/PACS open source project 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.
//
// The ClearCanvas RIS/PACS open source project 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
// the ClearCanvas RIS/PACS open source project. If not, see
// <http://www.gnu.org/licenses/>.
#endregion
using System;
using System.Security;
using System.Text;
using System.Text.RegularExpressions;
using System.Xml;
using ClearCanvas.Common;
using ClearCanvas.Dicom.Utilities.Xml;
namespace ClearCanvas.Dicom.Samples
{
public class EditSop
{
private readonly string _sourceFilename;
private DicomFile _dicomFile;
public EditSop(string file)
{
_sourceFilename = file;
}
public DicomFile DicomFile
{
get { return _dicomFile; }
}
public void Load()
{
_dicomFile = new DicomFile(_sourceFilename);
try
{
_dicomFile.Load();
}
catch (Exception e)
{
Platform.Log(LogLevel.Error, e, "Unexpected exception loading DICOM file: {0}", _sourceFilename);
}
}
public string GetXmlRepresentation()
{
var theDoc = GetXmlDoc();
var xmlSettings = new XmlWriterSettings
{
Encoding = Encoding.UTF8,
ConformanceLevel = ConformanceLevel.Document,
Indent = true,
NewLineOnAttributes = false,
CheckCharacters = true,
IndentChars = " "
};
StringBuilder sb = new StringBuilder();
XmlWriter tw = XmlWriter.Create(sb, xmlSettings);
theDoc.WriteTo(tw);
tw.Flush();
tw.Close();
return sb.ToString();
}
private XmlDocument GetXmlDoc()
{
var theDocument = new XmlDocument();
XmlElement instance = theDocument.CreateElement("Instance");
XmlAttribute sopInstanceUid = theDocument.CreateAttribute("UID");
sopInstanceUid.Value = _dicomFile.MediaStorageSopInstanceUid;
instance.Attributes.Append(sopInstanceUid);
XmlAttribute sopClassAttribute = theDocument.CreateAttribute("SopClassUID");
sopClassAttribute.Value = _dicomFile.SopClass.Uid;
instance.Attributes.Append(sopClassAttribute);
theDocument.AppendChild(instance);
foreach (DicomAttribute attribute in _dicomFile.DataSet)
{
XmlElement instanceElement = CreateDicomAttributeElement(theDocument, attribute.Tag, "Attribute");
if (attribute is DicomAttributeSQ || attribute is DicomAttributeOW || attribute is DicomAttributeUN ||
attribute is DicomAttributeOF || attribute is DicomAttributeOB)
{
continue;
}
instanceElement.InnerText = XmlEscapeString(attribute);
instance.AppendChild(instanceElement);
}
return theDocument;
}
private static XmlElement CreateDicomAttributeElement(XmlDocument document, DicomTag dicomTag, string name)
{
XmlElement dicomAttributeElement = document.CreateElement(name);
XmlAttribute tag = document.CreateAttribute("Tag");
tag.Value = "$" + dicomTag.VariableName;
XmlAttribute vr = document.CreateAttribute("VR");
vr.Value = dicomTag.VR.ToString();
dicomAttributeElement.Attributes.Append(tag);
dicomAttributeElement.Attributes.Append(vr);
return dicomAttributeElement;
}
private static string XmlEscapeString(string input)
{
string result = input ?? string.Empty;
result = SecurityElement.Escape(result);
// Do the regular expression to escape out other invalid XML characters in the string not caught by the above.
// NOTE: the \x sequences you see below are C# escapes, not Regex escapes
result = Regex.Replace(result, "[^\x9\xA\xD\x20-\xFFFD]", m => string.Format("&#x{0:X};", (int)m.Value[0]));
return result;
}
public void UpdateTags(string xml)
{
var theDoc = new XmlDocument();
try
{
theDoc.LoadXml(xml);
var instanceXml = new InstanceXml(theDoc.DocumentElement, null);
DicomAttributeCollection queryMessage = instanceXml.Collection;
if (queryMessage == null)
{
Platform.Log(LogLevel.Error, "Unexpected error parsing move message");
return;
}
foreach (var attribute in queryMessage)
{
_dicomFile.DataSet[attribute.Tag] = attribute.Copy();
}
}
catch (Exception x)
{
Platform.Log(LogLevel.Error, x, "Unable to perform update");
}
}
public void Save(string filename)
{
try
{
_dicomFile.Save(filename);
}
catch (Exception e)
{
Platform.Log(LogLevel.Error, e, "Unexpected exception saving dicom file: {0}", filename);
}
}
}
}
| testdoron/ClearCanvas | Dicom/Samples/EditSop.cs | C# | gpl-3.0 | 6,331 |
<!DOCTYPE html>
<html>
<title>Service Workers: ServiceWorker</title>
<head>
<link rel="help" href="https://w3c.github.io/ServiceWorker/#service-worker-obj">
<script src="/resources/testharness.js"></script>
<script src="/resources/testharnessreport.js"></script>
<script src=/resources/WebIDLParser.js></script>
<script src=/resources/idlharness.js></script>
</head>
<body>
<script type=text/plain id="idl_0">
[Constructor()] // no-op constructor
interface ServiceWorker : Worker {
readonly attribute DOMString scope;
readonly attribute DOMString url;
readonly attribute ServiceWorkerState state;
// event
attribute EventHandler onstatechange;
};
enum ServiceWorkerState {
"installing",
"installed",
"activating",
"activated",
"redundant"
};
</pre>
<!--
The `ServiceWorker` interface represents the document-side view of a Service
Worker. This object provides a no-op constructor. Callers should note that only
`ServiceWorker` objects created by the user agent (see
`navigator.serviceWorker.installing`, `navigator.serviceWorker.waiting`,
`navigator.serviceWorker.active` and `navigator.serviceWorker.controller`) will
provide meaningful functionality.
-->
<script type=text/plain id="untested_idls">
interface EventHandler {};
interface Worker {};
</pre>
<script>
var idl_array = new IdlArray();
idl_array.add_untested_idls(document.getElementById("untested_idls").textContent);
idl_array.add_idls(document.getElementById("idl_0").textContent);
idl_array.add_objects({
ServiceWorker: ["throw new Error ('No object defined for the ServiceWorker interface')"],
ServiceWorkerState: ["throw new Error ('No object defined for the ServiceWorkerState enum')"]
});
idl_array.test();
</script>
</body>
</html>
| bbansalWolfPack/servo | tests/wpt/web-platform-tests/service-workers/stub-3.1-service-worker-obj.html | HTML | mpl-2.0 | 1,893 |
// Copyright 2019 The go-ethereum Authors
// This file is part of the go-ethereum library.
//
// The go-ethereum library is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// The go-ethereum 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 go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
package netutil
import "net"
// AddrIP gets the IP address contained in addr. It returns nil if no address is present.
func AddrIP(addr net.Addr) net.IP {
switch a := addr.(type) {
case *net.IPAddr:
return a.IP
case *net.TCPAddr:
return a.IP
case *net.UDPAddr:
return a.IP
default:
return nil
}
}
| status-im/status-go | vendor/github.com/ethereum/go-ethereum/p2p/netutil/addrutil.go | GO | mpl-2.0 | 1,106 |
<?php
if(!defined('sugarEntry') || !sugarEntry) die('Not A Valid Entry Point');
/*********************************************************************************
* SugarCRM Community Edition is a customer relationship management program developed by
* SugarCRM, Inc. Copyright (C) 2004-2012 SugarCRM 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 SUGARCRM, SUGARCRM 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 SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
* SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.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
* SugarCRM" logo. If the display of the logo is not reasonably feasible for
* technical reasons, the Appropriate Legal Notices must display the words
* "Powered by SugarCRM".
********************************************************************************/
/*********************************************************************************
* Portions created by SugarCRM are Copyright (C) SugarCRM, Inc.
* All Rights Reserved.
* Contributor(s): ______________________________________..
********************************************************************************/
$module_name = 'lm_FaxMan';
$_module_name = 'lm_faxman';
$searchFields['lm_FaxMan'] =
array (
'document_name' => array( 'query_type'=>'default'),
'category_id'=> array('query_type'=>'default', 'options' => 'document_category_dom', 'template_var' => 'CATEGORY_OPTIONS'),
'subcategory_id'=> array('query_type'=>'default', 'options' => 'document_subcategory_dom', 'template_var' => 'SUBCATEGORY_OPTIONS'),
'active_date'=> array('query_type'=>'default'),
'exp_date'=> array('query_type'=>'default'),
//Range Search Support
'range_date_entered' => array ('query_type' => 'default', 'enable_range_search' => true, 'is_date_field' => true),
'start_range_date_entered' => array ('query_type' => 'default', 'enable_range_search' => true, 'is_date_field' => true),
'end_range_date_entered' => array ('query_type' => 'default', 'enable_range_search' => true, 'is_date_field' => true),
'range_date_modified' => array ('query_type' => 'default', 'enable_range_search' => true, 'is_date_field' => true),
'start_range_date_modified' => array ('query_type' => 'default', 'enable_range_search' => true, 'is_date_field' => true),
'end_range_date_modified' => array ('query_type' => 'default', 'enable_range_search' => true, 'is_date_field' => true),
//Range Search Support
);
?>
| KadJ/amazon_sugar | modules/lm_FaxMan/metadata/SearchFields.php | PHP | agpl-3.0 | 3,742 |
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>Iterators and Ranges</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. Boost.Numeric.Odeint">
<link rel="up" href="../odeint_in_detail.html" title="odeint in detail">
<link rel="prev" href="integrate_functions.html" title="Integrate functions">
<link rel="next" href="state_types__algebras_and_operations.html" title="State types, algebras and operations">
</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="../../logo.jpg"></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="integrate_functions.html"><img src="../../../../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../odeint_in_detail.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="state_types__algebras_and_operations.html"><img src="../../../../../../../doc/src/images/next.png" alt="Next"></a>
</div>
<div class="section">
<div class="titlepage"><div><div><h3 class="title">
<a name="boost_numeric_odeint.odeint_in_detail.iterators_and_ranges"></a><a class="link" href="iterators_and_ranges.html" title="Iterators and Ranges">Iterators
and Ranges</a>
</h3></div></div></div>
<div class="toc"><dl class="toc">
<dt><span class="section"><a href="iterators_and_ranges.html#boost_numeric_odeint.odeint_in_detail.iterators_and_ranges.examples">Examples</a></span></dt>
<dt><span class="section"><a href="iterators_and_ranges.html#boost_numeric_odeint.odeint_in_detail.iterators_and_ranges.const_step_iterator">const_step_iterator</a></span></dt>
<dt><span class="section"><a href="iterators_and_ranges.html#boost_numeric_odeint.odeint_in_detail.iterators_and_ranges.const_step_time_iterator">const_step_time_iterator</a></span></dt>
<dt><span class="section"><a href="iterators_and_ranges.html#boost_numeric_odeint.odeint_in_detail.iterators_and_ranges.adaptive_step_iterator">adaptive_step_iterator</a></span></dt>
<dt><span class="section"><a href="iterators_and_ranges.html#boost_numeric_odeint.odeint_in_detail.iterators_and_ranges.adaptive_step_time_iterator">adaptive_step_time_iterator</a></span></dt>
<dt><span class="section"><a href="iterators_and_ranges.html#boost_numeric_odeint.odeint_in_detail.iterators_and_ranges.n_step_iterator">n_step_iterator</a></span></dt>
<dt><span class="section"><a href="iterators_and_ranges.html#boost_numeric_odeint.odeint_in_detail.iterators_and_ranges.n_step_time_iterator">n_step_time_iterator</a></span></dt>
<dt><span class="section"><a href="iterators_and_ranges.html#boost_numeric_odeint.odeint_in_detail.iterators_and_ranges.times_iterator">times_iterator</a></span></dt>
<dt><span class="section"><a href="iterators_and_ranges.html#boost_numeric_odeint.odeint_in_detail.iterators_and_ranges.times_time_iterator">times_time_iterator</a></span></dt>
</dl></div>
<div class="section">
<div class="titlepage"><div><div><h4 class="title">
<a name="boost_numeric_odeint.odeint_in_detail.iterators_and_ranges.examples"></a><a class="link" href="iterators_and_ranges.html#boost_numeric_odeint.odeint_in_detail.iterators_and_ranges.examples" title="Examples">Examples</a>
</h4></div></div></div>
<p>
odeint supports iterators that iterate along an approximate solution of
an ordinary differential equation. Iterators offer you an alternative to
the integrate functions. Furthermore, many of the standard algorithms in
the C++ standard library and Boost.Range can be used with the odeint's
iterators.
</p>
<p>
Several iterator types are provided, in consistence with the <a class="link" href="integrate_functions.html" title="Integrate functions">integrate
functions</a>. Hence there are <code class="computeroutput"><span class="identifier">const_step_iterator</span></code>,
<code class="computeroutput"><span class="identifier">adaptive_step_iterator</span></code>,
<code class="computeroutput"><span class="identifier">n_step_iterator</span></code> and <code class="computeroutput"><span class="identifier">times_iterator</span></code> -- each of them in two
versions: either with only the <code class="computeroutput"><span class="identifier">state</span></code>
or with a <code class="computeroutput"><span class="identifier">std</span><span class="special">::</span><span class="identifier">pair</span><span class="special"><</span><span class="identifier">state</span><span class="special">,</span><span class="identifier">time</span><span class="special">></span></code>
as value type. They are all single pass iterators. In the following, we
show a few examples of how to use those iterators together with std algorithms.
</p>
<p>
</p>
<pre class="programlisting"><span class="identifier">runge_kutta4</span><span class="special"><</span> <span class="identifier">state_type</span> <span class="special">></span> <span class="identifier">stepper</span><span class="special">;</span>
<span class="identifier">state_type</span> <span class="identifier">x</span> <span class="special">=</span> <span class="special">{{</span> <span class="number">10.0</span> <span class="special">,</span> <span class="number">10.0</span> <span class="special">,</span> <span class="number">10.0</span> <span class="special">}};</span>
<span class="keyword">double</span> <span class="identifier">res</span> <span class="special">=</span> <span class="identifier">std</span><span class="special">::</span><span class="identifier">accumulate</span><span class="special">(</span> <span class="identifier">make_const_step_iterator_begin</span><span class="special">(</span> <span class="identifier">stepper</span> <span class="special">,</span> <span class="identifier">lorenz</span><span class="special">()</span> <span class="special">,</span> <span class="identifier">x</span> <span class="special">,</span> <span class="number">0.0</span> <span class="special">,</span> <span class="number">1.0</span> <span class="special">,</span> <span class="number">0.01</span> <span class="special">)</span> <span class="special">,</span>
<span class="identifier">make_const_step_iterator_end</span><span class="special">(</span> <span class="identifier">stepper</span> <span class="special">,</span> <span class="identifier">lorenz</span><span class="special">()</span> <span class="special">,</span> <span class="identifier">x</span> <span class="special">)</span> <span class="special">,</span>
<span class="number">0.0</span> <span class="special">,</span>
<span class="special">[](</span> <span class="keyword">double</span> <span class="identifier">sum</span> <span class="special">,</span> <span class="keyword">const</span> <span class="identifier">state_type</span> <span class="special">&</span><span class="identifier">x</span> <span class="special">)</span> <span class="special">{</span>
<span class="keyword">return</span> <span class="identifier">sum</span> <span class="special">+</span> <span class="identifier">x</span><span class="special">[</span><span class="number">0</span><span class="special">];</span> <span class="special">}</span> <span class="special">);</span>
<span class="identifier">cout</span> <span class="special"><<</span> <span class="identifier">res</span> <span class="special"><<</span> <span class="identifier">endl</span><span class="special">;</span>
</pre>
<p>
</p>
<p>
In this example all x-values of the solution are accumulated. Note, how
dereferencing the iterator gives the current state <code class="computeroutput"><span class="identifier">x</span></code>
of the ODE (the second argument of the accumulate lambda). The iterator
itself does not occur directly in this example but it is generated by the
factory functions <code class="computeroutput"><span class="identifier">make_const_step_iterator_begin</span></code>
and <code class="computeroutput"><span class="identifier">make_const_step_iterator_end</span></code>.
odeint also supports Boost.Range, that allows to write the above example
in a more compact form with the factory function <code class="computeroutput"><span class="identifier">make_const_step_range</span></code>,
but now using <code class="computeroutput"><span class="identifier">boost</span><span class="special">::</span><span class="identifier">accumulate</span></code> from __bost_range:
</p>
<p>
</p>
<pre class="programlisting"><span class="identifier">runge_kutta4</span><span class="special"><</span> <span class="identifier">state_type</span> <span class="special">></span> <span class="identifier">stepper</span><span class="special">;</span>
<span class="identifier">state_type</span> <span class="identifier">x</span> <span class="special">=</span> <span class="special">{{</span> <span class="number">10.0</span> <span class="special">,</span> <span class="number">10.0</span> <span class="special">,</span> <span class="number">10.0</span> <span class="special">}};</span>
<span class="keyword">double</span> <span class="identifier">res</span> <span class="special">=</span> <span class="identifier">boost</span><span class="special">::</span><span class="identifier">accumulate</span><span class="special">(</span> <span class="identifier">make_const_step_range</span><span class="special">(</span> <span class="identifier">stepper</span> <span class="special">,</span> <span class="identifier">lorenz</span><span class="special">()</span> <span class="special">,</span> <span class="identifier">x</span> <span class="special">,</span> <span class="number">0.0</span> <span class="special">,</span> <span class="number">1.0</span> <span class="special">,</span> <span class="number">0.01</span> <span class="special">)</span> <span class="special">,</span> <span class="number">0.0</span> <span class="special">,</span>
<span class="special">[](</span> <span class="keyword">double</span> <span class="identifier">sum</span> <span class="special">,</span> <span class="keyword">const</span> <span class="identifier">state_type</span> <span class="special">&</span><span class="identifier">x</span> <span class="special">)</span> <span class="special">{</span>
<span class="keyword">return</span> <span class="identifier">sum</span> <span class="special">+</span> <span class="identifier">x</span><span class="special">[</span><span class="number">0</span><span class="special">];</span> <span class="special">}</span> <span class="special">);</span>
<span class="identifier">cout</span> <span class="special"><<</span> <span class="identifier">res</span> <span class="special"><<</span> <span class="identifier">endl</span><span class="special">;</span>
</pre>
<p>
</p>
<p>
The second iterator type is also a iterator with const step size. But the
value type of this iterator consists here of a pair of the time and the
state of the solution of the ODE. An example is
</p>
<p>
</p>
<pre class="programlisting"><span class="identifier">runge_kutta4</span><span class="special"><</span> <span class="identifier">state_type</span> <span class="special">></span> <span class="identifier">stepper</span><span class="special">;</span>
<span class="identifier">state_type</span> <span class="identifier">x</span> <span class="special">=</span> <span class="special">{{</span> <span class="number">10.0</span> <span class="special">,</span> <span class="number">10.0</span> <span class="special">,</span> <span class="number">10.0</span> <span class="special">}};</span>
<span class="keyword">double</span> <span class="identifier">res</span> <span class="special">=</span> <span class="identifier">boost</span><span class="special">::</span><span class="identifier">accumulate</span><span class="special">(</span> <span class="identifier">make_const_step_time_range</span><span class="special">(</span> <span class="identifier">stepper</span> <span class="special">,</span> <span class="identifier">lorenz</span><span class="special">()</span> <span class="special">,</span> <span class="identifier">x</span> <span class="special">,</span> <span class="number">0.0</span> <span class="special">,</span> <span class="number">1.0</span> <span class="special">,</span> <span class="number">0.01</span> <span class="special">)</span> <span class="special">,</span> <span class="number">0.0</span> <span class="special">,</span>
<span class="special">[](</span> <span class="keyword">double</span> <span class="identifier">sum</span> <span class="special">,</span> <span class="keyword">const</span> <span class="identifier">std</span><span class="special">::</span><span class="identifier">pair</span><span class="special"><</span> <span class="keyword">const</span> <span class="identifier">state_type</span> <span class="special">&,</span> <span class="keyword">double</span> <span class="special">></span> <span class="special">&</span><span class="identifier">x</span> <span class="special">)</span> <span class="special">{</span>
<span class="keyword">return</span> <span class="identifier">sum</span> <span class="special">+</span> <span class="identifier">x</span><span class="special">.</span><span class="identifier">first</span><span class="special">[</span><span class="number">0</span><span class="special">];</span> <span class="special">}</span> <span class="special">);</span>
<span class="identifier">cout</span> <span class="special"><<</span> <span class="identifier">res</span> <span class="special"><<</span> <span class="identifier">endl</span><span class="special">;</span>
</pre>
<p>
</p>
<p>
The factory functions are now <code class="computeroutput"><span class="identifier">make_const_step_time_iterator_begin</span></code>,
<code class="computeroutput"><span class="identifier">make_const_step_time_iterator_end</span></code>
and <code class="computeroutput"><span class="identifier">make_const_step_time_range</span></code>.
Note, how the lambda now expects a <code class="computeroutput"><span class="identifier">std</span><span class="special">::</span><span class="identifier">pair</span></code>
as this is the value type of the <code class="computeroutput"><span class="identifier">const_step_time_iterator</span></code>'s.
</p>
<p>
Next, we discuss the adaptive iterators which are completely analogous
to the const step iterators, but are based on adaptive stepper routines
and thus adjust the step size during the iteration. Examples are
</p>
<p>
</p>
<pre class="programlisting"><span class="keyword">auto</span> <span class="identifier">stepper</span> <span class="special">=</span> <span class="identifier">make_controlled</span><span class="special">(</span> <span class="number">1.0e-6</span> <span class="special">,</span> <span class="number">1.0e-6</span> <span class="special">,</span> <span class="identifier">runge_kutta_cash_karp54</span><span class="special"><</span> <span class="identifier">state_type</span> <span class="special">>()</span> <span class="special">);</span>
<span class="identifier">state_type</span> <span class="identifier">x</span> <span class="special">=</span> <span class="special">{{</span> <span class="number">10.0</span> <span class="special">,</span> <span class="number">10.0</span> <span class="special">,</span> <span class="number">10.0</span> <span class="special">}};</span>
<span class="keyword">double</span> <span class="identifier">res</span> <span class="special">=</span> <span class="identifier">boost</span><span class="special">::</span><span class="identifier">accumulate</span><span class="special">(</span> <span class="identifier">make_adaptive_range</span><span class="special">(</span> <span class="identifier">stepper</span> <span class="special">,</span> <span class="identifier">lorenz</span><span class="special">()</span> <span class="special">,</span> <span class="identifier">x</span> <span class="special">,</span> <span class="number">0.0</span> <span class="special">,</span> <span class="number">1.0</span> <span class="special">,</span> <span class="number">0.01</span> <span class="special">)</span> <span class="special">,</span> <span class="number">0.0</span> <span class="special">,</span>
<span class="special">[](</span> <span class="keyword">double</span> <span class="identifier">sum</span> <span class="special">,</span> <span class="keyword">const</span> <span class="identifier">state_type</span><span class="special">&</span> <span class="identifier">x</span> <span class="special">)</span> <span class="special">{</span>
<span class="keyword">return</span> <span class="identifier">sum</span> <span class="special">+</span> <span class="identifier">x</span><span class="special">[</span><span class="number">0</span><span class="special">];</span> <span class="special">}</span> <span class="special">);</span>
<span class="identifier">cout</span> <span class="special"><<</span> <span class="identifier">res</span> <span class="special"><<</span> <span class="identifier">endl</span><span class="special">;</span>
</pre>
<p>
</p>
<p>
</p>
<pre class="programlisting"><span class="keyword">auto</span> <span class="identifier">stepper</span> <span class="special">=</span> <span class="identifier">make_controlled</span><span class="special">(</span> <span class="number">1.0e-6</span> <span class="special">,</span> <span class="number">1.0e-6</span> <span class="special">,</span> <span class="identifier">runge_kutta_cash_karp54</span><span class="special"><</span> <span class="identifier">state_type</span> <span class="special">>()</span> <span class="special">);</span>
<span class="identifier">state_type</span> <span class="identifier">x</span> <span class="special">=</span> <span class="special">{{</span> <span class="number">10.0</span> <span class="special">,</span> <span class="number">10.0</span> <span class="special">,</span> <span class="number">10.0</span> <span class="special">}};</span>
<span class="keyword">double</span> <span class="identifier">res</span> <span class="special">=</span> <span class="identifier">boost</span><span class="special">::</span><span class="identifier">accumulate</span><span class="special">(</span> <span class="identifier">make_adaptive_time_range</span><span class="special">(</span> <span class="identifier">stepper</span> <span class="special">,</span> <span class="identifier">lorenz</span><span class="special">()</span> <span class="special">,</span> <span class="identifier">x</span> <span class="special">,</span> <span class="number">0.0</span> <span class="special">,</span> <span class="number">1.0</span> <span class="special">,</span> <span class="number">0.01</span> <span class="special">)</span> <span class="special">,</span> <span class="number">0.0</span> <span class="special">,</span>
<span class="special">[](</span> <span class="keyword">double</span> <span class="identifier">sum</span> <span class="special">,</span> <span class="keyword">const</span> <span class="identifier">pair</span><span class="special"><</span> <span class="keyword">const</span> <span class="identifier">state_type</span><span class="special">&</span> <span class="special">,</span> <span class="keyword">double</span> <span class="special">></span> <span class="special">&</span><span class="identifier">x</span> <span class="special">)</span> <span class="special">{</span>
<span class="keyword">return</span> <span class="identifier">sum</span> <span class="special">+</span> <span class="identifier">x</span><span class="special">.</span><span class="identifier">first</span><span class="special">[</span><span class="number">0</span><span class="special">];</span> <span class="special">}</span> <span class="special">);</span>
<span class="identifier">cout</span> <span class="special"><<</span> <span class="identifier">res</span> <span class="special"><<</span> <span class="identifier">endl</span><span class="special">;</span>
</pre>
<p>
</p>
<div class="note"><table border="0" summary="Note">
<tr>
<td rowspan="2" align="center" valign="top" width="25"><img alt="[Note]" src="../../../../../../../doc/src/images/note.png"></td>
<th align="left">Note</th>
</tr>
<tr><td align="left" valign="top"><p>
'adaptive_iterator<code class="computeroutput"> <span class="keyword">and</span> </code>adaptive_time_iterator'
can only be used with <a class="link" href="../concepts/controlled_stepper.html" title="Controlled Stepper">Controlled
Stepper</a> or <a class="link" href="../concepts/dense_output_stepper.html" title="Dense Output Stepper">Dense
Output Stepper</a>.
</p></td></tr>
</table></div>
<p>
In general one can say that iterating over a range of a <code class="computeroutput"><span class="identifier">const_step_iterator</span></code>
behaves like an <code class="computeroutput"><span class="identifier">integrate_const</span></code>
function call, and similarly for <code class="computeroutput"><span class="identifier">adaptive_iterator</span></code>
and <code class="computeroutput"><span class="identifier">integrate_adaptive</span></code>,
<code class="computeroutput"><span class="identifier">n_step_iterator</span></code> and <code class="computeroutput"><span class="identifier">integrate_n_steps</span></code>, and finally <code class="computeroutput"><span class="identifier">times_iterator</span></code> and <code class="computeroutput"><span class="identifier">integrate_times</span></code>.
</p>
<p>
Below we list the most important properties of the exisiting iterators:
</p>
</div>
<div class="section">
<div class="titlepage"><div><div><h4 class="title">
<a name="boost_numeric_odeint.odeint_in_detail.iterators_and_ranges.const_step_iterator"></a><a class="link" href="iterators_and_ranges.html#boost_numeric_odeint.odeint_in_detail.iterators_and_ranges.const_step_iterator" title="const_step_iterator">const_step_iterator</a>
</h4></div></div></div>
<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; ">
<li class="listitem">
Definition: <code class="computeroutput"><span class="identifier">const_step_iterator</span><span class="special"><</span> <span class="identifier">Stepper</span>
<span class="special">,</span> <span class="identifier">System</span>
<span class="special">,</span> <span class="identifier">State</span>
<span class="special">></span></code>
</li>
<li class="listitem">
<code class="computeroutput"><span class="identifier">value_type</span></code> is <code class="computeroutput"><span class="identifier">State</span></code>
</li>
<li class="listitem">
<code class="computeroutput"><span class="identifier">reference_type</span></code> is
<code class="computeroutput"><span class="identifier">State</span> <span class="keyword">const</span><span class="special">&</span></code>
</li>
<li class="listitem">
Factory functions
<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: circle; ">
<li class="listitem">
<code class="computeroutput"><span class="identifier">make_const_step_iterator_begin</span><span class="special">(</span> <span class="identifier">stepper</span>
<span class="special">,</span> <span class="identifier">system</span>
<span class="special">,</span> <span class="identifier">state</span>
<span class="special">,</span> <span class="identifier">t_start</span>
<span class="special">,</span> <span class="identifier">t_end</span>
<span class="special">,</span> <span class="identifier">dt</span>
<span class="special">)</span></code>
</li>
<li class="listitem">
<code class="computeroutput"><span class="identifier">make_const_step_iterator_end</span><span class="special">(</span> <span class="identifier">stepper</span>
<span class="special">,</span> <span class="identifier">system</span>
<span class="special">,</span> <span class="identifier">state</span>
<span class="special">)</span></code>
</li>
<li class="listitem">
<code class="computeroutput"><span class="identifier">make_const_step_range</span><span class="special">(</span> <span class="identifier">stepper</span>
<span class="special">,</span> <span class="identifier">system</span>
<span class="special">,</span> <span class="identifier">state</span>
<span class="special">,</span> <span class="identifier">t_start</span>
<span class="special">,</span> <span class="identifier">t_end</span>
<span class="special">,</span> <span class="identifier">dt</span>
<span class="special">)</span></code>
</li>
</ul></div>
</li>
<li class="listitem">
This stepper works with all steppers fulfilling the Stepper concept
or the DenseOutputStepper concept.
</li>
<li class="listitem">
The value of <code class="computeroutput"><span class="identifier">state</span></code>
is the current state of the ODE during the iteration.
</li>
</ul></div>
</div>
<div class="section">
<div class="titlepage"><div><div><h4 class="title">
<a name="boost_numeric_odeint.odeint_in_detail.iterators_and_ranges.const_step_time_iterator"></a><a class="link" href="iterators_and_ranges.html#boost_numeric_odeint.odeint_in_detail.iterators_and_ranges.const_step_time_iterator" title="const_step_time_iterator">const_step_time_iterator</a>
</h4></div></div></div>
<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; ">
<li class="listitem">
Definition: <code class="computeroutput"><span class="identifier">const_step_time_iterator</span><span class="special"><</span> <span class="identifier">Stepper</span>
<span class="special">,</span> <span class="identifier">System</span>
<span class="special">,</span> <span class="identifier">State</span>
<span class="special">></span></code>
</li>
<li class="listitem">
<code class="computeroutput"><span class="identifier">value_type</span></code> is <code class="computeroutput"><span class="identifier">std</span><span class="special">::</span><span class="identifier">pair</span><span class="special"><</span>
<span class="identifier">State</span> <span class="special">,</span>
<span class="identifier">Stepper</span><span class="special">::</span><span class="identifier">time_type</span> <span class="special">></span></code>
</li>
<li class="listitem">
<code class="computeroutput"><span class="identifier">reference_type</span></code> is
<code class="computeroutput"><span class="identifier">std</span><span class="special">::</span><span class="identifier">pair</span><span class="special"><</span>
<span class="identifier">State</span> <span class="keyword">const</span><span class="special">&</span> <span class="special">,</span> <span class="identifier">Stepper</span><span class="special">::</span><span class="identifier">time_type</span> <span class="special">></span>
<span class="keyword">const</span><span class="special">&</span></code>
</li>
<li class="listitem">
Factory functions
<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: circle; ">
<li class="listitem">
<code class="computeroutput"><span class="identifier">make_const_step_time_iterator_begin</span><span class="special">(</span> <span class="identifier">stepper</span>
<span class="special">,</span> <span class="identifier">system</span>
<span class="special">,</span> <span class="identifier">state</span>
<span class="special">,</span> <span class="identifier">t_start</span>
<span class="special">,</span> <span class="identifier">t_end</span>
<span class="special">,</span> <span class="identifier">dt</span>
<span class="special">)</span></code>
</li>
<li class="listitem">
<code class="computeroutput"><span class="identifier">make_const_step_time_iterator_end</span><span class="special">(</span> <span class="identifier">stepper</span>
<span class="special">,</span> <span class="identifier">system</span>
<span class="special">,</span> <span class="identifier">state</span>
<span class="special">)</span></code>
</li>
<li class="listitem">
<code class="computeroutput"><span class="identifier">make_const_step_time_range</span><span class="special">(</span> <span class="identifier">stepper</span>
<span class="special">,</span> <span class="identifier">system</span>
<span class="special">,</span> <span class="identifier">state</span>
<span class="special">,</span> <span class="identifier">t_start</span>
<span class="special">,</span> <span class="identifier">t_end</span>
<span class="special">,</span> <span class="identifier">dt</span>
<span class="special">)</span></code>
</li>
</ul></div>
</li>
<li class="listitem">
This stepper works with all steppers fulfilling the Stepper concept
or the DenseOutputStepper concept.
</li>
<li class="listitem">
This stepper updates the value of <code class="computeroutput"><span class="identifier">state</span></code>.
The value of <code class="computeroutput"><span class="identifier">state</span></code>
is the current state of the ODE during the iteration.
</li>
</ul></div>
</div>
<div class="section">
<div class="titlepage"><div><div><h4 class="title">
<a name="boost_numeric_odeint.odeint_in_detail.iterators_and_ranges.adaptive_step_iterator"></a><a class="link" href="iterators_and_ranges.html#boost_numeric_odeint.odeint_in_detail.iterators_and_ranges.adaptive_step_iterator" title="adaptive_step_iterator">adaptive_step_iterator</a>
</h4></div></div></div>
<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; ">
<li class="listitem">
Definition: <code class="computeroutput"><span class="identifier">adaptive_iterator</span><span class="special"><</span> <span class="identifier">Stepper</span>
<span class="special">,</span> <span class="identifier">System</span>
<span class="special">,</span> <span class="identifier">State</span>
<span class="special">></span></code>
</li>
<li class="listitem">
<code class="computeroutput"><span class="identifier">value_type</span></code> is <code class="computeroutput"><span class="identifier">State</span></code>
</li>
<li class="listitem">
<code class="computeroutput"><span class="identifier">reference_type</span></code> is
<code class="computeroutput"><span class="identifier">State</span> <span class="keyword">const</span><span class="special">&</span></code>
</li>
<li class="listitem">
Factory functions
<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: circle; ">
<li class="listitem">
<code class="computeroutput"><span class="identifier">make_adaptive_iterator_begin</span><span class="special">(</span> <span class="identifier">stepper</span>
<span class="special">,</span> <span class="identifier">system</span>
<span class="special">,</span> <span class="identifier">state</span>
<span class="special">,</span> <span class="identifier">t_start</span>
<span class="special">,</span> <span class="identifier">t_end</span>
<span class="special">,</span> <span class="identifier">dt</span>
<span class="special">)</span></code>
</li>
<li class="listitem">
<code class="computeroutput"><span class="identifier">make_adaptive_iterator_end</span><span class="special">(</span> <span class="identifier">stepper</span>
<span class="special">,</span> <span class="identifier">system</span>
<span class="special">,</span> <span class="identifier">state</span>
<span class="special">)</span></code>
</li>
<li class="listitem">
<code class="computeroutput"><span class="identifier">make_adaptive_range</span><span class="special">(</span> <span class="identifier">stepper</span>
<span class="special">,</span> <span class="identifier">system</span>
<span class="special">,</span> <span class="identifier">state</span>
<span class="special">,</span> <span class="identifier">t_start</span>
<span class="special">,</span> <span class="identifier">t_end</span>
<span class="special">,</span> <span class="identifier">dt</span>
<span class="special">)</span></code>
</li>
</ul></div>
</li>
<li class="listitem">
This stepper works with all steppers fulfilling the ControlledStepper
concept or the DenseOutputStepper concept.
</li>
<li class="listitem">
For steppers fulfilling the ControlledStepper concept <code class="computeroutput"><span class="identifier">state</span></code> is modified according to the
current state of the ODE. For DenseOutputStepper the state is not modified
due to performance optimizations, but the steppers itself.
</li>
</ul></div>
</div>
<div class="section">
<div class="titlepage"><div><div><h4 class="title">
<a name="boost_numeric_odeint.odeint_in_detail.iterators_and_ranges.adaptive_step_time_iterator"></a><a class="link" href="iterators_and_ranges.html#boost_numeric_odeint.odeint_in_detail.iterators_and_ranges.adaptive_step_time_iterator" title="adaptive_step_time_iterator">adaptive_step_time_iterator</a>
</h4></div></div></div>
<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; ">
<li class="listitem">
Definition: <code class="computeroutput"><span class="identifier">adaptive_iterator</span><span class="special"><</span> <span class="identifier">Stepper</span>
<span class="special">,</span> <span class="identifier">System</span>
<span class="special">,</span> <span class="identifier">State</span>
<span class="special">></span></code>
</li>
<li class="listitem">
<code class="computeroutput"><span class="identifier">value_type</span></code> is <code class="computeroutput"><span class="identifier">std</span><span class="special">::</span><span class="identifier">pair</span><span class="special"><</span>
<span class="identifier">State</span> <span class="special">,</span>
<span class="identifier">Stepper</span><span class="special">::</span><span class="identifier">time_type</span> <span class="special">></span></code>
</li>
<li class="listitem">
<code class="computeroutput"><span class="identifier">reference_type</span></code> is
<code class="computeroutput"><span class="identifier">std</span><span class="special">::</span><span class="identifier">pair</span><span class="special"><</span>
<span class="identifier">State</span> <span class="keyword">const</span><span class="special">&</span> <span class="special">,</span> <span class="identifier">Stepper</span><span class="special">::</span><span class="identifier">time_type</span> <span class="special">></span>
<span class="keyword">const</span><span class="special">&</span></code>
</li>
<li class="listitem">
Factory functions
<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: circle; ">
<li class="listitem">
<code class="computeroutput"><span class="identifier">make_adaptive_time_iterator_begin</span><span class="special">(</span> <span class="identifier">stepper</span>
<span class="special">,</span> <span class="identifier">system</span>
<span class="special">,</span> <span class="identifier">state</span>
<span class="special">,</span> <span class="identifier">t_start</span>
<span class="special">,</span> <span class="identifier">t_end</span>
<span class="special">,</span> <span class="identifier">dt</span>
<span class="special">)</span></code>
</li>
<li class="listitem">
<code class="computeroutput"><span class="identifier">make_adaptive_time_iterator_end</span><span class="special">(</span> <span class="identifier">stepper</span>
<span class="special">,</span> <span class="identifier">system</span>
<span class="special">,</span> <span class="identifier">state</span>
<span class="special">)</span></code>
</li>
<li class="listitem">
<code class="computeroutput"><span class="identifier">make_adaptive_time_range</span><span class="special">(</span> <span class="identifier">stepper</span>
<span class="special">,</span> <span class="identifier">system</span>
<span class="special">,</span> <span class="identifier">state</span>
<span class="special">,</span> <span class="identifier">t_start</span>
<span class="special">,</span> <span class="identifier">t_end</span>
<span class="special">,</span> <span class="identifier">dt</span>
<span class="special">)</span></code>
</li>
</ul></div>
</li>
<li class="listitem">
This stepper works with all steppers fulfilling the ControlledStepper
concept or the DenseOutputStepper concept.
</li>
<li class="listitem">
For steppers fulfilling the ControlledStepper concept <code class="computeroutput"><span class="identifier">state</span></code> is modified according to the
current state of the ODE. For DenseOutputStepper the state is not modified
due to performance optimizations, but the stepper itself.
</li>
</ul></div>
</div>
<div class="section">
<div class="titlepage"><div><div><h4 class="title">
<a name="boost_numeric_odeint.odeint_in_detail.iterators_and_ranges.n_step_iterator"></a><a class="link" href="iterators_and_ranges.html#boost_numeric_odeint.odeint_in_detail.iterators_and_ranges.n_step_iterator" title="n_step_iterator">n_step_iterator</a>
</h4></div></div></div>
<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; ">
<li class="listitem">
Definition: <code class="computeroutput"><span class="identifier">n_step_iterator</span><span class="special"><</span> <span class="identifier">Stepper</span>
<span class="special">,</span> <span class="identifier">System</span>
<span class="special">,</span> <span class="identifier">State</span>
<span class="special">></span></code>
</li>
<li class="listitem">
<code class="computeroutput"><span class="identifier">value_type</span></code> is <code class="computeroutput"><span class="identifier">State</span></code>
</li>
<li class="listitem">
<code class="computeroutput"><span class="identifier">reference_type</span></code> is
<code class="computeroutput"><span class="identifier">State</span> <span class="keyword">const</span><span class="special">&</span></code>
</li>
<li class="listitem">
Factory functions
<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: circle; ">
<li class="listitem">
<code class="computeroutput"><span class="identifier">make_n_step_iterator_begin</span><span class="special">(</span> <span class="identifier">stepper</span>
<span class="special">,</span> <span class="identifier">system</span>
<span class="special">,</span> <span class="identifier">state</span>
<span class="special">,</span> <span class="identifier">t_start</span>
<span class="special">,</span> <span class="identifier">dt</span>
<span class="special">,</span> <span class="identifier">num_of_steps</span>
<span class="special">)</span></code>
</li>
<li class="listitem">
<code class="computeroutput"><span class="identifier">make_n_step_iterator_end</span><span class="special">(</span> <span class="identifier">stepper</span>
<span class="special">,</span> <span class="identifier">system</span>
<span class="special">,</span> <span class="identifier">state</span>
<span class="special">)</span></code>
</li>
<li class="listitem">
<code class="computeroutput"><span class="identifier">make_n_step_range</span><span class="special">(</span> <span class="identifier">stepper</span>
<span class="special">,</span> <span class="identifier">system</span>
<span class="special">,</span> <span class="identifier">state</span>
<span class="special">,</span> <span class="identifier">t_start</span>
<span class="special">,</span> <span class="identifier">dt</span>
<span class="special">,</span> <span class="identifier">num_of_steps</span>
<span class="special">)</span></code>
</li>
</ul></div>
</li>
<li class="listitem">
This stepper works with all steppers fulfilling the Stepper concept
or the DenseOutputStepper concept.
</li>
<li class="listitem">
The value of <code class="computeroutput"><span class="identifier">state</span></code>
is the current state of the ODE during the iteration.
</li>
</ul></div>
</div>
<div class="section">
<div class="titlepage"><div><div><h4 class="title">
<a name="boost_numeric_odeint.odeint_in_detail.iterators_and_ranges.n_step_time_iterator"></a><a class="link" href="iterators_and_ranges.html#boost_numeric_odeint.odeint_in_detail.iterators_and_ranges.n_step_time_iterator" title="n_step_time_iterator">n_step_time_iterator</a>
</h4></div></div></div>
<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; ">
<li class="listitem">
Definition: <code class="computeroutput"><span class="identifier">n_step_time_iterator</span><span class="special"><</span> <span class="identifier">Stepper</span>
<span class="special">,</span> <span class="identifier">System</span>
<span class="special">,</span> <span class="identifier">State</span>
<span class="special">></span></code>
</li>
<li class="listitem">
<code class="computeroutput"><span class="identifier">value_type</span></code> is <code class="computeroutput"><span class="identifier">std</span><span class="special">::</span><span class="identifier">pair</span><span class="special"><</span>
<span class="identifier">State</span> <span class="special">,</span>
<span class="identifier">Stepper</span><span class="special">::</span><span class="identifier">time_type</span> <span class="special">></span></code>
</li>
<li class="listitem">
<code class="computeroutput"><span class="identifier">reference_type</span></code> is
<code class="computeroutput"><span class="identifier">std</span><span class="special">::</span><span class="identifier">pair</span><span class="special"><</span>
<span class="identifier">State</span> <span class="keyword">const</span><span class="special">&</span> <span class="special">,</span> <span class="identifier">Stepper</span><span class="special">::</span><span class="identifier">time_type</span> <span class="special">></span>
<span class="keyword">const</span><span class="special">&</span></code>
</li>
<li class="listitem">
Factory functions
<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: circle; ">
<li class="listitem">
<code class="computeroutput"><span class="identifier">make_n_step_time_iterator_begin</span><span class="special">(</span> <span class="identifier">stepper</span>
<span class="special">,</span> <span class="identifier">system</span>
<span class="special">,</span> <span class="identifier">state</span>
<span class="special">,</span> <span class="identifier">t_start</span>
<span class="special">,</span> <span class="identifier">dt</span>
<span class="special">,</span> <span class="identifier">num_of_steps</span>
<span class="special">)</span></code>
</li>
<li class="listitem">
<code class="computeroutput"><span class="identifier">make_n_step_time_iterator_end</span><span class="special">(</span> <span class="identifier">stepper</span>
<span class="special">,</span> <span class="identifier">system</span>
<span class="special">,</span> <span class="identifier">state</span>
<span class="special">)</span></code>
</li>
<li class="listitem">
<code class="computeroutput"><span class="identifier">make_n_step_time_range</span><span class="special">(</span> <span class="identifier">stepper</span>
<span class="special">,</span> <span class="identifier">system</span>
<span class="special">,</span> <span class="identifier">state</span>
<span class="special">,</span> <span class="identifier">t_start</span>
<span class="special">,</span> <span class="identifier">dt</span>
<span class="special">,</span> <span class="identifier">num_of_steps</span>
<span class="special">)</span></code>
</li>
</ul></div>
</li>
<li class="listitem">
This stepper works with all steppers fulfilling the Stepper concept
or the DenseOutputStepper concept.
</li>
<li class="listitem">
This stepper updates the value of <code class="computeroutput"><span class="identifier">state</span></code>.
The value of <code class="computeroutput"><span class="identifier">state</span></code>
is the current state of the ODE during the iteration.
</li>
</ul></div>
</div>
<div class="section">
<div class="titlepage"><div><div><h4 class="title">
<a name="boost_numeric_odeint.odeint_in_detail.iterators_and_ranges.times_iterator"></a><a class="link" href="iterators_and_ranges.html#boost_numeric_odeint.odeint_in_detail.iterators_and_ranges.times_iterator" title="times_iterator">times_iterator</a>
</h4></div></div></div>
<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; ">
<li class="listitem">
Definition: <code class="computeroutput"><span class="identifier">times_iterator</span><span class="special"><</span> <span class="identifier">Stepper</span>
<span class="special">,</span> <span class="identifier">System</span>
<span class="special">,</span> <span class="identifier">State</span>
<span class="special">,</span> <span class="identifier">TimeIterator</span>
<span class="special">></span></code>
</li>
<li class="listitem">
<code class="computeroutput"><span class="identifier">value_type</span></code> is <code class="computeroutput"><span class="identifier">State</span></code>
</li>
<li class="listitem">
<code class="computeroutput"><span class="identifier">reference_type</span></code> is
<code class="computeroutput"><span class="identifier">State</span> <span class="keyword">const</span><span class="special">&</span></code>
</li>
<li class="listitem">
Factory functions
<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: circle; ">
<li class="listitem">
<code class="computeroutput"><span class="identifier">make_times_iterator_begin</span><span class="special">(</span> <span class="identifier">stepper</span>
<span class="special">,</span> <span class="identifier">system</span>
<span class="special">,</span> <span class="identifier">state</span>
<span class="special">,</span> <span class="identifier">t_start</span>
<span class="special">,</span> <span class="identifier">t_end</span>
<span class="special">,</span> <span class="identifier">dt</span>
<span class="special">)</span></code>
</li>
<li class="listitem">
<code class="computeroutput"><span class="identifier">make_times_iterator_end</span><span class="special">(</span> <span class="identifier">stepper</span>
<span class="special">,</span> <span class="identifier">system</span>
<span class="special">,</span> <span class="identifier">state</span>
<span class="special">)</span></code>
</li>
<li class="listitem">
<code class="computeroutput"><span class="identifier">make_times_range</span><span class="special">(</span> <span class="identifier">stepper</span>
<span class="special">,</span> <span class="identifier">system</span>
<span class="special">,</span> <span class="identifier">state</span>
<span class="special">,</span> <span class="identifier">t_start</span>
<span class="special">,</span> <span class="identifier">t_end</span>
<span class="special">,</span> <span class="identifier">dt</span>
<span class="special">)</span></code>
</li>
</ul></div>
</li>
<li class="listitem">
This stepper works with all steppers fulfilling the Stepper concept,
the ControlledStepper concept or the DenseOutputStepper concept.
</li>
<li class="listitem">
The value of <code class="computeroutput"><span class="identifier">state</span></code>
is the current state of the ODE during the iteration.
</li>
</ul></div>
</div>
<div class="section">
<div class="titlepage"><div><div><h4 class="title">
<a name="boost_numeric_odeint.odeint_in_detail.iterators_and_ranges.times_time_iterator"></a><a class="link" href="iterators_and_ranges.html#boost_numeric_odeint.odeint_in_detail.iterators_and_ranges.times_time_iterator" title="times_time_iterator">times_time_iterator</a>
</h4></div></div></div>
<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; ">
<li class="listitem">
Definition: <code class="computeroutput"><span class="identifier">times_time_iterator</span><span class="special"><</span> <span class="identifier">Stepper</span>
<span class="special">,</span> <span class="identifier">System</span>
<span class="special">,</span> <span class="identifier">State</span>
<span class="special">,</span> <span class="identifier">TimeIterator</span><span class="special">></span></code>
</li>
<li class="listitem">
<code class="computeroutput"><span class="identifier">value_type</span></code> is <code class="computeroutput"><span class="identifier">std</span><span class="special">::</span><span class="identifier">pair</span><span class="special"><</span>
<span class="identifier">State</span> <span class="special">,</span>
<span class="identifier">Stepper</span><span class="special">::</span><span class="identifier">time_type</span> <span class="special">></span></code>
</li>
<li class="listitem">
<code class="computeroutput"><span class="identifier">reference_type</span></code> is
<code class="computeroutput"><span class="identifier">std</span><span class="special">::</span><span class="identifier">pair</span><span class="special"><</span>
<span class="identifier">State</span> <span class="keyword">const</span><span class="special">&</span> <span class="special">,</span> <span class="identifier">Stepper</span><span class="special">::</span><span class="identifier">time_type</span> <span class="special">></span>
<span class="keyword">const</span><span class="special">&</span></code>
</li>
<li class="listitem">
Factory functions
<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: circle; ">
<li class="listitem">
<code class="computeroutput"><span class="identifier">make_times_time_iterator_begin</span><span class="special">(</span> <span class="identifier">stepper</span>
<span class="special">,</span> <span class="identifier">system</span>
<span class="special">,</span> <span class="identifier">state</span>
<span class="special">,</span> <span class="identifier">t_start</span>
<span class="special">,</span> <span class="identifier">t_end</span>
<span class="special">,</span> <span class="identifier">dt</span>
<span class="special">)</span></code>
</li>
<li class="listitem">
<code class="computeroutput"><span class="identifier">make_times_time_step_iterator_end</span><span class="special">(</span> <span class="identifier">stepper</span>
<span class="special">,</span> <span class="identifier">system</span>
<span class="special">,</span> <span class="identifier">state</span>
<span class="special">)</span></code>
</li>
<li class="listitem">
<code class="computeroutput"><span class="identifier">make_times_time_range</span><span class="special">(</span> <span class="identifier">stepper</span>
<span class="special">,</span> <span class="identifier">system</span>
<span class="special">,</span> <span class="identifier">state</span>
<span class="special">,</span> <span class="identifier">t_start</span>
<span class="special">,</span> <span class="identifier">t_end</span>
<span class="special">,</span> <span class="identifier">dt</span>
<span class="special">)</span></code>
</li>
</ul></div>
</li>
<li class="listitem">
This stepper works with all steppers fulfilling the Stepper concept,
the ControlledStepper concept or the DenseOutputStepper concept.
</li>
<li class="listitem">
This stepper updates the value of <code class="computeroutput"><span class="identifier">state</span></code>.
The value of <code class="computeroutput"><span class="identifier">state</span></code>
is the current state of the ODE during the iteration.
</li>
</ul></div>
</div>
</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 Karsten Ahnert and Mario Mulansky<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="integrate_functions.html"><img src="../../../../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../odeint_in_detail.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="state_types__algebras_and_operations.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/numeric/odeint/doc/html/boost_numeric_odeint/odeint_in_detail/iterators_and_ranges.html | HTML | agpl-3.0 | 59,447 |
<?php
if(!defined('sugarEntry') || !sugarEntry) die('Not A Valid Entry Point');
/*********************************************************************************
* SugarCRM Community Edition is a customer relationship management program developed by
* SugarCRM, Inc. Copyright (C) 2004-2012 SugarCRM 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 SUGARCRM, SUGARCRM 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 SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
* SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.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
* SugarCRM" logo. If the display of the logo is not reasonably feasible for
* technical reasons, the Appropriate Legal Notices must display the words
* "Powered by SugarCRM".
********************************************************************************/
function additionalDetailsMeeting($fields) {
static $mod_strings;
if(empty($mod_strings)) {
global $current_language;
$mod_strings = return_module_language($current_language, 'Meetings');
}
$overlib_string = '';
//Modify by jchi 6/27/2008 1515pm china time , bug 20626.
if(!empty($fields['DATE_START']))
$overlib_string .= '<b>'. $mod_strings['LBL_DATE_TIME'] . '</b> ' . $fields['DATE_START'] . ' <br>';
if(isset($fields['DURATION_HOURS']) || isset($fields['DURATION_MINUTES'])) {
$overlib_string .= '<b>'. $mod_strings['LBL_DURATION'] . '</b> ';
if(isset($fields['DURATION_HOURS'])) {
$overlib_string .= $fields['DURATION_HOURS'] . $mod_strings['LBL_HOURS_ABBREV'] . ' ';
}
if(isset($fields['DURATION_MINUTES'])) {
$overlib_string .= $fields['DURATION_MINUTES'] . $mod_strings['LBL_MINSS_ABBREV'];
}
$overlib_string .= '<br>';
}
if (!empty($fields['PARENT_ID']))
{
$overlib_string .= "<b>". $mod_strings['LBL_RELATED_TO'] . "</b> ".
"<a href='index.php?module=".$fields['PARENT_TYPE']."&action=DetailView&record=".$fields['PARENT_ID']."'>".
$fields['PARENT_NAME'] . "</a>";
$overlib_string .= '<br>';
}
if(!empty($fields['DESCRIPTION'])) {
$overlib_string .= '<b>'. $mod_strings['LBL_DESCRIPTION'] . '</b> ' . substr($fields['DESCRIPTION'], 0, 300);
if(strlen($fields['DESCRIPTION']) > 300) $overlib_string .= '...';
$overlib_string .= '<br>';
}
$editLink = "index.php?action=EditView&module=Meetings&record={$fields['ID']}";
$viewLink = "index.php?action=DetailView&module=Meetings&record={$fields['ID']}";
return array('fieldToAddTo' => 'NAME',
'string' => $overlib_string,
'editLink' => $editLink,
'viewLink' => $viewLink);
}
?>
| KadJ/amazon_sugar | upload/upload/upgrades/patch/SugarCE-Upgrade-6.5.x-to-6.5.9-restore/modules/Meetings/metadata/additionalDetails.php | PHP | agpl-3.0 | 3,933 |
# Contributor Code of Conduct
As contributors and maintainers of this project, and in the interest of
fostering an open and welcoming community, we pledge to respect all people who
contribute through reporting issues, posting feature requests, updating
documentation, submitting pull requests or patches, and other activities.
We are committed to making participation in this project a harassment-free
experience for everyone, regardless of level of experience, gender, gender
identity and expression, sexual orientation, disability, personal appearance,
body size, race, ethnicity, age, religion, or nationality.
Examples of unacceptable behavior by participants include:
* The use of sexualized language or imagery
* Personal attacks
* Trolling or insulting/derogatory comments
* Public or private harassment
* Publishing other's private information, such as physical or electronic
addresses, without explicit permission
* Other unethical or unprofessional conduct
Project maintainers have the right and responsibility to remove, edit, or
reject comments, commits, code, wiki edits, issues, and other contributions
that are not aligned to this Code of Conduct, or to ban temporarily or
permanently any contributor for other behaviors that they deem inappropriate,
threatening, offensive, or harmful.
By adopting this Code of Conduct, project maintainers commit themselves to
fairly and consistently applying these principles to every aspect of managing
this project. Project maintainers who do not follow or enforce the Code of
Conduct may be permanently removed from the project team.
This Code of Conduct applies both within project spaces and in public spaces
when an individual is representing the project or its community.
Instances of abusive, harassing, or otherwise unacceptable behavior may be
reported by contacting a project maintainer at <kytrinyx@exercism.io>. All
complaints will be reviewed and investigated and will result in a response that
is deemed necessary and appropriate to the circumstances. Maintainers are
obligated to maintain confidentiality with regard to the reporter of an
incident.
This Code of Conduct is adapted from the [Contributor Covenant][homepage],
version 1.3.0, available at
[http://contributor-covenant.org/version/1/3/0/][version]
[homepage]: http://contributor-covenant.org
[version]: http://contributor-covenant.org/version/1/3/0/
| nathanbwright/exercism.io | CODE_OF_CONDUCT.md | Markdown | agpl-3.0 | 2,392 |
/*
** I/O library.
** Copyright (C) 2005-2017 Mike Pall. See Copyright Notice in luajit.h
**
** Major portions taken verbatim or adapted from the Lua interpreter.
** Copyright (C) 1994-2011 Lua.org, PUC-Rio. See Copyright Notice in lua.h
*/
#include <errno.h>
#include <stdio.h>
#define lib_io_c
#define LUA_LIB
#include "lua.h"
#include "lauxlib.h"
#include "lualib.h"
#include "lj_obj.h"
#include "lj_gc.h"
#include "lj_err.h"
#include "lj_str.h"
#include "lj_state.h"
#include "lj_ff.h"
#include "lj_lib.h"
/* Userdata payload for I/O file. */
typedef struct IOFileUD {
FILE *fp; /* File handle. */
uint32_t type; /* File type. */
} IOFileUD;
#define IOFILE_TYPE_FILE 0 /* Regular file. */
#define IOFILE_TYPE_PIPE 1 /* Pipe. */
#define IOFILE_TYPE_STDF 2 /* Standard file handle. */
#define IOFILE_TYPE_MASK 3
#define IOFILE_FLAG_CLOSE 4 /* Close after io.lines() iterator. */
#define IOSTDF_UD(L, id) (&gcref(G(L)->gcroot[(id)])->ud)
#define IOSTDF_IOF(L, id) ((IOFileUD *)uddata(IOSTDF_UD(L, (id))))
/* -- Open/close helpers -------------------------------------------------- */
static IOFileUD *io_tofilep(lua_State *L)
{
if (!(L->base < L->top && tvisudata(L->base) &&
udataV(L->base)->udtype == UDTYPE_IO_FILE))
lj_err_argtype(L, 1, "FILE*");
return (IOFileUD *)uddata(udataV(L->base));
}
static IOFileUD *io_tofile(lua_State *L)
{
IOFileUD *iof = io_tofilep(L);
if (iof->fp == NULL)
lj_err_caller(L, LJ_ERR_IOCLFL);
return iof;
}
static FILE *io_stdfile(lua_State *L, ptrdiff_t id)
{
IOFileUD *iof = IOSTDF_IOF(L, id);
if (iof->fp == NULL)
lj_err_caller(L, LJ_ERR_IOSTDCL);
return iof->fp;
}
static IOFileUD *io_file_new(lua_State *L)
{
IOFileUD *iof = (IOFileUD *)lua_newuserdata(L, sizeof(IOFileUD));
GCudata *ud = udataV(L->top-1);
ud->udtype = UDTYPE_IO_FILE;
/* NOBARRIER: The GCudata is new (marked white). */
setgcrefr(ud->metatable, curr_func(L)->c.env);
iof->fp = NULL;
iof->type = IOFILE_TYPE_FILE;
return iof;
}
static IOFileUD *io_file_open(lua_State *L, const char *mode)
{
const char *fname = strdata(lj_lib_checkstr(L, 1));
IOFileUD *iof = io_file_new(L);
iof->fp = fopen(fname, mode);
if (iof->fp == NULL)
luaL_argerror(L, 1, lj_str_pushf(L, "%s: %s", fname, strerror(errno)));
return iof;
}
static int io_file_close(lua_State *L, IOFileUD *iof)
{
int ok;
if ((iof->type & IOFILE_TYPE_MASK) == IOFILE_TYPE_FILE) {
ok = (fclose(iof->fp) == 0);
} else if ((iof->type & IOFILE_TYPE_MASK) == IOFILE_TYPE_PIPE) {
int stat = -1;
#if LJ_TARGET_POSIX
stat = pclose(iof->fp);
#elif LJ_TARGET_WINDOWS
stat = _pclose(iof->fp);
#else
lua_assert(0);
return 0;
#endif
#if LJ_52
iof->fp = NULL;
return luaL_execresult(L, stat);
#else
ok = (stat != -1);
#endif
} else {
lua_assert((iof->type & IOFILE_TYPE_MASK) == IOFILE_TYPE_STDF);
setnilV(L->top++);
lua_pushliteral(L, "cannot close standard file");
return 2;
}
iof->fp = NULL;
return luaL_fileresult(L, ok, NULL);
}
/* -- Read/write helpers -------------------------------------------------- */
static int io_file_readnum(lua_State *L, FILE *fp)
{
lua_Number d;
if (fscanf(fp, LUA_NUMBER_SCAN, &d) == 1) {
if (LJ_DUALNUM) {
int32_t i = lj_num2int(d);
if (d == (lua_Number)i && !tvismzero((cTValue *)&d)) {
setintV(L->top++, i);
return 1;
}
}
setnumV(L->top++, d);
return 1;
} else {
setnilV(L->top++);
return 0;
}
}
static int io_file_readline(lua_State *L, FILE *fp, MSize chop)
{
MSize m = LUAL_BUFFERSIZE, n = 0, ok = 0;
char *buf;
for (;;) {
buf = lj_str_needbuf(L, &G(L)->tmpbuf, m);
if (fgets(buf+n, m-n, fp) == NULL) break;
n += (MSize)strlen(buf+n);
ok |= n;
if (n && buf[n-1] == '\n') { n -= chop; break; }
if (n >= m - 64) m += m;
}
setstrV(L, L->top++, lj_str_new(L, buf, (size_t)n));
lj_gc_check(L);
return (int)ok;
}
static void io_file_readall(lua_State *L, FILE *fp)
{
MSize m, n;
for (m = LUAL_BUFFERSIZE, n = 0; ; m += m) {
char *buf = lj_str_needbuf(L, &G(L)->tmpbuf, m);
n += (MSize)fread(buf+n, 1, m-n, fp);
if (n != m) {
setstrV(L, L->top++, lj_str_new(L, buf, (size_t)n));
lj_gc_check(L);
return;
}
}
}
static int io_file_readlen(lua_State *L, FILE *fp, MSize m)
{
if (m) {
char *buf = lj_str_needbuf(L, &G(L)->tmpbuf, m);
MSize n = (MSize)fread(buf, 1, m, fp);
setstrV(L, L->top++, lj_str_new(L, buf, (size_t)n));
lj_gc_check(L);
return (n > 0 || m == 0);
} else {
int c = getc(fp);
ungetc(c, fp);
setstrV(L, L->top++, &G(L)->strempty);
return (c != EOF);
}
}
static int io_file_read(lua_State *L, FILE *fp, int start)
{
int ok, n, nargs = (int)(L->top - L->base) - start;
clearerr(fp);
if (nargs == 0) {
ok = io_file_readline(L, fp, 1);
n = start+1; /* Return 1 result. */
} else {
/* The results plus the buffers go on top of the args. */
luaL_checkstack(L, nargs+LUA_MINSTACK, "too many arguments");
ok = 1;
for (n = start; nargs-- && ok; n++) {
if (tvisstr(L->base+n)) {
const char *p = strVdata(L->base+n);
if (p[0] != '*')
lj_err_arg(L, n+1, LJ_ERR_INVOPT);
if (p[1] == 'n')
ok = io_file_readnum(L, fp);
else if ((p[1] & ~0x20) == 'L')
ok = io_file_readline(L, fp, (p[1] == 'l'));
else if (p[1] == 'a')
io_file_readall(L, fp);
else
lj_err_arg(L, n+1, LJ_ERR_INVFMT);
} else if (tvisnumber(L->base+n)) {
ok = io_file_readlen(L, fp, (MSize)lj_lib_checkint(L, n+1));
} else {
lj_err_arg(L, n+1, LJ_ERR_INVOPT);
}
}
}
if (ferror(fp))
return luaL_fileresult(L, 0, NULL);
if (!ok)
setnilV(L->top-1); /* Replace last result with nil. */
return n - start;
}
static int io_file_write(lua_State *L, FILE *fp, int start)
{
cTValue *tv;
int status = 1;
for (tv = L->base+start; tv < L->top; tv++) {
if (tvisstr(tv)) {
MSize len = strV(tv)->len;
status = status && (fwrite(strVdata(tv), 1, len, fp) == len);
} else if (tvisint(tv)) {
char buf[LJ_STR_INTBUF];
char *p = lj_str_bufint(buf, intV(tv));
size_t len = (size_t)(buf+LJ_STR_INTBUF-p);
status = status && (fwrite(p, 1, len, fp) == len);
} else if (tvisnum(tv)) {
status = status && (fprintf(fp, LUA_NUMBER_FMT, numV(tv)) > 0);
} else {
lj_err_argt(L, (int)(tv - L->base) + 1, LUA_TSTRING);
}
}
if (LJ_52 && status) {
L->top = L->base+1;
if (start == 0)
setudataV(L, L->base, IOSTDF_UD(L, GCROOT_IO_OUTPUT));
return 1;
}
return luaL_fileresult(L, status, NULL);
}
static int io_file_iter(lua_State *L)
{
GCfunc *fn = curr_func(L);
IOFileUD *iof = uddata(udataV(&fn->c.upvalue[0]));
int n = fn->c.nupvalues - 1;
if (iof->fp == NULL)
lj_err_caller(L, LJ_ERR_IOCLFL);
L->top = L->base;
if (n) { /* Copy upvalues with options to stack. */
if (n > LUAI_MAXCSTACK)
lj_err_caller(L, LJ_ERR_STKOV);
lj_state_checkstack(L, (MSize)n);
memcpy(L->top, &fn->c.upvalue[1], n*sizeof(TValue));
L->top += n;
}
n = io_file_read(L, iof->fp, 0);
if (ferror(iof->fp))
lj_err_callermsg(L, strVdata(L->top-2));
if (tvisnil(L->base) && (iof->type & IOFILE_FLAG_CLOSE)) {
io_file_close(L, iof); /* Return values are ignored. */
return 0;
}
return n;
}
static int io_file_lines(lua_State *L)
{
int n = (int)(L->top - L->base);
if (n > LJ_MAX_UPVAL)
lj_err_caller(L, LJ_ERR_UNPACK);
lua_pushcclosure(L, io_file_iter, n);
return 1;
}
/* -- I/O file methods ---------------------------------------------------- */
#define LJLIB_MODULE_io_method
LJLIB_CF(io_method_close)
{
IOFileUD *iof = L->base < L->top ? io_tofile(L) :
IOSTDF_IOF(L, GCROOT_IO_OUTPUT);
return io_file_close(L, iof);
}
LJLIB_CF(io_method_read)
{
return io_file_read(L, io_tofile(L)->fp, 1);
}
LJLIB_CF(io_method_write) LJLIB_REC(io_write 0)
{
return io_file_write(L, io_tofile(L)->fp, 1);
}
LJLIB_CF(io_method_flush) LJLIB_REC(io_flush 0)
{
return luaL_fileresult(L, fflush(io_tofile(L)->fp) == 0, NULL);
}
LJLIB_CF(io_method_seek)
{
FILE *fp = io_tofile(L)->fp;
int opt = lj_lib_checkopt(L, 2, 1, "\3set\3cur\3end");
int64_t ofs = 0;
cTValue *o;
int res;
if (opt == 0) opt = SEEK_SET;
else if (opt == 1) opt = SEEK_CUR;
else if (opt == 2) opt = SEEK_END;
o = L->base+2;
if (o < L->top) {
if (tvisint(o))
ofs = (int64_t)intV(o);
else if (tvisnum(o))
ofs = (int64_t)numV(o);
else if (!tvisnil(o))
lj_err_argt(L, 3, LUA_TNUMBER);
}
#if LJ_TARGET_POSIX
res = fseeko(fp, ofs, opt);
#elif _MSC_VER >= 1400
res = _fseeki64(fp, ofs, opt);
#elif defined(__MINGW32__)
res = fseeko64(fp, ofs, opt);
#else
res = fseek(fp, (long)ofs, opt);
#endif
if (res)
return luaL_fileresult(L, 0, NULL);
#if LJ_TARGET_POSIX
ofs = ftello(fp);
#elif _MSC_VER >= 1400
ofs = _ftelli64(fp);
#elif defined(__MINGW32__)
ofs = ftello64(fp);
#else
ofs = (int64_t)ftell(fp);
#endif
setint64V(L->top-1, ofs);
return 1;
}
LJLIB_CF(io_method_setvbuf)
{
FILE *fp = io_tofile(L)->fp;
int opt = lj_lib_checkopt(L, 2, -1, "\4full\4line\2no");
size_t sz = (size_t)lj_lib_optint(L, 3, LUAL_BUFFERSIZE);
if (opt == 0) opt = _IOFBF;
else if (opt == 1) opt = _IOLBF;
else if (opt == 2) opt = _IONBF;
return luaL_fileresult(L, setvbuf(fp, NULL, opt, sz) == 0, NULL);
}
LJLIB_CF(io_method_lines)
{
io_tofile(L);
return io_file_lines(L);
}
LJLIB_CF(io_method___gc)
{
IOFileUD *iof = io_tofilep(L);
if (iof->fp != NULL && (iof->type & IOFILE_TYPE_MASK) != IOFILE_TYPE_STDF)
io_file_close(L, iof);
return 0;
}
LJLIB_CF(io_method___tostring)
{
IOFileUD *iof = io_tofilep(L);
if (iof->fp != NULL)
lua_pushfstring(L, "file (%p)", iof->fp);
else
lua_pushliteral(L, "file (closed)");
return 1;
}
LJLIB_PUSH(top-1) LJLIB_SET(__index)
#include "lj_libdef.h"
/* -- I/O library functions ----------------------------------------------- */
#define LJLIB_MODULE_io
LJLIB_PUSH(top-2) LJLIB_SET(!) /* Set environment. */
LJLIB_CF(io_open)
{
const char *fname = strdata(lj_lib_checkstr(L, 1));
GCstr *s = lj_lib_optstr(L, 2);
const char *mode = s ? strdata(s) : "r";
IOFileUD *iof = io_file_new(L);
iof->fp = fopen(fname, mode);
return iof->fp != NULL ? 1 : luaL_fileresult(L, 0, fname);
}
LJLIB_CF(io_popen)
{
#if LJ_TARGET_POSIX || LJ_TARGET_WINDOWS
const char *fname = strdata(lj_lib_checkstr(L, 1));
GCstr *s = lj_lib_optstr(L, 2);
const char *mode = s ? strdata(s) : "r";
IOFileUD *iof = io_file_new(L);
iof->type = IOFILE_TYPE_PIPE;
#if LJ_TARGET_POSIX
fflush(NULL);
iof->fp = popen(fname, mode);
#else
iof->fp = _popen(fname, mode);
#endif
return iof->fp != NULL ? 1 : luaL_fileresult(L, 0, fname);
#else
return luaL_error(L, LUA_QL("popen") " not supported");
#endif
}
LJLIB_CF(io_tmpfile)
{
IOFileUD *iof = io_file_new(L);
#if LJ_TARGET_PS3 || LJ_TARGET_PS4 || LJ_TARGET_PSVITA
iof->fp = NULL; errno = ENOSYS;
#else
iof->fp = tmpfile();
#endif
return iof->fp != NULL ? 1 : luaL_fileresult(L, 0, NULL);
}
LJLIB_CF(io_close)
{
return lj_cf_io_method_close(L);
}
LJLIB_CF(io_read)
{
return io_file_read(L, io_stdfile(L, GCROOT_IO_INPUT), 0);
}
LJLIB_CF(io_write) LJLIB_REC(io_write GCROOT_IO_OUTPUT)
{
return io_file_write(L, io_stdfile(L, GCROOT_IO_OUTPUT), 0);
}
LJLIB_CF(io_flush) LJLIB_REC(io_flush GCROOT_IO_OUTPUT)
{
return luaL_fileresult(L, fflush(io_stdfile(L, GCROOT_IO_OUTPUT)) == 0, NULL);
}
static int io_std_getset(lua_State *L, ptrdiff_t id, const char *mode)
{
if (L->base < L->top && !tvisnil(L->base)) {
if (tvisudata(L->base)) {
io_tofile(L);
L->top = L->base+1;
} else {
io_file_open(L, mode);
}
/* NOBARRIER: The standard I/O handles are GC roots. */
setgcref(G(L)->gcroot[id], gcV(L->top-1));
} else {
setudataV(L, L->top++, IOSTDF_UD(L, id));
}
return 1;
}
LJLIB_CF(io_input)
{
return io_std_getset(L, GCROOT_IO_INPUT, "r");
}
LJLIB_CF(io_output)
{
return io_std_getset(L, GCROOT_IO_OUTPUT, "w");
}
LJLIB_CF(io_lines)
{
if (L->base == L->top) setnilV(L->top++);
if (!tvisnil(L->base)) { /* io.lines(fname) */
IOFileUD *iof = io_file_open(L, "r");
iof->type = IOFILE_TYPE_FILE|IOFILE_FLAG_CLOSE;
L->top--;
setudataV(L, L->base, udataV(L->top));
} else { /* io.lines() iterates over stdin. */
setudataV(L, L->base, IOSTDF_UD(L, GCROOT_IO_INPUT));
}
return io_file_lines(L);
}
LJLIB_CF(io_type)
{
cTValue *o = lj_lib_checkany(L, 1);
if (!(tvisudata(o) && udataV(o)->udtype == UDTYPE_IO_FILE))
setnilV(L->top++);
else if (((IOFileUD *)uddata(udataV(o)))->fp != NULL)
lua_pushliteral(L, "file");
else
lua_pushliteral(L, "closed file");
return 1;
}
#include "lj_libdef.h"
/* ------------------------------------------------------------------------ */
static GCobj *io_std_new(lua_State *L, FILE *fp, const char *name)
{
IOFileUD *iof = (IOFileUD *)lua_newuserdata(L, sizeof(IOFileUD));
GCudata *ud = udataV(L->top-1);
ud->udtype = UDTYPE_IO_FILE;
/* NOBARRIER: The GCudata is new (marked white). */
setgcref(ud->metatable, gcV(L->top-3));
iof->fp = fp;
iof->type = IOFILE_TYPE_STDF;
lua_setfield(L, -2, name);
return obj2gco(ud);
}
LUALIB_API int luaopen_io(lua_State *L)
{
LJ_LIB_REG(L, NULL, io_method);
copyTV(L, L->top, L->top-1); L->top++;
lua_setfield(L, LUA_REGISTRYINDEX, LUA_FILEHANDLE);
LJ_LIB_REG(L, LUA_IOLIBNAME, io);
setgcref(G(L)->gcroot[GCROOT_IO_INPUT], io_std_new(L, stdin, "stdin"));
setgcref(G(L)->gcroot[GCROOT_IO_OUTPUT], io_std_new(L, stdout, "stdout"));
io_std_new(L, stderr, "stderr");
return 1;
}
| team-parasol/parasol | src/fluid/luajit-2.0.5/src/lib_io.c | C | lgpl-2.1 | 13,724 |
/*
* Copyright (C) 2014 Loci Controls Inc.
* 2018 HAW Hamburg
*
* This file is subject to the terms and conditions of the GNU Lesser
* General Public License v2.1. See the file LICENSE in the top level
* directory for more details.
*/
/**
* @defgroup cpu_cc2538_gptimer CC2538 General Purpose Timer
* @ingroup cpu_cc2538_regs
* @{
*
* @file
* @brief CC2538 General Purpose Timer (GPTIMER) driver
*
* @author Ian Martin <ian@locicontrols.com>
* @author Sebastian Meiling <s@mlng.net>
*/
#ifndef CC2538_GPTIMER_H
#define CC2538_GPTIMER_H
#include <stdint.h>
#include "cc2538.h"
#ifdef __cplusplus
extern "C" {
#endif
/**
* @brief Timer modes
*/
enum {
GPTIMER_ONE_SHOT_MODE = 1, /**< GPTIMER one-shot mode */
GPTIMER_PERIODIC_MODE = 2, /**< GPTIMER periodic mode */
GPTIMER_CAPTURE_MODE = 3, /**< GPTIMER capture mode */
};
/**
* @brief Timer width configuration
*/
enum {
GPTMCFG_32_BIT_TIMER = 0, /**< 32-bit timer configuration */
GPTMCFG_32_BIT_REAL_TIME_CLOCK = 1, /**< 32-bit real-time clock */
GPTMCFG_16_BIT_TIMER = 4, /**< 16-bit timer configuration */
};
/**
* @brief GPTIMER component registers
*/
typedef struct {
cc2538_reg_t CFG; /**< GPTIMER Configuration */
cc2538_reg_t TAMR; /**< GPTIMER Timer A mode */
cc2538_reg_t TBMR; /**< GPTIMER Timer B mode */
cc2538_reg_t CTL; /**< GPTIMER Control */
cc2538_reg_t SYNC; /**< GPTIMER Synchronize */
cc2538_reg_t RESERVED2; /**< Reserved word */
cc2538_reg_t IMR; /**< GPTIMER Interrupt Mask */
cc2538_reg_t RIS; /**< GPTIMER Raw Interrupt Status */
cc2538_reg_t MIS; /**< GPTIMER Masked Interrupt Status */
cc2538_reg_t ICR; /**< GPTIMER Interrupt Clear */
cc2538_reg_t TAILR; /**< GPTIMER Timer A Interval Load */
cc2538_reg_t TBILR; /**< GPTIMER Timer B Interval Load */
cc2538_reg_t TAMATCHR; /**< GPTIMER Timer A Match */
cc2538_reg_t TBMATCHR; /**< GPTIMER Timer B Match */
cc2538_reg_t TAPR; /**< GPTIMER Timer A Prescale Register */
cc2538_reg_t TBPR; /**< GPTIMER Timer B Prescale Register */
cc2538_reg_t TAPMR; /**< GPTIMER Timer A Prescale Match Register */
cc2538_reg_t TBPMR; /**< GPTIMER Timer B Prescale Match Register */
cc2538_reg_t TAR; /**< GPTIMER Timer A */
cc2538_reg_t TBR; /**< GPTIMER Timer B */
cc2538_reg_t TAV; /**< GPTIMER Timer A Value */
cc2538_reg_t TBV; /**< GPTIMER Timer B Value */
cc2538_reg_t RESERVED3; /**< Reserved word */
cc2538_reg_t TAPS; /**< GPTIMER Timer A Prescale Snapshot */
cc2538_reg_t TBPS; /**< GPTIMER Timer B Prescale Snapshot */
cc2538_reg_t TAPV; /**< GPTIMER Timer A Prescale Value */
cc2538_reg_t TBPV; /**< GPTIMER Timer B Prescale Value */
cc2538_reg_t RESERVED[981]; /**< Reserved */
cc2538_reg_t PP; /**< GPTIMER Peripheral Properties */
cc2538_reg_t RESERVED4[15]; /**< Reserved */
} cc2538_gptimer_t;
#ifdef __cplusplus
} /* end extern "C" */
#endif
#endif /* CC2538_GPTIMER_H */
/** @} */
| aabadie/RIOT | cpu/cc2538/include/cc2538_gptimer.h | C | lgpl-2.1 | 3,721 |
/*
* Copyright (C) 2016 Freie Universität Berlin
*
* This file is subject to the terms and conditions of the GNU Lesser
* General Public License v2.1. See the file LICENSE in the top level
* directory for more details.
*/
/**
* @defgroup cpu_nrf52 Nordic nRF52 MCU
* @ingroup cpu
* @brief Nordic nRF52 family of CPUs
* @{
*
* @file
* @brief nRF52 specific CPU configuration
*
* @author Hauke Petersen <hauke.petersen@fu-berlin.de>
*
*/
#ifndef CPU_CONF_H
#define CPU_CONF_H
#include "cpu_conf_common.h"
#ifdef CPU_MODEL_NRF52832XXAA
#include "vendor/nrf52.h"
#include "vendor/nrf52_bitfields.h"
#elif defined(CPU_MODEL_NRF52840XXAA)
#include "vendor/nrf52840.h"
#include "vendor/nrf52840_bitfields.h"
#else
#error "The CPU_MODEL of your board is currently not supported"
#endif
#ifdef __cplusplus
extern "C" {
#endif
/**
* @name ARM Cortex-M specific CPU configuration
* @{
*/
#define CPU_DEFAULT_IRQ_PRIO (2U)
#define CPU_FLASH_BASE (0x00000000)
#ifdef CPU_MODEL_NRF52832XXAA
#define CPU_IRQ_NUMOF (38U)
#elif CPU_MODEL_NRF52840XXAA
#define CPU_IRQ_NUMOF (46U)
#endif
/** @} */
/**
* @brief Flash page configuration
* @{
*/
#define FLASHPAGE_SIZE (4096U)
#if defined(CPU_MODEL_NRF52832XXAA)
#define FLASHPAGE_NUMOF (128U)
#elif defined(CPU_MODEL_NRF52840XXAA)
#define FLASHPAGE_NUMOF (256U)
#endif
/* The minimum block size which can be written is 4B. However, the erase
* block is always FLASHPAGE_SIZE.
*/
#define FLASHPAGE_RAW_BLOCKSIZE (4U)
/* Writing should be always 4 bytes aligned */
#define FLASHPAGE_RAW_ALIGNMENT (4U)
/** @} */
/**
* @brief SoftDevice settings
* @{
*/
#ifdef SOFTDEVICE_PRESENT
#ifndef DONT_OVERRIDE_NVIC
#include "nrf_soc.h"
#undef NVIC_SetPriority
#define NVIC_SetPriority sd_nvic_SetPriority
#endif /* DONT_OVERRIDE_NVIC */
#endif /* SOFTDEVICE_PRESENT */
/** @} */
/**
* @brief Put the CPU in the low-power 'wait for event' state
*/
static inline void nrf52_sleep(void)
{
__SEV();
__WFE();
__asm("nop");
}
#ifdef __cplusplus
}
#endif
#endif /* CPU_CONF_H */
/** @} */
| yogo1212/RIOT | cpu/nrf52/include/cpu_conf.h | C | lgpl-2.1 | 2,224 |
/**
* Copyright (C) 2014 Martin Landsmann <Martin.Landsmann@HAW-Hamburg.de>
*
* This file is subject to the terms and conditions of the GNU Lesser
* General Public License v2.1. See the file LICENSE in the top level
* directory for more details.
*/
/**
* @ingroup net_fib
* @{
*
* @file
* @brief Functions to manage FIB entries
*
* @author Martin Landsmann <martin.landsmann@haw-hamburg.de>
* @author Oliver Hahm <oliver.hahm@inria.fr>
*
* @}
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <inttypes.h>
#include <errno.h>
#include "thread.h"
#include "mutex.h"
#include "msg.h"
#include "xtimer.h"
#include "timex.h"
#include "utlist.h"
#define ENABLE_DEBUG (0)
#include "debug.h"
#include "net/fib.h"
#include "net/fib/table.h"
#ifdef MODULE_IPV6_ADDR
#include "net/ipv6/addr.h"
static char addr_str[IPV6_ADDR_MAX_STR_LEN];
#endif
#ifdef MODULE_IPV6_ADDR
#define FIB_ADDR_PRINT_LEN 39
#else
#define FIB_ADDR_PRINT_LEN 32
#if FIB_ADDR_PRINT_LEN != (UNIVERSAL_ADDRESS_SIZE * 2)
#error "FIB_ADDR_PRINT_LEN MUST BE (UNIVERSAL_ADDRESS_SIZE * 2)"
#endif
#endif
#define FIB_ADDR_PRINT_LENS1(X) #X
#define FIB_ADDR_PRINT_LENS2(X) FIB_ADDR_PRINT_LENS1(X)
#define FIB_ADDR_PRINT_LENS FIB_ADDR_PRINT_LENS2(FIB_ADDR_PRINT_LEN)
/**
* @brief convert an offset given in ms to absolute time in time in us
* @param[in] ms the milliseconds to be converted
* @param[out] target the converted point in time
*/
static void fib_lifetime_to_absolute(uint32_t ms, uint64_t *target)
{
*target = xtimer_now_usec64() + (ms * US_PER_MS);
}
/**
* @brief returns pointer to the entry for the given destination address
*
* @param[in] table the FIB table to search in
* @param[in] dst the destination address
* @param[in] dst_size the destination address size
* @param[out] entry_arr the array to scribe the found match
* @param[in, out] entry_arr_size the number of entries provided by entry_arr (should be always 1)
* this value is overwritten with the actual found number
*
* @return 0 if we found a next-hop prefix
* 1 if we found the exact address next-hop
* -EHOSTUNREACH if no fitting next-hop is available
*/
static int fib_find_entry(fib_table_t *table, uint8_t *dst, size_t dst_size,
fib_entry_t **entry_arr, size_t *entry_arr_size) {
uint64_t now = xtimer_now_usec64();
size_t count = 0;
size_t prefix_size = 0;
size_t match_size = dst_size << 3;
int ret = -EHOSTUNREACH;
bool is_all_zeros_addr = true;
#if ENABLE_DEBUG
DEBUG("[fib_find_entry] dst =");
for (size_t i = 0; i < dst_size; i++) {
DEBUG(" %02x", dst[i]);
}
DEBUG("\n");
#endif
for (size_t i = 0; i < dst_size; ++i) {
if (dst[i] != 0) {
is_all_zeros_addr = false;
break;
}
}
for (size_t i = 0; i < table->size; ++i) {
/* autoinvalidate if the entry lifetime is not set to not expire */
if (table->data.entries[i].lifetime != FIB_LIFETIME_NO_EXPIRE) {
/* check if the lifetime expired */
if (table->data.entries[i].lifetime < now) {
/* remove this entry if its lifetime expired */
table->data.entries[i].lifetime = 0;
table->data.entries[i].global_flags = 0;
table->data.entries[i].next_hop_flags = 0;
table->data.entries[i].iface_id = KERNEL_PID_UNDEF;
if (table->data.entries[i].global != NULL) {
universal_address_rem(table->data.entries[i].global);
table->data.entries[i].global = NULL;
}
if (table->data.entries[i].next_hop != NULL) {
universal_address_rem(table->data.entries[i].next_hop);
table->data.entries[i].next_hop = NULL;
}
}
}
if ((prefix_size < (dst_size<<3)) && (table->data.entries[i].global != NULL)) {
int ret_comp = universal_address_compare(table->data.entries[i].global, dst, &match_size);
/* If we found an exact match */
if ((ret_comp == UNIVERSAL_ADDRESS_EQUAL)
|| (is_all_zeros_addr && (ret_comp == UNIVERSAL_ADDRESS_IS_ALL_ZERO_ADDRESS))) {
entry_arr[0] = &(table->data.entries[i]);
*entry_arr_size = 1;
/* we will not find a better one so we return */
return 1;
}
else {
/* we try to find the most fitting prefix */
if (ret_comp == UNIVERSAL_ADDRESS_MATCHING_PREFIX) {
if (table->data.entries[i].global_flags & FIB_FLAG_NET_PREFIX_MASK) {
/* we shift the most upper flag byte back to get the number of prefix bits */
size_t global_prefix_len = (table->data.entries[i].global_flags
& FIB_FLAG_NET_PREFIX_MASK) >> FIB_FLAG_NET_PREFIX_SHIFT;
if ((match_size >= global_prefix_len) &&
((prefix_size == 0) || (match_size > prefix_size))) {
entry_arr[0] = &(table->data.entries[i]);
/* we could find a better one so we move on */
ret = 0;
prefix_size = match_size;
count = 1;
}
}
}
else if (ret_comp == UNIVERSAL_ADDRESS_IS_ALL_ZERO_ADDRESS) {
/* we found the default gateway entry, e.g. ::/0 for IPv6
* and we keep it only if there is no better one
*/
if (prefix_size == 0) {
entry_arr[0] = &(table->data.entries[i]);
/* we could find a better one so we move on */
ret = 0;
count = 1;
}
}
match_size = dst_size<<3;
}
}
}
#if ENABLE_DEBUG
if (count > 0) {
DEBUG("[fib_find_entry] found prefix on interface %d:", entry_arr[0]->iface_id);
for (size_t i = 0; i < entry_arr[0]->global->address_size; i++) {
DEBUG(" %02x", entry_arr[0]->global->address[i]);
}
DEBUG("\n");
}
#endif
*entry_arr_size = count;
return ret;
}
/**
* @brief updates the next hop the lifetime and the interface id for a given entry
*
* @param[in] entry the entry to be updated
* @param[in] next_hop the next hop address to be updated
* @param[in] next_hop_size the next hop address size
* @param[in] next_hop_flags the next-hop address flags
* @param[in] lifetime the lifetime in ms
*
* @return 0 if the entry has been updated
* -ENOMEM if the entry cannot be updated due to insufficient RAM
*/
static int fib_upd_entry(fib_entry_t *entry, uint8_t *next_hop,
size_t next_hop_size, uint32_t next_hop_flags,
uint32_t lifetime)
{
universal_address_container_t *container = universal_address_add(next_hop, next_hop_size);
if (container == NULL) {
return -ENOMEM;
}
universal_address_rem(entry->next_hop);
entry->next_hop = container;
entry->next_hop_flags = next_hop_flags;
if (lifetime != (uint32_t)FIB_LIFETIME_NO_EXPIRE) {
fib_lifetime_to_absolute(lifetime, &entry->lifetime);
}
else {
entry->lifetime = FIB_LIFETIME_NO_EXPIRE;
}
return 0;
}
/**
* @brief creates a new FIB entry with the provided parameters
*
* @param[in] table the FIB table to create the entry in
* @param[in] iface_id the interface ID
* @param[in] dst the destination address
* @param[in] dst_size the destination address size
* @param[in] dst_flags the destination address flags
* @param[in] next_hop the next hop address
* @param[in] next_hop_size the next hop address size
* @param[in] next_hop_flags the next-hop address flags
* @param[in] lifetime the lifetime in ms
*
* @return 0 on success
* -ENOMEM if no new entry can be created
*/
static int fib_create_entry(fib_table_t *table, kernel_pid_t iface_id,
uint8_t *dst, size_t dst_size, uint32_t dst_flags,
uint8_t *next_hop, size_t next_hop_size, uint32_t
next_hop_flags, uint32_t lifetime)
{
for (size_t i = 0; i < table->size; ++i) {
if (table->data.entries[i].lifetime == 0) {
table->data.entries[i].global = universal_address_add(dst, dst_size);
if (table->data.entries[i].global != NULL) {
table->data.entries[i].global_flags = dst_flags;
table->data.entries[i].next_hop = universal_address_add(next_hop, next_hop_size);
table->data.entries[i].next_hop_flags = next_hop_flags;
}
if (table->data.entries[i].next_hop != NULL) {
/* everything worked fine */
table->data.entries[i].iface_id = iface_id;
if (lifetime != (uint32_t) FIB_LIFETIME_NO_EXPIRE) {
fib_lifetime_to_absolute(lifetime, &table->data.entries[i].lifetime);
}
else {
table->data.entries[i].lifetime = FIB_LIFETIME_NO_EXPIRE;
}
return 0;
}
}
}
return -ENOMEM;
}
/**
* @brief removes the given entry
*
* @param[in] entry the entry to be removed
*
* @return 0 on success
*/
static int fib_remove(fib_entry_t *entry)
{
if (entry->global != NULL) {
universal_address_rem(entry->global);
}
if (entry->next_hop) {
universal_address_rem(entry->next_hop);
}
entry->global = NULL;
entry->global_flags = 0;
entry->next_hop = NULL;
entry->next_hop_flags = 0;
entry->iface_id = KERNEL_PID_UNDEF;
entry->lifetime = 0;
return 0;
}
/**
* @brief signals (sends a message to) all registered routing protocols
* registered with a matching prefix (usually this should be only one).
* The receiver MUST copy the content, i.e. the address before reply.
*
* @param[in] table the fib instance to use
* @param[in] type the kind of signal
* @param[in] dat the data to send
* @param[in] dat_size the data size in bytes
* @param[in] dat_flags the data flags
*
* @return 0 on a new available entry,
* -ENOENT if no suiting entry is provided.
*/
static int fib_signal_rp(fib_table_t *table, uint16_t type, uint8_t *dat,
size_t dat_size, uint32_t dat_flags)
{
msg_t msg, reply;
rp_address_msg_t rp_addr_msg;
int ret = -ENOENT;
void *content = NULL;
if (type != FIB_MSG_RP_SIGNAL_SOURCE_ROUTE_CREATED) {
/* the passed data is an address */
rp_addr_msg.address = dat;
rp_addr_msg.address_size = dat_size;
rp_addr_msg.address_flags = dat_flags;
content = (void *)&rp_addr_msg;
}
else {
/* the passed data is a sr head
* dat_size and dat_flags are not used in this case
*/
content = (void *)dat;
}
msg.type = type;
msg.content.ptr = content;
for (size_t i = 0; i < FIB_MAX_REGISTERED_RP; ++i) {
if (table->notify_rp[i] != KERNEL_PID_UNDEF) {
DEBUG("[fib_signal_rp] send msg@: %p to pid[%d]: %d\n", \
msg.content.ptr, (int)i, (int)(table->notify_rp[i]));
/* do only signal a RP if its registered prefix matches */
if (type != FIB_MSG_RP_SIGNAL_SOURCE_ROUTE_CREATED) {
size_t dat_size_in_bits = dat_size<<3;
if (universal_address_compare(table->prefix_rp[i], dat,
&dat_size_in_bits) != -ENOENT) {
/* the receiver, i.e. the RP, MUST copy the content value.
* using the provided pointer after replying this message
* will lead to errors
*/
msg_send_receive(&msg, &reply, table->notify_rp[i]);
DEBUG("[fib_signal_rp] got reply.\n");
ret = 0;
}
}
else {
fib_sr_t *temp_sr = (fib_sr_t *)dat;
size_t dat_size_in_bits = temp_sr->sr_dest->address->address_size << 3;
if (universal_address_compare(table->prefix_rp[i],
temp_sr->sr_dest->address->address,
&dat_size_in_bits) != -ENOENT) {
/* the receiver, i.e. the RP, MUST copy the content value.
* using the provided pointer after replying this message
* will lead to errors
*/
msg_send_receive(&msg, &reply, table->notify_rp[i]);
DEBUG("[fib_signal_rp] got reply.\n");
ret = 0;
}
}
}
}
return ret;
}
int fib_add_entry(fib_table_t *table,
kernel_pid_t iface_id, uint8_t *dst, size_t dst_size,
uint32_t dst_flags, uint8_t *next_hop, size_t next_hop_size,
uint32_t next_hop_flags, uint32_t lifetime)
{
mutex_lock(&(table->mtx_access));
DEBUG("[fib_add_entry]\n");
size_t count = 1;
fib_entry_t *entry[count];
/* check if dst and next_hop are valid pointers */
if ((dst == NULL) || (next_hop == NULL)) {
mutex_unlock(&(table->mtx_access));
return -EFAULT;
}
int ret = fib_find_entry(table, dst, dst_size, &(entry[0]), &count);
if (ret == 1) {
/* we must take the according entry and update the values */
ret = fib_upd_entry(entry[0], next_hop, next_hop_size, next_hop_flags, lifetime);
}
else {
ret = fib_create_entry(table, iface_id, dst, dst_size, dst_flags,
next_hop, next_hop_size, next_hop_flags, lifetime);
}
mutex_unlock(&(table->mtx_access));
return ret;
}
int fib_update_entry(fib_table_t *table, uint8_t *dst, size_t dst_size,
uint8_t *next_hop, size_t next_hop_size,
uint32_t next_hop_flags, uint32_t lifetime)
{
mutex_lock(&(table->mtx_access));
DEBUG("[fib_update_entry]\n");
size_t count = 1;
fib_entry_t *entry[count];
int ret = -ENOMEM;
/* check if dst and next_hop are valid pointers */
if ((dst == NULL) || (next_hop == NULL)) {
mutex_unlock(&(table->mtx_access));
return -EFAULT;
}
if (fib_find_entry(table, dst, dst_size, &(entry[0]), &count) == 1) {
DEBUG("[fib_update_entry] found entry: %p\n", (void *)(entry[0]));
/* we must take the according entry and update the values */
ret = fib_upd_entry(entry[0], next_hop, next_hop_size, next_hop_flags, lifetime);
}
else {
/* we have ambiguous entries, i.e. count > 1
* this should never happen
*/
DEBUG("[fib_update_entry] ambiguous entries detected!!!\n");
}
mutex_unlock(&(table->mtx_access));
return ret;
}
void fib_remove_entry(fib_table_t *table, uint8_t *dst, size_t dst_size)
{
mutex_lock(&(table->mtx_access));
DEBUG("[fib_remove_entry]\n");
size_t count = 1;
fib_entry_t *entry[count];
int ret = fib_find_entry(table, dst, dst_size, &(entry[0]), &count);
if (ret == 1) {
/* we must take the according entry and update the values */
fib_remove(entry[0]);
}
else {
/* we have ambiguous entries, i.e. count > 1
* this should never happen
*/
DEBUG("[fib_update_entry] ambiguous entries detected!!!\n");
}
mutex_unlock(&(table->mtx_access));
}
void fib_flush(fib_table_t *table, kernel_pid_t interface)
{
mutex_lock(&(table->mtx_access));
DEBUG("[fib_flush]\n");
for (size_t i = 0; i < table->size; ++i) {
if ((interface == KERNEL_PID_UNDEF) ||
(interface == table->data.entries[i].iface_id)) {
fib_remove(&table->data.entries[i]);
}
}
mutex_unlock(&(table->mtx_access));
}
int fib_get_next_hop(fib_table_t *table, kernel_pid_t *iface_id,
uint8_t *next_hop, size_t *next_hop_size,
uint32_t *next_hop_flags, uint8_t *dst, size_t dst_size,
uint32_t dst_flags)
{
mutex_lock(&(table->mtx_access));
DEBUG("[fib_get_next_hop]\n");
size_t count = 1;
fib_entry_t *entry[count];
if ((iface_id == NULL)
|| (next_hop_size == NULL)
|| (next_hop_flags == NULL)) {
mutex_unlock(&(table->mtx_access));
return -EINVAL;
}
if ((dst == NULL) || (next_hop == NULL)) {
mutex_unlock(&(table->mtx_access));
return -EFAULT;
}
int ret = fib_find_entry(table, dst, dst_size, &(entry[0]), &count);
if (!(ret == 0 || ret == 1)) {
/* notify all responsible RPs for unknown next-hop for the destination address */
if (fib_signal_rp(table, FIB_MSG_RP_SIGNAL_UNREACHABLE_DESTINATION,
dst, dst_size, dst_flags) == 0) {
count = 1;
/* now lets see if the RRPs have found a valid next-hop */
ret = fib_find_entry(table, dst, dst_size, &(entry[0]), &count);
}
}
if (ret == 0 || ret == 1) {
uint8_t *address_ret = universal_address_get_address(entry[0]->next_hop,
next_hop, next_hop_size);
if (address_ret == NULL) {
mutex_unlock(&(table->mtx_access));
return -ENOBUFS;
}
}
else {
mutex_unlock(&(table->mtx_access));
return -EHOSTUNREACH;
}
*iface_id = entry[0]->iface_id;
*next_hop_flags = entry[0]->next_hop_flags;
mutex_unlock(&(table->mtx_access));
return 0;
}
int fib_get_destination_set(fib_table_t *table, uint8_t *prefix,
size_t prefix_size,
fib_destination_set_entry_t *dst_set,
size_t* dst_set_size)
{
mutex_lock(&(table->mtx_access));
int ret = -EHOSTUNREACH;
size_t found_entries = 0;
for (size_t i = 0; i < table->size; ++i) {
if ((table->data.entries[i].global != NULL) &&
(universal_address_compare_prefix(table->data.entries[i].global, prefix, prefix_size<<3) >= UNIVERSAL_ADDRESS_EQUAL)) {
if( (dst_set != NULL) && (found_entries < *dst_set_size) ) {
/* set the size to full byte usage */
dst_set[found_entries].dest_size = sizeof(dst_set[found_entries].dest);
universal_address_get_address(table->data.entries[i].global,
dst_set[found_entries].dest,
&dst_set[found_entries].dest_size);
}
found_entries++;
}
}
if (found_entries > *dst_set_size) {
ret = -ENOBUFS;
}
else if (found_entries > 0) {
ret = 0;
}
*dst_set_size = found_entries;
mutex_unlock(&(table->mtx_access));
return ret;
}
void fib_init(fib_table_t *table)
{
DEBUG("[fib_init] hello. Initializing some stuff.\n");
mutex_init(&(table->mtx_access));
mutex_lock(&(table->mtx_access));
for (size_t i = 0; i < FIB_MAX_REGISTERED_RP; ++i) {
table->notify_rp[i] = KERNEL_PID_UNDEF;
table->prefix_rp[i] = NULL;
}
table->notify_rp_pos = 0;
if (table->table_type == FIB_TABLE_TYPE_SR) {
memset(table->data.source_routes->headers, 0,
sizeof(fib_sr_t) * table->size);
memset(table->data.source_routes->entry_pool, 0,
sizeof(fib_sr_entry_t) * table->data.source_routes->entry_pool_size);
}
else {
memset(table->data.entries, 0, (table->size * sizeof(fib_entry_t)));
}
universal_address_init();
mutex_unlock(&(table->mtx_access));
}
void fib_deinit(fib_table_t *table)
{
DEBUG("[fib_deinit] hello. De-Initializing stuff.\n");
mutex_lock(&(table->mtx_access));
for (size_t i = 0; i < FIB_MAX_REGISTERED_RP; ++i) {
table->notify_rp[i] = KERNEL_PID_UNDEF;
table->prefix_rp[i] = NULL;
}
table->notify_rp_pos = 0;
if (table->table_type == FIB_TABLE_TYPE_SR) {
memset(table->data.source_routes->headers, 0,
sizeof(fib_sr_t) * table->size);
memset(table->data.source_routes->entry_pool, 0,
sizeof(fib_sr_entry_t) * table->data.source_routes->entry_pool_size);
}
else {
memset(table->data.entries, 0, (table->size * sizeof(fib_entry_t)));
}
universal_address_reset();
mutex_unlock(&(table->mtx_access));
}
int fib_register_rp(fib_table_t *table, uint8_t *prefix, size_t prefix_addr_type_size)
{
mutex_lock(&(table->mtx_access));
if (table->notify_rp_pos >= FIB_MAX_REGISTERED_RP) {
mutex_unlock(&(table->mtx_access));
return -ENOMEM;
}
if ((prefix == NULL) || (prefix_addr_type_size == 0)) {
mutex_unlock(&(table->mtx_access));
return -EINVAL;
}
if (table->notify_rp_pos < FIB_MAX_REGISTERED_RP) {
table->notify_rp[table->notify_rp_pos] = sched_active_pid;
universal_address_container_t *container = universal_address_add(prefix,
prefix_addr_type_size);
table->prefix_rp[table->notify_rp_pos] = container;
table->notify_rp_pos++;
}
mutex_unlock(&(table->mtx_access));
return 0;
}
int fib_get_num_used_entries(fib_table_t *table)
{
mutex_lock(&(table->mtx_access));
size_t used_entries = 0;
for (size_t i = 0; i < table->size; ++i) {
used_entries += (size_t)(table->data.entries[i].global != NULL);
}
mutex_unlock(&(table->mtx_access));
return used_entries;
}
/* source route handling */
int fib_sr_create(fib_table_t *table, fib_sr_t **fib_sr, kernel_pid_t sr_iface_id,
uint32_t sr_flags, uint32_t sr_lifetime)
{
mutex_lock(&(table->mtx_access));
if ((fib_sr == NULL) || (sr_lifetime == 0)) {
mutex_unlock(&(table->mtx_access));
return -EFAULT;
}
for (size_t i = 0; i < table->size; ++i) {
if (table->data.source_routes->headers[i].sr_lifetime == 0) {
table->data.source_routes->headers[i].sr_iface_id = sr_iface_id;
table->data.source_routes->headers[i].sr_flags = sr_flags;
table->data.source_routes->headers[i].sr_path = NULL;
table->data.source_routes->headers[i].sr_dest = NULL;
if (sr_lifetime < (uint32_t)FIB_LIFETIME_NO_EXPIRE) {
fib_lifetime_to_absolute(sr_lifetime,
&table->data.source_routes->headers[i].sr_lifetime);
}
else {
table->data.source_routes->headers[i].sr_lifetime = FIB_LIFETIME_NO_EXPIRE;
}
*fib_sr = &table->data.source_routes->headers[i];
mutex_unlock(&(table->mtx_access));
return 0;
}
}
mutex_unlock(&(table->mtx_access));
return -ENOBUFS;
}
/**
* @brief Internal function:
* checks the lifetime and removes the entry in case it expired
*/
static int fib_sr_check_lifetime(fib_sr_t *fib_sr)
{
uint64_t tm = fib_sr->sr_lifetime - xtimer_now_usec64();
/* check if the lifetime expired */
if ((int64_t)tm < 0) {
/* remove this sr if its lifetime expired */
fib_sr->sr_lifetime = 0;
if (fib_sr->sr_path != NULL) {
fib_sr_entry_t *elt = NULL;
LL_FOREACH(fib_sr->sr_path, elt) {
universal_address_rem(elt->address);
}
fib_sr->sr_path = NULL;
}
/* and return an errorcode */
return -ENOENT;
}
return 0;
}
/**
* @brief Internal function:
* creates a new entry in the table entry pool for a hop in a source route
*/
static int fib_sr_new_entry(fib_table_t *table, uint8_t *addr, size_t addr_size,
fib_sr_entry_t **new_entry)
{
for (size_t i = 0; i < table->data.source_routes->entry_pool_size; ++i) {
if (table->data.source_routes->entry_pool[i].address == NULL) {
table->data.source_routes->entry_pool[i].address = universal_address_add(addr, addr_size);
if (table->data.source_routes->entry_pool[i].address == NULL) {
return -ENOMEM;
}
else {
(void)new_entry;
*new_entry = &table->data.source_routes->entry_pool[i];
return 0;
}
}
}
return -ENOMEM;
}
/**
* @brief Internal function:
* checks if the source route belongs to the given table
*/
static int fib_is_sr_in_table(fib_table_t *table, fib_sr_t *fib_sr)
{
for (size_t i = 0; i < table->size; ++i) {
if (&(table->data.source_routes->headers[i]) == fib_sr) {
return 0;
}
}
return -ENOENT;
}
int fib_sr_read_head(fib_table_t *table, fib_sr_t *fib_sr, kernel_pid_t *iface_id,
uint32_t *sr_flags, uint32_t *sr_lifetime)
{
mutex_lock(&(table->mtx_access));
if ((fib_sr == NULL) || (iface_id == NULL) || (sr_flags == NULL)
|| (sr_lifetime == NULL) || (fib_is_sr_in_table(table, fib_sr) == -ENOENT) ) {
mutex_unlock(&(table->mtx_access));
return -EFAULT;
}
if (fib_sr_check_lifetime(fib_sr) == -ENOENT) {
mutex_unlock(&(table->mtx_access));
return -ENOENT;
}
*iface_id = fib_sr->sr_iface_id;
*sr_flags = fib_sr->sr_flags;
*sr_lifetime = fib_sr->sr_lifetime - xtimer_now_usec64();
mutex_unlock(&(table->mtx_access));
return 0;
}
int fib_sr_read_destination(fib_table_t *table, fib_sr_t *fib_sr,
uint8_t *dst, size_t *dst_size)
{
mutex_lock(&(table->mtx_access));
if ((fib_sr == NULL) || (dst == NULL) || (dst_size == NULL)
|| (fib_is_sr_in_table(table, fib_sr) == -ENOENT)) {
mutex_unlock(&(table->mtx_access));
return -EFAULT;
}
if (fib_sr_check_lifetime(fib_sr) == -ENOENT) {
mutex_unlock(&(table->mtx_access));
return -ENOENT;
}
if (fib_sr->sr_dest == NULL) {
mutex_unlock(&(table->mtx_access));
return -EHOSTUNREACH;
}
if (universal_address_get_address(fib_sr->sr_dest->address, dst, dst_size) == NULL) {
mutex_unlock(&(table->mtx_access));
return -ENOBUFS;
}
mutex_unlock(&(table->mtx_access));
return 0;
}
int fib_sr_set(fib_table_t *table, fib_sr_t *fib_sr, kernel_pid_t *sr_iface_id,
uint32_t *sr_flags, uint32_t *sr_lifetime)
{
mutex_lock(&(table->mtx_access));
if ((fib_sr == NULL) || (fib_is_sr_in_table(table, fib_sr) == -ENOENT)) {
mutex_unlock(&(table->mtx_access));
return -EFAULT;
}
if (fib_sr_check_lifetime(fib_sr) == -ENOENT) {
mutex_unlock(&(table->mtx_access));
return -ENOENT;
}
if (sr_iface_id != NULL) {
fib_sr->sr_iface_id = *sr_iface_id;
}
if (sr_flags != NULL) {
fib_sr->sr_flags = *sr_flags;
}
if (sr_lifetime != NULL) {
fib_lifetime_to_absolute(*sr_lifetime, &(fib_sr->sr_lifetime));
}
mutex_unlock(&(table->mtx_access));
return 0;
}
int fib_sr_delete(fib_table_t *table, fib_sr_t *fib_sr)
{
mutex_lock(&(table->mtx_access));
if ((fib_sr == NULL) || (fib_is_sr_in_table(table, fib_sr) == -ENOENT)) {
mutex_unlock(&(table->mtx_access));
return -EFAULT;
}
fib_sr->sr_lifetime = 0;
if (fib_sr->sr_path != NULL) {
fib_sr_entry_t *elt = NULL, *tmp = NULL;
LL_FOREACH_SAFE(fib_sr->sr_path, elt, tmp) {
universal_address_rem(elt->address);
elt->address = NULL;
LL_DELETE(fib_sr->sr_path, elt);
}
fib_sr->sr_path = NULL;
}
mutex_unlock(&(table->mtx_access));
return 0;
}
int fib_sr_next(fib_table_t *table, fib_sr_t *fib_sr, fib_sr_entry_t **sr_path_entry)
{
mutex_lock(&(table->mtx_access));
if ((fib_sr == NULL) || (sr_path_entry == NULL)
|| (fib_is_sr_in_table(table, fib_sr) == -ENOENT)) {
mutex_unlock(&(table->mtx_access));
return -EFAULT;
}
if (fib_sr->sr_path == NULL) {
mutex_unlock(&(table->mtx_access));
return -EFAULT;
}
if (fib_sr_check_lifetime(fib_sr) == -ENOENT) {
mutex_unlock(&(table->mtx_access));
return -ENOENT;
}
/* if we reach the destination entry, i.e. the last entry we just return 1 */
if (*sr_path_entry == fib_sr->sr_dest) {
mutex_unlock(&(table->mtx_access));
return 1;
}
/* when we start, we pass the first entry */
if (*sr_path_entry == NULL) {
*sr_path_entry = fib_sr->sr_path;
}
else {
/* in any other case we just return the next entry */
*sr_path_entry = (*sr_path_entry)->next;
}
mutex_unlock(&(table->mtx_access));
return 0;
}
int fib_sr_search(fib_table_t *table, fib_sr_t *fib_sr, uint8_t *addr, size_t addr_size,
fib_sr_entry_t **sr_path_entry)
{
mutex_lock(&(table->mtx_access));
if ((fib_sr == NULL) || (addr == NULL) || (sr_path_entry == NULL)
|| (fib_is_sr_in_table(table, fib_sr) == -ENOENT)) {
mutex_unlock(&(table->mtx_access));
return -EFAULT;
}
if (fib_sr_check_lifetime(fib_sr) == -ENOENT) {
mutex_unlock(&(table->mtx_access));
return -ENOENT;
}
fib_sr_entry_t *elt = NULL;
LL_FOREACH(fib_sr->sr_path, elt) {
size_t addr_size_match = addr_size << 3;
if (universal_address_compare(elt->address, addr, &addr_size_match) == UNIVERSAL_ADDRESS_EQUAL) {
/* temporary workaround to calm compiler */
(void)sr_path_entry;
*sr_path_entry = elt;
mutex_unlock(&(table->mtx_access));
return 0;
}
}
mutex_unlock(&(table->mtx_access));
return -EHOSTUNREACH;
}
int fib_sr_entry_append(fib_table_t *table, fib_sr_t *fib_sr,
uint8_t *addr, size_t addr_size)
{
mutex_lock(&(table->mtx_access));
if ((fib_sr == NULL) || (addr == NULL)
|| (fib_is_sr_in_table(table, fib_sr) == -ENOENT)) {
mutex_unlock(&(table->mtx_access));
return -EFAULT;
}
if (fib_sr_check_lifetime(fib_sr) == -ENOENT) {
mutex_unlock(&(table->mtx_access));
return -ENOENT;
}
fib_sr_entry_t *elt = NULL;
LL_FOREACH(fib_sr->sr_path, elt) {
size_t addr_size_match = addr_size << 3;
if (universal_address_compare(elt->address, addr, &addr_size_match) == UNIVERSAL_ADDRESS_EQUAL) {
mutex_unlock(&(table->mtx_access));
return -EINVAL;
}
}
fib_sr_entry_t *new_entry[1];
int ret = fib_sr_new_entry(table, addr, addr_size, &new_entry[0]);
if (ret == 0) {
fib_sr_entry_t *tmp = fib_sr->sr_dest;
if (tmp != NULL) {
/* we append the new entry behind the former destination */
tmp->next = new_entry[0];
}
else {
/* this is also our first entry */
fib_sr->sr_path = new_entry[0];
}
fib_sr->sr_dest = new_entry[0];
}
mutex_unlock(&(table->mtx_access));
return ret;
}
int fib_sr_entry_add(fib_table_t *table, fib_sr_t *fib_sr,
fib_sr_entry_t *sr_path_entry, uint8_t *addr, size_t addr_size,
bool keep_remaining_route)
{
mutex_lock(&(table->mtx_access));
if ((fib_sr == NULL) || (sr_path_entry == NULL) || (addr == NULL)
|| (fib_is_sr_in_table(table, fib_sr) == -ENOENT)) {
mutex_unlock(&(table->mtx_access));
return -EFAULT;
}
if (fib_sr_check_lifetime(fib_sr) == -ENOENT) {
mutex_unlock(&(table->mtx_access));
return -ENOENT;
}
bool found = false;
fib_sr_entry_t *elt = NULL;
LL_FOREACH(fib_sr->sr_path, elt) {
size_t addr_size_match = addr_size << 3;
if (universal_address_compare(elt->address, addr, &addr_size_match) == UNIVERSAL_ADDRESS_EQUAL) {
mutex_unlock(&(table->mtx_access));
return -EINVAL;
}
if (sr_path_entry == elt) {
found = true;
break;
}
}
int ret = -ENOENT;
if (found) {
fib_sr_entry_t *new_entry[1];
ret = fib_sr_new_entry(table, addr, addr_size, &new_entry[0]);
if (ret == 0) {
fib_sr_entry_t *remaining = sr_path_entry->next;
sr_path_entry->next = new_entry[0];
if (keep_remaining_route) {
new_entry[0]->next = remaining;
}
else {
fib_sr_entry_t *elt = NULL, *tmp = NULL;
LL_FOREACH_SAFE(remaining, elt, tmp) {
universal_address_rem(elt->address);
elt->address = NULL;
LL_DELETE(remaining, elt);
}
new_entry[0]->next = NULL;
fib_sr->sr_dest = new_entry[0];
}
}
}
mutex_unlock(&(table->mtx_access));
return ret;
}
int fib_sr_entry_delete(fib_table_t *table, fib_sr_t *fib_sr, uint8_t *addr, size_t addr_size,
bool keep_remaining_route)
{
mutex_lock(&(table->mtx_access));
if ((fib_sr == NULL) || (fib_is_sr_in_table(table, fib_sr) == -ENOENT)) {
mutex_unlock(&(table->mtx_access));
return -EFAULT;
}
if (fib_sr_check_lifetime(fib_sr) == -ENOENT) {
mutex_unlock(&(table->mtx_access));
return -ENOENT;
}
fib_sr_entry_t *elt = NULL, *tmp;
tmp = fib_sr->sr_path;
LL_FOREACH(fib_sr->sr_path, elt) {
size_t addr_size_match = addr_size << 3;
if (universal_address_compare(elt->address, addr, &addr_size_match) == UNIVERSAL_ADDRESS_EQUAL) {
universal_address_rem(elt->address);
if (keep_remaining_route) {
tmp->next = elt->next;
}
else {
fib_sr_entry_t *elt_del = NULL, *tmp_del = NULL;
LL_FOREACH_SAFE(tmp, elt_del, tmp_del) {
universal_address_rem(elt_del->address);
elt_del->address = NULL;
LL_DELETE(tmp, elt_del);
}
}
if (elt == fib_sr->sr_path) {
/* if we remove the first entry we must adjust the path start */
fib_sr->sr_path = elt->next;
}
if (elt == fib_sr->sr_dest) {
/* if we remove the last entry we must adjust the destination */
fib_sr->sr_dest = tmp;
}
mutex_unlock(&(table->mtx_access));
return 0;
}
tmp = elt;
}
return -ENOENT;
}
int fib_sr_entry_overwrite(fib_table_t *table, fib_sr_t *fib_sr,
uint8_t *addr_old, size_t addr_old_size,
uint8_t *addr_new, size_t addr_new_size)
{
mutex_lock(&(table->mtx_access));
if ((fib_sr == NULL) || (addr_old == NULL) || (addr_new == NULL)
|| (fib_is_sr_in_table(table, fib_sr) == -ENOENT)) {
mutex_unlock(&(table->mtx_access));
return -EFAULT;
}
if (fib_sr_check_lifetime(fib_sr) == -ENOENT) {
mutex_unlock(&(table->mtx_access));
return -ENOENT;
}
fib_sr_entry_t *elt = NULL, *elt_repl;
elt_repl = NULL;
LL_FOREACH(fib_sr->sr_path, elt) {
size_t addr_old_size_match = addr_old_size << 3;
size_t addr_new_size_match = addr_old_size << 3;
if (universal_address_compare(elt->address, addr_old, &addr_old_size_match) == UNIVERSAL_ADDRESS_EQUAL) {
elt_repl = elt;
}
if (universal_address_compare(elt->address, addr_new, &addr_new_size_match) == UNIVERSAL_ADDRESS_EQUAL) {
mutex_unlock(&(table->mtx_access));
return -EINVAL;
}
}
if (elt_repl != NULL) {
universal_address_rem(elt_repl->address);
universal_address_container_t *add = universal_address_add(addr_new, addr_new_size);
if (add == NULL) {
/* if this happened we deleted one entry, i.e. decreased the usecount
* adding a new one was not possible since lack of memory
* so we add back the old entry, i.e. increasing the usecount
*/
universal_address_add(addr_old, addr_old_size);
mutex_unlock(&(table->mtx_access));
return -ENOMEM;
}
elt_repl->address = add;
}
mutex_unlock(&(table->mtx_access));
return 0;
}
int fib_sr_entry_get_address(fib_table_t *table, fib_sr_t *fib_sr, fib_sr_entry_t *sr_entry,
uint8_t *addr, size_t *addr_size)
{
mutex_lock(&(table->mtx_access));
if ((fib_sr == NULL) || (fib_is_sr_in_table(table, fib_sr) == -ENOENT)) {
mutex_unlock(&(table->mtx_access));
return -EFAULT;
}
if (fib_sr_check_lifetime(fib_sr) == -ENOENT) {
mutex_unlock(&(table->mtx_access));
return -ENOENT;
}
fib_sr_entry_t *elt = NULL;
LL_FOREACH(fib_sr->sr_path, elt) {
if (elt == sr_entry) {
if (universal_address_get_address(elt->address, addr, addr_size) != NULL) {
mutex_unlock(&(table->mtx_access));
return 0;
}
else {
mutex_unlock(&(table->mtx_access));
return -ENOMEM;
}
}
}
mutex_unlock(&(table->mtx_access));
return -ENOENT;
}
/**
* @brief helper function to search a partial path to a given destination,
* and iff successful to create a new source route
*
* @param[in] table the fib table the entry should be added to
* @param[in] dst pointer to the destination address bytes
* @param[in] dst_size the size in bytes of the destination address type
* @param[in] check_free_entry position to start the search for a free entry
* @param[out] error the state of of this operation when finished
*
* @return pointer to the new source route on success
* NULL otherwise
*/
static fib_sr_t* _fib_create_sr_from_partial(fib_table_t *table, uint8_t *dst, size_t dst_size,
int check_free_entry, int *error) {
fib_sr_t* hit = NULL;
for (size_t i = 0; i < table->size; ++i) {
if (table->data.source_routes->headers[i].sr_lifetime != 0) {
fib_sr_entry_t *elt = NULL;
LL_FOREACH(table->data.source_routes->headers[i].sr_path, elt) {
size_t addr_size_match = dst_size << 3;
if (universal_address_compare(elt->address, dst, &addr_size_match) == UNIVERSAL_ADDRESS_EQUAL) {
/* we create a new sr */
if (check_free_entry == -1) {
/* we have no room to create a new sr
* so we just return and NOT tell the RPs to find a route
* since we cannot save it
*/
*error = -ENOBUFS;
return NULL;
}
else {
/* we check if there is a free place for the new sr */
fib_sr_t *new_sr = NULL;
for (size_t j = check_free_entry; j < table->size; ++j) {
if (table->data.source_routes->headers[j].sr_lifetime != 0) {
/* not this one, maybe the next one */
continue;
}
else {
/* there it is, so we copy the header */
new_sr = &table->data.source_routes->headers[j];
new_sr->sr_iface_id = table->data.source_routes->headers[i].sr_iface_id;
new_sr->sr_flags = table->data.source_routes->headers[i].sr_flags;
new_sr->sr_lifetime = table->data.source_routes->headers[i].sr_lifetime;
new_sr->sr_path = NULL;
/* and the path until the searched destination */
fib_sr_entry_t *elt_iter = NULL, *elt_add = NULL;
LL_FOREACH(table->data.source_routes->headers[i].sr_path, elt_iter) {
fib_sr_entry_t *new_entry;
if (fib_sr_new_entry(table, elt_iter->address->address,
elt_iter->address->address_size,
&new_entry) != 0) {
/* we could not create a new entry
* so we return to clean up the partial route
*/
*error = -ENOBUFS;
return new_sr;
}
if (new_sr->sr_path == NULL) {
new_sr->sr_path = new_entry;
elt_add = new_sr->sr_path;
}
else {
elt_add->next = new_entry;
elt_add = elt_add->next;
}
if (elt_iter == elt) {
/* we copied until the destination */
new_sr->sr_dest = new_entry;
hit = new_sr;
/* tell the RPs that a new sr has been created
* the size and the flags parameters are ignored
*/
if (fib_signal_rp(table, FIB_MSG_RP_SIGNAL_SOURCE_ROUTE_CREATED,
(uint8_t *)new_sr, 0, 0) != 0) {
/* if no RP can handle the source route
* then the host is not directly reachable
*/
*error = -EHOSTUNREACH;
}
/* break from iterating for copy */
break;
}
}
}
}
/* break from iterating the found path */
break;
}
}
}
if (hit != NULL) {
/* break iterating all sr since we have a path now */
break;
}
}
}
return hit;
}
int fib_sr_get_route(fib_table_t *table, uint8_t *dst, size_t dst_size, kernel_pid_t *sr_iface_id,
uint32_t *sr_flags,
uint8_t *addr_list, size_t *addr_list_elements, size_t *element_size,
bool reverse, fib_sr_t **fib_sr)
{
mutex_lock(&(table->mtx_access));
if ((dst == NULL) || (sr_iface_id == NULL) || (sr_flags == NULL)
|| (addr_list == NULL) || (addr_list_elements == NULL) || (element_size == NULL)) {
mutex_unlock(&(table->mtx_access));
return -EFAULT;
}
fib_sr_t *hit = NULL;
fib_sr_t *tmp_hit = NULL;
int check_free_entry = -1;
bool skip = (fib_sr != NULL) && (*fib_sr != NULL)?true:false;
/* Case 1 - check if we know a direct route */
for (size_t i = 0; i < table->size; ++i) {
if (fib_sr_check_lifetime(&table->data.source_routes->headers[i]) == -ENOENT) {
/* expired, so skip this sr and remember its position */
if (check_free_entry == -1) {
/* we want to fill up the source routes from the beginning */
check_free_entry = i;
}
continue;
}
if( skip ) {
if(*fib_sr == &table->data.source_routes->headers[i]) {
skip = false;
}
/* we skip all entries upon the consecutive one to start search */
continue;
}
size_t addr_size_match = dst_size << 3;
if (universal_address_compare(table->data.source_routes->headers[i].sr_dest->address,
dst, &addr_size_match) == UNIVERSAL_ADDRESS_EQUAL) {
if (*sr_flags == table->data.source_routes->headers[i].sr_flags) {
/* found a perfect matching sr, no need to search further */
hit = &table->data.source_routes->headers[i];
tmp_hit = NULL;
if (check_free_entry == -1) {
check_free_entry = i;
}
break;
}
else {
/* found a sr to the destination but with different flags,
* maybe we find a better one.
*/
tmp_hit = &table->data.source_routes->headers[i];
}
}
}
if (hit == NULL) {
/* we didn't find a perfect sr, but one with distinct flags */
hit = tmp_hit;
}
/* Case 2 - if no hit is found check if there is a matching entry in one sr_path
* @note the first match wins, if we find one we will NOT continue searching,
* since this search is very expensive in terms of compare operations
*/
if (hit == NULL) {
int error = 0;
hit = _fib_create_sr_from_partial(table, dst, dst_size, check_free_entry, &error);
if ((error != 0) && (error != -EHOSTUNREACH)) {
/* something went wrong, so we clean up our mess
*
* @note we could handle -EHOSTUNREACH differently here,
* since it says that we have a partial source route but no RP
* to manage it.
* That's why I let it pass for now.
*/
if (hit != NULL) {
hit->sr_lifetime = 0;
if (hit->sr_path != NULL) {
fib_sr_entry_t *elt = NULL, *tmp = NULL;
LL_FOREACH_SAFE(hit->sr_path, elt, tmp) {
universal_address_rem(elt->address);
elt->address = NULL;
LL_DELETE(hit->sr_path, elt);
}
hit->sr_path = NULL;
}
}
mutex_unlock(&(table->mtx_access));
return error;
}
}
/* Final step - copy the list in the desired order */
if (hit != NULL) {
/* store the current hit to enable consecutive searches */
if( fib_sr != NULL ) {
*fib_sr = hit;
}
/* check the list size and if the sr entries will fit */
int count;
fib_sr_entry_t *elt = NULL;
LL_COUNT(hit->sr_path, elt, count);
if (((size_t)count > *addr_list_elements)
|| (sizeof(hit->sr_path->address->address) > *element_size)) {
*addr_list_elements = count;
*element_size = sizeof(hit->sr_path->address->address);
mutex_unlock(&(table->mtx_access));
return -ENOBUFS;
}
/* start copy the individual entries in the desired order */
uint8_t *next_entry = addr_list;
int one_address_size = *element_size;
if (reverse) {
/* we move to the last list element */
next_entry += (count - 1) * sizeof(hit->sr_path->address->address);
/* and set the storing direction during the iteration */
one_address_size *= -1;
}
elt = NULL;
LL_FOREACH(hit->sr_path, elt) {
size_t tmp_size = sizeof(hit->sr_path->address->address);
universal_address_get_address(elt->address, next_entry, &tmp_size);
next_entry += one_address_size;
}
*sr_iface_id = hit->sr_iface_id;
*sr_flags = hit->sr_flags;
*addr_list_elements = count;
*element_size = sizeof(hit->sr_path->address->address);
}
else {
/* trigger RPs for route discovery */
fib_signal_rp(table, FIB_MSG_RP_SIGNAL_UNREACHABLE_DESTINATION, dst, dst_size, *sr_flags);
mutex_unlock(&(table->mtx_access));
return -EHOSTUNREACH;
}
mutex_unlock(&(table->mtx_access));
if (tmp_hit == NULL) {
return 0;
}
else {
return 1;
}
}
/* print functions */
void fib_print_notify_rp(fib_table_t *table)
{
mutex_lock(&(table->mtx_access));
for (size_t i = 0; i < FIB_MAX_REGISTERED_RP; ++i) {
printf("[fib_print_notify_rp] pid[%d]: %d\n", (int)i, (int)(table->notify_rp[i]));
}
mutex_unlock(&(table->mtx_access));
}
void fib_print_fib_table(fib_table_t *table)
{
mutex_lock(&(table->mtx_access));
for (size_t i = 0; i < table->size; ++i) {
printf("[fib_print_table] %d) iface_id: %d, global: %p, next hop: %p, lifetime: %"PRIu32"\n",
(int)i, (int)table->data.entries[i].iface_id,
(void *)table->data.entries[i].global,
(void *)table->data.entries[i].next_hop,
(uint32_t)(table->data.entries[i].lifetime / 1000));
}
mutex_unlock(&(table->mtx_access));
}
void fib_print_sr(fib_table_t *table, fib_sr_t *sr)
{
/* does not adjust the lifetime */
mutex_lock(&(table->mtx_access));
if ((sr == NULL) || (fib_is_sr_in_table(table, sr) == -ENOENT)) {
mutex_unlock(&(table->mtx_access));
return;
}
printf("\n-= Source route (%p) =-\nIface: %d\nflags: %x\npath: %p\ndest: ",
(void *)sr, sr->sr_iface_id, (unsigned int)sr->sr_flags, (void *)sr->sr_path);
if (sr->sr_dest != NULL) {
universal_address_print_entry(sr->sr_dest->address);
} else {
puts("Not set.");
}
fib_sr_entry_t *nxt = sr->sr_path;
while (nxt) {
universal_address_print_entry(nxt->address);
nxt = nxt->next;
}
printf("-= END (%p) =-\n", (void *)sr);
mutex_unlock(&(table->mtx_access));
}
static void fib_print_address(universal_address_container_t *entry)
{
uint8_t address[UNIVERSAL_ADDRESS_SIZE];
size_t addr_size = UNIVERSAL_ADDRESS_SIZE;
uint8_t *ret = universal_address_get_address(entry, address, &addr_size);
if (ret == address) {
#ifdef MODULE_IPV6_ADDR
if (addr_size == sizeof(ipv6_addr_t)) {
printf("%-" FIB_ADDR_PRINT_LENS "s",
ipv6_addr_to_str(addr_str, (ipv6_addr_t *) address, sizeof(addr_str)));
return;
}
#endif
for (size_t i = 0; i < UNIVERSAL_ADDRESS_SIZE; ++i) {
if (i <= addr_size) {
printf("%02x", address[i]);
}
else {
printf(" ");
}
}
#ifdef MODULE_IPV6_ADDR
/* print trailing whitespaces */
for (size_t i = 0; i < FIB_ADDR_PRINT_LEN - (UNIVERSAL_ADDRESS_SIZE * 2); ++i) {
printf(" ");
}
#endif
}
}
void fib_print_routes(fib_table_t *table)
{
mutex_lock(&(table->mtx_access));
uint64_t now = xtimer_now_usec64();
if (table->table_type == FIB_TABLE_TYPE_SH) {
printf("%-" FIB_ADDR_PRINT_LENS "s %-17s %-" FIB_ADDR_PRINT_LENS "s %-10s %-16s"
" Interface\n" , "Destination", "Flags", "Next Hop", "Flags", "Expires");
for (size_t i = 0; i < table->size; ++i) {
if (table->data.entries[i].lifetime != 0) {
fib_print_address(table->data.entries[i].global);
printf(" 0x%08"PRIx32" ", table->data.entries[i].global_flags);
if(table->data.entries[i].global_flags & FIB_FLAG_NET_PREFIX_MASK) {
uint32_t prefix = (table->data.entries[i].global_flags
& FIB_FLAG_NET_PREFIX_MASK);
printf("N /%-3d ", (int)(prefix >> FIB_FLAG_NET_PREFIX_SHIFT));
} else {
printf("H ");
}
fib_print_address(table->data.entries[i].next_hop);
printf(" 0x%08"PRIx32" ", table->data.entries[i].next_hop_flags);
if (table->data.entries[i].lifetime != FIB_LIFETIME_NO_EXPIRE) {
uint64_t tm = table->data.entries[i].lifetime - now;
/* we must interpret the values as signed */
if ((int64_t)tm < 0 ) {
printf("%-16s ", "EXPIRED");
}
else {
printf("%"PRIu32".%05"PRIu32, (uint32_t)(tm / 1000000),
(uint32_t)(tm % 1000000));
}
}
else {
printf("%-16s ", "NEVER");
}
printf("%d\n", (int)table->data.entries[i].iface_id);
}
}
}
else if (table->table_type == FIB_TABLE_TYPE_SR) {
printf("%-" FIB_ADDR_PRINT_LENS "s %-" FIB_ADDR_PRINT_LENS "s %-6s %-16s Interface\n"
, "SR Destination", "SR First Hop", "SR Flags", "Expires");
for (size_t i = 0; i < table->size; ++i) {
if (table->data.source_routes->headers[i].sr_lifetime != 0) {
fib_print_address(table->data.source_routes->headers[i].sr_dest->address);
fib_print_address(table->data.source_routes->headers[i].sr_path->address);
printf(" 0x%04"PRIx32" ", table->data.source_routes->headers[i].sr_flags);
if (table->data.source_routes->headers[i].sr_lifetime != FIB_LIFETIME_NO_EXPIRE) {
uint64_t tm = table->data.source_routes->headers[i].sr_lifetime - now;
/* we must interpret the values as signed */
if ((int64_t)tm < 0 ) {
printf("%-16s ", "EXPIRED");
}
else {
printf("%"PRIu32".%05"PRIu32, (uint32_t)(tm / 1000000),
(uint32_t)(tm % 1000000));
}
}
else {
printf("%-16s ", "NEVER");
}
printf("%d\n", (int)table->data.source_routes->headers[i].sr_iface_id);
}
}
}
mutex_unlock(&(table->mtx_access));
}
#if FIB_DEVEL_HELPER
int fib_devel_get_lifetime(fib_table_t *table, uint64_t *lifetime, uint8_t *dst,
size_t dst_size)
{
if (table->table_type == FIB_TABLE_TYPE_SH) {
size_t count = 1;
fib_entry_t *entry[count];
int ret = fib_find_entry(table, dst, dst_size, &(entry[0]), &count);
if (ret == 1 ) {
/* only return lifetime of exact matches */
*lifetime = entry[0]->lifetime;
return 0;
}
return -EHOSTUNREACH;
}
else if (table->table_type == FIB_TABLE_TYPE_SR) {
size_t addr_size_match = dst_size << 3;
/* first hit wins here */
for (size_t i = 0; i < table->size; ++i) {
if (universal_address_compare(table->data.source_routes->headers[i].sr_dest->address,
dst, &addr_size_match) == UNIVERSAL_ADDRESS_EQUAL) {
*lifetime = table->data.source_routes->headers[i].sr_lifetime;
return 0;
}
}
return -EHOSTUNREACH;
}
return -EFAULT;
}
#endif
| yogo1212/RIOT | sys/net/network_layer/fib/fib.c | C | lgpl-2.1 | 56,622 |
/*= -*- c-basic-offset: 4; indent-tabs-mode: nil; -*-
*
* librsync -- the library for network deltas
* $Id: msg.c,v 1.15 2003/06/12 05:47:22 wayned Exp $
*
* Copyright (C) 2000, 2001 by Martin Pool <mbp@samba.org>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation; either version 2.1 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
/*
| Welcome to Arco AM/PM Mini-Market. We
| would like to advise our customers
| that any individual who offers to
| pump gas, wash windows or solicit
| products is not employed by or
| associated with this facility. We
| discourage any contact with these
| individuals and ask that you report
| any problems to uniformed personal
| inside. Thankyou for shopping at
| Arco, and have a nice day.
*/
#include <config.h>
#include <stdlib.h>
#include <stdio.h>
#include "librsync.h"
/*
* TODO: (Suggestion by tridge) Add a function which outputs a
* complete text description of a job, including only the fields
* relevant to the current encoding function.
*/
/** \brief Translate from rs_result to human-readable messages. */
char const *rs_strerror(rs_result r)
{
switch (r) {
case RS_DONE:
return "OK";
case RS_RUNNING:
return "still running";
case RS_BLOCKED:
return "blocked waiting for input or output buffers";
case RS_BAD_MAGIC:
return "bad magic number at start of stream";
case RS_INPUT_ENDED:
return "unexpected end of input";
case RS_CORRUPT:
return "stream corrupt";
case RS_UNIMPLEMENTED:
return "unimplemented case";
case RS_MEM_ERROR:
return "out of memory";
case RS_IO_ERROR:
return "IO error";
case RS_SYNTAX_ERROR:
return "bad command line syntax";
case RS_INTERNAL_ERROR:
return "library internal error";
default:
return "unexplained problem";
}
}
| kaseya/librsync | msg.c | C | lgpl-2.1 | 2,883 |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (version 1.7.0_25) on Thu Sep 26 14:06:50 PDT 2013 -->
<meta http-equiv="Content-Type" content="text/html" charset="UTF-8">
<title>LognormalDistr</title>
<meta name="date" content="2013-09-26">
<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="LognormalDistr";
}
//-->
</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="navBarCell1Rev">Class</li>
<li><a href="class-use/LognormalDistr.html">Use</a></li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../index-files/index-1.html">Index</a></li>
<li><a href="../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../../org/cloudbus/cloudsim/distributions/GammaDistr.html" title="class in org.cloudbus.cloudsim.distributions"><span class="strong">Prev Class</span></a></li>
<li><a href="../../../../org/cloudbus/cloudsim/distributions/LomaxDistribution.html" title="class in org.cloudbus.cloudsim.distributions"><span class="strong">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../../../index.html?org/cloudbus/cloudsim/distributions/LognormalDistr.html" target="_top">Frames</a></li>
<li><a href="LognormalDistr.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>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li>Nested | </li>
<li>Field | </li>
<li><a href="#constructor_summary">Constr</a> | </li>
<li><a href="#method_summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li>Field | </li>
<li><a href="#constructor_detail">Constr</a> | </li>
<li><a href="#method_detail">Method</a></li>
</ul>
</div>
<a name="skip-navbar_top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<!-- ======== START OF CLASS DATA ======== -->
<div class="header">
<div class="subTitle">org.cloudbus.cloudsim.distributions</div>
<h2 title="Class LognormalDistr" class="title">Class LognormalDistr</h2>
</div>
<div class="contentContainer">
<ul class="inheritance">
<li>java.lang.Object</li>
<li>
<ul class="inheritance">
<li>org.cloudbus.cloudsim.distributions.LognormalDistr</li>
</ul>
</li>
</ul>
<div class="description">
<ul class="blockList">
<li class="blockList">
<dl>
<dt>All Implemented Interfaces:</dt>
<dd><a href="../../../../org/cloudbus/cloudsim/distributions/ContinuousDistribution.html" title="interface in org.cloudbus.cloudsim.distributions">ContinuousDistribution</a></dd>
</dl>
<hr>
<br>
<pre>public class <span class="strong">LognormalDistr</span>
extends java.lang.Object
implements <a href="../../../../org/cloudbus/cloudsim/distributions/ContinuousDistribution.html" title="interface in org.cloudbus.cloudsim.distributions">ContinuousDistribution</a></pre>
<div class="block">The Class LognormalDistr.</div>
<dl><dt><span class="strong">Since:</span></dt>
<dd>CloudSim Toolkit 1.0</dd></dl>
</li>
</ul>
</div>
<div class="summary">
<ul class="blockList">
<li class="blockList">
<!-- ======== CONSTRUCTOR SUMMARY ======== -->
<ul class="blockList">
<li class="blockList"><a name="constructor_summary">
<!-- -->
</a>
<h3>Constructor Summary</h3>
<table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Constructor Summary table, listing constructors, and an explanation">
<caption><span>Constructors</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colOne" scope="col">Constructor and Description</th>
</tr>
<tr class="altColor">
<td class="colOne"><code><strong><a href="../../../../org/cloudbus/cloudsim/distributions/LognormalDistr.html#LognormalDistr(double, double)">LognormalDistr</a></strong>(double mean,
double dev)</code>
<div class="block">Instantiates a new lognormal distr.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colOne"><code><strong><a href="../../../../org/cloudbus/cloudsim/distributions/LognormalDistr.html#LognormalDistr(java.util.Random, double, double)">LognormalDistr</a></strong>(java.util.Random seed,
double mean,
double dev)</code>
<div class="block">Instantiates a new lognormal distr.</div>
</td>
</tr>
</table>
</li>
</ul>
<!-- ========== METHOD SUMMARY =========== -->
<ul class="blockList">
<li class="blockList"><a name="method_summary">
<!-- -->
</a>
<h3>Method Summary</h3>
<table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Method Summary table, listing methods, and an explanation">
<caption><span>Methods</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tr class="altColor">
<td class="colFirst"><code>double</code></td>
<td class="colLast"><code><strong><a href="../../../../org/cloudbus/cloudsim/distributions/LognormalDistr.html#sample()">sample</a></strong>()</code>
<div class="block">Sample the random number generator.</div>
</td>
</tr>
</table>
<ul class="blockList">
<li class="blockList"><a name="methods_inherited_from_class_java.lang.Object">
<!-- -->
</a>
<h3>Methods inherited from class java.lang.Object</h3>
<code>clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait</code></li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
<div class="details">
<ul class="blockList">
<li class="blockList">
<!-- ========= CONSTRUCTOR DETAIL ======== -->
<ul class="blockList">
<li class="blockList"><a name="constructor_detail">
<!-- -->
</a>
<h3>Constructor Detail</h3>
<a name="LognormalDistr(java.util.Random, double, double)">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>LognormalDistr</h4>
<pre>public LognormalDistr(java.util.Random seed,
double mean,
double dev)</pre>
<div class="block">Instantiates a new lognormal distr.</div>
<dl><dt><span class="strong">Parameters:</span></dt><dd><code>seed</code> - the seed</dd><dd><code>mean</code> - the mean</dd><dd><code>dev</code> - the dev</dd></dl>
</li>
</ul>
<a name="LognormalDistr(double, double)">
<!-- -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>LognormalDistr</h4>
<pre>public LognormalDistr(double mean,
double dev)</pre>
<div class="block">Instantiates a new lognormal distr.</div>
<dl><dt><span class="strong">Parameters:</span></dt><dd><code>mean</code> - the mean</dd><dd><code>dev</code> - the dev</dd></dl>
</li>
</ul>
</li>
</ul>
<!-- ============ METHOD DETAIL ========== -->
<ul class="blockList">
<li class="blockList"><a name="method_detail">
<!-- -->
</a>
<h3>Method Detail</h3>
<a name="sample()">
<!-- -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>sample</h4>
<pre>public double sample()</pre>
<div class="block"><strong>Description copied from interface: <code><a href="../../../../org/cloudbus/cloudsim/distributions/ContinuousDistribution.html#sample()">ContinuousDistribution</a></code></strong></div>
<div class="block">Sample the random number generator.</div>
<dl>
<dt><strong>Specified by:</strong></dt>
<dd><code><a href="../../../../org/cloudbus/cloudsim/distributions/ContinuousDistribution.html#sample()">sample</a></code> in interface <code><a href="../../../../org/cloudbus/cloudsim/distributions/ContinuousDistribution.html" title="interface in org.cloudbus.cloudsim.distributions">ContinuousDistribution</a></code></dd>
<dt><span class="strong">Returns:</span></dt><dd>The sample</dd></dl>
</li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
</div>
<!-- ========= END OF CLASS DATA ========= -->
<!-- ======= 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="navBarCell1Rev">Class</li>
<li><a href="class-use/LognormalDistr.html">Use</a></li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../index-files/index-1.html">Index</a></li>
<li><a href="../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../../org/cloudbus/cloudsim/distributions/GammaDistr.html" title="class in org.cloudbus.cloudsim.distributions"><span class="strong">Prev Class</span></a></li>
<li><a href="../../../../org/cloudbus/cloudsim/distributions/LomaxDistribution.html" title="class in org.cloudbus.cloudsim.distributions"><span class="strong">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../../../index.html?org/cloudbus/cloudsim/distributions/LognormalDistr.html" target="_top">Frames</a></li>
<li><a href="LognormalDistr.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>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li>Nested | </li>
<li>Field | </li>
<li><a href="#constructor_summary">Constr</a> | </li>
<li><a href="#method_summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li>Field | </li>
<li><a href="#constructor_detail">Constr</a> | </li>
<li><a href="#method_detail">Method</a></li>
</ul>
</div>
<a name="skip-navbar_bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
</body>
</html>
| Nishi-Inc/WorkflowSim-1.0 | docs/org/cloudbus/cloudsim/distributions/LognormalDistr.html | HTML | lgpl-3.0 | 11,073 |
package crazypants.enderio.machine.capbank.network;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.inventory.IInventory;
import net.minecraft.item.ItemStack;
import cofh.api.energy.IEnergyContainerItem;
import crazypants.enderio.EnderIO;
import crazypants.enderio.machine.capbank.TileCapBank;
public class InventoryImpl implements IInventory {
public static boolean isInventoryEmtpy(TileCapBank cap) {
for (ItemStack st : cap.getInventory()) {
if(st != null) {
return false;
}
}
return true;
}
public static boolean isInventoryEmtpy(ItemStack[] inv) {
if(inv == null) {
return true;
}
for (ItemStack st : inv) {
if(st != null) {
return false;
}
}
return true;
}
private ItemStack[] inventory;
private TileCapBank capBank;
public InventoryImpl() {
}
public TileCapBank getCapBank() {
return capBank;
}
public void setCapBank(TileCapBank cap) {
capBank = cap;
if(cap == null) {
inventory = null;
return;
}
inventory = cap.getInventory();
}
public boolean isEmtpy() {
return isInventoryEmtpy(inventory);
}
public ItemStack[] getStacks() {
return inventory;
}
@Override
public ItemStack getStackInSlot(int slot) {
if(inventory == null) {
return null;
}
if(slot < 0 || slot >= inventory.length) {
return null;
}
return inventory[slot];
}
@Override
public ItemStack decrStackSize(int fromSlot, int amount) {
if(inventory == null) {
return null;
}
if(fromSlot < 0 || fromSlot >= inventory.length) {
return null;
}
ItemStack item = inventory[fromSlot];
if(item == null) {
return null;
}
if(item.stackSize <= amount) {
ItemStack result = item.copy();
inventory[fromSlot] = null;
return result;
}
item.stackSize -= amount;
return item.copy();
}
@Override
public void setInventorySlotContents(int slot, ItemStack itemstack) {
if(inventory == null) {
return;
}
if(slot < 0 || slot >= inventory.length) {
return;
}
inventory[slot] = itemstack;
}
@Override
public int getSizeInventory() {
return 4;
}
//--- constant values
@Override
public ItemStack getStackInSlotOnClosing(int p_70304_1_) {
return null;
}
@Override
public String getInventoryName() {
return EnderIO.blockCapBank.getUnlocalizedName() + ".name";
}
@Override
public boolean hasCustomInventoryName() {
return false;
}
@Override
public int getInventoryStackLimit() {
return 1;
}
@Override
public boolean isUseableByPlayer(EntityPlayer p_70300_1_) {
return true;
}
@Override
public boolean isItemValidForSlot(int slot, ItemStack itemstack) {
if(itemstack == null) {
return false;
}
return itemstack.getItem() instanceof IEnergyContainerItem;
}
@Override
public void openInventory() {
}
@Override
public void closeInventory() {
}
@Override
public void markDirty() {
}
}
| Samernieve/EnderIO | src/main/java/crazypants/enderio/machine/capbank/network/InventoryImpl.java | Java | unlicense | 3,083 |
/*
* 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.
*/
namespace Apache.Ignite.Core.Impl.Messaging
{
using System;
using System.Diagnostics;
using Apache.Ignite.Core.Binary;
using Apache.Ignite.Core.Impl.Binary;
using Apache.Ignite.Core.Impl.Binary.IO;
using Apache.Ignite.Core.Impl.Common;
using Apache.Ignite.Core.Impl.Handle;
using Apache.Ignite.Core.Impl.Resource;
using Apache.Ignite.Core.Messaging;
/// <summary>
/// Non-generic binary message listener wrapper.
/// </summary>
internal class MessageListenerHolder : IBinaryWriteAware, IHandle
{
/** Invoker function that takes key and value and invokes wrapped IMessageListener */
private readonly Func<Guid, object, bool> _invoker;
/** Current Ignite instance. */
private readonly Ignite _ignite;
/** Underlying filter. */
private readonly object _filter;
/// <summary>
/// Initializes a new instance of the <see cref="MessageListenerHolder" /> class.
/// </summary>
/// <param name="grid">Grid.</param>
/// <param name="filter">The <see cref="IMessageListener{T}" /> to wrap.</param>
/// <param name="invoker">The invoker func that takes key and value and invokes wrapped IMessageListener.</param>
private MessageListenerHolder(Ignite grid, object filter, Func<Guid, object, bool> invoker)
{
Debug.Assert(filter != null);
Debug.Assert(invoker != null);
_invoker = invoker;
_filter = filter;
// 1. Set fields.
Debug.Assert(grid != null);
_ignite = grid;
_invoker = invoker;
// 2. Perform injections.
ResourceProcessor.Inject(filter, grid);
}
/// <summary>
/// Invoke the filter.
/// </summary>
/// <param name="input">Input.</param>
/// <returns></returns>
public int Invoke(IBinaryStream input)
{
var rawReader = _ignite.Marshaller.StartUnmarshal(input).GetRawReader();
var nodeId = rawReader.ReadGuid();
Debug.Assert(nodeId != null);
return _invoker(nodeId.Value, rawReader.ReadObject<object>()) ? 1 : 0;
}
/// <summary>
/// Wrapped <see cref="IMessageListener{T}" />.
/// </summary>
public object Filter
{
get { return _filter; }
}
/// <summary>
/// Destroy callback.
/// </summary>
public Action DestroyAction { private get; set; }
/** <inheritDoc /> */
public void Release()
{
if (DestroyAction != null)
DestroyAction();
}
/** <inheritDoc /> */
public bool Released
{
get { return false; } // Multiple releases are allowed.
}
/// <summary>
/// Creates local holder instance.
/// </summary>
/// <param name="grid">Ignite instance.</param>
/// <param name="listener">Filter.</param>
/// <returns>
/// New instance of <see cref="MessageListenerHolder" />
/// </returns>
public static MessageListenerHolder CreateLocal<T>(Ignite grid, IMessageListener<T> listener)
{
Debug.Assert(listener != null);
return new MessageListenerHolder(grid, listener, (id, msg) => listener.Invoke(id, (T)msg));
}
/// <summary>
/// Creates remote holder instance.
/// </summary>
/// <param name="grid">Grid.</param>
/// <param name="memPtr">Memory pointer.</param>
/// <returns>Deserialized instance of <see cref="MessageListenerHolder"/></returns>
public static MessageListenerHolder CreateRemote(Ignite grid, long memPtr)
{
Debug.Assert(grid != null);
using (var stream = IgniteManager.Memory.Get(memPtr).GetStream())
{
return grid.Marshaller.Unmarshal<MessageListenerHolder>(stream);
}
}
/// <summary>
/// Gets the invoker func.
/// </summary>
private static Func<Guid, object, bool> GetInvoker(object pred)
{
var func = DelegateTypeDescriptor.GetMessageListener(pred.GetType());
return (id, msg) => func(pred, id, msg);
}
/** <inheritdoc /> */
public void WriteBinary(IBinaryWriter writer)
{
var writer0 = (BinaryWriter)writer.GetRawWriter();
writer0.WithDetach(w => w.WriteObject(Filter));
}
/// <summary>
/// Initializes a new instance of the <see cref="MessageListenerHolder"/> class.
/// </summary>
/// <param name="reader">The reader.</param>
public MessageListenerHolder(IBinaryReader reader)
{
var reader0 = (BinaryReader)reader.GetRawReader();
_filter = reader0.ReadObject<object>();
_invoker = GetInvoker(_filter);
_ignite = reader0.Marshaller.Ignite;
ResourceProcessor.Inject(_filter, _ignite);
}
}
}
| tkpanther/ignite | modules/platforms/dotnet/Apache.Ignite.Core/Impl/Messaging/MessageListenerHolder.cs | C# | apache-2.0 | 5,939 |
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 1.0 Transitional//EN">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel="stylesheet" href="../includes/main.css" type="text/css">
<link rel="shortcut icon" href="../favicon.ico" type="image/x-icon">
<title>Apache CloudStack | The Power Behind Your Cloud</title>
</head>
<body>
<div id="insidetopbg">
<div id="inside_wrapper">
<div class="uppermenu_panel">
<div class="uppermenu_box"></div>
</div>
<div id="main_master">
<div id="inside_header">
<div class="header_top">
<a class="cloud_logo" href="http://cloudstack.org"></a>
<div class="mainemenu_panel"></div>
</div>
</div>
<div id="main_content">
<div class="inside_apileftpanel">
<div class="inside_contentpanel" style="width:930px;">
<div class="api_titlebox">
<div class="api_titlebox_left">
<span>
Apache CloudStack v4.9.0 Root Admin API Reference
</span>
<p></p>
<h1>extractIso</h1>
<p>Extracts an ISO</p>
</div>
<div class="api_titlebox_right">
<a class="api_backbutton" href="../index.html"></a>
</div>
</div>
<div class="api_tablepanel">
<h2>Request parameters</h2>
<table class="apitable">
<tr class="hed">
<td style="width:200px;"><strong>Parameter Name</strong></td><td style="width:500px;">Description</td><td style="width:180px;">Required</td>
</tr>
<tr>
<td style="width:200px;"><strong>id</strong></td><td style="width:500px;"><strong>the ID of the ISO file</strong></td><td style="width:180px;"><strong>true</strong></td>
</tr>
<tr>
<td style="width:200px;"><strong>mode</strong></td><td style="width:500px;"><strong>the mode of extraction - HTTP_DOWNLOAD or FTP_UPLOAD</strong></td><td style="width:180px;"><strong>true</strong></td>
</tr>
<tr>
<td style="width:200px;"><i>url</i></td><td style="width:500px;"><i>the URL to which the ISO would be extracted</i></td><td style="width:180px;"><i>false</i></td>
</tr>
<tr>
<td style="width:200px;"><i>zoneid</i></td><td style="width:500px;"><i>the ID of the zone where the ISO is originally located</i></td><td style="width:180px;"><i>false</i></td>
</tr>
</table>
</div>
<div class="api_tablepanel">
<h2>Response Tags</h2>
<table class="apitable">
<tr class="hed">
<td style="width:200px;"><strong>Response Name</strong></td><td style="width:500px;">Description</td>
</tr>
<tr>
<td style="width:200px;"><strong>id</strong></td><td style="width:500px;">the id of extracted object</td>
</tr>
<tr>
<td style="width:200px;"><strong>accountid</strong></td><td style="width:500px;">the account id to which the extracted object belongs</td>
</tr>
<tr>
<td style="width:200px;"><strong>created</strong></td><td style="width:500px;">the time and date the object was created</td>
</tr>
<tr>
<td style="width:200px;"><strong>extractId</strong></td><td style="width:500px;">the upload id of extracted object</td>
</tr>
<tr>
<td style="width:200px;"><strong>extractMode</strong></td><td style="width:500px;">the mode of extraction - upload or download</td>
</tr>
<tr>
<td style="width:200px;"><strong>name</strong></td><td style="width:500px;">the name of the extracted object</td>
</tr>
<tr>
<td style="width:200px;"><strong>state</strong></td><td style="width:500px;">the state of the extracted object</td>
</tr>
<tr>
<td style="width:200px;"><strong>status</strong></td><td style="width:500px;">the status of the extraction</td>
</tr>
<tr>
<td style="width:200px;"><strong>storagetype</strong></td><td style="width:500px;">type of the storage</td>
</tr>
<tr>
<td style="width:200px;"><strong>uploadpercentage</strong></td><td style="width:500px;">the percentage of the entity uploaded to the specified location</td>
</tr>
<tr>
<td style="width:200px;"><strong>url</strong></td><td style="width:500px;">if mode = upload then url of the uploaded entity. if mode = download the url from which the entity can be downloaded</td>
</tr>
<tr>
<td style="width:200px;"><strong>zoneid</strong></td><td style="width:500px;">zone ID the object was extracted from</td>
</tr>
<tr>
<td style="width:200px;"><strong>zonename</strong></td><td style="width:500px;">zone name the object was extracted from</td>
</tr>
</table>
</div>
</div>
</div>
</div>
</div>
<div id="footer">
<div id="comments_thread">
<script type="text/javascript" src="https://comments.apache.org/show_comments.lua?site=test" async="true"></script>
<noscript>
<iframe width="930" height="500" src="https://comments.apache.org/iframe.lua?site=test&page=4.2.0/rootadmin"></iframe>
</noscript>
</div>
<div id="footer_mainmaster">
<p>Copyright © 2015 The Apache Software Foundation, Licensed under the
<a href="http://www.apache.org/licenses/LICENSE-2.0">Apache License, Version 2.0.</a>
<br>
Apache, CloudStack, Apache CloudStack, the Apache CloudStack logo, the CloudMonkey logo and the Apache feather logo are trademarks of The Apache Software Foundation.</p>
</div>
</div>
</div>
</div>
</body>
</html>
| apache/cloudstack-www | source/api/apidocs-4.9/apis/extractIso.html | HTML | apache-2.0 | 5,014 |
/*
Copyright 2019 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package milestoneapplier
import (
"testing"
"github.com/sirupsen/logrus"
"k8s.io/test-infra/prow/github"
"k8s.io/test-infra/prow/github/fakegithub"
)
func TestMilestoneApplier(t *testing.T) {
var milestonesMap = map[string]int{"v1.0": 1, "v2.0": 2}
testcases := []struct {
name string
baseBranch string
prAction github.PullRequestEventAction
merged bool
previousMilestone int
configuredMilestone int
expectedMilestone int
}{
{
name: "opened PR on default branch => do nothing",
baseBranch: "master",
prAction: github.PullRequestActionOpened,
expectedMilestone: 0,
configuredMilestone: 1,
},
{
name: "closed (not merged) PR on default branch => do nothing",
baseBranch: "master",
prAction: github.PullRequestActionClosed,
merged: false,
expectedMilestone: 0,
configuredMilestone: 1,
},
{
name: "merged PR but has existing milestone on default branch => apply configured milestone",
baseBranch: "master",
prAction: github.PullRequestActionClosed,
merged: true,
previousMilestone: 1,
configuredMilestone: 2,
expectedMilestone: 2,
},
{
name: "merged PR but already has configured milestone on default branch => do nothing",
baseBranch: "master",
prAction: github.PullRequestActionClosed,
merged: true,
previousMilestone: 2,
configuredMilestone: 2,
expectedMilestone: 2,
},
{
name: "merged PR but does not have existing milestone on default branch => add milestone",
prAction: github.PullRequestActionClosed,
baseBranch: "master",
merged: true,
previousMilestone: 0,
configuredMilestone: 2,
expectedMilestone: 2,
},
{
name: "opened PR on non-default branch => add milestone",
baseBranch: "release-1.0",
prAction: github.PullRequestActionOpened,
configuredMilestone: 1,
expectedMilestone: 1,
},
{
name: "synced PR on non-default branch => do nothing",
baseBranch: "release-1.0",
prAction: github.PullRequestActionSynchronize,
previousMilestone: 0,
configuredMilestone: 1,
expectedMilestone: 0,
},
{
name: "closed (not merged) PR on non-default branch => do nothing",
baseBranch: "release-1.0",
prAction: github.PullRequestActionClosed,
merged: false,
expectedMilestone: 0,
configuredMilestone: 1,
},
{
name: "merged PR but has existing milestone on non-default branch => add configured milestone",
baseBranch: "release-1.0",
prAction: github.PullRequestActionClosed,
merged: true,
previousMilestone: 1,
configuredMilestone: 2,
expectedMilestone: 2,
},
{
name: "merged PR but already has configured milestone on non-default branch => do nothing",
baseBranch: "release-1.0",
prAction: github.PullRequestActionClosed,
merged: true,
previousMilestone: 2,
configuredMilestone: 2,
expectedMilestone: 2,
},
{
name: "merged PR but does not have existing milestone on non-default branch => add milestone",
prAction: github.PullRequestActionClosed,
baseBranch: "release-1.0",
merged: true,
previousMilestone: 0,
configuredMilestone: 1,
expectedMilestone: 1,
},
}
for _, tc := range testcases {
t.Run(tc.name, func(t *testing.T) {
basicPR := github.PullRequest{
Number: 1,
Base: github.PullRequestBranch{
Repo: github.Repo{
Owner: github.User{
Login: "kubernetes",
},
Name: "kubernetes",
DefaultBranch: "master",
},
Ref: tc.baseBranch,
},
}
basicPR.Merged = tc.merged
if tc.previousMilestone != 0 {
basicPR.Milestone = &github.Milestone{
Number: tc.previousMilestone,
}
}
event := github.PullRequestEvent{
Action: tc.prAction,
Number: basicPR.Number,
PullRequest: basicPR,
}
fakeClient := fakegithub.NewFakeClient()
fakeClient.PullRequests = map[int]*github.PullRequest{
basicPR.Number: &basicPR,
}
fakeClient.MilestoneMap = milestonesMap
fakeClient.Milestone = tc.previousMilestone
var configuredMilestoneTitle string
for title, number := range milestonesMap {
if number == tc.configuredMilestone {
configuredMilestoneTitle = title
}
}
if err := handle(fakeClient, logrus.WithField("plugin", pluginName), configuredMilestoneTitle, event); err != nil {
t.Fatalf("(%s): Unexpected error from handle: %v.", tc.name, err)
}
if fakeClient.Milestone != tc.expectedMilestone {
t.Fatalf("%s: expected milestone: %d, received milestone: %d", tc.name, tc.expectedMilestone, fakeClient.Milestone)
}
})
}
}
| cjwagner/test-infra | prow/plugins/milestoneapplier/milestoneapplier_test.go | GO | apache-2.0 | 5,704 |
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with this
* work for additional information regarding copyright ownership. The ASF
* licenses this file to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.apache.zookeeper.server.quorum;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import static org.junit.Assert.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.nio.ByteBuffer;
import java.nio.channels.SelectableChannel;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;
import org.apache.jute.InputArchive;
import org.apache.jute.OutputArchive;
import org.apache.zookeeper.MockPacket;
import org.apache.zookeeper.ZooDefs;
import org.apache.zookeeper.proto.ConnectRequest;
import org.apache.zookeeper.proto.ReplyHeader;
import org.apache.zookeeper.proto.RequestHeader;
import org.apache.zookeeper.proto.SetWatches;
import org.apache.zookeeper.server.MockNIOServerCnxn;
import org.apache.zookeeper.server.NIOServerCnxn;
import org.apache.zookeeper.server.NIOServerCnxnFactory;
import org.apache.zookeeper.server.MockSelectorThread;
import org.apache.zookeeper.server.ZKDatabase;
import org.apache.zookeeper.server.ZooTrace;
import org.apache.zookeeper.server.persistence.FileTxnSnapLog;
import org.junit.Test;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Demonstrate ZOOKEEPER-1382 : Watches leak on expired session
*/
@RunWith(Parameterized.class)
public class WatchLeakTest {
protected static final Logger LOG = LoggerFactory
.getLogger(WatchLeakTest.class);
final long SESSION_ID = 0xBABEL;
private final boolean sessionTimedout;
public WatchLeakTest(boolean sessionTimedout) {
this.sessionTimedout = sessionTimedout;
}
@Parameters
public static Collection<Object[]> configs() {
return Arrays.asList(new Object[][] {
{ false }, { true },
});
}
/**
* Check that if session has expired then no watch can be set
*/
@Test
public void testWatchesLeak() throws Exception {
NIOServerCnxnFactory serverCnxnFactory = mock(NIOServerCnxnFactory.class);
final SelectionKey sk = new FakeSK();
MockSelectorThread selectorThread = mock(MockSelectorThread.class);
when(selectorThread.addInterestOpsUpdateRequest(any(SelectionKey.class))).thenAnswer(new Answer<Boolean>() {
@Override
public Boolean answer(InvocationOnMock invocation) throws Throwable {
SelectionKey sk = (SelectionKey)invocation.getArguments()[0];
NIOServerCnxn nioSrvCnx = (NIOServerCnxn)sk.attachment();
sk.interestOps(nioSrvCnx.getInterestOps());
return true;
}
});
ZKDatabase database = new ZKDatabase(null);
database.setlastProcessedZxid(2L);
QuorumPeer quorumPeer = mock(QuorumPeer.class);
FileTxnSnapLog logfactory = mock(FileTxnSnapLog.class);
// Directories are not used but we need it to avoid NPE
when(logfactory.getDataDir()).thenReturn(new File(""));
when(logfactory.getSnapDir()).thenReturn(new File(""));
FollowerZooKeeperServer fzks = null;
try {
// Create a new follower
fzks = new FollowerZooKeeperServer(logfactory, quorumPeer, database);
fzks.startup();
fzks.setServerCnxnFactory(serverCnxnFactory);
quorumPeer.follower = new MyFollower(quorumPeer, fzks);
LOG.info("Follower created");
// Simulate a socket channel between a client and a follower
final SocketChannel socketChannel = createClientSocketChannel();
// Create the NIOServerCnxn that will handle the client requests
final MockNIOServerCnxn nioCnxn = new MockNIOServerCnxn(fzks,
socketChannel, sk, serverCnxnFactory, selectorThread);
sk.attach(nioCnxn);
// Send the connection request as a client do
nioCnxn.doIO(sk);
LOG.info("Client connection sent");
// Send the valid or invalid session packet to the follower
QuorumPacket qp = createValidateSessionPacketResponse(!sessionTimedout);
quorumPeer.follower.processPacket(qp);
LOG.info("Session validation sent");
// OK, now the follower knows that the session is valid or invalid, let's try
// to send the watches
nioCnxn.doIO(sk);
// wait for the the request processor to do his job
Thread.sleep(1000L);
LOG.info("Watches processed");
// If session has not been validated, there must be NO watches
int watchCount = database.getDataTree().getWatchCount();
if (sessionTimedout) {
// Session has not been re-validated !
LOG.info("session is not valid, watches = {}", watchCount);
assertEquals("Session is not valid so there should be no watches", 0, watchCount);
} else {
// Session has been re-validated
LOG.info("session is valid, watches = {}", watchCount);
assertEquals("Session is valid so the watch should be there", 1, watchCount);
}
} finally {
if (fzks != null) {
fzks.shutdown();
}
}
}
/**
* A follower with no real leader connection
*/
public static class MyFollower extends Follower {
/**
* Create a follower with a mocked leader connection
*
* @param self
* @param zk
*/
MyFollower(QuorumPeer self, FollowerZooKeeperServer zk) {
super(self, zk);
leaderOs = mock(OutputArchive.class);
leaderIs = mock(InputArchive.class);
bufferedOutput = mock(BufferedOutputStream.class);
}
}
/**
* Simulate the behavior of a real selection key
*/
private static class FakeSK extends SelectionKey {
@Override
public SelectableChannel channel() {
return null;
}
@Override
public Selector selector() {
return mock(Selector.class);
}
@Override
public boolean isValid() {
return true;
}
@Override
public void cancel() {
}
@Override
public int interestOps() {
return ops;
}
private int ops = OP_WRITE + OP_READ;
@Override
public SelectionKey interestOps(int ops) {
this.ops = ops;
return this;
}
@Override
public int readyOps() {
boolean reading = (ops & OP_READ) != 0;
boolean writing = (ops & OP_WRITE) != 0;
if (reading && writing) {
LOG.info("Channel is ready for reading and writing");
} else if (reading) {
LOG.info("Channel is ready for reading only");
} else if (writing) {
LOG.info("Channel is ready for writing only");
}
return ops;
}
}
/**
* Create a watches message with a single watch on /
*
* @return a message that attempts to set 1 watch on /
*/
private ByteBuffer createWatchesMessage() {
List<String> dataWatches = new ArrayList<String>(1);
dataWatches.add("/");
List<String> existWatches = Collections.emptyList();
List<String> childWatches = Collections.emptyList();
SetWatches sw = new SetWatches(1L, dataWatches, existWatches,
childWatches);
RequestHeader h = new RequestHeader();
h.setType(ZooDefs.OpCode.setWatches);
h.setXid(-8);
MockPacket p = new MockPacket(h, new ReplyHeader(), sw, null, null);
return p.createAndReturnBB();
}
/**
* This is the secret that we use to generate passwords, for the moment it
* is more of a sanity check.
*/
static final private long superSecret = 0XB3415C00L;
/**
* Create a connection request
*
* @return a serialized connection request
*/
private ByteBuffer createConnRequest() {
Random r = new Random(SESSION_ID ^ superSecret);
byte p[] = new byte[16];
r.nextBytes(p);
ConnectRequest conReq = new ConnectRequest(0, 1L, 30000, SESSION_ID, p);
MockPacket packet = new MockPacket(null, null, conReq, null, null, false);
return packet.createAndReturnBB();
}
/**
* Mock a client channel with a connection request and a watches message
* inside.
*
* @return a socket channel
* @throws IOException
*/
private SocketChannel createClientSocketChannel() throws IOException {
SocketChannel socketChannel = mock(SocketChannel.class);
Socket socket = mock(Socket.class);
InetSocketAddress socketAddress = new InetSocketAddress(1234);
when(socket.getRemoteSocketAddress()).thenReturn(socketAddress);
when(socketChannel.socket()).thenReturn(socket);
// Send watches packet to server connection
final ByteBuffer connRequest = createConnRequest();
final ByteBuffer watchesMessage = createWatchesMessage();
final ByteBuffer request = ByteBuffer.allocate(connRequest.limit()
+ watchesMessage.limit());
request.put(connRequest);
request.put(watchesMessage);
Answer<Integer> answer = new Answer<Integer>() {
int i = 0;
@Override
public Integer answer(InvocationOnMock invocation) throws Throwable {
Object[] args = invocation.getArguments();
ByteBuffer bb = (ByteBuffer) args[0];
for (int k = 0; k < bb.limit(); k++) {
bb.put(request.get(i));
i = i + 1;
}
return bb.limit();
}
};
when(socketChannel.read(any(ByteBuffer.class))).thenAnswer(answer);
return socketChannel;
}
/**
* Forge an invalid session packet as a LEADER do
*
* @param valid <code>true</code> to create a valid session message
*
* @throws Exception
*/
private QuorumPacket createValidateSessionPacketResponse(boolean valid) throws Exception {
QuorumPacket qp = createValidateSessionPacket();
ByteArrayInputStream bis = new ByteArrayInputStream(qp.getData());
DataInputStream dis = new DataInputStream(bis);
long id = dis.readLong();
ByteArrayOutputStream bos = new ByteArrayOutputStream();
DataOutputStream dos = new DataOutputStream(bos);
dos.writeLong(id);
// false means that the session has expired
dos.writeBoolean(valid);
qp.setData(bos.toByteArray());
return qp;
}
/**
* Forge an validate session packet as a LEARNER do
*
* @return
* @throws Exception
*/
private QuorumPacket createValidateSessionPacket() throws Exception {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
DataOutputStream dos = new DataOutputStream(baos);
dos.writeLong(SESSION_ID);
dos.writeInt(3000);
dos.close();
QuorumPacket qp = new QuorumPacket(Leader.REVALIDATE, -1,
baos.toByteArray(), null);
return qp;
}
}
| bit1129/open-source-projects | src/java/test/org/apache/zookeeper/server/quorum/WatchLeakTest.java | Java | apache-2.0 | 12,847 |
/*
* Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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.
*/
/*
* Do not modify this file. This file is generated from the dynamodb-2012-08-10.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Text;
using System.Xml.Serialization;
using Amazon.DynamoDBv2.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
using ThirdParty.Json.LitJson;
namespace Amazon.DynamoDBv2.Model.Internal.MarshallTransformations
{
/// <summary>
/// GlobalSecondaryIndex Marshaller
/// </summary>
public class GlobalSecondaryIndexMarshaller : IRequestMarshaller<GlobalSecondaryIndex, JsonMarshallerContext>
{
public void Marshall(GlobalSecondaryIndex requestObject, JsonMarshallerContext context)
{
if(requestObject.IsSetIndexName())
{
context.Writer.WritePropertyName("IndexName");
context.Writer.Write(requestObject.IndexName);
}
if(requestObject.IsSetKeySchema())
{
context.Writer.WritePropertyName("KeySchema");
context.Writer.WriteArrayStart();
foreach(var requestObjectKeySchemaListValue in requestObject.KeySchema)
{
context.Writer.WriteObjectStart();
var marshaller = KeySchemaElementMarshaller.Instance;
marshaller.Marshall(requestObjectKeySchemaListValue, context);
context.Writer.WriteObjectEnd();
}
context.Writer.WriteArrayEnd();
}
if(requestObject.IsSetProjection())
{
context.Writer.WritePropertyName("Projection");
context.Writer.WriteObjectStart();
var marshaller = ProjectionMarshaller.Instance;
marshaller.Marshall(requestObject.Projection, context);
context.Writer.WriteObjectEnd();
}
if(requestObject.IsSetProvisionedThroughput())
{
context.Writer.WritePropertyName("ProvisionedThroughput");
context.Writer.WriteObjectStart();
var marshaller = ProvisionedThroughputMarshaller.Instance;
marshaller.Marshall(requestObject.ProvisionedThroughput, context);
context.Writer.WriteObjectEnd();
}
}
public readonly static GlobalSecondaryIndexMarshaller Instance = new GlobalSecondaryIndexMarshaller();
}
} | ykbarros/aws-sdk-xamarin | AWS.XamarinSDK/AWSSDK_iOS/Amazon.DynamoDBv2/Model/Internal/MarshallTransformations/GlobalSecondaryIndexMarshaller.cs | C# | apache-2.0 | 3,183 |
-- +goose Up
-- SQL in section 'Up' is executed when this migration is applied
alter table deliveryservice add logs_enabled tinyint(1);
-- +goose Down
-- SQL section 'Down' is executed when this migration is rolled back
alter table deliveryservice drop column logs_enabled;
| smalenfant/traffic_control | traffic_ops/app/db/migrations/20160603084204_add_logs_enabled.sql | SQL | apache-2.0 | 278 |
// Copyright John Maddock 2008.
// Use, modification and distribution are subject to the
// Boost Software License, Version 1.0. (See accompanying file
// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
# include <pch.hpp>
#ifndef BOOST_MATH_TR1_SOURCE
# define BOOST_MATH_TR1_SOURCE
#endif
#include <boost/math/tr1.hpp>
#include <boost/math/special_functions/next.hpp>
#include "c_policy.hpp"
namespace boost{ namespace math{ namespace tr1{
extern "C" long double BOOST_MATH_TR1_DECL boost_nexttowardl BOOST_PREVENT_MACRO_SUBSTITUTION(long double x, long double y) BOOST_MATH_C99_THROW_SPEC
{
return c_policies::nextafter BOOST_PREVENT_MACRO_SUBSTITUTION(x, y);
}
}}}
| flingone/frameworks_base_cmds_remoted | libs/boost/libs/math/src/tr1/nexttowardl.cpp | C++ | apache-2.0 | 727 |
"""Support for MySensors covers."""
from homeassistant.components import mysensors
from homeassistant.components.cover import ATTR_POSITION, DOMAIN, CoverDevice
from homeassistant.const import STATE_OFF, STATE_ON
async def async_setup_platform(
hass, config, async_add_entities, discovery_info=None):
"""Set up the mysensors platform for covers."""
mysensors.setup_mysensors_platform(
hass, DOMAIN, discovery_info, MySensorsCover,
async_add_entities=async_add_entities)
class MySensorsCover(mysensors.device.MySensorsEntity, CoverDevice):
"""Representation of the value of a MySensors Cover child node."""
@property
def assumed_state(self):
"""Return True if unable to access real state of entity."""
return self.gateway.optimistic
@property
def is_closed(self):
"""Return True if cover is closed."""
set_req = self.gateway.const.SetReq
if set_req.V_DIMMER in self._values:
return self._values.get(set_req.V_DIMMER) == 0
return self._values.get(set_req.V_LIGHT) == STATE_OFF
@property
def current_cover_position(self):
"""Return current position of cover.
None is unknown, 0 is closed, 100 is fully open.
"""
set_req = self.gateway.const.SetReq
return self._values.get(set_req.V_DIMMER)
async def async_open_cover(self, **kwargs):
"""Move the cover up."""
set_req = self.gateway.const.SetReq
self.gateway.set_child_value(
self.node_id, self.child_id, set_req.V_UP, 1)
if self.gateway.optimistic:
# Optimistically assume that cover has changed state.
if set_req.V_DIMMER in self._values:
self._values[set_req.V_DIMMER] = 100
else:
self._values[set_req.V_LIGHT] = STATE_ON
self.async_schedule_update_ha_state()
async def async_close_cover(self, **kwargs):
"""Move the cover down."""
set_req = self.gateway.const.SetReq
self.gateway.set_child_value(
self.node_id, self.child_id, set_req.V_DOWN, 1)
if self.gateway.optimistic:
# Optimistically assume that cover has changed state.
if set_req.V_DIMMER in self._values:
self._values[set_req.V_DIMMER] = 0
else:
self._values[set_req.V_LIGHT] = STATE_OFF
self.async_schedule_update_ha_state()
async def async_set_cover_position(self, **kwargs):
"""Move the cover to a specific position."""
position = kwargs.get(ATTR_POSITION)
set_req = self.gateway.const.SetReq
self.gateway.set_child_value(
self.node_id, self.child_id, set_req.V_DIMMER, position)
if self.gateway.optimistic:
# Optimistically assume that cover has changed state.
self._values[set_req.V_DIMMER] = position
self.async_schedule_update_ha_state()
async def async_stop_cover(self, **kwargs):
"""Stop the device."""
set_req = self.gateway.const.SetReq
self.gateway.set_child_value(
self.node_id, self.child_id, set_req.V_STOP, 1)
| MartinHjelmare/home-assistant | homeassistant/components/mysensors/cover.py | Python | apache-2.0 | 3,195 |
/*
* Copyright 2012-2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.boot.cli.command.shell;
import java.io.IOException;
import java.util.Arrays;
import java.util.Collection;
import org.springframework.boot.cli.command.AbstractCommand;
import org.springframework.boot.cli.command.Command;
import org.springframework.boot.cli.command.status.ExitStatus;
import org.springframework.boot.loader.tools.RunProcess;
import org.springframework.util.StringUtils;
/**
* Special {@link Command} used to run a process from the shell. NOTE: this command is not
* directly installed into the shell.
*
* @author Phillip Webb
*/
class RunProcessCommand extends AbstractCommand {
private final String[] command;
private volatile RunProcess process;
RunProcessCommand(String... command) {
super(null, null);
this.command = command;
}
@Override
public ExitStatus run(String... args) throws Exception {
return run(Arrays.asList(args));
}
protected ExitStatus run(Collection<String> args) throws IOException {
this.process = new RunProcess(this.command);
int code = this.process.run(true, StringUtils.toStringArray(args));
if (code == 0) {
return ExitStatus.OK;
}
else {
return new ExitStatus(code, "EXTERNAL_ERROR");
}
}
public boolean handleSigInt() {
return this.process.handleSigInt();
}
}
| hello2009chen/spring-boot | spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/shell/RunProcessCommand.java | Java | apache-2.0 | 1,906 |
"""Tests for Airly."""
| nkgilley/home-assistant | tests/components/airly/__init__.py | Python | apache-2.0 | 23 |
/**
* This class is generated by jOOQ
*/
package io.cattle.platform.core.model.tables;
/**
* This class is generated by jOOQ.
*/
@javax.annotation.Generated(value = { "http://www.jooq.org", "3.3.0" },
comments = "This class is generated by jOOQ")
@java.lang.SuppressWarnings({ "all", "unchecked", "rawtypes" })
public class AgentTable extends org.jooq.impl.TableImpl<io.cattle.platform.core.model.tables.records.AgentRecord> {
private static final long serialVersionUID = -328097319;
/**
* The singleton instance of <code>cattle.agent</code>
*/
public static final io.cattle.platform.core.model.tables.AgentTable AGENT = new io.cattle.platform.core.model.tables.AgentTable();
/**
* The class holding records for this type
*/
@Override
public java.lang.Class<io.cattle.platform.core.model.tables.records.AgentRecord> getRecordType() {
return io.cattle.platform.core.model.tables.records.AgentRecord.class;
}
/**
* The column <code>cattle.agent.id</code>.
*/
public final org.jooq.TableField<io.cattle.platform.core.model.tables.records.AgentRecord, java.lang.Long> ID = createField("id", org.jooq.impl.SQLDataType.BIGINT.nullable(false), this, "");
/**
* The column <code>cattle.agent.name</code>.
*/
public final org.jooq.TableField<io.cattle.platform.core.model.tables.records.AgentRecord, java.lang.String> NAME = createField("name", org.jooq.impl.SQLDataType.VARCHAR.length(255), this, "");
/**
* The column <code>cattle.agent.account_id</code>.
*/
public final org.jooq.TableField<io.cattle.platform.core.model.tables.records.AgentRecord, java.lang.Long> ACCOUNT_ID = createField("account_id", org.jooq.impl.SQLDataType.BIGINT, this, "");
/**
* The column <code>cattle.agent.kind</code>.
*/
public final org.jooq.TableField<io.cattle.platform.core.model.tables.records.AgentRecord, java.lang.String> KIND = createField("kind", org.jooq.impl.SQLDataType.VARCHAR.length(255).nullable(false), this, "");
/**
* The column <code>cattle.agent.uuid</code>.
*/
public final org.jooq.TableField<io.cattle.platform.core.model.tables.records.AgentRecord, java.lang.String> UUID = createField("uuid", org.jooq.impl.SQLDataType.VARCHAR.length(128).nullable(false), this, "");
/**
* The column <code>cattle.agent.description</code>.
*/
public final org.jooq.TableField<io.cattle.platform.core.model.tables.records.AgentRecord, java.lang.String> DESCRIPTION = createField("description", org.jooq.impl.SQLDataType.VARCHAR.length(1024), this, "");
/**
* The column <code>cattle.agent.state</code>.
*/
public final org.jooq.TableField<io.cattle.platform.core.model.tables.records.AgentRecord, java.lang.String> STATE = createField("state", org.jooq.impl.SQLDataType.VARCHAR.length(128).nullable(false), this, "");
/**
* The column <code>cattle.agent.created</code>.
*/
public final org.jooq.TableField<io.cattle.platform.core.model.tables.records.AgentRecord, java.util.Date> CREATED = createField("created", org.jooq.impl.SQLDataType.TIMESTAMP.asConvertedDataType(new io.cattle.platform.db.jooq.converter.DateConverter()), this, "");
/**
* The column <code>cattle.agent.removed</code>.
*/
public final org.jooq.TableField<io.cattle.platform.core.model.tables.records.AgentRecord, java.util.Date> REMOVED = createField("removed", org.jooq.impl.SQLDataType.TIMESTAMP.asConvertedDataType(new io.cattle.platform.db.jooq.converter.DateConverter()), this, "");
/**
* The column <code>cattle.agent.remove_time</code>.
*/
public final org.jooq.TableField<io.cattle.platform.core.model.tables.records.AgentRecord, java.util.Date> REMOVE_TIME = createField("remove_time", org.jooq.impl.SQLDataType.TIMESTAMP.asConvertedDataType(new io.cattle.platform.db.jooq.converter.DateConverter()), this, "");
/**
* The column <code>cattle.agent.data</code>.
*/
public final org.jooq.TableField<io.cattle.platform.core.model.tables.records.AgentRecord, java.util.Map<String,Object>> DATA = createField("data", org.jooq.impl.SQLDataType.CLOB.length(16777215).asConvertedDataType(new io.cattle.platform.db.jooq.converter.DataConverter()), this, "");
/**
* The column <code>cattle.agent.uri</code>.
*/
public final org.jooq.TableField<io.cattle.platform.core.model.tables.records.AgentRecord, java.lang.String> URI = createField("uri", org.jooq.impl.SQLDataType.VARCHAR.length(255), this, "");
/**
* The column <code>cattle.agent.managed_config</code>.
*/
public final org.jooq.TableField<io.cattle.platform.core.model.tables.records.AgentRecord, java.lang.Boolean> MANAGED_CONFIG = createField("managed_config", org.jooq.impl.SQLDataType.BIT.nullable(false).defaulted(true), this, "");
/**
* The column <code>cattle.agent.agent_group_id</code>.
*/
public final org.jooq.TableField<io.cattle.platform.core.model.tables.records.AgentRecord, java.lang.Long> AGENT_GROUP_ID = createField("agent_group_id", org.jooq.impl.SQLDataType.BIGINT, this, "");
/**
* The column <code>cattle.agent.zone_id</code>.
*/
public final org.jooq.TableField<io.cattle.platform.core.model.tables.records.AgentRecord, java.lang.Long> ZONE_ID = createField("zone_id", org.jooq.impl.SQLDataType.BIGINT, this, "");
/**
* Create a <code>cattle.agent</code> table reference
*/
public AgentTable() {
this("agent", null);
}
/**
* Create an aliased <code>cattle.agent</code> table reference
*/
public AgentTable(java.lang.String alias) {
this(alias, io.cattle.platform.core.model.tables.AgentTable.AGENT);
}
private AgentTable(java.lang.String alias, org.jooq.Table<io.cattle.platform.core.model.tables.records.AgentRecord> aliased) {
this(alias, aliased, null);
}
private AgentTable(java.lang.String alias, org.jooq.Table<io.cattle.platform.core.model.tables.records.AgentRecord> aliased, org.jooq.Field<?>[] parameters) {
super(alias, io.cattle.platform.core.model.CattleTable.CATTLE, aliased, parameters, "");
}
/**
* {@inheritDoc}
*/
@Override
public org.jooq.Identity<io.cattle.platform.core.model.tables.records.AgentRecord, java.lang.Long> getIdentity() {
return io.cattle.platform.core.model.Keys.IDENTITY_AGENT;
}
/**
* {@inheritDoc}
*/
@Override
public org.jooq.UniqueKey<io.cattle.platform.core.model.tables.records.AgentRecord> getPrimaryKey() {
return io.cattle.platform.core.model.Keys.KEY_AGENT_PRIMARY;
}
/**
* {@inheritDoc}
*/
@Override
public java.util.List<org.jooq.UniqueKey<io.cattle.platform.core.model.tables.records.AgentRecord>> getKeys() {
return java.util.Arrays.<org.jooq.UniqueKey<io.cattle.platform.core.model.tables.records.AgentRecord>>asList(io.cattle.platform.core.model.Keys.KEY_AGENT_PRIMARY, io.cattle.platform.core.model.Keys.KEY_AGENT_IDX_AGENT_UUID);
}
/**
* {@inheritDoc}
*/
@Override
public java.util.List<org.jooq.ForeignKey<io.cattle.platform.core.model.tables.records.AgentRecord, ?>> getReferences() {
return java.util.Arrays.<org.jooq.ForeignKey<io.cattle.platform.core.model.tables.records.AgentRecord, ?>>asList(io.cattle.platform.core.model.Keys.FK_AGENT__ACCOUNT_ID, io.cattle.platform.core.model.Keys.FK_AGENT__AGENT_GROUP_ID, io.cattle.platform.core.model.Keys.FK_AGENT__ZONE_ID);
}
/**
* {@inheritDoc}
*/
@Override
public io.cattle.platform.core.model.tables.AgentTable as(java.lang.String alias) {
return new io.cattle.platform.core.model.tables.AgentTable(alias, this);
}
/**
* Rename this table
*/
public io.cattle.platform.core.model.tables.AgentTable rename(java.lang.String name) {
return new io.cattle.platform.core.model.tables.AgentTable(name, null);
}
}
| sonchang/cattle | code/iaas/model/src/main/java/io/cattle/platform/core/model/tables/AgentTable.java | Java | apache-2.0 | 7,604 |
/*
* Version.h
*
* Created on: Mar 9, 2017
* Author: eski
*/
#ifndef INC_VERSION_H_
#define INC_VERSION_H_
#define SDK_VERSION "2.0"
#endif /* INC_VERSION_H_ */
| commoninvestor/NanoleafHackathon | Examples/WeirdWheel/inc/Version.h | C | apache-2.0 | 177 |
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 1.0 Transitional//EN">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel="stylesheet" href="../includes/main.css" type="text/css">
<link rel="shortcut icon" href="../favicon.ico" type="image/x-icon">
<title>Apache CloudStack | The Power Behind Your Cloud</title>
</head>
<body>
<div id="insidetopbg">
<div id="inside_wrapper">
<div class="uppermenu_panel">
<div class="uppermenu_box"></div>
</div>
<div id="main_master">
<div id="inside_header">
<div class="header_top">
<a class="cloud_logo" href="http://cloudstack.org"></a>
<div class="mainemenu_panel"></div>
</div>
</div>
<div id="main_content">
<div class="inside_apileftpanel">
<div class="inside_contentpanel" style="width:930px;">
<div class="api_titlebox">
<div class="api_titlebox_left">
<span>
Apache CloudStack v4.2.0 User API Reference
</span>
<p></p>
<h1>deleteVpnCustomerGateway</h1>
<p>Delete site to site vpn customer gateway</p>
</div>
<div class="api_titlebox_right">
<a class="api_backbutton" href="../TOC_User.html"></a>
</div>
</div>
<div class="api_tablepanel">
<h2>Request parameters</h2>
<table class="apitable">
<tr class="hed">
<td style="width:200px;"><strong>Parameter Name</strong></td><td style="width:500px;">Description</td><td style="width:180px;">Required</td>
</tr>
<tr>
<td style="width:200px;"><strong>id</strong></td><td style="width:500px;"><strong>id of customer gateway</strong></td><td style="width:180px;"><strong>true</strong></td>
</tr>
</table>
</div>
<div class="api_tablepanel">
<h2>Response Tags</h2>
<table class="apitable">
<tr class="hed">
<td style="width:200px;"><strong>Response Name</strong></td><td style="width:500px;">Description</td>
</tr>
<tr>
<td style="width:200px;"><strong>displaytext</strong></td><td style="width:500px;">any text associated with the success or failure</td>
</tr>
<tr>
<td style="width:200px;"><strong>success</strong></td><td style="width:500px;">true if operation is executed successfully</td>
</tr>
</table>
</div>
</div>
</div>
</div>
</div>
<div id="footer">
<div id="footer_mainmaster">
<p>Copyright © 2013 The Apache Software Foundation, Licensed under the
<a href="http://www.apache.org/licenses/LICENSE-2.0">Apache License, Version 2.0.</a>
<br>
Apache, CloudStack, Apache CloudStack, the Apache CloudStack logo, the CloudMonkey logo and the Apache feather logo are trademarks of The Apache Software Foundation.</p>
</div>
</div>
</div>
</div>
</body>
</html>
| resmo/cloudstack-www | source/api/apidocs-4.2/user/deleteVpnCustomerGateway.html | HTML | apache-2.0 | 2,649 |
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 1.0 Transitional//EN">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel="stylesheet" href="../includes/main.css" type="text/css">
<link rel="shortcut icon" href="../favicon.ico" type="image/x-icon">
<title>Apache CloudStack | The Power Behind Your Cloud</title>
</head>
<body>
<div id="insidetopbg">
<div id="inside_wrapper">
<div class="uppermenu_panel">
<div class="uppermenu_box"></div>
</div>
<div id="main_master">
<div id="inside_header">
<div class="header_top">
<a class="cloud_logo" href="http://cloudstack.org"></a>
<div class="mainemenu_panel"></div>
</div>
</div>
<div id="main_content">
<div class="inside_apileftpanel">
<div class="inside_contentpanel" style="width:930px;">
<div class="api_titlebox">
<div class="api_titlebox_left">
<span>
Apache CloudStack v4.4.1 User API Reference
</span>
<p></p>
<h1>deleteIso</h1>
<p>Deletes an ISO file.</p>
</div>
<div class="api_titlebox_right">
<a class="api_backbutton" href="../TOC_User.html"></a>
</div>
</div>
<div class="api_tablepanel">
<h2>Request parameters</h2>
<table class="apitable">
<tr class="hed">
<td style="width:200px;"><strong>Parameter Name</strong></td><td style="width:500px;">Description</td><td style="width:180px;">Required</td>
</tr>
<tr>
<td style="width:200px;"><strong>id</strong></td><td style="width:500px;"><strong>the ID of the ISO file</strong></td><td style="width:180px;"><strong>true</strong></td>
</tr>
<tr>
<td style="width:200px;"><i>zoneid</i></td><td style="width:500px;"><i>the ID of the zone of the ISO file. If not specified, the ISO will be deleted from all the zones</i></td><td style="width:180px;"><i>false</i></td>
</tr>
</table>
</div>
<div class="api_tablepanel">
<h2>Response Tags</h2>
<table class="apitable">
<tr class="hed">
<td style="width:200px;"><strong>Response Name</strong></td><td style="width:500px;">Description</td>
</tr>
<tr>
<td style="width:200px;"><strong>displaytext</strong></td><td style="width:500px;">any text associated with the success or failure</td>
</tr>
<tr>
<td style="width:200px;"><strong>success</strong></td><td style="width:500px;">true if operation is executed successfully</td>
</tr>
</table>
</div>
</div>
</div>
</div>
</div>
<div id="footer">
<div id="footer_mainmaster">
<p>Copyright © 2014 The Apache Software Foundation, Licensed under the
<a href="http://www.apache.org/licenses/LICENSE-2.0">Apache License, Version 2.0.</a>
<br>
Apache, CloudStack, Apache CloudStack, the Apache CloudStack logo, the CloudMonkey logo and the Apache feather logo are trademarks of The Apache Software Foundation.</p>
</div>
</div>
</div>
</div>
</body>
</html>
| resmo/cloudstack-www | source/api/apidocs-4.4/user/deleteIso.html | HTML | apache-2.0 | 2,844 |
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.presto.ml;
import com.facebook.presto.operator.scalar.AbstractTestFunctions;
import org.testng.annotations.BeforeClass;
import static com.facebook.presto.metadata.FunctionExtractor.extractFunctions;
abstract class AbstractTestMLFunctions
extends AbstractTestFunctions
{
@BeforeClass
protected void registerFunctions()
{
functionAssertions.getMetadata().registerBuiltInFunctions(
extractFunctions(new MLPlugin().getFunctions()));
}
}
| prestodb/presto | presto-ml/src/test/java/com/facebook/presto/ml/AbstractTestMLFunctions.java | Java | apache-2.0 | 1,068 |
/*
*
* 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.
*
*/
/* CSS file */
global {
chromeColor: #9999FF;
contentBackgroundColor: #CC9966;
symbolColor: #66FF00;
selectionColor: #0099FF;
rollOverColor: #FF9933;
focusColor: #009900;
focusedTextSelectionColor: #0099FF;
}
| adufilie/flex-sdk | mustella/tests/Managers/StyleManager/SparkStyles/SWFs/assets/globalStyles2.css | CSS | apache-2.0 | 1,045 |
/*
* Copyright 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Author: morlovich@google.com (Maksim Orlovich)
//
// A wrapper around PthreadThreadSystem that takes care of some signal masking
// issues that arise in forking servers. We prefer pthreads to APR as APR
// mutex, etc., creation requires pools which are generally thread unsafe,
// introducing some additional risks.
#ifndef PAGESPEED_SYSTEM_SYSTEM_THREAD_SYSTEM_H_
#define PAGESPEED_SYSTEM_SYSTEM_THREAD_SYSTEM_H_
#include "pagespeed/kernel/base/basictypes.h"
#include "pagespeed/kernel/thread/pthread_thread_system.h"
namespace net_instaweb {
class SystemThreadSystem : public PthreadThreadSystem {
public:
SystemThreadSystem();
virtual ~SystemThreadSystem();
// It's not safe to start threads in a process that will later fork. In order
// to enforce this, call PermitThreadStarting() in the child process right
// after forking, and DCHECK-fail if something tries to start a thread before
// then.
void PermitThreadStarting();
protected:
virtual void BeforeThreadRunHook();
private:
bool may_start_threads_;
DISALLOW_COPY_AND_ASSIGN(SystemThreadSystem);
};
} // namespace net_instaweb
#endif // PAGESPEED_SYSTEM_SYSTEM_THREAD_SYSTEM_H_
| ajayanandgit/mod_pagespeed | pagespeed/system/system_thread_system.h | C | apache-2.0 | 1,776 |
import { expect } from 'chai';
import parse from 'url-parse';
import { buildDfpVideoUrl, buildAdpodVideoUrl } from 'modules/dfpAdServerVideo.js';
import adUnit from 'test/fixtures/video/adUnit.json';
import * as utils from 'src/utils.js';
import { config } from 'src/config.js';
import { targeting } from 'src/targeting.js';
import { auctionManager } from 'src/auctionManager.js';
import { gdprDataHandler, uspDataHandler } from 'src/adapterManager.js';
import * as adpod from 'modules/adpod.js';
import { server } from 'test/mocks/xhr.js';
const bid = {
videoCacheKey: 'abc',
adserverTargeting: {
hb_uuid: 'abc',
hb_cache_id: 'abc',
},
};
describe('The DFP video support module', function () {
it('should make a legal request URL when given the required params', function () {
const url = parse(buildDfpVideoUrl({
adUnit: adUnit,
bid: bid,
params: {
'iu': 'my/adUnit',
'description_url': 'someUrl.com',
}
}));
expect(url.protocol).to.equal('https:');
expect(url.host).to.equal('securepubads.g.doubleclick.net');
const queryParams = utils.parseQS(url.query);
expect(queryParams).to.have.property('correlator');
expect(queryParams).to.have.property('description_url', 'someUrl.com');
expect(queryParams).to.have.property('env', 'vp');
expect(queryParams).to.have.property('gdfp_req', '1');
expect(queryParams).to.have.property('iu', 'my/adUnit');
expect(queryParams).to.have.property('output', 'vast');
expect(queryParams).to.have.property('sz', '640x480');
expect(queryParams).to.have.property('unviewed_position_start', '1');
expect(queryParams).to.have.property('url');
});
it('can take an adserver url as a parameter', function () {
const bidCopy = utils.deepClone(bid);
bidCopy.vastUrl = 'vastUrl.example';
const url = parse(buildDfpVideoUrl({
adUnit: adUnit,
bid: bidCopy,
url: 'https://video.adserver.example/',
}));
expect(url.host).to.equal('video.adserver.example');
const queryObject = utils.parseQS(url.query);
expect(queryObject.description_url).to.equal('vastUrl.example');
});
it('requires a params object or url', function () {
const url = buildDfpVideoUrl({
adUnit: adUnit,
bid: bid,
});
expect(url).to.be.undefined;
});
it('overwrites url params when both url and params object are given', function () {
const url = parse(buildDfpVideoUrl({
adUnit: adUnit,
bid: bid,
url: 'https://video.adserver.example/ads?sz=640x480&iu=/123/aduniturl&impl=s',
params: { iu: 'my/adUnit' }
}));
const queryObject = utils.parseQS(url.query);
expect(queryObject.iu).to.equal('my/adUnit');
});
it('should override param defaults with user-provided ones', function () {
const url = parse(buildDfpVideoUrl({
adUnit: adUnit,
bid: bid,
params: {
'iu': 'my/adUnit',
'output': 'vast',
}
}));
expect(utils.parseQS(url.query)).to.have.property('output', 'vast');
});
it('should include the cache key and adserver targeting in cust_params', function () {
const bidCopy = utils.deepClone(bid);
bidCopy.adserverTargeting = Object.assign(bidCopy.adserverTargeting, {
hb_adid: 'ad_id',
});
const url = parse(buildDfpVideoUrl({
adUnit: adUnit,
bid: bidCopy,
params: {
'iu': 'my/adUnit'
}
}));
const queryObject = utils.parseQS(url.query);
const customParams = utils.parseQS('?' + decodeURIComponent(queryObject.cust_params));
expect(customParams).to.have.property('hb_adid', 'ad_id');
expect(customParams).to.have.property('hb_uuid', bid.videoCacheKey);
expect(customParams).to.have.property('hb_cache_id', bid.videoCacheKey);
});
it('should include the us_privacy key when USP Consent is available', function () {
let uspDataHandlerStub = sinon.stub(uspDataHandler, 'getConsentData');
uspDataHandlerStub.returns('1YYY');
const bidCopy = utils.deepClone(bid);
bidCopy.adserverTargeting = Object.assign(bidCopy.adserverTargeting, {
hb_adid: 'ad_id',
});
const url = parse(buildDfpVideoUrl({
adUnit: adUnit,
bid: bidCopy,
params: {
'iu': 'my/adUnit'
}
}));
const queryObject = utils.parseQS(url.query);
expect(queryObject.us_privacy).to.equal('1YYY');
uspDataHandlerStub.restore();
});
it('should not include the us_privacy key when USP Consent is not available', function () {
const bidCopy = utils.deepClone(bid);
bidCopy.adserverTargeting = Object.assign(bidCopy.adserverTargeting, {
hb_adid: 'ad_id',
});
const url = parse(buildDfpVideoUrl({
adUnit: adUnit,
bid: bidCopy,
params: {
'iu': 'my/adUnit'
}
}));
const queryObject = utils.parseQS(url.query);
expect(queryObject.us_privacy).to.equal(undefined);
});
it('should include the GDPR keys when GDPR Consent is available', function () {
let gdprDataHandlerStub = sinon.stub(gdprDataHandler, 'getConsentData');
gdprDataHandlerStub.returns({
gdprApplies: true,
consentString: 'consent',
addtlConsent: 'moreConsent'
});
const bidCopy = utils.deepClone(bid);
bidCopy.adserverTargeting = Object.assign(bidCopy.adserverTargeting, {
hb_adid: 'ad_id',
});
const url = parse(buildDfpVideoUrl({
adUnit: adUnit,
bid: bidCopy,
params: {
'iu': 'my/adUnit'
}
}));
const queryObject = utils.parseQS(url.query);
expect(queryObject.gdpr).to.equal('1');
expect(queryObject.gdpr_consent).to.equal('consent');
expect(queryObject.addtl_consent).to.equal('moreConsent');
gdprDataHandlerStub.restore();
});
it('should not include the GDPR keys when GDPR Consent is not available', function () {
const bidCopy = utils.deepClone(bid);
bidCopy.adserverTargeting = Object.assign(bidCopy.adserverTargeting, {
hb_adid: 'ad_id',
});
const url = parse(buildDfpVideoUrl({
adUnit: adUnit,
bid: bidCopy,
params: {
'iu': 'my/adUnit'
}
}));
const queryObject = utils.parseQS(url.query);
expect(queryObject.gdpr).to.equal(undefined);
expect(queryObject.gdpr_consent).to.equal(undefined);
expect(queryObject.addtl_consent).to.equal(undefined);
});
it('should only include the GDPR keys for GDPR Consent fields with values', function () {
let gdprDataHandlerStub = sinon.stub(gdprDataHandler, 'getConsentData');
gdprDataHandlerStub.returns({
gdprApplies: true,
consentString: 'consent',
});
const bidCopy = utils.deepClone(bid);
bidCopy.adserverTargeting = Object.assign(bidCopy.adserverTargeting, {
hb_adid: 'ad_id',
});
const url = parse(buildDfpVideoUrl({
adUnit: adUnit,
bid: bidCopy,
params: {
'iu': 'my/adUnit'
}
}));
const queryObject = utils.parseQS(url.query);
expect(queryObject.gdpr).to.equal('1');
expect(queryObject.gdpr_consent).to.equal('consent');
expect(queryObject.addtl_consent).to.equal(undefined);
gdprDataHandlerStub.restore();
});
describe('special targeting unit test', function () {
const allTargetingData = {
'hb_format': 'video',
'hb_source': 'client',
'hb_size': '640x480',
'hb_pb': '5.00',
'hb_adid': '2c4f6cc3ba128a',
'hb_bidder': 'testBidder2',
'hb_format_testBidder2': 'video',
'hb_source_testBidder2': 'client',
'hb_size_testBidder2': '640x480',
'hb_pb_testBidder2': '5.00',
'hb_adid_testBidder2': '2c4f6cc3ba128a',
'hb_bidder_testBidder2': 'testBidder2',
'hb_format_appnexus': 'video',
'hb_source_appnexus': 'client',
'hb_size_appnexus': '640x480',
'hb_pb_appnexus': '5.00',
'hb_adid_appnexus': '44e0b5f2e5cace',
'hb_bidder_appnexus': 'appnexus'
};
let targetingStub;
before(function () {
targetingStub = sinon.stub(targeting, 'getAllTargeting');
targetingStub.returns({'video1': allTargetingData});
config.setConfig({
enableSendAllBids: true
});
});
after(function () {
config.resetConfig();
targetingStub.restore();
});
it('should include all adserver targeting in cust_params if pbjs.enableSendAllBids is true', function () {
const adUnitsCopy = utils.deepClone(adUnit);
adUnitsCopy.bids.push({
'bidder': 'testBidder2',
'params': {
'placementId': '9333431',
'video': {
'skipppable': false,
'playback_methods': ['auto_play_sound_off']
}
}
});
const bidCopy = utils.deepClone(bid);
bidCopy.adserverTargeting = Object.assign(bidCopy.adserverTargeting, {
hb_adid: 'ad_id',
});
const url = parse(buildDfpVideoUrl({
adUnit: adUnitsCopy,
bid: bidCopy,
params: {
'iu': 'my/adUnit'
}
}));
const queryObject = utils.parseQS(url.query);
const customParams = utils.parseQS('?' + decodeURIComponent(queryObject.cust_params));
expect(customParams).to.have.property('hb_adid', 'ad_id');
expect(customParams).to.have.property('hb_uuid', bid.videoCacheKey);
expect(customParams).to.have.property('hb_cache_id', bid.videoCacheKey);
expect(customParams).to.have.property('hb_bidder_appnexus', 'appnexus');
expect(customParams).to.have.property('hb_bidder_testBidder2', 'testBidder2');
});
});
it('should merge the user-provided cust_params with the default ones', function () {
const bidCopy = utils.deepClone(bid);
bidCopy.adserverTargeting = Object.assign(bidCopy.adserverTargeting, {
hb_adid: 'ad_id',
});
const url = parse(buildDfpVideoUrl({
adUnit: adUnit,
bid: bidCopy,
params: {
'iu': 'my/adUnit',
cust_params: {
'my_targeting': 'foo',
},
},
}));
const queryObject = utils.parseQS(url.query);
const customParams = utils.parseQS('?' + decodeURIComponent(queryObject.cust_params));
expect(customParams).to.have.property('hb_adid', 'ad_id');
expect(customParams).to.have.property('my_targeting', 'foo');
});
it('should merge the user-provided cust-params with the default ones when using url object', function () {
const bidCopy = utils.deepClone(bid);
bidCopy.adserverTargeting = Object.assign(bidCopy.adserverTargeting, {
hb_adid: 'ad_id',
});
const url = parse(buildDfpVideoUrl({
adUnit: adUnit,
bid: bidCopy,
url: 'https://video.adserver.example/ads?sz=640x480&iu=/123/aduniturl&impl=s&cust_params=section%3dblog%26mykey%3dmyvalue'
}));
const queryObject = utils.parseQS(url.query);
const customParams = utils.parseQS('?' + decodeURIComponent(queryObject.cust_params));
expect(customParams).to.have.property('hb_adid', 'ad_id');
expect(customParams).to.have.property('section', 'blog');
expect(customParams).to.have.property('mykey', 'myvalue');
expect(customParams).to.have.property('hb_uuid', 'abc');
expect(customParams).to.have.property('hb_cache_id', 'abc');
});
it('should not overwrite an existing description_url for object input and cache disabled', function () {
const bidCopy = utils.deepClone(bid);
bidCopy.vastUrl = 'vastUrl.example';
const url = parse(buildDfpVideoUrl({
adUnit: adUnit,
bid: bidCopy,
params: {
iu: 'my/adUnit',
description_url: 'descriptionurl.example'
}
}));
const queryObject = utils.parseQS(url.query);
expect(queryObject.description_url).to.equal('descriptionurl.example');
});
it('should work with nobid responses', function () {
const url = buildDfpVideoUrl({
adUnit: adUnit,
params: { 'iu': 'my/adUnit' }
});
expect(url).to.be.a('string');
});
it('should include hb_uuid and hb_cache_id in cust_params when both keys are exluded from overwritten bidderSettings', function () {
const bidCopy = utils.deepClone(bid);
delete bidCopy.adserverTargeting.hb_uuid;
delete bidCopy.adserverTargeting.hb_cache_id;
const url = parse(buildDfpVideoUrl({
adUnit: adUnit,
bid: bidCopy,
params: {
'iu': 'my/adUnit'
}
}));
const queryObject = utils.parseQS(url.query);
const customParams = utils.parseQS('?' + decodeURIComponent(queryObject.cust_params));
expect(customParams).to.have.property('hb_uuid', bid.videoCacheKey);
expect(customParams).to.have.property('hb_cache_id', bid.videoCacheKey);
});
it('should include hb_uuid and hb_cache_id in cust params from overwritten standard bidderSettings', function () {
const bidCopy = utils.deepClone(bid);
bidCopy.adserverTargeting = Object.assign(bidCopy.adserverTargeting, {
hb_uuid: 'def',
hb_cache_id: 'def'
});
const url = parse(buildDfpVideoUrl({
adUnit: adUnit,
bid: bidCopy,
params: {
'iu': 'my/adUnit'
}
}));
const queryObject = utils.parseQS(url.query);
const customParams = utils.parseQS('?' + decodeURIComponent(queryObject.cust_params));
expect(customParams).to.have.property('hb_uuid', 'def');
expect(customParams).to.have.property('hb_cache_id', 'def');
});
describe('adpod unit tests', function () {
let amStub;
let amGetAdUnitsStub;
before(function () {
let adUnits = [{
code: 'adUnitCode-1',
mediaTypes: {
video: {
context: 'adpod',
playerSize: [640, 480],
adPodDurationSec: 60,
durationRangeSec: [15, 30],
requireExactDuration: true
}
},
bids: [
{
bidder: 'appnexus',
params: {
placementId: 14542875,
}
}
]
}];
amGetAdUnitsStub = sinon.stub(auctionManager, 'getAdUnits');
amGetAdUnitsStub.returns(adUnits);
amStub = sinon.stub(auctionManager, 'getBidsReceived');
});
beforeEach(function () {
config.setConfig({
adpod: {
brandCategoryExclusion: true,
deferCaching: false
}
});
})
afterEach(function() {
config.resetConfig();
});
after(function () {
amGetAdUnitsStub.restore();
amStub.restore();
});
it('should return masterTag url', function() {
amStub.returns(getBidsReceived());
let uspDataHandlerStub = sinon.stub(uspDataHandler, 'getConsentData');
uspDataHandlerStub.returns('1YYY');
let gdprDataHandlerStub = sinon.stub(gdprDataHandler, 'getConsentData');
gdprDataHandlerStub.returns({
gdprApplies: true,
consentString: 'consent',
addtlConsent: 'moreConsent'
});
let url;
parse(buildAdpodVideoUrl({
code: 'adUnitCode-1',
callback: handleResponse,
params: {
'iu': 'my/adUnit',
'description_url': 'someUrl.com',
}
}));
function handleResponse(err, masterTag) {
if (err) {
return;
}
url = parse(masterTag);
expect(url.protocol).to.equal('https:');
expect(url.host).to.equal('securepubads.g.doubleclick.net');
const queryParams = utils.parseQS(url.query);
expect(queryParams).to.have.property('correlator');
expect(queryParams).to.have.property('description_url', 'someUrl.com');
expect(queryParams).to.have.property('env', 'vp');
expect(queryParams).to.have.property('gdfp_req', '1');
expect(queryParams).to.have.property('iu', 'my/adUnit');
expect(queryParams).to.have.property('output', 'vast');
expect(queryParams).to.have.property('sz', '640x480');
expect(queryParams).to.have.property('unviewed_position_start', '1');
expect(queryParams).to.have.property('url');
expect(queryParams).to.have.property('cust_params');
expect(queryParams).to.have.property('us_privacy', '1YYY');
expect(queryParams).to.have.property('gdpr', '1');
expect(queryParams).to.have.property('gdpr_consent', 'consent');
expect(queryParams).to.have.property('addtl_consent', 'moreConsent');
const custParams = utils.parseQS(decodeURIComponent(queryParams.cust_params));
expect(custParams).to.have.property('hb_cache_id', '123');
expect(custParams).to.have.property('hb_pb_cat_dur', '15.00_395_15s,15.00_406_30s,10.00_395_15s');
uspDataHandlerStub.restore();
gdprDataHandlerStub.restore();
}
});
it('should return masterTag url with correct custom params when brandCategoryExclusion is false', function() {
config.setConfig({
adpod: {
brandCategoryExclusion: false,
}
});
function getBids() {
let bids = [
createBid(10, 'adUnitCode-1', 15, '10.00_15s', '123', '395', '10.00'),
createBid(15, 'adUnitCode-1', 15, '15.00_15s', '123', '395', '15.00'),
createBid(25, 'adUnitCode-1', 30, '15.00_30s', '123', '406', '25.00'),
];
bids.forEach((bid) => {
delete bid.meta;
});
return bids;
}
amStub.returns(getBids());
let url;
parse(buildAdpodVideoUrl({
code: 'adUnitCode-1',
callback: handleResponse,
params: {
'iu': 'my/adUnit',
'description_url': 'someUrl.com',
}
}));
function handleResponse(err, masterTag) {
if (err) {
return;
}
url = parse(masterTag);
expect(url.protocol).to.equal('https:');
expect(url.host).to.equal('securepubads.g.doubleclick.net');
const queryParams = utils.parseQS(url.query);
expect(queryParams).to.have.property('correlator');
expect(queryParams).to.have.property('description_url', 'someUrl.com');
expect(queryParams).to.have.property('env', 'vp');
expect(queryParams).to.have.property('gdfp_req', '1');
expect(queryParams).to.have.property('iu', 'my/adUnit');
expect(queryParams).to.have.property('output', 'xml_vast3');
expect(queryParams).to.have.property('sz', '640x480');
expect(queryParams).to.have.property('unviewed_position_start', '1');
expect(queryParams).to.have.property('url');
expect(queryParams).to.have.property('cust_params');
const custParams = utils.parseQS(decodeURIComponent(queryParams.cust_params));
expect(custParams).to.have.property('hb_cache_id', '123');
expect(custParams).to.have.property('hb_pb_cat_dur', '10.00_15s,15.00_15s,15.00_30s');
}
});
it('should handle error when cache fails', function() {
config.setConfig({
adpod: {
brandCategoryExclusion: true,
deferCaching: true
}
});
amStub.returns(getBidsReceived());
parse(buildAdpodVideoUrl({
code: 'adUnitCode-1',
callback: handleResponse,
params: {
'iu': 'my/adUnit',
'description_url': 'someUrl.com',
}
}));
server.requests[0].respond(503, {
'Content-Type': 'plain/text',
}, 'The server could not save anything at the moment.');
function handleResponse(err, masterTag) {
expect(masterTag).to.be.null;
expect(err).to.be.an('error');
}
});
})
});
function getBidsReceived() {
return [
createBid(10, 'adUnitCode-1', 15, '10.00_395_15s', '123', '395', '10.00'),
createBid(15, 'adUnitCode-1', 15, '15.00_395_15s', '123', '395', '15.00'),
createBid(25, 'adUnitCode-1', 30, '15.00_406_30s', '123', '406', '25.00'),
]
}
function createBid(cpm, adUnitCode, durationBucket, priceIndustryDuration, uuid, label, hbpb) {
return {
'bidderCode': 'appnexus',
'width': 640,
'height': 360,
'statusMessage': 'Bid available',
'adId': '28f24ced14586c',
'mediaType': 'video',
'source': 'client',
'requestId': '28f24ced14586c',
'cpm': cpm,
'creativeId': 97517771,
'currency': 'USD',
'netRevenue': true,
'ttl': 3600,
'adUnitCode': adUnitCode,
'video': {
'context': 'adpod',
'durationBucket': durationBucket
},
'appnexus': {
'buyerMemberId': 9325
},
'vastUrl': 'http://some-vast-url.com',
'vastImpUrl': 'http://some-vast-imp-url.com',
'auctionId': 'ec266b31-d652-49c5-8295-e83fafe5532b',
'responseTimestamp': 1548442460888,
'requestTimestamp': 1548442460827,
'bidder': 'appnexus',
'timeToRespond': 61,
'pbLg': '5.00',
'pbMg': '5.00',
'pbHg': '5.00',
'pbAg': '5.00',
'pbDg': '5.00',
'pbCg': '',
'size': '640x360',
'adserverTargeting': {
'hb_bidder': 'appnexus',
'hb_adid': '28f24ced14586c',
'hb_pb': hbpb,
'hb_size': '640x360',
'hb_source': 'client',
'hb_format': 'video',
'hb_pb_cat_dur': priceIndustryDuration,
'hb_cache_id': uuid
},
'customCacheKey': `${priceIndustryDuration}_${uuid}`,
'meta': {
'primaryCatId': 'iab-1',
'adServerCatId': label
},
'videoCacheKey': '4cf395af-8fee-4960-af0e-88d44e399f14'
}
}
| prebid/Prebid.js | test/spec/modules/dfpAdServerVideo_spec.js | JavaScript | apache-2.0 | 21,329 |
partial_search Cookbook CHANGELOG
=================================
This file is used to list changes made in each version of the partial_search cookbook.
v1.0.6
------
- **Hotfix** - Revert client-side caching bug
v1.0.4
------
### New Feature
- **[COOK-2584](https://tickets.opscode.com/browse/COOK-2584)** - Add client-side result cache
v1.0.2
------
### Bug
- [COOK-3164]: `partial_search` should use
`Chef::Config[:chef_server_url]` instead of `search_url`
v1.0.0
------
- Initial release
| nfuentes/chef-glassfish-example | partial_search/CHANGELOG.md | Markdown | apache-2.0 | 504 |
# Copyright 2015 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
require 'google/apis/core/base_service'
require 'google/apis/core/json_representation'
require 'google/apis/core/hashable'
require 'google/apis/errors'
module Google
module Apis
module BooksV1
# Books API
#
# Lets you search for books and manage your Google Books library.
#
# @example
# require 'google/apis/books_v1'
#
# Books = Google::Apis::BooksV1 # Alias the module
# service = Books::BooksService.new
#
# @see https://developers.google.com/books/docs/v1/getting_started
class BooksService < Google::Apis::Core::BaseService
# @return [String]
# API key. Your API key identifies your project and provides you with API access,
# quota, and reports. Required unless you provide an OAuth 2.0 token.
attr_accessor :key
# @return [String]
# Available to use for quota purposes for server-side applications. Can be any
# arbitrary string assigned to a user, but should not exceed 40 characters.
# Overrides userIp if both are provided.
attr_accessor :quota_user
# @return [String]
# IP address of the site where the request originates. Use this if you want to
# enforce per-user limits.
attr_accessor :user_ip
def initialize
super('https://www.googleapis.com/', 'books/v1/')
end
# Retrieves metadata for a specific bookshelf for the specified user.
# @param [String] user_id
# ID of user for whom to retrieve bookshelves.
# @param [String] shelf
# ID of bookshelf to retrieve.
# @param [String] source
# String to identify the originator of this request.
# @param [String] fields
# Selector specifying which fields to include in a partial response.
# @param [String] quota_user
# Available to use for quota purposes for server-side applications. Can be any
# arbitrary string assigned to a user, but should not exceed 40 characters.
# Overrides userIp if both are provided.
# @param [String] user_ip
# IP address of the site where the request originates. Use this if you want to
# enforce per-user limits.
# @param [Google::Apis::RequestOptions] options
# Request-specific options
#
# @yield [result, err] Result & error if block supplied
# @yieldparam result [Google::Apis::BooksV1::Bookshelf] parsed result object
# @yieldparam err [StandardError] error object if request failed
#
# @return [Google::Apis::BooksV1::Bookshelf]
#
# @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried
# @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification
# @raise [Google::Apis::AuthorizationError] Authorization is required
def get_bookshelf(user_id, shelf, source: nil, fields: nil, quota_user: nil, user_ip: nil, options: nil, &block)
path = 'users/{userId}/bookshelves/{shelf}'
command = make_simple_command(:get, path, options)
command.response_representation = Google::Apis::BooksV1::Bookshelf::Representation
command.response_class = Google::Apis::BooksV1::Bookshelf
command.params['userId'] = user_id unless user_id.nil?
command.params['shelf'] = shelf unless shelf.nil?
command.query['source'] = source unless source.nil?
command.query['fields'] = fields unless fields.nil?
command.query['quotaUser'] = quota_user unless quota_user.nil?
command.query['userIp'] = user_ip unless user_ip.nil?
execute_or_queue_command(command, &block)
end
# Retrieves a list of public bookshelves for the specified user.
# @param [String] user_id
# ID of user for whom to retrieve bookshelves.
# @param [String] source
# String to identify the originator of this request.
# @param [String] fields
# Selector specifying which fields to include in a partial response.
# @param [String] quota_user
# Available to use for quota purposes for server-side applications. Can be any
# arbitrary string assigned to a user, but should not exceed 40 characters.
# Overrides userIp if both are provided.
# @param [String] user_ip
# IP address of the site where the request originates. Use this if you want to
# enforce per-user limits.
# @param [Google::Apis::RequestOptions] options
# Request-specific options
#
# @yield [result, err] Result & error if block supplied
# @yieldparam result [Google::Apis::BooksV1::Bookshelves] parsed result object
# @yieldparam err [StandardError] error object if request failed
#
# @return [Google::Apis::BooksV1::Bookshelves]
#
# @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried
# @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification
# @raise [Google::Apis::AuthorizationError] Authorization is required
def list_bookshelves(user_id, source: nil, fields: nil, quota_user: nil, user_ip: nil, options: nil, &block)
path = 'users/{userId}/bookshelves'
command = make_simple_command(:get, path, options)
command.response_representation = Google::Apis::BooksV1::Bookshelves::Representation
command.response_class = Google::Apis::BooksV1::Bookshelves
command.params['userId'] = user_id unless user_id.nil?
command.query['source'] = source unless source.nil?
command.query['fields'] = fields unless fields.nil?
command.query['quotaUser'] = quota_user unless quota_user.nil?
command.query['userIp'] = user_ip unless user_ip.nil?
execute_or_queue_command(command, &block)
end
# Retrieves volumes in a specific bookshelf for the specified user.
# @param [String] user_id
# ID of user for whom to retrieve bookshelf volumes.
# @param [String] shelf
# ID of bookshelf to retrieve volumes.
# @param [Fixnum] max_results
# Maximum number of results to return
# @param [Boolean] show_preorders
# Set to true to show pre-ordered books. Defaults to false.
# @param [String] source
# String to identify the originator of this request.
# @param [Fixnum] start_index
# Index of the first element to return (starts at 0)
# @param [String] fields
# Selector specifying which fields to include in a partial response.
# @param [String] quota_user
# Available to use for quota purposes for server-side applications. Can be any
# arbitrary string assigned to a user, but should not exceed 40 characters.
# Overrides userIp if both are provided.
# @param [String] user_ip
# IP address of the site where the request originates. Use this if you want to
# enforce per-user limits.
# @param [Google::Apis::RequestOptions] options
# Request-specific options
#
# @yield [result, err] Result & error if block supplied
# @yieldparam result [Google::Apis::BooksV1::Volumes] parsed result object
# @yieldparam err [StandardError] error object if request failed
#
# @return [Google::Apis::BooksV1::Volumes]
#
# @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried
# @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification
# @raise [Google::Apis::AuthorizationError] Authorization is required
def list_bookshelf_volumes(user_id, shelf, max_results: nil, show_preorders: nil, source: nil, start_index: nil, fields: nil, quota_user: nil, user_ip: nil, options: nil, &block)
path = 'users/{userId}/bookshelves/{shelf}/volumes'
command = make_simple_command(:get, path, options)
command.response_representation = Google::Apis::BooksV1::Volumes::Representation
command.response_class = Google::Apis::BooksV1::Volumes
command.params['userId'] = user_id unless user_id.nil?
command.params['shelf'] = shelf unless shelf.nil?
command.query['maxResults'] = max_results unless max_results.nil?
command.query['showPreorders'] = show_preorders unless show_preorders.nil?
command.query['source'] = source unless source.nil?
command.query['startIndex'] = start_index unless start_index.nil?
command.query['fields'] = fields unless fields.nil?
command.query['quotaUser'] = quota_user unless quota_user.nil?
command.query['userIp'] = user_ip unless user_ip.nil?
execute_or_queue_command(command, &block)
end
#
# @param [String] drive_document_id
# A drive document id. The upload_client_token must not be set.
# @param [String] mime_type
# The document MIME type. It can be set only if the drive_document_id is set.
# @param [String] name
# The document name. It can be set only if the drive_document_id is set.
# @param [String] upload_client_token
# @param [String] fields
# Selector specifying which fields to include in a partial response.
# @param [String] quota_user
# Available to use for quota purposes for server-side applications. Can be any
# arbitrary string assigned to a user, but should not exceed 40 characters.
# Overrides userIp if both are provided.
# @param [String] user_ip
# IP address of the site where the request originates. Use this if you want to
# enforce per-user limits.
# @param [Google::Apis::RequestOptions] options
# Request-specific options
#
# @yield [result, err] Result & error if block supplied
# @yieldparam result [Google::Apis::BooksV1::LoadingResource] parsed result object
# @yieldparam err [StandardError] error object if request failed
#
# @return [Google::Apis::BooksV1::LoadingResource]
#
# @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried
# @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification
# @raise [Google::Apis::AuthorizationError] Authorization is required
def add_book(drive_document_id: nil, mime_type: nil, name: nil, upload_client_token: nil, fields: nil, quota_user: nil, user_ip: nil, options: nil, &block)
path = 'cloudloading/addBook'
command = make_simple_command(:post, path, options)
command.response_representation = Google::Apis::BooksV1::LoadingResource::Representation
command.response_class = Google::Apis::BooksV1::LoadingResource
command.query['drive_document_id'] = drive_document_id unless drive_document_id.nil?
command.query['mime_type'] = mime_type unless mime_type.nil?
command.query['name'] = name unless name.nil?
command.query['upload_client_token'] = upload_client_token unless upload_client_token.nil?
command.query['fields'] = fields unless fields.nil?
command.query['quotaUser'] = quota_user unless quota_user.nil?
command.query['userIp'] = user_ip unless user_ip.nil?
execute_or_queue_command(command, &block)
end
# Remove the book and its contents
# @param [String] volume_id
# The id of the book to be removed.
# @param [String] fields
# Selector specifying which fields to include in a partial response.
# @param [String] quota_user
# Available to use for quota purposes for server-side applications. Can be any
# arbitrary string assigned to a user, but should not exceed 40 characters.
# Overrides userIp if both are provided.
# @param [String] user_ip
# IP address of the site where the request originates. Use this if you want to
# enforce per-user limits.
# @param [Google::Apis::RequestOptions] options
# Request-specific options
#
# @yield [result, err] Result & error if block supplied
# @yieldparam result [NilClass] No result returned for this method
# @yieldparam err [StandardError] error object if request failed
#
# @return [void]
#
# @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried
# @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification
# @raise [Google::Apis::AuthorizationError] Authorization is required
def delete_book(volume_id, fields: nil, quota_user: nil, user_ip: nil, options: nil, &block)
path = 'cloudloading/deleteBook'
command = make_simple_command(:post, path, options)
command.query['volumeId'] = volume_id unless volume_id.nil?
command.query['fields'] = fields unless fields.nil?
command.query['quotaUser'] = quota_user unless quota_user.nil?
command.query['userIp'] = user_ip unless user_ip.nil?
execute_or_queue_command(command, &block)
end
#
# @param [Google::Apis::BooksV1::LoadingResource] loading_resource_object
# @param [String] fields
# Selector specifying which fields to include in a partial response.
# @param [String] quota_user
# Available to use for quota purposes for server-side applications. Can be any
# arbitrary string assigned to a user, but should not exceed 40 characters.
# Overrides userIp if both are provided.
# @param [String] user_ip
# IP address of the site where the request originates. Use this if you want to
# enforce per-user limits.
# @param [Google::Apis::RequestOptions] options
# Request-specific options
#
# @yield [result, err] Result & error if block supplied
# @yieldparam result [Google::Apis::BooksV1::LoadingResource] parsed result object
# @yieldparam err [StandardError] error object if request failed
#
# @return [Google::Apis::BooksV1::LoadingResource]
#
# @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried
# @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification
# @raise [Google::Apis::AuthorizationError] Authorization is required
def update_book(loading_resource_object = nil, fields: nil, quota_user: nil, user_ip: nil, options: nil, &block)
path = 'cloudloading/updateBook'
command = make_simple_command(:post, path, options)
command.request_representation = Google::Apis::BooksV1::LoadingResource::Representation
command.request_object = loading_resource_object
command.response_representation = Google::Apis::BooksV1::LoadingResource::Representation
command.response_class = Google::Apis::BooksV1::LoadingResource
command.query['fields'] = fields unless fields.nil?
command.query['quotaUser'] = quota_user unless quota_user.nil?
command.query['userIp'] = user_ip unless user_ip.nil?
execute_or_queue_command(command, &block)
end
# Returns a list of offline dictionary meatadata available
# @param [String] cpksver
# The device/version ID from which to request the data.
# @param [String] fields
# Selector specifying which fields to include in a partial response.
# @param [String] quota_user
# Available to use for quota purposes for server-side applications. Can be any
# arbitrary string assigned to a user, but should not exceed 40 characters.
# Overrides userIp if both are provided.
# @param [String] user_ip
# IP address of the site where the request originates. Use this if you want to
# enforce per-user limits.
# @param [Google::Apis::RequestOptions] options
# Request-specific options
#
# @yield [result, err] Result & error if block supplied
# @yieldparam result [Google::Apis::BooksV1::Metadata] parsed result object
# @yieldparam err [StandardError] error object if request failed
#
# @return [Google::Apis::BooksV1::Metadata]
#
# @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried
# @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification
# @raise [Google::Apis::AuthorizationError] Authorization is required
def list_offline_metadata_dictionary(cpksver, fields: nil, quota_user: nil, user_ip: nil, options: nil, &block)
path = 'dictionary/listOfflineMetadata'
command = make_simple_command(:get, path, options)
command.response_representation = Google::Apis::BooksV1::Metadata::Representation
command.response_class = Google::Apis::BooksV1::Metadata
command.query['cpksver'] = cpksver unless cpksver.nil?
command.query['fields'] = fields unless fields.nil?
command.query['quotaUser'] = quota_user unless quota_user.nil?
command.query['userIp'] = user_ip unless user_ip.nil?
execute_or_queue_command(command, &block)
end
# Gets the layer summary for a volume.
# @param [String] volume_id
# The volume to retrieve layers for.
# @param [String] summary_id
# The ID for the layer to get the summary for.
# @param [String] content_version
# The content version for the requested volume.
# @param [String] source
# String to identify the originator of this request.
# @param [String] fields
# Selector specifying which fields to include in a partial response.
# @param [String] quota_user
# Available to use for quota purposes for server-side applications. Can be any
# arbitrary string assigned to a user, but should not exceed 40 characters.
# Overrides userIp if both are provided.
# @param [String] user_ip
# IP address of the site where the request originates. Use this if you want to
# enforce per-user limits.
# @param [Google::Apis::RequestOptions] options
# Request-specific options
#
# @yield [result, err] Result & error if block supplied
# @yieldparam result [Google::Apis::BooksV1::LayerSummary] parsed result object
# @yieldparam err [StandardError] error object if request failed
#
# @return [Google::Apis::BooksV1::LayerSummary]
#
# @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried
# @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification
# @raise [Google::Apis::AuthorizationError] Authorization is required
def get_layer(volume_id, summary_id, content_version: nil, source: nil, fields: nil, quota_user: nil, user_ip: nil, options: nil, &block)
path = 'volumes/{volumeId}/layersummary/{summaryId}'
command = make_simple_command(:get, path, options)
command.response_representation = Google::Apis::BooksV1::LayerSummary::Representation
command.response_class = Google::Apis::BooksV1::LayerSummary
command.params['volumeId'] = volume_id unless volume_id.nil?
command.params['summaryId'] = summary_id unless summary_id.nil?
command.query['contentVersion'] = content_version unless content_version.nil?
command.query['source'] = source unless source.nil?
command.query['fields'] = fields unless fields.nil?
command.query['quotaUser'] = quota_user unless quota_user.nil?
command.query['userIp'] = user_ip unless user_ip.nil?
execute_or_queue_command(command, &block)
end
# List the layer summaries for a volume.
# @param [String] volume_id
# The volume to retrieve layers for.
# @param [String] content_version
# The content version for the requested volume.
# @param [Fixnum] max_results
# Maximum number of results to return
# @param [String] page_token
# The value of the nextToken from the previous page.
# @param [String] source
# String to identify the originator of this request.
# @param [String] fields
# Selector specifying which fields to include in a partial response.
# @param [String] quota_user
# Available to use for quota purposes for server-side applications. Can be any
# arbitrary string assigned to a user, but should not exceed 40 characters.
# Overrides userIp if both are provided.
# @param [String] user_ip
# IP address of the site where the request originates. Use this if you want to
# enforce per-user limits.
# @param [Google::Apis::RequestOptions] options
# Request-specific options
#
# @yield [result, err] Result & error if block supplied
# @yieldparam result [Google::Apis::BooksV1::LayerSummaries] parsed result object
# @yieldparam err [StandardError] error object if request failed
#
# @return [Google::Apis::BooksV1::LayerSummaries]
#
# @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried
# @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification
# @raise [Google::Apis::AuthorizationError] Authorization is required
def list_layers(volume_id, content_version: nil, max_results: nil, page_token: nil, source: nil, fields: nil, quota_user: nil, user_ip: nil, options: nil, &block)
path = 'volumes/{volumeId}/layersummary'
command = make_simple_command(:get, path, options)
command.response_representation = Google::Apis::BooksV1::LayerSummaries::Representation
command.response_class = Google::Apis::BooksV1::LayerSummaries
command.params['volumeId'] = volume_id unless volume_id.nil?
command.query['contentVersion'] = content_version unless content_version.nil?
command.query['maxResults'] = max_results unless max_results.nil?
command.query['pageToken'] = page_token unless page_token.nil?
command.query['source'] = source unless source.nil?
command.query['fields'] = fields unless fields.nil?
command.query['quotaUser'] = quota_user unless quota_user.nil?
command.query['userIp'] = user_ip unless user_ip.nil?
execute_or_queue_command(command, &block)
end
# Gets the annotation data.
# @param [String] volume_id
# The volume to retrieve annotations for.
# @param [String] layer_id
# The ID for the layer to get the annotations.
# @param [String] annotation_data_id
# The ID of the annotation data to retrieve.
# @param [String] content_version
# The content version for the volume you are trying to retrieve.
# @param [Boolean] allow_web_definitions
# For the dictionary layer. Whether or not to allow web definitions.
# @param [Fixnum] h
# The requested pixel height for any images. If height is provided width must
# also be provided.
# @param [String] locale
# The locale information for the data. ISO-639-1 language and ISO-3166-1 country
# code. Ex: 'en_US'.
# @param [Fixnum] scale
# The requested scale for the image.
# @param [String] source
# String to identify the originator of this request.
# @param [Fixnum] w
# The requested pixel width for any images. If width is provided height must
# also be provided.
# @param [String] fields
# Selector specifying which fields to include in a partial response.
# @param [String] quota_user
# Available to use for quota purposes for server-side applications. Can be any
# arbitrary string assigned to a user, but should not exceed 40 characters.
# Overrides userIp if both are provided.
# @param [String] user_ip
# IP address of the site where the request originates. Use this if you want to
# enforce per-user limits.
# @param [Google::Apis::RequestOptions] options
# Request-specific options
#
# @yield [result, err] Result & error if block supplied
# @yieldparam result [Google::Apis::BooksV1::AnnotationData] parsed result object
# @yieldparam err [StandardError] error object if request failed
#
# @return [Google::Apis::BooksV1::AnnotationData]
#
# @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried
# @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification
# @raise [Google::Apis::AuthorizationError] Authorization is required
def get_layer_annotation_data(volume_id, layer_id, annotation_data_id, content_version, allow_web_definitions: nil, h: nil, locale: nil, scale: nil, source: nil, w: nil, fields: nil, quota_user: nil, user_ip: nil, options: nil, &block)
path = 'volumes/{volumeId}/layers/{layerId}/data/{annotationDataId}'
command = make_simple_command(:get, path, options)
command.response_representation = Google::Apis::BooksV1::AnnotationData::Representation
command.response_class = Google::Apis::BooksV1::AnnotationData
command.params['volumeId'] = volume_id unless volume_id.nil?
command.params['layerId'] = layer_id unless layer_id.nil?
command.params['annotationDataId'] = annotation_data_id unless annotation_data_id.nil?
command.query['allowWebDefinitions'] = allow_web_definitions unless allow_web_definitions.nil?
command.query['contentVersion'] = content_version unless content_version.nil?
command.query['h'] = h unless h.nil?
command.query['locale'] = locale unless locale.nil?
command.query['scale'] = scale unless scale.nil?
command.query['source'] = source unless source.nil?
command.query['w'] = w unless w.nil?
command.query['fields'] = fields unless fields.nil?
command.query['quotaUser'] = quota_user unless quota_user.nil?
command.query['userIp'] = user_ip unless user_ip.nil?
execute_or_queue_command(command, &block)
end
# Gets the annotation data for a volume and layer.
# @param [String] volume_id
# The volume to retrieve annotation data for.
# @param [String] layer_id
# The ID for the layer to get the annotation data.
# @param [String] content_version
# The content version for the requested volume.
# @param [Array<String>, String] annotation_data_id
# The list of Annotation Data Ids to retrieve. Pagination is ignored if this is
# set.
# @param [Fixnum] h
# The requested pixel height for any images. If height is provided width must
# also be provided.
# @param [String] locale
# The locale information for the data. ISO-639-1 language and ISO-3166-1 country
# code. Ex: 'en_US'.
# @param [Fixnum] max_results
# Maximum number of results to return
# @param [String] page_token
# The value of the nextToken from the previous page.
# @param [Fixnum] scale
# The requested scale for the image.
# @param [String] source
# String to identify the originator of this request.
# @param [String] updated_max
# RFC 3339 timestamp to restrict to items updated prior to this timestamp (
# exclusive).
# @param [String] updated_min
# RFC 3339 timestamp to restrict to items updated since this timestamp (
# inclusive).
# @param [Fixnum] w
# The requested pixel width for any images. If width is provided height must
# also be provided.
# @param [String] fields
# Selector specifying which fields to include in a partial response.
# @param [String] quota_user
# Available to use for quota purposes for server-side applications. Can be any
# arbitrary string assigned to a user, but should not exceed 40 characters.
# Overrides userIp if both are provided.
# @param [String] user_ip
# IP address of the site where the request originates. Use this if you want to
# enforce per-user limits.
# @param [Google::Apis::RequestOptions] options
# Request-specific options
#
# @yield [result, err] Result & error if block supplied
# @yieldparam result [Google::Apis::BooksV1::AnnotationsData] parsed result object
# @yieldparam err [StandardError] error object if request failed
#
# @return [Google::Apis::BooksV1::AnnotationsData]
#
# @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried
# @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification
# @raise [Google::Apis::AuthorizationError] Authorization is required
def list_layer_annotation_data(volume_id, layer_id, content_version, annotation_data_id: nil, h: nil, locale: nil, max_results: nil, page_token: nil, scale: nil, source: nil, updated_max: nil, updated_min: nil, w: nil, fields: nil, quota_user: nil, user_ip: nil, options: nil, &block)
path = 'volumes/{volumeId}/layers/{layerId}/data'
command = make_simple_command(:get, path, options)
command.response_representation = Google::Apis::BooksV1::AnnotationsData::Representation
command.response_class = Google::Apis::BooksV1::AnnotationsData
command.params['volumeId'] = volume_id unless volume_id.nil?
command.params['layerId'] = layer_id unless layer_id.nil?
command.query['annotationDataId'] = annotation_data_id unless annotation_data_id.nil?
command.query['contentVersion'] = content_version unless content_version.nil?
command.query['h'] = h unless h.nil?
command.query['locale'] = locale unless locale.nil?
command.query['maxResults'] = max_results unless max_results.nil?
command.query['pageToken'] = page_token unless page_token.nil?
command.query['scale'] = scale unless scale.nil?
command.query['source'] = source unless source.nil?
command.query['updatedMax'] = updated_max unless updated_max.nil?
command.query['updatedMin'] = updated_min unless updated_min.nil?
command.query['w'] = w unless w.nil?
command.query['fields'] = fields unless fields.nil?
command.query['quotaUser'] = quota_user unless quota_user.nil?
command.query['userIp'] = user_ip unless user_ip.nil?
execute_or_queue_command(command, &block)
end
# Gets the volume annotation.
# @param [String] volume_id
# The volume to retrieve annotations for.
# @param [String] layer_id
# The ID for the layer to get the annotations.
# @param [String] annotation_id
# The ID of the volume annotation to retrieve.
# @param [String] locale
# The locale information for the data. ISO-639-1 language and ISO-3166-1 country
# code. Ex: 'en_US'.
# @param [String] source
# String to identify the originator of this request.
# @param [String] fields
# Selector specifying which fields to include in a partial response.
# @param [String] quota_user
# Available to use for quota purposes for server-side applications. Can be any
# arbitrary string assigned to a user, but should not exceed 40 characters.
# Overrides userIp if both are provided.
# @param [String] user_ip
# IP address of the site where the request originates. Use this if you want to
# enforce per-user limits.
# @param [Google::Apis::RequestOptions] options
# Request-specific options
#
# @yield [result, err] Result & error if block supplied
# @yieldparam result [Google::Apis::BooksV1::VolumeAnnotation] parsed result object
# @yieldparam err [StandardError] error object if request failed
#
# @return [Google::Apis::BooksV1::VolumeAnnotation]
#
# @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried
# @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification
# @raise [Google::Apis::AuthorizationError] Authorization is required
def get_layer_volume_annotation(volume_id, layer_id, annotation_id, locale: nil, source: nil, fields: nil, quota_user: nil, user_ip: nil, options: nil, &block)
path = 'volumes/{volumeId}/layers/{layerId}/annotations/{annotationId}'
command = make_simple_command(:get, path, options)
command.response_representation = Google::Apis::BooksV1::VolumeAnnotation::Representation
command.response_class = Google::Apis::BooksV1::VolumeAnnotation
command.params['volumeId'] = volume_id unless volume_id.nil?
command.params['layerId'] = layer_id unless layer_id.nil?
command.params['annotationId'] = annotation_id unless annotation_id.nil?
command.query['locale'] = locale unless locale.nil?
command.query['source'] = source unless source.nil?
command.query['fields'] = fields unless fields.nil?
command.query['quotaUser'] = quota_user unless quota_user.nil?
command.query['userIp'] = user_ip unless user_ip.nil?
execute_or_queue_command(command, &block)
end
# Gets the volume annotations for a volume and layer.
# @param [String] volume_id
# The volume to retrieve annotations for.
# @param [String] layer_id
# The ID for the layer to get the annotations.
# @param [String] content_version
# The content version for the requested volume.
# @param [String] end_offset
# The end offset to end retrieving data from.
# @param [String] end_position
# The end position to end retrieving data from.
# @param [String] locale
# The locale information for the data. ISO-639-1 language and ISO-3166-1 country
# code. Ex: 'en_US'.
# @param [Fixnum] max_results
# Maximum number of results to return
# @param [String] page_token
# The value of the nextToken from the previous page.
# @param [Boolean] show_deleted
# Set to true to return deleted annotations. updatedMin must be in the request
# to use this. Defaults to false.
# @param [String] source
# String to identify the originator of this request.
# @param [String] start_offset
# The start offset to start retrieving data from.
# @param [String] start_position
# The start position to start retrieving data from.
# @param [String] updated_max
# RFC 3339 timestamp to restrict to items updated prior to this timestamp (
# exclusive).
# @param [String] updated_min
# RFC 3339 timestamp to restrict to items updated since this timestamp (
# inclusive).
# @param [String] volume_annotations_version
# The version of the volume annotations that you are requesting.
# @param [String] fields
# Selector specifying which fields to include in a partial response.
# @param [String] quota_user
# Available to use for quota purposes for server-side applications. Can be any
# arbitrary string assigned to a user, but should not exceed 40 characters.
# Overrides userIp if both are provided.
# @param [String] user_ip
# IP address of the site where the request originates. Use this if you want to
# enforce per-user limits.
# @param [Google::Apis::RequestOptions] options
# Request-specific options
#
# @yield [result, err] Result & error if block supplied
# @yieldparam result [Google::Apis::BooksV1::Volumeannotations] parsed result object
# @yieldparam err [StandardError] error object if request failed
#
# @return [Google::Apis::BooksV1::Volumeannotations]
#
# @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried
# @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification
# @raise [Google::Apis::AuthorizationError] Authorization is required
def list_layer_volume_annotations(volume_id, layer_id, content_version, end_offset: nil, end_position: nil, locale: nil, max_results: nil, page_token: nil, show_deleted: nil, source: nil, start_offset: nil, start_position: nil, updated_max: nil, updated_min: nil, volume_annotations_version: nil, fields: nil, quota_user: nil, user_ip: nil, options: nil, &block)
path = 'volumes/{volumeId}/layers/{layerId}'
command = make_simple_command(:get, path, options)
command.response_representation = Google::Apis::BooksV1::Volumeannotations::Representation
command.response_class = Google::Apis::BooksV1::Volumeannotations
command.params['volumeId'] = volume_id unless volume_id.nil?
command.params['layerId'] = layer_id unless layer_id.nil?
command.query['contentVersion'] = content_version unless content_version.nil?
command.query['endOffset'] = end_offset unless end_offset.nil?
command.query['endPosition'] = end_position unless end_position.nil?
command.query['locale'] = locale unless locale.nil?
command.query['maxResults'] = max_results unless max_results.nil?
command.query['pageToken'] = page_token unless page_token.nil?
command.query['showDeleted'] = show_deleted unless show_deleted.nil?
command.query['source'] = source unless source.nil?
command.query['startOffset'] = start_offset unless start_offset.nil?
command.query['startPosition'] = start_position unless start_position.nil?
command.query['updatedMax'] = updated_max unless updated_max.nil?
command.query['updatedMin'] = updated_min unless updated_min.nil?
command.query['volumeAnnotationsVersion'] = volume_annotations_version unless volume_annotations_version.nil?
command.query['fields'] = fields unless fields.nil?
command.query['quotaUser'] = quota_user unless quota_user.nil?
command.query['userIp'] = user_ip unless user_ip.nil?
execute_or_queue_command(command, &block)
end
# Gets the current settings for the user.
# @param [String] fields
# Selector specifying which fields to include in a partial response.
# @param [String] quota_user
# Available to use for quota purposes for server-side applications. Can be any
# arbitrary string assigned to a user, but should not exceed 40 characters.
# Overrides userIp if both are provided.
# @param [String] user_ip
# IP address of the site where the request originates. Use this if you want to
# enforce per-user limits.
# @param [Google::Apis::RequestOptions] options
# Request-specific options
#
# @yield [result, err] Result & error if block supplied
# @yieldparam result [Google::Apis::BooksV1::UserSettings] parsed result object
# @yieldparam err [StandardError] error object if request failed
#
# @return [Google::Apis::BooksV1::UserSettings]
#
# @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried
# @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification
# @raise [Google::Apis::AuthorizationError] Authorization is required
def get_user_settings(fields: nil, quota_user: nil, user_ip: nil, options: nil, &block)
path = 'myconfig/getUserSettings'
command = make_simple_command(:get, path, options)
command.response_representation = Google::Apis::BooksV1::UserSettings::Representation
command.response_class = Google::Apis::BooksV1::UserSettings
command.query['fields'] = fields unless fields.nil?
command.query['quotaUser'] = quota_user unless quota_user.nil?
command.query['userIp'] = user_ip unless user_ip.nil?
execute_or_queue_command(command, &block)
end
# Release downloaded content access restriction.
# @param [Array<String>, String] volume_ids
# The volume(s) to release restrictions for.
# @param [String] cpksver
# The device/version ID from which to release the restriction.
# @param [String] locale
# ISO-639-1, ISO-3166-1 codes for message localization, i.e. en_US.
# @param [String] source
# String to identify the originator of this request.
# @param [String] fields
# Selector specifying which fields to include in a partial response.
# @param [String] quota_user
# Available to use for quota purposes for server-side applications. Can be any
# arbitrary string assigned to a user, but should not exceed 40 characters.
# Overrides userIp if both are provided.
# @param [String] user_ip
# IP address of the site where the request originates. Use this if you want to
# enforce per-user limits.
# @param [Google::Apis::RequestOptions] options
# Request-specific options
#
# @yield [result, err] Result & error if block supplied
# @yieldparam result [Google::Apis::BooksV1::DownloadAccesses] parsed result object
# @yieldparam err [StandardError] error object if request failed
#
# @return [Google::Apis::BooksV1::DownloadAccesses]
#
# @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried
# @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification
# @raise [Google::Apis::AuthorizationError] Authorization is required
def release_download_access(volume_ids, cpksver, locale: nil, source: nil, fields: nil, quota_user: nil, user_ip: nil, options: nil, &block)
path = 'myconfig/releaseDownloadAccess'
command = make_simple_command(:post, path, options)
command.response_representation = Google::Apis::BooksV1::DownloadAccesses::Representation
command.response_class = Google::Apis::BooksV1::DownloadAccesses
command.query['cpksver'] = cpksver unless cpksver.nil?
command.query['locale'] = locale unless locale.nil?
command.query['source'] = source unless source.nil?
command.query['volumeIds'] = volume_ids unless volume_ids.nil?
command.query['fields'] = fields unless fields.nil?
command.query['quotaUser'] = quota_user unless quota_user.nil?
command.query['userIp'] = user_ip unless user_ip.nil?
execute_or_queue_command(command, &block)
end
# Request concurrent and download access restrictions.
# @param [String] source
# String to identify the originator of this request.
# @param [String] volume_id
# The volume to request concurrent/download restrictions for.
# @param [String] nonce
# The client nonce value.
# @param [String] cpksver
# The device/version ID from which to request the restrictions.
# @param [String] license_types
# The type of access license to request. If not specified, the default is BOTH.
# @param [String] locale
# ISO-639-1, ISO-3166-1 codes for message localization, i.e. en_US.
# @param [String] fields
# Selector specifying which fields to include in a partial response.
# @param [String] quota_user
# Available to use for quota purposes for server-side applications. Can be any
# arbitrary string assigned to a user, but should not exceed 40 characters.
# Overrides userIp if both are provided.
# @param [String] user_ip
# IP address of the site where the request originates. Use this if you want to
# enforce per-user limits.
# @param [Google::Apis::RequestOptions] options
# Request-specific options
#
# @yield [result, err] Result & error if block supplied
# @yieldparam result [Google::Apis::BooksV1::RequestAccess] parsed result object
# @yieldparam err [StandardError] error object if request failed
#
# @return [Google::Apis::BooksV1::RequestAccess]
#
# @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried
# @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification
# @raise [Google::Apis::AuthorizationError] Authorization is required
def request_access(source, volume_id, nonce, cpksver, license_types: nil, locale: nil, fields: nil, quota_user: nil, user_ip: nil, options: nil, &block)
path = 'myconfig/requestAccess'
command = make_simple_command(:post, path, options)
command.response_representation = Google::Apis::BooksV1::RequestAccess::Representation
command.response_class = Google::Apis::BooksV1::RequestAccess
command.query['cpksver'] = cpksver unless cpksver.nil?
command.query['licenseTypes'] = license_types unless license_types.nil?
command.query['locale'] = locale unless locale.nil?
command.query['nonce'] = nonce unless nonce.nil?
command.query['source'] = source unless source.nil?
command.query['volumeId'] = volume_id unless volume_id.nil?
command.query['fields'] = fields unless fields.nil?
command.query['quotaUser'] = quota_user unless quota_user.nil?
command.query['userIp'] = user_ip unless user_ip.nil?
execute_or_queue_command(command, &block)
end
# Request downloaded content access for specified volumes on the My eBooks shelf.
# @param [String] source
# String to identify the originator of this request.
# @param [String] nonce
# The client nonce value.
# @param [String] cpksver
# The device/version ID from which to release the restriction.
# @param [Array<String>, String] features
# List of features supported by the client, i.e., 'RENTALS'
# @param [String] locale
# ISO-639-1, ISO-3166-1 codes for message localization, i.e. en_US.
# @param [Boolean] show_preorders
# Set to true to show pre-ordered books. Defaults to false.
# @param [Array<String>, String] volume_ids
# The volume(s) to request download restrictions for.
# @param [String] fields
# Selector specifying which fields to include in a partial response.
# @param [String] quota_user
# Available to use for quota purposes for server-side applications. Can be any
# arbitrary string assigned to a user, but should not exceed 40 characters.
# Overrides userIp if both are provided.
# @param [String] user_ip
# IP address of the site where the request originates. Use this if you want to
# enforce per-user limits.
# @param [Google::Apis::RequestOptions] options
# Request-specific options
#
# @yield [result, err] Result & error if block supplied
# @yieldparam result [Google::Apis::BooksV1::Volumes] parsed result object
# @yieldparam err [StandardError] error object if request failed
#
# @return [Google::Apis::BooksV1::Volumes]
#
# @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried
# @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification
# @raise [Google::Apis::AuthorizationError] Authorization is required
def sync_volume_licenses(source, nonce, cpksver, features: nil, locale: nil, show_preorders: nil, volume_ids: nil, fields: nil, quota_user: nil, user_ip: nil, options: nil, &block)
path = 'myconfig/syncVolumeLicenses'
command = make_simple_command(:post, path, options)
command.response_representation = Google::Apis::BooksV1::Volumes::Representation
command.response_class = Google::Apis::BooksV1::Volumes
command.query['cpksver'] = cpksver unless cpksver.nil?
command.query['features'] = features unless features.nil?
command.query['locale'] = locale unless locale.nil?
command.query['nonce'] = nonce unless nonce.nil?
command.query['showPreorders'] = show_preorders unless show_preorders.nil?
command.query['source'] = source unless source.nil?
command.query['volumeIds'] = volume_ids unless volume_ids.nil?
command.query['fields'] = fields unless fields.nil?
command.query['quotaUser'] = quota_user unless quota_user.nil?
command.query['userIp'] = user_ip unless user_ip.nil?
execute_or_queue_command(command, &block)
end
# Sets the settings for the user. If a sub-object is specified, it will
# overwrite the existing sub-object stored in the server. Unspecified sub-
# objects will retain the existing value.
# @param [Google::Apis::BooksV1::UserSettings] user_settings_object
# @param [String] fields
# Selector specifying which fields to include in a partial response.
# @param [String] quota_user
# Available to use for quota purposes for server-side applications. Can be any
# arbitrary string assigned to a user, but should not exceed 40 characters.
# Overrides userIp if both are provided.
# @param [String] user_ip
# IP address of the site where the request originates. Use this if you want to
# enforce per-user limits.
# @param [Google::Apis::RequestOptions] options
# Request-specific options
#
# @yield [result, err] Result & error if block supplied
# @yieldparam result [Google::Apis::BooksV1::UserSettings] parsed result object
# @yieldparam err [StandardError] error object if request failed
#
# @return [Google::Apis::BooksV1::UserSettings]
#
# @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried
# @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification
# @raise [Google::Apis::AuthorizationError] Authorization is required
def update_user_settings(user_settings_object = nil, fields: nil, quota_user: nil, user_ip: nil, options: nil, &block)
path = 'myconfig/updateUserSettings'
command = make_simple_command(:post, path, options)
command.request_representation = Google::Apis::BooksV1::UserSettings::Representation
command.request_object = user_settings_object
command.response_representation = Google::Apis::BooksV1::UserSettings::Representation
command.response_class = Google::Apis::BooksV1::UserSettings
command.query['fields'] = fields unless fields.nil?
command.query['quotaUser'] = quota_user unless quota_user.nil?
command.query['userIp'] = user_ip unless user_ip.nil?
execute_or_queue_command(command, &block)
end
# Deletes an annotation.
# @param [String] annotation_id
# The ID for the annotation to delete.
# @param [String] source
# String to identify the originator of this request.
# @param [String] fields
# Selector specifying which fields to include in a partial response.
# @param [String] quota_user
# Available to use for quota purposes for server-side applications. Can be any
# arbitrary string assigned to a user, but should not exceed 40 characters.
# Overrides userIp if both are provided.
# @param [String] user_ip
# IP address of the site where the request originates. Use this if you want to
# enforce per-user limits.
# @param [Google::Apis::RequestOptions] options
# Request-specific options
#
# @yield [result, err] Result & error if block supplied
# @yieldparam result [NilClass] No result returned for this method
# @yieldparam err [StandardError] error object if request failed
#
# @return [void]
#
# @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried
# @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification
# @raise [Google::Apis::AuthorizationError] Authorization is required
def delete_my_library_annotation(annotation_id, source: nil, fields: nil, quota_user: nil, user_ip: nil, options: nil, &block)
path = 'mylibrary/annotations/{annotationId}'
command = make_simple_command(:delete, path, options)
command.params['annotationId'] = annotation_id unless annotation_id.nil?
command.query['source'] = source unless source.nil?
command.query['fields'] = fields unless fields.nil?
command.query['quotaUser'] = quota_user unless quota_user.nil?
command.query['userIp'] = user_ip unless user_ip.nil?
execute_or_queue_command(command, &block)
end
# Inserts a new annotation.
# @param [Google::Apis::BooksV1::Annotation] annotation_object
# @param [String] country
# ISO-3166-1 code to override the IP-based location.
# @param [Boolean] show_only_summary_in_response
# Requests that only the summary of the specified layer be provided in the
# response.
# @param [String] source
# String to identify the originator of this request.
# @param [String] fields
# Selector specifying which fields to include in a partial response.
# @param [String] quota_user
# Available to use for quota purposes for server-side applications. Can be any
# arbitrary string assigned to a user, but should not exceed 40 characters.
# Overrides userIp if both are provided.
# @param [String] user_ip
# IP address of the site where the request originates. Use this if you want to
# enforce per-user limits.
# @param [Google::Apis::RequestOptions] options
# Request-specific options
#
# @yield [result, err] Result & error if block supplied
# @yieldparam result [Google::Apis::BooksV1::Annotation] parsed result object
# @yieldparam err [StandardError] error object if request failed
#
# @return [Google::Apis::BooksV1::Annotation]
#
# @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried
# @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification
# @raise [Google::Apis::AuthorizationError] Authorization is required
def insert_my_library_annotation(annotation_object = nil, country: nil, show_only_summary_in_response: nil, source: nil, fields: nil, quota_user: nil, user_ip: nil, options: nil, &block)
path = 'mylibrary/annotations'
command = make_simple_command(:post, path, options)
command.request_representation = Google::Apis::BooksV1::Annotation::Representation
command.request_object = annotation_object
command.response_representation = Google::Apis::BooksV1::Annotation::Representation
command.response_class = Google::Apis::BooksV1::Annotation
command.query['country'] = country unless country.nil?
command.query['showOnlySummaryInResponse'] = show_only_summary_in_response unless show_only_summary_in_response.nil?
command.query['source'] = source unless source.nil?
command.query['fields'] = fields unless fields.nil?
command.query['quotaUser'] = quota_user unless quota_user.nil?
command.query['userIp'] = user_ip unless user_ip.nil?
execute_or_queue_command(command, &block)
end
# Retrieves a list of annotations, possibly filtered.
# @param [String] content_version
# The content version for the requested volume.
# @param [String] layer_id
# The layer ID to limit annotation by.
# @param [Array<String>, String] layer_ids
# The layer ID(s) to limit annotation by.
# @param [Fixnum] max_results
# Maximum number of results to return
# @param [String] page_token
# The value of the nextToken from the previous page.
# @param [Boolean] show_deleted
# Set to true to return deleted annotations. updatedMin must be in the request
# to use this. Defaults to false.
# @param [String] source
# String to identify the originator of this request.
# @param [String] updated_max
# RFC 3339 timestamp to restrict to items updated prior to this timestamp (
# exclusive).
# @param [String] updated_min
# RFC 3339 timestamp to restrict to items updated since this timestamp (
# inclusive).
# @param [String] volume_id
# The volume to restrict annotations to.
# @param [String] fields
# Selector specifying which fields to include in a partial response.
# @param [String] quota_user
# Available to use for quota purposes for server-side applications. Can be any
# arbitrary string assigned to a user, but should not exceed 40 characters.
# Overrides userIp if both are provided.
# @param [String] user_ip
# IP address of the site where the request originates. Use this if you want to
# enforce per-user limits.
# @param [Google::Apis::RequestOptions] options
# Request-specific options
#
# @yield [result, err] Result & error if block supplied
# @yieldparam result [Google::Apis::BooksV1::Annotations] parsed result object
# @yieldparam err [StandardError] error object if request failed
#
# @return [Google::Apis::BooksV1::Annotations]
#
# @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried
# @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification
# @raise [Google::Apis::AuthorizationError] Authorization is required
def list_my_library_annotations(content_version: nil, layer_id: nil, layer_ids: nil, max_results: nil, page_token: nil, show_deleted: nil, source: nil, updated_max: nil, updated_min: nil, volume_id: nil, fields: nil, quota_user: nil, user_ip: nil, options: nil, &block)
path = 'mylibrary/annotations'
command = make_simple_command(:get, path, options)
command.response_representation = Google::Apis::BooksV1::Annotations::Representation
command.response_class = Google::Apis::BooksV1::Annotations
command.query['contentVersion'] = content_version unless content_version.nil?
command.query['layerId'] = layer_id unless layer_id.nil?
command.query['layerIds'] = layer_ids unless layer_ids.nil?
command.query['maxResults'] = max_results unless max_results.nil?
command.query['pageToken'] = page_token unless page_token.nil?
command.query['showDeleted'] = show_deleted unless show_deleted.nil?
command.query['source'] = source unless source.nil?
command.query['updatedMax'] = updated_max unless updated_max.nil?
command.query['updatedMin'] = updated_min unless updated_min.nil?
command.query['volumeId'] = volume_id unless volume_id.nil?
command.query['fields'] = fields unless fields.nil?
command.query['quotaUser'] = quota_user unless quota_user.nil?
command.query['userIp'] = user_ip unless user_ip.nil?
execute_or_queue_command(command, &block)
end
# Gets the summary of specified layers.
# @param [Array<String>, String] layer_ids
# Array of layer IDs to get the summary for.
# @param [String] volume_id
# Volume id to get the summary for.
# @param [String] fields
# Selector specifying which fields to include in a partial response.
# @param [String] quota_user
# Available to use for quota purposes for server-side applications. Can be any
# arbitrary string assigned to a user, but should not exceed 40 characters.
# Overrides userIp if both are provided.
# @param [String] user_ip
# IP address of the site where the request originates. Use this if you want to
# enforce per-user limits.
# @param [Google::Apis::RequestOptions] options
# Request-specific options
#
# @yield [result, err] Result & error if block supplied
# @yieldparam result [Google::Apis::BooksV1::AnnotationsSummary] parsed result object
# @yieldparam err [StandardError] error object if request failed
#
# @return [Google::Apis::BooksV1::AnnotationsSummary]
#
# @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried
# @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification
# @raise [Google::Apis::AuthorizationError] Authorization is required
def summarize_my_library_annotation(layer_ids, volume_id, fields: nil, quota_user: nil, user_ip: nil, options: nil, &block)
path = 'mylibrary/annotations/summary'
command = make_simple_command(:post, path, options)
command.response_representation = Google::Apis::BooksV1::AnnotationsSummary::Representation
command.response_class = Google::Apis::BooksV1::AnnotationsSummary
command.query['layerIds'] = layer_ids unless layer_ids.nil?
command.query['volumeId'] = volume_id unless volume_id.nil?
command.query['fields'] = fields unless fields.nil?
command.query['quotaUser'] = quota_user unless quota_user.nil?
command.query['userIp'] = user_ip unless user_ip.nil?
execute_or_queue_command(command, &block)
end
# Updates an existing annotation.
# @param [String] annotation_id
# The ID for the annotation to update.
# @param [Google::Apis::BooksV1::Annotation] annotation_object
# @param [String] source
# String to identify the originator of this request.
# @param [String] fields
# Selector specifying which fields to include in a partial response.
# @param [String] quota_user
# Available to use for quota purposes for server-side applications. Can be any
# arbitrary string assigned to a user, but should not exceed 40 characters.
# Overrides userIp if both are provided.
# @param [String] user_ip
# IP address of the site where the request originates. Use this if you want to
# enforce per-user limits.
# @param [Google::Apis::RequestOptions] options
# Request-specific options
#
# @yield [result, err] Result & error if block supplied
# @yieldparam result [Google::Apis::BooksV1::Annotation] parsed result object
# @yieldparam err [StandardError] error object if request failed
#
# @return [Google::Apis::BooksV1::Annotation]
#
# @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried
# @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification
# @raise [Google::Apis::AuthorizationError] Authorization is required
def update_my_library_annotation(annotation_id, annotation_object = nil, source: nil, fields: nil, quota_user: nil, user_ip: nil, options: nil, &block)
path = 'mylibrary/annotations/{annotationId}'
command = make_simple_command(:put, path, options)
command.request_representation = Google::Apis::BooksV1::Annotation::Representation
command.request_object = annotation_object
command.response_representation = Google::Apis::BooksV1::Annotation::Representation
command.response_class = Google::Apis::BooksV1::Annotation
command.params['annotationId'] = annotation_id unless annotation_id.nil?
command.query['source'] = source unless source.nil?
command.query['fields'] = fields unless fields.nil?
command.query['quotaUser'] = quota_user unless quota_user.nil?
command.query['userIp'] = user_ip unless user_ip.nil?
execute_or_queue_command(command, &block)
end
# Adds a volume to a bookshelf.
# @param [String] shelf
# ID of bookshelf to which to add a volume.
# @param [String] volume_id
# ID of volume to add.
# @param [String] reason
# The reason for which the book is added to the library.
# @param [String] source
# String to identify the originator of this request.
# @param [String] fields
# Selector specifying which fields to include in a partial response.
# @param [String] quota_user
# Available to use for quota purposes for server-side applications. Can be any
# arbitrary string assigned to a user, but should not exceed 40 characters.
# Overrides userIp if both are provided.
# @param [String] user_ip
# IP address of the site where the request originates. Use this if you want to
# enforce per-user limits.
# @param [Google::Apis::RequestOptions] options
# Request-specific options
#
# @yield [result, err] Result & error if block supplied
# @yieldparam result [NilClass] No result returned for this method
# @yieldparam err [StandardError] error object if request failed
#
# @return [void]
#
# @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried
# @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification
# @raise [Google::Apis::AuthorizationError] Authorization is required
def add_my_library_volume(shelf, volume_id, reason: nil, source: nil, fields: nil, quota_user: nil, user_ip: nil, options: nil, &block)
path = 'mylibrary/bookshelves/{shelf}/addVolume'
command = make_simple_command(:post, path, options)
command.params['shelf'] = shelf unless shelf.nil?
command.query['reason'] = reason unless reason.nil?
command.query['source'] = source unless source.nil?
command.query['volumeId'] = volume_id unless volume_id.nil?
command.query['fields'] = fields unless fields.nil?
command.query['quotaUser'] = quota_user unless quota_user.nil?
command.query['userIp'] = user_ip unless user_ip.nil?
execute_or_queue_command(command, &block)
end
# Clears all volumes from a bookshelf.
# @param [String] shelf
# ID of bookshelf from which to remove a volume.
# @param [String] source
# String to identify the originator of this request.
# @param [String] fields
# Selector specifying which fields to include in a partial response.
# @param [String] quota_user
# Available to use for quota purposes for server-side applications. Can be any
# arbitrary string assigned to a user, but should not exceed 40 characters.
# Overrides userIp if both are provided.
# @param [String] user_ip
# IP address of the site where the request originates. Use this if you want to
# enforce per-user limits.
# @param [Google::Apis::RequestOptions] options
# Request-specific options
#
# @yield [result, err] Result & error if block supplied
# @yieldparam result [NilClass] No result returned for this method
# @yieldparam err [StandardError] error object if request failed
#
# @return [void]
#
# @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried
# @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification
# @raise [Google::Apis::AuthorizationError] Authorization is required
def clear_my_library_volumes(shelf, source: nil, fields: nil, quota_user: nil, user_ip: nil, options: nil, &block)
path = 'mylibrary/bookshelves/{shelf}/clearVolumes'
command = make_simple_command(:post, path, options)
command.params['shelf'] = shelf unless shelf.nil?
command.query['source'] = source unless source.nil?
command.query['fields'] = fields unless fields.nil?
command.query['quotaUser'] = quota_user unless quota_user.nil?
command.query['userIp'] = user_ip unless user_ip.nil?
execute_or_queue_command(command, &block)
end
# Retrieves metadata for a specific bookshelf belonging to the authenticated
# user.
# @param [String] shelf
# ID of bookshelf to retrieve.
# @param [String] source
# String to identify the originator of this request.
# @param [String] fields
# Selector specifying which fields to include in a partial response.
# @param [String] quota_user
# Available to use for quota purposes for server-side applications. Can be any
# arbitrary string assigned to a user, but should not exceed 40 characters.
# Overrides userIp if both are provided.
# @param [String] user_ip
# IP address of the site where the request originates. Use this if you want to
# enforce per-user limits.
# @param [Google::Apis::RequestOptions] options
# Request-specific options
#
# @yield [result, err] Result & error if block supplied
# @yieldparam result [Google::Apis::BooksV1::Bookshelf] parsed result object
# @yieldparam err [StandardError] error object if request failed
#
# @return [Google::Apis::BooksV1::Bookshelf]
#
# @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried
# @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification
# @raise [Google::Apis::AuthorizationError] Authorization is required
def get_my_library_bookshelf(shelf, source: nil, fields: nil, quota_user: nil, user_ip: nil, options: nil, &block)
path = 'mylibrary/bookshelves/{shelf}'
command = make_simple_command(:get, path, options)
command.response_representation = Google::Apis::BooksV1::Bookshelf::Representation
command.response_class = Google::Apis::BooksV1::Bookshelf
command.params['shelf'] = shelf unless shelf.nil?
command.query['source'] = source unless source.nil?
command.query['fields'] = fields unless fields.nil?
command.query['quotaUser'] = quota_user unless quota_user.nil?
command.query['userIp'] = user_ip unless user_ip.nil?
execute_or_queue_command(command, &block)
end
# Retrieves a list of bookshelves belonging to the authenticated user.
# @param [String] source
# String to identify the originator of this request.
# @param [String] fields
# Selector specifying which fields to include in a partial response.
# @param [String] quota_user
# Available to use for quota purposes for server-side applications. Can be any
# arbitrary string assigned to a user, but should not exceed 40 characters.
# Overrides userIp if both are provided.
# @param [String] user_ip
# IP address of the site where the request originates. Use this if you want to
# enforce per-user limits.
# @param [Google::Apis::RequestOptions] options
# Request-specific options
#
# @yield [result, err] Result & error if block supplied
# @yieldparam result [Google::Apis::BooksV1::Bookshelves] parsed result object
# @yieldparam err [StandardError] error object if request failed
#
# @return [Google::Apis::BooksV1::Bookshelves]
#
# @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried
# @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification
# @raise [Google::Apis::AuthorizationError] Authorization is required
def list_my_library_bookshelves(source: nil, fields: nil, quota_user: nil, user_ip: nil, options: nil, &block)
path = 'mylibrary/bookshelves'
command = make_simple_command(:get, path, options)
command.response_representation = Google::Apis::BooksV1::Bookshelves::Representation
command.response_class = Google::Apis::BooksV1::Bookshelves
command.query['source'] = source unless source.nil?
command.query['fields'] = fields unless fields.nil?
command.query['quotaUser'] = quota_user unless quota_user.nil?
command.query['userIp'] = user_ip unless user_ip.nil?
execute_or_queue_command(command, &block)
end
# Moves a volume within a bookshelf.
# @param [String] shelf
# ID of bookshelf with the volume.
# @param [String] volume_id
# ID of volume to move.
# @param [Fixnum] volume_position
# Position on shelf to move the item (0 puts the item before the current first
# item, 1 puts it between the first and the second and so on.)
# @param [String] source
# String to identify the originator of this request.
# @param [String] fields
# Selector specifying which fields to include in a partial response.
# @param [String] quota_user
# Available to use for quota purposes for server-side applications. Can be any
# arbitrary string assigned to a user, but should not exceed 40 characters.
# Overrides userIp if both are provided.
# @param [String] user_ip
# IP address of the site where the request originates. Use this if you want to
# enforce per-user limits.
# @param [Google::Apis::RequestOptions] options
# Request-specific options
#
# @yield [result, err] Result & error if block supplied
# @yieldparam result [NilClass] No result returned for this method
# @yieldparam err [StandardError] error object if request failed
#
# @return [void]
#
# @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried
# @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification
# @raise [Google::Apis::AuthorizationError] Authorization is required
def move_my_library_volume(shelf, volume_id, volume_position, source: nil, fields: nil, quota_user: nil, user_ip: nil, options: nil, &block)
path = 'mylibrary/bookshelves/{shelf}/moveVolume'
command = make_simple_command(:post, path, options)
command.params['shelf'] = shelf unless shelf.nil?
command.query['source'] = source unless source.nil?
command.query['volumeId'] = volume_id unless volume_id.nil?
command.query['volumePosition'] = volume_position unless volume_position.nil?
command.query['fields'] = fields unless fields.nil?
command.query['quotaUser'] = quota_user unless quota_user.nil?
command.query['userIp'] = user_ip unless user_ip.nil?
execute_or_queue_command(command, &block)
end
# Removes a volume from a bookshelf.
# @param [String] shelf
# ID of bookshelf from which to remove a volume.
# @param [String] volume_id
# ID of volume to remove.
# @param [String] reason
# The reason for which the book is removed from the library.
# @param [String] source
# String to identify the originator of this request.
# @param [String] fields
# Selector specifying which fields to include in a partial response.
# @param [String] quota_user
# Available to use for quota purposes for server-side applications. Can be any
# arbitrary string assigned to a user, but should not exceed 40 characters.
# Overrides userIp if both are provided.
# @param [String] user_ip
# IP address of the site where the request originates. Use this if you want to
# enforce per-user limits.
# @param [Google::Apis::RequestOptions] options
# Request-specific options
#
# @yield [result, err] Result & error if block supplied
# @yieldparam result [NilClass] No result returned for this method
# @yieldparam err [StandardError] error object if request failed
#
# @return [void]
#
# @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried
# @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification
# @raise [Google::Apis::AuthorizationError] Authorization is required
def remove_my_library_volume(shelf, volume_id, reason: nil, source: nil, fields: nil, quota_user: nil, user_ip: nil, options: nil, &block)
path = 'mylibrary/bookshelves/{shelf}/removeVolume'
command = make_simple_command(:post, path, options)
command.params['shelf'] = shelf unless shelf.nil?
command.query['reason'] = reason unless reason.nil?
command.query['source'] = source unless source.nil?
command.query['volumeId'] = volume_id unless volume_id.nil?
command.query['fields'] = fields unless fields.nil?
command.query['quotaUser'] = quota_user unless quota_user.nil?
command.query['userIp'] = user_ip unless user_ip.nil?
execute_or_queue_command(command, &block)
end
# Gets volume information for volumes on a bookshelf.
# @param [String] shelf
# The bookshelf ID or name retrieve volumes for.
# @param [String] country
# ISO-3166-1 code to override the IP-based location.
# @param [Fixnum] max_results
# Maximum number of results to return
# @param [String] projection
# Restrict information returned to a set of selected fields.
# @param [String] q
# Full-text search query string in this bookshelf.
# @param [Boolean] show_preorders
# Set to true to show pre-ordered books. Defaults to false.
# @param [String] source
# String to identify the originator of this request.
# @param [Fixnum] start_index
# Index of the first element to return (starts at 0)
# @param [String] fields
# Selector specifying which fields to include in a partial response.
# @param [String] quota_user
# Available to use for quota purposes for server-side applications. Can be any
# arbitrary string assigned to a user, but should not exceed 40 characters.
# Overrides userIp if both are provided.
# @param [String] user_ip
# IP address of the site where the request originates. Use this if you want to
# enforce per-user limits.
# @param [Google::Apis::RequestOptions] options
# Request-specific options
#
# @yield [result, err] Result & error if block supplied
# @yieldparam result [Google::Apis::BooksV1::Volumes] parsed result object
# @yieldparam err [StandardError] error object if request failed
#
# @return [Google::Apis::BooksV1::Volumes]
#
# @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried
# @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification
# @raise [Google::Apis::AuthorizationError] Authorization is required
def list_my_library_volumes(shelf, country: nil, max_results: nil, projection: nil, q: nil, show_preorders: nil, source: nil, start_index: nil, fields: nil, quota_user: nil, user_ip: nil, options: nil, &block)
path = 'mylibrary/bookshelves/{shelf}/volumes'
command = make_simple_command(:get, path, options)
command.response_representation = Google::Apis::BooksV1::Volumes::Representation
command.response_class = Google::Apis::BooksV1::Volumes
command.params['shelf'] = shelf unless shelf.nil?
command.query['country'] = country unless country.nil?
command.query['maxResults'] = max_results unless max_results.nil?
command.query['projection'] = projection unless projection.nil?
command.query['q'] = q unless q.nil?
command.query['showPreorders'] = show_preorders unless show_preorders.nil?
command.query['source'] = source unless source.nil?
command.query['startIndex'] = start_index unless start_index.nil?
command.query['fields'] = fields unless fields.nil?
command.query['quotaUser'] = quota_user unless quota_user.nil?
command.query['userIp'] = user_ip unless user_ip.nil?
execute_or_queue_command(command, &block)
end
# Retrieves my reading position information for a volume.
# @param [String] volume_id
# ID of volume for which to retrieve a reading position.
# @param [String] content_version
# Volume content version for which this reading position is requested.
# @param [String] source
# String to identify the originator of this request.
# @param [String] fields
# Selector specifying which fields to include in a partial response.
# @param [String] quota_user
# Available to use for quota purposes for server-side applications. Can be any
# arbitrary string assigned to a user, but should not exceed 40 characters.
# Overrides userIp if both are provided.
# @param [String] user_ip
# IP address of the site where the request originates. Use this if you want to
# enforce per-user limits.
# @param [Google::Apis::RequestOptions] options
# Request-specific options
#
# @yield [result, err] Result & error if block supplied
# @yieldparam result [Google::Apis::BooksV1::ReadingPosition] parsed result object
# @yieldparam err [StandardError] error object if request failed
#
# @return [Google::Apis::BooksV1::ReadingPosition]
#
# @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried
# @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification
# @raise [Google::Apis::AuthorizationError] Authorization is required
def get_my_library_reading_position(volume_id, content_version: nil, source: nil, fields: nil, quota_user: nil, user_ip: nil, options: nil, &block)
path = 'mylibrary/readingpositions/{volumeId}'
command = make_simple_command(:get, path, options)
command.response_representation = Google::Apis::BooksV1::ReadingPosition::Representation
command.response_class = Google::Apis::BooksV1::ReadingPosition
command.params['volumeId'] = volume_id unless volume_id.nil?
command.query['contentVersion'] = content_version unless content_version.nil?
command.query['source'] = source unless source.nil?
command.query['fields'] = fields unless fields.nil?
command.query['quotaUser'] = quota_user unless quota_user.nil?
command.query['userIp'] = user_ip unless user_ip.nil?
execute_or_queue_command(command, &block)
end
# Sets my reading position information for a volume.
# @param [String] volume_id
# ID of volume for which to update the reading position.
# @param [String] timestamp
# RFC 3339 UTC format timestamp associated with this reading position.
# @param [String] position
# Position string for the new volume reading position.
# @param [String] action
# Action that caused this reading position to be set.
# @param [String] content_version
# Volume content version for which this reading position applies.
# @param [String] device_cookie
# Random persistent device cookie optional on set position.
# @param [String] source
# String to identify the originator of this request.
# @param [String] fields
# Selector specifying which fields to include in a partial response.
# @param [String] quota_user
# Available to use for quota purposes for server-side applications. Can be any
# arbitrary string assigned to a user, but should not exceed 40 characters.
# Overrides userIp if both are provided.
# @param [String] user_ip
# IP address of the site where the request originates. Use this if you want to
# enforce per-user limits.
# @param [Google::Apis::RequestOptions] options
# Request-specific options
#
# @yield [result, err] Result & error if block supplied
# @yieldparam result [NilClass] No result returned for this method
# @yieldparam err [StandardError] error object if request failed
#
# @return [void]
#
# @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried
# @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification
# @raise [Google::Apis::AuthorizationError] Authorization is required
def set_my_library_reading_position(volume_id, timestamp, position, action: nil, content_version: nil, device_cookie: nil, source: nil, fields: nil, quota_user: nil, user_ip: nil, options: nil, &block)
path = 'mylibrary/readingpositions/{volumeId}/setPosition'
command = make_simple_command(:post, path, options)
command.params['volumeId'] = volume_id unless volume_id.nil?
command.query['action'] = action unless action.nil?
command.query['contentVersion'] = content_version unless content_version.nil?
command.query['deviceCookie'] = device_cookie unless device_cookie.nil?
command.query['position'] = position unless position.nil?
command.query['source'] = source unless source.nil?
command.query['timestamp'] = timestamp unless timestamp.nil?
command.query['fields'] = fields unless fields.nil?
command.query['quotaUser'] = quota_user unless quota_user.nil?
command.query['userIp'] = user_ip unless user_ip.nil?
execute_or_queue_command(command, &block)
end
# List categories for onboarding experience.
# @param [String] locale
# ISO-639-1 language and ISO-3166-1 country code. Default is en-US if unset.
# @param [String] fields
# Selector specifying which fields to include in a partial response.
# @param [String] quota_user
# Available to use for quota purposes for server-side applications. Can be any
# arbitrary string assigned to a user, but should not exceed 40 characters.
# Overrides userIp if both are provided.
# @param [String] user_ip
# IP address of the site where the request originates. Use this if you want to
# enforce per-user limits.
# @param [Google::Apis::RequestOptions] options
# Request-specific options
#
# @yield [result, err] Result & error if block supplied
# @yieldparam result [Google::Apis::BooksV1::Category] parsed result object
# @yieldparam err [StandardError] error object if request failed
#
# @return [Google::Apis::BooksV1::Category]
#
# @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried
# @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification
# @raise [Google::Apis::AuthorizationError] Authorization is required
def list_onboarding_categories(locale: nil, fields: nil, quota_user: nil, user_ip: nil, options: nil, &block)
path = 'onboarding/listCategories'
command = make_simple_command(:get, path, options)
command.response_representation = Google::Apis::BooksV1::Category::Representation
command.response_class = Google::Apis::BooksV1::Category
command.query['locale'] = locale unless locale.nil?
command.query['fields'] = fields unless fields.nil?
command.query['quotaUser'] = quota_user unless quota_user.nil?
command.query['userIp'] = user_ip unless user_ip.nil?
execute_or_queue_command(command, &block)
end
# List available volumes under categories for onboarding experience.
# @param [Array<String>, String] category_id
# List of category ids requested.
# @param [String] locale
# ISO-639-1 language and ISO-3166-1 country code. Default is en-US if unset.
# @param [String] max_allowed_maturity_rating
# The maximum allowed maturity rating of returned volumes. Books with a higher
# maturity rating are filtered out.
# @param [Fixnum] page_size
# Number of maximum results per page to be included in the response.
# @param [String] page_token
# The value of the nextToken from the previous page.
# @param [String] fields
# Selector specifying which fields to include in a partial response.
# @param [String] quota_user
# Available to use for quota purposes for server-side applications. Can be any
# arbitrary string assigned to a user, but should not exceed 40 characters.
# Overrides userIp if both are provided.
# @param [String] user_ip
# IP address of the site where the request originates. Use this if you want to
# enforce per-user limits.
# @param [Google::Apis::RequestOptions] options
# Request-specific options
#
# @yield [result, err] Result & error if block supplied
# @yieldparam result [Google::Apis::BooksV1::Volume2] parsed result object
# @yieldparam err [StandardError] error object if request failed
#
# @return [Google::Apis::BooksV1::Volume2]
#
# @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried
# @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification
# @raise [Google::Apis::AuthorizationError] Authorization is required
def list_onboarding_category_volumes(category_id: nil, locale: nil, max_allowed_maturity_rating: nil, page_size: nil, page_token: nil, fields: nil, quota_user: nil, user_ip: nil, options: nil, &block)
path = 'onboarding/listCategoryVolumes'
command = make_simple_command(:get, path, options)
command.response_representation = Google::Apis::BooksV1::Volume2::Representation
command.response_class = Google::Apis::BooksV1::Volume2
command.query['categoryId'] = category_id unless category_id.nil?
command.query['locale'] = locale unless locale.nil?
command.query['maxAllowedMaturityRating'] = max_allowed_maturity_rating unless max_allowed_maturity_rating.nil?
command.query['pageSize'] = page_size unless page_size.nil?
command.query['pageToken'] = page_token unless page_token.nil?
command.query['fields'] = fields unless fields.nil?
command.query['quotaUser'] = quota_user unless quota_user.nil?
command.query['userIp'] = user_ip unless user_ip.nil?
execute_or_queue_command(command, &block)
end
#
# @param [String] android_id
# device android_id
# @param [String] device
# device device
# @param [String] manufacturer
# device manufacturer
# @param [String] model
# device model
# @param [String] offer_id
# @param [String] product
# device product
# @param [String] serial
# device serial
# @param [String] volume_id
# Volume id to exercise the offer
# @param [String] fields
# Selector specifying which fields to include in a partial response.
# @param [String] quota_user
# Available to use for quota purposes for server-side applications. Can be any
# arbitrary string assigned to a user, but should not exceed 40 characters.
# Overrides userIp if both are provided.
# @param [String] user_ip
# IP address of the site where the request originates. Use this if you want to
# enforce per-user limits.
# @param [Google::Apis::RequestOptions] options
# Request-specific options
#
# @yield [result, err] Result & error if block supplied
# @yieldparam result [NilClass] No result returned for this method
# @yieldparam err [StandardError] error object if request failed
#
# @return [void]
#
# @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried
# @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification
# @raise [Google::Apis::AuthorizationError] Authorization is required
def accept_promo_offer(android_id: nil, device: nil, manufacturer: nil, model: nil, offer_id: nil, product: nil, serial: nil, volume_id: nil, fields: nil, quota_user: nil, user_ip: nil, options: nil, &block)
path = 'promooffer/accept'
command = make_simple_command(:post, path, options)
command.query['androidId'] = android_id unless android_id.nil?
command.query['device'] = device unless device.nil?
command.query['manufacturer'] = manufacturer unless manufacturer.nil?
command.query['model'] = model unless model.nil?
command.query['offerId'] = offer_id unless offer_id.nil?
command.query['product'] = product unless product.nil?
command.query['serial'] = serial unless serial.nil?
command.query['volumeId'] = volume_id unless volume_id.nil?
command.query['fields'] = fields unless fields.nil?
command.query['quotaUser'] = quota_user unless quota_user.nil?
command.query['userIp'] = user_ip unless user_ip.nil?
execute_or_queue_command(command, &block)
end
#
# @param [String] android_id
# device android_id
# @param [String] device
# device device
# @param [String] manufacturer
# device manufacturer
# @param [String] model
# device model
# @param [String] offer_id
# Offer to dimiss
# @param [String] product
# device product
# @param [String] serial
# device serial
# @param [String] fields
# Selector specifying which fields to include in a partial response.
# @param [String] quota_user
# Available to use for quota purposes for server-side applications. Can be any
# arbitrary string assigned to a user, but should not exceed 40 characters.
# Overrides userIp if both are provided.
# @param [String] user_ip
# IP address of the site where the request originates. Use this if you want to
# enforce per-user limits.
# @param [Google::Apis::RequestOptions] options
# Request-specific options
#
# @yield [result, err] Result & error if block supplied
# @yieldparam result [NilClass] No result returned for this method
# @yieldparam err [StandardError] error object if request failed
#
# @return [void]
#
# @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried
# @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification
# @raise [Google::Apis::AuthorizationError] Authorization is required
def dismiss_promo_offer(android_id: nil, device: nil, manufacturer: nil, model: nil, offer_id: nil, product: nil, serial: nil, fields: nil, quota_user: nil, user_ip: nil, options: nil, &block)
path = 'promooffer/dismiss'
command = make_simple_command(:post, path, options)
command.query['androidId'] = android_id unless android_id.nil?
command.query['device'] = device unless device.nil?
command.query['manufacturer'] = manufacturer unless manufacturer.nil?
command.query['model'] = model unless model.nil?
command.query['offerId'] = offer_id unless offer_id.nil?
command.query['product'] = product unless product.nil?
command.query['serial'] = serial unless serial.nil?
command.query['fields'] = fields unless fields.nil?
command.query['quotaUser'] = quota_user unless quota_user.nil?
command.query['userIp'] = user_ip unless user_ip.nil?
execute_or_queue_command(command, &block)
end
# Returns a list of promo offers available to the user
# @param [String] android_id
# device android_id
# @param [String] device
# device device
# @param [String] manufacturer
# device manufacturer
# @param [String] model
# device model
# @param [String] product
# device product
# @param [String] serial
# device serial
# @param [String] fields
# Selector specifying which fields to include in a partial response.
# @param [String] quota_user
# Available to use for quota purposes for server-side applications. Can be any
# arbitrary string assigned to a user, but should not exceed 40 characters.
# Overrides userIp if both are provided.
# @param [String] user_ip
# IP address of the site where the request originates. Use this if you want to
# enforce per-user limits.
# @param [Google::Apis::RequestOptions] options
# Request-specific options
#
# @yield [result, err] Result & error if block supplied
# @yieldparam result [Google::Apis::BooksV1::Offers] parsed result object
# @yieldparam err [StandardError] error object if request failed
#
# @return [Google::Apis::BooksV1::Offers]
#
# @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried
# @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification
# @raise [Google::Apis::AuthorizationError] Authorization is required
def get_promo_offer(android_id: nil, device: nil, manufacturer: nil, model: nil, product: nil, serial: nil, fields: nil, quota_user: nil, user_ip: nil, options: nil, &block)
path = 'promooffer/get'
command = make_simple_command(:get, path, options)
command.response_representation = Google::Apis::BooksV1::Offers::Representation
command.response_class = Google::Apis::BooksV1::Offers
command.query['androidId'] = android_id unless android_id.nil?
command.query['device'] = device unless device.nil?
command.query['manufacturer'] = manufacturer unless manufacturer.nil?
command.query['model'] = model unless model.nil?
command.query['product'] = product unless product.nil?
command.query['serial'] = serial unless serial.nil?
command.query['fields'] = fields unless fields.nil?
command.query['quotaUser'] = quota_user unless quota_user.nil?
command.query['userIp'] = user_ip unless user_ip.nil?
execute_or_queue_command(command, &block)
end
# Gets volume information for a single volume.
# @param [String] volume_id
# ID of volume to retrieve.
# @param [String] country
# ISO-3166-1 code to override the IP-based location.
# @param [String] partner
# Brand results for partner ID.
# @param [String] projection
# Restrict information returned to a set of selected fields.
# @param [String] source
# String to identify the originator of this request.
# @param [Boolean] user_library_consistent_read
# @param [String] fields
# Selector specifying which fields to include in a partial response.
# @param [String] quota_user
# Available to use for quota purposes for server-side applications. Can be any
# arbitrary string assigned to a user, but should not exceed 40 characters.
# Overrides userIp if both are provided.
# @param [String] user_ip
# IP address of the site where the request originates. Use this if you want to
# enforce per-user limits.
# @param [Google::Apis::RequestOptions] options
# Request-specific options
#
# @yield [result, err] Result & error if block supplied
# @yieldparam result [Google::Apis::BooksV1::Volume] parsed result object
# @yieldparam err [StandardError] error object if request failed
#
# @return [Google::Apis::BooksV1::Volume]
#
# @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried
# @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification
# @raise [Google::Apis::AuthorizationError] Authorization is required
def get_volume(volume_id, country: nil, partner: nil, projection: nil, source: nil, user_library_consistent_read: nil, fields: nil, quota_user: nil, user_ip: nil, options: nil, &block)
path = 'volumes/{volumeId}'
command = make_simple_command(:get, path, options)
command.response_representation = Google::Apis::BooksV1::Volume::Representation
command.response_class = Google::Apis::BooksV1::Volume
command.params['volumeId'] = volume_id unless volume_id.nil?
command.query['country'] = country unless country.nil?
command.query['partner'] = partner unless partner.nil?
command.query['projection'] = projection unless projection.nil?
command.query['source'] = source unless source.nil?
command.query['user_library_consistent_read'] = user_library_consistent_read unless user_library_consistent_read.nil?
command.query['fields'] = fields unless fields.nil?
command.query['quotaUser'] = quota_user unless quota_user.nil?
command.query['userIp'] = user_ip unless user_ip.nil?
execute_or_queue_command(command, &block)
end
# Performs a book search.
# @param [String] q
# Full-text search query string.
# @param [String] download
# Restrict to volumes by download availability.
# @param [String] filter
# Filter search results.
# @param [String] lang_restrict
# Restrict results to books with this language code.
# @param [String] library_restrict
# Restrict search to this user's library.
# @param [Fixnum] max_results
# Maximum number of results to return.
# @param [String] order_by
# Sort search results.
# @param [String] partner
# Restrict and brand results for partner ID.
# @param [String] print_type
# Restrict to books or magazines.
# @param [String] projection
# Restrict information returned to a set of selected fields.
# @param [Boolean] show_preorders
# Set to true to show books available for preorder. Defaults to false.
# @param [String] source
# String to identify the originator of this request.
# @param [Fixnum] start_index
# Index of the first result to return (starts at 0)
# @param [String] fields
# Selector specifying which fields to include in a partial response.
# @param [String] quota_user
# Available to use for quota purposes for server-side applications. Can be any
# arbitrary string assigned to a user, but should not exceed 40 characters.
# Overrides userIp if both are provided.
# @param [String] user_ip
# IP address of the site where the request originates. Use this if you want to
# enforce per-user limits.
# @param [Google::Apis::RequestOptions] options
# Request-specific options
#
# @yield [result, err] Result & error if block supplied
# @yieldparam result [Google::Apis::BooksV1::Volumes] parsed result object
# @yieldparam err [StandardError] error object if request failed
#
# @return [Google::Apis::BooksV1::Volumes]
#
# @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried
# @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification
# @raise [Google::Apis::AuthorizationError] Authorization is required
def list_volumes(q, download: nil, filter: nil, lang_restrict: nil, library_restrict: nil, max_results: nil, order_by: nil, partner: nil, print_type: nil, projection: nil, show_preorders: nil, source: nil, start_index: nil, fields: nil, quota_user: nil, user_ip: nil, options: nil, &block)
path = 'volumes'
command = make_simple_command(:get, path, options)
command.response_representation = Google::Apis::BooksV1::Volumes::Representation
command.response_class = Google::Apis::BooksV1::Volumes
command.query['download'] = download unless download.nil?
command.query['filter'] = filter unless filter.nil?
command.query['langRestrict'] = lang_restrict unless lang_restrict.nil?
command.query['libraryRestrict'] = library_restrict unless library_restrict.nil?
command.query['maxResults'] = max_results unless max_results.nil?
command.query['orderBy'] = order_by unless order_by.nil?
command.query['partner'] = partner unless partner.nil?
command.query['printType'] = print_type unless print_type.nil?
command.query['projection'] = projection unless projection.nil?
command.query['q'] = q unless q.nil?
command.query['showPreorders'] = show_preorders unless show_preorders.nil?
command.query['source'] = source unless source.nil?
command.query['startIndex'] = start_index unless start_index.nil?
command.query['fields'] = fields unless fields.nil?
command.query['quotaUser'] = quota_user unless quota_user.nil?
command.query['userIp'] = user_ip unless user_ip.nil?
execute_or_queue_command(command, &block)
end
# Return a list of associated books.
# @param [String] volume_id
# ID of the source volume.
# @param [String] association
# Association type.
# @param [String] locale
# ISO-639-1 language and ISO-3166-1 country code. Ex: 'en_US'. Used for
# generating recommendations.
# @param [String] max_allowed_maturity_rating
# The maximum allowed maturity rating of returned recommendations. Books with a
# higher maturity rating are filtered out.
# @param [String] source
# String to identify the originator of this request.
# @param [String] fields
# Selector specifying which fields to include in a partial response.
# @param [String] quota_user
# Available to use for quota purposes for server-side applications. Can be any
# arbitrary string assigned to a user, but should not exceed 40 characters.
# Overrides userIp if both are provided.
# @param [String] user_ip
# IP address of the site where the request originates. Use this if you want to
# enforce per-user limits.
# @param [Google::Apis::RequestOptions] options
# Request-specific options
#
# @yield [result, err] Result & error if block supplied
# @yieldparam result [Google::Apis::BooksV1::Volumes] parsed result object
# @yieldparam err [StandardError] error object if request failed
#
# @return [Google::Apis::BooksV1::Volumes]
#
# @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried
# @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification
# @raise [Google::Apis::AuthorizationError] Authorization is required
def list_associated_volumes(volume_id, association: nil, locale: nil, max_allowed_maturity_rating: nil, source: nil, fields: nil, quota_user: nil, user_ip: nil, options: nil, &block)
path = 'volumes/{volumeId}/associated'
command = make_simple_command(:get, path, options)
command.response_representation = Google::Apis::BooksV1::Volumes::Representation
command.response_class = Google::Apis::BooksV1::Volumes
command.params['volumeId'] = volume_id unless volume_id.nil?
command.query['association'] = association unless association.nil?
command.query['locale'] = locale unless locale.nil?
command.query['maxAllowedMaturityRating'] = max_allowed_maturity_rating unless max_allowed_maturity_rating.nil?
command.query['source'] = source unless source.nil?
command.query['fields'] = fields unless fields.nil?
command.query['quotaUser'] = quota_user unless quota_user.nil?
command.query['userIp'] = user_ip unless user_ip.nil?
execute_or_queue_command(command, &block)
end
# Return a list of books in My Library.
# @param [Array<String>, String] acquire_method
# How the book was aquired
# @param [String] locale
# ISO-639-1 language and ISO-3166-1 country code. Ex:'en_US'. Used for
# generating recommendations.
# @param [Fixnum] max_results
# Maximum number of results to return.
# @param [Array<String>, String] processing_state
# The processing state of the user uploaded volumes to be returned. Applicable
# only if the UPLOADED is specified in the acquireMethod.
# @param [String] source
# String to identify the originator of this request.
# @param [Fixnum] start_index
# Index of the first result to return (starts at 0)
# @param [String] fields
# Selector specifying which fields to include in a partial response.
# @param [String] quota_user
# Available to use for quota purposes for server-side applications. Can be any
# arbitrary string assigned to a user, but should not exceed 40 characters.
# Overrides userIp if both are provided.
# @param [String] user_ip
# IP address of the site where the request originates. Use this if you want to
# enforce per-user limits.
# @param [Google::Apis::RequestOptions] options
# Request-specific options
#
# @yield [result, err] Result & error if block supplied
# @yieldparam result [Google::Apis::BooksV1::Volumes] parsed result object
# @yieldparam err [StandardError] error object if request failed
#
# @return [Google::Apis::BooksV1::Volumes]
#
# @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried
# @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification
# @raise [Google::Apis::AuthorizationError] Authorization is required
def list_my_books(acquire_method: nil, locale: nil, max_results: nil, processing_state: nil, source: nil, start_index: nil, fields: nil, quota_user: nil, user_ip: nil, options: nil, &block)
path = 'volumes/mybooks'
command = make_simple_command(:get, path, options)
command.response_representation = Google::Apis::BooksV1::Volumes::Representation
command.response_class = Google::Apis::BooksV1::Volumes
command.query['acquireMethod'] = acquire_method unless acquire_method.nil?
command.query['locale'] = locale unless locale.nil?
command.query['maxResults'] = max_results unless max_results.nil?
command.query['processingState'] = processing_state unless processing_state.nil?
command.query['source'] = source unless source.nil?
command.query['startIndex'] = start_index unless start_index.nil?
command.query['fields'] = fields unless fields.nil?
command.query['quotaUser'] = quota_user unless quota_user.nil?
command.query['userIp'] = user_ip unless user_ip.nil?
execute_or_queue_command(command, &block)
end
# Return a list of recommended books for the current user.
# @param [String] locale
# ISO-639-1 language and ISO-3166-1 country code. Ex: 'en_US'. Used for
# generating recommendations.
# @param [String] max_allowed_maturity_rating
# The maximum allowed maturity rating of returned recommendations. Books with a
# higher maturity rating are filtered out.
# @param [String] source
# String to identify the originator of this request.
# @param [String] fields
# Selector specifying which fields to include in a partial response.
# @param [String] quota_user
# Available to use for quota purposes for server-side applications. Can be any
# arbitrary string assigned to a user, but should not exceed 40 characters.
# Overrides userIp if both are provided.
# @param [String] user_ip
# IP address of the site where the request originates. Use this if you want to
# enforce per-user limits.
# @param [Google::Apis::RequestOptions] options
# Request-specific options
#
# @yield [result, err] Result & error if block supplied
# @yieldparam result [Google::Apis::BooksV1::Volumes] parsed result object
# @yieldparam err [StandardError] error object if request failed
#
# @return [Google::Apis::BooksV1::Volumes]
#
# @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried
# @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification
# @raise [Google::Apis::AuthorizationError] Authorization is required
def list_recommended_volumes(locale: nil, max_allowed_maturity_rating: nil, source: nil, fields: nil, quota_user: nil, user_ip: nil, options: nil, &block)
path = 'volumes/recommended'
command = make_simple_command(:get, path, options)
command.response_representation = Google::Apis::BooksV1::Volumes::Representation
command.response_class = Google::Apis::BooksV1::Volumes
command.query['locale'] = locale unless locale.nil?
command.query['maxAllowedMaturityRating'] = max_allowed_maturity_rating unless max_allowed_maturity_rating.nil?
command.query['source'] = source unless source.nil?
command.query['fields'] = fields unless fields.nil?
command.query['quotaUser'] = quota_user unless quota_user.nil?
command.query['userIp'] = user_ip unless user_ip.nil?
execute_or_queue_command(command, &block)
end
# Rate a recommended book for the current user.
# @param [String] rating
# Rating to be given to the volume.
# @param [String] volume_id
# ID of the source volume.
# @param [String] locale
# ISO-639-1 language and ISO-3166-1 country code. Ex: 'en_US'. Used for
# generating recommendations.
# @param [String] source
# String to identify the originator of this request.
# @param [String] fields
# Selector specifying which fields to include in a partial response.
# @param [String] quota_user
# Available to use for quota purposes for server-side applications. Can be any
# arbitrary string assigned to a user, but should not exceed 40 characters.
# Overrides userIp if both are provided.
# @param [String] user_ip
# IP address of the site where the request originates. Use this if you want to
# enforce per-user limits.
# @param [Google::Apis::RequestOptions] options
# Request-specific options
#
# @yield [result, err] Result & error if block supplied
# @yieldparam result [Google::Apis::BooksV1::RateRecommendedVolumeResponse] parsed result object
# @yieldparam err [StandardError] error object if request failed
#
# @return [Google::Apis::BooksV1::RateRecommendedVolumeResponse]
#
# @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried
# @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification
# @raise [Google::Apis::AuthorizationError] Authorization is required
def rate_recommended_volume(rating, volume_id, locale: nil, source: nil, fields: nil, quota_user: nil, user_ip: nil, options: nil, &block)
path = 'volumes/recommended/rate'
command = make_simple_command(:post, path, options)
command.response_representation = Google::Apis::BooksV1::RateRecommendedVolumeResponse::Representation
command.response_class = Google::Apis::BooksV1::RateRecommendedVolumeResponse
command.query['locale'] = locale unless locale.nil?
command.query['rating'] = rating unless rating.nil?
command.query['source'] = source unless source.nil?
command.query['volumeId'] = volume_id unless volume_id.nil?
command.query['fields'] = fields unless fields.nil?
command.query['quotaUser'] = quota_user unless quota_user.nil?
command.query['userIp'] = user_ip unless user_ip.nil?
execute_or_queue_command(command, &block)
end
# Return a list of books uploaded by the current user.
# @param [String] locale
# ISO-639-1 language and ISO-3166-1 country code. Ex: 'en_US'. Used for
# generating recommendations.
# @param [Fixnum] max_results
# Maximum number of results to return.
# @param [Array<String>, String] processing_state
# The processing state of the user uploaded volumes to be returned.
# @param [String] source
# String to identify the originator of this request.
# @param [Fixnum] start_index
# Index of the first result to return (starts at 0)
# @param [Array<String>, String] volume_id
# The ids of the volumes to be returned. If not specified all that match the
# processingState are returned.
# @param [String] fields
# Selector specifying which fields to include in a partial response.
# @param [String] quota_user
# Available to use for quota purposes for server-side applications. Can be any
# arbitrary string assigned to a user, but should not exceed 40 characters.
# Overrides userIp if both are provided.
# @param [String] user_ip
# IP address of the site where the request originates. Use this if you want to
# enforce per-user limits.
# @param [Google::Apis::RequestOptions] options
# Request-specific options
#
# @yield [result, err] Result & error if block supplied
# @yieldparam result [Google::Apis::BooksV1::Volumes] parsed result object
# @yieldparam err [StandardError] error object if request failed
#
# @return [Google::Apis::BooksV1::Volumes]
#
# @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried
# @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification
# @raise [Google::Apis::AuthorizationError] Authorization is required
def list_user_uploaded_volumes(locale: nil, max_results: nil, processing_state: nil, source: nil, start_index: nil, volume_id: nil, fields: nil, quota_user: nil, user_ip: nil, options: nil, &block)
path = 'volumes/useruploaded'
command = make_simple_command(:get, path, options)
command.response_representation = Google::Apis::BooksV1::Volumes::Representation
command.response_class = Google::Apis::BooksV1::Volumes
command.query['locale'] = locale unless locale.nil?
command.query['maxResults'] = max_results unless max_results.nil?
command.query['processingState'] = processing_state unless processing_state.nil?
command.query['source'] = source unless source.nil?
command.query['startIndex'] = start_index unless start_index.nil?
command.query['volumeId'] = volume_id unless volume_id.nil?
command.query['fields'] = fields unless fields.nil?
command.query['quotaUser'] = quota_user unless quota_user.nil?
command.query['userIp'] = user_ip unless user_ip.nil?
execute_or_queue_command(command, &block)
end
protected
def apply_command_defaults(command)
command.query['key'] = key unless key.nil?
command.query['quotaUser'] = quota_user unless quota_user.nil?
command.query['userIp'] = user_ip unless user_ip.nil?
end
end
end
end
end
| hanpanpan200/google-api-ruby-client | generated/google/apis/books_v1/service.rb | Ruby | apache-2.0 | 126,385 |
/*
* Copyright 2017 Red Hat, Inc. and/or its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jbpm.kie.test.objects;
public interface Building {
public Integer getDoors();
}
| droolsjbpm/jbpm | jbpm-services/jbpm-kie-services/src/test/java/org/jbpm/kie/test/objects/Building.java | Java | apache-2.0 | 720 |
#include <Wt/WApplication>
#include <Wt/WStandardItemModel>
#include <Wt/WTableView>
#include "../treeview-dragdrop/CsvUtil.h"
SAMPLE_BEGIN(SmallTableView)
Wt::WTableView *tableView = new Wt::WTableView();
tableView->setModel(csvToModel(Wt::WApplication::appRoot() + "table.csv",
tableView));
tableView->setColumnResizeEnabled(false);
tableView->setColumnAlignment(0, Wt::AlignCenter);
tableView->setHeaderAlignment(0, Wt::AlignCenter);
tableView->setAlternatingRowColors(true);
tableView->setRowHeight(28);
tableView->setHeaderHeight(28);
tableView->setSelectionMode(Wt::SingleSelection);
tableView->setEditTriggers(Wt::WAbstractItemView::NoEditTrigger);
/*
* Configure column widths and matching table width
*/
const int WIDTH = 120;
for (int i = 0; i < tableView->model()->columnCount(); ++i)
tableView->setColumnWidth(i, 120);
/*
* 7 pixels are padding/border per column
* 2 pixels are border of the entire table
*/
tableView->setWidth((WIDTH + 7) * tableView->model()->columnCount() + 2);
SAMPLE_END(return tableView)
| sanathkumarv/RestAPIWt | tools/wt-3.3.5-rc1/examples/widgetgallery/examples/SmallTableView.cpp | C++ | apache-2.0 | 1,047 |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.ignite.internal.client.util;
import java.util.Arrays;
import java.util.Collection;
import java.util.Comparator;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.NavigableMap;
import java.util.Random;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeMap;
import java.util.TreeSet;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import org.apache.ignite.internal.client.GridClientPredicate;
import org.apache.ignite.internal.util.typedef.internal.U;
import org.jetbrains.annotations.Nullable;
/**
* Controls key to node affinity using consistent hash algorithm. This class is thread-safe
* and does not have to be externally synchronized.
* <p>
* For a good explanation of what consistent hashing is, you can refer to
* <a href="http://weblogs.java.net/blog/tomwhite/archive/2007/11/consistent_hash.html">Tom White's Blog</a>.
*/
public class GridClientConsistentHash<N> {
/** Prime number. */
private static final int PRIME = 15485857;
/** Random generator. */
private static final Random RAND = new Random();
/** Affinity seed. */
private final Object affSeed;
/** Map of hash assignments. */
private final NavigableMap<Integer, SortedSet<N>> circle = new TreeMap<>();
/** Read/write lock. */
private final ReadWriteLock rw = new ReentrantReadWriteLock();
/** Distinct nodes in the hash. */
private Collection<N> nodes = new HashSet<>();
/** Nodes comparator to resolve hash codes collisions. */
private Comparator<N> nodesComp;
/**
* Constructs consistent hash using empty affinity seed and {@code MD5} hasher function.
*/
public GridClientConsistentHash() {
this(null, null);
}
/**
* Constructs consistent hash using given affinity seed and {@code MD5} hasher function.
*
* @param affSeed Affinity seed (will be used as key prefix for hashing).
*/
public GridClientConsistentHash(Object affSeed) {
this(null, affSeed);
}
/**
* Constructs consistent hash using given affinity seed and hasher function.
*
* @param nodesComp Nodes comparator to resolve hash codes collisions.
* If {@code null} natural order will be used.
* @param affSeed Affinity seed (will be used as key prefix for hashing).
*/
public GridClientConsistentHash(Comparator<N> nodesComp, Object affSeed) {
this.nodesComp = nodesComp;
this.affSeed = affSeed == null ? new Integer(PRIME) : affSeed;
}
/**
* Adds nodes to consistent hash algorithm (if nodes are {@code null} or empty, then no-op).
*
* @param nodes Nodes to add.
* @param replicas Number of replicas for every node.
*/
public void addNodes(Collection<N> nodes, int replicas) {
if (nodes == null || nodes.isEmpty())
return;
rw.writeLock().lock();
try {
for (N node : nodes)
addNode(node, replicas);
}
finally {
rw.writeLock().unlock();
}
}
/**
* Adds a node to consistent hash algorithm.
*
* @param node New node (if {@code null} then no-op).
* @param replicas Number of replicas for the node.
* @return {@code True} if node was added, {@code false} if it is {@code null} or
* is already contained in the hash.
*/
public boolean addNode(N node, int replicas) {
if (node == null)
return false;
long seed = affSeed.hashCode() * 31 + hash(node);
rw.writeLock().lock();
try {
if (!nodes.add(node))
return false;
int hash = hash(seed);
SortedSet<N> set = circle.get(hash);
if (set == null)
circle.put(hash, set = new TreeSet<>(nodesComp));
set.add(node);
for (int i = 1; i <= replicas; i++) {
seed = seed * affSeed.hashCode() + i;
hash = hash(seed);
set = circle.get(hash);
if (set == null)
circle.put(hash, set = new TreeSet<>(nodesComp));
set.add(node);
}
return true;
}
finally {
rw.writeLock().unlock();
}
}
/**
* Removes a node and all of its replicas.
*
* @param node Node to remove (if {@code null}, then no-op).
* @return {@code True} if node was removed, {@code false} if node is {@code null} or
* not present in hash.
*/
public boolean removeNode(N node) {
if (node == null)
return false;
rw.writeLock().lock();
try {
if (!nodes.remove(node))
return false;
for (Iterator<SortedSet<N>> it = circle.values().iterator(); it.hasNext();) {
SortedSet<N> set = it.next();
if (!set.remove(node))
continue;
if (set.isEmpty())
it.remove();
}
return true;
}
finally {
rw.writeLock().unlock();
}
}
/**
* Gets number of distinct nodes, excluding replicas, in consistent hash.
*
* @return Number of distinct nodes, excluding replicas, in consistent hash.
*/
public int count() {
rw.readLock().lock();
try {
return nodes.size();
}
finally {
rw.readLock().unlock();
}
}
/**
* Gets size of all nodes (including replicas) in consistent hash.
*
* @return Size of all nodes (including replicas) in consistent hash.
*/
public int size() {
rw.readLock().lock();
try {
int size = 0;
for (SortedSet<N> set : circle.values())
size += set.size();
return size;
}
finally {
rw.readLock().unlock();
}
}
/**
* Checks if consistent hash has nodes added to it.
*
* @return {@code True} if consistent hash is empty, {@code false} otherwise.
*/
public boolean isEmpty() {
return count() == 0;
}
/**
* Gets set of all distinct nodes in the consistent hash (in no particular order).
*
* @return Set of all distinct nodes in the consistent hash.
*/
public Set<N> nodes() {
rw.readLock().lock();
try {
return new HashSet<>(nodes);
}
finally {
rw.readLock().unlock();
}
}
/**
* Picks a random node from consistent hash.
*
* @return Random node from consistent hash or {@code null} if there are no nodes.
*/
public N random() {
return node(RAND.nextLong());
}
/**
* Gets node for a key.
*
* @param key Key.
* @return Node.
*/
public N node(Object key) {
int hash = hash(key);
rw.readLock().lock();
try {
Map.Entry<Integer, SortedSet<N>> firstEntry = circle.firstEntry();
if (firstEntry == null)
return null;
Map.Entry<Integer, SortedSet<N>> tailEntry = circle.tailMap(hash, true).firstEntry();
// Get first node hash in the circle clock-wise.
return circle.get(tailEntry == null ? firstEntry.getKey() : tailEntry.getKey()).first();
}
finally {
rw.readLock().unlock();
}
}
/**
* Gets node for a given key.
*
* @param key Key to get node for.
* @param inc Optional inclusion set. Only nodes contained in this set may be returned.
* If {@code null}, then all nodes may be included.
* @return Node for key, or {@code null} if node was not found.
*/
public N node(Object key, Collection<N> inc) {
return node(key, inc, null);
}
/**
* Gets node for a given key.
*
* @param key Key to get node for.
* @param inc Optional inclusion set. Only nodes contained in this set may be returned.
* If {@code null}, then all nodes may be included.
* @param exc Optional exclusion set. Only nodes not contained in this set may be returned.
* If {@code null}, then all nodes may be returned.
* @return Node for key, or {@code null} if node was not found.
*/
public N node(Object key, @Nullable final Collection<N> inc, @Nullable final Collection<N> exc) {
if (inc == null && exc == null)
return node(key);
return node(key, new GridClientPredicate<N>() {
@Override public boolean apply(N n) {
return (inc == null || inc.contains(n)) && (exc == null || !exc.contains(n));
}
});
}
/**
* Gets node for a given key.
*
* @param key Key to get node for.
* @param p Optional predicate for node filtering.
* @return Node for key, or {@code null} if node was not found.
*/
public N node(Object key, GridClientPredicate<N>... p) {
if (p == null || p.length == 0)
return node(key);
int hash = hash(key);
rw.readLock().lock();
try {
final int size = nodes.size();
if (size == 0)
return null;
Set<N> failed = null;
// Move clock-wise starting from selected position 'hash'.
for (SortedSet<N> set : circle.tailMap(hash, true).values()) {
for (N n : set) {
if (failed != null && failed.contains(n))
continue;
if (apply(p, n))
return n;
if (failed == null)
failed = new HashSet<>();
failed.add(n);
if (failed.size() == size)
return null;
}
}
//
// Copy-paste is used to escape several new objects creation.
//
// Wrap around moving clock-wise from the circle start.
for (SortedSet<N> set : circle.headMap(hash, false).values()) { // Circle head.
for (N n : set) {
if (failed != null && failed.contains(n))
continue;
if (apply(p, n))
return n;
if (failed == null)
failed = U.newHashSet(size);
failed.add(n);
if (failed.size() == size)
return null;
}
}
return null;
}
finally {
rw.readLock().unlock();
}
}
/**
* Apply predicate to the node.
*
* @param p Predicate.
* @param n Node.
* @return {@code True} if filter passed or empty.
*/
private boolean apply(GridClientPredicate<N>[] p, N n) {
if (p != null) {
for (GridClientPredicate<? super N> r : p) {
if (r != null && !r.apply(n))
return false;
}
}
return true;
}
/**
* Gets hash code for a given object.
*
* @param o Object to get hash code for.
* @return Hash code.
*/
public static int hash(Object o) {
int h = o == null ? 0 : o instanceof byte[] ? Arrays.hashCode((byte[])o) : o.hashCode();
// Spread bits to hash code.
h += (h << 15) ^ 0xffffcd7d;
h ^= (h >>> 10);
h += (h << 3);
h ^= (h >>> 6);
h += (h << 2) + (h << 14);
return h ^ (h >>> 16);
}
/** {@inheritDoc} */
@Override public String toString() {
return getClass().getSimpleName() + " [affSeed=" + affSeed +
", circle=" + circle +
", nodesComp=" + nodesComp +
", nodes=" + nodes + "]";
}
}
| samaitra/ignite | modules/core/src/main/java/org/apache/ignite/internal/client/util/GridClientConsistentHash.java | Java | apache-2.0 | 12,863 |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache license, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the license for the specific language governing permissions and
* limitations under the license.
*/
package org.apache.logging.log4j;
import org.apache.logging.log4j.message.Message;
import org.apache.logging.log4j.message.ObjectMessage;
import org.apache.logging.log4j.message.ParameterizedMessage;
import org.apache.logging.log4j.message.SimpleMessage;
import org.apache.logging.log4j.spi.AbstractLogger;
import org.junit.Test;
import static org.junit.Assert.*;
/**
*
*/
public class AbstractLoggerTest extends AbstractLogger {
private static class LogEvent {
String markerName;
Message data;
Throwable t;
public LogEvent(final String markerName, final Message data, final Throwable t) {
this.markerName = markerName;
this.data = data;
this.t = t;
}
}
private static final long serialVersionUID = 1L;
private static Level currentLevel;
private LogEvent currentEvent;
private static Throwable t = new UnsupportedOperationException("Test");
private static Class<AbstractLogger> obj = AbstractLogger.class;
private static String pattern = "{}, {}";
private static String p1 = "Long Beach";
private static String p2 = "California";
private static Message simple = new SimpleMessage("Hello");
private static Message object = new ObjectMessage(obj);
private static Message param = new ParameterizedMessage(pattern, p1, p2);
private static String marker = "TEST";
private static LogEvent[] events = new LogEvent[] {
new LogEvent(null, simple, null),
new LogEvent(marker, simple, null),
new LogEvent(null, simple, t),
new LogEvent(marker, simple, t),
new LogEvent(null, object, null),
new LogEvent(marker, object, null),
new LogEvent(null, object, t),
new LogEvent(marker, object, t),
new LogEvent(null, param, null),
new LogEvent(marker, param, null),
new LogEvent(null, simple, null),
new LogEvent(null, simple, t),
new LogEvent(marker, simple, null),
new LogEvent(marker, simple, t),
new LogEvent(marker, simple, null),
};
@Override
public Level getLevel() {
return currentLevel;
}
@Override
public boolean isEnabled(final Level level, final Marker marker, final Message data, final Throwable t) {
assertTrue("Incorrect Level. Expected " + currentLevel + ", actual " + level, level.equals(currentLevel));
if (marker == null) {
if (currentEvent.markerName != null) {
fail("Incorrect marker. Expected " + currentEvent.markerName + ", actual is null");
}
} else {
if (currentEvent.markerName == null) {
fail("Incorrect marker. Expected null. Actual is " + marker.getName());
} else {
assertTrue("Incorrect marker. Expected " + currentEvent.markerName + ", actual " +
marker.getName(), currentEvent.markerName.equals(marker.getName()));
}
}
if (data == null) {
if (currentEvent.data != null) {
fail("Incorrect message. Expected " + currentEvent.data + ", actual is null");
}
} else {
if (currentEvent.data == null) {
fail("Incorrect message. Expected null. Actual is " + data.getFormattedMessage());
} else {
assertTrue("Incorrect message type. Expected " + currentEvent.data + ", actual " + data,
data.getClass().isAssignableFrom(currentEvent.data.getClass()));
assertTrue("Incorrect message. Expected " + currentEvent.data.getFormattedMessage() + ", actual " +
data.getFormattedMessage(),
currentEvent.data.getFormattedMessage().equals(data.getFormattedMessage()));
}
}
if (t == null) {
if (currentEvent.t != null) {
fail("Incorrect Throwable. Expected " + currentEvent.t + ", actual is null");
}
} else {
if (currentEvent.t == null) {
fail("Incorrect Throwable. Expected null. Actual is " + t);
} else {
assertTrue("Incorrect Throwable. Expected " + currentEvent.t + ", actual " + t,
currentEvent.t.equals(t));
}
}
return true;
}
@Override
public boolean isEnabled(final Level level, final Marker marker, final Object data, final Throwable t) {
return isEnabled(level, marker, new ObjectMessage(data), t);
}
@Override
public boolean isEnabled(final Level level, final Marker marker, final String data) {
return isEnabled(level, marker, new SimpleMessage(data), null);
}
@Override
public boolean isEnabled(final Level level, final Marker marker, final String data, final Object... p1) {
return isEnabled(level, marker, new ParameterizedMessage(data, p1), null);
}
@Override
public boolean isEnabled(final Level level, final Marker marker, final String data, final Throwable t) {
return isEnabled(level, marker, new SimpleMessage(data), t);
}
@Override
public void logMessage(final String fqcn, final Level level, final Marker marker, final Message data, final Throwable t) {
assertTrue("Incorrect Level. Expected " + currentLevel + ", actual " + level, level.equals(currentLevel));
if (marker == null) {
if (currentEvent.markerName != null) {
fail("Incorrect marker. Expected " + currentEvent.markerName + ", actual is null");
}
} else {
if (currentEvent.markerName == null) {
fail("Incorrect marker. Expected null. Actual is " + marker.getName());
} else {
assertTrue("Incorrect marker. Expected " + currentEvent.markerName + ", actual " +
marker.getName(), currentEvent.markerName.equals(marker.getName()));
}
}
if (data == null) {
if (currentEvent.data != null) {
fail("Incorrect message. Expected " + currentEvent.data + ", actual is null");
}
} else {
if (currentEvent.data == null) {
fail("Incorrect message. Expected null. Actual is " + data.getFormattedMessage());
} else {
assertTrue("Incorrect message type. Expected " + currentEvent.data + ", actual " + data,
data.getClass().isAssignableFrom(currentEvent.data.getClass()));
assertTrue("Incorrect message. Expected " + currentEvent.data.getFormattedMessage() + ", actual " +
data.getFormattedMessage(),
currentEvent.data.getFormattedMessage().equals(data.getFormattedMessage()));
}
}
if (t == null) {
if (currentEvent.t != null) {
fail("Incorrect Throwable. Expected " + currentEvent.t + ", actual is null");
}
} else {
if (currentEvent.t == null) {
fail("Incorrect Throwable. Expected null. Actual is " + t);
} else {
assertTrue("Incorrect Throwable. Expected " + currentEvent.t + ", actual " + t,
currentEvent.t.equals(t));
}
}
}
@Test
public void testDebug() {
currentLevel = Level.DEBUG;
currentEvent = events[0];
debug("Hello");
debug(null, "Hello");
currentEvent = events[1];
debug(MarkerManager.getMarker("TEST"), "Hello");
currentEvent = events[2];
debug("Hello", t);
debug(null, "Hello", t);
currentEvent = events[3];
debug(MarkerManager.getMarker("TEST"), "Hello", t);
currentEvent = events[4];
debug(obj);
currentEvent = events[5];
debug(MarkerManager.getMarker("TEST"), obj);
currentEvent = events[6];
debug(obj, t);
debug(null, obj, t);
currentEvent = events[7];
debug(MarkerManager.getMarker("TEST"), obj, t);
currentEvent = events[8];
debug(pattern, p1, p2);
currentEvent = events[9];
debug(MarkerManager.getMarker("TEST"), pattern, p1, p2);
currentEvent = events[10];
debug(simple);
debug(null, simple);
debug(null, simple, null);
currentEvent = events[11];
debug(simple, t);
debug(null, simple, t);
currentEvent = events[12];
debug(MarkerManager.getMarker("TEST"), simple, null);
currentEvent = events[13];
debug(MarkerManager.getMarker("TEST"), simple, t);
currentEvent = events[14];
debug(MarkerManager.getMarker("TEST"), simple);
}
@Test
public void testError() {
currentLevel = Level.ERROR;
currentEvent = events[0];
error("Hello");
error(null, "Hello");
currentEvent = events[1];
error(MarkerManager.getMarker("TEST"), "Hello");
currentEvent = events[2];
error("Hello", t);
error(null, "Hello", t);
currentEvent = events[3];
error(MarkerManager.getMarker("TEST"), "Hello", t);
currentEvent = events[4];
error(obj);
currentEvent = events[5];
error(MarkerManager.getMarker("TEST"), obj);
currentEvent = events[6];
error(obj, t);
error(null, obj, t);
currentEvent = events[7];
error(MarkerManager.getMarker("TEST"), obj, t);
currentEvent = events[8];
error(pattern, p1, p2);
currentEvent = events[9];
error(MarkerManager.getMarker("TEST"), pattern, p1, p2);
currentEvent = events[10];
error(simple);
error(null, simple);
error(null, simple, null);
currentEvent = events[11];
error(simple, t);
error(null, simple, t);
currentEvent = events[12];
error(MarkerManager.getMarker("TEST"), simple, null);
currentEvent = events[13];
error(MarkerManager.getMarker("TEST"), simple, t);
currentEvent = events[14];
error(MarkerManager.getMarker("TEST"), simple);
}
@Test
public void testFatal() {
currentLevel = Level.FATAL;
currentEvent = events[0];
fatal("Hello");
fatal(null, "Hello");
currentEvent = events[1];
fatal(MarkerManager.getMarker("TEST"), "Hello");
currentEvent = events[2];
fatal("Hello", t);
fatal(null, "Hello", t);
currentEvent = events[3];
fatal(MarkerManager.getMarker("TEST"), "Hello", t);
currentEvent = events[4];
fatal(obj);
currentEvent = events[5];
fatal(MarkerManager.getMarker("TEST"), obj);
currentEvent = events[6];
fatal(obj, t);
fatal(null, obj, t);
currentEvent = events[7];
fatal(MarkerManager.getMarker("TEST"), obj, t);
currentEvent = events[8];
fatal(pattern, p1, p2);
currentEvent = events[9];
fatal(MarkerManager.getMarker("TEST"), pattern, p1, p2);
currentEvent = events[10];
fatal(simple);
fatal(null, simple);
fatal(null, simple, null);
currentEvent = events[11];
fatal(simple, t);
fatal(null, simple, t);
currentEvent = events[12];
fatal(MarkerManager.getMarker("TEST"), simple, null);
currentEvent = events[13];
fatal(MarkerManager.getMarker("TEST"), simple, t);
currentEvent = events[14];
fatal(MarkerManager.getMarker("TEST"), simple);
}
@Test
public void testInfo() {
currentLevel = Level.INFO;
currentEvent = events[0];
info("Hello");
info(null, "Hello");
currentEvent = events[1];
info(MarkerManager.getMarker("TEST"), "Hello");
currentEvent = events[2];
info("Hello", t);
info(null, "Hello", t);
currentEvent = events[3];
info(MarkerManager.getMarker("TEST"), "Hello", t);
currentEvent = events[4];
info(obj);
currentEvent = events[5];
info(MarkerManager.getMarker("TEST"), obj);
currentEvent = events[6];
info(obj, t);
info(null, obj, t);
currentEvent = events[7];
info(MarkerManager.getMarker("TEST"), obj, t);
currentEvent = events[8];
info(pattern, p1, p2);
currentEvent = events[9];
info(MarkerManager.getMarker("TEST"), pattern, p1, p2);
currentEvent = events[10];
info(simple);
info(null, simple);
info(null, simple, null);
currentEvent = events[11];
info(simple, t);
info(null, simple, t);
currentEvent = events[12];
info(MarkerManager.getMarker("TEST"), simple, null);
currentEvent = events[13];
info(MarkerManager.getMarker("TEST"), simple, t);
currentEvent = events[14];
info(MarkerManager.getMarker("TEST"), simple);
}
@Test
public void testLogDebug() {
currentLevel = Level.DEBUG;
currentEvent = events[0];
log(Level.DEBUG, "Hello");
log(Level.DEBUG, null, "Hello");
currentEvent = events[1];
log(Level.DEBUG, MarkerManager.getMarker("TEST"), "Hello");
currentEvent = events[2];
log(Level.DEBUG, "Hello", t);
log(Level.DEBUG, null, "Hello", t);
currentEvent = events[3];
log(Level.DEBUG, MarkerManager.getMarker("TEST"), "Hello", t);
currentEvent = events[4];
log(Level.DEBUG, obj);
currentEvent = events[5];
log(Level.DEBUG, MarkerManager.getMarker("TEST"), obj);
currentEvent = events[6];
log(Level.DEBUG, obj, t);
log(Level.DEBUG, null, obj, t);
currentEvent = events[7];
log(Level.DEBUG, MarkerManager.getMarker("TEST"), obj, t);
currentEvent = events[8];
log(Level.DEBUG, pattern, p1, p2);
currentEvent = events[9];
log(Level.DEBUG, MarkerManager.getMarker("TEST"), pattern, p1, p2);
currentEvent = events[10];
log(Level.DEBUG, simple);
log(Level.DEBUG, null, simple);
log(Level.DEBUG, null, simple, null);
currentEvent = events[11];
log(Level.DEBUG, simple, t);
log(Level.DEBUG, null, simple, t);
currentEvent = events[12];
log(Level.DEBUG, MarkerManager.getMarker("TEST"), simple, null);
currentEvent = events[13];
log(Level.DEBUG, MarkerManager.getMarker("TEST"), simple, t);
currentEvent = events[14];
log(Level.DEBUG, MarkerManager.getMarker("TEST"), simple);
}
@Test
public void testLogError() {
currentLevel = Level.ERROR;
currentEvent = events[0];
log(Level.ERROR, "Hello");
log(Level.ERROR, null, "Hello");
currentEvent = events[1];
log(Level.ERROR, MarkerManager.getMarker("TEST"), "Hello");
currentEvent = events[2];
log(Level.ERROR, "Hello", t);
log(Level.ERROR, null, "Hello", t);
currentEvent = events[3];
log(Level.ERROR, MarkerManager.getMarker("TEST"), "Hello", t);
currentEvent = events[4];
log(Level.ERROR, obj);
currentEvent = events[5];
log(Level.ERROR, MarkerManager.getMarker("TEST"), obj);
currentEvent = events[6];
log(Level.ERROR, obj, t);
log(Level.ERROR, null, obj, t);
currentEvent = events[7];
log(Level.ERROR, MarkerManager.getMarker("TEST"), obj, t);
currentEvent = events[8];
log(Level.ERROR, pattern, p1, p2);
currentEvent = events[9];
log(Level.ERROR, MarkerManager.getMarker("TEST"), pattern, p1, p2);
currentEvent = events[10];
log(Level.ERROR, simple);
log(Level.ERROR, null, simple);
log(Level.ERROR, null, simple, null);
currentEvent = events[11];
log(Level.ERROR, simple, t);
log(Level.ERROR, null, simple, t);
currentEvent = events[12];
log(Level.ERROR, MarkerManager.getMarker("TEST"), simple, null);
currentEvent = events[13];
log(Level.ERROR, MarkerManager.getMarker("TEST"), simple, t);
currentEvent = events[14];
log(Level.ERROR, MarkerManager.getMarker("TEST"), simple);
}
@Test
public void testLogFatal() {
currentLevel = Level.FATAL;
currentEvent = events[0];
log(Level.FATAL, "Hello");
log(Level.FATAL, null, "Hello");
currentEvent = events[1];
log(Level.FATAL, MarkerManager.getMarker("TEST"), "Hello");
currentEvent = events[2];
log(Level.FATAL, "Hello", t);
log(Level.FATAL, null, "Hello", t);
currentEvent = events[3];
log(Level.FATAL, MarkerManager.getMarker("TEST"), "Hello", t);
currentEvent = events[4];
log(Level.FATAL, obj);
currentEvent = events[5];
log(Level.FATAL, MarkerManager.getMarker("TEST"), obj);
currentEvent = events[6];
log(Level.FATAL, obj, t);
log(Level.FATAL, null, obj, t);
currentEvent = events[7];
log(Level.FATAL, MarkerManager.getMarker("TEST"), obj, t);
currentEvent = events[8];
log(Level.FATAL, pattern, p1, p2);
currentEvent = events[9];
log(Level.FATAL, MarkerManager.getMarker("TEST"), pattern, p1, p2);
currentEvent = events[10];
log(Level.FATAL, simple);
log(Level.FATAL, null, simple);
log(Level.FATAL, null, simple, null);
currentEvent = events[11];
log(Level.FATAL, simple, t);
log(Level.FATAL, null, simple, t);
currentEvent = events[12];
log(Level.FATAL, MarkerManager.getMarker("TEST"), simple, null);
currentEvent = events[13];
log(Level.FATAL, MarkerManager.getMarker("TEST"), simple, t);
currentEvent = events[14];
log(Level.FATAL, MarkerManager.getMarker("TEST"), simple);
}
@Test
public void testLogInfo() {
currentLevel = Level.INFO;
currentEvent = events[0];
log(Level.INFO, "Hello");
log(Level.INFO, null, "Hello");
currentEvent = events[1];
log(Level.INFO, MarkerManager.getMarker("TEST"), "Hello");
currentEvent = events[2];
log(Level.INFO, "Hello", t);
log(Level.INFO, null, "Hello", t);
currentEvent = events[3];
log(Level.INFO, MarkerManager.getMarker("TEST"), "Hello", t);
currentEvent = events[4];
log(Level.INFO, obj);
currentEvent = events[5];
log(Level.INFO, MarkerManager.getMarker("TEST"), obj);
currentEvent = events[6];
log(Level.INFO, obj, t);
log(Level.INFO, null, obj, t);
currentEvent = events[7];
log(Level.INFO, MarkerManager.getMarker("TEST"), obj, t);
currentEvent = events[8];
log(Level.INFO, pattern, p1, p2);
currentEvent = events[9];
log(Level.INFO, MarkerManager.getMarker("TEST"), pattern, p1, p2);
currentEvent = events[10];
log(Level.INFO, simple);
log(Level.INFO, null, simple);
log(Level.INFO, null, simple, null);
currentEvent = events[11];
log(Level.INFO, simple, t);
log(Level.INFO, null, simple, t);
currentEvent = events[12];
log(Level.INFO, MarkerManager.getMarker("TEST"), simple, null);
currentEvent = events[13];
log(Level.INFO, MarkerManager.getMarker("TEST"), simple, t);
currentEvent = events[14];
log(Level.INFO, MarkerManager.getMarker("TEST"), simple);
}
@Test
public void testLogTrace() {
currentLevel = Level.TRACE;
currentEvent = events[0];
log(Level.TRACE, "Hello");
log(Level.TRACE, null, "Hello");
currentEvent = events[1];
log(Level.TRACE, MarkerManager.getMarker("TEST"), "Hello");
currentEvent = events[2];
log(Level.TRACE, "Hello", t);
log(Level.TRACE, null, "Hello", t);
currentEvent = events[3];
log(Level.TRACE, MarkerManager.getMarker("TEST"), "Hello", t);
currentEvent = events[4];
log(Level.TRACE, obj);
currentEvent = events[5];
log(Level.TRACE, MarkerManager.getMarker("TEST"), obj);
currentEvent = events[6];
log(Level.TRACE, obj, t);
log(Level.TRACE, null, obj, t);
currentEvent = events[7];
log(Level.TRACE, MarkerManager.getMarker("TEST"), obj, t);
currentEvent = events[8];
log(Level.TRACE, pattern, p1, p2);
currentEvent = events[9];
log(Level.TRACE, MarkerManager.getMarker("TEST"), pattern, p1, p2);
currentEvent = events[10];
log(Level.TRACE, simple);
log(Level.TRACE, null, simple);
log(Level.TRACE, null, simple, null);
currentEvent = events[11];
log(Level.TRACE, simple, t);
log(Level.TRACE, null, simple, t);
currentEvent = events[12];
log(Level.TRACE, MarkerManager.getMarker("TEST"), simple, null);
currentEvent = events[13];
log(Level.TRACE, MarkerManager.getMarker("TEST"), simple, t);
currentEvent = events[14];
log(Level.TRACE, MarkerManager.getMarker("TEST"), simple);
}
@Test
public void testLogWarn() {
currentLevel = Level.WARN;
currentEvent = events[0];
log(Level.WARN, "Hello");
log(Level.WARN, null, "Hello");
currentEvent = events[1];
log(Level.WARN, MarkerManager.getMarker("TEST"), "Hello");
currentEvent = events[2];
log(Level.WARN, "Hello", t);
log(Level.WARN, null, "Hello", t);
currentEvent = events[3];
log(Level.WARN, MarkerManager.getMarker("TEST"), "Hello", t);
currentEvent = events[4];
log(Level.WARN, obj);
currentEvent = events[5];
log(Level.WARN, MarkerManager.getMarker("TEST"), obj);
currentEvent = events[6];
log(Level.WARN, obj, t);
log(Level.WARN, null, obj, t);
currentEvent = events[7];
log(Level.WARN, MarkerManager.getMarker("TEST"), obj, t);
currentEvent = events[8];
log(Level.WARN, pattern, p1, p2);
currentEvent = events[9];
log(Level.WARN, MarkerManager.getMarker("TEST"), pattern, p1, p2);
currentEvent = events[10];
log(Level.WARN, simple);
log(Level.WARN, null, simple);
log(Level.WARN, null, simple, null);
currentEvent = events[11];
log(Level.WARN, simple, t);
log(Level.WARN, null, simple, t);
currentEvent = events[12];
log(Level.WARN, MarkerManager.getMarker("TEST"), simple, null);
currentEvent = events[13];
log(Level.WARN, MarkerManager.getMarker("TEST"), simple, t);
currentEvent = events[14];
log(Level.WARN, MarkerManager.getMarker("TEST"), simple);
}
@Test
public void testTrace() {
currentLevel = Level.TRACE;
currentEvent = events[0];
trace("Hello");
trace(null, "Hello");
currentEvent = events[1];
trace(MarkerManager.getMarker("TEST"), "Hello");
currentEvent = events[2];
trace("Hello", t);
trace(null, "Hello", t);
currentEvent = events[3];
trace(MarkerManager.getMarker("TEST"), "Hello", t);
currentEvent = events[4];
trace(obj);
currentEvent = events[5];
trace(MarkerManager.getMarker("TEST"), obj);
currentEvent = events[6];
trace(obj, t);
trace(null, obj, t);
currentEvent = events[7];
trace(MarkerManager.getMarker("TEST"), obj, t);
currentEvent = events[8];
trace(pattern, p1, p2);
currentEvent = events[9];
trace(MarkerManager.getMarker("TEST"), pattern, p1, p2);
currentEvent = events[10];
trace(simple);
trace(null, simple);
trace(null, simple, null);
currentEvent = events[11];
trace(simple, t);
trace(null, simple, t);
currentEvent = events[12];
trace(MarkerManager.getMarker("TEST"), simple, null);
currentEvent = events[13];
trace(MarkerManager.getMarker("TEST"), simple, t);
currentEvent = events[14];
trace(MarkerManager.getMarker("TEST"), simple);
}
@Test
public void testWarn() {
currentLevel = Level.WARN;
currentEvent = events[0];
warn("Hello");
warn(null, "Hello");
currentEvent = events[1];
warn(MarkerManager.getMarker("TEST"), "Hello");
currentEvent = events[2];
warn("Hello", t);
warn(null, "Hello", t);
currentEvent = events[3];
warn(MarkerManager.getMarker("TEST"), "Hello", t);
currentEvent = events[4];
warn(obj);
currentEvent = events[5];
warn(MarkerManager.getMarker("TEST"), obj);
currentEvent = events[6];
warn(obj, t);
warn(null, obj, t);
currentEvent = events[7];
warn(MarkerManager.getMarker("TEST"), obj, t);
currentEvent = events[8];
warn(pattern, p1, p2);
currentEvent = events[9];
warn(MarkerManager.getMarker("TEST"), pattern, p1, p2);
currentEvent = events[10];
warn(simple);
warn(null, simple);
warn(null, simple, null);
currentEvent = events[11];
warn(simple, t);
warn(null, simple, t);
currentEvent = events[12];
warn(MarkerManager.getMarker("TEST"), simple, null);
currentEvent = events[13];
warn(MarkerManager.getMarker("TEST"), simple, t);
currentEvent = events[14];
warn(MarkerManager.getMarker("TEST"), simple);
}
}
| MagicWiz/log4j2 | log4j-api/src/test/java/org/apache/logging/log4j/AbstractLoggerTest.java | Java | apache-2.0 | 26,624 |
/*
* Licensed to Metamarkets Group Inc. (Metamarkets) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. Metamarkets licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package io.druid.segment.data;
import io.druid.java.util.common.IAE;
import java.io.IOException;
public abstract class SingleValueIndexedIntsWriter implements IndexedIntsWriter
{
@Override
public void add(Object obj) throws IOException
{
if (obj == null) {
addValue(0);
} else if (obj instanceof Integer) {
addValue(((Number) obj).intValue());
} else if (obj instanceof int[]) {
int[] vals = (int[]) obj;
if (vals.length == 0) {
addValue(0);
} else {
addValue(vals[0]);
}
} else {
throw new IAE("Unsupported single value type: " + obj.getClass());
}
}
protected abstract void addValue(int val) throws IOException;
}
| erikdubbelboer/druid | processing/src/main/java/io/druid/segment/data/SingleValueIndexedIntsWriter.java | Java | apache-2.0 | 1,515 |
/*
* Copyright 2013 Red Hat, Inc. and/or its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jbpm.executor.cdi;
import javax.enterprise.context.ApplicationScoped;
import javax.enterprise.inject.Produces;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.PersistenceUnit;
import org.jbpm.shared.services.impl.TransactionalCommandService;
@ApplicationScoped
public class ExecutorDatabaseProducer {
private EntityManagerFactory emf;
@PersistenceUnit(unitName = "org.jbpm.executor")
@ApplicationScoped
@Produces
public EntityManagerFactory getEntityManagerFactory() {
if (this.emf == null) {
// this needs to be here for non EE containers
this.emf = Persistence.createEntityManagerFactory("org.jbpm.executor");
}
return this.emf;
}
@Produces
public TransactionalCommandService produceCommandService(EntityManagerFactory emf) {
return new TransactionalCommandService(emf);
}
}
| pleacu/jbpm | jbpm-services/jbpm-executor-cdi/src/test/java/org/jbpm/executor/cdi/ExecutorDatabaseProducer.java | Java | apache-2.0 | 1,548 |
// "Replace with 'Stream.mapToLong().sum()'" "true"
import java.util.Collection;
import java.util.List;
class Test {
void foo(List<List<String>> s) {
long count = s.stream().peek(System.out::println).flatMap(Collection::stream).c<caret>ount();
}
} | smmribeiro/intellij-community | java/java-tests/testData/inspection/inefficientStreamCount/beforePeekFlatMapCount.java | Java | apache-2.0 | 257 |
#!/usr/bin/env python
import xml.etree.ElementTree as ET
class brocade_ip_access_list(object):
"""Auto generated class.
"""
def __init__(self, **kwargs):
self._callback = kwargs.pop('callback')
def ip_acl_ip_access_list_standard_name(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
ip_acl = ET.SubElement(config, "ip-acl", xmlns="urn:brocade.com:mgmt:brocade-ip-access-list")
ip = ET.SubElement(ip_acl, "ip")
access_list = ET.SubElement(ip, "access-list")
standard = ET.SubElement(access_list, "standard")
name = ET.SubElement(standard, "name")
name.text = kwargs.pop('name')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def ip_acl_ip_access_list_standard_hide_ip_acl_std_seq_seq_id(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
ip_acl = ET.SubElement(config, "ip-acl", xmlns="urn:brocade.com:mgmt:brocade-ip-access-list")
ip = ET.SubElement(ip_acl, "ip")
access_list = ET.SubElement(ip, "access-list")
standard = ET.SubElement(access_list, "standard")
name_key = ET.SubElement(standard, "name")
name_key.text = kwargs.pop('name')
hide_ip_acl_std = ET.SubElement(standard, "hide-ip-acl-std")
seq = ET.SubElement(hide_ip_acl_std, "seq")
seq_id = ET.SubElement(seq, "seq-id")
seq_id.text = kwargs.pop('seq_id')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def ip_acl_ip_access_list_standard_hide_ip_acl_std_seq_action(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
ip_acl = ET.SubElement(config, "ip-acl", xmlns="urn:brocade.com:mgmt:brocade-ip-access-list")
ip = ET.SubElement(ip_acl, "ip")
access_list = ET.SubElement(ip, "access-list")
standard = ET.SubElement(access_list, "standard")
name_key = ET.SubElement(standard, "name")
name_key.text = kwargs.pop('name')
hide_ip_acl_std = ET.SubElement(standard, "hide-ip-acl-std")
seq = ET.SubElement(hide_ip_acl_std, "seq")
seq_id_key = ET.SubElement(seq, "seq-id")
seq_id_key.text = kwargs.pop('seq_id')
action = ET.SubElement(seq, "action")
action.text = kwargs.pop('action')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def ip_acl_ip_access_list_standard_hide_ip_acl_std_seq_src_host_any_sip(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
ip_acl = ET.SubElement(config, "ip-acl", xmlns="urn:brocade.com:mgmt:brocade-ip-access-list")
ip = ET.SubElement(ip_acl, "ip")
access_list = ET.SubElement(ip, "access-list")
standard = ET.SubElement(access_list, "standard")
name_key = ET.SubElement(standard, "name")
name_key.text = kwargs.pop('name')
hide_ip_acl_std = ET.SubElement(standard, "hide-ip-acl-std")
seq = ET.SubElement(hide_ip_acl_std, "seq")
seq_id_key = ET.SubElement(seq, "seq-id")
seq_id_key.text = kwargs.pop('seq_id')
src_host_any_sip = ET.SubElement(seq, "src-host-any-sip")
src_host_any_sip.text = kwargs.pop('src_host_any_sip')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def ip_acl_ip_access_list_standard_hide_ip_acl_std_seq_src_host_ip(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
ip_acl = ET.SubElement(config, "ip-acl", xmlns="urn:brocade.com:mgmt:brocade-ip-access-list")
ip = ET.SubElement(ip_acl, "ip")
access_list = ET.SubElement(ip, "access-list")
standard = ET.SubElement(access_list, "standard")
name_key = ET.SubElement(standard, "name")
name_key.text = kwargs.pop('name')
hide_ip_acl_std = ET.SubElement(standard, "hide-ip-acl-std")
seq = ET.SubElement(hide_ip_acl_std, "seq")
seq_id_key = ET.SubElement(seq, "seq-id")
seq_id_key.text = kwargs.pop('seq_id')
src_host_ip = ET.SubElement(seq, "src-host-ip")
src_host_ip.text = kwargs.pop('src_host_ip')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def ip_acl_ip_access_list_standard_hide_ip_acl_std_seq_src_mask(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
ip_acl = ET.SubElement(config, "ip-acl", xmlns="urn:brocade.com:mgmt:brocade-ip-access-list")
ip = ET.SubElement(ip_acl, "ip")
access_list = ET.SubElement(ip, "access-list")
standard = ET.SubElement(access_list, "standard")
name_key = ET.SubElement(standard, "name")
name_key.text = kwargs.pop('name')
hide_ip_acl_std = ET.SubElement(standard, "hide-ip-acl-std")
seq = ET.SubElement(hide_ip_acl_std, "seq")
seq_id_key = ET.SubElement(seq, "seq-id")
seq_id_key.text = kwargs.pop('seq_id')
src_mask = ET.SubElement(seq, "src-mask")
src_mask.text = kwargs.pop('src_mask')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def ip_acl_ip_access_list_standard_hide_ip_acl_std_seq_count(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
ip_acl = ET.SubElement(config, "ip-acl", xmlns="urn:brocade.com:mgmt:brocade-ip-access-list")
ip = ET.SubElement(ip_acl, "ip")
access_list = ET.SubElement(ip, "access-list")
standard = ET.SubElement(access_list, "standard")
name_key = ET.SubElement(standard, "name")
name_key.text = kwargs.pop('name')
hide_ip_acl_std = ET.SubElement(standard, "hide-ip-acl-std")
seq = ET.SubElement(hide_ip_acl_std, "seq")
seq_id_key = ET.SubElement(seq, "seq-id")
seq_id_key.text = kwargs.pop('seq_id')
count = ET.SubElement(seq, "count")
callback = kwargs.pop('callback', self._callback)
return callback(config)
def ip_acl_ip_access_list_standard_hide_ip_acl_std_seq_log(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
ip_acl = ET.SubElement(config, "ip-acl", xmlns="urn:brocade.com:mgmt:brocade-ip-access-list")
ip = ET.SubElement(ip_acl, "ip")
access_list = ET.SubElement(ip, "access-list")
standard = ET.SubElement(access_list, "standard")
name_key = ET.SubElement(standard, "name")
name_key.text = kwargs.pop('name')
hide_ip_acl_std = ET.SubElement(standard, "hide-ip-acl-std")
seq = ET.SubElement(hide_ip_acl_std, "seq")
seq_id_key = ET.SubElement(seq, "seq-id")
seq_id_key.text = kwargs.pop('seq_id')
log = ET.SubElement(seq, "log")
callback = kwargs.pop('callback', self._callback)
return callback(config)
def ip_acl_ip_access_list_extended_name(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
ip_acl = ET.SubElement(config, "ip-acl", xmlns="urn:brocade.com:mgmt:brocade-ip-access-list")
ip = ET.SubElement(ip_acl, "ip")
access_list = ET.SubElement(ip, "access-list")
extended = ET.SubElement(access_list, "extended")
name = ET.SubElement(extended, "name")
name.text = kwargs.pop('name')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def ip_acl_ip_access_list_extended_hide_ip_acl_ext_seq_seq_id(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
ip_acl = ET.SubElement(config, "ip-acl", xmlns="urn:brocade.com:mgmt:brocade-ip-access-list")
ip = ET.SubElement(ip_acl, "ip")
access_list = ET.SubElement(ip, "access-list")
extended = ET.SubElement(access_list, "extended")
name_key = ET.SubElement(extended, "name")
name_key.text = kwargs.pop('name')
hide_ip_acl_ext = ET.SubElement(extended, "hide-ip-acl-ext")
seq = ET.SubElement(hide_ip_acl_ext, "seq")
seq_id = ET.SubElement(seq, "seq-id")
seq_id.text = kwargs.pop('seq_id')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def ip_acl_ip_access_list_extended_hide_ip_acl_ext_seq_action(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
ip_acl = ET.SubElement(config, "ip-acl", xmlns="urn:brocade.com:mgmt:brocade-ip-access-list")
ip = ET.SubElement(ip_acl, "ip")
access_list = ET.SubElement(ip, "access-list")
extended = ET.SubElement(access_list, "extended")
name_key = ET.SubElement(extended, "name")
name_key.text = kwargs.pop('name')
hide_ip_acl_ext = ET.SubElement(extended, "hide-ip-acl-ext")
seq = ET.SubElement(hide_ip_acl_ext, "seq")
seq_id_key = ET.SubElement(seq, "seq-id")
seq_id_key.text = kwargs.pop('seq_id')
action = ET.SubElement(seq, "action")
action.text = kwargs.pop('action')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def ip_acl_ip_access_list_extended_hide_ip_acl_ext_seq_protocol_type(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
ip_acl = ET.SubElement(config, "ip-acl", xmlns="urn:brocade.com:mgmt:brocade-ip-access-list")
ip = ET.SubElement(ip_acl, "ip")
access_list = ET.SubElement(ip, "access-list")
extended = ET.SubElement(access_list, "extended")
name_key = ET.SubElement(extended, "name")
name_key.text = kwargs.pop('name')
hide_ip_acl_ext = ET.SubElement(extended, "hide-ip-acl-ext")
seq = ET.SubElement(hide_ip_acl_ext, "seq")
seq_id_key = ET.SubElement(seq, "seq-id")
seq_id_key.text = kwargs.pop('seq_id')
protocol_type = ET.SubElement(seq, "protocol-type")
protocol_type.text = kwargs.pop('protocol_type')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def ip_acl_ip_access_list_extended_hide_ip_acl_ext_seq_src_host_any_sip(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
ip_acl = ET.SubElement(config, "ip-acl", xmlns="urn:brocade.com:mgmt:brocade-ip-access-list")
ip = ET.SubElement(ip_acl, "ip")
access_list = ET.SubElement(ip, "access-list")
extended = ET.SubElement(access_list, "extended")
name_key = ET.SubElement(extended, "name")
name_key.text = kwargs.pop('name')
hide_ip_acl_ext = ET.SubElement(extended, "hide-ip-acl-ext")
seq = ET.SubElement(hide_ip_acl_ext, "seq")
seq_id_key = ET.SubElement(seq, "seq-id")
seq_id_key.text = kwargs.pop('seq_id')
src_host_any_sip = ET.SubElement(seq, "src-host-any-sip")
src_host_any_sip.text = kwargs.pop('src_host_any_sip')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def ip_acl_ip_access_list_extended_hide_ip_acl_ext_seq_src_host_ip(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
ip_acl = ET.SubElement(config, "ip-acl", xmlns="urn:brocade.com:mgmt:brocade-ip-access-list")
ip = ET.SubElement(ip_acl, "ip")
access_list = ET.SubElement(ip, "access-list")
extended = ET.SubElement(access_list, "extended")
name_key = ET.SubElement(extended, "name")
name_key.text = kwargs.pop('name')
hide_ip_acl_ext = ET.SubElement(extended, "hide-ip-acl-ext")
seq = ET.SubElement(hide_ip_acl_ext, "seq")
seq_id_key = ET.SubElement(seq, "seq-id")
seq_id_key.text = kwargs.pop('seq_id')
src_host_ip = ET.SubElement(seq, "src-host-ip")
src_host_ip.text = kwargs.pop('src_host_ip')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def ip_acl_ip_access_list_extended_hide_ip_acl_ext_seq_src_mask(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
ip_acl = ET.SubElement(config, "ip-acl", xmlns="urn:brocade.com:mgmt:brocade-ip-access-list")
ip = ET.SubElement(ip_acl, "ip")
access_list = ET.SubElement(ip, "access-list")
extended = ET.SubElement(access_list, "extended")
name_key = ET.SubElement(extended, "name")
name_key.text = kwargs.pop('name')
hide_ip_acl_ext = ET.SubElement(extended, "hide-ip-acl-ext")
seq = ET.SubElement(hide_ip_acl_ext, "seq")
seq_id_key = ET.SubElement(seq, "seq-id")
seq_id_key.text = kwargs.pop('seq_id')
src_mask = ET.SubElement(seq, "src-mask")
src_mask.text = kwargs.pop('src_mask')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def ip_acl_ip_access_list_extended_hide_ip_acl_ext_seq_sport(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
ip_acl = ET.SubElement(config, "ip-acl", xmlns="urn:brocade.com:mgmt:brocade-ip-access-list")
ip = ET.SubElement(ip_acl, "ip")
access_list = ET.SubElement(ip, "access-list")
extended = ET.SubElement(access_list, "extended")
name_key = ET.SubElement(extended, "name")
name_key.text = kwargs.pop('name')
hide_ip_acl_ext = ET.SubElement(extended, "hide-ip-acl-ext")
seq = ET.SubElement(hide_ip_acl_ext, "seq")
seq_id_key = ET.SubElement(seq, "seq-id")
seq_id_key.text = kwargs.pop('seq_id')
sport = ET.SubElement(seq, "sport")
sport.text = kwargs.pop('sport')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def ip_acl_ip_access_list_extended_hide_ip_acl_ext_seq_sport_number_eq_neq_tcp(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
ip_acl = ET.SubElement(config, "ip-acl", xmlns="urn:brocade.com:mgmt:brocade-ip-access-list")
ip = ET.SubElement(ip_acl, "ip")
access_list = ET.SubElement(ip, "access-list")
extended = ET.SubElement(access_list, "extended")
name_key = ET.SubElement(extended, "name")
name_key.text = kwargs.pop('name')
hide_ip_acl_ext = ET.SubElement(extended, "hide-ip-acl-ext")
seq = ET.SubElement(hide_ip_acl_ext, "seq")
seq_id_key = ET.SubElement(seq, "seq-id")
seq_id_key.text = kwargs.pop('seq_id')
sport_number_eq_neq_tcp = ET.SubElement(seq, "sport-number-eq-neq-tcp")
sport_number_eq_neq_tcp.text = kwargs.pop('sport_number_eq_neq_tcp')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def ip_acl_ip_access_list_extended_hide_ip_acl_ext_seq_sport_number_lt_tcp(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
ip_acl = ET.SubElement(config, "ip-acl", xmlns="urn:brocade.com:mgmt:brocade-ip-access-list")
ip = ET.SubElement(ip_acl, "ip")
access_list = ET.SubElement(ip, "access-list")
extended = ET.SubElement(access_list, "extended")
name_key = ET.SubElement(extended, "name")
name_key.text = kwargs.pop('name')
hide_ip_acl_ext = ET.SubElement(extended, "hide-ip-acl-ext")
seq = ET.SubElement(hide_ip_acl_ext, "seq")
seq_id_key = ET.SubElement(seq, "seq-id")
seq_id_key.text = kwargs.pop('seq_id')
sport_number_lt_tcp = ET.SubElement(seq, "sport-number-lt-tcp")
sport_number_lt_tcp.text = kwargs.pop('sport_number_lt_tcp')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def ip_acl_ip_access_list_extended_hide_ip_acl_ext_seq_sport_number_gt_tcp(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
ip_acl = ET.SubElement(config, "ip-acl", xmlns="urn:brocade.com:mgmt:brocade-ip-access-list")
ip = ET.SubElement(ip_acl, "ip")
access_list = ET.SubElement(ip, "access-list")
extended = ET.SubElement(access_list, "extended")
name_key = ET.SubElement(extended, "name")
name_key.text = kwargs.pop('name')
hide_ip_acl_ext = ET.SubElement(extended, "hide-ip-acl-ext")
seq = ET.SubElement(hide_ip_acl_ext, "seq")
seq_id_key = ET.SubElement(seq, "seq-id")
seq_id_key.text = kwargs.pop('seq_id')
sport_number_gt_tcp = ET.SubElement(seq, "sport-number-gt-tcp")
sport_number_gt_tcp.text = kwargs.pop('sport_number_gt_tcp')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def ip_acl_ip_access_list_extended_hide_ip_acl_ext_seq_sport_number_eq_neq_udp(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
ip_acl = ET.SubElement(config, "ip-acl", xmlns="urn:brocade.com:mgmt:brocade-ip-access-list")
ip = ET.SubElement(ip_acl, "ip")
access_list = ET.SubElement(ip, "access-list")
extended = ET.SubElement(access_list, "extended")
name_key = ET.SubElement(extended, "name")
name_key.text = kwargs.pop('name')
hide_ip_acl_ext = ET.SubElement(extended, "hide-ip-acl-ext")
seq = ET.SubElement(hide_ip_acl_ext, "seq")
seq_id_key = ET.SubElement(seq, "seq-id")
seq_id_key.text = kwargs.pop('seq_id')
sport_number_eq_neq_udp = ET.SubElement(seq, "sport-number-eq-neq-udp")
sport_number_eq_neq_udp.text = kwargs.pop('sport_number_eq_neq_udp')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def ip_acl_ip_access_list_extended_hide_ip_acl_ext_seq_sport_number_lt_udp(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
ip_acl = ET.SubElement(config, "ip-acl", xmlns="urn:brocade.com:mgmt:brocade-ip-access-list")
ip = ET.SubElement(ip_acl, "ip")
access_list = ET.SubElement(ip, "access-list")
extended = ET.SubElement(access_list, "extended")
name_key = ET.SubElement(extended, "name")
name_key.text = kwargs.pop('name')
hide_ip_acl_ext = ET.SubElement(extended, "hide-ip-acl-ext")
seq = ET.SubElement(hide_ip_acl_ext, "seq")
seq_id_key = ET.SubElement(seq, "seq-id")
seq_id_key.text = kwargs.pop('seq_id')
sport_number_lt_udp = ET.SubElement(seq, "sport-number-lt-udp")
sport_number_lt_udp.text = kwargs.pop('sport_number_lt_udp')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def ip_acl_ip_access_list_extended_hide_ip_acl_ext_seq_sport_number_gt_udp(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
ip_acl = ET.SubElement(config, "ip-acl", xmlns="urn:brocade.com:mgmt:brocade-ip-access-list")
ip = ET.SubElement(ip_acl, "ip")
access_list = ET.SubElement(ip, "access-list")
extended = ET.SubElement(access_list, "extended")
name_key = ET.SubElement(extended, "name")
name_key.text = kwargs.pop('name')
hide_ip_acl_ext = ET.SubElement(extended, "hide-ip-acl-ext")
seq = ET.SubElement(hide_ip_acl_ext, "seq")
seq_id_key = ET.SubElement(seq, "seq-id")
seq_id_key.text = kwargs.pop('seq_id')
sport_number_gt_udp = ET.SubElement(seq, "sport-number-gt-udp")
sport_number_gt_udp.text = kwargs.pop('sport_number_gt_udp')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def ip_acl_ip_access_list_extended_hide_ip_acl_ext_seq_sport_number_range_lower_tcp(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
ip_acl = ET.SubElement(config, "ip-acl", xmlns="urn:brocade.com:mgmt:brocade-ip-access-list")
ip = ET.SubElement(ip_acl, "ip")
access_list = ET.SubElement(ip, "access-list")
extended = ET.SubElement(access_list, "extended")
name_key = ET.SubElement(extended, "name")
name_key.text = kwargs.pop('name')
hide_ip_acl_ext = ET.SubElement(extended, "hide-ip-acl-ext")
seq = ET.SubElement(hide_ip_acl_ext, "seq")
seq_id_key = ET.SubElement(seq, "seq-id")
seq_id_key.text = kwargs.pop('seq_id')
sport_number_range_lower_tcp = ET.SubElement(seq, "sport-number-range-lower-tcp")
sport_number_range_lower_tcp.text = kwargs.pop('sport_number_range_lower_tcp')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def ip_acl_ip_access_list_extended_hide_ip_acl_ext_seq_sport_number_range_lower_udp(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
ip_acl = ET.SubElement(config, "ip-acl", xmlns="urn:brocade.com:mgmt:brocade-ip-access-list")
ip = ET.SubElement(ip_acl, "ip")
access_list = ET.SubElement(ip, "access-list")
extended = ET.SubElement(access_list, "extended")
name_key = ET.SubElement(extended, "name")
name_key.text = kwargs.pop('name')
hide_ip_acl_ext = ET.SubElement(extended, "hide-ip-acl-ext")
seq = ET.SubElement(hide_ip_acl_ext, "seq")
seq_id_key = ET.SubElement(seq, "seq-id")
seq_id_key.text = kwargs.pop('seq_id')
sport_number_range_lower_udp = ET.SubElement(seq, "sport-number-range-lower-udp")
sport_number_range_lower_udp.text = kwargs.pop('sport_number_range_lower_udp')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def ip_acl_ip_access_list_extended_hide_ip_acl_ext_seq_sport_number_range_higher_tcp(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
ip_acl = ET.SubElement(config, "ip-acl", xmlns="urn:brocade.com:mgmt:brocade-ip-access-list")
ip = ET.SubElement(ip_acl, "ip")
access_list = ET.SubElement(ip, "access-list")
extended = ET.SubElement(access_list, "extended")
name_key = ET.SubElement(extended, "name")
name_key.text = kwargs.pop('name')
hide_ip_acl_ext = ET.SubElement(extended, "hide-ip-acl-ext")
seq = ET.SubElement(hide_ip_acl_ext, "seq")
seq_id_key = ET.SubElement(seq, "seq-id")
seq_id_key.text = kwargs.pop('seq_id')
sport_number_range_higher_tcp = ET.SubElement(seq, "sport-number-range-higher-tcp")
sport_number_range_higher_tcp.text = kwargs.pop('sport_number_range_higher_tcp')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def ip_acl_ip_access_list_extended_hide_ip_acl_ext_seq_sport_number_range_higher_udp(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
ip_acl = ET.SubElement(config, "ip-acl", xmlns="urn:brocade.com:mgmt:brocade-ip-access-list")
ip = ET.SubElement(ip_acl, "ip")
access_list = ET.SubElement(ip, "access-list")
extended = ET.SubElement(access_list, "extended")
name_key = ET.SubElement(extended, "name")
name_key.text = kwargs.pop('name')
hide_ip_acl_ext = ET.SubElement(extended, "hide-ip-acl-ext")
seq = ET.SubElement(hide_ip_acl_ext, "seq")
seq_id_key = ET.SubElement(seq, "seq-id")
seq_id_key.text = kwargs.pop('seq_id')
sport_number_range_higher_udp = ET.SubElement(seq, "sport-number-range-higher-udp")
sport_number_range_higher_udp.text = kwargs.pop('sport_number_range_higher_udp')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def ip_acl_ip_access_list_extended_hide_ip_acl_ext_seq_dst_host_any_dip(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
ip_acl = ET.SubElement(config, "ip-acl", xmlns="urn:brocade.com:mgmt:brocade-ip-access-list")
ip = ET.SubElement(ip_acl, "ip")
access_list = ET.SubElement(ip, "access-list")
extended = ET.SubElement(access_list, "extended")
name_key = ET.SubElement(extended, "name")
name_key.text = kwargs.pop('name')
hide_ip_acl_ext = ET.SubElement(extended, "hide-ip-acl-ext")
seq = ET.SubElement(hide_ip_acl_ext, "seq")
seq_id_key = ET.SubElement(seq, "seq-id")
seq_id_key.text = kwargs.pop('seq_id')
dst_host_any_dip = ET.SubElement(seq, "dst-host-any-dip")
dst_host_any_dip.text = kwargs.pop('dst_host_any_dip')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def ip_acl_ip_access_list_extended_hide_ip_acl_ext_seq_dst_host_ip(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
ip_acl = ET.SubElement(config, "ip-acl", xmlns="urn:brocade.com:mgmt:brocade-ip-access-list")
ip = ET.SubElement(ip_acl, "ip")
access_list = ET.SubElement(ip, "access-list")
extended = ET.SubElement(access_list, "extended")
name_key = ET.SubElement(extended, "name")
name_key.text = kwargs.pop('name')
hide_ip_acl_ext = ET.SubElement(extended, "hide-ip-acl-ext")
seq = ET.SubElement(hide_ip_acl_ext, "seq")
seq_id_key = ET.SubElement(seq, "seq-id")
seq_id_key.text = kwargs.pop('seq_id')
dst_host_ip = ET.SubElement(seq, "dst-host-ip")
dst_host_ip.text = kwargs.pop('dst_host_ip')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def ip_acl_ip_access_list_extended_hide_ip_acl_ext_seq_dst_mask(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
ip_acl = ET.SubElement(config, "ip-acl", xmlns="urn:brocade.com:mgmt:brocade-ip-access-list")
ip = ET.SubElement(ip_acl, "ip")
access_list = ET.SubElement(ip, "access-list")
extended = ET.SubElement(access_list, "extended")
name_key = ET.SubElement(extended, "name")
name_key.text = kwargs.pop('name')
hide_ip_acl_ext = ET.SubElement(extended, "hide-ip-acl-ext")
seq = ET.SubElement(hide_ip_acl_ext, "seq")
seq_id_key = ET.SubElement(seq, "seq-id")
seq_id_key.text = kwargs.pop('seq_id')
dst_mask = ET.SubElement(seq, "dst-mask")
dst_mask.text = kwargs.pop('dst_mask')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def ip_acl_ip_access_list_extended_hide_ip_acl_ext_seq_dport(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
ip_acl = ET.SubElement(config, "ip-acl", xmlns="urn:brocade.com:mgmt:brocade-ip-access-list")
ip = ET.SubElement(ip_acl, "ip")
access_list = ET.SubElement(ip, "access-list")
extended = ET.SubElement(access_list, "extended")
name_key = ET.SubElement(extended, "name")
name_key.text = kwargs.pop('name')
hide_ip_acl_ext = ET.SubElement(extended, "hide-ip-acl-ext")
seq = ET.SubElement(hide_ip_acl_ext, "seq")
seq_id_key = ET.SubElement(seq, "seq-id")
seq_id_key.text = kwargs.pop('seq_id')
dport = ET.SubElement(seq, "dport")
dport.text = kwargs.pop('dport')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def ip_acl_ip_access_list_extended_hide_ip_acl_ext_seq_dport_number_eq_neq_tcp(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
ip_acl = ET.SubElement(config, "ip-acl", xmlns="urn:brocade.com:mgmt:brocade-ip-access-list")
ip = ET.SubElement(ip_acl, "ip")
access_list = ET.SubElement(ip, "access-list")
extended = ET.SubElement(access_list, "extended")
name_key = ET.SubElement(extended, "name")
name_key.text = kwargs.pop('name')
hide_ip_acl_ext = ET.SubElement(extended, "hide-ip-acl-ext")
seq = ET.SubElement(hide_ip_acl_ext, "seq")
seq_id_key = ET.SubElement(seq, "seq-id")
seq_id_key.text = kwargs.pop('seq_id')
dport_number_eq_neq_tcp = ET.SubElement(seq, "dport-number-eq-neq-tcp")
dport_number_eq_neq_tcp.text = kwargs.pop('dport_number_eq_neq_tcp')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def ip_acl_ip_access_list_extended_hide_ip_acl_ext_seq_dport_number_lt_tcp(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
ip_acl = ET.SubElement(config, "ip-acl", xmlns="urn:brocade.com:mgmt:brocade-ip-access-list")
ip = ET.SubElement(ip_acl, "ip")
access_list = ET.SubElement(ip, "access-list")
extended = ET.SubElement(access_list, "extended")
name_key = ET.SubElement(extended, "name")
name_key.text = kwargs.pop('name')
hide_ip_acl_ext = ET.SubElement(extended, "hide-ip-acl-ext")
seq = ET.SubElement(hide_ip_acl_ext, "seq")
seq_id_key = ET.SubElement(seq, "seq-id")
seq_id_key.text = kwargs.pop('seq_id')
dport_number_lt_tcp = ET.SubElement(seq, "dport-number-lt-tcp")
dport_number_lt_tcp.text = kwargs.pop('dport_number_lt_tcp')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def ip_acl_ip_access_list_extended_hide_ip_acl_ext_seq_dport_number_gt_tcp(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
ip_acl = ET.SubElement(config, "ip-acl", xmlns="urn:brocade.com:mgmt:brocade-ip-access-list")
ip = ET.SubElement(ip_acl, "ip")
access_list = ET.SubElement(ip, "access-list")
extended = ET.SubElement(access_list, "extended")
name_key = ET.SubElement(extended, "name")
name_key.text = kwargs.pop('name')
hide_ip_acl_ext = ET.SubElement(extended, "hide-ip-acl-ext")
seq = ET.SubElement(hide_ip_acl_ext, "seq")
seq_id_key = ET.SubElement(seq, "seq-id")
seq_id_key.text = kwargs.pop('seq_id')
dport_number_gt_tcp = ET.SubElement(seq, "dport-number-gt-tcp")
dport_number_gt_tcp.text = kwargs.pop('dport_number_gt_tcp')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def ip_acl_ip_access_list_extended_hide_ip_acl_ext_seq_dport_number_eq_neq_udp(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
ip_acl = ET.SubElement(config, "ip-acl", xmlns="urn:brocade.com:mgmt:brocade-ip-access-list")
ip = ET.SubElement(ip_acl, "ip")
access_list = ET.SubElement(ip, "access-list")
extended = ET.SubElement(access_list, "extended")
name_key = ET.SubElement(extended, "name")
name_key.text = kwargs.pop('name')
hide_ip_acl_ext = ET.SubElement(extended, "hide-ip-acl-ext")
seq = ET.SubElement(hide_ip_acl_ext, "seq")
seq_id_key = ET.SubElement(seq, "seq-id")
seq_id_key.text = kwargs.pop('seq_id')
dport_number_eq_neq_udp = ET.SubElement(seq, "dport-number-eq-neq-udp")
dport_number_eq_neq_udp.text = kwargs.pop('dport_number_eq_neq_udp')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def ip_acl_ip_access_list_extended_hide_ip_acl_ext_seq_dport_number_lt_udp(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
ip_acl = ET.SubElement(config, "ip-acl", xmlns="urn:brocade.com:mgmt:brocade-ip-access-list")
ip = ET.SubElement(ip_acl, "ip")
access_list = ET.SubElement(ip, "access-list")
extended = ET.SubElement(access_list, "extended")
name_key = ET.SubElement(extended, "name")
name_key.text = kwargs.pop('name')
hide_ip_acl_ext = ET.SubElement(extended, "hide-ip-acl-ext")
seq = ET.SubElement(hide_ip_acl_ext, "seq")
seq_id_key = ET.SubElement(seq, "seq-id")
seq_id_key.text = kwargs.pop('seq_id')
dport_number_lt_udp = ET.SubElement(seq, "dport-number-lt-udp")
dport_number_lt_udp.text = kwargs.pop('dport_number_lt_udp')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def ip_acl_ip_access_list_extended_hide_ip_acl_ext_seq_dport_number_gt_udp(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
ip_acl = ET.SubElement(config, "ip-acl", xmlns="urn:brocade.com:mgmt:brocade-ip-access-list")
ip = ET.SubElement(ip_acl, "ip")
access_list = ET.SubElement(ip, "access-list")
extended = ET.SubElement(access_list, "extended")
name_key = ET.SubElement(extended, "name")
name_key.text = kwargs.pop('name')
hide_ip_acl_ext = ET.SubElement(extended, "hide-ip-acl-ext")
seq = ET.SubElement(hide_ip_acl_ext, "seq")
seq_id_key = ET.SubElement(seq, "seq-id")
seq_id_key.text = kwargs.pop('seq_id')
dport_number_gt_udp = ET.SubElement(seq, "dport-number-gt-udp")
dport_number_gt_udp.text = kwargs.pop('dport_number_gt_udp')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def ip_acl_ip_access_list_extended_hide_ip_acl_ext_seq_dport_number_range_lower_tcp(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
ip_acl = ET.SubElement(config, "ip-acl", xmlns="urn:brocade.com:mgmt:brocade-ip-access-list")
ip = ET.SubElement(ip_acl, "ip")
access_list = ET.SubElement(ip, "access-list")
extended = ET.SubElement(access_list, "extended")
name_key = ET.SubElement(extended, "name")
name_key.text = kwargs.pop('name')
hide_ip_acl_ext = ET.SubElement(extended, "hide-ip-acl-ext")
seq = ET.SubElement(hide_ip_acl_ext, "seq")
seq_id_key = ET.SubElement(seq, "seq-id")
seq_id_key.text = kwargs.pop('seq_id')
dport_number_range_lower_tcp = ET.SubElement(seq, "dport-number-range-lower-tcp")
dport_number_range_lower_tcp.text = kwargs.pop('dport_number_range_lower_tcp')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def ip_acl_ip_access_list_extended_hide_ip_acl_ext_seq_dport_number_range_lower_udp(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
ip_acl = ET.SubElement(config, "ip-acl", xmlns="urn:brocade.com:mgmt:brocade-ip-access-list")
ip = ET.SubElement(ip_acl, "ip")
access_list = ET.SubElement(ip, "access-list")
extended = ET.SubElement(access_list, "extended")
name_key = ET.SubElement(extended, "name")
name_key.text = kwargs.pop('name')
hide_ip_acl_ext = ET.SubElement(extended, "hide-ip-acl-ext")
seq = ET.SubElement(hide_ip_acl_ext, "seq")
seq_id_key = ET.SubElement(seq, "seq-id")
seq_id_key.text = kwargs.pop('seq_id')
dport_number_range_lower_udp = ET.SubElement(seq, "dport-number-range-lower-udp")
dport_number_range_lower_udp.text = kwargs.pop('dport_number_range_lower_udp')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def ip_acl_ip_access_list_extended_hide_ip_acl_ext_seq_dport_number_range_higher_tcp(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
ip_acl = ET.SubElement(config, "ip-acl", xmlns="urn:brocade.com:mgmt:brocade-ip-access-list")
ip = ET.SubElement(ip_acl, "ip")
access_list = ET.SubElement(ip, "access-list")
extended = ET.SubElement(access_list, "extended")
name_key = ET.SubElement(extended, "name")
name_key.text = kwargs.pop('name')
hide_ip_acl_ext = ET.SubElement(extended, "hide-ip-acl-ext")
seq = ET.SubElement(hide_ip_acl_ext, "seq")
seq_id_key = ET.SubElement(seq, "seq-id")
seq_id_key.text = kwargs.pop('seq_id')
dport_number_range_higher_tcp = ET.SubElement(seq, "dport-number-range-higher-tcp")
dport_number_range_higher_tcp.text = kwargs.pop('dport_number_range_higher_tcp')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def ip_acl_ip_access_list_extended_hide_ip_acl_ext_seq_dport_number_range_higher_udp(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
ip_acl = ET.SubElement(config, "ip-acl", xmlns="urn:brocade.com:mgmt:brocade-ip-access-list")
ip = ET.SubElement(ip_acl, "ip")
access_list = ET.SubElement(ip, "access-list")
extended = ET.SubElement(access_list, "extended")
name_key = ET.SubElement(extended, "name")
name_key.text = kwargs.pop('name')
hide_ip_acl_ext = ET.SubElement(extended, "hide-ip-acl-ext")
seq = ET.SubElement(hide_ip_acl_ext, "seq")
seq_id_key = ET.SubElement(seq, "seq-id")
seq_id_key.text = kwargs.pop('seq_id')
dport_number_range_higher_udp = ET.SubElement(seq, "dport-number-range-higher-udp")
dport_number_range_higher_udp.text = kwargs.pop('dport_number_range_higher_udp')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def ip_acl_ip_access_list_extended_hide_ip_acl_ext_seq_dscp(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
ip_acl = ET.SubElement(config, "ip-acl", xmlns="urn:brocade.com:mgmt:brocade-ip-access-list")
ip = ET.SubElement(ip_acl, "ip")
access_list = ET.SubElement(ip, "access-list")
extended = ET.SubElement(access_list, "extended")
name_key = ET.SubElement(extended, "name")
name_key.text = kwargs.pop('name')
hide_ip_acl_ext = ET.SubElement(extended, "hide-ip-acl-ext")
seq = ET.SubElement(hide_ip_acl_ext, "seq")
seq_id_key = ET.SubElement(seq, "seq-id")
seq_id_key.text = kwargs.pop('seq_id')
dscp = ET.SubElement(seq, "dscp")
dscp.text = kwargs.pop('dscp')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def ip_acl_ip_access_list_extended_hide_ip_acl_ext_seq_urg(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
ip_acl = ET.SubElement(config, "ip-acl", xmlns="urn:brocade.com:mgmt:brocade-ip-access-list")
ip = ET.SubElement(ip_acl, "ip")
access_list = ET.SubElement(ip, "access-list")
extended = ET.SubElement(access_list, "extended")
name_key = ET.SubElement(extended, "name")
name_key.text = kwargs.pop('name')
hide_ip_acl_ext = ET.SubElement(extended, "hide-ip-acl-ext")
seq = ET.SubElement(hide_ip_acl_ext, "seq")
seq_id_key = ET.SubElement(seq, "seq-id")
seq_id_key.text = kwargs.pop('seq_id')
urg = ET.SubElement(seq, "urg")
callback = kwargs.pop('callback', self._callback)
return callback(config)
def ip_acl_ip_access_list_extended_hide_ip_acl_ext_seq_ack(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
ip_acl = ET.SubElement(config, "ip-acl", xmlns="urn:brocade.com:mgmt:brocade-ip-access-list")
ip = ET.SubElement(ip_acl, "ip")
access_list = ET.SubElement(ip, "access-list")
extended = ET.SubElement(access_list, "extended")
name_key = ET.SubElement(extended, "name")
name_key.text = kwargs.pop('name')
hide_ip_acl_ext = ET.SubElement(extended, "hide-ip-acl-ext")
seq = ET.SubElement(hide_ip_acl_ext, "seq")
seq_id_key = ET.SubElement(seq, "seq-id")
seq_id_key.text = kwargs.pop('seq_id')
ack = ET.SubElement(seq, "ack")
callback = kwargs.pop('callback', self._callback)
return callback(config)
def ip_acl_ip_access_list_extended_hide_ip_acl_ext_seq_push(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
ip_acl = ET.SubElement(config, "ip-acl", xmlns="urn:brocade.com:mgmt:brocade-ip-access-list")
ip = ET.SubElement(ip_acl, "ip")
access_list = ET.SubElement(ip, "access-list")
extended = ET.SubElement(access_list, "extended")
name_key = ET.SubElement(extended, "name")
name_key.text = kwargs.pop('name')
hide_ip_acl_ext = ET.SubElement(extended, "hide-ip-acl-ext")
seq = ET.SubElement(hide_ip_acl_ext, "seq")
seq_id_key = ET.SubElement(seq, "seq-id")
seq_id_key.text = kwargs.pop('seq_id')
push = ET.SubElement(seq, "push")
callback = kwargs.pop('callback', self._callback)
return callback(config)
def ip_acl_ip_access_list_extended_hide_ip_acl_ext_seq_fin(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
ip_acl = ET.SubElement(config, "ip-acl", xmlns="urn:brocade.com:mgmt:brocade-ip-access-list")
ip = ET.SubElement(ip_acl, "ip")
access_list = ET.SubElement(ip, "access-list")
extended = ET.SubElement(access_list, "extended")
name_key = ET.SubElement(extended, "name")
name_key.text = kwargs.pop('name')
hide_ip_acl_ext = ET.SubElement(extended, "hide-ip-acl-ext")
seq = ET.SubElement(hide_ip_acl_ext, "seq")
seq_id_key = ET.SubElement(seq, "seq-id")
seq_id_key.text = kwargs.pop('seq_id')
fin = ET.SubElement(seq, "fin")
callback = kwargs.pop('callback', self._callback)
return callback(config)
def ip_acl_ip_access_list_extended_hide_ip_acl_ext_seq_rst(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
ip_acl = ET.SubElement(config, "ip-acl", xmlns="urn:brocade.com:mgmt:brocade-ip-access-list")
ip = ET.SubElement(ip_acl, "ip")
access_list = ET.SubElement(ip, "access-list")
extended = ET.SubElement(access_list, "extended")
name_key = ET.SubElement(extended, "name")
name_key.text = kwargs.pop('name')
hide_ip_acl_ext = ET.SubElement(extended, "hide-ip-acl-ext")
seq = ET.SubElement(hide_ip_acl_ext, "seq")
seq_id_key = ET.SubElement(seq, "seq-id")
seq_id_key.text = kwargs.pop('seq_id')
rst = ET.SubElement(seq, "rst")
callback = kwargs.pop('callback', self._callback)
return callback(config)
def ip_acl_ip_access_list_extended_hide_ip_acl_ext_seq_sync(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
ip_acl = ET.SubElement(config, "ip-acl", xmlns="urn:brocade.com:mgmt:brocade-ip-access-list")
ip = ET.SubElement(ip_acl, "ip")
access_list = ET.SubElement(ip, "access-list")
extended = ET.SubElement(access_list, "extended")
name_key = ET.SubElement(extended, "name")
name_key.text = kwargs.pop('name')
hide_ip_acl_ext = ET.SubElement(extended, "hide-ip-acl-ext")
seq = ET.SubElement(hide_ip_acl_ext, "seq")
seq_id_key = ET.SubElement(seq, "seq-id")
seq_id_key.text = kwargs.pop('seq_id')
sync = ET.SubElement(seq, "sync")
callback = kwargs.pop('callback', self._callback)
return callback(config)
def ip_acl_ip_access_list_extended_hide_ip_acl_ext_seq_vlan(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
ip_acl = ET.SubElement(config, "ip-acl", xmlns="urn:brocade.com:mgmt:brocade-ip-access-list")
ip = ET.SubElement(ip_acl, "ip")
access_list = ET.SubElement(ip, "access-list")
extended = ET.SubElement(access_list, "extended")
name_key = ET.SubElement(extended, "name")
name_key.text = kwargs.pop('name')
hide_ip_acl_ext = ET.SubElement(extended, "hide-ip-acl-ext")
seq = ET.SubElement(hide_ip_acl_ext, "seq")
seq_id_key = ET.SubElement(seq, "seq-id")
seq_id_key.text = kwargs.pop('seq_id')
vlan = ET.SubElement(seq, "vlan")
vlan.text = kwargs.pop('vlan')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def ip_acl_ip_access_list_extended_hide_ip_acl_ext_seq_count(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
ip_acl = ET.SubElement(config, "ip-acl", xmlns="urn:brocade.com:mgmt:brocade-ip-access-list")
ip = ET.SubElement(ip_acl, "ip")
access_list = ET.SubElement(ip, "access-list")
extended = ET.SubElement(access_list, "extended")
name_key = ET.SubElement(extended, "name")
name_key.text = kwargs.pop('name')
hide_ip_acl_ext = ET.SubElement(extended, "hide-ip-acl-ext")
seq = ET.SubElement(hide_ip_acl_ext, "seq")
seq_id_key = ET.SubElement(seq, "seq-id")
seq_id_key.text = kwargs.pop('seq_id')
count = ET.SubElement(seq, "count")
callback = kwargs.pop('callback', self._callback)
return callback(config)
def ip_acl_ip_access_list_extended_hide_ip_acl_ext_seq_log(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
ip_acl = ET.SubElement(config, "ip-acl", xmlns="urn:brocade.com:mgmt:brocade-ip-access-list")
ip = ET.SubElement(ip_acl, "ip")
access_list = ET.SubElement(ip, "access-list")
extended = ET.SubElement(access_list, "extended")
name_key = ET.SubElement(extended, "name")
name_key.text = kwargs.pop('name')
hide_ip_acl_ext = ET.SubElement(extended, "hide-ip-acl-ext")
seq = ET.SubElement(hide_ip_acl_ext, "seq")
seq_id_key = ET.SubElement(seq, "seq-id")
seq_id_key.text = kwargs.pop('seq_id')
log = ET.SubElement(seq, "log")
callback = kwargs.pop('callback', self._callback)
return callback(config)
def ip_acl_ip_access_list_standard_name(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
ip_acl = ET.SubElement(config, "ip-acl", xmlns="urn:brocade.com:mgmt:brocade-ip-access-list")
ip = ET.SubElement(ip_acl, "ip")
access_list = ET.SubElement(ip, "access-list")
standard = ET.SubElement(access_list, "standard")
name = ET.SubElement(standard, "name")
name.text = kwargs.pop('name')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def ip_acl_ip_access_list_standard_hide_ip_acl_std_seq_seq_id(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
ip_acl = ET.SubElement(config, "ip-acl", xmlns="urn:brocade.com:mgmt:brocade-ip-access-list")
ip = ET.SubElement(ip_acl, "ip")
access_list = ET.SubElement(ip, "access-list")
standard = ET.SubElement(access_list, "standard")
name_key = ET.SubElement(standard, "name")
name_key.text = kwargs.pop('name')
hide_ip_acl_std = ET.SubElement(standard, "hide-ip-acl-std")
seq = ET.SubElement(hide_ip_acl_std, "seq")
seq_id = ET.SubElement(seq, "seq-id")
seq_id.text = kwargs.pop('seq_id')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def ip_acl_ip_access_list_standard_hide_ip_acl_std_seq_action(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
ip_acl = ET.SubElement(config, "ip-acl", xmlns="urn:brocade.com:mgmt:brocade-ip-access-list")
ip = ET.SubElement(ip_acl, "ip")
access_list = ET.SubElement(ip, "access-list")
standard = ET.SubElement(access_list, "standard")
name_key = ET.SubElement(standard, "name")
name_key.text = kwargs.pop('name')
hide_ip_acl_std = ET.SubElement(standard, "hide-ip-acl-std")
seq = ET.SubElement(hide_ip_acl_std, "seq")
seq_id_key = ET.SubElement(seq, "seq-id")
seq_id_key.text = kwargs.pop('seq_id')
action = ET.SubElement(seq, "action")
action.text = kwargs.pop('action')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def ip_acl_ip_access_list_standard_hide_ip_acl_std_seq_src_host_any_sip(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
ip_acl = ET.SubElement(config, "ip-acl", xmlns="urn:brocade.com:mgmt:brocade-ip-access-list")
ip = ET.SubElement(ip_acl, "ip")
access_list = ET.SubElement(ip, "access-list")
standard = ET.SubElement(access_list, "standard")
name_key = ET.SubElement(standard, "name")
name_key.text = kwargs.pop('name')
hide_ip_acl_std = ET.SubElement(standard, "hide-ip-acl-std")
seq = ET.SubElement(hide_ip_acl_std, "seq")
seq_id_key = ET.SubElement(seq, "seq-id")
seq_id_key.text = kwargs.pop('seq_id')
src_host_any_sip = ET.SubElement(seq, "src-host-any-sip")
src_host_any_sip.text = kwargs.pop('src_host_any_sip')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def ip_acl_ip_access_list_standard_hide_ip_acl_std_seq_src_host_ip(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
ip_acl = ET.SubElement(config, "ip-acl", xmlns="urn:brocade.com:mgmt:brocade-ip-access-list")
ip = ET.SubElement(ip_acl, "ip")
access_list = ET.SubElement(ip, "access-list")
standard = ET.SubElement(access_list, "standard")
name_key = ET.SubElement(standard, "name")
name_key.text = kwargs.pop('name')
hide_ip_acl_std = ET.SubElement(standard, "hide-ip-acl-std")
seq = ET.SubElement(hide_ip_acl_std, "seq")
seq_id_key = ET.SubElement(seq, "seq-id")
seq_id_key.text = kwargs.pop('seq_id')
src_host_ip = ET.SubElement(seq, "src-host-ip")
src_host_ip.text = kwargs.pop('src_host_ip')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def ip_acl_ip_access_list_standard_hide_ip_acl_std_seq_src_mask(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
ip_acl = ET.SubElement(config, "ip-acl", xmlns="urn:brocade.com:mgmt:brocade-ip-access-list")
ip = ET.SubElement(ip_acl, "ip")
access_list = ET.SubElement(ip, "access-list")
standard = ET.SubElement(access_list, "standard")
name_key = ET.SubElement(standard, "name")
name_key.text = kwargs.pop('name')
hide_ip_acl_std = ET.SubElement(standard, "hide-ip-acl-std")
seq = ET.SubElement(hide_ip_acl_std, "seq")
seq_id_key = ET.SubElement(seq, "seq-id")
seq_id_key.text = kwargs.pop('seq_id')
src_mask = ET.SubElement(seq, "src-mask")
src_mask.text = kwargs.pop('src_mask')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def ip_acl_ip_access_list_standard_hide_ip_acl_std_seq_count(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
ip_acl = ET.SubElement(config, "ip-acl", xmlns="urn:brocade.com:mgmt:brocade-ip-access-list")
ip = ET.SubElement(ip_acl, "ip")
access_list = ET.SubElement(ip, "access-list")
standard = ET.SubElement(access_list, "standard")
name_key = ET.SubElement(standard, "name")
name_key.text = kwargs.pop('name')
hide_ip_acl_std = ET.SubElement(standard, "hide-ip-acl-std")
seq = ET.SubElement(hide_ip_acl_std, "seq")
seq_id_key = ET.SubElement(seq, "seq-id")
seq_id_key.text = kwargs.pop('seq_id')
count = ET.SubElement(seq, "count")
callback = kwargs.pop('callback', self._callback)
return callback(config)
def ip_acl_ip_access_list_standard_hide_ip_acl_std_seq_log(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
ip_acl = ET.SubElement(config, "ip-acl", xmlns="urn:brocade.com:mgmt:brocade-ip-access-list")
ip = ET.SubElement(ip_acl, "ip")
access_list = ET.SubElement(ip, "access-list")
standard = ET.SubElement(access_list, "standard")
name_key = ET.SubElement(standard, "name")
name_key.text = kwargs.pop('name')
hide_ip_acl_std = ET.SubElement(standard, "hide-ip-acl-std")
seq = ET.SubElement(hide_ip_acl_std, "seq")
seq_id_key = ET.SubElement(seq, "seq-id")
seq_id_key.text = kwargs.pop('seq_id')
log = ET.SubElement(seq, "log")
callback = kwargs.pop('callback', self._callback)
return callback(config)
def ip_acl_ip_access_list_extended_name(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
ip_acl = ET.SubElement(config, "ip-acl", xmlns="urn:brocade.com:mgmt:brocade-ip-access-list")
ip = ET.SubElement(ip_acl, "ip")
access_list = ET.SubElement(ip, "access-list")
extended = ET.SubElement(access_list, "extended")
name = ET.SubElement(extended, "name")
name.text = kwargs.pop('name')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def ip_acl_ip_access_list_extended_hide_ip_acl_ext_seq_seq_id(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
ip_acl = ET.SubElement(config, "ip-acl", xmlns="urn:brocade.com:mgmt:brocade-ip-access-list")
ip = ET.SubElement(ip_acl, "ip")
access_list = ET.SubElement(ip, "access-list")
extended = ET.SubElement(access_list, "extended")
name_key = ET.SubElement(extended, "name")
name_key.text = kwargs.pop('name')
hide_ip_acl_ext = ET.SubElement(extended, "hide-ip-acl-ext")
seq = ET.SubElement(hide_ip_acl_ext, "seq")
seq_id = ET.SubElement(seq, "seq-id")
seq_id.text = kwargs.pop('seq_id')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def ip_acl_ip_access_list_extended_hide_ip_acl_ext_seq_action(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
ip_acl = ET.SubElement(config, "ip-acl", xmlns="urn:brocade.com:mgmt:brocade-ip-access-list")
ip = ET.SubElement(ip_acl, "ip")
access_list = ET.SubElement(ip, "access-list")
extended = ET.SubElement(access_list, "extended")
name_key = ET.SubElement(extended, "name")
name_key.text = kwargs.pop('name')
hide_ip_acl_ext = ET.SubElement(extended, "hide-ip-acl-ext")
seq = ET.SubElement(hide_ip_acl_ext, "seq")
seq_id_key = ET.SubElement(seq, "seq-id")
seq_id_key.text = kwargs.pop('seq_id')
action = ET.SubElement(seq, "action")
action.text = kwargs.pop('action')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def ip_acl_ip_access_list_extended_hide_ip_acl_ext_seq_protocol_type(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
ip_acl = ET.SubElement(config, "ip-acl", xmlns="urn:brocade.com:mgmt:brocade-ip-access-list")
ip = ET.SubElement(ip_acl, "ip")
access_list = ET.SubElement(ip, "access-list")
extended = ET.SubElement(access_list, "extended")
name_key = ET.SubElement(extended, "name")
name_key.text = kwargs.pop('name')
hide_ip_acl_ext = ET.SubElement(extended, "hide-ip-acl-ext")
seq = ET.SubElement(hide_ip_acl_ext, "seq")
seq_id_key = ET.SubElement(seq, "seq-id")
seq_id_key.text = kwargs.pop('seq_id')
protocol_type = ET.SubElement(seq, "protocol-type")
protocol_type.text = kwargs.pop('protocol_type')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def ip_acl_ip_access_list_extended_hide_ip_acl_ext_seq_src_host_any_sip(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
ip_acl = ET.SubElement(config, "ip-acl", xmlns="urn:brocade.com:mgmt:brocade-ip-access-list")
ip = ET.SubElement(ip_acl, "ip")
access_list = ET.SubElement(ip, "access-list")
extended = ET.SubElement(access_list, "extended")
name_key = ET.SubElement(extended, "name")
name_key.text = kwargs.pop('name')
hide_ip_acl_ext = ET.SubElement(extended, "hide-ip-acl-ext")
seq = ET.SubElement(hide_ip_acl_ext, "seq")
seq_id_key = ET.SubElement(seq, "seq-id")
seq_id_key.text = kwargs.pop('seq_id')
src_host_any_sip = ET.SubElement(seq, "src-host-any-sip")
src_host_any_sip.text = kwargs.pop('src_host_any_sip')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def ip_acl_ip_access_list_extended_hide_ip_acl_ext_seq_src_host_ip(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
ip_acl = ET.SubElement(config, "ip-acl", xmlns="urn:brocade.com:mgmt:brocade-ip-access-list")
ip = ET.SubElement(ip_acl, "ip")
access_list = ET.SubElement(ip, "access-list")
extended = ET.SubElement(access_list, "extended")
name_key = ET.SubElement(extended, "name")
name_key.text = kwargs.pop('name')
hide_ip_acl_ext = ET.SubElement(extended, "hide-ip-acl-ext")
seq = ET.SubElement(hide_ip_acl_ext, "seq")
seq_id_key = ET.SubElement(seq, "seq-id")
seq_id_key.text = kwargs.pop('seq_id')
src_host_ip = ET.SubElement(seq, "src-host-ip")
src_host_ip.text = kwargs.pop('src_host_ip')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def ip_acl_ip_access_list_extended_hide_ip_acl_ext_seq_src_mask(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
ip_acl = ET.SubElement(config, "ip-acl", xmlns="urn:brocade.com:mgmt:brocade-ip-access-list")
ip = ET.SubElement(ip_acl, "ip")
access_list = ET.SubElement(ip, "access-list")
extended = ET.SubElement(access_list, "extended")
name_key = ET.SubElement(extended, "name")
name_key.text = kwargs.pop('name')
hide_ip_acl_ext = ET.SubElement(extended, "hide-ip-acl-ext")
seq = ET.SubElement(hide_ip_acl_ext, "seq")
seq_id_key = ET.SubElement(seq, "seq-id")
seq_id_key.text = kwargs.pop('seq_id')
src_mask = ET.SubElement(seq, "src-mask")
src_mask.text = kwargs.pop('src_mask')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def ip_acl_ip_access_list_extended_hide_ip_acl_ext_seq_sport(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
ip_acl = ET.SubElement(config, "ip-acl", xmlns="urn:brocade.com:mgmt:brocade-ip-access-list")
ip = ET.SubElement(ip_acl, "ip")
access_list = ET.SubElement(ip, "access-list")
extended = ET.SubElement(access_list, "extended")
name_key = ET.SubElement(extended, "name")
name_key.text = kwargs.pop('name')
hide_ip_acl_ext = ET.SubElement(extended, "hide-ip-acl-ext")
seq = ET.SubElement(hide_ip_acl_ext, "seq")
seq_id_key = ET.SubElement(seq, "seq-id")
seq_id_key.text = kwargs.pop('seq_id')
sport = ET.SubElement(seq, "sport")
sport.text = kwargs.pop('sport')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def ip_acl_ip_access_list_extended_hide_ip_acl_ext_seq_sport_number_eq_neq_tcp(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
ip_acl = ET.SubElement(config, "ip-acl", xmlns="urn:brocade.com:mgmt:brocade-ip-access-list")
ip = ET.SubElement(ip_acl, "ip")
access_list = ET.SubElement(ip, "access-list")
extended = ET.SubElement(access_list, "extended")
name_key = ET.SubElement(extended, "name")
name_key.text = kwargs.pop('name')
hide_ip_acl_ext = ET.SubElement(extended, "hide-ip-acl-ext")
seq = ET.SubElement(hide_ip_acl_ext, "seq")
seq_id_key = ET.SubElement(seq, "seq-id")
seq_id_key.text = kwargs.pop('seq_id')
sport_number_eq_neq_tcp = ET.SubElement(seq, "sport-number-eq-neq-tcp")
sport_number_eq_neq_tcp.text = kwargs.pop('sport_number_eq_neq_tcp')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def ip_acl_ip_access_list_extended_hide_ip_acl_ext_seq_sport_number_lt_tcp(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
ip_acl = ET.SubElement(config, "ip-acl", xmlns="urn:brocade.com:mgmt:brocade-ip-access-list")
ip = ET.SubElement(ip_acl, "ip")
access_list = ET.SubElement(ip, "access-list")
extended = ET.SubElement(access_list, "extended")
name_key = ET.SubElement(extended, "name")
name_key.text = kwargs.pop('name')
hide_ip_acl_ext = ET.SubElement(extended, "hide-ip-acl-ext")
seq = ET.SubElement(hide_ip_acl_ext, "seq")
seq_id_key = ET.SubElement(seq, "seq-id")
seq_id_key.text = kwargs.pop('seq_id')
sport_number_lt_tcp = ET.SubElement(seq, "sport-number-lt-tcp")
sport_number_lt_tcp.text = kwargs.pop('sport_number_lt_tcp')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def ip_acl_ip_access_list_extended_hide_ip_acl_ext_seq_sport_number_gt_tcp(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
ip_acl = ET.SubElement(config, "ip-acl", xmlns="urn:brocade.com:mgmt:brocade-ip-access-list")
ip = ET.SubElement(ip_acl, "ip")
access_list = ET.SubElement(ip, "access-list")
extended = ET.SubElement(access_list, "extended")
name_key = ET.SubElement(extended, "name")
name_key.text = kwargs.pop('name')
hide_ip_acl_ext = ET.SubElement(extended, "hide-ip-acl-ext")
seq = ET.SubElement(hide_ip_acl_ext, "seq")
seq_id_key = ET.SubElement(seq, "seq-id")
seq_id_key.text = kwargs.pop('seq_id')
sport_number_gt_tcp = ET.SubElement(seq, "sport-number-gt-tcp")
sport_number_gt_tcp.text = kwargs.pop('sport_number_gt_tcp')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def ip_acl_ip_access_list_extended_hide_ip_acl_ext_seq_sport_number_eq_neq_udp(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
ip_acl = ET.SubElement(config, "ip-acl", xmlns="urn:brocade.com:mgmt:brocade-ip-access-list")
ip = ET.SubElement(ip_acl, "ip")
access_list = ET.SubElement(ip, "access-list")
extended = ET.SubElement(access_list, "extended")
name_key = ET.SubElement(extended, "name")
name_key.text = kwargs.pop('name')
hide_ip_acl_ext = ET.SubElement(extended, "hide-ip-acl-ext")
seq = ET.SubElement(hide_ip_acl_ext, "seq")
seq_id_key = ET.SubElement(seq, "seq-id")
seq_id_key.text = kwargs.pop('seq_id')
sport_number_eq_neq_udp = ET.SubElement(seq, "sport-number-eq-neq-udp")
sport_number_eq_neq_udp.text = kwargs.pop('sport_number_eq_neq_udp')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def ip_acl_ip_access_list_extended_hide_ip_acl_ext_seq_sport_number_lt_udp(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
ip_acl = ET.SubElement(config, "ip-acl", xmlns="urn:brocade.com:mgmt:brocade-ip-access-list")
ip = ET.SubElement(ip_acl, "ip")
access_list = ET.SubElement(ip, "access-list")
extended = ET.SubElement(access_list, "extended")
name_key = ET.SubElement(extended, "name")
name_key.text = kwargs.pop('name')
hide_ip_acl_ext = ET.SubElement(extended, "hide-ip-acl-ext")
seq = ET.SubElement(hide_ip_acl_ext, "seq")
seq_id_key = ET.SubElement(seq, "seq-id")
seq_id_key.text = kwargs.pop('seq_id')
sport_number_lt_udp = ET.SubElement(seq, "sport-number-lt-udp")
sport_number_lt_udp.text = kwargs.pop('sport_number_lt_udp')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def ip_acl_ip_access_list_extended_hide_ip_acl_ext_seq_sport_number_gt_udp(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
ip_acl = ET.SubElement(config, "ip-acl", xmlns="urn:brocade.com:mgmt:brocade-ip-access-list")
ip = ET.SubElement(ip_acl, "ip")
access_list = ET.SubElement(ip, "access-list")
extended = ET.SubElement(access_list, "extended")
name_key = ET.SubElement(extended, "name")
name_key.text = kwargs.pop('name')
hide_ip_acl_ext = ET.SubElement(extended, "hide-ip-acl-ext")
seq = ET.SubElement(hide_ip_acl_ext, "seq")
seq_id_key = ET.SubElement(seq, "seq-id")
seq_id_key.text = kwargs.pop('seq_id')
sport_number_gt_udp = ET.SubElement(seq, "sport-number-gt-udp")
sport_number_gt_udp.text = kwargs.pop('sport_number_gt_udp')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def ip_acl_ip_access_list_extended_hide_ip_acl_ext_seq_sport_number_range_lower_tcp(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
ip_acl = ET.SubElement(config, "ip-acl", xmlns="urn:brocade.com:mgmt:brocade-ip-access-list")
ip = ET.SubElement(ip_acl, "ip")
access_list = ET.SubElement(ip, "access-list")
extended = ET.SubElement(access_list, "extended")
name_key = ET.SubElement(extended, "name")
name_key.text = kwargs.pop('name')
hide_ip_acl_ext = ET.SubElement(extended, "hide-ip-acl-ext")
seq = ET.SubElement(hide_ip_acl_ext, "seq")
seq_id_key = ET.SubElement(seq, "seq-id")
seq_id_key.text = kwargs.pop('seq_id')
sport_number_range_lower_tcp = ET.SubElement(seq, "sport-number-range-lower-tcp")
sport_number_range_lower_tcp.text = kwargs.pop('sport_number_range_lower_tcp')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def ip_acl_ip_access_list_extended_hide_ip_acl_ext_seq_sport_number_range_lower_udp(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
ip_acl = ET.SubElement(config, "ip-acl", xmlns="urn:brocade.com:mgmt:brocade-ip-access-list")
ip = ET.SubElement(ip_acl, "ip")
access_list = ET.SubElement(ip, "access-list")
extended = ET.SubElement(access_list, "extended")
name_key = ET.SubElement(extended, "name")
name_key.text = kwargs.pop('name')
hide_ip_acl_ext = ET.SubElement(extended, "hide-ip-acl-ext")
seq = ET.SubElement(hide_ip_acl_ext, "seq")
seq_id_key = ET.SubElement(seq, "seq-id")
seq_id_key.text = kwargs.pop('seq_id')
sport_number_range_lower_udp = ET.SubElement(seq, "sport-number-range-lower-udp")
sport_number_range_lower_udp.text = kwargs.pop('sport_number_range_lower_udp')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def ip_acl_ip_access_list_extended_hide_ip_acl_ext_seq_sport_number_range_higher_tcp(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
ip_acl = ET.SubElement(config, "ip-acl", xmlns="urn:brocade.com:mgmt:brocade-ip-access-list")
ip = ET.SubElement(ip_acl, "ip")
access_list = ET.SubElement(ip, "access-list")
extended = ET.SubElement(access_list, "extended")
name_key = ET.SubElement(extended, "name")
name_key.text = kwargs.pop('name')
hide_ip_acl_ext = ET.SubElement(extended, "hide-ip-acl-ext")
seq = ET.SubElement(hide_ip_acl_ext, "seq")
seq_id_key = ET.SubElement(seq, "seq-id")
seq_id_key.text = kwargs.pop('seq_id')
sport_number_range_higher_tcp = ET.SubElement(seq, "sport-number-range-higher-tcp")
sport_number_range_higher_tcp.text = kwargs.pop('sport_number_range_higher_tcp')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def ip_acl_ip_access_list_extended_hide_ip_acl_ext_seq_sport_number_range_higher_udp(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
ip_acl = ET.SubElement(config, "ip-acl", xmlns="urn:brocade.com:mgmt:brocade-ip-access-list")
ip = ET.SubElement(ip_acl, "ip")
access_list = ET.SubElement(ip, "access-list")
extended = ET.SubElement(access_list, "extended")
name_key = ET.SubElement(extended, "name")
name_key.text = kwargs.pop('name')
hide_ip_acl_ext = ET.SubElement(extended, "hide-ip-acl-ext")
seq = ET.SubElement(hide_ip_acl_ext, "seq")
seq_id_key = ET.SubElement(seq, "seq-id")
seq_id_key.text = kwargs.pop('seq_id')
sport_number_range_higher_udp = ET.SubElement(seq, "sport-number-range-higher-udp")
sport_number_range_higher_udp.text = kwargs.pop('sport_number_range_higher_udp')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def ip_acl_ip_access_list_extended_hide_ip_acl_ext_seq_dst_host_any_dip(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
ip_acl = ET.SubElement(config, "ip-acl", xmlns="urn:brocade.com:mgmt:brocade-ip-access-list")
ip = ET.SubElement(ip_acl, "ip")
access_list = ET.SubElement(ip, "access-list")
extended = ET.SubElement(access_list, "extended")
name_key = ET.SubElement(extended, "name")
name_key.text = kwargs.pop('name')
hide_ip_acl_ext = ET.SubElement(extended, "hide-ip-acl-ext")
seq = ET.SubElement(hide_ip_acl_ext, "seq")
seq_id_key = ET.SubElement(seq, "seq-id")
seq_id_key.text = kwargs.pop('seq_id')
dst_host_any_dip = ET.SubElement(seq, "dst-host-any-dip")
dst_host_any_dip.text = kwargs.pop('dst_host_any_dip')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def ip_acl_ip_access_list_extended_hide_ip_acl_ext_seq_dst_host_ip(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
ip_acl = ET.SubElement(config, "ip-acl", xmlns="urn:brocade.com:mgmt:brocade-ip-access-list")
ip = ET.SubElement(ip_acl, "ip")
access_list = ET.SubElement(ip, "access-list")
extended = ET.SubElement(access_list, "extended")
name_key = ET.SubElement(extended, "name")
name_key.text = kwargs.pop('name')
hide_ip_acl_ext = ET.SubElement(extended, "hide-ip-acl-ext")
seq = ET.SubElement(hide_ip_acl_ext, "seq")
seq_id_key = ET.SubElement(seq, "seq-id")
seq_id_key.text = kwargs.pop('seq_id')
dst_host_ip = ET.SubElement(seq, "dst-host-ip")
dst_host_ip.text = kwargs.pop('dst_host_ip')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def ip_acl_ip_access_list_extended_hide_ip_acl_ext_seq_dst_mask(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
ip_acl = ET.SubElement(config, "ip-acl", xmlns="urn:brocade.com:mgmt:brocade-ip-access-list")
ip = ET.SubElement(ip_acl, "ip")
access_list = ET.SubElement(ip, "access-list")
extended = ET.SubElement(access_list, "extended")
name_key = ET.SubElement(extended, "name")
name_key.text = kwargs.pop('name')
hide_ip_acl_ext = ET.SubElement(extended, "hide-ip-acl-ext")
seq = ET.SubElement(hide_ip_acl_ext, "seq")
seq_id_key = ET.SubElement(seq, "seq-id")
seq_id_key.text = kwargs.pop('seq_id')
dst_mask = ET.SubElement(seq, "dst-mask")
dst_mask.text = kwargs.pop('dst_mask')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def ip_acl_ip_access_list_extended_hide_ip_acl_ext_seq_dport(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
ip_acl = ET.SubElement(config, "ip-acl", xmlns="urn:brocade.com:mgmt:brocade-ip-access-list")
ip = ET.SubElement(ip_acl, "ip")
access_list = ET.SubElement(ip, "access-list")
extended = ET.SubElement(access_list, "extended")
name_key = ET.SubElement(extended, "name")
name_key.text = kwargs.pop('name')
hide_ip_acl_ext = ET.SubElement(extended, "hide-ip-acl-ext")
seq = ET.SubElement(hide_ip_acl_ext, "seq")
seq_id_key = ET.SubElement(seq, "seq-id")
seq_id_key.text = kwargs.pop('seq_id')
dport = ET.SubElement(seq, "dport")
dport.text = kwargs.pop('dport')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def ip_acl_ip_access_list_extended_hide_ip_acl_ext_seq_dport_number_eq_neq_tcp(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
ip_acl = ET.SubElement(config, "ip-acl", xmlns="urn:brocade.com:mgmt:brocade-ip-access-list")
ip = ET.SubElement(ip_acl, "ip")
access_list = ET.SubElement(ip, "access-list")
extended = ET.SubElement(access_list, "extended")
name_key = ET.SubElement(extended, "name")
name_key.text = kwargs.pop('name')
hide_ip_acl_ext = ET.SubElement(extended, "hide-ip-acl-ext")
seq = ET.SubElement(hide_ip_acl_ext, "seq")
seq_id_key = ET.SubElement(seq, "seq-id")
seq_id_key.text = kwargs.pop('seq_id')
dport_number_eq_neq_tcp = ET.SubElement(seq, "dport-number-eq-neq-tcp")
dport_number_eq_neq_tcp.text = kwargs.pop('dport_number_eq_neq_tcp')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def ip_acl_ip_access_list_extended_hide_ip_acl_ext_seq_dport_number_lt_tcp(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
ip_acl = ET.SubElement(config, "ip-acl", xmlns="urn:brocade.com:mgmt:brocade-ip-access-list")
ip = ET.SubElement(ip_acl, "ip")
access_list = ET.SubElement(ip, "access-list")
extended = ET.SubElement(access_list, "extended")
name_key = ET.SubElement(extended, "name")
name_key.text = kwargs.pop('name')
hide_ip_acl_ext = ET.SubElement(extended, "hide-ip-acl-ext")
seq = ET.SubElement(hide_ip_acl_ext, "seq")
seq_id_key = ET.SubElement(seq, "seq-id")
seq_id_key.text = kwargs.pop('seq_id')
dport_number_lt_tcp = ET.SubElement(seq, "dport-number-lt-tcp")
dport_number_lt_tcp.text = kwargs.pop('dport_number_lt_tcp')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def ip_acl_ip_access_list_extended_hide_ip_acl_ext_seq_dport_number_gt_tcp(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
ip_acl = ET.SubElement(config, "ip-acl", xmlns="urn:brocade.com:mgmt:brocade-ip-access-list")
ip = ET.SubElement(ip_acl, "ip")
access_list = ET.SubElement(ip, "access-list")
extended = ET.SubElement(access_list, "extended")
name_key = ET.SubElement(extended, "name")
name_key.text = kwargs.pop('name')
hide_ip_acl_ext = ET.SubElement(extended, "hide-ip-acl-ext")
seq = ET.SubElement(hide_ip_acl_ext, "seq")
seq_id_key = ET.SubElement(seq, "seq-id")
seq_id_key.text = kwargs.pop('seq_id')
dport_number_gt_tcp = ET.SubElement(seq, "dport-number-gt-tcp")
dport_number_gt_tcp.text = kwargs.pop('dport_number_gt_tcp')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def ip_acl_ip_access_list_extended_hide_ip_acl_ext_seq_dport_number_eq_neq_udp(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
ip_acl = ET.SubElement(config, "ip-acl", xmlns="urn:brocade.com:mgmt:brocade-ip-access-list")
ip = ET.SubElement(ip_acl, "ip")
access_list = ET.SubElement(ip, "access-list")
extended = ET.SubElement(access_list, "extended")
name_key = ET.SubElement(extended, "name")
name_key.text = kwargs.pop('name')
hide_ip_acl_ext = ET.SubElement(extended, "hide-ip-acl-ext")
seq = ET.SubElement(hide_ip_acl_ext, "seq")
seq_id_key = ET.SubElement(seq, "seq-id")
seq_id_key.text = kwargs.pop('seq_id')
dport_number_eq_neq_udp = ET.SubElement(seq, "dport-number-eq-neq-udp")
dport_number_eq_neq_udp.text = kwargs.pop('dport_number_eq_neq_udp')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def ip_acl_ip_access_list_extended_hide_ip_acl_ext_seq_dport_number_lt_udp(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
ip_acl = ET.SubElement(config, "ip-acl", xmlns="urn:brocade.com:mgmt:brocade-ip-access-list")
ip = ET.SubElement(ip_acl, "ip")
access_list = ET.SubElement(ip, "access-list")
extended = ET.SubElement(access_list, "extended")
name_key = ET.SubElement(extended, "name")
name_key.text = kwargs.pop('name')
hide_ip_acl_ext = ET.SubElement(extended, "hide-ip-acl-ext")
seq = ET.SubElement(hide_ip_acl_ext, "seq")
seq_id_key = ET.SubElement(seq, "seq-id")
seq_id_key.text = kwargs.pop('seq_id')
dport_number_lt_udp = ET.SubElement(seq, "dport-number-lt-udp")
dport_number_lt_udp.text = kwargs.pop('dport_number_lt_udp')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def ip_acl_ip_access_list_extended_hide_ip_acl_ext_seq_dport_number_gt_udp(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
ip_acl = ET.SubElement(config, "ip-acl", xmlns="urn:brocade.com:mgmt:brocade-ip-access-list")
ip = ET.SubElement(ip_acl, "ip")
access_list = ET.SubElement(ip, "access-list")
extended = ET.SubElement(access_list, "extended")
name_key = ET.SubElement(extended, "name")
name_key.text = kwargs.pop('name')
hide_ip_acl_ext = ET.SubElement(extended, "hide-ip-acl-ext")
seq = ET.SubElement(hide_ip_acl_ext, "seq")
seq_id_key = ET.SubElement(seq, "seq-id")
seq_id_key.text = kwargs.pop('seq_id')
dport_number_gt_udp = ET.SubElement(seq, "dport-number-gt-udp")
dport_number_gt_udp.text = kwargs.pop('dport_number_gt_udp')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def ip_acl_ip_access_list_extended_hide_ip_acl_ext_seq_dport_number_range_lower_tcp(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
ip_acl = ET.SubElement(config, "ip-acl", xmlns="urn:brocade.com:mgmt:brocade-ip-access-list")
ip = ET.SubElement(ip_acl, "ip")
access_list = ET.SubElement(ip, "access-list")
extended = ET.SubElement(access_list, "extended")
name_key = ET.SubElement(extended, "name")
name_key.text = kwargs.pop('name')
hide_ip_acl_ext = ET.SubElement(extended, "hide-ip-acl-ext")
seq = ET.SubElement(hide_ip_acl_ext, "seq")
seq_id_key = ET.SubElement(seq, "seq-id")
seq_id_key.text = kwargs.pop('seq_id')
dport_number_range_lower_tcp = ET.SubElement(seq, "dport-number-range-lower-tcp")
dport_number_range_lower_tcp.text = kwargs.pop('dport_number_range_lower_tcp')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def ip_acl_ip_access_list_extended_hide_ip_acl_ext_seq_dport_number_range_lower_udp(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
ip_acl = ET.SubElement(config, "ip-acl", xmlns="urn:brocade.com:mgmt:brocade-ip-access-list")
ip = ET.SubElement(ip_acl, "ip")
access_list = ET.SubElement(ip, "access-list")
extended = ET.SubElement(access_list, "extended")
name_key = ET.SubElement(extended, "name")
name_key.text = kwargs.pop('name')
hide_ip_acl_ext = ET.SubElement(extended, "hide-ip-acl-ext")
seq = ET.SubElement(hide_ip_acl_ext, "seq")
seq_id_key = ET.SubElement(seq, "seq-id")
seq_id_key.text = kwargs.pop('seq_id')
dport_number_range_lower_udp = ET.SubElement(seq, "dport-number-range-lower-udp")
dport_number_range_lower_udp.text = kwargs.pop('dport_number_range_lower_udp')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def ip_acl_ip_access_list_extended_hide_ip_acl_ext_seq_dport_number_range_higher_tcp(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
ip_acl = ET.SubElement(config, "ip-acl", xmlns="urn:brocade.com:mgmt:brocade-ip-access-list")
ip = ET.SubElement(ip_acl, "ip")
access_list = ET.SubElement(ip, "access-list")
extended = ET.SubElement(access_list, "extended")
name_key = ET.SubElement(extended, "name")
name_key.text = kwargs.pop('name')
hide_ip_acl_ext = ET.SubElement(extended, "hide-ip-acl-ext")
seq = ET.SubElement(hide_ip_acl_ext, "seq")
seq_id_key = ET.SubElement(seq, "seq-id")
seq_id_key.text = kwargs.pop('seq_id')
dport_number_range_higher_tcp = ET.SubElement(seq, "dport-number-range-higher-tcp")
dport_number_range_higher_tcp.text = kwargs.pop('dport_number_range_higher_tcp')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def ip_acl_ip_access_list_extended_hide_ip_acl_ext_seq_dport_number_range_higher_udp(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
ip_acl = ET.SubElement(config, "ip-acl", xmlns="urn:brocade.com:mgmt:brocade-ip-access-list")
ip = ET.SubElement(ip_acl, "ip")
access_list = ET.SubElement(ip, "access-list")
extended = ET.SubElement(access_list, "extended")
name_key = ET.SubElement(extended, "name")
name_key.text = kwargs.pop('name')
hide_ip_acl_ext = ET.SubElement(extended, "hide-ip-acl-ext")
seq = ET.SubElement(hide_ip_acl_ext, "seq")
seq_id_key = ET.SubElement(seq, "seq-id")
seq_id_key.text = kwargs.pop('seq_id')
dport_number_range_higher_udp = ET.SubElement(seq, "dport-number-range-higher-udp")
dport_number_range_higher_udp.text = kwargs.pop('dport_number_range_higher_udp')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def ip_acl_ip_access_list_extended_hide_ip_acl_ext_seq_dscp(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
ip_acl = ET.SubElement(config, "ip-acl", xmlns="urn:brocade.com:mgmt:brocade-ip-access-list")
ip = ET.SubElement(ip_acl, "ip")
access_list = ET.SubElement(ip, "access-list")
extended = ET.SubElement(access_list, "extended")
name_key = ET.SubElement(extended, "name")
name_key.text = kwargs.pop('name')
hide_ip_acl_ext = ET.SubElement(extended, "hide-ip-acl-ext")
seq = ET.SubElement(hide_ip_acl_ext, "seq")
seq_id_key = ET.SubElement(seq, "seq-id")
seq_id_key.text = kwargs.pop('seq_id')
dscp = ET.SubElement(seq, "dscp")
dscp.text = kwargs.pop('dscp')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def ip_acl_ip_access_list_extended_hide_ip_acl_ext_seq_urg(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
ip_acl = ET.SubElement(config, "ip-acl", xmlns="urn:brocade.com:mgmt:brocade-ip-access-list")
ip = ET.SubElement(ip_acl, "ip")
access_list = ET.SubElement(ip, "access-list")
extended = ET.SubElement(access_list, "extended")
name_key = ET.SubElement(extended, "name")
name_key.text = kwargs.pop('name')
hide_ip_acl_ext = ET.SubElement(extended, "hide-ip-acl-ext")
seq = ET.SubElement(hide_ip_acl_ext, "seq")
seq_id_key = ET.SubElement(seq, "seq-id")
seq_id_key.text = kwargs.pop('seq_id')
urg = ET.SubElement(seq, "urg")
callback = kwargs.pop('callback', self._callback)
return callback(config)
def ip_acl_ip_access_list_extended_hide_ip_acl_ext_seq_ack(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
ip_acl = ET.SubElement(config, "ip-acl", xmlns="urn:brocade.com:mgmt:brocade-ip-access-list")
ip = ET.SubElement(ip_acl, "ip")
access_list = ET.SubElement(ip, "access-list")
extended = ET.SubElement(access_list, "extended")
name_key = ET.SubElement(extended, "name")
name_key.text = kwargs.pop('name')
hide_ip_acl_ext = ET.SubElement(extended, "hide-ip-acl-ext")
seq = ET.SubElement(hide_ip_acl_ext, "seq")
seq_id_key = ET.SubElement(seq, "seq-id")
seq_id_key.text = kwargs.pop('seq_id')
ack = ET.SubElement(seq, "ack")
callback = kwargs.pop('callback', self._callback)
return callback(config)
def ip_acl_ip_access_list_extended_hide_ip_acl_ext_seq_push(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
ip_acl = ET.SubElement(config, "ip-acl", xmlns="urn:brocade.com:mgmt:brocade-ip-access-list")
ip = ET.SubElement(ip_acl, "ip")
access_list = ET.SubElement(ip, "access-list")
extended = ET.SubElement(access_list, "extended")
name_key = ET.SubElement(extended, "name")
name_key.text = kwargs.pop('name')
hide_ip_acl_ext = ET.SubElement(extended, "hide-ip-acl-ext")
seq = ET.SubElement(hide_ip_acl_ext, "seq")
seq_id_key = ET.SubElement(seq, "seq-id")
seq_id_key.text = kwargs.pop('seq_id')
push = ET.SubElement(seq, "push")
callback = kwargs.pop('callback', self._callback)
return callback(config)
def ip_acl_ip_access_list_extended_hide_ip_acl_ext_seq_fin(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
ip_acl = ET.SubElement(config, "ip-acl", xmlns="urn:brocade.com:mgmt:brocade-ip-access-list")
ip = ET.SubElement(ip_acl, "ip")
access_list = ET.SubElement(ip, "access-list")
extended = ET.SubElement(access_list, "extended")
name_key = ET.SubElement(extended, "name")
name_key.text = kwargs.pop('name')
hide_ip_acl_ext = ET.SubElement(extended, "hide-ip-acl-ext")
seq = ET.SubElement(hide_ip_acl_ext, "seq")
seq_id_key = ET.SubElement(seq, "seq-id")
seq_id_key.text = kwargs.pop('seq_id')
fin = ET.SubElement(seq, "fin")
callback = kwargs.pop('callback', self._callback)
return callback(config)
def ip_acl_ip_access_list_extended_hide_ip_acl_ext_seq_rst(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
ip_acl = ET.SubElement(config, "ip-acl", xmlns="urn:brocade.com:mgmt:brocade-ip-access-list")
ip = ET.SubElement(ip_acl, "ip")
access_list = ET.SubElement(ip, "access-list")
extended = ET.SubElement(access_list, "extended")
name_key = ET.SubElement(extended, "name")
name_key.text = kwargs.pop('name')
hide_ip_acl_ext = ET.SubElement(extended, "hide-ip-acl-ext")
seq = ET.SubElement(hide_ip_acl_ext, "seq")
seq_id_key = ET.SubElement(seq, "seq-id")
seq_id_key.text = kwargs.pop('seq_id')
rst = ET.SubElement(seq, "rst")
callback = kwargs.pop('callback', self._callback)
return callback(config)
def ip_acl_ip_access_list_extended_hide_ip_acl_ext_seq_sync(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
ip_acl = ET.SubElement(config, "ip-acl", xmlns="urn:brocade.com:mgmt:brocade-ip-access-list")
ip = ET.SubElement(ip_acl, "ip")
access_list = ET.SubElement(ip, "access-list")
extended = ET.SubElement(access_list, "extended")
name_key = ET.SubElement(extended, "name")
name_key.text = kwargs.pop('name')
hide_ip_acl_ext = ET.SubElement(extended, "hide-ip-acl-ext")
seq = ET.SubElement(hide_ip_acl_ext, "seq")
seq_id_key = ET.SubElement(seq, "seq-id")
seq_id_key.text = kwargs.pop('seq_id')
sync = ET.SubElement(seq, "sync")
callback = kwargs.pop('callback', self._callback)
return callback(config)
def ip_acl_ip_access_list_extended_hide_ip_acl_ext_seq_vlan(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
ip_acl = ET.SubElement(config, "ip-acl", xmlns="urn:brocade.com:mgmt:brocade-ip-access-list")
ip = ET.SubElement(ip_acl, "ip")
access_list = ET.SubElement(ip, "access-list")
extended = ET.SubElement(access_list, "extended")
name_key = ET.SubElement(extended, "name")
name_key.text = kwargs.pop('name')
hide_ip_acl_ext = ET.SubElement(extended, "hide-ip-acl-ext")
seq = ET.SubElement(hide_ip_acl_ext, "seq")
seq_id_key = ET.SubElement(seq, "seq-id")
seq_id_key.text = kwargs.pop('seq_id')
vlan = ET.SubElement(seq, "vlan")
vlan.text = kwargs.pop('vlan')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def ip_acl_ip_access_list_extended_hide_ip_acl_ext_seq_count(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
ip_acl = ET.SubElement(config, "ip-acl", xmlns="urn:brocade.com:mgmt:brocade-ip-access-list")
ip = ET.SubElement(ip_acl, "ip")
access_list = ET.SubElement(ip, "access-list")
extended = ET.SubElement(access_list, "extended")
name_key = ET.SubElement(extended, "name")
name_key.text = kwargs.pop('name')
hide_ip_acl_ext = ET.SubElement(extended, "hide-ip-acl-ext")
seq = ET.SubElement(hide_ip_acl_ext, "seq")
seq_id_key = ET.SubElement(seq, "seq-id")
seq_id_key.text = kwargs.pop('seq_id')
count = ET.SubElement(seq, "count")
callback = kwargs.pop('callback', self._callback)
return callback(config)
def ip_acl_ip_access_list_extended_hide_ip_acl_ext_seq_log(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
ip_acl = ET.SubElement(config, "ip-acl", xmlns="urn:brocade.com:mgmt:brocade-ip-access-list")
ip = ET.SubElement(ip_acl, "ip")
access_list = ET.SubElement(ip, "access-list")
extended = ET.SubElement(access_list, "extended")
name_key = ET.SubElement(extended, "name")
name_key.text = kwargs.pop('name')
hide_ip_acl_ext = ET.SubElement(extended, "hide-ip-acl-ext")
seq = ET.SubElement(hide_ip_acl_ext, "seq")
seq_id_key = ET.SubElement(seq, "seq-id")
seq_id_key.text = kwargs.pop('seq_id')
log = ET.SubElement(seq, "log")
callback = kwargs.pop('callback', self._callback)
return callback(config)
| BRCDcomm/pynos | pynos/versions/ver_7/ver_7_1_0/yang/brocade_ip_access_list.py | Python | apache-2.0 | 93,629 |
#include "board.h"
#include "uart.h"
#include "app_util_platform.h"
#include "nrf_drv_common.h"
#include "nrf_systick.h"
#include "nrf_rtc.h"
#include "nrf_drv_clock.h"
#include "softdevice_handler.h"
#include "nrf_drv_uart.h"
#include "nrf_gpio.h"
#include <rtthread.h>
#include <rthw.h>
#if 0
/*******************************************************************************
* Function Name : SysTick_Configuration
* Description : Configures the SysTick for OS tick.
* Input : None
* Output : None
* Return : None
*******************************************************************************/
void SysTick_Configuration(void)
{
nrf_drv_common_irq_enable(SysTick_IRQn, APP_TIMER_CONFIG_IRQ_PRIORITY);
nrf_systick_load_set(SystemCoreClock / RT_TICK_PER_SECOND);
nrf_systick_val_clear();
nrf_systick_csr_set(NRF_SYSTICK_CSR_CLKSOURCE_CPU | NRF_SYSTICK_CSR_TICKINT_ENABLE
| NRF_SYSTICK_CSR_ENABLE);
}
/**
* This is the timer interrupt service routine.
*
*/
void SysTick_Handler(void)
{
if (rt_thread_self() != RT_NULL)
{
/* enter interrupt */
rt_interrupt_enter();
rt_tick_increase();
/* leave interrupt */
rt_interrupt_leave();
}
}
#else
#define TICK_RATE_HZ RT_TICK_PER_SECOND
#define SYSTICK_CLOCK_HZ ( 32768UL )
#define NRF_RTC_REG NRF_RTC1
/* IRQn used by the selected RTC */
#define NRF_RTC_IRQn RTC1_IRQn
/* Constants required to manipulate the NVIC. */
#define NRF_RTC_PRESCALER ( (uint32_t) (ROUNDED_DIV(SYSTICK_CLOCK_HZ, TICK_RATE_HZ) - 1) )
/* Maximum RTC ticks */
#define NRF_RTC_MAXTICKS ((1U<<24)-1U)
static volatile uint32_t m_tick_overflow_count = 0;
#define NRF_RTC_BITWIDTH 24
#define OSTick_Handler RTC1_IRQHandler
#define EXPECTED_IDLE_TIME_BEFORE_SLEEP 2
void SysTick_Configuration(void)
{
nrf_drv_clock_lfclk_request(NULL);
/* Configure SysTick to interrupt at the requested rate. */
nrf_rtc_prescaler_set(NRF_RTC_REG, NRF_RTC_PRESCALER);
nrf_rtc_int_enable (NRF_RTC_REG, RTC_INTENSET_TICK_Msk);
nrf_rtc_task_trigger (NRF_RTC_REG, NRF_RTC_TASK_CLEAR);
nrf_rtc_task_trigger (NRF_RTC_REG, NRF_RTC_TASK_START);
nrf_rtc_event_enable(NRF_RTC_REG, RTC_EVTEN_OVRFLW_Msk);
NVIC_SetPriority(NRF_RTC_IRQn, 0xF);
NVIC_EnableIRQ(NRF_RTC_IRQn);
}
static rt_tick_t _tick_distance(void)
{
nrf_rtc_event_clear(NRF_RTC_REG, NRF_RTC_EVENT_COMPARE_0);
uint32_t systick_counter = nrf_rtc_counter_get(NRF_RTC_REG);
nrf_rtc_event_clear(NRF_RTC_REG, NRF_RTC_EVENT_TICK);
/* check for overflow in TICK counter */
if(nrf_rtc_event_pending(NRF_RTC_REG, NRF_RTC_EVENT_OVERFLOW))
{
nrf_rtc_event_clear(NRF_RTC_REG, NRF_RTC_EVENT_OVERFLOW);
m_tick_overflow_count++;
}
return ((m_tick_overflow_count << NRF_RTC_BITWIDTH) + systick_counter) - rt_tick_get();
}
void OSTick_Handler( void )
{
uint32_t diff;
diff = _tick_distance();
while((diff--) > 0)
{
if (rt_thread_self() != RT_NULL)
{
/* enter interrupt */
rt_interrupt_enter();
rt_tick_increase();
/* leave interrupt */
rt_interrupt_leave();
}
}
}
static void _wakeup_tick_adjust(void)
{
uint32_t diff;
uint32_t level;
level = rt_hw_interrupt_disable();
diff = _tick_distance();
rt_tick_set(rt_tick_get() + diff);
if (rt_thread_self() != RT_NULL)
{
struct rt_thread *thread;
/* check time slice */
thread = rt_thread_self();
if (thread->remaining_tick <= diff)
{
/* change to initialized tick */
thread->remaining_tick = thread->init_tick;
/* yield */
rt_thread_yield();
}
else
{
thread->remaining_tick -= diff;
}
/* check timer */
rt_timer_check();
}
rt_hw_interrupt_enable(level);
}
static void _sleep_ongo( uint32_t sleep_tick )
{
uint32_t enterTime;
uint32_t entry_tick;
/* Make sure the SysTick reload value does not overflow the counter. */
if ( sleep_tick > NRF_RTC_MAXTICKS - EXPECTED_IDLE_TIME_BEFORE_SLEEP )
{
sleep_tick = NRF_RTC_MAXTICKS - EXPECTED_IDLE_TIME_BEFORE_SLEEP;
}
rt_enter_critical();
enterTime = nrf_rtc_counter_get(NRF_RTC_REG);
{
uint32_t wakeupTime = (enterTime + sleep_tick) & NRF_RTC_MAXTICKS;
/* Stop tick events */
nrf_rtc_int_disable(NRF_RTC_REG, NRF_RTC_INT_TICK_MASK);
/* Configure CTC interrupt */
nrf_rtc_cc_set(NRF_RTC_REG, 0, wakeupTime);
nrf_rtc_event_clear(NRF_RTC_REG, NRF_RTC_EVENT_COMPARE_0);
nrf_rtc_int_enable(NRF_RTC_REG, NRF_RTC_INT_COMPARE0_MASK);
entry_tick = rt_tick_get();
__DSB();
if ( sleep_tick > 0 )
{
#ifdef SOFTDEVICE_PRESENT
if (softdevice_handler_is_enabled())
{
uint32_t err_code = sd_app_evt_wait();
APP_ERROR_CHECK(err_code);
}
else
#endif
{
/* No SD - we would just block interrupts globally.
* BASEPRI cannot be used for that because it would prevent WFE from wake up.
*/
do{
__WFE();
} while (0 == (NVIC->ISPR[0] | NVIC->ISPR[1]));
}
}
nrf_rtc_int_disable(NRF_RTC_REG, NRF_RTC_INT_COMPARE0_MASK);
nrf_rtc_event_clear(NRF_RTC_REG, NRF_RTC_EVENT_COMPARE_0);
_wakeup_tick_adjust();
/* Correct the system ticks */
{
nrf_rtc_event_clear(NRF_RTC_REG, NRF_RTC_EVENT_TICK);
nrf_rtc_int_enable (NRF_RTC_REG, NRF_RTC_INT_TICK_MASK);
/* It is important that we clear pending here so that our corrections are latest and in sync with tick_interrupt handler */
NVIC_ClearPendingIRQ(NRF_RTC_IRQn);
}
rt_kprintf("entry tick:%u, expected:%u, current tick:%u\n", entry_tick, sleep_tick, rt_tick_get());
}
rt_exit_critical();
}
#endif
void rt_hw_system_powersave(void)
{
uint32_t sleep_tick;
sleep_tick = rt_timer_next_timeout_tick() - rt_tick_get();
if ( sleep_tick >= EXPECTED_IDLE_TIME_BEFORE_SLEEP)
{
// rt_kprintf("sleep entry:%u\n", rt_tick_get());
_sleep_ongo( sleep_tick );
}
}
void rt_hw_board_init(void)
{
// sd_power_dcdc_mode_set(NRF_POWER_DCDC_ENABLE);
/* Activate deep sleep mode */
SCB->SCR |= SCB_SCR_SLEEPDEEP_Msk;
nrf_drv_clock_init();
// nrf_drv_clock_hfclk_request(0);
SysTick_Configuration();
rt_thread_idle_sethook(rt_hw_system_powersave);
rt_hw_uart_init();
#ifdef RT_USING_CONSOLE
rt_console_set_device(RT_CONSOLE_DEVICE_NAME);
#endif
#ifdef RT_USING_COMPONENTS_INIT
rt_components_board_init();
#endif
}
| igou/rt-thread | bsp/nrf52832/board/board.c | C | apache-2.0 | 6,920 |
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// no-pretty-expanded FIXME #15189
#[derive(PartialEq, Eq, PartialOrd, Ord)]
enum E<T> {
E0,
E1(T),
E2(T,T)
}
pub fn main() {
let e0 = E::E0;
let e11 = E::E1(1);
let e12 = E::E1(2);
let e21 = E::E2(1, 1);
let e22 = E::E2(1, 2);
// in order for both PartialOrd and Ord
let es = [e0, e11, e12, e21, e22];
for (i, e1) in es.iter().enumerate() {
for (j, e2) in es.iter().enumerate() {
let ord = i.cmp(&j);
let eq = i == j;
let lt = i < j;
let le = i <= j;
let gt = i > j;
let ge = i >= j;
// PartialEq
assert_eq!(*e1 == *e2, eq);
assert_eq!(*e1 != *e2, !eq);
// PartialOrd
assert_eq!(*e1 < *e2, lt);
assert_eq!(*e1 > *e2, gt);
assert_eq!(*e1 <= *e2, le);
assert_eq!(*e1 >= *e2, ge);
// Ord
assert_eq!(e1.cmp(e2), ord);
}
}
}
| bombless/rust | src/test/run-pass/deriving-cmp-generic-enum.rs | Rust | apache-2.0 | 1,453 |
cask "paragon-ntfs" do
version "15"
sha256 :no_check # required as upstream package is updated in-place
url "https://dl.paragon-software.com/demo/ntfsmac#{version}_trial.dmg"
name "Paragon NTFS for Mac"
homepage "https://www.paragon-software.com/ufsdhome/ntfs-mac/"
auto_updates true
installer manual: "FSInstaller.app"
uninstall kext: "com.paragon-software.filesystems.ntfs",
launchctl: "com.paragon-software.ntfs*",
pkgutil: "com.paragon-software.pkg.ntfs",
quit: "com.paragon-software.ntfs*",
signal: [
["KILL", "com.paragon-software.ntfs.FSMenuApp"],
["KILL", "com.paragon-software.ntfs.notification-agent"],
]
zap trash: "~/Library/Preferences/com.paragon-software.ntfs.fsapp.plist"
end
| kingthorin/homebrew-cask | Casks/paragon-ntfs.rb | Ruby | bsd-2-clause | 818 |
<?php
/**
* Zend Framework (http://framework.zend.com/)
*
* @link http://github.com/zendframework/zf2 for the canonical source repository
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
namespace ZendTest\Feed\Writer\Renderer\Entry;
use Zend\Feed\Writer\Renderer;
use Zend\Feed\Writer;
use Zend\Feed\Reader;
/**
* @group Zend_Feed
* @group Zend_Feed_Writer
*/
class RssTest extends \PHPUnit_Framework_TestCase
{
protected $validWriter = null;
protected $validEntry = null;
public function setUp()
{
$this->validWriter = new Writer\Feed;
$this->validWriter->setType('rss');
$this->validWriter->setTitle('This is a test feed.');
$this->validWriter->setDescription('This is a test description.');
$this->validWriter->setLink('http://www.example.com');
$this->validEntry = $this->validWriter->createEntry();
$this->validEntry->setTitle('This is a test entry.');
$this->validEntry->setDescription('This is a test entry description.');
$this->validEntry->setLink('http://www.example.com/1');
$this->validWriter->addEntry($this->validEntry);
}
public function tearDown()
{
$this->validWriter = null;
$this->validEntry = null;
}
public function testRenderMethodRunsMinimalWriterContainerProperlyBeforeICheckAtomCompliance()
{
$renderer = new Renderer\Feed\Rss($this->validWriter);
$renderer->render();
}
public function testEntryEncodingHasBeenSet()
{
$this->validWriter->setEncoding('iso-8859-1');
$renderer = new Renderer\Feed\Rss($this->validWriter);
$feed = Reader\Reader::importString($renderer->render()->saveXml());
$entry = $feed->current();
$this->assertEquals('iso-8859-1', $entry->getEncoding());
}
public function testEntryEncodingDefaultIsUsedIfEncodingNotSetByHand()
{
$renderer = new Renderer\Feed\Rss($this->validWriter);
$feed = Reader\Reader::importString($renderer->render()->saveXml());
$entry = $feed->current();
$this->assertEquals('UTF-8', $entry->getEncoding());
}
public function testEntryTitleHasBeenSet()
{
$renderer = new Renderer\Feed\Rss($this->validWriter);
$feed = Reader\Reader::importString($renderer->render()->saveXml());
$entry = $feed->current();
$this->assertEquals('This is a test entry.', $entry->getTitle());
}
/**
* @expectedException Zend\Feed\Writer\Exception\ExceptionInterface
*/
public function testEntryTitleIfMissingThrowsExceptionIfDescriptionAlsoMissing()
{
$atomFeed = new Renderer\Feed\Rss($this->validWriter);
$this->validEntry->remove('title');
$this->validEntry->remove('description');
$atomFeed->render();
}
public function testEntryTitleCharDataEncoding()
{
$renderer = new Renderer\Feed\Rss($this->validWriter);
$this->validEntry->setTitle('<>&\'"áéíóú');
$feed = Reader\Reader::importString($renderer->render()->saveXml());
$entry = $feed->current();
$this->assertEquals('<>&\'"áéíóú', $entry->getTitle());
}
public function testEntrySummaryDescriptionHasBeenSet()
{
$renderer = new Renderer\Feed\Rss($this->validWriter);
$feed = Reader\Reader::importString($renderer->render()->saveXml());
$entry = $feed->current();
$this->assertEquals('This is a test entry description.', $entry->getDescription());
}
/**
* @expectedException Zend\Feed\Writer\Exception\ExceptionInterface
*/
public function testEntryDescriptionIfMissingThrowsExceptionIfAlsoNoTitle()
{
$atomFeed = new Renderer\Feed\Rss($this->validWriter);
$this->validEntry->remove('description');
$this->validEntry->remove('title');
$atomFeed->render();
}
public function testEntryDescriptionCharDataEncoding()
{
$renderer = new Renderer\Feed\Rss($this->validWriter);
$this->validEntry->setDescription('<>&\'"áéíóú');
$feed = Reader\Reader::importString($renderer->render()->saveXml());
$entry = $feed->current();
$this->assertEquals('<>&\'"áéíóú', $entry->getDescription());
}
public function testEntryContentHasBeenSet()
{
$this->validEntry->setContent('This is test entry content.');
$renderer = new Renderer\Feed\Rss($this->validWriter);
$feed = Reader\Reader::importString($renderer->render()->saveXml());
$entry = $feed->current();
$this->assertEquals('This is test entry content.', $entry->getContent());
}
public function testEntryContentCharDataEncoding()
{
$renderer = new Renderer\Feed\Rss($this->validWriter);
$this->validEntry->setContent('<>&\'"áéíóú');
$feed = Reader\Reader::importString($renderer->render()->saveXml());
$entry = $feed->current();
$this->assertEquals('<>&\'"áéíóú', $entry->getContent());
}
public function testEntryUpdatedDateHasBeenSet()
{
$this->validEntry->setDateModified(1234567890);
$renderer = new Renderer\Feed\Rss($this->validWriter);
$feed = Reader\Reader::importString($renderer->render()->saveXml());
$entry = $feed->current();
$this->assertEquals(1234567890, $entry->getDateModified()->getTimestamp());
}
public function testEntryPublishedDateHasBeenSet()
{
$this->validEntry->setDateCreated(1234567000);
$renderer = new Renderer\Feed\Rss($this->validWriter);
$feed = Reader\Reader::importString($renderer->render()->saveXml());
$entry = $feed->current();
$this->assertEquals(1234567000, $entry->getDateCreated()->getTimestamp());
}
public function testEntryIncludesLinkToHtmlVersionOfFeed()
{
$renderer = new Renderer\Feed\Rss($this->validWriter);
$feed = Reader\Reader::importString($renderer->render()->saveXml());
$entry = $feed->current();
$this->assertEquals('http://www.example.com/1', $entry->getLink());
}
public function testEntryHoldsAnyAuthorAdded()
{
$this->validEntry->addAuthor(array('name' => 'Jane',
'email'=> 'jane@example.com',
'uri' => 'http://www.example.com/jane'));
$renderer = new Renderer\Feed\Rss($this->validWriter);
$feed = Reader\Reader::importString($renderer->render()->saveXml());
$entry = $feed->current();
$author = $entry->getAuthor();
$this->assertEquals(array('name'=> 'Jane'), $entry->getAuthor());
}
public function testEntryAuthorCharDataEncoding()
{
$this->validEntry->addAuthor(array('name' => '<>&\'"áéíóú',
'email'=> 'jane@example.com',
'uri' => 'http://www.example.com/jane'));
$renderer = new Renderer\Feed\Rss($this->validWriter);
$feed = Reader\Reader::importString($renderer->render()->saveXml());
$entry = $feed->current();
$author = $entry->getAuthor();
$this->assertEquals(array('name'=> '<>&\'"áéíóú'), $entry->getAuthor());
}
public function testEntryHoldsAnyEnclosureAdded()
{
$renderer = new Renderer\Feed\Rss($this->validWriter);
$this->validEntry->setEnclosure(array(
'type' => 'audio/mpeg',
'length' => '1337',
'uri' => 'http://example.com/audio.mp3'
));
$feed = Reader\Reader::importString($renderer->render()->saveXml());
$entry = $feed->current();
$enc = $entry->getEnclosure();
$this->assertEquals('audio/mpeg', $enc->type);
$this->assertEquals('1337', $enc->length);
$this->assertEquals('http://example.com/audio.mp3', $enc->url);
}
/**
* @expectedException Zend\Feed\Writer\Exception\ExceptionInterface
*/
public function testAddsEnclosureThrowsExceptionOnMissingType()
{
$renderer = new Renderer\Feed\Rss($this->validWriter);
$this->validEntry->setEnclosure(array(
'uri' => 'http://example.com/audio.mp3',
'length' => '1337'
));
$renderer->render();
}
/**
* @expectedException Zend\Feed\Writer\Exception\ExceptionInterface
*/
public function testAddsEnclosureThrowsExceptionOnMissingLength()
{
$renderer = new Renderer\Feed\Rss($this->validWriter);
$this->validEntry->setEnclosure(array(
'type' => 'audio/mpeg',
'uri' => 'http://example.com/audio.mp3'
));
$renderer->render();
}
/**
* @expectedException Zend\Feed\Writer\Exception\ExceptionInterface
*/
public function testAddsEnclosureThrowsExceptionOnNonNumericLength()
{
$renderer = new Renderer\Feed\Rss($this->validWriter);
$this->validEntry->setEnclosure(array(
'type' => 'audio/mpeg',
'uri' => 'http://example.com/audio.mp3',
'length' => 'abc'
));
$renderer->render();
}
/**
* @expectedException Zend\Feed\Writer\Exception\ExceptionInterface
*/
public function testAddsEnclosureThrowsExceptionOnNegativeLength()
{
$renderer = new Renderer\Feed\Rss($this->validWriter);
$this->validEntry->setEnclosure(array(
'type' => 'audio/mpeg',
'uri' => 'http://example.com/audio.mp3',
'length' => -23
));
$renderer->render();
}
public function testEntryIdHasBeenSet()
{
$this->validEntry->setId('urn:uuid:60a76c80-d399-11d9-b93C-0003939e0af6');
$renderer = new Renderer\Feed\Rss($this->validWriter);
$feed = Reader\Reader::importString($renderer->render()->saveXml());
$entry = $feed->current();
$this->assertEquals('urn:uuid:60a76c80-d399-11d9-b93C-0003939e0af6', $entry->getId());
}
public function testEntryIdHasBeenSetWithPermaLinkAsFalseWhenNotUri()
{
$this->markTestIncomplete('Untest due to ZFR potential bug');
}
public function testEntryIdDefaultIsUsedIfNotSetByHand()
{
$renderer = new Renderer\Feed\Rss($this->validWriter);
$feed = Reader\Reader::importString($renderer->render()->saveXml());
$entry = $feed->current();
$this->assertEquals($entry->getLink(), $entry->getId());
}
public function testCommentLinkRendered()
{
$renderer = new Renderer\Feed\Rss($this->validWriter);
$this->validEntry->setCommentLink('http://www.example.com/id/1');
$feed = Reader\Reader::importString($renderer->render()->saveXml());
$entry = $feed->current();
$this->assertEquals('http://www.example.com/id/1', $entry->getCommentLink());
}
public function testCommentCountRendered()
{
$renderer = new Renderer\Feed\Rss($this->validWriter);
$this->validEntry->setCommentCount(22);
$feed = Reader\Reader::importString($renderer->render()->saveXml());
$entry = $feed->current();
$this->assertEquals(22, $entry->getCommentCount());
}
public function testCommentFeedLinksRendered()
{
$renderer = new Renderer\Feed\Rss($this->validWriter);
$this->validEntry->setCommentFeedLinks(array(
array('uri' => 'http://www.example.com/atom/id/1',
'type'=> 'atom'),
array('uri' => 'http://www.example.com/rss/id/1',
'type'=> 'rss'),
));
$feed = Reader\Reader::importString($renderer->render()->saveXml());
$entry = $feed->current();
// Skipped assertion is because RSS has no facility to show Atom feeds without an extension
$this->assertEquals('http://www.example.com/rss/id/1', $entry->getCommentFeedLink('rss'));
//$this->assertEquals('http://www.example.com/atom/id/1', $entry->getCommentFeedLink('atom'));
}
public function testCategoriesCanBeSet()
{
$this->validEntry->addCategories(array(
array('term' => 'cat_dog',
'label' => 'Cats & Dogs',
'scheme' => 'http://example.com/schema1'),
array('term'=> 'cat_dog2')
));
$renderer = new Renderer\Feed\Rss($this->validWriter);
$feed = Reader\Reader::importString($renderer->render()->saveXml());
$entry = $feed->current();
$expected = array(
array('term' => 'cat_dog',
'label' => 'cat_dog',
'scheme' => 'http://example.com/schema1'),
array('term' => 'cat_dog2',
'label' => 'cat_dog2',
'scheme' => null)
);
$this->assertEquals($expected, (array) $entry->getCategories());
}
/**
* @group ZFWCHARDATA01
*/
public function testCategoriesCharDataEncoding()
{
$this->validEntry->addCategories(array(
array('term' => '<>&\'"áéíóú',
'label' => 'Cats & Dogs',
'scheme' => 'http://example.com/schema1'),
array('term'=> 'cat_dog2')
));
$renderer = new Renderer\Feed\Rss($this->validWriter);
$feed = Reader\Reader::importString($renderer->render()->saveXml());
$entry = $feed->current();
$expected = array(
array('term' => '<>&\'"áéíóú',
'label' => '<>&\'"áéíóú',
'scheme' => 'http://example.com/schema1'),
array('term' => 'cat_dog2',
'label' => 'cat_dog2',
'scheme' => null)
);
$this->assertEquals($expected, (array) $entry->getCategories());
}
}
| julianodecezaro/zf2 | vendor/zendframework/zendframework/tests/ZendTest/Feed/Writer/Renderer/Entry/RssTest.php | PHP | bsd-3-clause | 15,279 |
def test_is_generator_alias():
from nose.util import is_generator, isgenerator
| DESHRAJ/fjord | vendor/packages/nose/unit_tests/test_issue_064.py | Python | bsd-3-clause | 83 |
/*
* Copyright 2008 Ayman Al-Sairafi ayman.alsairafi@gmail.com
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License
* at http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package jsyntaxpane.components;
import jsyntaxpane.actions.*;
import java.awt.Color;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.swing.text.BadLocationException;
import javax.swing.text.DefaultHighlighter;
import javax.swing.text.Highlighter;
import javax.swing.text.JTextComponent;
import jsyntaxpane.SyntaxDocument;
import jsyntaxpane.Token;
/**
* This class contains static utility methods to make highliting in text
* components easier.
*
* @author Ayman Al-Sairafi
*/
public class Markers {
// This subclass is used in our highlighting code
public static class SimpleMarker extends DefaultHighlighter.DefaultHighlightPainter {
public SimpleMarker(Color color) {
super(color);
}
}
/**
* Removes only our private highlights
* This is public so that we can remove the highlights when the editorKit
* is unregistered. SimpleMarker can be null, in which case all instances of
* our Markers are removed.
* @param component the text component whose markers are to be removed
* @param marker the SimpleMarker to remove
*/
public static void removeMarkers(JTextComponent component, SimpleMarker marker) {
Highlighter hilite = component.getHighlighter();
Highlighter.Highlight[] hilites = hilite.getHighlights();
for (int i = 0; i < hilites.length; i++) {
if (hilites[i].getPainter() instanceof SimpleMarker) {
SimpleMarker hMarker = (SimpleMarker) hilites[i].getPainter();
if (marker == null || hMarker.equals(marker)) {
hilite.removeHighlight(hilites[i]);
}
}
}
}
/**
* Remove all the markers from an JEditorPane
* @param editorPane
*/
public static void removeMarkers(JTextComponent editorPane) {
removeMarkers(editorPane, null);
}
/**
* add highlights for the given Token on the given pane
* @param pane
* @param token
* @param marker
*/
public static void markToken(JTextComponent pane, Token token, SimpleMarker marker) {
markText(pane, token.start, token.end(), marker);
}
/**
* add highlights for the given region on the given pane
* @param pane
* @param start
* @param end
* @param marker
*/
public static void markText(JTextComponent pane, int start, int end, SimpleMarker marker) {
try {
Highlighter hiliter = pane.getHighlighter();
int selStart = pane.getSelectionStart();
int selEnd = pane.getSelectionEnd();
// if there is no selection or selection does not overlap
if(selStart == selEnd || end < selStart || start > selStart) {
hiliter.addHighlight(start, end, marker);
return;
}
// selection starts within the highlight, highlight before slection
if(selStart > start && selStart < end ) {
hiliter.addHighlight(start, selStart, marker);
}
// selection ends within the highlight, highlight remaining
if(selEnd > start && selEnd < end ) {
hiliter.addHighlight(selEnd, end, marker);
}
} catch (BadLocationException ex) {
// nothing we can do if the request is out of bound
LOG.log(Level.SEVERE, null, ex);
}
}
/**
* Mark all text in the document that matches the given pattern
* @param pane control to use
* @param pattern pattern to match
* @param marker marker to use for highlighting
*/
public static void markAll(JTextComponent pane, Pattern pattern, SimpleMarker marker) {
SyntaxDocument sDoc = ActionUtils.getSyntaxDocument(pane);
if(sDoc == null || pattern == null) {
return;
}
Matcher matcher = sDoc.getMatcher(pattern);
// we may not have any matcher (due to undo or something, so don't do anything.
if(matcher==null) {
return;
}
while(matcher.find()) {
markText(pane, matcher.start(), matcher.end(), marker);
}
}
private static final Logger LOG = Logger.getLogger(Markers.class.getName());
}
| zqq90/webit-editor | src/main/java/jsyntaxpane/components/Markers.java | Java | bsd-3-clause | 4,976 |
# The absolute import feature is required so that we get the root celery
# module rather than `amo.celery`.
from __future__ import absolute_import
from inspect import isclass
from celery.datastructures import AttributeDict
from tower import ugettext_lazy as _
__all__ = ('LOG', 'LOG_BY_ID', 'LOG_KEEP',)
class _LOG(object):
action_class = None
class CREATE_ADDON(_LOG):
id = 1
action_class = 'add'
format = _(u'{addon} was created.')
keep = True
class EDIT_PROPERTIES(_LOG):
""" Expects: addon """
id = 2
action_class = 'edit'
format = _(u'{addon} properties edited.')
class EDIT_DESCRIPTIONS(_LOG):
id = 3
action_class = 'edit'
format = _(u'{addon} description edited.')
class EDIT_CATEGORIES(_LOG):
id = 4
action_class = 'edit'
format = _(u'Categories edited for {addon}.')
class ADD_USER_WITH_ROLE(_LOG):
id = 5
action_class = 'add'
format = _(u'{0.name} ({1}) added to {addon}.')
keep = True
class REMOVE_USER_WITH_ROLE(_LOG):
id = 6
action_class = 'delete'
# L10n: {0} is the user being removed, {1} is their role.
format = _(u'{0.name} ({1}) removed from {addon}.')
keep = True
class EDIT_CONTRIBUTIONS(_LOG):
id = 7
action_class = 'edit'
format = _(u'Contributions for {addon}.')
class USER_DISABLE(_LOG):
id = 8
format = _(u'{addon} disabled.')
keep = True
class USER_ENABLE(_LOG):
id = 9
format = _(u'{addon} enabled.')
keep = True
# TODO(davedash): Log these types when pages are present
class SET_PUBLIC_STATS(_LOG):
id = 10
format = _(u'Stats set public for {addon}.')
keep = True
# TODO(davedash): Log these types when pages are present
class UNSET_PUBLIC_STATS(_LOG):
id = 11
format = _(u'{addon} stats set to private.')
keep = True
class CHANGE_STATUS(_LOG):
id = 12
# L10n: {0} is the status
format = _(u'{addon} status changed to {0}.')
keep = True
class ADD_PREVIEW(_LOG):
id = 13
action_class = 'add'
format = _(u'Preview added to {addon}.')
class EDIT_PREVIEW(_LOG):
id = 14
action_class = 'edit'
format = _(u'Preview edited for {addon}.')
class DELETE_PREVIEW(_LOG):
id = 15
action_class = 'delete'
format = _(u'Preview deleted from {addon}.')
class ADD_VERSION(_LOG):
id = 16
action_class = 'add'
format = _(u'{version} added to {addon}.')
keep = True
class EDIT_VERSION(_LOG):
id = 17
action_class = 'edit'
format = _(u'{version} edited for {addon}.')
class DELETE_VERSION(_LOG):
id = 18
action_class = 'delete'
# Note, {0} is a string not a version since the version is deleted.
# L10n: {0} is the version number
format = _(u'Version {0} deleted from {addon}.')
keep = True
class ADD_FILE_TO_VERSION(_LOG):
id = 19
action_class = 'add'
format = _(u'File {0.name} added to {version} of {addon}.')
class DELETE_FILE_FROM_VERSION(_LOG):
"""
Expecting: addon, filename, version
Because the file is being deleted, filename and version
should be strings and not the object.
"""
id = 20
action_class = 'delete'
format = _(u'File {0} deleted from {version} of {addon}.')
class APPROVE_VERSION(_LOG):
id = 21
action_class = 'approve'
format = _(u'{addon} {version} approved.')
short = _(u'Approved')
keep = True
review_email_user = True
review_queue = True
class PRELIMINARY_VERSION(_LOG):
id = 42
action_class = 'approve'
format = _(u'{addon} {version} given preliminary review.')
short = _(u'Preliminarily approved')
keep = True
review_email_user = True
review_queue = True
class REJECT_VERSION(_LOG):
# takes add-on, version, reviewtype
id = 43
action_class = 'reject'
format = _(u'{addon} {version} rejected.')
short = _(u'Rejected')
keep = True
review_email_user = True
review_queue = True
class RETAIN_VERSION(_LOG):
# takes add-on, version, reviewtype
id = 22
format = _(u'{addon} {version} retained.')
short = _(u'Retained')
keep = True
review_email_user = True
review_queue = True
class ESCALATE_VERSION(_LOG):
# takes add-on, version, reviewtype
id = 23
format = _(u'{addon} {version} escalated.')
short = _(u'Escalated')
keep = True
review_email_user = True
review_queue = True
class REQUEST_VERSION(_LOG):
# takes add-on, version, reviewtype
id = 24
format = _(u'{addon} {version} review requested.')
short = _(u'Review requested')
keep = True
review_email_user = True
review_queue = True
class REQUEST_INFORMATION(_LOG):
id = 44
format = _(u'{addon} {version} more information requested.')
short = _(u'More information requested')
keep = True
review_email_user = True
review_queue = True
class REQUEST_SUPER_REVIEW(_LOG):
id = 45
format = _(u'{addon} {version} super review requested.')
short = _(u'Super review requested')
keep = True
review_queue = True
class COMMENT_VERSION(_LOG):
id = 49
format = _(u'Comment on {addon} {version}.')
short = _(u'Comment')
keep = True
review_queue = True
hide_developer = True
class ADD_TAG(_LOG):
id = 25
action_class = 'tag'
format = _(u'{tag} added to {addon}.')
class REMOVE_TAG(_LOG):
id = 26
action_class = 'tag'
format = _(u'{tag} removed from {addon}.')
class ADD_TO_COLLECTION(_LOG):
id = 27
action_class = 'collection'
format = _(u'{addon} added to {collection}.')
class REMOVE_FROM_COLLECTION(_LOG):
id = 28
action_class = 'collection'
format = _(u'{addon} removed from {collection}.')
class ADD_REVIEW(_LOG):
id = 29
action_class = 'review'
format = _(u'{review} for {addon} written.')
# TODO(davedash): Add these when we do the admin site
class ADD_RECOMMENDED_CATEGORY(_LOG):
id = 31
action_class = 'edit'
# L10n: {0} is a category name.
format = _(u'{addon} featured in {0}.')
class REMOVE_RECOMMENDED_CATEGORY(_LOG):
id = 32
action_class = 'edit'
# L10n: {0} is a category name.
format = _(u'{addon} no longer featured in {0}.')
class ADD_RECOMMENDED(_LOG):
id = 33
format = _(u'{addon} is now featured.')
keep = True
class REMOVE_RECOMMENDED(_LOG):
id = 34
format = _(u'{addon} is no longer featured.')
keep = True
class ADD_APPVERSION(_LOG):
id = 35
action_class = 'add'
# L10n: {0} is the application, {1} is the version of the app
format = _(u'{0} {1} added.')
class CHANGE_USER_WITH_ROLE(_LOG):
""" Expects: author.user, role, addon """
id = 36
# L10n: {0} is a user, {1} is their role
format = _(u'{0.name} role changed to {1} for {addon}.')
keep = True
class CHANGE_LICENSE(_LOG):
""" Expects: license, addon """
id = 37
action_class = 'edit'
format = _(u'{addon} is now licensed under {0.name}.')
class CHANGE_POLICY(_LOG):
id = 38
action_class = 'edit'
format = _(u'{addon} policy changed.')
class CHANGE_ICON(_LOG):
id = 39
action_class = 'edit'
format = _(u'{addon} icon changed.')
class APPROVE_REVIEW(_LOG):
id = 40
action_class = 'approve'
format = _(u'{review} for {addon} approved.')
editor_format = _(u'{user} approved {review} for {addon}.')
keep = True
editor_event = True
class DELETE_REVIEW(_LOG):
"""Requires review.id and add-on objects."""
id = 41
action_class = 'review'
format = _(u'Review {review} for {addon} deleted.')
editor_format = _(u'{user} deleted {review} for {addon}.')
keep = True
editor_event = True
class MAX_APPVERSION_UPDATED(_LOG):
id = 46
format = _(u'Application max version for {version} updated.')
class BULK_VALIDATION_EMAILED(_LOG):
id = 47
format = _(u'Authors emailed about compatibility of {version}.')
class BULK_VALIDATION_USER_EMAILED(_LOG):
id = 130
format = _(u'Email sent to Author about add-on compatibility.')
class CHANGE_PASSWORD(_LOG):
id = 48
format = _(u'Password changed.')
class PAYPAL_FAILED(_LOG):
id = 51
format = _(u'{addon} failed checks with PayPal.')
class MANIFEST_UPDATED(_LOG):
id = 52
format = _(u'{addon} manifest updated.')
class APPROVE_VERSION_WAITING(_LOG):
id = 53
action_class = 'approve'
format = _(u'{addon} {version} approved but waiting to be made public.')
short = _(u'Approved but waiting')
keep = True
review_email_user = True
review_queue = True
class PURCHASE_ADDON(_LOG):
id = 54
format = _(u'{addon} purchased.')
class INSTALL_ADDON(_LOG):
id = 55
format = _(u'{addon} installed.')
class USER_EDITED(_LOG):
id = 60
format = _(u'Account updated.')
class ESCALATION_CLEARED(_LOG):
id = 66
format = _(u'Escalation cleared for {addon}.')
short = _(u'Escalation cleared')
keep = True
review_queue = True
class APP_DISABLED(_LOG):
id = 67
format = _(u'{addon} disabled.')
short = _(u'App disabled')
keep = True
review_queue = True
class ESCALATED_HIGH_ABUSE(_LOG):
id = 68
format = _(u'{addon} escalated because of high number of abuse reports.')
short = _(u'High Abuse Reports')
keep = True
review_queue = True
class ESCALATE_MANUAL(_LOG):
id = 73
format = _(u'{addon} escalated by reviewer.')
short = _(u'Reviewer escalation')
keep = True
review_queue = True
# TODO(robhudson): Escalation log for editor escalation..
class VIDEO_ERROR(_LOG):
id = 74
format = _(u'Video removed from {addon} because of a problem with '
u'the video. ')
short = _(u'Video removed')
class REREVIEW_DEVICES_ADDED(_LOG):
id = 75
format = _(u'{addon} re-review because of new device(s) added.')
short = _(u'Device(s) Added')
keep = True
review_queue = True
class REVIEW_DEVICE_OVERRIDE(_LOG):
id = 76
format = _(u'{addon} device support manually changed by reviewer.')
short = _(u'Device(s) Changed by Reviewer')
keep = True
review_queue = True
class CUSTOM_TEXT(_LOG):
id = 98
format = '{0}'
class CUSTOM_HTML(_LOG):
id = 99
format = '{0}'
class OBJECT_ADDED(_LOG):
id = 100
format = _(u'Created: {0}.')
admin_event = True
class OBJECT_EDITED(_LOG):
id = 101
format = _(u'Edited field: {2} set to: {0}.')
admin_event = True
class OBJECT_DELETED(_LOG):
id = 102
format = _(u'Deleted: {1}.')
admin_event = True
class ADMIN_USER_EDITED(_LOG):
id = 103
format = _(u'User {user} edited, reason: {1}')
admin_event = True
class ADMIN_USER_ANONYMIZED(_LOG):
id = 104
format = _(u'User {user} anonymized.')
admin_event = True
class ADMIN_USER_RESTRICTED(_LOG):
id = 105
format = _(u'User {user} restricted.')
admin_event = True
class ADMIN_VIEWED_LOG(_LOG):
id = 106
format = _(u'Admin {0} viewed activity log for {user}.')
admin_event = True
class EDIT_REVIEW(_LOG):
id = 107
action_class = 'review'
format = _(u'{review} for {addon} updated.')
class THEME_REVIEW(_LOG):
id = 108
action_class = 'review'
format = _(u'{addon} reviewed.')
class GROUP_USER_ADDED(_LOG):
id = 120
action_class = 'access'
format = _(u'User {0.name} added to {group}.')
keep = True
admin_event = True
class GROUP_USER_REMOVED(_LOG):
id = 121
action_class = 'access'
format = _(u'User {0.name} removed from {group}.')
keep = True
admin_event = True
class REVIEW_FEATURES_OVERRIDE(_LOG):
id = 122
format = _(u'{addon} minimum requirements manually changed by reviewer.')
short = _(u'Requirements Changed by Reviewer')
keep = True
review_queue = True
class REREVIEW_FEATURES_CHANGED(_LOG):
id = 123
format = _(u'{addon} minimum requirements manually changed.')
short = _(u'Requirements Changed')
keep = True
review_queue = True
class CHANGE_VERSION_STATUS(_LOG):
id = 124
# L10n: {0} is the status
format = _(u'{version} status changed to {0}.')
keep = True
class DELETE_USER_LOOKUP(_LOG):
id = 125
# L10n: {0} is the status
format = _(u'User {0.name} {0.id} deleted via lookup tool.')
keep = True
class CONTENT_RATING_TO_ADULT(_LOG):
id = 126
format = _('{addon} content rating changed to Adult.')
review_queue = True
class CONTENT_RATING_CHANGED(_LOG):
id = 127
format = _('{addon} content rating changed.')
class ADDON_UNLISTED(_LOG):
id = 128
format = _(u'{addon} unlisted.')
keep = True
class BETA_SIGNED_VALIDATION_PASSED(_LOG):
id = 131
format = _(u'{file} was signed.')
keep = True
class BETA_SIGNED_VALIDATION_FAILED(_LOG):
id = 132
format = _(u'{file} was signed.')
keep = True
class DELETE_ADDON(_LOG):
id = 133
action_class = 'delete'
# L10n: {0} is the add-on GUID.
format = _(u'Addon id {0} with GUID {1} has been deleted')
keep = True
LOGS = [x for x in vars().values()
if isclass(x) and issubclass(x, _LOG) and x != _LOG]
# Make sure there's no duplicate IDs.
assert len(LOGS) == len(set(log.id for log in LOGS))
LOG_BY_ID = dict((l.id, l) for l in LOGS)
LOG = AttributeDict((l.__name__, l) for l in LOGS)
LOG_ADMINS = [l.id for l in LOGS if hasattr(l, 'admin_event')]
LOG_KEEP = [l.id for l in LOGS if hasattr(l, 'keep')]
LOG_EDITORS = [l.id for l in LOGS if hasattr(l, 'editor_event')]
LOG_REVIEW_QUEUE = [l.id for l in LOGS if hasattr(l, 'review_queue')]
# Is the user emailed the message?
LOG_REVIEW_EMAIL_USER = [l.id for l in LOGS if hasattr(l, 'review_email_user')]
# Logs *not* to show to the developer.
LOG_HIDE_DEVELOPER = [l.id for l in LOGS
if (getattr(l, 'hide_developer', False)
or l.id in LOG_ADMINS)]
def log(action, *args, **kw):
"""
e.g. amo.log(amo.LOG.CREATE_ADDON, []),
amo.log(amo.LOG.ADD_FILE_TO_VERSION, file, version)
"""
from access.models import Group
from addons.models import Addon
from amo import get_user, logger_log
from devhub.models import (ActivityLog, AddonLog, CommentLog, GroupLog,
UserLog, VersionLog)
from users.models import UserProfile
from versions.models import Version
user = kw.get('user', get_user())
if not user:
logger_log.warning('Activity log called with no user: %s' % action.id)
return
al = ActivityLog(user=user, action=action.id)
al.arguments = args
if 'details' in kw:
al.details = kw['details']
al.save()
if 'details' in kw and 'comments' in al.details:
CommentLog(comments=al.details['comments'], activity_log=al).save()
# TODO(davedash): post-remora this may not be necessary.
if 'created' in kw:
al.created = kw['created']
# Double save necessary since django resets the created date on save.
al.save()
for arg in args:
if isinstance(arg, tuple):
if arg[0] == Addon:
AddonLog(addon_id=arg[1], activity_log=al).save()
elif arg[0] == Version:
VersionLog(version_id=arg[1], activity_log=al).save()
elif arg[0] == UserProfile:
UserLog(user_id=arg[1], activity_log=al).save()
elif arg[0] == Group:
GroupLog(group_id=arg[1], activity_log=al).save()
elif isinstance(arg, Addon):
AddonLog(addon=arg, activity_log=al).save()
elif isinstance(arg, Version):
VersionLog(version=arg, activity_log=al).save()
elif isinstance(arg, UserProfile):
# Index by any user who is mentioned as an argument.
UserLog(activity_log=al, user=arg).save()
elif isinstance(arg, Group):
GroupLog(group=arg, activity_log=al).save()
# Index by every user
UserLog(activity_log=al, user=user).save()
return al
| muffinresearch/addons-server | apps/amo/log.py | Python | bsd-3-clause | 16,053 |
/****** Form Header File *******/
#ifndef FORM_H
#define FORM_H
/***** Shared Definitions *****/
#include "form.d"
/***** Function Declarations *****/
PublicFnDecl FORM *FORM_read(char const *filename, int isBuffer);
PublicFnDecl PAGE_Action FORM_handler(
FORM *form, CUR_WINDOW *win, PAGE_Action action
);
PublicFnDecl void FORM_menuToForm();
PublicFnDecl void FORM_centerFormElts(FORM *fptr, int width);
#endif
/************************************************************************
form.h 2 replace /users/ees/interface
860730 15:33:11 ees
************************************************************************/
/************************************************************************
form.h 3 replace /users/lis/frontend/M2/sys
870811 17:04:30 m2 Curses, VAX conversion, and editor fixes/enhancements
************************************************************************/
/************************************************************************
form.h 4 replace /users/lis/frontend/M2/sys
880505 11:04:15 m2 Apollo and VAX port
************************************************************************/
| MichaelJCaruso/vision | software/src/master/src/frontend/form.h | C | bsd-3-clause | 1,149 |
// Copyright 2018 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef PPAPI_TESTS_TEST_TCP_SOCKET_PRIVATE_CRASH_H_
#define PPAPI_TESTS_TEST_TCP_SOCKET_PRIVATE_CRASH_H_
#include <string>
#include "ppapi/c/pp_stdint.h"
#include "ppapi/tests/test_case.h"
class TestTCPSocketPrivateCrash : public TestCase {
public:
explicit TestTCPSocketPrivateCrash(TestingInstance* instance);
// TestCase implementation.
virtual bool Init();
virtual void RunTests(const std::string& filter);
private:
std::string TestResolve();
};
#endif // PPAPI_TESTS_TEST_TCP_SOCKET_PRIVATE_CRASH_H_
| scheib/chromium | ppapi/tests/test_tcp_socket_private_crash.h | C | bsd-3-clause | 691 |
// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "cc/scheduler/scheduler_settings.h"
#include "cc/trees/layer_tree_settings.h"
namespace cc {
SchedulerSettings::SchedulerSettings()
: begin_frame_scheduling_enabled(true),
main_frame_before_draw_enabled(true),
main_frame_before_activation_enabled(false),
impl_side_painting(false),
timeout_and_draw_when_animation_checkerboards(true),
maximum_number_of_failed_draws_before_draw_is_forced_(3),
using_synchronous_renderer_compositor(false),
throttle_frame_production(true) {
}
SchedulerSettings::SchedulerSettings(const LayerTreeSettings& settings)
: begin_frame_scheduling_enabled(settings.begin_frame_scheduling_enabled),
main_frame_before_draw_enabled(settings.main_frame_before_draw_enabled),
main_frame_before_activation_enabled(
settings.main_frame_before_activation_enabled),
impl_side_painting(settings.impl_side_painting),
timeout_and_draw_when_animation_checkerboards(
settings.timeout_and_draw_when_animation_checkerboards),
maximum_number_of_failed_draws_before_draw_is_forced_(
settings.maximum_number_of_failed_draws_before_draw_is_forced_),
using_synchronous_renderer_compositor(
settings.using_synchronous_renderer_compositor),
throttle_frame_production(settings.throttle_frame_production) {
}
SchedulerSettings::~SchedulerSettings() {}
scoped_ptr<base::Value> SchedulerSettings::AsValue() const {
scoped_ptr<base::DictionaryValue> state(new base::DictionaryValue);
state->SetBoolean("begin_frame_scheduling_enabled",
begin_frame_scheduling_enabled);
state->SetBoolean("main_frame_before_draw_enabled",
main_frame_before_draw_enabled);
state->SetBoolean("main_frame_before_activation_enabled",
main_frame_before_activation_enabled);
state->SetBoolean("impl_side_painting", impl_side_painting);
state->SetBoolean("timeout_and_draw_when_animation_checkerboards",
timeout_and_draw_when_animation_checkerboards);
state->SetInteger("maximum_number_of_failed_draws_before_draw_is_forced_",
maximum_number_of_failed_draws_before_draw_is_forced_);
state->SetBoolean("using_synchronous_renderer_compositor",
using_synchronous_renderer_compositor);
state->SetBoolean("throttle_frame_production", throttle_frame_production);
return state.PassAs<base::Value>();
}
} // namespace cc
| boundarydevices/android_external_chromium_org | cc/scheduler/scheduler_settings.cc | C++ | bsd-3-clause | 2,639 |
// Copyright 2007 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview DOM pattern to match a sequence of other patterns.
*/
goog.provide('goog.dom.pattern.Sequence');
goog.require('goog.dom.NodeType');
goog.require('goog.dom.pattern');
goog.require('goog.dom.pattern.AbstractPattern');
goog.require('goog.dom.pattern.MatchType');
/**
* Pattern object that matches a sequence of other patterns.
*
* @param {Array<goog.dom.pattern.AbstractPattern>} patterns Ordered array of
* patterns to match.
* @param {boolean=} opt_ignoreWhitespace Optional flag to ignore text nodes
* consisting entirely of whitespace. The default is to not ignore them.
* @constructor
* @extends {goog.dom.pattern.AbstractPattern}
* @final
*/
goog.dom.pattern.Sequence = function(patterns, opt_ignoreWhitespace) {
/**
* Ordered array of patterns to match.
*
* @type {Array<goog.dom.pattern.AbstractPattern>}
*/
this.patterns = patterns;
/**
* Whether or not to ignore whitespace only Text nodes.
*
* @private {boolean}
*/
this.ignoreWhitespace_ = !!opt_ignoreWhitespace;
/**
* Position in the patterns array we have reached by successful matches.
*
* @private {number}
*/
this.currentPosition_ = 0;
};
goog.inherits(goog.dom.pattern.Sequence, goog.dom.pattern.AbstractPattern);
/**
* Regular expression for breaking text nodes.
* @private {!RegExp}
*/
goog.dom.pattern.Sequence.BREAKING_TEXTNODE_RE_ = /^\s*$/;
/**
* Test whether the given token starts, continues, or finishes the sequence
* of patterns given in the constructor.
*
* @param {Node} token Token to match against.
* @param {goog.dom.TagWalkType} type The type of token.
* @return {goog.dom.pattern.MatchType} <code>MATCH</code> if the pattern
* matches, <code>MATCHING</code> if the pattern starts a match, and
* <code>NO_MATCH</code> if the pattern does not match.
* @override
*/
goog.dom.pattern.Sequence.prototype.matchToken = function(token, type) {
// If the option is set, ignore any whitespace only text nodes
if (this.ignoreWhitespace_ && token.nodeType == goog.dom.NodeType.TEXT &&
goog.dom.pattern.Sequence.BREAKING_TEXTNODE_RE_.test(token.nodeValue)) {
return goog.dom.pattern.MatchType.MATCHING;
}
switch (this.patterns[this.currentPosition_].matchToken(token, type)) {
case goog.dom.pattern.MatchType.MATCH:
// Record the first token we match.
if (this.currentPosition_ == 0) {
this.matchedNode = token;
}
// Move forward one position.
this.currentPosition_++;
// Check if this is the last position.
if (this.currentPosition_ == this.patterns.length) {
this.reset();
return goog.dom.pattern.MatchType.MATCH;
} else {
return goog.dom.pattern.MatchType.MATCHING;
}
case goog.dom.pattern.MatchType.MATCHING:
// This can happen when our child pattern is a sequence or a repetition.
return goog.dom.pattern.MatchType.MATCHING;
case goog.dom.pattern.MatchType.BACKTRACK_MATCH:
// This means a repetitive match succeeded 1 token ago.
// TODO(robbyw): Backtrack further if necessary.
this.currentPosition_++;
if (this.currentPosition_ == this.patterns.length) {
this.reset();
return goog.dom.pattern.MatchType.BACKTRACK_MATCH;
} else {
// Retry the same token on the next pattern.
return this.matchToken(token, type);
}
default:
this.reset();
return goog.dom.pattern.MatchType.NO_MATCH;
}
};
/**
* Reset any internal state this pattern keeps.
* @override
*/
goog.dom.pattern.Sequence.prototype.reset = function() {
if (this.patterns[this.currentPosition_]) {
this.patterns[this.currentPosition_].reset();
}
this.currentPosition_ = 0;
};
| scheib/chromium | third_party/google-closure-library/closure/goog/dom/pattern/sequence.js | JavaScript | bsd-3-clause | 4,393 |
/*
* Copyright (c) 2014, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
#pragma once
#include <osquery/enroll.h>
#include <osquery/flags.h>
#include "osquery/remote/requests.h"
#include "osquery/remote/transports/tls.h"
namespace osquery {
DECLARE_string(tls_enroll_override);
DECLARE_string(tls_hostname);
DECLARE_bool(tls_node_api);
DECLARE_bool(tls_secret_always);
/**
* @brief Helper class for allowing TLS plugins to easily kick off requests
*
* There are many static functions in this class that have very similar
* behaviour, which allow them to be used in many context. Some methods accept
* parameters, some don't require them. Some have built-in retry logic, some
* don't. Some return results in a ptree, some return results in JSON, etc.
*/
class TLSRequestHelper {
public:
/**
* @brief Using the `tls_hostname` flag and an endpoint, construct a URI
*
* @param endpoint is the URI endpoint to be combined with `tls_hostname`
* @return a string representing the uri
*/
static std::string makeURI(const std::string& endpoint) {
auto node_key = getNodeKey("tls");
auto uri = "https://" + FLAGS_tls_hostname;
if (FLAGS_tls_node_api) {
// The TLS API should treat clients as nodes.
// In this case the node_key acts as an identifier (node) and the
// endpoints
// (if provided) are treated as edges from the nodes.
uri += "/" + node_key;
}
uri += endpoint;
// Some APIs may require persistent identification.
if (FLAGS_tls_secret_always) {
uri += ((uri.find("?") != std::string::npos) ? "&" : "?") +
FLAGS_tls_enroll_override + "=" + getEnrollSecret();
}
return std::move(uri);
}
/**
* @brief Send a TLS request
*
* @param uri is the URI to send the request to
* @param params is a ptree of the params to send to the server. This isn't
* const because it will be modified to include node_key.
* @param output is the ptree which will be populated with the deserialized
* results
*
* @return a Status object indicating the success or failure of the operation
*/
template <class TSerializer>
static Status go(const std::string& uri,
boost::property_tree::ptree& params,
boost::property_tree::ptree& output) {
auto node_key = getNodeKey("tls");
// If using a GET request, append the node_key to the URI variables.
std::string uri_suffix;
if (FLAGS_tls_node_api) {
uri_suffix = "&node_key=" + node_key;
} else {
params.put<std::string>("node_key", node_key);
}
// Again check for GET to call with/without parameters.
auto request = Request<TLSTransport, TSerializer>(uri + uri_suffix);
auto status = (FLAGS_tls_node_api) ? request.call() : request.call(params);
if (!status.ok()) {
return status;
}
// The call succeeded, store the enrolled key.
status = request.getResponse(output);
if (!status.ok()) {
return status;
}
// Receive config or key rejection
if (output.count("node_invalid") > 0 || output.count("error") > 0) {
return Status(1, "Request failed: Invalid node key");
}
return Status(0, "OK");
}
/**
* @brief Send a TLS request
*
* @param uri is the URI to send the request to
* @param params is a ptree of the params to send to the server. This isn't
* const because it will be modified to include node_key.
*
* @return a Status object indicating the success or failure of the operation
*/
template <class TSerializer>
static Status go(const std::string& uri,
boost::property_tree::ptree& output) {
boost::property_tree::ptree params;
return TLSRequestHelper::go<TSerializer>(uri, params, output);
}
/**
* @brief Send a TLS request
*
* @param uri is the URI to send the request to
* @param params is a ptree of the params to send to the server. This isn't
* const because it will be modified to include node_key.
* @param output is the string which will be populated with the deserialized
* results
*
* @return a Status object indicating the success or failure of the operation
*/
template <class TSerializer>
static Status go(const std::string& uri,
boost::property_tree::ptree& params,
std::string& output) {
boost::property_tree::ptree recv;
auto s = TLSRequestHelper::go<TSerializer>(uri, params, recv);
if (s.ok()) {
auto serializer = TSerializer();
return serializer.serialize(recv, output);
}
return s;
}
/**
* @brief Send a TLS request
*
* @param uri is the URI to send the request to
* @param output is the string which will be populated with the deserialized
* results
*
* @return a Status object indicating the success or failure of the operation
*/
template <class TSerializer>
static Status go(const std::string& uri, std::string& output) {
boost::property_tree::ptree params;
return TLSRequestHelper::go<TSerializer>(uri, params, output);
}
/**
* @brief Send a TLS request
*
* @param uri is the URI to send the request to
* @param params is a ptree of the params to send to the server. This isn't
* const because it will be modified to include node_key.
* @param output is the string which will be populated with the deserialized
* results
* @param attempts is the number of attempts to make if the request fails
*
* @return a Status object indicating the success or failure of the operation
*/
template <class TSerializer>
static Status go(const std::string& uri,
boost::property_tree::ptree& params,
std::string& output,
const size_t attempts) {
Status s;
for (size_t i = 1; i <= attempts; i++) {
s = TLSRequestHelper::go<TSerializer>(uri, params, output);
if (s.ok()) {
return s;
}
if (i == attempts) {
break;
}
::sleep(i * i);
}
return s;
}
/**
* @brief Send a TLS request
*
* @param uri is the URI to send the request to
* @param output is the string which will be populated with the deserialized
* results
* @param attempts is the number of attempts to make if the request fails
*
* @return a Status object indicating the success or failure of the operation
*/
template <class TSerializer>
static Status go(const std::string& uri,
std::string& output,
const size_t attempts) {
boost::property_tree::ptree params;
return TLSRequestHelper::go<TSerializer>(uri, params, output, attempts);
}
};
}
| SEC-squad/osquery | osquery/remote/utility.h | C | bsd-3-clause | 6,930 |
/**
* PANDA 3D SOFTWARE
* Copyright (c) Carnegie Mellon University. All rights reserved.
*
* All use of this software is subject to the terms of the revised BSD
* license. You should have received a copy of this license along
* with this source code in a file named "LICENSE."
*
* @file fltRecord.h
* @author drose
* @date 2000-08-24
*/
#ifndef FLTRECORD_H
#define FLTRECORD_H
#include "pandatoolbase.h"
#include "fltOpcode.h"
#include "fltError.h"
#include "typedObject.h"
#include "typedReferenceCount.h"
#include "pointerTo.h"
class FltHeader;
class FltRecordReader;
class FltRecordWriter;
class DatagramIterator;
/**
* The base class for all kinds of records in a MultiGen OpenFlight file. A
* flt file consists of a hierarchy of "beads" of various kinds, each of which
* may be followed by n ancillary records, written sequentially to the file.
*/
class FltRecord : public TypedReferenceCount {
public:
FltRecord(FltHeader *header);
virtual ~FltRecord();
int get_num_children() const;
FltRecord *get_child(int n) const;
void clear_children();
void add_child(FltRecord *child);
int get_num_subfaces() const;
FltRecord *get_subface(int n) const;
void clear_subfaces();
void add_subface(FltRecord *subface);
int get_num_extensions() const;
FltRecord *get_extension(int n) const;
void clear_extensions();
void add_extension(FltRecord *extension);
int get_num_ancillary() const;
FltRecord *get_ancillary(int n) const;
void clear_ancillary();
void add_ancillary(FltRecord *ancillary);
bool has_comment() const;
const std::string &get_comment() const;
void clear_comment();
void set_comment(const std::string &comment);
void check_remaining_size(const DatagramIterator &di,
const std::string &name = std::string()) const;
virtual void apply_converted_filenames();
virtual void output(std::ostream &out) const;
virtual void write(std::ostream &out, int indent_level = 0) const;
protected:
void write_children(std::ostream &out, int indent_level) const;
static bool is_ancillary(FltOpcode opcode);
FltRecord *create_new_record(FltOpcode opcode) const;
FltError read_record_and_children(FltRecordReader &reader);
virtual bool extract_record(FltRecordReader &reader);
virtual bool extract_ancillary(FltRecordReader &reader);
virtual FltError write_record_and_children(FltRecordWriter &writer) const;
virtual bool build_record(FltRecordWriter &writer) const;
virtual FltError write_ancillary(FltRecordWriter &writer) const;
protected:
FltHeader *_header;
private:
typedef pvector<PT(FltRecord)> Records;
Records _children;
Records _subfaces;
Records _extensions;
Records _ancillary;
std::string _comment;
public:
virtual TypeHandle get_type() const {
return get_class_type();
}
virtual TypeHandle force_init_type() {init_type(); return get_class_type();}
static TypeHandle get_class_type() {
return _type_handle;
}
static void init_type() {
TypedReferenceCount::init_type();
register_type(_type_handle, "FltRecord",
TypedReferenceCount::get_class_type());
}
private:
static TypeHandle _type_handle;
};
INLINE std::ostream &operator << (std::ostream &out, const FltRecord &record);
#include "fltRecord.I"
#endif
| chandler14362/panda3d | pandatool/src/flt/fltRecord.h | C | bsd-3-clause | 3,311 |
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <stdint.h>
#include <utility>
#include <vector>
#include "base/strings/string16.h"
#include "content/common/content_export.h"
#include "ipc/ipc_message_macros.h"
#undef IPC_MESSAGE_EXPORT
#define IPC_MESSAGE_EXPORT CONTENT_EXPORT
#define IPC_MESSAGE_START DWriteFontProxyMsgStart
#ifndef CONTENT_COMMON_DWRITE_FONT_PROXY_MESSAGES_H_
#define CONTENT_COMMON_DWRITE_FONT_PROXY_MESSAGES_H_
// The macros can't handle a complex template declaration, so we typedef it.
typedef std::pair<base::string16, base::string16> DWriteStringPair;
#endif // CONTENT_COMMON_DWRITE_FONT_PROXY_MESSAGES_H_
// Locates the index of the specified font family within the system collection.
IPC_SYNC_MESSAGE_CONTROL1_1(DWriteFontProxyMsg_FindFamily,
base::string16 /* family_name */,
uint32_t /* out index */)
// Returns the number of font families in the system collection.
IPC_SYNC_MESSAGE_CONTROL0_1(DWriteFontProxyMsg_GetFamilyCount,
uint32_t /* out count */)
// Returns the list of locale and family name pairs for the font family at the
// specified index.
IPC_SYNC_MESSAGE_CONTROL1_1(
DWriteFontProxyMsg_GetFamilyNames,
uint32_t /* family_index */,
std::vector<DWriteStringPair> /* out family_names */)
// Returns the list of font file paths in the system font directory that contain
// font data for the font family at the specified index.
IPC_SYNC_MESSAGE_CONTROL1_1(DWriteFontProxyMsg_GetFontFiles,
uint32_t /* family_index */,
std::vector<base::string16> /* out file_paths */)
| hujiajie/chromium-crosswalk | content/common/dwrite_font_proxy_messages.h | C | bsd-3-clause | 1,801 |
"""test a warning is triggered when using for a lists comprehension variable"""
__revision__ = 'yo'
TEST_LC = [C for C in __revision__ if C.isalpha()]
print C # WARN
C = 4
print C # this one shouldn't trigger any warning
B = [B for B in __revision__ if B.isalpha()]
print B # nor this one
for var1, var2 in TEST_LC:
var1 = var2 + 4
print var1 # WARN
for note in __revision__:
note.something()
for line in __revision__:
for note in line:
A = note.anotherthing()
for x in []:
pass
for x in range(3):
print (lambda : x)() # OK
| dbbhattacharya/kitsune | vendor/packages/pylint/test/input/func_use_for_or_listcomp_var.py | Python | bsd-3-clause | 560 |
// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/ui/app_list/search/people/people_result.h"
#include <vector>
#include "base/bind.h"
#include "base/memory/ref_counted.h"
#include "base/strings/utf_string_conversions.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/signin/profile_oauth2_token_service_factory.h"
#include "chrome/browser/signin/signin_manager_factory.h"
#include "chrome/browser/ui/app_list/search/common/url_icon_source.h"
#include "chrome/browser/ui/app_list/search/people/person.h"
#include "chrome/browser/ui/browser_navigator.h"
#include "chrome/common/extensions/api/hangouts_private.h"
#include "components/signin/core/browser/profile_oauth2_token_service.h"
#include "components/signin/core/browser/signin_manager.h"
#include "content/public/browser/user_metrics.h"
#include "extensions/browser/event_router.h"
#include "grit/generated_resources.h"
#include "grit/theme_resources.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/base/resource/resource_bundle.h"
namespace OnHangoutRequested =
extensions::api::hangouts_private::OnHangoutRequested;
using extensions::api::hangouts_private::User;
using extensions::api::hangouts_private::HangoutRequest;
namespace {
const int kIconSize = 32;
const char kImageSizePath[] = "s64-p/";
const char kEmailUrlPrefix[] = "mailto:";
const char* const kHangoutsExtensionIds[] = {
"nckgahadagoaajjgafhacjanaoiihapd",
"ljclpkphhpbpinifbeabbhlfddcpfdde",
"ppleadejekpmccmnpjdimmlfljlkdfej",
"eggnbpckecmjlblplehfpjjdhhidfdoj",
"jfjjdfefebklmdbmenmlehlopoocnoeh",
"knipolnnllmklapflnccelgolnpehhpl"
};
// Add a query parameter to specify the size to fetch the image in. The
// original profile image can be of an arbitrary size, we ask the server to
// crop it to a square 64x64 using its smart cropping algorithm.
GURL GetImageUrl(const GURL& url) {
std::string image_filename = url.ExtractFileName();
if (image_filename.empty())
return url;
return url.Resolve(kImageSizePath + image_filename);
}
} // namespace
namespace app_list {
PeopleResult::PeopleResult(Profile* profile, scoped_ptr<Person> person)
: profile_(profile), person_(person.Pass()), weak_factory_(this) {
set_id(person_->id);
set_title(base::UTF8ToUTF16(person_->display_name));
set_relevance(person_->interaction_rank);
set_details(base::UTF8ToUTF16(person_->email));
RefreshHangoutsExtensionId();
SetDefaultActions();
image_ = gfx::ImageSkia(
new UrlIconSource(base::Bind(&PeopleResult::OnIconLoaded,
weak_factory_.GetWeakPtr()),
profile_->GetRequestContext(),
GetImageUrl(person_->image_url),
kIconSize,
IDR_PROFILE_PICTURE_LOADING),
gfx::Size(kIconSize, kIconSize));
SetIcon(image_);
}
PeopleResult::~PeopleResult() {
}
void PeopleResult::Open(int event_flags) {
// Action 0 will always be our default action.
InvokeAction(0, event_flags);
}
void PeopleResult::InvokeAction(int action_index, int event_flags) {
if (hangouts_extension_id_.empty()) {
// If the hangouts app is not available, the only option we are showing
// to the user is 'Send Email'.
SendEmail();
} else {
switch (action_index) {
case 0:
OpenChat();
break;
case 1:
SendEmail();
break;
default:
LOG(ERROR) << "Invalid people search action: " << action_index;
}
}
}
scoped_ptr<ChromeSearchResult> PeopleResult::Duplicate() {
return scoped_ptr<ChromeSearchResult>(
new PeopleResult(profile_, person_->Duplicate().Pass())).Pass();
}
void PeopleResult::OnIconLoaded() {
// Remove the existing image reps since the icon data is loaded and they
// need to be re-created.
const std::vector<gfx::ImageSkiaRep>& image_reps = image_.image_reps();
for (size_t i = 0; i < image_reps.size(); ++i)
image_.RemoveRepresentation(image_reps[i].scale());
SetIcon(image_);
}
void PeopleResult::SetDefaultActions() {
Actions actions;
ui::ResourceBundle& bundle = ui::ResourceBundle::GetSharedInstance();
if (!hangouts_extension_id_.empty()) {
actions.push_back(Action(
*bundle.GetImageSkiaNamed(IDR_PEOPLE_SEARCH_ACTION_CHAT),
*bundle.GetImageSkiaNamed(IDR_PEOPLE_SEARCH_ACTION_CHAT_HOVER),
*bundle.GetImageSkiaNamed(IDR_PEOPLE_SEARCH_ACTION_CHAT_PRESSED),
l10n_util::GetStringUTF16(IDS_PEOPLE_SEARCH_ACTION_CHAT_TOOLTIP)));
}
actions.push_back(Action(
*bundle.GetImageSkiaNamed(IDR_PEOPLE_SEARCH_ACTION_EMAIL),
*bundle.GetImageSkiaNamed(IDR_PEOPLE_SEARCH_ACTION_EMAIL_HOVER),
*bundle.GetImageSkiaNamed(IDR_PEOPLE_SEARCH_ACTION_EMAIL_PRESSED),
l10n_util::GetStringUTF16(IDS_PEOPLE_SEARCH_ACTION_EMAIL_TOOLTIP)));
SetActions(actions);
}
void PeopleResult::OpenChat() {
HangoutRequest request;
request.type = extensions::api::hangouts_private::HANGOUT_TYPE_CHAT;
// from: the user this chat request is originating from.
SigninManagerBase* signin_manager =
SigninManagerFactory::GetInstance()->GetForProfile(profile_);
DCHECK(signin_manager);
request.from = signin_manager->GetAuthenticatedAccountId();
// to: list of users with whom to start this hangout is with.
linked_ptr<User> target(new User());
target->id = person_->owner_id;
request.to.push_back(target);
scoped_ptr<extensions::Event> event(
new extensions::Event(OnHangoutRequested::kEventName,
OnHangoutRequested::Create(request)));
// TODO(rkc): Change this once we remove the hangoutsPrivate API.
// See crbug.com/306672
extensions::EventRouter::Get(profile_)
->DispatchEventToExtension(hangouts_extension_id_, event.Pass());
content::RecordAction(base::UserMetricsAction("PeopleSearch_OpenChat"));
}
void PeopleResult::SendEmail() {
chrome::NavigateParams params(profile_,
GURL(kEmailUrlPrefix + person_->email),
content::PAGE_TRANSITION_LINK);
// If no window exists, this will open a new window this one tab.
params.disposition = NEW_FOREGROUND_TAB;
chrome::Navigate(¶ms);
content::RecordAction(base::UserMetricsAction("PeopleSearch_SendEmail"));
}
void PeopleResult::RefreshHangoutsExtensionId() {
// TODO(rkc): Change this once we remove the hangoutsPrivate API.
// See crbug.com/306672
for (size_t i = 0; i < arraysize(kHangoutsExtensionIds); ++i) {
if (extensions::EventRouter::Get(profile_)->ExtensionHasEventListener(
kHangoutsExtensionIds[i], OnHangoutRequested::kEventName)) {
hangouts_extension_id_ = kHangoutsExtensionIds[i];
return;
}
}
hangouts_extension_id_.clear();
}
ChromeSearchResultType PeopleResult::GetType() {
return SEARCH_PEOPLE_SEARCH_RESULT;
}
} // namespace app_list
| boundarydevices/android_external_chromium_org | chrome/browser/ui/app_list/search/people/people_result.cc | C++ | bsd-3-clause | 7,006 |
#include <set>
#include <string>
#include <math.h>
#include <gtest/gtest.h>
#include "agent.h"
#include "bid.h"
#include "bid_portfolio.h"
#include "composition.h"
#include "equality_helpers.h"
#include "exchange_context.h"
#include "facility.h"
#include "material.h"
#include "request.h"
#include "request_portfolio.h"
#include "resource_exchange.h"
#include "resource_helpers.h"
#include "test_context.h"
#include "test_agents/test_facility.h"
using cyclus::Bid;
using cyclus::BidPortfolio;
using cyclus::CommodMap;
using cyclus::Composition;
using cyclus::Context;
using cyclus::ExchangeContext;
using cyclus::Facility;
using cyclus::Material;
using cyclus::Agent;
using cyclus::PrefMap;
using cyclus::Request;
using cyclus::RequestPortfolio;
using cyclus::ResourceExchange;
using cyclus::TestContext;
using std::set;
using std::string;
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
class Requester: public TestFacility {
public:
Requester(Context* ctx, int i = 1)
: TestFacility(ctx),
i_(i),
req_ctr_(0),
pref_ctr_(0) {}
virtual cyclus::Agent* Clone() {
Requester* m = new Requester(context());
m->InitFrom(this);
m->i_ = i_;
m->port_ = port_;
return m;
}
set<RequestPortfolio<Material>::Ptr> GetMatlRequests() {
set<RequestPortfolio<Material>::Ptr> rps;
RequestPortfolio<Material>::Ptr rp(new RequestPortfolio<Material>());
rps.insert(port_);
req_ctr_++;
return rps;
}
// increments counter and squares all preferences
virtual void AdjustMatlPrefs(PrefMap<Material>::type& prefs) {
std::map<Request<Material>*,
std::map<Bid<Material>*, double> >::iterator p_it;
for (p_it = prefs.begin(); p_it != prefs.end(); ++p_it) {
std::map<Bid<Material>*, double>& map = p_it->second;
std::map<Bid<Material>*, double>::iterator m_it;
for (m_it = map.begin(); m_it != map.end(); ++m_it) {
m_it->second = std::pow(m_it->second, 2);
}
}
pref_ctr_++;
}
RequestPortfolio<Material>::Ptr port_;
int i_;
int pref_ctr_;
int req_ctr_;
};
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
class Bidder: public TestFacility {
public:
Bidder(Context* ctx, std::string commod)
: TestFacility(ctx),
commod_(commod),
bid_ctr_(0) {}
virtual cyclus::Agent* Clone() {
Bidder* m = new Bidder(context(), commod_);
m->InitFrom(this);
m->port_ = port_;
return m;
}
set<BidPortfolio<Material>::Ptr> GetMatlBids(
CommodMap<Material>::type& commod_requests) {
set<BidPortfolio<Material>::Ptr> bps;
bps.insert(port_);
bid_ctr_++;
return bps;
}
BidPortfolio<Material>::Ptr port_;
std::string commod_;
int bid_ctr_;
};
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
class ResourceExchangeTests: public ::testing::Test {
protected:
TestContext tc;
Requester* reqr;
Bidder* bidr;
ResourceExchange<Material>* exchng;
string commod;
double pref;
Material::Ptr mat;
Request<Material>* req;
Bid<Material>* bid;
virtual void SetUp() {
commod = "name";
pref = 2.4;
cyclus::CompMap cm;
cm[92235] = 1.0;
Composition::Ptr comp = Composition::CreateFromMass(cm);
double qty = 1.0;
mat = Material::CreateUntracked(qty, comp);
reqr = new Requester(tc.get());
exchng = new ResourceExchange<Material>(tc.get());
}
virtual void TearDown() {
delete exchng;
}
};
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TEST_F(ResourceExchangeTests, Requests) {
RequestPortfolio<Material>::Ptr rp(new RequestPortfolio<Material>());
req = rp->AddRequest(mat, reqr, commod, pref);
reqr->port_ = rp;
Facility* clone = dynamic_cast<Facility*>(reqr->Clone());
clone->Build(NULL);
Requester* rcast = dynamic_cast<Requester*>(clone);
EXPECT_EQ(0, rcast->req_ctr_);
exchng->AddAllRequests();
EXPECT_EQ(1, rcast->req_ctr_);
EXPECT_EQ(1, exchng->ex_ctx().requesters.size());
ExchangeContext<Material>& ctx = exchng->ex_ctx();
const std::vector<RequestPortfolio<Material>::Ptr>& obsvp = ctx.requests;
EXPECT_EQ(1, obsvp.size());
EXPECT_TRUE(RPEq(*rp.get(), *obsvp[0].get()));
const std::vector<Request<Material>*>& obsvr = ctx.commod_requests[commod];
EXPECT_EQ(1, obsvr.size());
std::vector<Request<Material>*> vr;
vr.push_back(req);
EXPECT_EQ(vr, obsvr);
clone->Decommission();
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TEST_F(ResourceExchangeTests, Bids) {
ExchangeContext<Material>& ctx = exchng->ex_ctx();
RequestPortfolio<Material>::Ptr rp(new RequestPortfolio<Material>());
req = rp->AddRequest(mat, reqr, commod, pref);
Request<Material>* req1 = rp->AddRequest(mat, reqr, commod, pref);
ctx.AddRequestPortfolio(rp);
const std::vector<Request<Material>*>& reqs = ctx.commod_requests[commod];
EXPECT_EQ(2, reqs.size());
Bidder* bidr = new Bidder(tc.get(), commod);
BidPortfolio<Material>::Ptr bp(new BidPortfolio<Material>());
bid = bp->AddBid(req, mat, bidr);
Bid<Material>* bid1 = bp->AddBid(req1, mat, bidr);
std::vector<Bid<Material>*> bids;
bids.push_back(bid);
bids.push_back(bid1);
bidr->port_ = bp;
Facility* clone = dynamic_cast<Facility*>(bidr->Clone());
clone->Build(NULL);
Bidder* bcast = dynamic_cast<Bidder*>(clone);
EXPECT_EQ(0, bcast->bid_ctr_);
exchng->AddAllBids();
EXPECT_EQ(1, bcast->bid_ctr_);
EXPECT_EQ(1, exchng->ex_ctx().bidders.size());
const std::vector<BidPortfolio<Material>::Ptr>& obsvp = ctx.bids;
EXPECT_EQ(1, obsvp.size());
EXPECT_TRUE(BPEq(*bp.get(), *obsvp[0].get()));
const cyclus::BidPortfolio<Material>& lhs = *bp;
const cyclus::BidPortfolio<Material>& rhs = *obsvp[0];
EXPECT_TRUE(BPEq(*bp, *obsvp[0]));
const std::vector<Bid<Material>*>& obsvb = ctx.bids_by_request[req];
EXPECT_EQ(1, obsvb.size());
std::vector<Bid<Material>*> vb;
vb.push_back(bid);
EXPECT_EQ(vb, obsvb);
const std::vector<Bid<Material>*>& obsvb1 = ctx.bids_by_request[req1];
EXPECT_EQ(1, obsvb1.size());
vb.clear();
vb.push_back(bid1);
EXPECT_EQ(vb, obsvb1);
clone->Decommission();
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TEST_F(ResourceExchangeTests, PrefCalls) {
Facility* parent = dynamic_cast<Facility*>(reqr->Clone());
Facility* child = dynamic_cast<Facility*>(reqr->Clone());
parent->Build(NULL);
child->Build(parent);
Requester* pcast = dynamic_cast<Requester*>(parent);
Requester* ccast = dynamic_cast<Requester*>(child);
ASSERT_TRUE(pcast != NULL);
ASSERT_TRUE(ccast != NULL);
ASSERT_TRUE(pcast->parent() == NULL);
ASSERT_TRUE(ccast->parent() == dynamic_cast<Agent*>(pcast));
ASSERT_TRUE(pcast->manager() == dynamic_cast<Agent*>(pcast));
ASSERT_TRUE(ccast->manager() == dynamic_cast<Agent*>(ccast));
// doin a little magic to simulate each requester making their own request
RequestPortfolio<Material>::Ptr rp1(new RequestPortfolio<Material>());
Request<Material>* preq = rp1->AddRequest(mat, pcast, commod, pref);
pcast->port_ = rp1;
RequestPortfolio<Material>::Ptr rp2(new RequestPortfolio<Material>());
Request<Material>* creq = rp2->AddRequest(mat, ccast, commod, pref);
ccast->port_ = rp2;
EXPECT_EQ(0, pcast->req_ctr_);
EXPECT_EQ(0, ccast->req_ctr_);
exchng->AddAllRequests();
EXPECT_EQ(2, exchng->ex_ctx().requesters.size());
EXPECT_EQ(1, pcast->req_ctr_);
EXPECT_EQ(1, ccast->req_ctr_);
EXPECT_EQ(0, pcast->pref_ctr_);
EXPECT_EQ(0, ccast->pref_ctr_);
EXPECT_NO_THROW(exchng->AdjustAll());
// child gets to adjust once - its own request
// parent gets called twice - its request and adjusting its child's request
EXPECT_EQ(2, pcast->pref_ctr_);
EXPECT_EQ(1, ccast->pref_ctr_);
child->Decommission();
parent->Decommission();
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TEST_F(ResourceExchangeTests, PrefValues) {
Facility* parent = dynamic_cast<Facility*>(reqr->Clone());
Facility* child = dynamic_cast<Facility*>(reqr->Clone());
parent->Build(NULL);
child->Build(parent);
Requester* pcast = dynamic_cast<Requester*>(parent);
Requester* ccast = dynamic_cast<Requester*>(child);
// doin a little magic to simulate each requester making their own request
RequestPortfolio<Material>::Ptr rp1(new RequestPortfolio<Material>());
Request<Material>* preq = rp1->AddRequest(mat, pcast, commod, pref);
pcast->port_ = rp1;
RequestPortfolio<Material>::Ptr rp2(new RequestPortfolio<Material>());
Request<Material>* creq = rp2->AddRequest(mat, ccast, commod, pref);
ccast->port_ = rp2;
Bidder* bidr = new Bidder(tc.get(), commod);
BidPortfolio<Material>::Ptr bp(new BidPortfolio<Material>());
Bid<Material>* pbid = bp->AddBid(preq, mat, bidr);
Bid<Material>* cbid = bp->AddBid(creq, mat, bidr);
std::vector<Bid<Material>*> bids;
bids.push_back(pbid);
bids.push_back(cbid);
bidr->port_ = bp;
Facility* bclone = dynamic_cast<Facility*>(bidr->Clone());
bclone->Build(NULL);
EXPECT_NO_THROW(exchng->AddAllRequests());
EXPECT_NO_THROW(exchng->AddAllBids());
PrefMap<Material>::type pobs;
pobs[preq].insert(std::make_pair(pbid, preq->preference()));
PrefMap<Material>::type cobs;
cobs[creq].insert(std::make_pair(cbid, creq->preference()));
ExchangeContext<Material>& context = exchng->ex_ctx();
EXPECT_EQ(context.trader_prefs[parent], pobs);
EXPECT_EQ(context.trader_prefs[child], cobs);
EXPECT_NO_THROW(exchng->AdjustAll());
pobs[preq].begin()->second = std::pow(preq->preference(), 2);
cobs[creq].begin()->second = std::pow(std::pow(creq->preference(), 2), 2);
EXPECT_EQ(context.trader_prefs[parent], pobs);
EXPECT_EQ(context.trader_prefs[child], cobs);
child->Decommission();
parent->Decommission();
}
| rwcarlsen/cyclus | tests/resource_exchange_tests.cc | C++ | bsd-3-clause | 9,917 |
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Loader
* @subpackage UnitTests
* @copyright Copyright (c) 2005-2014 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id$
*/
/**
* @category Zend
* @package Zend_Loader
* @subpackage UnitTests
* @copyright Copyright (c) 2005-2014 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Foo_Bar_Model_Baz
{
}
| sadeq89/smoothieme | tests/Zend/Loader/Autoloader/_files/models/Baz.php | PHP | bsd-3-clause | 998 |
<!DOCTYPE html>
<!-- DO NOT EDIT! This test has been generated by /html/canvas/tools/gentest.py. -->
<title>OffscreenCanvas test: 2d.composite.uncovered.fill.copy</title>
<script src="/resources/testharness.js"></script>
<script src="/resources/testharnessreport.js"></script>
<script src="/html/canvas/resources/canvas-tests.js"></script>
<h1>2d.composite.uncovered.fill.copy</h1>
<p class="desc">fill() draws pixels not covered by the source object as (0,0,0,0), and does not leave the pixels unchanged.</p>
<script>
var t = async_test("fill() draws pixels not covered by the source object as (0,0,0,0), and does not leave the pixels unchanged.");
var t_pass = t.done.bind(t);
var t_fail = t.step_func(function(reason) {
throw reason;
});
t.step(function() {
var offscreenCanvas = new OffscreenCanvas(100, 50);
var ctx = offscreenCanvas.getContext('2d');
ctx.fillStyle = 'rgba(0, 255, 0, 0.5)';
ctx.fillRect(0, 0, 100, 50);
ctx.globalCompositeOperation = 'copy';
ctx.fillStyle = 'rgba(0, 0, 255, 0.75)';
ctx.translate(0, 25);
ctx.fillRect(0, 50, 100, 50);
_assertPixelApprox(offscreenCanvas, 50,25, 0,0,0,0, "50,25", "0,0,0,0", 5);
t.done();
});
</script>
| scheib/chromium | third_party/blink/web_tests/external/wpt/html/canvas/offscreen/compositing/2d.composite.uncovered.fill.copy.html | HTML | bsd-3-clause | 1,169 |
// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef CHROME_BROWSER_CHROME_PAGE_ZOOM_H_
#define CHROME_BROWSER_CHROME_PAGE_ZOOM_H_
#pragma once
#include <vector>
namespace chrome_page_zoom {
// Return a sorted vector of zoom factors. The vector will consist of preset
// values along with a custom value (if the custom value is not already
// represented.)
std::vector<double> PresetZoomFactors(double custom_factor);
// Return a sorted vector of zoom levels. The vector will consist of preset
// values along with a custom value (if the custom value is not already
// represented.)
std::vector<double> PresetZoomLevels(double custom_level);
} // namespace chrome_page_zoom
#endif // CHROME_BROWSER_CHROME_PAGE_ZOOM_H_
| ropik/chromium | chrome/browser/chrome_page_zoom.h | C | bsd-3-clause | 852 |
# Copyright 2017 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import py_utils
from telemetry import story as story_module
from telemetry.page import page as page_module
from telemetry.page import shared_page_state
class LeakDetectionSharedState(shared_page_state.SharedDesktopPageState):
def ShouldReuseBrowserForAllStoryRuns(self):
return True
class LeakDetectionPage(page_module.Page):
def __init__(self, url, page_set, name=''):
super(LeakDetectionPage, self).__init__(
url=url, page_set=page_set, name=name,
shared_page_state_class=LeakDetectionSharedState)
def RunNavigateSteps(self, action_runner):
tabs = action_runner.tab.browser.tabs
new_tab = tabs.New()
new_tab.action_runner.Navigate('about:blank')
new_tab.action_runner.PrepareForLeakDetection()
new_tab.action_runner.MeasureMemory()
new_tab.action_runner.Navigate(self.url)
self._WaitForPageLoadToComplete(new_tab.action_runner)
new_tab.action_runner.Navigate('about:blank')
new_tab.action_runner.PrepareForLeakDetection()
new_tab.action_runner.MeasureMemory()
new_tab.Close()
def _WaitForPageLoadToComplete(self, action_runner):
py_utils.WaitFor(action_runner.tab.HasReachedQuiescence, timeout=30)
# Some websites have a script that loads resources continuously, in which cases
# HasReachedQuiescence would not be reached. This class waits for document ready
# state to be complete to avoid timeout for those pages.
class ResourceLoadingLeakDetectionPage(LeakDetectionPage):
def _WaitForPageLoadToComplete(self, action_runner):
action_runner.tab.WaitForDocumentReadyStateToBeComplete()
class LeakDetectionStorySet(story_module.StorySet):
def __init__(self):
super(LeakDetectionStorySet, self).__init__(
archive_data_file='data/leak_detection.json',
cloud_storage_bucket=story_module.PARTNER_BUCKET)
urls_list = [
# Alexa top websites
'https://www.google.com',
'https://www.youtube.com',
'https://www.facebook.com',
'https://www.baidu.com',
'https://www.wikipedia.org',
'https://world.taobao.com/',
'https://www.tmall.com/',
'http://www.amazon.com',
'http://www.twitter.com',
'https://www.instagram.com/',
'http://www.jd.com/',
'https://vk.com/',
'https://outlook.live.com',
'https://www.reddit.com/',
'https://weibo.com/',
'https://www.sina.com.cn/',
'https://www.360.cn/',
'https://yandex.ru/',
'https://www.blogger.com/',
'https://www.netflix.com/',
'https://www.pornhub.com/',
'https://www.linkedin.com/',
'https://www.yahoo.co.jp/',
'https://www.csdn.net/',
'https://www.alipay.com/',
'https://www.twitch.tv/',
# TODO(keishi): Memory dump fails flakily crbug.com/963273
#'https://www.ebay.com/',
# TODO(keishi): Memory dump fails flakily crbug.com/963273
#'https://www.microsoft.com/',
# TODO(keishi): Memory dump fails flakily crbug.com/963273
#'https://www.xvideos.com/',
'https://mail.ru/',
'https://www.bing.com/',
'http://www.wikia.com/',
'https://www.office.com/',
'https://www.imdb.com/',
'https://www.aliexpress.com/',
'https://www.msn.com/',
'https://news.google.com/',
'https://www.theguardian.com/',
'https://www.indiatimes.com/',
# TODO(keishi): Memory dump fails flakily crbug.com/963273
#'http://www.foxnews.com/',
'https://weather.com/',
'https://www.shutterstock.com/',
'https://docs.google.com/',
'https://wordpress.com/',
# TODO(yuzus): This test crashes.
# 'https://www.apple.com/',
'https://play.google.com/store',
'https://www.dropbox.com/',
'https://soundcloud.com/',
'https://vimeo.com/',
'https://www.slideshare.net/',
'https://www.mediafire.com/',
'https://www.etsy.com/',
'https://www.ikea.com/',
'https://www.bestbuy.com/',
'https://www.homedepot.com/',
# TODO(keishi): Memory dump fails flakily crbug.com/963273
#'https://www.target.com/',
'https://www.booking.com/',
'https://www.tripadvisor.com/',
'https://9gag.com/',
'https://www.expedia.com/',
'https://www.roblox.com/',
'https://www.gamespot.com/',
'https://www.blizzard.com',
# TODO(keishi): Memory dump fails flakily crbug.com/963273
#'https://ign.com/',
'https://www.yelp.com/',
# Times out waiting for HasReachedQuiescence - crbug.com/927427
# 'https://gizmodo.com/',
'https://www.gsmarena.com/',
'https://www.theverge.com/',
'https://www.nlm.nih.gov/',
'https://archive.org/',
'https://www.udemy.com/',
'https://answers.yahoo.com/',
# TODO(crbug.com/985552): Memory dump fails flakily.
# 'https://www.goodreads.com/',
'https://www.cricbuzz.com/',
'http://www.goal.com/',
'http://siteadvisor.com/',
'https://www.patreon.com/',
'https://www.jw.org/',
'http://europa.eu/',
'https://translate.google.com/',
'https://www.epicgames.com/',
'http://www.reverso.net/',
'https://play.na.leagueoflegends.com/',
'https://www.thesaurus.com/',
'https://www.weebly.com/',
'https://www.deviantart.com/',
'https://www.scribd.com/',
'https://www.hulu.com/',
'https://www.xfinity.com/',
# India Alexa top websites
'https://porn555.com/',
'https://www.onlinesbi.com/',
'https://www.flipkart.com/',
'https://www.hotstar.com/',
'https://www.incometaxindiaefiling.gov.in/',
'https://stackoverflow.com/',
# TODO(crbug.com/1005035) Memory dump fails flakily.
# 'https://www.irctc.co.in/nget/',
'https://www.hdfcbank.com/',
'https://www.whatsapp.com/',
'https://uidai.gov.in/',
'https://billdesk.com/',
'https://www.icicibank.com/',
# US Alexa top websites
'https://imgur.com/',
'https://www.craigslist.org/',
'https://www.chase.com/',
# TODO(892352): tumblr started timing out due to a catapult roll. See
# https://crbug.com/892352
# 'https://www.tumblr.com/',
'https://www.paypal.com/',
# TODO(yuzus): espn.com is flaky. https://crbug.com/959796
#'http://www.espn.com/',
'https://edition.cnn.com/',
'https://www.pinterest.com/',
# TODO(keishi): Memory dump fails flakily crbug.com/963273
#'https://www.nytimes.com/',
'https://github.com/',
'https://www.salesforce.com/',
# Japan Alexa top websites
'https://www.rakuten.co.jp/',
'http://www.nicovideo.jp/',
'https://fc2.com/',
'https://ameblo.jp/',
'http://kakaku.com/',
'https://www.goo.ne.jp/',
'https://www.pixiv.net/',
# websites which were found to be leaking in the past
'https://www.prezi.com',
# TODO(keishi): Memory dump fails flakily crbug.com/963273
#'http://www.time.com',
'http://www.cheapoair.com',
'http://www.onlinedown.net',
'http://www.dailypost.ng',
'http://www.aljazeera.net',
'http://www.googleapps.com',
'http://www.airbnb.ch',
'http://www.livedoor.jp',
'http://www.blu-ray.com',
# TODO(953195): Test times out.
# 'http://www.block.io',
'http://www.hockeybuzz.com',
'http://www.silverpop.com',
'http://www.ansa.it',
'http://www.gulfair.com',
'http://www.nusatrip.com',
'http://www.samsung-fun.ru',
'http://www.opentable.com',
'http://www.magnetmail.net',
'http://zzz.com.ua',
'http://a-rakumo.appspot.com',
'http://www.sakurafile.com',
'http://www.psiexams.com',
'http://www.contentful.com',
'http://www.estibot.com',
'http://www.mbs.de',
'http://www.zhengjie.com',
'http://www.sjp.pl',
'http://www.mastodon.social',
'http://www.horairetrain.net',
'http://www.torrentzeu.to',
'http://www.inbank.it',
'http://www.gradpoint.com',
'http://www.mail.bg',
'http://www.aaannunci.it',
'http://www.leandomainsearch.com',
'http://www.wpjam.com',
'http://www.nigma.ru',
'http://www.do-search.com',
'http://www.omniboxes.com',
'http://whu.edu.cn',
'http://support.wordpress.com',
'http://www.webwebweb.com',
'http://www.sick.com',
'http://www.iowacconline.com',
'http://hdu.edu.cn',
'http://www.register.com',
'http://www.careesma.in',
'http://www.bestdic.ir',
'http://www.privacyassistant.net',
'http://www.sklavenzentrale.com',
'http://www.podbay.fm',
'http://www.coco.fr',
'http://www.skipaas.com',
'http://www.chatword.org',
'http://www.ezcardinfo.com',
'http://www.daydao.com',
'http://www.expediapartnercentral.com',
'http://www.22find.com',
'http://www.e-shop.gr',
'http://www.indeed.com',
'http://www.highwaybus.com',
'http://www.pingpang.info',
'http://www.besgold.com',
'http://www.arabam.com',
'http://makfax.com.mk',
'http://game.co.za',
'http://www.savaari.com',
'http://www.railsguides.jp',
]
resource_loading_urls_list = [
'https://www.hotels.com/',
'https://www.livejournal.com/',
# TODO(keishi): Memory dump fails flakily crbug.com/963273
#'https://www.yahoo.com',
'http://www.quora.com',
'https://www.macys.com',
'http://infomoney.com.br',
'http://www.listindiario.com',
'https://www.engadget.com/',
'https://www.sohu.com/',
'http://www.qq.com',
'http://www.benzworld.org',
'http://www.520mojing.com',
]
for url in urls_list:
self.AddStory(LeakDetectionPage(url, self, url))
for url in resource_loading_urls_list:
self.AddStory(ResourceLoadingLeakDetectionPage(url, self, url))
| chromium/chromium | tools/perf/contrib/leak_detection/page_sets.py | Python | bsd-3-clause | 10,066 |
/*
* Copyright (c) 2016, Alliance for Open Media. All rights reserved
*
* This source code is subject to the terms of the BSD 2 Clause License and
* the Alliance for Open Media Patent License 1.0. If the BSD 2 Clause License
* was not distributed with this source code in the LICENSE file, you can
* obtain it at www.aomedia.org/license/software. If the Alliance for Open
* Media Patent License 1.0 was not distributed with this source code in the
* PATENTS file, you can obtain it at www.aomedia.org/license/patent.
*/
#ifndef AOM_AOM_DSP_X86_BLEND_SSE4_H_
#define AOM_AOM_DSP_X86_BLEND_SSE4_H_
#include "aom_dsp/blend.h"
#include "aom_dsp/x86/synonyms.h"
static const uint8_t g_blend_a64_mask_shuffle[32] = {
0, 2, 4, 6, 8, 10, 12, 14, 1, 3, 5, 7, 9, 11, 13, 15,
0, 2, 4, 6, 8, 10, 12, 14, 1, 3, 5, 7, 9, 11, 13, 15,
};
//////////////////////////////////////////////////////////////////////////////
// Common kernels
//////////////////////////////////////////////////////////////////////////////
static INLINE __m128i blend_4(const uint8_t *src0, const uint8_t *src1,
const __m128i *v_m0_w, const __m128i *v_m1_w) {
const __m128i v_s0_b = xx_loadl_32(src0);
const __m128i v_s1_b = xx_loadl_32(src1);
const __m128i v_s0_w = _mm_cvtepu8_epi16(v_s0_b);
const __m128i v_s1_w = _mm_cvtepu8_epi16(v_s1_b);
const __m128i v_p0_w = _mm_mullo_epi16(v_s0_w, *v_m0_w);
const __m128i v_p1_w = _mm_mullo_epi16(v_s1_w, *v_m1_w);
const __m128i v_sum_w = _mm_add_epi16(v_p0_w, v_p1_w);
const __m128i v_res_w = xx_roundn_epu16(v_sum_w, AOM_BLEND_A64_ROUND_BITS);
return v_res_w;
}
static INLINE __m128i blend_8(const uint8_t *src0, const uint8_t *src1,
const __m128i *v_m0_w, const __m128i *v_m1_w) {
const __m128i v_s0_b = xx_loadl_64(src0);
const __m128i v_s1_b = xx_loadl_64(src1);
const __m128i v_s0_w = _mm_cvtepu8_epi16(v_s0_b);
const __m128i v_s1_w = _mm_cvtepu8_epi16(v_s1_b);
const __m128i v_p0_w = _mm_mullo_epi16(v_s0_w, *v_m0_w);
const __m128i v_p1_w = _mm_mullo_epi16(v_s1_w, *v_m1_w);
const __m128i v_sum_w = _mm_add_epi16(v_p0_w, v_p1_w);
const __m128i v_res_w = xx_roundn_epu16(v_sum_w, AOM_BLEND_A64_ROUND_BITS);
return v_res_w;
}
static INLINE __m128i blend_4_u8(const uint8_t *src0, const uint8_t *src1,
const __m128i *v_m0_b, const __m128i *v_m1_b,
const __m128i *rounding) {
const __m128i v_s0_b = xx_loadl_32(src0);
const __m128i v_s1_b = xx_loadl_32(src1);
const __m128i v_p0_w = _mm_maddubs_epi16(_mm_unpacklo_epi8(v_s0_b, v_s1_b),
_mm_unpacklo_epi8(*v_m0_b, *v_m1_b));
const __m128i v_res_w = _mm_mulhrs_epi16(v_p0_w, *rounding);
const __m128i v_res = _mm_packus_epi16(v_res_w, v_res_w);
return v_res;
}
static INLINE __m128i blend_8_u8(const uint8_t *src0, const uint8_t *src1,
const __m128i *v_m0_b, const __m128i *v_m1_b,
const __m128i *rounding) {
const __m128i v_s0_b = xx_loadl_64(src0);
const __m128i v_s1_b = xx_loadl_64(src1);
const __m128i v_p0_w = _mm_maddubs_epi16(_mm_unpacklo_epi8(v_s0_b, v_s1_b),
_mm_unpacklo_epi8(*v_m0_b, *v_m1_b));
const __m128i v_res_w = _mm_mulhrs_epi16(v_p0_w, *rounding);
const __m128i v_res = _mm_packus_epi16(v_res_w, v_res_w);
return v_res;
}
static INLINE __m128i blend_16_u8(const uint8_t *src0, const uint8_t *src1,
const __m128i *v_m0_b, const __m128i *v_m1_b,
const __m128i *rounding) {
const __m128i v_s0_b = xx_loadu_128(src0);
const __m128i v_s1_b = xx_loadu_128(src1);
const __m128i v_p0_w = _mm_maddubs_epi16(_mm_unpacklo_epi8(v_s0_b, v_s1_b),
_mm_unpacklo_epi8(*v_m0_b, *v_m1_b));
const __m128i v_p1_w = _mm_maddubs_epi16(_mm_unpackhi_epi8(v_s0_b, v_s1_b),
_mm_unpackhi_epi8(*v_m0_b, *v_m1_b));
const __m128i v_res0_w = _mm_mulhrs_epi16(v_p0_w, *rounding);
const __m128i v_res1_w = _mm_mulhrs_epi16(v_p1_w, *rounding);
const __m128i v_res = _mm_packus_epi16(v_res0_w, v_res1_w);
return v_res;
}
typedef __m128i (*blend_unit_fn)(const uint16_t *src0, const uint16_t *src1,
const __m128i v_m0_w, const __m128i v_m1_w);
static INLINE __m128i blend_4_b10(const uint16_t *src0, const uint16_t *src1,
const __m128i v_m0_w, const __m128i v_m1_w) {
const __m128i v_s0_w = xx_loadl_64(src0);
const __m128i v_s1_w = xx_loadl_64(src1);
const __m128i v_p0_w = _mm_mullo_epi16(v_s0_w, v_m0_w);
const __m128i v_p1_w = _mm_mullo_epi16(v_s1_w, v_m1_w);
const __m128i v_sum_w = _mm_add_epi16(v_p0_w, v_p1_w);
const __m128i v_res_w = xx_roundn_epu16(v_sum_w, AOM_BLEND_A64_ROUND_BITS);
return v_res_w;
}
static INLINE __m128i blend_8_b10(const uint16_t *src0, const uint16_t *src1,
const __m128i v_m0_w, const __m128i v_m1_w) {
const __m128i v_s0_w = xx_loadu_128(src0);
const __m128i v_s1_w = xx_loadu_128(src1);
const __m128i v_p0_w = _mm_mullo_epi16(v_s0_w, v_m0_w);
const __m128i v_p1_w = _mm_mullo_epi16(v_s1_w, v_m1_w);
const __m128i v_sum_w = _mm_add_epi16(v_p0_w, v_p1_w);
const __m128i v_res_w = xx_roundn_epu16(v_sum_w, AOM_BLEND_A64_ROUND_BITS);
return v_res_w;
}
static INLINE __m128i blend_4_b12(const uint16_t *src0, const uint16_t *src1,
const __m128i v_m0_w, const __m128i v_m1_w) {
const __m128i v_s0_w = xx_loadl_64(src0);
const __m128i v_s1_w = xx_loadl_64(src1);
// Interleave
const __m128i v_m01_w = _mm_unpacklo_epi16(v_m0_w, v_m1_w);
const __m128i v_s01_w = _mm_unpacklo_epi16(v_s0_w, v_s1_w);
// Multiply-Add
const __m128i v_sum_d = _mm_madd_epi16(v_s01_w, v_m01_w);
// Scale
const __m128i v_ssum_d =
_mm_srli_epi32(v_sum_d, AOM_BLEND_A64_ROUND_BITS - 1);
// Pack
const __m128i v_pssum_d = _mm_packs_epi32(v_ssum_d, v_ssum_d);
// Round
const __m128i v_res_w = xx_round_epu16(v_pssum_d);
return v_res_w;
}
static INLINE __m128i blend_8_b12(const uint16_t *src0, const uint16_t *src1,
const __m128i v_m0_w, const __m128i v_m1_w) {
const __m128i v_s0_w = xx_loadu_128(src0);
const __m128i v_s1_w = xx_loadu_128(src1);
// Interleave
const __m128i v_m01l_w = _mm_unpacklo_epi16(v_m0_w, v_m1_w);
const __m128i v_m01h_w = _mm_unpackhi_epi16(v_m0_w, v_m1_w);
const __m128i v_s01l_w = _mm_unpacklo_epi16(v_s0_w, v_s1_w);
const __m128i v_s01h_w = _mm_unpackhi_epi16(v_s0_w, v_s1_w);
// Multiply-Add
const __m128i v_suml_d = _mm_madd_epi16(v_s01l_w, v_m01l_w);
const __m128i v_sumh_d = _mm_madd_epi16(v_s01h_w, v_m01h_w);
// Scale
const __m128i v_ssuml_d =
_mm_srli_epi32(v_suml_d, AOM_BLEND_A64_ROUND_BITS - 1);
const __m128i v_ssumh_d =
_mm_srli_epi32(v_sumh_d, AOM_BLEND_A64_ROUND_BITS - 1);
// Pack
const __m128i v_pssum_d = _mm_packs_epi32(v_ssuml_d, v_ssumh_d);
// Round
const __m128i v_res_w = xx_round_epu16(v_pssum_d);
return v_res_w;
}
#endif // AOM_AOM_DSP_X86_BLEND_SSE4_H_
| endlessm/chromium-browser | third_party/libaom/source/libaom/aom_dsp/x86/blend_sse4.h | C | bsd-3-clause | 7,290 |
// libjingle
// Copyright 2004 Google Inc.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
// 3. The name of the author may not be used to endorse or promote products
// derived from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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.
//
// Implementation of VideoRecorder and FileVideoCapturer.
#include "talk/media/devices/filevideocapturer.h"
#include "talk/base/bytebuffer.h"
#include "talk/base/logging.h"
#include "talk/base/thread.h"
namespace cricket {
/////////////////////////////////////////////////////////////////////
// Implementation of class VideoRecorder
/////////////////////////////////////////////////////////////////////
bool VideoRecorder::Start(const std::string& filename, bool write_header) {
Stop();
write_header_ = write_header;
int err;
if (!video_file_.Open(filename, "wb", &err)) {
LOG(LS_ERROR) << "Unable to open file " << filename << " err=" << err;
return false;
}
return true;
}
void VideoRecorder::Stop() {
video_file_.Close();
}
bool VideoRecorder::RecordFrame(const CapturedFrame& frame) {
if (talk_base::SS_CLOSED == video_file_.GetState()) {
LOG(LS_ERROR) << "File not opened yet";
return false;
}
uint32 size = 0;
if (!frame.GetDataSize(&size)) {
LOG(LS_ERROR) << "Unable to calculate the data size of the frame";
return false;
}
if (write_header_) {
// Convert the frame header to bytebuffer.
talk_base::ByteBuffer buffer;
buffer.WriteUInt32(frame.width);
buffer.WriteUInt32(frame.height);
buffer.WriteUInt32(frame.fourcc);
buffer.WriteUInt32(frame.pixel_width);
buffer.WriteUInt32(frame.pixel_height);
buffer.WriteUInt64(frame.elapsed_time);
buffer.WriteUInt64(frame.time_stamp);
buffer.WriteUInt32(size);
// Write the bytebuffer to file.
if (talk_base::SR_SUCCESS != video_file_.Write(buffer.Data(),
buffer.Length(),
NULL,
NULL)) {
LOG(LS_ERROR) << "Failed to write frame header";
return false;
}
}
// Write the frame data to file.
if (talk_base::SR_SUCCESS != video_file_.Write(frame.data,
size,
NULL,
NULL)) {
LOG(LS_ERROR) << "Failed to write frame data";
return false;
}
return true;
}
///////////////////////////////////////////////////////////////////////
// Definition of private class FileReadThread that periodically reads
// frames from a file.
///////////////////////////////////////////////////////////////////////
class FileVideoCapturer::FileReadThread
: public talk_base::Thread, public talk_base::MessageHandler {
public:
explicit FileReadThread(FileVideoCapturer* capturer)
: capturer_(capturer),
finished_(false) {
}
// Override virtual method of parent Thread. Context: Worker Thread.
virtual void Run() {
// Read the first frame and start the message pump. The pump runs until
// Stop() is called externally or Quit() is called by OnMessage().
int waiting_time_ms = 0;
if (capturer_ && capturer_->ReadFrame(true, &waiting_time_ms)) {
PostDelayed(waiting_time_ms, this);
Thread::Run();
}
finished_ = true;
}
// Override virtual method of parent MessageHandler. Context: Worker Thread.
virtual void OnMessage(talk_base::Message* /*pmsg*/) {
int waiting_time_ms = 0;
if (capturer_ && capturer_->ReadFrame(false, &waiting_time_ms)) {
PostDelayed(waiting_time_ms, this);
} else {
Quit();
}
}
// Check if Run() is finished.
bool Finished() const { return finished_; }
private:
FileVideoCapturer* capturer_;
bool finished_;
DISALLOW_COPY_AND_ASSIGN(FileReadThread);
};
/////////////////////////////////////////////////////////////////////
// Implementation of class FileVideoCapturer
/////////////////////////////////////////////////////////////////////
static const int64 kNumNanoSecsPerMilliSec = 1000000;
const char* FileVideoCapturer::kVideoFileDevicePrefix = "video-file:";
FileVideoCapturer::FileVideoCapturer()
: frame_buffer_size_(0),
file_read_thread_(NULL),
repeat_(0),
start_time_ns_(0),
last_frame_timestamp_ns_(0),
ignore_framerate_(false) {
}
FileVideoCapturer::~FileVideoCapturer() {
Stop();
delete[] static_cast<char*>(captured_frame_.data);
}
bool FileVideoCapturer::Init(const Device& device) {
if (!FileVideoCapturer::IsFileVideoCapturerDevice(device)) {
return false;
}
std::string filename(device.name);
if (IsRunning()) {
LOG(LS_ERROR) << "The file video capturer is already running";
return false;
}
// Open the file.
int err;
if (!video_file_.Open(filename, "rb", &err)) {
LOG(LS_ERROR) << "Unable to open the file " << filename << " err=" << err;
return false;
}
// Read the first frame's header to determine the supported format.
CapturedFrame frame;
if (talk_base::SR_SUCCESS != ReadFrameHeader(&frame)) {
LOG(LS_ERROR) << "Failed to read the first frame header";
video_file_.Close();
return false;
}
// Seek back to the start of the file.
if (!video_file_.SetPosition(0)) {
LOG(LS_ERROR) << "Failed to seek back to beginning of the file";
video_file_.Close();
return false;
}
// Enumerate the supported formats. We have only one supported format. We set
// the frame interval to kMinimumInterval here. In Start(), if the capture
// format's interval is greater than kMinimumInterval, we use the interval;
// otherwise, we use the timestamp in the file to control the interval.
VideoFormat format(frame.width, frame.height, VideoFormat::kMinimumInterval,
frame.fourcc);
std::vector<VideoFormat> supported;
supported.push_back(format);
SetId(device.id);
SetSupportedFormats(supported);
return true;
}
bool FileVideoCapturer::Init(const std::string& filename) {
return Init(FileVideoCapturer::CreateFileVideoCapturerDevice(filename));
}
CaptureState FileVideoCapturer::Start(const VideoFormat& capture_format) {
if (IsRunning()) {
LOG(LS_ERROR) << "The file video capturer is already running";
return CS_FAILED;
}
if (talk_base::SS_CLOSED == video_file_.GetState()) {
LOG(LS_ERROR) << "File not opened yet";
return CS_NO_DEVICE;
} else if (!video_file_.SetPosition(0)) {
LOG(LS_ERROR) << "Failed to seek back to beginning of the file";
return CS_FAILED;
}
SetCaptureFormat(&capture_format);
// Create a thread to read the file.
file_read_thread_ = new FileReadThread(this);
bool ret = file_read_thread_->Start();
start_time_ns_ = kNumNanoSecsPerMilliSec *
static_cast<int64>(talk_base::Time());
if (ret) {
LOG(LS_INFO) << "File video capturer '" << GetId() << "' started";
return CS_RUNNING;
} else {
LOG(LS_ERROR) << "File video capturer '" << GetId() << "' failed to start";
return CS_FAILED;
}
}
bool FileVideoCapturer::IsRunning() {
return file_read_thread_ && !file_read_thread_->Finished();
}
void FileVideoCapturer::Stop() {
if (file_read_thread_) {
file_read_thread_->Stop();
file_read_thread_ = NULL;
LOG(LS_INFO) << "File video capturer '" << GetId() << "' stopped";
}
SetCaptureFormat(NULL);
}
bool FileVideoCapturer::GetPreferredFourccs(std::vector<uint32>* fourccs) {
if (!fourccs) {
return false;
}
fourccs->push_back(GetSupportedFormats()->at(0).fourcc);
return true;
}
talk_base::StreamResult FileVideoCapturer::ReadFrameHeader(
CapturedFrame* frame) {
// We first read kFrameHeaderSize bytes from the file stream to a memory
// buffer, then construct a bytebuffer from the memory buffer, and finally
// read the frame header from the bytebuffer.
char header[CapturedFrame::kFrameHeaderSize];
talk_base::StreamResult sr;
size_t bytes_read;
int error;
sr = video_file_.Read(header,
CapturedFrame::kFrameHeaderSize,
&bytes_read,
&error);
LOG(LS_VERBOSE) << "Read frame header: stream_result = " << sr
<< ", bytes read = " << bytes_read << ", error = " << error;
if (talk_base::SR_SUCCESS == sr) {
if (CapturedFrame::kFrameHeaderSize != bytes_read) {
return talk_base::SR_EOS;
}
talk_base::ByteBuffer buffer(header, CapturedFrame::kFrameHeaderSize);
buffer.ReadUInt32(reinterpret_cast<uint32*>(&frame->width));
buffer.ReadUInt32(reinterpret_cast<uint32*>(&frame->height));
buffer.ReadUInt32(&frame->fourcc);
buffer.ReadUInt32(&frame->pixel_width);
buffer.ReadUInt32(&frame->pixel_height);
buffer.ReadUInt64(reinterpret_cast<uint64*>(&frame->elapsed_time));
buffer.ReadUInt64(reinterpret_cast<uint64*>(&frame->time_stamp));
buffer.ReadUInt32(&frame->data_size);
}
return sr;
}
// Executed in the context of FileReadThread.
bool FileVideoCapturer::ReadFrame(bool first_frame, int* wait_time_ms) {
uint32 start_read_time_ms = talk_base::Time();
// 1. Signal the previously read frame to downstream.
if (!first_frame) {
captured_frame_.time_stamp = kNumNanoSecsPerMilliSec *
static_cast<int64>(start_read_time_ms);
captured_frame_.elapsed_time = captured_frame_.time_stamp - start_time_ns_;
SignalFrameCaptured(this, &captured_frame_);
}
// 2. Read the next frame.
if (talk_base::SS_CLOSED == video_file_.GetState()) {
LOG(LS_ERROR) << "File not opened yet";
return false;
}
// 2.1 Read the frame header.
talk_base::StreamResult result = ReadFrameHeader(&captured_frame_);
if (talk_base::SR_EOS == result) { // Loop back if repeat.
if (repeat_ != talk_base::kForever) {
if (repeat_ > 0) {
--repeat_;
} else {
return false;
}
}
if (video_file_.SetPosition(0)) {
result = ReadFrameHeader(&captured_frame_);
}
}
if (talk_base::SR_SUCCESS != result) {
LOG(LS_ERROR) << "Failed to read the frame header";
return false;
}
// 2.2 Reallocate memory for the frame data if necessary.
if (frame_buffer_size_ < captured_frame_.data_size) {
frame_buffer_size_ = captured_frame_.data_size;
delete[] static_cast<char*>(captured_frame_.data);
captured_frame_.data = new char[frame_buffer_size_];
}
// 2.3 Read the frame adata.
if (talk_base::SR_SUCCESS != video_file_.Read(captured_frame_.data,
captured_frame_.data_size,
NULL, NULL)) {
LOG(LS_ERROR) << "Failed to read frame data";
return false;
}
// 3. Decide how long to wait for the next frame.
*wait_time_ms = 0;
// If the capture format's interval is not kMinimumInterval, we use it to
// control the rate; otherwise, we use the timestamp in the file to control
// the rate.
if (!first_frame && !ignore_framerate_) {
int64 interval_ns =
GetCaptureFormat()->interval > VideoFormat::kMinimumInterval ?
GetCaptureFormat()->interval :
captured_frame_.time_stamp - last_frame_timestamp_ns_;
int interval_ms = static_cast<int>(interval_ns / kNumNanoSecsPerMilliSec);
interval_ms -= talk_base::Time() - start_read_time_ms;
if (interval_ms > 0) {
*wait_time_ms = interval_ms;
}
}
// Keep the original timestamp read from the file.
last_frame_timestamp_ns_ = captured_frame_.time_stamp;
return true;
}
} // namespace cricket
| wangscript/libjingle-1 | trunk/talk/media/devices/filevideocapturer.cc | C++ | bsd-3-clause | 12,792 |
package collectors
import (
"encoding/json"
"fmt"
"net/http"
"net/url"
"strings"
"bosun.org/metadata"
"bosun.org/opentsdb"
)
var (
rmqQueueStatusMap = map[string]int{
"running": 0,
"syncing": 1,
"flow": 2,
"idle": 3,
"down": 4,
}
)
const (
defaultRabbitmqURL string = "http://guest:guest@localhost:15672"
rmqPrefix = "rabbitmq."
)
func init() {
collectors = append(collectors, &IntervalCollector{F: c_rabbitmq_overview, Enable: enableRabbitmq})
collectors = append(collectors, &IntervalCollector{F: c_rabbitmq_queues, Enable: enableRabbitmq})
collectors = append(collectors, &IntervalCollector{F: c_rabbitmq_nodes, Enable: enableRabbitmq})
}
// RabbitMQ registers a RabbitMQ collector.
func RabbitMQ(url string) error {
safeURL, err := urlUserHost(url)
if err != nil {
return err
}
collectors = append(collectors,
&IntervalCollector{
F: func() (opentsdb.MultiDataPoint, error) {
return rabbitmqOverview(url)
},
name: fmt.Sprintf("rabbitmq-overview-%s", safeURL),
},
&IntervalCollector{
F: func() (opentsdb.MultiDataPoint, error) {
return rabbitmqNodes(url)
},
name: fmt.Sprintf("rabbitmq-nodes-%s", safeURL),
},
&IntervalCollector{
F: func() (opentsdb.MultiDataPoint, error) {
return rabbitmqQueues(url)
},
name: fmt.Sprintf("rabbitmq-queues-%s", safeURL),
})
return nil
}
func enableRabbitmq() bool {
return enableURL(defaultRabbitmqURL)()
}
func c_rabbitmq_overview() (opentsdb.MultiDataPoint, error) {
return rabbitmqOverview(defaultRabbitmqURL)
}
func c_rabbitmq_nodes() (opentsdb.MultiDataPoint, error) {
return rabbitmqNodes(defaultRabbitmqURL)
}
func c_rabbitmq_queues() (opentsdb.MultiDataPoint, error) {
return rabbitmqQueues(defaultRabbitmqURL)
}
func rabbitmqOverview(s string) (opentsdb.MultiDataPoint, error) {
p := rmqPrefix + "overview."
res, err := http.Get(s + "/api/overview")
if err != nil {
return nil, err
}
defer res.Body.Close()
var o rmqOverview
if err := json.NewDecoder(res.Body).Decode(&o); err != nil {
return nil, err
}
var md opentsdb.MultiDataPoint
splitNode := strings.Split(o.Node, "@")
if len(splitNode) < 2 {
return nil, fmt.Errorf("Error: invalid RabbitMQ node name, can not split '%s'", o.Node)
}
host := splitNode[1]
ts := opentsdb.TagSet{"host": host}
Add(&md, p+"channels", o.ObjectTotals.Channels, ts, metadata.Gauge, metadata.Channel, DescRmqObjecttotalsChannels)
Add(&md, p+"connections", o.ObjectTotals.Connections, ts, metadata.Gauge, metadata.Connection, DescRmqObjectTotalsConnections)
Add(&md, p+"consumers", o.ObjectTotals.Consumers, ts, metadata.Gauge, metadata.Consumer, DescRmqObjectTotalsConsumers)
Add(&md, p+"exchanges", o.ObjectTotals.Exchanges, ts, metadata.Gauge, metadata.Exchange, DescRmqObjectTotalsExchanges)
Add(&md, p+"queues", o.ObjectTotals.Queues, ts, metadata.Gauge, metadata.Queue, DescRmqObjectTotalsQueues)
msgStats := rabbitmqMessageStats(p, ts, o.MessageStats)
md = append(md, msgStats...)
return md, nil
}
func rabbitmqQueues(s string) (opentsdb.MultiDataPoint, error) {
p := rmqPrefix + "queue."
res, err := http.Get(s + "/api/queues")
if err != nil {
return nil, err
}
defer res.Body.Close()
var qs []rmqQueue
if err := json.NewDecoder(res.Body).Decode(&qs); err != nil {
return nil, err
}
var md opentsdb.MultiDataPoint
for _, q := range qs {
if strings.HasPrefix(q.Name, "amq.gen-") {
continue // skip auto-generated queues
}
splitNode := strings.Split(q.Node, "@")
if len(splitNode) < 2 {
return nil, fmt.Errorf("Error: invalid RabbitMQ node name, can not split '%s'", q.Node)
}
host := splitNode[1]
ts := opentsdb.TagSet{"host": host, "queue": q.Name, "vhost": q.Vhost}
Add(&md, p+"consumers", q.Consumers, ts, metadata.Gauge, metadata.Consumer, DescRmqConsumers)
Add(&md, p+"memory", q.Memory, ts, metadata.Gauge, metadata.Bytes, DescRmqMemory)
Add(&md, p+"message_bytes_total", q.MessageBytes, ts, metadata.Gauge, metadata.Bytes, DescRmqMessageBytes)
Add(&md, p+"message_bytes_persistent", q.MessageBytesPersistent, ts, metadata.Gauge, metadata.Bytes, DescRmqMessageBytesPersistent)
Add(&md, p+"message_bytes_transient", q.MessageBytesRAM, ts, metadata.Gauge, metadata.Bytes, DescRmqMessageBytesRAM)
Add(&md, p+"message_bytes_ready", q.MessageBytesReady, ts, metadata.Gauge, metadata.Bytes, DescRmqMessageBytesReady)
Add(&md, p+"message_bytes_unack", q.MessageBytesUnacknowledged, ts, metadata.Gauge, metadata.Bytes, DescRmqMessageBytesUnacknowledged)
Add(&md, p+"messages_queue_depth", q.Messages, ts, metadata.Gauge, metadata.Message, DescRmqMessages)
Add(&md, p+"messages_persistent", q.MessagesPersistent, ts, metadata.Gauge, metadata.Message, DescRmqMessagesPersistent)
Add(&md, p+"messages_transient", q.MessagesRAM, ts, metadata.Gauge, metadata.Message, DescRmqMessagesRAM)
Add(&md, p+"messages_ready_total", q.MessagesReady, ts, metadata.Gauge, metadata.Message, DescRmqMessagesReady)
Add(&md, p+"messages_ready_transient", q.MessagesReadyRAM, ts, metadata.Gauge, metadata.Message, DescRmqMessagesReadyRAM)
Add(&md, p+"messages_unack_total", q.MessagesUnacknowledged, ts, metadata.Gauge, metadata.Message, DescRmqMessagesUnacknowledged)
Add(&md, p+"messages_unack_transient", q.MessagesUnacknowledgedRAM, ts, metadata.Gauge, metadata.Message, DescRmqMessagesUnacknowledgedRAM)
if sn, ok := q.SlaveNodes.([]interface{}); ok {
Add(&md, p+"slave_nodes", len(sn), ts, metadata.Gauge, metadata.Node, DescRmqSlaveNodes)
}
if dsn, ok := q.DownSlaveNodes.([]interface{}); ok {
Add(&md, p+"down_slave_nodes", len(dsn), ts, metadata.Gauge, metadata.Node, DescRmqDownSlaveNodes)
}
if ssn, ok := q.SynchronisedSlaveNodes.([]interface{}); ok {
Add(&md, p+"sync_slave_nodes", len(ssn), ts, metadata.Gauge, metadata.Node, DescRmqSynchronisedSlaveNodes)
}
if cu, ok := q.ConsumerUtilisation.(float64); ok {
Add(&md, p+"consumer_utilisation", cu, ts, metadata.Gauge, metadata.Fraction, DescRmqConsumerUtilisation)
}
msgStats := rabbitmqMessageStats(p, ts, q.MessageStats)
md = append(md, msgStats...)
backingQueueStatus := rabbitmqBackingQueueStatus(p+"backing_queue.", ts, q.BackingQueueStatus)
md = append(md, backingQueueStatus...)
if state, ok := rmqQueueStatusMap[q.State]; ok {
Add(&md, p+"state", state, ts, metadata.Gauge, metadata.StatusCode, DescRmqState)
} else {
Add(&md, p+"state", -1, ts, metadata.Gauge, metadata.StatusCode, DescRmqState)
}
}
return md, nil
}
func rabbitmqNodes(s string) (opentsdb.MultiDataPoint, error) {
p := rmqPrefix + "node."
res, err := http.Get(s + "/api/nodes")
if err != nil {
return nil, err
}
defer res.Body.Close()
var ns []rmqNode
if err := json.NewDecoder(res.Body).Decode(&ns); err != nil {
return nil, err
}
var md opentsdb.MultiDataPoint
for _, n := range ns {
splitName := strings.Split(n.Name, "@")
if len(splitName) < 2 {
return nil, fmt.Errorf("Error: invalid RabbitMQ node name, can not split '%s'", n.Name)
}
host := splitName[1]
ts := opentsdb.TagSet{"host": host}
Add(&md, p+"disk_free", n.DiskFree, ts, metadata.Gauge, metadata.Consumer, DescRmqDiskFree)
Add(&md, p+"disk_free_alarm", n.DiskFreeAlarm, ts, metadata.Gauge, metadata.Bool, DescRmqDiskFreeAlarm)
Add(&md, p+"disk_free_limit", n.DiskFreeLimit, ts, metadata.Gauge, metadata.Consumer, DescRmqDiskFreeLimit)
Add(&md, p+"fd_total", n.FDTotal, ts, metadata.Gauge, metadata.Files, DescRmqFDTotal)
Add(&md, p+"fd_used", n.FDUsed, ts, metadata.Gauge, metadata.Files, DescRmqFDUsed)
Add(&md, p+"mem_used", n.MemUsed, ts, metadata.Gauge, metadata.Bytes, DescRmqMemUsed)
Add(&md, p+"mem_alarm", n.MemAlarm, ts, metadata.Gauge, metadata.Bool, DescRmqMemAlarm)
Add(&md, p+"mem_limit", n.MemLimit, ts, metadata.Gauge, metadata.Bytes, DescRmqMemLimit)
Add(&md, p+"proc_used", n.ProcUsed, ts, metadata.Gauge, metadata.Process, DescRmqProcUsed)
Add(&md, p+"proc_total", n.ProcTotal, ts, metadata.Gauge, metadata.Process, DescRmqProcTotal)
Add(&md, p+"sockets_used", n.SocketsUsed, ts, metadata.Gauge, metadata.Socket, DescRmqSocketsUsed)
Add(&md, p+"sockets_total", n.SocketsTotal, ts, metadata.Gauge, metadata.Socket, DescRmqSocketsTotal)
Add(&md, p+"uptime", n.Uptime, ts, metadata.Gauge, metadata.Second, DescRmqUptime)
Add(&md, p+"running", n.Running, ts, metadata.Gauge, metadata.StatusCode, DescRmqRunning)
if partitions, ok := n.Partitions.([]interface{}); ok {
Add(&md, p+"partitions", len(partitions), ts, metadata.Gauge, metadata.Node, DescRmqPartitions)
}
}
return md, nil
}
func rabbitmqMessageStats(p string, ts opentsdb.TagSet, ms rmqMessageStats) opentsdb.MultiDataPoint {
var md opentsdb.MultiDataPoint
Add(&md, p+"message_stats", ms.Ack, ts.Copy().Merge(opentsdb.TagSet{"method": "ack"}),
metadata.Counter, metadata.Message, DescRmqMessageStatsAck)
Add(&md, p+"message_stats", ms.Confirm, ts.Copy().Merge(opentsdb.TagSet{"method": "confirm"}),
metadata.Counter, metadata.Message, DescRmqMessageStatsConfirm)
Add(&md, p+"message_stats", ms.Deliver, ts.Copy().Merge(opentsdb.TagSet{"method": "deliver"}),
metadata.Counter, metadata.Message, DescRmqMessageStatsDeliver)
Add(&md, p+"message_stats", ms.DeliverGet, ts.Copy().Merge(opentsdb.TagSet{"method": "deliver_get"}),
metadata.Counter, metadata.Message, DescRmqMessageStatsDeliverGet)
Add(&md, p+"message_stats", ms.DeliverNoAck, ts.Copy().Merge(opentsdb.TagSet{"method": "deliver_noack"}),
metadata.Counter, metadata.Message, DescRmqMessageStatsDeliverNoAck)
Add(&md, p+"message_stats", ms.Get, ts.Copy().Merge(opentsdb.TagSet{"method": "get"}),
metadata.Counter, metadata.Message, DescRmqMessageStatsGet)
Add(&md, p+"message_stats", ms.GetNoAck, ts.Copy().Merge(opentsdb.TagSet{"method": "get_noack"}),
metadata.Counter, metadata.Message, DescRmqMessageStatsGetNoack)
Add(&md, p+"message_stats", ms.Publish, ts.Copy().Merge(opentsdb.TagSet{"method": "publish"}),
metadata.Counter, metadata.Message, DescRmqMessageStatsPublish)
Add(&md, p+"message_stats", ms.PublishIn, ts.Copy().Merge(opentsdb.TagSet{"method": "publish_in"}),
metadata.Counter, metadata.Message, DescRmqMessageStatsPublishIn)
Add(&md, p+"message_stats", ms.PublishOut, ts.Copy().Merge(opentsdb.TagSet{"method": "publish_out"}),
metadata.Counter, metadata.Message, DescRmqMessageStatsPublishOut)
Add(&md, p+"message_stats", ms.Redeliver, ts.Copy().Merge(opentsdb.TagSet{"method": "redeliver"}),
metadata.Counter, metadata.Message, DescRmqMessageStatsRedeliver)
Add(&md, p+"message_stats", ms.Return, ts.Copy().Merge(opentsdb.TagSet{"method": "return"}),
metadata.Counter, metadata.Message, DescRmqMessageStatsReturn)
return md
}
func rabbitmqBackingQueueStatus(p string, ts opentsdb.TagSet, bqs rmqBackingQueueStatus) opentsdb.MultiDataPoint {
var md opentsdb.MultiDataPoint
Add(&md, p+"avg_rate", bqs.AvgAckEgressRate, ts.Copy().Merge(opentsdb.TagSet{"method": "ack", "direction": "out"}),
metadata.Rate, metadata.Message, DescRmqBackingQueueStatusAvgAckEgressRate)
Add(&md, p+"avg_rate", bqs.AvgAckIngressRate, ts.Copy().Merge(opentsdb.TagSet{"method": "ack", "direction": "in"}),
metadata.Rate, metadata.Message, DescRmqBackingQueueStatusAvgAckIngressRate)
Add(&md, p+"avg_rate", bqs.AvgEgressRate, ts.Copy().Merge(opentsdb.TagSet{"method": "noack", "direction": "out"}),
metadata.Rate, metadata.Message, DescRmqBackingQueueStatusAvgEgressRate)
Add(&md, p+"avg_rate", bqs.AvgIngressRate, ts.Copy().Merge(opentsdb.TagSet{"method": "noack", "direction": "in"}),
metadata.Rate, metadata.Message, DescRmqBackingQueueStatusAvgIngressRate)
Add(&md, p+"len", bqs.Len, ts,
metadata.Gauge, metadata.Message, DescRmqBackingQueueStatusLen)
return md
}
func urlUserHost(s string) (string, error) {
u, err := url.Parse(s)
if err != nil {
return "", err
}
if u.User != nil {
res := fmt.Sprintf("%s@%s", u.User.Username(), u.Host)
return res, nil
}
res := fmt.Sprintf("%s", u.Host)
return res, nil
}
type rmqOverview struct {
ClusterName string `json:"cluster_name"`
MessageStats rmqMessageStats `json:"message_stats"`
QueueTotals struct {
Messages int `json:"messages"`
MessagesReady int `json:"messages_ready"`
MessagesUnacknowledged int `json:"messages_unacknowledged"`
} `json:"queue_totals"`
ObjectTotals struct {
Consumers int `json:"consumers"`
Queues int `json:"queues"`
Exchanges int `json:"exchanges"`
Connections int `json:"connections"`
Channels int `json:"channels"`
} `json:"object_totals"`
Node string `json:"node"`
}
type rmqNode struct {
DiskFree int64 `json:"disk_free"`
DiskFreeAlarm bool `json:"disk_free_alarm"`
DiskFreeLimit int `json:"disk_free_limit"`
FDTotal int `json:"fd_total"`
FDUsed int `json:"fd_used"`
MemAlarm bool `json:"mem_alarm"`
MemLimit int64 `json:"mem_limit"`
MemUsed int `json:"mem_used"`
Name string `json:"name"`
Partitions interface{} `json:"partitions"`
ProcTotal int `json:"proc_total"`
ProcUsed int `json:"proc_used"`
Processors int `json:"processors"`
RunQueue int `json:"run_queue"`
Running bool `json:"running"`
SocketsTotal int `json:"sockets_total"`
SocketsUsed int `json:"sockets_used"`
Uptime int `json:"uptime"`
}
type rmqQueue struct {
Messages int `json:"messages"`
MessagesReady int `json:"messages_ready"`
MessagesUnacknowledged int `json:"messages_unacknowledged"`
Consumers int `json:"consumers"`
ConsumerUtilisation interface{} `json:"consumer_utilisation"`
Memory int `json:"memory"`
SlaveNodes interface{} `json:"slave_nodes"`
SynchronisedSlaveNodes interface{} `json:"synchronised_slave_nodes"`
DownSlaveNodes interface{} `json:"down_slave_nodes"`
BackingQueueStatus rmqBackingQueueStatus `json:"backing_queue_status"`
State string `json:"state"`
MessagesRAM int `json:"messages_ram"`
MessagesReadyRAM int `json:"messages_ready_ram"`
MessagesUnacknowledgedRAM int `json:"messages_unacknowledged_ram"`
MessagesPersistent int `json:"messages_persistent"`
MessageBytes int `json:"message_bytes"`
MessageBytesReady int `json:"message_bytes_ready"`
MessageBytesUnacknowledged int `json:"message_bytes_unacknowledged"`
MessageBytesRAM int `json:"message_bytes_ram"`
MessageBytesPersistent int `json:"message_bytes_persistent"`
Name string `json:"name"`
Vhost string `json:"vhost"`
Durable bool `json:"durable"`
Node string `json:"node"`
MessageStats rmqMessageStats `json:"message_stats"`
}
type rmqMessageStats struct {
Ack int `json:"ack"`
Confirm int `json:"confirm"`
Deliver int `json:"deliver"`
DeliverGet int `json:"deliver_get"`
DeliverNoAck int `json:"deliver_no_ack"`
Get int `json:"get"`
GetAck int `json:"get_ack"`
GetNoAck int `json:"get_noack"`
Publish int `json:"publish"`
PublishIn int `json:"publish_in"`
PublishOut int `json:"publish_out"`
Redeliver int `json:"redeliver"`
Return int `json:"return"`
}
type rmqBackingQueueStatus struct {
Len int `json:"len"`
AvgIngressRate float64 `json:"avg_ingress_rate"`
AvgEgressRate float64 `json:"avg_egress_rate"`
AvgAckIngressRate float64 `json:"avg_ack_ingress_rate"`
AvgAckEgressRate float64 `json:"avg_ack_egress_rate"`
MirrorSeen int `json:"mirror_seen"`
MirrorSenders int `json:"mirror_senders"`
}
const (
DescRmqBackingQueueStatusAvgAckEgressRate = "Rate at which unacknowledged message records leave RAM, e.g. because acks arrive or unacked messages are paged out"
DescRmqBackingQueueStatusAvgAckIngressRate = "Rate at which unacknowledged message records enter RAM, e.g. because messages are delivered requiring acknowledgement"
DescRmqBackingQueueStatusAvgEgressRate = "Average egress (outbound) rate, not including messages that straight through to auto-acking consumers."
DescRmqBackingQueueStatusAvgIngressRate = "Average ingress (inbound) rate, not including messages that straight through to auto-acking consumers."
DescRmqBackingQueueStatusLen = "Total backing queue length."
DescRmqConsumers = "Number of consumers."
DescRmqConsumerUtilisation = "Fraction of the time (between 0.0 and 1.0) that the queue is able to immediately deliver messages to consumers. This can be less than 1.0 if consumers are limited by network congestion or prefetch count."
DescRmqDiskFreeAlarm = "Whether the disk alarm has gone off."
DescRmqDiskFree = "Disk free space in bytes."
DescRmqDiskFreeLimit = "Point at which the disk alarm will go off."
DescRmqDownSlaveNodes = "Count of down nodes having a copy of the queue."
DescRmqFDTotal = "File descriptors available."
DescRmqFDUsed = "Used file descriptors."
DescRmqIOReadAvgTime = "Average wall time (milliseconds) for each disk read operation in the last statistics interval."
DescRmqIOReadBytes = "Total number of bytes read from disk by the persister."
DescRmqIOReadCount = "Total number of read operations by the persister."
DescRmqIOReopenCount = "Total number of times the persister has needed to recycle file handles between queues. In an ideal world this number will be zero; if the number is large, performance might be improved by increasing the number of file handles available to RabbitMQ."
DescRmqIOSeekAvgTime = "Average wall time (milliseconds) for each seek operation in the last statistics interval."
DescRmqIOSeekCount = "Total number of seek operations by the persister."
DescRmqIOSyncAvgTime = "Average wall time (milliseconds) for each sync operation in the last statistics interval."
DescRmqIOSyncCount = "Total number of fsync() operations by the persister."
DescRmqIOWriteAvgTime = "Average wall time (milliseconds) for each write operation in the last statistics interval."
DescRmqIOWriteBytes = "Total number of bytes written to disk by the persister."
DescRmqIOWriteCount = "Total number of write operations by the persister."
DescRmqMemAlarm = ""
DescRmqMemLimit = "Point at which the memory alarm will go off."
DescRmqMemory = "Bytes of memory consumed by the Erlang process associated with the queue, including stack, heap and internal structures."
DescRmqMemUsed = "Memory used in bytes."
DescRmqMessageBytesPersistent = "Like messageBytes but counting only those messages which are persistent."
DescRmqMessageBytesRAM = "Like messageBytes but counting only those messages which are in RAM."
DescRmqMessageBytesReady = "Like messageBytes but counting only those messages ready to be delivered to clients."
DescRmqMessageBytes = "Sum of the size of all message bodies in the queue. This does not include the message properties (including headers) or any overhead."
DescRmqMessageBytesUnacknowledged = "Like messageBytes but counting only those messages delivered to clients but not yet acknowledged."
DescRmqMessagesPersistent = "Total number of persistent messages in the queue (will always be 0 for transient queues)."
DescRmqMessagesRAM = "Total number of messages which are resident in ram."
DescRmqMessagesReady = "Number of messages ready to be delivered to clients."
DescRmqMessagesReadyRAM = "Number of messages from messagesReady which are resident in ram."
DescRmqMessages = "Sum of ready and unacknowledged messages (queue depth)."
DescRmqMessageStatsAck = "Count of acknowledged messages."
DescRmqMessageStatsConfirm = "Count of messages confirmed."
DescRmqMessageStatsDeliver = "Count of messages delivered in acknowledgement mode to consumers."
DescRmqMessageStatsDeliverGet = "Sum of deliver, deliverNoack, get, getNoack."
DescRmqMessageStatsDeliverNoAck = "Count of messages delivered in no-acknowledgement mode to consumers."
DescRmqMessageStatsGet = "Count of messages delivered in acknowledgement mode in response to basic.get."
DescRmqMessageStatsGetNoack = "Count of messages delivered in no-acknowledgement mode in response to basic.get."
DescRmqMessageStatsPublish = "Count of messages published."
DescRmqMessageStatsPublishIn = "Count of messages published \"in\" to an exchange, i.e. not taking account of routing."
DescRmqMessageStatsPublishOut = "Count of messages published \"out\" of an exchange, i.e. taking account of routing."
DescRmqMessageStatsRedeliver = "Count of subset of messages in deliverGet which had the redelivered flag set."
DescRmqMessageStatsReturn = "Count of messages returned to publisher as unroutable."
DescRmqMessagesUnacknowledged = "Number of messages delivered to clients but not yet acknowledged."
DescRmqMessagesUnacknowledgedRAM = "Number of messages from messagesUnacknowledged which are resident in ram."
DescRmqMnesiaDiskTxCount = "Number of Mnesia transactions which have been performed that required writes to disk. (e.g. creating a durable queue). Only transactions which originated on this node are included."
DescRmqMnesiaRAMTxCount = "Number of Mnesia transactions which have been performed that did not require writes to disk. (e.g. creating a transient queue). Only transactions which originated on this node are included."
DescRmqMsgStoreReadCount = "Number of messages which have been read from the message store."
DescRmqMsgStoreWriteCount = "Number of messages which have been written to the message store."
DescRmqObjecttotalsChannels = "Overall number of channels."
DescRmqObjectTotalsConnections = "Overall number of connections."
DescRmqObjectTotalsConsumers = "Overall number of consumers."
DescRmqObjectTotalsExchanges = "Overall number of exchanges."
DescRmqObjectTotalsQueues = "Overall number of queues."
DescRmqPartitions = "Count of network partitions this node is seeing."
DescRmqProcessors = "Number of cores detected and usable by Erlang."
DescRmqProcTotal = "Maximum number of Erlang processes."
DescRmqProcUsed = "Number of Erlang processes in use."
DescRmqQueueIndexJournalWriteCount = "Number of records written to the queue index journal. Each record represents a message being published to a queue, being delivered from a queue, and being acknowledged in a queue."
DescRmqQueueIndexReadCount = "Number of records read from the queue index."
DescRmqQueueIndexWriteCount = "Number of records written to the queue index."
DescRmqQueueTotalsMessages = "Overall sum of ready and unacknowledged messages (queue depth)."
DescRmqQueueTotalsMessagesReady = "Overall number of messages ready to be delivered to clients."
DescRmqQueueTotalsMessagesUnacknowledged = "Overall number of messages delivered to clients but not yet acknowledged."
DescRmqRunning = "Boolean for whether this node is up. Obviously if this is false, most other stats will be missing."
DescRmqRunQueue = "Average number of Erlang processes waiting to run."
DescRmqSlaveNodes = "Count of nodes having a copy of the queue."
DescRmqSocketsTotal = "File descriptors available for use as sockets."
DescRmqSocketsUsed = "File descriptors used as sockets."
DescRmqState = "The state of the queue. Unknown=> -1, Running=> 0, Syncing=> 1, Flow=> 2, Down=> 3"
DescRmqSynchronisedSlaveNodes = "Count of nodes having synchronised copy of the queue."
DescRmqSyncMessages = "Count of already synchronised messages on a slave node."
DescRmqUptime = "Node uptime in seconds."
)
| augporto/bosun | cmd/scollector/collectors/rabbitmq.go | GO | mit | 25,540 |
require "spec_helper"
describe ProjectWiki, models: true do
let(:project) { create(:empty_project) }
let(:repository) { project.repository }
let(:user) { project.owner }
let(:gitlab_shell) { Gitlab::Shell.new }
let(:project_wiki) { ProjectWiki.new(project, user) }
subject { project_wiki }
before { project_wiki.wiki }
describe "#path_with_namespace" do
it "returns the project path with namespace with the .wiki extension" do
expect(subject.path_with_namespace).to eq(project.path_with_namespace + ".wiki")
end
end
describe '#web_url' do
it 'returns the full web URL to the wiki' do
expect(subject.web_url).to eq("#{Gitlab.config.gitlab.url}/#{project.path_with_namespace}/wikis/home")
end
end
describe "#url_to_repo" do
it "returns the correct ssh url to the repo" do
expect(subject.url_to_repo).to eq(gitlab_shell.url_to_repo(subject.path_with_namespace))
end
end
describe "#ssh_url_to_repo" do
it "equals #url_to_repo" do
expect(subject.ssh_url_to_repo).to eq(subject.url_to_repo)
end
end
describe "#http_url_to_repo" do
it "provides the full http url to the repo" do
gitlab_url = Gitlab.config.gitlab.url
repo_http_url = "#{gitlab_url}/#{subject.path_with_namespace}.git"
expect(subject.http_url_to_repo).to eq(repo_http_url)
end
end
describe "#wiki_base_path" do
it "returns the wiki base path" do
wiki_base_path = "#{Gitlab.config.gitlab.relative_url_root}/#{project.path_with_namespace}/wikis"
expect(subject.wiki_base_path).to eq(wiki_base_path)
end
end
describe "#wiki" do
it "contains a Gollum::Wiki instance" do
expect(subject.wiki).to be_a Gollum::Wiki
end
it "creates a new wiki repo if one does not yet exist" do
expect(project_wiki.create_page("index", "test content")).to be_truthy
end
it "raises CouldNotCreateWikiError if it can't create the wiki repository" do
allow(project_wiki).to receive(:init_repo).and_return(false)
expect { project_wiki.send(:create_repo!) }.to raise_exception(ProjectWiki::CouldNotCreateWikiError)
end
end
describe "#empty?" do
context "when the wiki repository is empty" do
before do
allow_any_instance_of(Gitlab::Shell).to receive(:add_repository) do
create_temp_repo("#{Rails.root}/tmp/test-git-base-path/non-existant.wiki.git")
end
allow(project).to receive(:path_with_namespace).and_return("non-existant")
end
describe '#empty?' do
subject { super().empty? }
it { is_expected.to be_truthy }
end
end
context "when the wiki has pages" do
before do
project_wiki.create_page("index", "This is an awesome new Gollum Wiki")
end
describe '#empty?' do
subject { super().empty? }
it { is_expected.to be_falsey }
end
end
end
describe "#pages" do
before do
create_page("index", "This is an awesome new Gollum Wiki")
@pages = subject.pages
end
after do
destroy_page(@pages.first.page)
end
it "returns an array of WikiPage instances" do
expect(@pages.first).to be_a WikiPage
end
it "returns the correct number of pages" do
expect(@pages.count).to eq(1)
end
end
describe "#find_page" do
before do
create_page("index page", "This is an awesome Gollum Wiki")
end
after do
destroy_page(subject.pages.first.page)
end
it "returns the latest version of the page if it exists" do
page = subject.find_page("index page")
expect(page.title).to eq("index page")
end
it "returns nil if the page does not exist" do
expect(subject.find_page("non-existant")).to eq(nil)
end
it "can find a page by slug" do
page = subject.find_page("index-page")
expect(page.title).to eq("index page")
end
it "returns a WikiPage instance" do
page = subject.find_page("index page")
expect(page).to be_a WikiPage
end
end
describe '#find_file' do
before do
file = Gollum::File.new(subject.wiki)
allow_any_instance_of(Gollum::Wiki).
to receive(:file).with('image.jpg', 'master', true).
and_return(file)
allow_any_instance_of(Gollum::File).
to receive(:mime_type).
and_return('image/jpeg')
allow_any_instance_of(Gollum::Wiki).
to receive(:file).with('non-existant', 'master', true).
and_return(nil)
end
after do
allow_any_instance_of(Gollum::Wiki).to receive(:file).and_call_original
allow_any_instance_of(Gollum::File).to receive(:mime_type).and_call_original
end
it 'returns the latest version of the file if it exists' do
file = subject.find_file('image.jpg')
expect(file.mime_type).to eq('image/jpeg')
end
it 'returns nil if the page does not exist' do
expect(subject.find_file('non-existant')).to eq(nil)
end
it 'returns a Gollum::File instance' do
file = subject.find_file('image.jpg')
expect(file).to be_a Gollum::File
end
end
describe "#create_page" do
after do
destroy_page(subject.pages.first.page)
end
it "creates a new wiki page" do
expect(subject.create_page("test page", "this is content")).not_to eq(false)
expect(subject.pages.count).to eq(1)
end
it "returns false when a duplicate page exists" do
subject.create_page("test page", "content")
expect(subject.create_page("test page", "content")).to eq(false)
end
it "stores an error message when a duplicate page exists" do
2.times { subject.create_page("test page", "content") }
expect(subject.error_message).to match(/Duplicate page:/)
end
it "sets the correct commit message" do
subject.create_page("test page", "some content", :markdown, "commit message")
expect(subject.pages.first.page.version.message).to eq("commit message")
end
it 'updates project activity' do
expect(subject).to receive(:update_project_activity)
subject.create_page('Test Page', 'This is content')
end
end
describe "#update_page" do
before do
create_page("update-page", "some content")
@gollum_page = subject.wiki.paged("update-page")
subject.update_page(@gollum_page, "some other content", :markdown, "updated page")
@page = subject.pages.first.page
end
after do
destroy_page(@page)
end
it "updates the content of the page" do
expect(@page.raw_data).to eq("some other content")
end
it "sets the correct commit message" do
expect(@page.version.message).to eq("updated page")
end
it 'updates project activity' do
expect(subject).to receive(:update_project_activity)
subject.update_page(@gollum_page, 'Yet more content', :markdown, 'Updated page again')
end
end
describe "#delete_page" do
before do
create_page("index", "some content")
@page = subject.wiki.paged("index")
end
it "deletes the page" do
subject.delete_page(@page)
expect(subject.pages.count).to eq(0)
end
it 'updates project activity' do
expect(subject).to receive(:update_project_activity)
subject.delete_page(@page)
end
end
describe '#create_repo!' do
it 'creates a repository' do
expect(subject).to receive(:init_repo).
with(subject.path_with_namespace).
and_return(true)
expect(subject.repository).to receive(:after_create)
expect(subject.create_repo!).to be_an_instance_of(Gollum::Wiki)
end
end
describe '#hook_attrs' do
it 'returns a hash with values' do
expect(subject.hook_attrs).to be_a Hash
expect(subject.hook_attrs.keys).to contain_exactly(:web_url, :git_ssh_url, :git_http_url, :path_with_namespace, :default_branch)
end
end
private
def create_temp_repo(path)
FileUtils.mkdir_p path
system(*%W(#{Gitlab.config.git.bin_path} init --quiet --bare -- #{path}))
end
def remove_temp_repo(path)
FileUtils.rm_rf path
end
def commit_details
{ name: user.name, email: user.email, message: "test commit" }
end
def create_page(name, content)
subject.wiki.write_page(name, :markdown, content, commit_details)
end
def destroy_page(page)
subject.wiki.delete_page(page, commit_details)
end
end
| mr-dxdy/gitlabhq | spec/models/project_wiki_spec.rb | Ruby | mit | 8,476 |
class StaticController < ApplicationController
def guidelines
@title = t('static.guidelines.title')
end
def guidelines_tips
@title = t('static.guidelines_tips.title')
end
def faq
@title = t('static.faq.title')
end
def thank_you
backer = Backer.find session[:thank_you_backer_id]
redirect_to [backer.project, backer]
end
def sitemap
# TODO: update this sitemap to use new homepage logic
@home_page ||= Project.includes(:user, :category).visible.limit(6).all
@expiring ||= Project.includes(:user, :category).visible.expiring.not_expired.order("(projects.expires_at), created_at DESC").limit(3).all
@recent ||= Project.includes(:user, :category).visible.not_expiring.not_expired.where("projects.user_id <> 7329").order('created_at DESC').limit(3).all
@successful ||= Project.includes(:user, :category).visible.successful.order("(projects.expires_at) DESC").limit(3).all
return render 'sitemap'
end
end
| alexandred/catarse | app/controllers/static_controller.rb | Ruby | mit | 983 |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
using System.Runtime.ExceptionServices;
using System.Threading;
using System.Threading.Tasks;
namespace System.Net.Sockets
{
// This object is used to wrap a bunch of ConnectAsync operations
// on behalf of a single user call to ConnectAsync with a DnsEndPoint
internal abstract class MultipleConnectAsync
{
protected SocketAsyncEventArgs _userArgs;
protected SocketAsyncEventArgs _internalArgs;
protected DnsEndPoint _endPoint;
protected IPAddress[] _addressList;
protected int _nextAddress;
private enum State
{
NotStarted,
DnsQuery,
ConnectAttempt,
Completed,
Canceled,
}
private State _state;
private object _lockObject = new object();
// Called by Socket to kick off the ConnectAsync process. We'll complete the user's SAEA
// when it's done. Returns true if the operation will be asynchronous, false if it has failed synchronously
public bool StartConnectAsync(SocketAsyncEventArgs args, DnsEndPoint endPoint)
{
lock (_lockObject)
{
if (endPoint.AddressFamily != AddressFamily.Unspecified &&
endPoint.AddressFamily != AddressFamily.InterNetwork &&
endPoint.AddressFamily != AddressFamily.InterNetworkV6)
{
NetEventSource.Fail(this, $"Unexpected endpoint address family: {endPoint.AddressFamily}");
}
_userArgs = args;
_endPoint = endPoint;
// If Cancel() was called before we got the lock, it only set the state to Canceled: we need to
// fail synchronously from here. Once State.DnsQuery is set, the Cancel() call will handle calling AsyncFail.
if (_state == State.Canceled)
{
SyncFail(new SocketException((int)SocketError.OperationAborted));
return false;
}
if (_state != State.NotStarted)
{
NetEventSource.Fail(this, "MultipleConnectAsync.StartConnectAsync(): Unexpected object state");
}
_state = State.DnsQuery;
IAsyncResult result = Dns.BeginGetHostAddresses(endPoint.Host, new AsyncCallback(DnsCallback), null);
if (result.CompletedSynchronously)
{
return DoDnsCallback(result, true);
}
else
{
return true;
}
}
}
// Callback which fires when the Dns Resolve is complete
private void DnsCallback(IAsyncResult result)
{
if (!result.CompletedSynchronously)
{
DoDnsCallback(result, false);
}
}
// Called when the DNS query completes (either synchronously or asynchronously). Checks for failure and
// starts the first connection attempt if it succeeded. Returns true if the operation will be asynchronous,
// false if it has failed synchronously.
private bool DoDnsCallback(IAsyncResult result, bool sync)
{
Exception exception = null;
lock (_lockObject)
{
// If the connection attempt was canceled during the dns query, the user's callback has already been
// called asynchronously and we simply need to return.
if (_state == State.Canceled)
{
return true;
}
if (_state != State.DnsQuery)
{
NetEventSource.Fail(this, "MultipleConnectAsync.DoDnsCallback(): Unexpected object state");
}
try
{
_addressList = Dns.EndGetHostAddresses(result);
if (_addressList == null)
{
NetEventSource.Fail(this, "MultipleConnectAsync.DoDnsCallback(): EndGetHostAddresses returned null!");
}
}
catch (Exception e)
{
_state = State.Completed;
exception = e;
}
// If the dns query succeeded, try to connect to the first address
if (exception == null)
{
_state = State.ConnectAttempt;
_internalArgs = new SocketAsyncEventArgs();
_internalArgs.Completed += InternalConnectCallback;
_internalArgs.CopyBufferFrom(_userArgs);
exception = AttemptConnection();
if (exception != null)
{
// There was a synchronous error while connecting
_state = State.Completed;
}
}
}
// Call this outside of the lock because it might call the user's callback.
if (exception != null)
{
return Fail(sync, exception);
}
else
{
return true;
}
}
// Callback which fires when an internal connection attempt completes.
// If it failed and there are more addresses to try, do it.
private void InternalConnectCallback(object sender, SocketAsyncEventArgs args)
{
Exception exception = null;
lock (_lockObject)
{
if (_state == State.Canceled)
{
// If Cancel was called before we got the lock, the Socket will be closed soon. We need to report
// OperationAborted (even though the connection actually completed), or the user will try to use a
// closed Socket.
exception = new SocketException((int)SocketError.OperationAborted);
}
else
{
Debug.Assert(_state == State.ConnectAttempt);
if (args.SocketError == SocketError.Success)
{
// The connection attempt succeeded; go to the completed state.
// The callback will be called outside the lock.
_state = State.Completed;
}
else if (args.SocketError == SocketError.OperationAborted)
{
// The socket was closed while the connect was in progress. This can happen if the user
// closes the socket, and is equivalent to a call to CancelConnectAsync
exception = new SocketException((int)SocketError.OperationAborted);
_state = State.Canceled;
}
else
{
// Keep track of this because it will be overwritten by AttemptConnection
SocketError currentFailure = args.SocketError;
Exception connectException = AttemptConnection();
if (connectException == null)
{
// don't call the callback, another connection attempt is successfully started
return;
}
else
{
SocketException socketException = connectException as SocketException;
if (socketException != null && socketException.SocketErrorCode == SocketError.NoData)
{
// If the error is NoData, that means there are no more IPAddresses to attempt
// a connection to. Return the last error from an actual connection instead.
exception = new SocketException((int)currentFailure);
}
else
{
exception = connectException;
}
_state = State.Completed;
}
}
}
}
if (exception == null)
{
Succeed();
}
else
{
AsyncFail(exception);
}
}
// Called to initiate a connection attempt to the next address in the list. Returns an exception
// if the attempt failed synchronously, or null if it was successfully initiated.
private Exception AttemptConnection()
{
try
{
Socket attemptSocket;
IPAddress attemptAddress = GetNextAddress(out attemptSocket);
if (attemptAddress == null)
{
return new SocketException((int)SocketError.NoData);
}
_internalArgs.RemoteEndPoint = new IPEndPoint(attemptAddress, _endPoint.Port);
return AttemptConnection(attemptSocket, _internalArgs);
}
catch (Exception e)
{
if (e is ObjectDisposedException)
{
NetEventSource.Fail(this, "unexpected ObjectDisposedException");
}
return e;
}
}
private Exception AttemptConnection(Socket attemptSocket, SocketAsyncEventArgs args)
{
try
{
if (attemptSocket == null)
{
NetEventSource.Fail(null, "attemptSocket is null!");
}
bool pending = attemptSocket.ConnectAsync(args);
if (!pending)
{
InternalConnectCallback(null, args);
}
}
catch (ObjectDisposedException)
{
// This can happen if the user closes the socket, and is equivalent to a call
// to CancelConnectAsync
return new SocketException((int)SocketError.OperationAborted);
}
catch (Exception e)
{
return e;
}
return null;
}
protected abstract void OnSucceed();
private void Succeed()
{
OnSucceed();
_userArgs.FinishWrapperConnectSuccess(_internalArgs.ConnectSocket, _internalArgs.BytesTransferred, _internalArgs.SocketFlags);
_internalArgs.Dispose();
}
protected abstract void OnFail(bool abortive);
private bool Fail(bool sync, Exception e)
{
if (sync)
{
SyncFail(e);
return false;
}
else
{
AsyncFail(e);
return true;
}
}
private void SyncFail(Exception e)
{
OnFail(false);
if (_internalArgs != null)
{
_internalArgs.Dispose();
}
SocketException socketException = e as SocketException;
if (socketException != null)
{
_userArgs.FinishConnectByNameSyncFailure(socketException, 0, SocketFlags.None);
}
else
{
ExceptionDispatchInfo.Throw(e);
}
}
private void AsyncFail(Exception e)
{
OnFail(false);
if (_internalArgs != null)
{
_internalArgs.Dispose();
}
_userArgs.FinishOperationAsyncFailure(e, 0, SocketFlags.None);
}
public void Cancel()
{
bool callOnFail = false;
lock (_lockObject)
{
switch (_state)
{
case State.NotStarted:
// Cancel was called before the Dns query was started. The dns query won't be started
// and the connection attempt will fail synchronously after the state change to DnsQuery.
// All we need to do here is close all the sockets.
callOnFail = true;
break;
case State.DnsQuery:
// Cancel was called after the Dns query was started, but before it finished. We can't
// actually cancel the Dns query, but we'll fake it by failing the connect attempt asynchronously
// from here, and silently dropping the connection attempt when the Dns query finishes.
Task.Factory.StartNew(
s => CallAsyncFail(s),
null,
CancellationToken.None,
TaskCreationOptions.DenyChildAttach,
TaskScheduler.Default);
callOnFail = true;
break;
case State.ConnectAttempt:
// Cancel was called after the Dns query completed, but before we had a connection result to give
// to the user. Closing the sockets will cause any in-progress ConnectAsync call to fail immediately
// with OperationAborted, and will cause ObjectDisposedException from any new calls to ConnectAsync
// (which will be translated to OperationAborted by AttemptConnection).
callOnFail = true;
break;
case State.Completed:
// Cancel was called after we locked in a result to give to the user. Ignore it and give the user
// the real completion.
break;
default:
NetEventSource.Fail(this, "Unexpected object state");
break;
}
_state = State.Canceled;
}
// Call this outside the lock because Socket.Close may block
if (callOnFail)
{
OnFail(true);
}
}
// Call AsyncFail on a threadpool thread so it's asynchronous with respect to Cancel().
private void CallAsyncFail(object ignored)
{
AsyncFail(new SocketException((int)SocketError.OperationAborted));
}
protected abstract IPAddress GetNextAddress(out Socket attemptSocket);
}
// Used when the instance ConnectAsync method is called, or when the DnsEndPoint specified
// an AddressFamily. There's only one Socket, and we only try addresses that match its
// AddressFamily
internal sealed class SingleSocketMultipleConnectAsync : MultipleConnectAsync
{
private Socket _socket;
private bool _userSocket;
public SingleSocketMultipleConnectAsync(Socket socket, bool userSocket)
{
_socket = socket;
_userSocket = userSocket;
}
protected override IPAddress GetNextAddress(out Socket attemptSocket)
{
_socket.ReplaceHandleIfNecessaryAfterFailedConnect();
IPAddress rval = null;
do
{
if (_nextAddress >= _addressList.Length)
{
attemptSocket = null;
return null;
}
rval = _addressList[_nextAddress];
++_nextAddress;
}
while (!_socket.CanTryAddressFamily(rval.AddressFamily));
attemptSocket = _socket;
return rval;
}
protected override void OnFail(bool abortive)
{
// Close the socket if this is an abortive failure (CancelConnectAsync)
// or if we created it internally
if (abortive || !_userSocket)
{
_socket.Dispose();
}
}
// nothing to do on success
protected override void OnSucceed() { }
}
// This is used when the static ConnectAsync method is called. We don't know the address family
// ahead of time, so we create both IPv4 and IPv6 sockets.
internal sealed class DualSocketMultipleConnectAsync : MultipleConnectAsync
{
private Socket _socket4;
private Socket _socket6;
public DualSocketMultipleConnectAsync(SocketType socketType, ProtocolType protocolType)
{
if (Socket.OSSupportsIPv4)
{
_socket4 = new Socket(AddressFamily.InterNetwork, socketType, protocolType);
}
if (Socket.OSSupportsIPv6)
{
_socket6 = new Socket(AddressFamily.InterNetworkV6, socketType, protocolType);
}
}
protected override IPAddress GetNextAddress(out Socket attemptSocket)
{
IPAddress rval = null;
attemptSocket = null;
while (attemptSocket == null)
{
if (_nextAddress >= _addressList.Length)
{
return null;
}
rval = _addressList[_nextAddress];
++_nextAddress;
if (rval.AddressFamily == AddressFamily.InterNetworkV6)
{
attemptSocket = _socket6;
}
else if (rval.AddressFamily == AddressFamily.InterNetwork)
{
attemptSocket = _socket4;
}
}
attemptSocket?.ReplaceHandleIfNecessaryAfterFailedConnect();
return rval;
}
// on success, close the socket that wasn't used
protected override void OnSucceed()
{
if (_socket4 != null && !_socket4.Connected)
{
_socket4.Dispose();
}
if (_socket6 != null && !_socket6.Connected)
{
_socket6.Dispose();
}
}
// close both sockets whether its abortive or not - we always create them internally
protected override void OnFail(bool abortive)
{
_socket4?.Dispose();
_socket6?.Dispose();
}
}
}
| Ermiar/corefx | src/System.Net.Sockets/src/System/Net/Sockets/MultipleConnectAsync.cs | C# | mit | 18,925 |
package org.knowm.xchange.ccex.dto.account;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.math.BigDecimal;
public class CCEXBalance {
private String Currency;
private BigDecimal Balance;
private BigDecimal Available;
private BigDecimal Pending;
private String CryptoAddress;
public CCEXBalance(
@JsonProperty("Currency") String currency,
@JsonProperty("Balance") BigDecimal balance,
@JsonProperty("Available") BigDecimal available,
@JsonProperty("Pending") BigDecimal pending,
@JsonProperty("CryptoAddress") String cryptoAddress) {
super();
Currency = currency;
Balance = balance;
Available = available;
Pending = pending;
CryptoAddress = cryptoAddress;
}
public String getCurrency() {
return Currency;
}
public void setCurrency(String currency) {
Currency = currency;
}
public BigDecimal getBalance() {
return Balance;
}
public void setBalance(BigDecimal balance) {
Balance = balance;
}
public BigDecimal getAvailable() {
return Available;
}
public void setAvailable(BigDecimal available) {
Available = available;
}
public BigDecimal getPending() {
return Pending;
}
public void setPending(BigDecimal pending) {
Pending = pending;
}
public String getCryptoAddress() {
return CryptoAddress;
}
public void setCryptoAddress(String cryptoAddress) {
CryptoAddress = cryptoAddress;
}
@Override
public String toString() {
return "CCEXBalance [Currency="
+ Currency
+ ", Balance="
+ Balance
+ ", Available="
+ Available
+ ", Pending="
+ Pending
+ ", CryptoAddress="
+ CryptoAddress
+ "]";
}
}
| timmolter/XChange | xchange-ccex/src/main/java/org/knowm/xchange/ccex/dto/account/CCEXBalance.java | Java | mit | 1,759 |
angular.module('ordercloud-address', [])
.directive('ordercloudAddressForm', AddressFormDirective)
.directive('ordercloudAddressInfo', AddressInfoDirective)
.filter('address', AddressFilter)
;
function AddressFormDirective(OCGeography) {
return {
restrict: 'E',
scope: {
address: '=',
isbilling: '='
},
templateUrl: 'common/address/templates/address.form.tpl.html',
link: function(scope) {
scope.countries = OCGeography.Countries;
scope.states = OCGeography.States;
}
};
}
function AddressInfoDirective() {
return {
restrict: 'E',
scope: {
addressid: '@'
},
templateUrl: 'common/address/templates/address.info.tpl.html',
controller: 'AddressInfoCtrl',
controllerAs: 'addressInfo'
};
}
function AddressFilter() {
return function(address, option) {
if (!address) return null;
if (option === 'full') {
var result = [];
if (address.AddressName) {
result.push(address.AddressName);
}
result.push((address.FirstName ? address.FirstName + ' ' : '') + address.LastName);
result.push(address.Street1);
if (address.Street2) {
result.push(address.Street2);
}
result.push(address.City + ', ' + address.State + ' ' + address.Zip);
return result.join('\n');
}
else {
return address.Street1 + (address.Street2 ? ', ' + address.Street2 : '');
}
}
}
| Four51/OrderCloud-Seed-AngularJS | src/app/common/address/address.js | JavaScript | mit | 1,620 |
#pragma once
namespace graphic
{
class cCube
{
public:
cCube();
cCube(const Vector3 &vMin, const Vector3 &vMax );
void SetCube(const Vector3 &vMin, const Vector3 &vMax );
void SetTransform( const Matrix44 &tm );
void SetColor( DWORD color);
const Matrix44& GetTransform() const;
const Vector3& GetMin() const;
const Vector3& GetMax() const;
void Render(const Matrix44 &tm);
protected:
void InitCube();
private:
cVertexBuffer m_vtxBuff;
cIndexBuffer m_idxBuff;
Vector3 m_min;
Vector3 m_max;
Matrix44 m_tm;
};
inline void cCube::SetTransform( const Matrix44 &tm ) { m_tm = tm; }
inline const Matrix44& cCube::GetTransform() const { return m_tm; }
inline const Vector3& cCube::GetMin() const { return m_min; }
inline const Vector3& cCube::GetMax() const { return m_max; }
}
| sgajaejung/3D-Lecture-2 | Shadow Study/base/cube.h | C | mit | 823 |
// RUN: %clang_cc1 -verify -fopenmp=libiomp5 %s
void foo() {
}
bool foobool(int argc) {
return argc;
}
struct S1; // expected-note {{declared here}}
template <class T, typename S, int N, int ST> // expected-note {{declared here}}
T tmain(T argc, S **argv) { //expected-note 2 {{declared here}}
#pragma omp parallel for collapse // expected-error {{expected '(' after 'collapse'}}
for (int i = ST; i < N; i++) argv[0][i] = argv[0][i] - argv[0][i-ST];
#pragma omp parallel for collapse ( // expected-error {{expected expression}} expected-error {{expected ')'}} expected-note {{to match this '('}}
for (int i = ST; i < N; i++) argv[0][i] = argv[0][i] - argv[0][i-ST];
#pragma omp parallel for collapse () // expected-error {{expected expression}}
for (int i = ST; i < N; i++) argv[0][i] = argv[0][i] - argv[0][i-ST];
// expected-error@+3 {{expected ')'}} expected-note@+3 {{to match this '('}}
// expected-error@+2 2 {{expression is not an integral constant expression}}
// expected-note@+1 2 {{read of non-const variable 'argc' is not allowed in a constant expression}}
#pragma omp parallel for collapse (argc
for (int i = ST; i < N; i++) argv[0][i] = argv[0][i] - argv[0][i-ST];
// expected-error@+1 2 {{argument to 'collapse' clause must be a positive integer value}}
#pragma omp parallel for collapse (ST // expected-error {{expected ')'}} expected-note {{to match this '('}}
for (int i = ST; i < N; i++) argv[0][i] = argv[0][i] - argv[0][i-ST];
#pragma omp parallel for collapse (1)) // expected-warning {{extra tokens at the end of '#pragma omp parallel for' are ignored}}
for (int i = ST; i < N; i++) argv[0][i] = argv[0][i] - argv[0][i-ST];
#pragma omp parallel for collapse ((ST > 0) ? 1 + ST : 2) // expected-note 2 {{as specified in 'collapse' clause}}
for (int i = ST; i < N; i++) argv[0][i] = argv[0][i] - argv[0][i-ST]; // expected-error 2 {{expected 2 for loops after '#pragma omp parallel for', but found only 1}}
// expected-error@+3 2 {{directive '#pragma omp parallel for' cannot contain more than one 'collapse' clause}}
// expected-error@+2 2 {{argument to 'collapse' clause must be a positive integer value}}
// expected-error@+1 2 {{expression is not an integral constant expression}}
#pragma omp parallel for collapse (foobool(argc)), collapse (true), collapse (-5)
for (int i = ST; i < N; i++) argv[0][i] = argv[0][i] - argv[0][i-ST];
#pragma omp parallel for collapse (S) // expected-error {{'S' does not refer to a value}}
for (int i = ST; i < N; i++) argv[0][i] = argv[0][i] - argv[0][i-ST];
// expected-error@+1 2 {{expression is not an integral constant expression}}
#pragma omp parallel for collapse (argv[1]=2) // expected-error {{expected ')'}} expected-note {{to match this '('}}
for (int i = ST; i < N; i++) argv[0][i] = argv[0][i] - argv[0][i-ST];
#pragma omp parallel for collapse (1)
for (int i = ST; i < N; i++) argv[0][i] = argv[0][i] - argv[0][i-ST];
#pragma omp parallel for collapse (N) // expected-error {{argument to 'collapse' clause must be a positive integer value}}
for (T i = ST; i < N; i++) argv[0][i] = argv[0][i] - argv[0][i-ST];
#pragma omp parallel for collapse (2) // expected-note {{as specified in 'collapse' clause}}
foo(); // expected-error {{expected 2 for loops after '#pragma omp parallel for'}}
return argc;
}
int main(int argc, char **argv) {
#pragma omp parallel for collapse // expected-error {{expected '(' after 'collapse'}}
for (int i = 4; i < 12; i++) argv[0][i] = argv[0][i] - argv[0][i-4];
#pragma omp parallel for collapse ( // expected-error {{expected expression}} expected-error {{expected ')'}} expected-note {{to match this '('}}
for (int i = 4; i < 12; i++) argv[0][i] = argv[0][i] - argv[0][i-4];
#pragma omp parallel for collapse () // expected-error {{expected expression}}
for (int i = 4; i < 12; i++) argv[0][i] = argv[0][i] - argv[0][i-4];
#pragma omp parallel for collapse (4 // expected-error {{expected ')'}} expected-note {{to match this '('}} expected-note {{as specified in 'collapse' clause}}
for (int i = 4; i < 12; i++) argv[0][i] = argv[0][i] - argv[0][i-4]; // expected-error {{expected 4 for loops after '#pragma omp parallel for', but found only 1}}
#pragma omp parallel for collapse (2+2)) // expected-warning {{extra tokens at the end of '#pragma omp parallel for' are ignored}} expected-note {{as specified in 'collapse' clause}}
for (int i = 4; i < 12; i++) argv[0][i] = argv[0][i] - argv[0][i-4]; // expected-error {{expected 4 for loops after '#pragma omp parallel for', but found only 1}}
#pragma omp parallel for collapse (foobool(1) > 0 ? 1 : 2) // expected-error {{expression is not an integral constant expression}}
for (int i = 4; i < 12; i++) argv[0][i] = argv[0][i] - argv[0][i-4];
// expected-error@+3 {{expression is not an integral constant expression}}
// expected-error@+2 2 {{directive '#pragma omp parallel for' cannot contain more than one 'collapse' clause}}
// expected-error@+1 2 {{argument to 'collapse' clause must be a positive integer value}}
#pragma omp parallel for collapse (foobool(argc)), collapse (true), collapse (-5)
for (int i = 4; i < 12; i++) argv[0][i] = argv[0][i] - argv[0][i-4];
#pragma omp parallel for collapse (S1) // expected-error {{'S1' does not refer to a value}}
for (int i = 4; i < 12; i++) argv[0][i] = argv[0][i] - argv[0][i-4];
// expected-error@+1 {{expression is not an integral constant expression}}
#pragma omp parallel for collapse (argv[1]=2) // expected-error {{expected ')'}} expected-note {{to match this '('}}
for (int i = 4; i < 12; i++) argv[0][i] = argv[0][i] - argv[0][i-4];
// expected-error@+3 {{statement after '#pragma omp parallel for' must be a for loop}}
// expected-note@+1 {{in instantiation of function template specialization 'tmain<int, char, -1, -2>' requested here}}
#pragma omp parallel for collapse(collapse(tmain<int, char, -1, -2>(argc, argv) // expected-error 2 {{expected ')'}} expected-note 2 {{to match this '('}}
foo();
#pragma omp parallel for collapse (2) // expected-note {{as specified in 'collapse' clause}}
foo(); // expected-error {{expected 2 for loops after '#pragma omp parallel for'}}
// expected-note@+1 {{in instantiation of function template specialization 'tmain<int, char, 1, 0>' requested here}}
return tmain<int, char, 1, 0>(argc, argv);
}
| Rapier-Foundation/rapier-script | src/rapierlang/test/OpenMP/parallel_for_collapse_messages.cpp | C++ | mit | 6,389 |
#!/bin/bash
export ORIGINAL_PATH=`pwd`
for name in builtin/*
do
if [ -d "${name}" ]; then
echo ------------------------------------------
echo ${name}
echo ------------------------------------------
cd ${name}
# check if we have uncommit changes
result=$(git cherry -v)
if [ ! "${result}" == "" ]; then
git push $@
fi
cd ${ORIGINAL_PATH}
echo
fi
done
| jarradh/nucliasm | utils/git-push.sh | Shell | mit | 456 |
// ==========================================================================
// SeqAn - The Library for Sequence Analysis
// ==========================================================================
// Copyright (c) 2006-2013, Knut Reinert, FU Berlin
// 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 Knut Reinert or the FU Berlin 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 KNUT REINERT OR THE FU BERLIN 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.
//
// ==========================================================================
// Author: Manuel Holtgrewe <manuel.holtgrewe@fu-berlin.de>
// ==========================================================================
// Shuffling.
// ==========================================================================
#ifndef SEQAN_RANDOM_RANDOM_SHUFFLE_H_
#define SEQAN_RANDOM_RANDOM_SHUFFLE_H_
namespace seqan {
// ===========================================================================
// Forwards, Tags.
// ===========================================================================
// ===========================================================================
// Classes
// ===========================================================================
// ===========================================================================
// Metafunctions
// ===========================================================================
// ===========================================================================
// Functions
// ===========================================================================
/*!
* @fn shuffle
* @brief Shuffle the given container.
*
* @signature void shuffle(container, rng);
*
* @param[in,out] container The container to shuffle.
* @param[in,out] rng The random number generator to use.
*/
/**
.Function.shuffle
..summary:Shuffle the given container.
..cat:Random
..include:seqan/random.h
..signature:shuffle(container, rng)
..param.container:Container to shuffle elements of.
..param.rng:Random number generator to use.
...type:Class.Rng
..wiki:Tutorial/Randomness#Shuffling|Tutorial: Randomness
*/
template <typename TContainer, typename TRNG>
void shuffle(TContainer & container, TRNG & rng)
{
SEQAN_CHECKPOINT;
typedef typename Position<TContainer>::Type TPosition;
typedef typename Value<TContainer>::Type TValue;
TValue tmp;
for (TPosition i = 0, iend = length(container); i < iend; ++i) {
Pdf<Uniform<TPosition> > uniformDist(i, iend - 1);
TPosition j = pickRandomNumber(rng, uniformDist);
// swap
move(tmp, container[i]);
move(container[i], container[j]);
move(container[j], tmp);
}
}
} // namespace seqan
#endif // SEQAN_RANDOM_RANDOM_SHUFFLE_H_
| wwood/fxtract | third_party/seqan-1.4.1/include/seqan/random/random_shuffle.h | C | mit | 4,110 |
<?php
/**
* @author Mark van der Velden <mark@dynom.nl>
*/
namespace Faker\Test\Provider;
use Faker;
/**
* Class ProviderOverrideTest
*
* @package Faker\Test\Provider
*
* This class tests a large portion of all locale specific providers. It does not test the entire stack, because each
* locale specific provider (can) has specific implementations. The goal of this test is to test the common denominator
* and to try to catch possible invalid multi-byte sequences.
*/
class ProviderOverrideTest extends \PHPUnit_Framework_TestCase
{
/**
* Constants with regular expression patterns for testing the output.
*
* Regular expressions are sensitive for malformed strings (e.g.: strings with incorrect encodings) so by using
* PCRE for the tests, even though they seem fairly pointless, we test for incorrect encodings also.
*/
const TEST_STRING_REGEX = '/.+/u';
/**
* Slightly more specific for e-mail, the point isn't to properly validate e-mails.
*/
const TEST_EMAIL_REGEX = '/^(.+)@(.+)$/ui';
/**
* @dataProvider localeDataProvider
* @param string $locale
*/
public function testAddress($locale = null)
{
$faker = Faker\Factory::create($locale);
$this->assertRegExp(static::TEST_STRING_REGEX, $faker->city);
$this->assertRegExp(static::TEST_STRING_REGEX, $faker->postcode);
$this->assertRegExp(static::TEST_STRING_REGEX, $faker->address);
$this->assertRegExp(static::TEST_STRING_REGEX, $faker->country);
}
/**
* @dataProvider localeDataProvider
* @param string $locale
*/
public function testCompany($locale = null)
{
$faker = Faker\Factory::create($locale);
$this->assertRegExp(static::TEST_STRING_REGEX, $faker->company);
}
/**
* @dataProvider localeDataProvider
* @param string $locale
*/
public function testDateTime($locale = null)
{
$faker = Faker\Factory::create($locale);
$this->assertRegExp(static::TEST_STRING_REGEX, $faker->century);
$this->assertRegExp(static::TEST_STRING_REGEX, $faker->timezone);
}
/**
* @dataProvider localeDataProvider
* @param string $locale
*/
public function testInternet($locale = null)
{
$faker = Faker\Factory::create($locale);
$this->assertRegExp(static::TEST_STRING_REGEX, $faker->userName);
$this->assertRegExp(static::TEST_EMAIL_REGEX, $faker->email);
$this->assertRegExp(static::TEST_EMAIL_REGEX, $faker->safeEmail);
$this->assertRegExp(static::TEST_EMAIL_REGEX, $faker->freeEmail);
$this->assertRegExp(static::TEST_EMAIL_REGEX, $faker->companyEmail);
}
/**
* @dataProvider localeDataProvider
* @param string $locale
*/
public function testPerson($locale = null)
{
$faker = Faker\Factory::create($locale);
$this->assertRegExp(static::TEST_STRING_REGEX, $faker->name);
$this->assertRegExp(static::TEST_STRING_REGEX, $faker->title);
$this->assertRegExp(static::TEST_STRING_REGEX, $faker->firstName);
$this->assertRegExp(static::TEST_STRING_REGEX, $faker->lastName);
}
/**
* @dataProvider localeDataProvider
* @param string $locale
*/
public function testPhoneNumber($locale = null)
{
$faker = Faker\Factory::create($locale);
$this->assertRegExp(static::TEST_STRING_REGEX, $faker->phoneNumber);
}
/**
* @dataProvider localeDataProvider
* @param string $locale
*/
public function testUserAgent($locale = null)
{
$faker = Faker\Factory::create($locale);
$this->assertRegExp(static::TEST_STRING_REGEX, $faker->userAgent);
}
/**
* @dataProvider localeDataProvider
*
* @param null $locale
* @param string $locale
*/
public function testUuid($locale = null)
{
$faker = Faker\Factory::create($locale);
$this->assertRegExp(static::TEST_STRING_REGEX, $faker->uuid);
}
/**
* @return array
*/
public function localeDataProvider()
{
$locales = $this->getAllLocales();
$data = array();
foreach ($locales as $locale) {
$data[] = array(
$locale
);
}
return $data;
}
/**
* Returns all locales as array values
*
* @return array
*/
private function getAllLocales()
{
static $locales = array();
if ( ! empty($locales)) {
return $locales;
}
// Finding all PHP files in the xx_XX directories
$providerDir = __DIR__ .'/../../../src/Faker/Provider';
foreach (glob($providerDir .'/*_*/*.php') as $file) {
$localisation = basename(dirname($file));
if (isset($locales[ $localisation ])) {
continue;
}
$locales[ $localisation ] = $localisation;
}
return $locales;
}
}
| i-chengl/Student-activity-management-system | vendor/fzaninotto/faker/test/Faker/Provider/ProviderOverrideTest.php | PHP | mit | 5,228 |
<HTML>
<HEAD>
<TITLE>
Changes in TIFF v3.6.0
</TITLE>
</HEAD>
<BODY BGCOLOR=white>
<FONT FACE="Helvetica, Arial, Sans">
<FONT FACE="Helvetica, Arial, Sans">
<BASEFONT SIZE=4>
<B><FONT SIZE=+3>T</FONT>IFF <FONT SIZE=+2>C</FONT>HANGE <FONT SIZE=+2>I</FONT>NFORMATION</B>
<BASEFONT SIZE=3>
<UL>
<HR SIZE=4 WIDTH=65% ALIGN=left>
<B>Current Version</B>: v3.6.0<BR>
<B>Previous Version</B>: <A HREF=v3.5.7.html>v3.5.7</a><BR>
<B>Master FTP Site</B>: <A HREF="ftp://download.osgeo.org/libtiff">
download.osgeo.org</a>, directory pub/libtiff</A><BR>
<B>Master HTTP Site</B>: <A HREF="http://www.simplesystems.org/libtiff/">
http://www.simplesystems.org/libtiff/</a>
<HR SIZE=4 WIDTH=65% ALIGN=left>
</UL>
<P>
This document describes the changes made to the software between the
<I>previous</I> and <I>current</I> versions (see above).
If you don't find something listed here, then it was not done in this
timeframe, or it was not considered important enough to be mentioned.
The following information is located here:
<UL>
<LI><A HREF="#hightlights">Major Changes</A>
<LI><A HREF="#configure">Changes in the software configuration</A>
<LI><A HREF="#libtiff">Changes in libtiff</A>
<LI><A HREF="#tools">Changes in the tools</A>
<LI><A HREF="#contrib">Changes in the contrib area</A>
<LI><A HREF="#lzwkit">Changes in the LZW compression kit</A>
</UL>
<p>
<P><HR WIDTH=65% ALIGN=left>
<!--------------------------------------------------------------------------->
<A NAME="highlights"><B><FONT SIZE=+3>M</FONT>AJOR CHANGES:</B></A>
<ul>
<li> New utility <a href=./man/raw2tiff.1.html>raw2tiff</a>
for converting raw rasters into TIFF files.
<li> Lots of new <a href=./man/tiff2ps.1.html>tiff2ps</a> options.
<li> Lots of new <a href=./man/fax2tiff.1.html>fax2tiff</a> options.
<li> Lots of bug fixes for LZW, JPEG and OJPEG compression.
</ul>
<h3>Custom Tag Support</h3>
The approach to extending libtiff with custom tags has changed radically.
Previously, all internally supported TIFF tags had a place in the
private TIFFDirectory structure within libtiff to hold the values (if read),
and a "field number" (ie. FIELD_SUBFILETYPE) used to identify that tag.
However, every time a new tag was added to the core, the size of the
TIFFDirectory structure would changing, breaking any dynamically linked
software that used the private data structures.<p>
Also, any tag not recognised
by libtiff would not be read and accessable to applications without some
fairly complicated work on the applications part to pre-register the tags
as exemplified by the support for "Geo"TIFF tags by libgeotiff layered on
libtiff. <p>
Amoung other things this approach required the extension code
to access the private libtiff structures ... which made the higher level
non-libtiff code be locked into a specific version of libtiff at compile time.
This caused no end of bug reports!<p>
The new approach is for libtiff to read all tags from TIFF files. Those that
aren't recognised as "core tags" (those having an associated FIELD_ value,
and place for storage in the TIFFDirectory structure) are now read into a
dynamic list of extra tags (td_customValues in TIFFDirectory). When a new
tag code is encountered for the first time in a given TIFF file, a new
anonymous tag definition is created for the tag in the tag definition list.
The type, and some other metadata is worked out from the instance encountered.
These fields are known as "custom tags". <p>
Custom tags can be set and fetched normally using TIFFSetField() and
TIFFGetField(), and appear pretty much like normal tags to application code.
However, they have no impact on internal libtiff processing (such as
compression). Some utilities, such as tiffcp will now copy these custom
tags to the new output files. <p>
As well as the internal work with custom tags, new C API entry points
were added so that extension libraries, such as libgeotiff, could
define new tags more easily without accessing internal data structures.
Because tag handling of extension tags is done via the "custom fields"
mechanism as well, the definition provided externally mostly serves to provide
a meaningful name for the tag.
The addition of "custom tags" and the altered approach to extending libtiff
with externally defined tags is the primary reason for the shift to the
3.6.x version number from 3.5.x.<p>
<P><HR WIDTH=65% ALIGN=left>
<!--------------------------------------------------------------------------->
<A NAME="configure"><B><FONT SIZE=+3>C</FONT>HANGES IN THE SOFTWARE CONFIGURATION:</B></A>
<UL>
<li> configure, config.site: Fix for large files (>2GiB) support. New
option in the config.site: LARGEFILE="yes". Should be enougth for the large
files I/O.
<li> configure: Set -DPIXARLOG_SUPPORT option along with -DZIP_SUPPORT.
<li> html/Makefile.in: Updated to use groffhtml for generating html pages
from man pages.
<li> configure, libtiff/Makefile.in: Added SCO OpenServer 5.0.6 support
from John H. DuBois III.
<li> libtiff/{Makefile.vc, libtiff.def}: Missed declarations added.
<li> libtiff/Makefile.in, tools/Makefile.in: Shared library will not be
stripped when installing, utility binaries will do be stripped. As per bug 93.
<li> man/Makefile.in: Patch DESTDIR handling as per bug 95.
<li> configure: OpenBSD changes for Sparc64 and DSO version as per bug 96.
<li> config.site/configure: added support for OJPEG=yes option to enable
OJPEG support from config.site.
<li> config.guess, config.sub: Updated from ftp.gnu.org/pub/config.
<li> configure: Modify CheckForBigEndian so it can work in a cross
compiled situation.
<li> configure, libtiff/Makefile.in: Changes for building on MacOS 10.1
as per bug 94.
<li> html/Makefile.in: added missing images per bug 92.
<li> port/Makefile.in: fixed clean target per bug 92.
</UL>
<P><HR WIDTH=65% ALIGN=left>
<!--------------------------------------------------------------------------->
<A NAME="libtiff"><B><FONT SIZE=+3>C</FONT>HANGES IN LIBTIFF:</B></A>
<UL>
<li> libtiff/tif_getimage.c: New function <A
HREF="./man/TIFFReadRGBAImage.3t.html">TIFFReadRGBAImageOriented()</A>
implemented to retrieve raster array with user-specified origin position.
<li> libtiff/tif_fax3.c: Fix wrong line numbering.
<li> libtiff/tif_dirread.c: Check field counter against number of fields.
<li> Store a list of opened IFD to prevent directory looping.
<li> libtiff/tif_jpeg.c: modified segment_height calculation to always
be a full height tile for tiled images. Also changed error to just
be a warning.
<li> libtiff/tif_lzw.c: fixed so that decoder state isn't allocated till
LZWSetupDecode(). Needed to read LZW files in "r+" mode.
<li> libtiff/tif_dir.c: fixed up the tif_postdecode settings responsible
for byte swapping complex image data.
<li> libtiff/tif_open.c: Removed error if opening a compressed file
in update mode bug (198).
<li> libtiff/tif_write.c: TIFFWriteCheck() now fails if the image is
a pre-existing compressed image. That is, image writing to pre-existing
compressed images is not allowed.
<li> html/man/*.html: Web pages regenerated from man pages.
<li> libtiff/tif_jpeg.c: Hack to ensure that "boolean" is defined properly
on Windows so as to avoid the structure size mismatch error from libjpeg
(bug 188).
<li> libtiff/tiff.h: #ifdef USING_VISUALAGE around previous Visual Age
AIX porting hack as it screwed up gcc. (bug 39)
<li> libtiff/tiff.h: added COMPRESSION_JP2000 (34712) for LEAD tools
custom compression.
<li> libtiff/tif_dirread.c: Another fix for the fetching SBYTE arrays
by the TIFFFetchByteArray() function. (bug 52)
<li> libtiff/tif_dirread.c: Expand v[2] to v[4] in TIFFFetchShortPair()
as per bug 196.
<li> libtiff/tif_lzw.c: Additional consistency checking added in
LZWDecode() and LZWDecodeCompat() fixing bugs 190 and 100.
<li> libtiff/tif_lzw.c: Added check for valid code lengths in LZWDecode()
and LZWDecodeCompat(). Fixes bug 115.
<li> tif_getimage.c: Ensure that TIFFRGBAImageBegin() returns the
return code from the underlying pick function as per bug 177.
<li> libtiff/{tif_jpeg.c,tif_strip.c,tif_print.c}: Hacked tif_jpeg.c to
fetch TIFFTAG_YCBCRSUBSAMPLING from the jpeg data stream if it isn't
present in the tiff tags as per bug 168.
<li> libtiff/tif_jpeg.c: Fixed problem with setting of nrows in
JPEGDecode() as per bug 129.
<li> libtiff/tif_read.c, libtiff/tif_write.c: TIFFReadScanline() and
TIFFWriteScanline() now set tif_row explicitly in case the codec has
fooled with the value as per bug 129.
<li> libtiff/tif_ojpeg.c: Major upgrade from Scott. Details in bug 156.
<li> libtiff/tif_open.c: Pointers to custom procedures
in TIFFClientOpen() are checked to be not NULL-pointers.
<li> libtiff/tif_lzw.c: Assertions in LZWDecode and LZWDecodeCompat
replaced by warnings. Now libtiff should read corrupted LZW-compressed
files by skipping bad strips as per bug 100.
<li> libtiff/: tif_dirwrite.c, tif_write.c, tiffio.h:
<a href=./man/TIFFWriteDirectory.3t.html>TIFFCheckpointDirectory()</a>
routine added as per bug 124. The
<a href=./man/TIFFWriteDirectory.3t.html>TIFFWriteDirectory</a>
man page discusses this new function as well as the related
<a href=./man/TIFFWriteDirectory.3t.html>TIFFRewriteDirectory()</a>.
<li> libtiff/: tif_codec.c, tif_compress.c, tiffiop.h, tif_getimage.c:
Introduced
additional members tif->tif_decodestatus and tif->tif_encodestatus
for correct handling of unconfigured codecs (we should not try to read
data or to define data size without correct codecs). See bug 119.
<li> tif_dirread.c: avoid div-by-zero if rowbytes is zero in chop func as
per bug 111.
<li> libtiff/: tiff.h, tif_dir.c, tif_dir.h, tif_dirinfo.c, tif_dirread.c,
tif_dirwrite.c: Dwight Kelly added get/put code for new tag XMLPACKET as
defined in Adobe XMP Technote. Added missing INKSET tag value from TIFF 6.0
spec INKSET_MULTIINK (=2). Added missing tags from Adobe TIFF technotes:
CLIPPATH, XCLIPPATHUNITS, YCLIPPATHUNITS, OPIIMAGEID, OPIPROXY and
INDEXED. Added PHOTOMETRIC tag value from TIFF technote 4 ICCLAB (=9).
<li> libtiff/tif_getimage.c: Additional check for supported codecs added in
TIFFRGBAImageOK, TIFFReadRGBAImage, TIFFReadRGBAStrip and TIFFReadRGBATile now
use TIFFRGBAImageOK before reading a per bug 110.
<li> libtiff/: tif_dir.c, tif_dir.h, tif_dirinfo.c, tif_dirread.c,
tif_dirwrite.c: Added routine
<a href=./man/TIFFDataWidth.3t.html>TIFFDataWidth</a> for determining
TIFFDataType sizes instead of working with tiffDataWidth array
directly as per bug 109.
<li>libtiff/: tif_dirinfo.c, tif_dirwrite.c: Added possibility to
read broken TIFFs with LONG type used for TIFFTAG_COMPRESSION,
TIFFTAG_BITSPERSAMPLE, TIFFTAG_PHOTOMETRIC as per bug 99.
<li> libtiff/{tiff.h,tif_fax3.c}: Add support for __arch64__ as per bug 94.
<li> libtiff/tif_read.c: Fixed TIFFReadEncodedStrip() to fail if the
decodestrip function returns anything not greater than zero as per bug 97.
<li> libtiff/tif_jpeg.c: fixed computation of segment_width for
tiles files to avoid error about it not matching the
cinfo.d.image_width values ("JPEGPreDecode: Improper JPEG strip/tile
size.") for ITIFF files. Apparently the problem was incorporated since
3.5.5, presumably during the OJPEG/JPEG work recently.
<li> libtiff/tif_getimage.c: If DEFAULT_EXTRASAMPLE_AS_ALPHA is 1
(defined in tiffconf.h - 1 by default) then the RGBA interface
will assume that a fourth extra sample is ASSOCALPHA if the
EXTRASAMPLE value isn't set for it. This changes the behaviour of
the library, but makes it work better with RGBA files produced by
lots of applications that don't mark the alpha values properly.
As per bugs 93 and 65.
<li> libtiff/tif_jpeg.c: allow jpeg data stream sampling values to
override those from tiff directory. This makes this work with
ImageGear generated files.
</UL>
<P><HR WIDTH=65% ALIGN=left>
<!-------------------------------------------------------------------------->
<A NAME="tools"><B><FONT SIZE=+3>C</FONT>HANGES IN THE TOOLS:</B></A>
<UL>
<li> <a href=./man/tiff2ps.1.html>tiff2ps</a>: Added page size setting
when creating PS Level 2.
<li> <a href=./man/tiff2ps.1.html>tiff2ps</a>: Fixed PS comment emitted when
FlateDecode is being used.
<li> <a href=./man/tiffsplit.1.html>tiffsplit</a>: increased the maximum
number of pages that can be split.
<li> <a href=./man/raw2tiff.1.html>raw2tiff</a>: Added option `-p' to
explicitly select color space of input image data.
<li> <a href=./man/tiffmedian.1.html>tiffmedian</a>: Suppiort for large
(> 2GB) images.
<li> <a href=./man/ppm2tiff.1.html>ppm2tiff</a>: Fixed possible endless loop.
<li> <a href=./man/tiff2rgba.1.html>tiff2rgba</a>: Switched to use
<A HREF="./man/TIFFReadRGBAImage.3t.html">TIFFReadRGBAImageOriented()</A>
instead of <A HREF="./man/TIFFReadRGBAImage.3t.html">TIFFReadRGBAImage()</A>.
<li> <a href=./man/tiffcmp.1.html>tiffcmp</a>: Fixed problem with unused data
comparing (bug 349). `-z' option now can be used to set the number of reported
different bytes.
<li> <a href=./man/tiffcp.1.html>tiffcp</a>: Added possibility to specify
value -1 to -r option to get the entire image as one strip (bug 343).
<li> <a href=./man/tiffcp.1.html>tiffcp</a>: Set the correct RowsPerStrip
and PageNumber values (bug 343).
<li> <a href=./man/fax2tiff.1.html>fax2tiff</a>: Page numbering fixed (bug
341).
<li> <a href=./man/ppm2tiff.1.html>ppm2tiff</a>: PPM header parser improved:
now able to skip comments.
<li> <a href=./man/tiff2ps.1.html>tiff2ps</a>: Force deadzone printing when
EPS output specified (bug 325).
<li> <a href=./man/tiff2ps.1.html>tiff2ps</a>: Add ability to generate
PS Level 3. It basically allows one to use the /flateDecode filter for ZIP
compressed TIFF images. Patch supplied by Tom Kacvinsky (bug 328).
<li> <a href=./man/tiffcp.1.html>tiffcp</a>: Fixed problem with colorspace
conversion for JPEG encoded images (bugs 23 and 275)
<li> <a href=./man/fax2tiff.1.html>fax2tiff</a>: Applied patch from
Julien Gaulmin. More switches for fax2tiff tool for better control
of input and output (bugs 272 and 293).
<li> <a href=./man/raw2tiff.1.html>raw2tiff</a>:
New utility for turning raw raster images into TIFF files
written by Andrey Kiselev.
<li> <a href=./man/tiff2ps.1.html>tiff2ps</a>:
Sebastian Eken provided patches (bug 200) to add new these new
switches:
<ul>
<li> <b>-b #</b>: for a bottom margin of # inches
<li> <b>-c</b>: center image
<li> <b>-l #</b>: for a left margin of # inches
<li> <b>-r</b>: rotate the image by 180 degrees
</ul>
Also, new features merged with code for shrinking/overlapping.
<li> <a href=./man/tiff2ps.1.html>tiff2ps</a>: Don't emit BeginData/EndData
DSC comments since we are unable to properly include the amount to skip
as per bug 80.
<li> <a href=./man/tiff2ps.1.html>tiff2ps</a>: Added workaround for some
software that may crash when last strip of image contains fewer number
of scanlines than specified by the `/Height' variable as per bug 164.
<li> <a href=./man/tiff2ps.1.html>tiff2ps</a>: Patch from John Williams to add new
functionality for tiff2ps utility splitting long images in several pages as
per bug 142. New switches:
<ul>
<li> <b>-H #</b>: split image if height is more than # inches
<li> <b>-L #</b>: overLap split images by # inches
</ul>
<li> <a href=./man/tiff2ps.1.html>tiff2ps</a>: New commandline
switches to override resolution units obtained from the input file per bug 131:
<ul>
<li> <b>-x</b>: override resolution units as centimeters
<li> <b>-y</b>: override resolution units as inches
</ul>
<li> <a href=./man/fax2tiff.1.html>fax2tiff</a>: Updated to reflect
latest changes in libtiff per bug 125.
<li> tiff2ps: Division by zero fixed as per bug 88.
<li> <a href=./man/tiffcp.1.html>tiffcp<a>:
Added support for 'Orientation' tag.
<li> <a href=./man/tiffdump.1.html>tiffdump</a>:
include TIFFTAG_JPEGTABLES in tag list.
<li> tiffset: fix bug in error reporting.
</UL>
<P><HR WIDTH=65% ALIGN=left>
<!--------------------------------------------------------------------------->
<A NAME="contrib"><B><FONT SIZE=+3>C</FONT>HANGES IN THE CONTRIB AREA:</B></A>
<UL>
<li> Fixed distribution to include contrib/addtiffo/tif_ovrcache.{c,h}.
<li> libtiff/contrib/win95: renamed to contrib/win_dib. Added new
Tiffile.cpp example of converting TIFF files into a DIB on Win32 as per
bug 143.
</UL>
<!--------------------------------------------------------------------------->
<A NAME="lzwkit"><B><FONT SIZE=+3>C</FONT>HANGES IN THE LZW COMPRESSION
KIT:</B></A>
<UL>
<li> LZW compression kit synchronized with actual libtiff version.
</UL>
<A HREF="index.html"><IMG SRC="images/back.gif"></A> TIFF home page.<BR>
<HR>
Last updated $Date: 2016-09-25 20:05:45 $.
</BODY>
</HTML>
| mbelicki/warp | libs/SDL_Image/external/tiff-4.0.8/html/v3.6.0.html | HTML | mit | 16,777 |
// Approach:
//
// 1. Get the minimatch set
// 2. For each pattern in the set, PROCESS(pattern, false)
// 3. Store matches per-set, then uniq them
//
// PROCESS(pattern, inGlobStar)
// Get the first [n] items from pattern that are all strings
// Join these together. This is PREFIX.
// If there is no more remaining, then stat(PREFIX) and
// add to matches if it succeeds. END.
//
// If inGlobStar and PREFIX is symlink and points to dir
// set ENTRIES = []
// else readdir(PREFIX) as ENTRIES
// If fail, END
//
// with ENTRIES
// If pattern[n] is GLOBSTAR
// // handle the case where the globstar match is empty
// // by pruning it out, and testing the resulting pattern
// PROCESS(pattern[0..n] + pattern[n+1 .. $], false)
// // handle other cases.
// for ENTRY in ENTRIES (not dotfiles)
// // attach globstar + tail onto the entry
// // Mark that this entry is a globstar match
// PROCESS(pattern[0..n] + ENTRY + pattern[n .. $], true)
//
// else // not globstar
// for ENTRY in ENTRIES (not dotfiles, unless pattern[n] is dot)
// Test ENTRY against pattern[n]
// If fails, continue
// If passes, PROCESS(pattern[0..n] + item + pattern[n+1 .. $])
//
// Caveat:
// Cache all stats and readdirs results to minimize syscall. Since all
// we ever care about is existence and directory-ness, we can just keep
// `true` for files, and [children,...] for directories, or `false` for
// things that don't exist.
module.exports = glob
var rp = require('fs.realpath')
var minimatch = require('minimatch')
var Minimatch = minimatch.Minimatch
var inherits = require('inherits')
var EE = require('events').EventEmitter
var path = require('path')
var assert = require('assert')
var isAbsolute = require('path-is-absolute')
var globSync = require('./sync.js')
var common = require('./common.js')
var setopts = common.setopts
var ownProp = common.ownProp
var inflight = require('inflight')
var util = require('util')
var childrenIgnored = common.childrenIgnored
var isIgnored = common.isIgnored
var once = require('once')
function glob (pattern, options, cb) {
if (typeof options === 'function') cb = options, options = {}
if (!options) options = {}
if (options.sync) {
if (cb)
throw new TypeError('callback provided to sync glob')
return globSync(pattern, options)
}
return new Glob(pattern, options, cb)
}
glob.sync = globSync
var GlobSync = glob.GlobSync = globSync.GlobSync
// old api surface
glob.glob = glob
function extend (origin, add) {
if (add === null || typeof add !== 'object') {
return origin
}
var keys = Object.keys(add)
var i = keys.length
while (i--) {
origin[keys[i]] = add[keys[i]]
}
return origin
}
glob.hasMagic = function (pattern, options_) {
var options = extend({}, options_)
options.noprocess = true
var g = new Glob(pattern, options)
var set = g.minimatch.set
if (!pattern)
return false
if (set.length > 1)
return true
for (var j = 0; j < set[0].length; j++) {
if (typeof set[0][j] !== 'string')
return true
}
return false
}
glob.Glob = Glob
inherits(Glob, EE)
function Glob (pattern, options, cb) {
if (typeof options === 'function') {
cb = options
options = null
}
if (options && options.sync) {
if (cb)
throw new TypeError('callback provided to sync glob')
return new GlobSync(pattern, options)
}
if (!(this instanceof Glob))
return new Glob(pattern, options, cb)
setopts(this, pattern, options)
this._didRealPath = false
// process each pattern in the minimatch set
var n = this.minimatch.set.length
// The matches are stored as {<filename>: true,...} so that
// duplicates are automagically pruned.
// Later, we do an Object.keys() on these.
// Keep them as a list so we can fill in when nonull is set.
this.matches = new Array(n)
if (typeof cb === 'function') {
cb = once(cb)
this.on('error', cb)
this.on('end', function (matches) {
cb(null, matches)
})
}
var self = this
this._processing = 0
this._emitQueue = []
this._processQueue = []
this.paused = false
if (this.noprocess)
return this
if (n === 0)
return done()
var sync = true
for (var i = 0; i < n; i ++) {
this._process(this.minimatch.set[i], i, false, done)
}
sync = false
function done () {
--self._processing
if (self._processing <= 0) {
if (sync) {
process.nextTick(function () {
self._finish()
})
} else {
self._finish()
}
}
}
}
Glob.prototype._finish = function () {
assert(this instanceof Glob)
if (this.aborted)
return
if (this.realpath && !this._didRealpath)
return this._realpath()
common.finish(this)
this.emit('end', this.found)
}
Glob.prototype._realpath = function () {
if (this._didRealpath)
return
this._didRealpath = true
var n = this.matches.length
if (n === 0)
return this._finish()
var self = this
for (var i = 0; i < this.matches.length; i++)
this._realpathSet(i, next)
function next () {
if (--n === 0)
self._finish()
}
}
Glob.prototype._realpathSet = function (index, cb) {
var matchset = this.matches[index]
if (!matchset)
return cb()
var found = Object.keys(matchset)
var self = this
var n = found.length
if (n === 0)
return cb()
var set = this.matches[index] = Object.create(null)
found.forEach(function (p, i) {
// If there's a problem with the stat, then it means that
// one or more of the links in the realpath couldn't be
// resolved. just return the abs value in that case.
p = self._makeAbs(p)
rp.realpath(p, self.realpathCache, function (er, real) {
if (!er)
set[real] = true
else if (er.syscall === 'stat')
set[p] = true
else
self.emit('error', er) // srsly wtf right here
if (--n === 0) {
self.matches[index] = set
cb()
}
})
})
}
Glob.prototype._mark = function (p) {
return common.mark(this, p)
}
Glob.prototype._makeAbs = function (f) {
return common.makeAbs(this, f)
}
Glob.prototype.abort = function () {
this.aborted = true
this.emit('abort')
}
Glob.prototype.pause = function () {
if (!this.paused) {
this.paused = true
this.emit('pause')
}
}
Glob.prototype.resume = function () {
if (this.paused) {
this.emit('resume')
this.paused = false
if (this._emitQueue.length) {
var eq = this._emitQueue.slice(0)
this._emitQueue.length = 0
for (var i = 0; i < eq.length; i ++) {
var e = eq[i]
this._emitMatch(e[0], e[1])
}
}
if (this._processQueue.length) {
var pq = this._processQueue.slice(0)
this._processQueue.length = 0
for (var i = 0; i < pq.length; i ++) {
var p = pq[i]
this._processing--
this._process(p[0], p[1], p[2], p[3])
}
}
}
}
Glob.prototype._process = function (pattern, index, inGlobStar, cb) {
assert(this instanceof Glob)
assert(typeof cb === 'function')
if (this.aborted)
return
this._processing++
if (this.paused) {
this._processQueue.push([pattern, index, inGlobStar, cb])
return
}
//console.error('PROCESS %d', this._processing, pattern)
// Get the first [n] parts of pattern that are all strings.
var n = 0
while (typeof pattern[n] === 'string') {
n ++
}
// now n is the index of the first one that is *not* a string.
// see if there's anything else
var prefix
switch (n) {
// if not, then this is rather simple
case pattern.length:
this._processSimple(pattern.join('/'), index, cb)
return
case 0:
// pattern *starts* with some non-trivial item.
// going to readdir(cwd), but not include the prefix in matches.
prefix = null
break
default:
// pattern has some string bits in the front.
// whatever it starts with, whether that's 'absolute' like /foo/bar,
// or 'relative' like '../baz'
prefix = pattern.slice(0, n).join('/')
break
}
var remain = pattern.slice(n)
// get the list of entries.
var read
if (prefix === null)
read = '.'
else if (isAbsolute(prefix) || isAbsolute(pattern.join('/'))) {
if (!prefix || !isAbsolute(prefix))
prefix = '/' + prefix
read = prefix
} else
read = prefix
var abs = this._makeAbs(read)
//if ignored, skip _processing
if (childrenIgnored(this, read))
return cb()
var isGlobStar = remain[0] === minimatch.GLOBSTAR
if (isGlobStar)
this._processGlobStar(prefix, read, abs, remain, index, inGlobStar, cb)
else
this._processReaddir(prefix, read, abs, remain, index, inGlobStar, cb)
}
Glob.prototype._processReaddir = function (prefix, read, abs, remain, index, inGlobStar, cb) {
var self = this
this._readdir(abs, inGlobStar, function (er, entries) {
return self._processReaddir2(prefix, read, abs, remain, index, inGlobStar, entries, cb)
})
}
Glob.prototype._processReaddir2 = function (prefix, read, abs, remain, index, inGlobStar, entries, cb) {
// if the abs isn't a dir, then nothing can match!
if (!entries)
return cb()
// It will only match dot entries if it starts with a dot, or if
// dot is set. Stuff like @(.foo|.bar) isn't allowed.
var pn = remain[0]
var negate = !!this.minimatch.negate
var rawGlob = pn._glob
var dotOk = this.dot || rawGlob.charAt(0) === '.'
var matchedEntries = []
for (var i = 0; i < entries.length; i++) {
var e = entries[i]
if (e.charAt(0) !== '.' || dotOk) {
var m
if (negate && !prefix) {
m = !e.match(pn)
} else {
m = e.match(pn)
}
if (m)
matchedEntries.push(e)
}
}
//console.error('prd2', prefix, entries, remain[0]._glob, matchedEntries)
var len = matchedEntries.length
// If there are no matched entries, then nothing matches.
if (len === 0)
return cb()
// if this is the last remaining pattern bit, then no need for
// an additional stat *unless* the user has specified mark or
// stat explicitly. We know they exist, since readdir returned
// them.
if (remain.length === 1 && !this.mark && !this.stat) {
if (!this.matches[index])
this.matches[index] = Object.create(null)
for (var i = 0; i < len; i ++) {
var e = matchedEntries[i]
if (prefix) {
if (prefix !== '/')
e = prefix + '/' + e
else
e = prefix + e
}
if (e.charAt(0) === '/' && !this.nomount) {
e = path.join(this.root, e)
}
this._emitMatch(index, e)
}
// This was the last one, and no stats were needed
return cb()
}
// now test all matched entries as stand-ins for that part
// of the pattern.
remain.shift()
for (var i = 0; i < len; i ++) {
var e = matchedEntries[i]
var newPattern
if (prefix) {
if (prefix !== '/')
e = prefix + '/' + e
else
e = prefix + e
}
this._process([e].concat(remain), index, inGlobStar, cb)
}
cb()
}
Glob.prototype._emitMatch = function (index, e) {
if (this.aborted)
return
if (isIgnored(this, e))
return
if (this.paused) {
this._emitQueue.push([index, e])
return
}
var abs = isAbsolute(e) ? e : this._makeAbs(e)
if (this.mark)
e = this._mark(e)
if (this.absolute)
e = abs
if (this.matches[index][e])
return
if (this.nodir) {
var c = this.cache[abs]
if (c === 'DIR' || Array.isArray(c))
return
}
this.matches[index][e] = true
var st = this.statCache[abs]
if (st)
this.emit('stat', e, st)
this.emit('match', e)
}
Glob.prototype._readdirInGlobStar = function (abs, cb) {
if (this.aborted)
return
// follow all symlinked directories forever
// just proceed as if this is a non-globstar situation
if (this.follow)
return this._readdir(abs, false, cb)
var lstatkey = 'lstat\0' + abs
var self = this
var lstatcb = inflight(lstatkey, lstatcb_)
if (lstatcb)
self.fs.lstat(abs, lstatcb)
function lstatcb_ (er, lstat) {
if (er && er.code === 'ENOENT')
return cb()
var isSym = lstat && lstat.isSymbolicLink()
self.symlinks[abs] = isSym
// If it's not a symlink or a dir, then it's definitely a regular file.
// don't bother doing a readdir in that case.
if (!isSym && lstat && !lstat.isDirectory()) {
self.cache[abs] = 'FILE'
cb()
} else
self._readdir(abs, false, cb)
}
}
Glob.prototype._readdir = function (abs, inGlobStar, cb) {
if (this.aborted)
return
cb = inflight('readdir\0'+abs+'\0'+inGlobStar, cb)
if (!cb)
return
//console.error('RD %j %j', +inGlobStar, abs)
if (inGlobStar && !ownProp(this.symlinks, abs))
return this._readdirInGlobStar(abs, cb)
if (ownProp(this.cache, abs)) {
var c = this.cache[abs]
if (!c || c === 'FILE')
return cb()
if (Array.isArray(c))
return cb(null, c)
}
var self = this
self.fs.readdir(abs, readdirCb(this, abs, cb))
}
function readdirCb (self, abs, cb) {
return function (er, entries) {
if (er)
self._readdirError(abs, er, cb)
else
self._readdirEntries(abs, entries, cb)
}
}
Glob.prototype._readdirEntries = function (abs, entries, cb) {
if (this.aborted)
return
// if we haven't asked to stat everything, then just
// assume that everything in there exists, so we can avoid
// having to stat it a second time.
if (!this.mark && !this.stat) {
for (var i = 0; i < entries.length; i ++) {
var e = entries[i]
if (abs === '/')
e = abs + e
else
e = abs + '/' + e
this.cache[e] = true
}
}
this.cache[abs] = entries
return cb(null, entries)
}
Glob.prototype._readdirError = function (f, er, cb) {
if (this.aborted)
return
// handle errors, and cache the information
switch (er.code) {
case 'ENOTSUP': // https://github.com/isaacs/node-glob/issues/205
case 'ENOTDIR': // totally normal. means it *does* exist.
var abs = this._makeAbs(f)
this.cache[abs] = 'FILE'
if (abs === this.cwdAbs) {
var error = new Error(er.code + ' invalid cwd ' + this.cwd)
error.path = this.cwd
error.code = er.code
this.emit('error', error)
this.abort()
}
break
case 'ENOENT': // not terribly unusual
case 'ELOOP':
case 'ENAMETOOLONG':
case 'UNKNOWN':
this.cache[this._makeAbs(f)] = false
break
default: // some unusual error. Treat as failure.
this.cache[this._makeAbs(f)] = false
if (this.strict) {
this.emit('error', er)
// If the error is handled, then we abort
// if not, we threw out of here
this.abort()
}
if (!this.silent)
console.error('glob error', er)
break
}
return cb()
}
Glob.prototype._processGlobStar = function (prefix, read, abs, remain, index, inGlobStar, cb) {
var self = this
this._readdir(abs, inGlobStar, function (er, entries) {
self._processGlobStar2(prefix, read, abs, remain, index, inGlobStar, entries, cb)
})
}
Glob.prototype._processGlobStar2 = function (prefix, read, abs, remain, index, inGlobStar, entries, cb) {
//console.error('pgs2', prefix, remain[0], entries)
// no entries means not a dir, so it can never have matches
// foo.txt/** doesn't match foo.txt
if (!entries)
return cb()
// test without the globstar, and with every child both below
// and replacing the globstar.
var remainWithoutGlobStar = remain.slice(1)
var gspref = prefix ? [ prefix ] : []
var noGlobStar = gspref.concat(remainWithoutGlobStar)
// the noGlobStar pattern exits the inGlobStar state
this._process(noGlobStar, index, false, cb)
var isSym = this.symlinks[abs]
var len = entries.length
// If it's a symlink, and we're in a globstar, then stop
if (isSym && inGlobStar)
return cb()
for (var i = 0; i < len; i++) {
var e = entries[i]
if (e.charAt(0) === '.' && !this.dot)
continue
// these two cases enter the inGlobStar state
var instead = gspref.concat(entries[i], remainWithoutGlobStar)
this._process(instead, index, true, cb)
var below = gspref.concat(entries[i], remain)
this._process(below, index, true, cb)
}
cb()
}
Glob.prototype._processSimple = function (prefix, index, cb) {
// XXX review this. Shouldn't it be doing the mounting etc
// before doing stat? kinda weird?
var self = this
this._stat(prefix, function (er, exists) {
self._processSimple2(prefix, index, er, exists, cb)
})
}
Glob.prototype._processSimple2 = function (prefix, index, er, exists, cb) {
//console.error('ps2', prefix, exists)
if (!this.matches[index])
this.matches[index] = Object.create(null)
// If it doesn't exist, then just mark the lack of results
if (!exists)
return cb()
if (prefix && isAbsolute(prefix) && !this.nomount) {
var trail = /[\/\\]$/.test(prefix)
if (prefix.charAt(0) === '/') {
prefix = path.join(this.root, prefix)
} else {
prefix = path.resolve(this.root, prefix)
if (trail)
prefix += '/'
}
}
if (process.platform === 'win32')
prefix = prefix.replace(/\\/g, '/')
// Mark this as a match
this._emitMatch(index, prefix)
cb()
}
// Returns either 'DIR', 'FILE', or false
Glob.prototype._stat = function (f, cb) {
var abs = this._makeAbs(f)
var needDir = f.slice(-1) === '/'
if (f.length > this.maxLength)
return cb()
if (!this.stat && ownProp(this.cache, abs)) {
var c = this.cache[abs]
if (Array.isArray(c))
c = 'DIR'
// It exists, but maybe not how we need it
if (!needDir || c === 'DIR')
return cb(null, c)
if (needDir && c === 'FILE')
return cb()
// otherwise we have to stat, because maybe c=true
// if we know it exists, but not what it is.
}
var exists
var stat = this.statCache[abs]
if (stat !== undefined) {
if (stat === false)
return cb(null, stat)
else {
var type = stat.isDirectory() ? 'DIR' : 'FILE'
if (needDir && type === 'FILE')
return cb()
else
return cb(null, type, stat)
}
}
var self = this
var statcb = inflight('stat\0' + abs, lstatcb_)
if (statcb)
self.fs.lstat(abs, statcb)
function lstatcb_ (er, lstat) {
if (lstat && lstat.isSymbolicLink()) {
// If it's a symlink, then treat it as the target, unless
// the target does not exist, then treat it as a file.
return self.fs.stat(abs, function (er, stat) {
if (er)
self._stat2(f, abs, null, lstat, cb)
else
self._stat2(f, abs, er, stat, cb)
})
} else {
self._stat2(f, abs, er, lstat, cb)
}
}
}
Glob.prototype._stat2 = function (f, abs, er, stat, cb) {
if (er && (er.code === 'ENOENT' || er.code === 'ENOTDIR')) {
this.statCache[abs] = false
return cb()
}
var needDir = f.slice(-1) === '/'
this.statCache[abs] = stat
if (abs.slice(-1) === '/' && stat && !stat.isDirectory())
return cb(null, false, stat)
var c = true
if (stat)
c = stat.isDirectory() ? 'DIR' : 'FILE'
this.cache[abs] = this.cache[abs] || c
if (needDir && c === 'FILE')
return cb()
return cb(null, c, stat)
}
| ealbertos/dotfiles | vscode.symlink/extensions/ms-mssql.mssql-1.11.1/node_modules/glob/glob.js | JavaScript | mit | 19,362 |
<?php
/*
* This file is part of the symfony package.
* (c) 2004-2006 Fabien Potencier <fabien.potencier@symfony-project.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
* sfGeneratorManager helps generate classes, views and templates for scaffolding, admin interface, ...
*
* @package symfony
* @subpackage generator
* @author Fabien Potencier <fabien.potencier@symfony-project.com>
* @version SVN: $Id: sfGeneratorManager.class.php 17858 2009-05-01 21:22:50Z FabianLange $
*/
class sfGeneratorManager
{
protected
$configuration = null,
$basePath = null;
/**
* Class constructor.
*
* @param sfProjectConfiguration $configuration A sfProjectConfiguration instance
* @param string $basePath The base path for file generation
*
* @see initialize()
*/
public function __construct(sfProjectConfiguration $configuration, $basePath = null)
{
$this->configuration = $configuration;
$this->basePath = $basePath;
}
/**
* Initializes the sfGeneratorManager instance.
*
* @param sfProjectConfiguration $configuration A sfProjectConfiguration instance
* @deprecated
*/
public function initialize(sfProjectConfiguration $configuration)
{
// DEPRECATED
}
/**
* Returns the current configuration instance.
*
* @return sfProjectConfiguration A sfProjectConfiguration instance
*/
public function getConfiguration()
{
return $this->configuration;
}
/**
* Gets the base path to use when generating files.
*
* @return string The base path
*/
public function getBasePath()
{
if (is_null($this->basePath))
{
// for BC
$this->basePath = sfConfig::get('sf_module_cache_dir');
}
return $this->basePath;
}
/**
* Sets the base path to use when generating files.
*
* @param string $basePath The base path
*/
public function setBasePath($basePath)
{
$this->basePath = $basePath;
}
/**
* Saves some content.
*
* @param string $path The relative path
* @param string $content The content
*/
public function save($path, $content)
{
$path = $this->getBasePath().DIRECTORY_SEPARATOR.$path;
if (!is_dir(dirname($path)))
{
$current_umask = umask(0000);
if (false === @mkdir(dirname($path), 0777, true))
{
throw new sfCacheException(sprintf('Failed to make cache directory "%s".', dirname($path)));
}
umask($current_umask);
}
if (false === $ret = @file_put_contents($path, $content))
{
throw new sfCacheException(sprintf('Failed to write cache file "%s".', $path));
}
return $ret;
}
/**
* Generates classes and templates for a given generator class.
*
* @param string $generatorClass The generator class name
* @param array $param An array of parameters
*
* @return string The cache for the configuration file
*/
public function generate($generatorClass, $param)
{
$generator = new $generatorClass($this);
return $generator->generate($param);
}
}
| serg-smirnoff/symfony-pposter | symfony/lib/symfony/generator/sfGeneratorManager.class.php | PHP | mit | 3,181 |
.noscript-two {
color: blue;
}
| pingjiang/uncss | tests/selectors/unused/noscript.css | CSS | mit | 33 |
require 'rails_helper'
RSpec.describe "Stylesheets", type: :request do
require "sprockets"
let(:css) do
assets = Rails.application.assets
assets.find_asset("active_admin.css")
end
it "should successfully render the scss stylesheets using sprockets" do
expect(css).to_not eq nil
end
it "should not have any syntax errors" do
expect(css.to_s).to_not include("Syntax error:")
end
end
| cmunozgar/activeadmin | spec/requests/stylesheets_spec.rb | Ruby | mit | 415 |
// Boost.Geometry (aka GGL, Generic Geometry Library)
// Copyright (c) 2007-2012 Barend Gehrels, Amsterdam, the Netherlands.
// Copyright (c) 2008-2012 Bruno Lalande, Paris, France.
// Copyright (c) 2009-2012 Mateusz Loskot, London, UK.
// Copyright (c) 2014 Adam Wulkiewicz, Lodz, Poland.
// Parts of Boost.Geometry are redesigned from Geodan's Geographic Library
// (geolib/GGL), copyright (c) 1995-2010 Geodan, Amsterdam, the Netherlands.
// Use, modification and distribution is subject to the Boost Software License,
// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#ifndef BOOST_GEOMETRY_ALGORITHMS_CORRECT_HPP
#define BOOST_GEOMETRY_ALGORITHMS_CORRECT_HPP
#include <algorithm>
#include <cstddef>
#include <functional>
#include <boost/mpl/assert.hpp>
#include <boost/range.hpp>
#include <boost/type_traits/remove_reference.hpp>
#include <boost/variant/apply_visitor.hpp>
#include <boost/variant/static_visitor.hpp>
#include <boost/variant/variant_fwd.hpp>
#include <boost/geometry/algorithms/detail/interior_iterator.hpp>
#include <boost/geometry/core/closure.hpp>
#include <boost/geometry/core/cs.hpp>
#include <boost/geometry/core/exterior_ring.hpp>
#include <boost/geometry/core/interior_rings.hpp>
#include <boost/geometry/core/mutable_range.hpp>
#include <boost/geometry/core/ring_type.hpp>
#include <boost/geometry/core/tags.hpp>
#include <boost/geometry/geometries/concepts/check.hpp>
#include <boost/geometry/algorithms/area.hpp>
#include <boost/geometry/algorithms/disjoint.hpp>
#include <boost/geometry/algorithms/detail/multi_modify.hpp>
#include <boost/geometry/util/order_as_direction.hpp>
namespace boost { namespace geometry
{
// Silence warning C4127: conditional expression is constant
#if defined(_MSC_VER)
#pragma warning(push)
#pragma warning(disable : 4127)
#endif
#ifndef DOXYGEN_NO_DETAIL
namespace detail { namespace correct
{
template <typename Geometry>
struct correct_nop
{
static inline void apply(Geometry& )
{}
};
template <typename Box, std::size_t Dimension, std::size_t DimensionCount>
struct correct_box_loop
{
typedef typename coordinate_type<Box>::type coordinate_type;
static inline void apply(Box& box)
{
if (get<min_corner, Dimension>(box) > get<max_corner, Dimension>(box))
{
// Swap the coordinates
coordinate_type max_value = get<min_corner, Dimension>(box);
coordinate_type min_value = get<max_corner, Dimension>(box);
set<min_corner, Dimension>(box, min_value);
set<max_corner, Dimension>(box, max_value);
}
correct_box_loop
<
Box, Dimension + 1, DimensionCount
>::apply(box);
}
};
template <typename Box, std::size_t DimensionCount>
struct correct_box_loop<Box, DimensionCount, DimensionCount>
{
static inline void apply(Box& )
{}
};
// Correct a box: make min/max correct
template <typename Box>
struct correct_box
{
static inline void apply(Box& box)
{
// Currently only for Cartesian coordinates
// (or spherical without crossing dateline)
// Future version: adapt using strategies
correct_box_loop
<
Box, 0, dimension<Box>::type::value
>::apply(box);
}
};
// Close a ring, if not closed
template <typename Ring, typename Predicate>
struct correct_ring
{
typedef typename point_type<Ring>::type point_type;
typedef typename coordinate_type<Ring>::type coordinate_type;
typedef typename strategy::area::services::default_strategy
<
typename cs_tag<point_type>::type,
point_type
>::type strategy_type;
typedef detail::area::ring_area
<
order_as_direction<geometry::point_order<Ring>::value>::value,
geometry::closure<Ring>::value
> ring_area_type;
static inline void apply(Ring& r)
{
// Check close-ness
if (boost::size(r) > 2)
{
// check if closed, if not, close it
bool const disjoint = geometry::disjoint(*boost::begin(r), *(boost::end(r) - 1));
closure_selector const s = geometry::closure<Ring>::value;
if (disjoint && (s == closed))
{
geometry::append(r, *boost::begin(r));
}
if (! disjoint && s != closed)
{
// Open it by removing last point
geometry::traits::resize<Ring>::apply(r, boost::size(r) - 1);
}
}
// Check area
Predicate predicate;
typedef typename default_area_result<Ring>::type area_result_type;
area_result_type const zero = area_result_type();
if (predicate(ring_area_type::apply(r, strategy_type()), zero))
{
std::reverse(boost::begin(r), boost::end(r));
}
}
};
// Correct a polygon: normalizes all rings, sets outer ring clockwise, sets all
// inner rings counter clockwise (or vice versa depending on orientation)
template <typename Polygon>
struct correct_polygon
{
typedef typename ring_type<Polygon>::type ring_type;
typedef typename default_area_result<Polygon>::type area_result_type;
static inline void apply(Polygon& poly)
{
correct_ring
<
ring_type,
std::less<area_result_type>
>::apply(exterior_ring(poly));
typename interior_return_type<Polygon>::type
rings = interior_rings(poly);
for (typename detail::interior_iterator<Polygon>::type
it = boost::begin(rings); it != boost::end(rings); ++it)
{
correct_ring
<
ring_type,
std::greater<area_result_type>
>::apply(*it);
}
}
};
}} // namespace detail::correct
#endif // DOXYGEN_NO_DETAIL
#ifndef DOXYGEN_NO_DISPATCH
namespace dispatch
{
template <typename Geometry, typename Tag = typename tag<Geometry>::type>
struct correct: not_implemented<Tag>
{};
template <typename Point>
struct correct<Point, point_tag>
: detail::correct::correct_nop<Point>
{};
template <typename LineString>
struct correct<LineString, linestring_tag>
: detail::correct::correct_nop<LineString>
{};
template <typename Segment>
struct correct<Segment, segment_tag>
: detail::correct::correct_nop<Segment>
{};
template <typename Box>
struct correct<Box, box_tag>
: detail::correct::correct_box<Box>
{};
template <typename Ring>
struct correct<Ring, ring_tag>
: detail::correct::correct_ring
<
Ring,
std::less<typename default_area_result<Ring>::type>
>
{};
template <typename Polygon>
struct correct<Polygon, polygon_tag>
: detail::correct::correct_polygon<Polygon>
{};
template <typename MultiPoint>
struct correct<MultiPoint, multi_point_tag>
: detail::correct::correct_nop<MultiPoint>
{};
template <typename MultiLineString>
struct correct<MultiLineString, multi_linestring_tag>
: detail::correct::correct_nop<MultiLineString>
{};
template <typename Geometry>
struct correct<Geometry, multi_polygon_tag>
: detail::multi_modify
<
Geometry,
detail::correct::correct_polygon
<
typename boost::range_value<Geometry>::type
>
>
{};
} // namespace dispatch
#endif // DOXYGEN_NO_DISPATCH
namespace resolve_variant {
template <typename Geometry>
struct correct
{
static inline void apply(Geometry& geometry)
{
concepts::check<Geometry const>();
dispatch::correct<Geometry>::apply(geometry);
}
};
template <BOOST_VARIANT_ENUM_PARAMS(typename T)>
struct correct<boost::variant<BOOST_VARIANT_ENUM_PARAMS(T)> >
{
struct visitor: boost::static_visitor<void>
{
template <typename Geometry>
void operator()(Geometry& geometry) const
{
correct<Geometry>::apply(geometry);
}
};
static inline void
apply(boost::variant<BOOST_VARIANT_ENUM_PARAMS(T)>& geometry)
{
boost::apply_visitor(visitor(), geometry);
}
};
} // namespace resolve_variant
/*!
\brief Corrects a geometry
\details Corrects a geometry: all rings which are wrongly oriented with respect
to their expected orientation are reversed. To all rings which do not have a
closing point and are typed as they should have one, the first point is
appended. Also boxes can be corrected.
\ingroup correct
\tparam Geometry \tparam_geometry
\param geometry \param_geometry which will be corrected if necessary
\qbk{[include reference/algorithms/correct.qbk]}
*/
template <typename Geometry>
inline void correct(Geometry& geometry)
{
resolve_variant::correct<Geometry>::apply(geometry);
}
#if defined(_MSC_VER)
#pragma warning(pop)
#endif
}} // namespace boost::geometry
#endif // BOOST_GEOMETRY_ALGORITHMS_CORRECT_HPP
| nginnever/zogminer | tests/deps/boost/geometry/algorithms/correct.hpp | C++ | mit | 9,374 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.