answer stringlengths 15 1.25M |
|---|
<!
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="../../resources/js-test-style.css"/>
<script src="../../resources/js-test-pre.js"></script>
<script src="../resources/webgl-test.js"></script>
<script src="../resources/webgl-test-utils.js"></script>
</head>
<body>
<script id="vshader" type="x-shader/x-vertex">
attribute vec3 aOne;
attribute vec2 aTwo;
void main() {
gl_Position = vec4(aOne, 1.0) + vec4(aTwo, 0.0, 1.0);
}
</script>
<script id="fshader" type="x-shader/x-fragment">
void main() {
gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0);
}
</script>
<div id="description"></div>
<div id="console"></div>
<script>
"use strict";
description("Test of drawArrays with out-of-bounds parameters");
var wtu = WebGLTestUtils;
var context = wtu.create3DContext();
var program = wtu.loadStandardProgram(context);
context.useProgram(program);
var vertexObject = context.createBuffer();
context.bindBuffer(context.ARRAY_BUFFER, vertexObject);
context.<API key>(0);
debug("Test empty buffer")
context.bufferData(context.ARRAY_BUFFER, new Float32Array([ ]), context.STATIC_DRAW);
context.vertexAttribPointer(0, 3, context.FLOAT, false, 0, 0);
<API key>(context, context.INVALID_OPERATION, "context.drawArrays(context.TRIANGLES, 0, 1)");
<API key>(context, context.INVALID_OPERATION, "context.drawArrays(context.TRIANGLES, 0, 10000)");
<API key>(context, context.INVALID_OPERATION, "context.drawArrays(context.TRIANGLES, 0, 10000000000000)");
<API key>(context, context.INVALID_VALUE, "context.drawArrays(context.TRIANGLES, 0, -1)");
<API key>(context, context.NO_ERROR, "context.drawArrays(context.TRIANGLES, 1, 0)");
<API key>(context, context.INVALID_VALUE, "context.drawArrays(context.TRIANGLES, -1, 0)");
<API key>(context, context.NO_ERROR, "context.drawArrays(context.TRIANGLES, 0, 0)");
<API key>(context, context.NO_ERROR, "context.drawArrays(context.TRIANGLES, 100, 0)");
<API key>(context, context.INVALID_VALUE, "context.drawArrays(context.TRIANGLES, 1, -1)");
<API key>(context, context.INVALID_VALUE, "context.drawArrays(context.TRIANGLES, -1, 1)");
debug("")
debug("Test buffer with 3 float vectors")
context.bufferData(context.ARRAY_BUFFER, new Float32Array([ 0,0.5,0, -0.5,-0.5,0, 0.5,-0.5,0 ]), context.STATIC_DRAW);
context.vertexAttribPointer(0, 3, context.FLOAT, false, 0, 0);
<API key>(context, context.NO_ERROR, "context.drawArrays(context.TRIANGLES, 0, 3)");
<API key>(context, context.INVALID_ENUM, "context.drawArrays(0x0009, 0, 3)"); // GL_POLYGON
<API key>(context, context.INVALID_OPERATION, "context.drawArrays(context.TRIANGLES, 3, 2)");
<API key>(context, context.INVALID_OPERATION, "context.drawArrays(context.TRIANGLES, 0, 10000)");
<API key>(context, context.INVALID_OPERATION, "context.drawArrays(context.TRIANGLES, 0, 10000000000000)");
<API key>(context, context.INVALID_VALUE, "context.drawArrays(context.TRIANGLES, 0, -1)");
<API key>(context, context.INVALID_VALUE, "context.drawArrays(context.TRIANGLES, -1, 0)");
<API key>(context, context.NO_ERROR, "context.drawArrays(context.TRIANGLES, 0, 0)");
<API key>(context, context.NO_ERROR, "context.drawArrays(context.TRIANGLES, 100, 0)");
<API key>(context, context.INVALID_VALUE, "context.drawArrays(context.TRIANGLES, 1, -1)");
<API key>(context, context.INVALID_VALUE, "context.drawArrays(context.TRIANGLES, -1, 1)");
debug("")
debug("Test buffer with interleaved (3+2) float vectors")
var program2 = wtu.setupProgram(context, ["vshader", "fshader"], [ "aOne", "aTwo" ]);
if (!program2) {
testFailed("failed to create test program");
}
var vbo = context.createBuffer();
context.bindBuffer(context.ARRAY_BUFFER, vbo);
// enough for 9 vertices, so 3 triangles
context.bufferData(context.ARRAY_BUFFER, new Float32Array(9*5), context.STATIC_DRAW);
// bind first 3 elements, with a stride of 5 float elements
context.vertexAttribPointer(0, 3, context.FLOAT, false, 5*4, 0);
// bind 2 elements, starting after the first 3; same stride of 5 float elements
context.vertexAttribPointer(1, 2, context.FLOAT, false, 5*4, 3*4);
context.<API key>(0);
context.<API key>(1);
<API key>(context, context.NO_ERROR, "context.drawArrays(context.TRIANGLES, 0, 9)");
// negative values must generate INVALID_VALUE; they can never be valid
<API key>(context, context.INVALID_VALUE, "context.drawArrays(context.TRIANGLES, 0, -500)");
<API key>(context, context.INVALID_VALUE, "context.drawArrays(context.TRIANGLES, -200, 1)");
<API key>(context, context.INVALID_VALUE, "context.drawArrays(context.TRIANGLES, -200, -500)");
// 0xffffffff needs to convert to a 'long' IDL argument as -1, as per
// WebIDL 4.1.7. JS ToInt32(0xffffffff) == -1, which is the first step
// of the conversion. Thus INVALID_VALUE.
<API key>(context, context.INVALID_VALUE, "context.drawArrays(context.TRIANGLES, 0, 0xffffffff)");
<API key>(context, context.INVALID_VALUE, "context.drawArrays(context.TRIANGLES, 0xffffffff, 1)");
<API key>(context, context.INVALID_VALUE, "context.drawArrays(context.TRIANGLES, 0xffffffff, 0xffffffff)");
// values that could otherwise be valid but aren't due to bindings generate
// INVALID_OPERATION
<API key>(context, context.INVALID_OPERATION, "context.drawArrays(context.TRIANGLES, 0, 200)");
<API key>(context, context.INVALID_OPERATION, "context.drawArrays(context.TRIANGLES, 0, 0x7fffffff)");
<API key>(context, context.INVALID_OPERATION, "context.drawArrays(context.TRIANGLES, 0x7fffffff, 1)");
<API key>(context, context.INVALID_OPERATION, "context.drawArrays(context.TRIANGLES, 0x7fffffff, 0x7fffffff)");
debug("")
var successfullyParsed = true;
</script>
<script src="../../resources/js-test-post.js"></script>
</body>
</html> |
<?php
Yii::import('zii.widgets.grid.CGridView');
Yii::import('bootstrap.widgets.TbDataColumn');
/**
* Bootstrap Zii grid view.
*/
class TbGridView extends CGridView
{
// Table types.
const TYPE_STRIPED = 'striped';
const TYPE_BORDERED = 'bordered';
const TYPE_CONDENSED = 'condensed';
const TYPE_HOVER = 'hover';
/**
* @var string|array the table type.
* Valid values are 'striped', 'bordered', ' condensed' and/or 'hover'.
*/
public $type;
/**
* @var string the CSS class name for the pager container. Defaults to 'pagination'.
*/
public $pagerCssClass = 'pagination';
/**
* @var array the configuration for the pager.
* Defaults to <code>array('class'=>'ext.bootstrap.widgets.TbPager')</code>.
*/
public $pager = array('class'=>'bootstrap.widgets.TbPager');
/**
* @var string the URL of the CSS file used by this grid view.
* Defaults to false, meaning that no CSS will be included.
*/
public $cssFile = false;
/**
* @var bool whether to make the grid responsive
*/
public $responsiveTable = false;
/**
* Initializes the widget.
*/
public function init()
{
parent::init();
$classes = array('table');
if (isset($this->type))
{
if (is_string($this->type))
$this->type = explode(' ', $this->type);
$validTypes = array(self::TYPE_STRIPED, self::TYPE_BORDERED, self::TYPE_CONDENSED, self::TYPE_HOVER);
if (!empty($this->type))
{
foreach ($this->type as $type)
{
if (in_array($type, $validTypes))
$classes[] = 'table-'.$type;
}
}
}
if (!empty($classes))
{
$classes = implode(' ', $classes);
if (isset($this->itemsCssClass))
$this->itemsCssClass .= ' '.$classes;
else
$this->itemsCssClass = $classes;
}
$popover = Yii::app()->bootstrap->popoverSelector;
$tooltip = Yii::app()->bootstrap->tooltipSelector;
$afterAjaxUpdate = "js:function() {
jQuery('.popover').remove();
jQuery('{$popover}').popover();
jQuery('.tooltip').remove();
jQuery('{$tooltip}').tooltip();
}";
if (!isset($this->afterAjaxUpdate))
$this->afterAjaxUpdate = $afterAjaxUpdate;
}
/**
* Creates column objects and initializes them.
*/
protected function initColumns()
{
foreach ($this->columns as $i => $column)
{
if (is_array($column) && !isset($column['class']))
$this->columns[$i]['class'] = 'bootstrap.widgets.TbDataColumn';
}
parent::initColumns();
if($this->responsiveTable)
$this->writeResponsiveCss();
}
/**
* Creates a column based on a shortcut column specification string.
* @param mixed $text the column specification string
* @return \TbDataColumn|\CDataColumn the column instance
* @throws CException if the column format is incorrect
*/
protected function createDataColumn($text)
{
if (!preg_match('/^([\w\.]+)(:(\w*))?(:(.*))?$/', $text, $matches))
throw new CException(Yii::t('zii', 'The column must be specified in the format of "Name:Type:Label", where "Type" and "Label" are optional.'));
$column = new TbDataColumn($this);
$column->name = $matches[1];
if (isset($matches[3]) && $matches[3] !== '')
$column->type = $matches[3];
if (isset($matches[5]))
$column->header = $matches[5];
return $column;
}
/**
* Writes responsiveCSS
*/
protected function writeResponsiveCss()
{
$cnt = 1; $labels='';
foreach($this->columns as $column)
{
ob_start();
$column->renderHeaderCell();
$name = strip_tags(ob_get_clean());
$labels .= "td:nth-of-type($cnt):before { content: '{$name}'; }\n";
$cnt++;
}
$css = <<<EOD
@media
only screen and (max-width: 760px),
(min-device-width: 768px) and (max-device-width: 1024px) {
/* Force table to not be like tables anymore */
#{$this->id} table,#{$this->id} thead,#{$this->id} tbody,#{$this->id} th,#{$this->id} td,#{$this->id} tr {
display: block;
}
/* Hide table headers (but not display: none;, for accessibility) */
#{$this->id} thead tr {
position: absolute;
top: -9999px;
left: -9999px;
}
#{$this->id} tr { border: 1px solid #ccc; }
#{$this->id} td {
/* Behave like a "row" */
border: none;
border-bottom: 1px solid #eee;
position: relative;
padding-left: 50%;
}
#{$this->id} td:before {
/* Now like a table header */
position: absolute;
/* Top/left values mimic padding */
top: 6px;
left: 6px;
width: 45%;
padding-right: 10px;
white-space: nowrap;
}
.grid-view .button-column {
text-align: left;
width:auto;
}
/*
Label the data
*/
{$labels}
}
EOD;
Yii::app()->clientScript->registerCss(__CLASS__.'#'.$this->id, $css);
}
} |
#ifndef <API key>
#define <API key>
#pragma once
#include "chrome/browser/extensions/extension_function.h"
class ShowInfoBarFunction : public <API key> {
virtual ~ShowInfoBarFunction() {}
virtual bool RunImpl() OVERRIDE;
<API key>("experimental.infobars.show")
};
#endif // <API key> |
#ifndef <API key>
#define <API key>
#include "third_party/blink/public/mojom/notifications/notification.mojom-blink.h"
#include "third_party/blink/renderer/modules/modules_export.h"
namespace WTF {
class String;
}
namespace blink {
class ExceptionState;
class ExecutionContext;
class NotificationOptions;
// Creates a mojom::blink::NotificationData object based on the
// developer-provided notification options. An exception will be thrown on the
// ExceptionState when the given options do not match the constraints imposed by
// the specification.
MODULES_EXPORT mojom::blink::NotificationDataPtr <API key>(
ExecutionContext* context,
const String& title,
const NotificationOptions* options,
ExceptionState& exception_state);
} // namespace blink
#endif // <API key> |
{{+bindTo:partials.<API key>}}
<b><font color="#cc0000">
NOTE:
Deprecation of the technologies described here has been announced
for platforms other than ChromeOS.<br/>
Please visit our
<a href="/native-client/migration">migration guide</a>
for details.
</font></b>
<hr/><section id="tutorial">
<h1 id="tutorial">Tutorial</h1>
<p>This section contains a multi-part tutorial that explains how to get started
developing applications with Native Client.</p>
<ul class="small-gap">
<li><a class="reference internal" href="/native-client/devguide/tutorial/tutorial-part1.html"><em>C++ Tutorial: Getting Started (Part 1)</em></a></li>
<li><a class="reference internal" href="/native-client/devguide/tutorial/tutorial-part2.html"><em>C++ Tutorial: Getting Started (Part 2)</em></a></li>
</ul>
</section>
{{/partials.<API key>}} |
#ifndef <API key>
#define <API key>
#include <jni.h>
void InstallHandlers();
bool <API key>(JNIEnv* env);
#endif // <API key> |
from django.contrib.gis.db.models import Collect, Count, Extent, F, Union
from django.contrib.gis.geometry.backend import Geometry
from django.contrib.gis.geos import GEOSGeometry, MultiPoint, Point
from django.db import connection
from django.test import TestCase, skipUnlessDBFeature
from django.test.utils import override_settings
from django.utils import timezone
from ..utils import no_oracle
from .models import (
Article, Author, Book, City, DirectoryEntry, Event, Location, Parcel,
)
@skipUnlessDBFeature("gis_enabled")
class RelatedGeoModelTest(TestCase):
fixtures = ['initial']
def <API key>(self):
"Testing `select_related` on geographic models (see #7126)."
qs1 = City.objects.order_by('id')
qs2 = City.objects.order_by('id').select_related()
qs3 = City.objects.order_by('id').select_related('location')
# Reference data for what's in the fixtures.
cities = (
('Aurora', 'TX', -97.516111, 33.058333),
('Roswell', 'NM', -104.528056, 33.387222),
('Kecksburg', 'PA', -79.460734, 40.18476),
)
for qs in (qs1, qs2, qs3):
for ref, c in zip(cities, qs):
nm, st, lon, lat = ref
self.assertEqual(nm, c.name)
self.assertEqual(st, c.state)
self.assertEqual(Point(lon, lat, srid=c.location.point.srid), c.location.point)
@skipUnlessDBFeature("<API key>")
def <API key>(self):
"Testing the `Extent` aggregate on related geographic models."
# This combines the Extent and Union aggregates into one query
aggs = City.objects.aggregate(Extent('location__point'))
# One for all locations, one that excludes New Mexico (Roswell).
all_extent = (-104.528056, 29.763374, -79.460734, 40.18476)
txpa_extent = (-97.516111, 29.763374, -79.460734, 40.18476)
e1 = City.objects.aggregate(Extent('location__point'))['<API key>']
e2 = City.objects.exclude(state='NM').aggregate(Extent('location__point'))['<API key>']
e3 = aggs['<API key>']
# The tolerance value is to four decimal places because of differences
# between the Oracle and PostGIS spatial backends on the extent calculation.
tol = 4
for ref, e in [(all_extent, e1), (txpa_extent, e2), (all_extent, e3)]:
for ref_val, e_val in zip(ref, e):
self.assertAlmostEqual(ref_val, e_val, tol)
@skipUnlessDBFeature("<API key>")
def <API key>(self):
"""
Test annotation with Extent GeoAggregate.
"""
cities = City.objects.annotate(points_extent=Extent('location__point')).order_by('name')
tol = 4
self.assertAlmostEqual(
cities[0].points_extent,
(-97.516111, 33.058333, -97.516111, 33.058333),
tol
)
@skipUnlessDBFeature('supports_union_aggr')
def <API key>(self):
"Testing the `Union` aggregate on related geographic models."
# This combines the Extent and Union aggregates into one query
aggs = City.objects.aggregate(Union('location__point'))
# These are the points that are components of the aggregate geographic
# union that is returned. Each point # corresponds to City PK.
p1 = Point(-104.528056, 33.387222)
p2 = Point(-97.516111, 33.058333)
p3 = Point(-79.460734, 40.18476)
p4 = Point(-96.801611, 32.782057)
p5 = Point(-95.363151, 29.763374)
# The second union aggregate is for a union
# query that includes limiting information in the WHERE clause (in other
# words a `.filter()` precedes the call to `.aggregate(Union()`).
ref_u1 = MultiPoint(p1, p2, p4, p5, p3, srid=4326)
ref_u2 = MultiPoint(p2, p3, srid=4326)
u1 = City.objects.aggregate(Union('location__point'))['<API key>']
u2 = City.objects.exclude(
name__in=('Roswell', 'Houston', 'Dallas', 'Fort Worth'),
).aggregate(Union('location__point'))['<API key>']
u3 = aggs['<API key>']
self.assertEqual(type(u1), MultiPoint)
self.assertEqual(type(u3), MultiPoint)
# Ordering of points in the result of the union is not defined and
# <API key> (DB backend, GEOS version)
self.assertSetEqual({p.ewkt for p in ref_u1}, {p.ewkt for p in u1})
self.assertSetEqual({p.ewkt for p in ref_u2}, {p.ewkt for p in u2})
self.assertSetEqual({p.ewkt for p in ref_u1}, {p.ewkt for p in u3})
def <API key>(self):
"Testing that calling select_related on a query over a model with an FK to a model subclass works"
# Regression test for #9752.
list(DirectoryEntry.objects.all().select_related())
def <API key>(self):
"Testing F() expressions on GeometryFields."
# Constructing a dummy parcel border and getting the City instance for
# assigning the FK.
b1 = GEOSGeometry(
'POLYGON((-97.501205 33.052520,-97.501205 33.052576,'
'-97.501150 33.052576,-97.501150 33.052520,-97.501205 33.052520))',
srid=4326
)
pcity = City.objects.get(name='Aurora')
# First parcel has incorrect center point that is equal to the City;
# it also has a second border that is different from the first as a
# 100ft buffer around the City.
c1 = pcity.location.point
c2 = c1.transform(2276, clone=True)
b2 = c2.buffer(100)
Parcel.objects.create(name='P1', city=pcity, center1=c1, center2=c2, border1=b1, border2=b2)
# Now creating a second Parcel where the borders are the same, just
# in different coordinate systems. The center points are also the
# same (but in different coordinate systems), and this time they
# actually correspond to the centroid of the border.
c1 = b1.centroid
c2 = c1.transform(2276, clone=True)
Parcel.objects.create(name='P2', city=pcity, center1=c1, center2=c2, border1=b1, border2=b1)
# Should return the second Parcel, which has the center within the
# border.
qs = Parcel.objects.filter(center1__within=F('border1'))
self.assertEqual(1, len(qs))
self.assertEqual('P2', qs[0].name)
if connection.features.supports_transform:
# This time center2 is in a different coordinate system and needs
# to be wrapped in transformation SQL.
qs = Parcel.objects.filter(center2__within=F('border1'))
self.assertEqual(1, len(qs))
self.assertEqual('P2', qs[0].name)
# Should return the first Parcel, which has the center point equal
# to the point in the City ForeignKey.
qs = Parcel.objects.filter(center1=F('<API key>'))
self.assertEqual(1, len(qs))
self.assertEqual('P1', qs[0].name)
if connection.features.supports_transform:
# This time the city column should be wrapped in transformation SQL.
qs = Parcel.objects.filter(border2__contains=F('<API key>'))
self.assertEqual(1, len(qs))
self.assertEqual('P1', qs[0].name)
def test07_values(self):
"Testing values() and values_list()."
gqs = Location.objects.all()
gvqs = Location.objects.values()
gvlqs = Location.objects.values_list()
# Incrementing through each of the models, dictionaries, and tuples
# returned by each QuerySet.
for m, d, t in zip(gqs, gvqs, gvlqs):
# The values should be Geometry objects and not raw strings returned
# by the spatial database.
self.assertIsInstance(d['point'], Geometry)
self.assertIsInstance(t[1], Geometry)
self.assertEqual(m.point, d['point'])
self.assertEqual(m.point, t[1])
@override_settings(USE_TZ=True)
def test_07b_values(self):
"Testing values() and values_list() with aware datetime. See #21565."
Event.objects.create(name="foo", when=timezone.now())
list(Event.objects.values_list('when'))
def test08_defer_only(self):
"Testing defer() and only() on Geographic models."
qs = Location.objects.all()
def_qs = Location.objects.defer('point')
for loc, def_loc in zip(qs, def_qs):
self.assertEqual(loc.point, def_loc.point)
def test09_pk_relations(self):
"Ensuring correct primary key column is selected across relations. See #10757."
# The expected ID values -- notice the last two location IDs
# are out of order. Dallas and Houston have location IDs that differ
# from their PKs -- this is done to ensure that the related location
# ID column is selected instead of ID column for the city.
city_ids = (1, 2, 3, 4, 5)
loc_ids = (1, 2, 3, 5, 4)
ids_qs = City.objects.order_by('id').values('id', 'location__id')
for val_dict, c_id, l_id in zip(ids_qs, city_ids, loc_ids):
self.assertEqual(val_dict['id'], c_id)
self.assertEqual(val_dict['location__id'], l_id)
# TODO: fix on Oracle -- qs2 returns an empty result for an unknown reason
@no_oracle
def test10_combine(self):
"Testing the combination of two QuerySets (#10807)."
buf1 = City.objects.get(name='Aurora').location.point.buffer(0.1)
buf2 = City.objects.get(name='Kecksburg').location.point.buffer(0.1)
qs1 = City.objects.filter(<API key>=buf1)
qs2 = City.objects.filter(<API key>=buf2)
combined = qs1 | qs2
names = [c.name for c in combined]
self.assertEqual(2, len(names))
self.assertIn('Aurora', names)
self.assertIn('Kecksburg', names)
# TODO: fix on Oracle -- get the following error because the SQL is ordered
# by a geometry object, which Oracle apparently doesn't like:
# ORA-22901: cannot compare nested table or VARRAY or LOB attributes of an object type
@no_oracle
def test12a_count(self):
"Testing `Count` aggregate on geo-fields."
# The City, 'Fort Worth' uses the same location as Dallas.
dallas = City.objects.get(name='Dallas')
# Count annotation should be 2 for the Dallas location now.
loc = Location.objects.annotate(num_cities=Count('city')).get(id=dallas.location.id)
self.assertEqual(2, loc.num_cities)
def test12b_count(self):
"Testing `Count` aggregate on non geo-fields."
# Should only be one author (Trevor Paglen) returned by this query, and
# the annotation should have 3 for the number of books, see #11087.
# Also testing with a values(), see #11489.
qs = Author.objects.annotate(num_books=Count('books')).filter(num_books__gt=1)
vqs = Author.objects.values('name').annotate(num_books=Count('books')).filter(num_books__gt=1)
self.assertEqual(1, len(qs))
self.assertEqual(3, qs[0].num_books)
self.assertEqual(1, len(vqs))
self.assertEqual(3, vqs[0]['num_books'])
# TODO: fix on Oracle -- get the following error because the SQL is ordered
# by a geometry object, which Oracle apparently doesn't like:
# ORA-22901: cannot compare nested table or VARRAY or LOB attributes of an object type
@no_oracle
def test13c_count(self):
"Testing `Count` aggregate with `.values()`. See #15305."
qs = Location.objects.filter(id=5).annotate(num_cities=Count('city')).values('id', 'point', 'num_cities')
self.assertEqual(1, len(qs))
self.assertEqual(2, qs[0]['num_cities'])
self.assertIsInstance(qs[0]['point'], GEOSGeometry)
# TODO: The phantom model does appear on Oracle.
@no_oracle
def <API key>(self):
"Testing `select_related` on a nullable ForeignKey."
Book.objects.create(title='Without Author')
b = Book.objects.select_related('author').get(title='Without Author')
# Should be `None`, and not a 'dummy' model.
self.assertIsNone(b.author)
@skipUnlessDBFeature("<API key>")
def test_collect(self):
"""
Testing the `Collect` aggregate.
"""
# Reference query:
# SELECT AsText(ST_Collect("relatedapp_location"."point")) FROM "relatedapp_city" LEFT OUTER JOIN
# "relatedapp_location" ON ("relatedapp_city"."location_id" = "relatedapp_location"."id")
# WHERE "relatedapp_city"."state" = 'TX';
ref_geom = GEOSGeometry(
'MULTIPOINT(-97.516111 33.058333,-96.801611 32.782057,'
'-95.363151 29.763374,-96.801611 32.782057)'
)
coll = City.objects.filter(state='TX').aggregate(Collect('location__point'))['<API key>']
# Even though Dallas and Ft. Worth share same point, Collect doesn't
# consolidate -- that's why 4 points in MultiPoint.
self.assertEqual(4, len(coll))
self.assertTrue(ref_geom.equals(coll))
def <API key>(self):
"Testing doing select_related on the related name manager of a unique FK. See #13934."
qs = Article.objects.select_related('author__article')
# This triggers TypeError when `get_default_columns` has no `local_only`
# keyword. The TypeError is swallowed if QuerySet is actually
# evaluated as list generation swallows TypeError in CPython.
str(qs.query)
def <API key>(self):
"Ensure annotated date querysets work if spatial backend is used. See #14648."
birth_years = [dt.year for dt in
list(Author.objects.annotate(num_books=Count('books')).dates('dob', 'year'))]
birth_years.sort()
self.assertEqual([1950, 1974], birth_years)
# TODO: Related tests for KML, GML, and distance lookups. |
# AUTO-GENERATED by tools/checkspecs.py - DO NOT EDIT
from ....testing import assert_equal
from ..utils import WarpPointsToStd
def <API key>():
input_map = dict(args=dict(argstr='%s',
),
coord_mm=dict(argstr='-mm',
xor=['coord_vox'],
),
coord_vox=dict(argstr='-vox',
xor=['coord_mm'],
),
environ=dict(nohash=True,
usedefault=True,
),
ignore_exception=dict(nohash=True,
usedefault=True,
),
img_file=dict(argstr='-img %s',
mandatory=True,
),
in_coords=dict(argstr='%s',
mandatory=True,
position=-1,
),
out_file=dict(name_source='in_coords',
name_template='%s_warped',
output_name='out_file',
),
premat_file=dict(argstr='-premat %s',
),
std_file=dict(argstr='-std %s',
mandatory=True,
),
terminal_output=dict(nohash=True,
),
warp_file=dict(argstr='-warp %s',
xor=['xfm_file'],
),
xfm_file=dict(argstr='-xfm %s',
xor=['warp_file'],
),
)
inputs = WarpPointsToStd.input_spec()
for key, metadata in list(input_map.items()):
for metakey, value in list(metadata.items()):
yield assert_equal, getattr(inputs.traits()[key], metakey), value
def <API key>():
output_map = dict(out_file=dict(),
)
outputs = WarpPointsToStd.output_spec()
for key, metadata in list(output_map.items()):
for metakey, value in list(metadata.items()):
yield assert_equal, getattr(outputs.traits()[key], metakey), value |
goog.provide('ngmaterial.components.toast');
goog.require('ngmaterial.components.button');
goog.require('ngmaterial.core');
/**
* @ngdoc module
* @name material.components.toast
* @description
* Toast
*/
MdToastDirective['$inject'] = ["$mdToast"];
MdToastProvider['$inject'] = ["$$<API key>"];
angular.module('material.components.toast', [
'material.core',
'material.components.button'
])
.directive('mdToast', MdToastDirective)
.provider('$mdToast', MdToastProvider);
/* ngInject */
function MdToastDirective($mdToast) {
return {
restrict: 'E',
link: function postLink(scope, element) {
element.addClass('_md'); // private md component indicator for styling
// When navigation force destroys an interimElement, then
// listen and $destroy() that interim instance...
scope.$on('$destroy', function() {
$mdToast.destroy();
});
}
};
}
/**
* @ngdoc method
* @name $mdToast#showSimple
*
* @param {string} message The message to display inside the toast
* @description
* Convenience method which builds and shows a simple toast.
*
* @returns {promise} A promise that can be resolved with `$mdToast.hide()` or
* rejected with `$mdToast.cancel()`.
*
*/
/**
* @ngdoc method
* @name $mdToast#simple
*
* @description
* Builds a preconfigured toast.
*
* @returns {obj} a `$mdToastPreset` with the following chainable configuration methods.
*
* _**Note:** These configuration methods are provided in addition to the methods provided by
* the `build()` and `show()` methods below._
*
* <table class="md-api-table methods">
* <thead>
* <tr>
* <th>Method</th>
* <th>Description</th>
* </tr>
* </thead>
* <tbody>
* <tr>
* <td>`.textContent(string)`</td>
* <td>Sets the toast content to the specified string</td>
* </tr>
* <tr>
* <td>`.action(string)`</td>
* <td>
* Adds an action button. <br/>
* If clicked, the promise (returned from `show()`)
* will resolve with the value `'ok'`; otherwise, it is resolved with `true` after a `hideDelay`
* timeout
* </td>
* </tr>
* <tr>
* <td>`.highlightAction(boolean)`</td>
* <td>
* Whether or not the action button will have an additional highlight class.<br/>
* By default the `accent` color will be applied to the action button.
* </td>
* </tr>
* <tr>
* <td>`.highlightClass(string)`</td>
* <td>
* If set, the given class will be applied to the highlighted action button.<br/>
* This allows you to specify the highlight color easily. Highlight classes are `md-primary`, `md-warn`
* and `md-accent`
* </td>
* </tr>
* <tr>
* <td>`.capsule(boolean)`</td>
* <td>Whether or not to add the `md-capsule` class to the toast to provide rounded corners</td>
* </tr>
* <tr>
* <td>`.theme(string)`</td>
* <td>Sets the theme on the toast to the requested theme. Default is `$mdThemingProvider`'s default.</td>
* </tr>
* <tr>
* <td>`.toastClass(string)`</td>
* <td>Sets a class on the toast element</td>
* </tr>
* </tbody>
* </table>
*
*/
/**
* @ngdoc method
* @name $mdToast#updateTextContent
*
* @description
* Updates the content of an existing toast. Useful for updating things like counts, etc.
*
*/
/**
* @ngdoc method
* @name $mdToast#build
*
* @description
* Creates a custom `$mdToastPreset` that you can configure.
*
* @returns {obj} a `$mdToastPreset` with the chainable configuration methods for shows' options (see below).
*/
/**
* @ngdoc method
* @name $mdToast#show
*
* @description Shows the toast.
*
* @param {object} optionsOrPreset Either provide an `$mdToastPreset` returned from `simple()`
* and `build()`, or an options object with the following properties:
*
* - `templateUrl` - `{string=}`: The url of an html template file that will
* be used as the content of the toast. Restrictions: the template must
* have an outer `md-toast` element.
* - `template` - `{string=}`: Same as templateUrl, except this is an actual
* template string.
* - `autoWrap` - `{boolean=}`: Whether or not to automatically wrap the template content with a
* `<div class="md-toast-content">` if one is not provided. Defaults to true. Can be disabled if you provide a
* custom toast directive.
* - `scope` - `{object=}`: the scope to link the template / controller to. If none is specified, it will create a new child scope.
* This scope will be destroyed when the toast is removed unless `preserveScope` is set to true.
* - `preserveScope` - `{boolean=}`: whether to preserve the scope when the element is removed. Default is false
* - `hideDelay` - `{number=}`: How many milliseconds the toast should stay
* active before automatically closing. Set to 0 or false to have the toast stay open until
* closed manually. Default: 3000.
* - `position` - `{string=}`: Sets the position of the toast. <br/>
* Available: any combination of `'bottom'`, `'left'`, `'top'`, `'right'`, `'end'` and `'start'`.
* The properties `'end'` and `'start'` are dynamic and can be used for RTL support.<br/>
* Default combination: `'bottom left'`.
* - `toastClass` - `{string=}`: A class to set on the toast element.
* - `controller` - `{string=}`: The controller to associate with this toast.
* The controller will be injected the local `$mdToast.hide( )`, which is a function
* used to hide the toast.
* - `locals` - `{string=}`: An object containing key/value pairs. The keys will
* be used as names of values to inject into the controller. For example,
* `locals: {three: 3}` would inject `three` into the controller with the value
* of 3.
* - `bindToController` - `bool`: bind the locals to the controller, instead of passing them in.
* - `resolve` - `{object=}`: Similar to locals, except it takes promises as values
* and the toast will not open until the promises resolve.
* - `controllerAs` - `{string=}`: An alias to assign the controller to on the scope.
* - `parent` - `{element=}`: The element to append the toast to. Defaults to appending
* to the root element of the application.
*
* @returns {promise} A promise that can be resolved with `$mdToast.hide()` or
* rejected with `$mdToast.cancel()`. `$mdToast.hide()` will resolve either with a Boolean
* value == 'true' or the value passed as an argument to `$mdToast.hide()`.
* And `$mdToast.cancel()` will resolve the promise with a Boolean value == 'false'
*/
/**
* @ngdoc method
* @name $mdToast#hide
*
* @description
* Hide an existing toast and resolve the promise returned from `$mdToast.show()`.
*
* @param {*=} response An argument for the resolved promise.
*
* @returns {promise} a promise that is called when the existing element is removed from the DOM.
* The promise is resolved with either a Boolean value == 'true' or the value passed as the
* argument to `.hide()`.
*
*/
/**
* @ngdoc method
* @name $mdToast#cancel
*
* @description
* `DEPRECATED` - The promise returned from opening a toast is used only to notify about the closing of the toast.
* As such, there isn't any reason to also allow that promise to be rejected,
* since it's not clear what the difference between resolve and reject would be.
*
* Hide the existing toast and reject the promise returned from
* `$mdToast.show()`.
*
* @param {*=} response An argument for the rejected promise.
*
* @returns {promise} a promise that is called when the existing element is removed from the DOM
* The promise is resolved with a Boolean value == 'false'.
*
*/
function MdToastProvider($$<API key>) {
// Differentiate promise resolves: hide timeout (value == true) and hide action clicks (value == ok).
MdToastController['$inject'] = ["$mdToast", "$scope"];
toastDefaultOptions['$inject'] = ["$animate", "$mdToast", "$mdUtil", "$mdMedia"];
var ACTION_RESOLVE = 'ok';
var activeToastContent;
var $mdToast = $$<API key>('$mdToast')
.setDefaults({
methods: ['position', 'hideDelay', 'capsule', 'parent', 'position', 'toastClass'],
options: toastDefaultOptions
})
.addPreset('simple', {
argOption: 'textContent',
methods: ['textContent', 'content', 'action', 'highlightAction', 'highlightClass', 'theme', 'parent' ],
options: /* ngInject */ ["$mdToast", "$mdTheming", function($mdToast, $mdTheming) {
return {
template:
'<md-toast md-theme="{{ toast.theme }}" ng-class="{\'md-capsule\': toast.capsule}">' +
' <div class="md-toast-content">' +
' <span class="md-toast-text" role="alert" aria-relevant="all" aria-atomic="true">' +
' {{ toast.content }}' +
' </span>' +
' <md-button class="md-action" ng-if="toast.action" ng-click="toast.resolve()" ' +
' ng-class="highlightClasses">' +
' {{ toast.action }}' +
' </md-button>' +
' </div>' +
'</md-toast>',
controller: MdToastController,
theme: $mdTheming.defaultTheme(),
controllerAs: 'toast',
bindToController: true
};
}]
})
.addMethod('updateTextContent', updateTextContent)
.addMethod('updateContent', updateTextContent);
function updateTextContent(newContent) {
activeToastContent = newContent;
}
return $mdToast;
/**
* Controller for the Toast interim elements.
* ngInject
*/
function MdToastController($mdToast, $scope) {
// For compatibility with AngularJS 1.6+, we should always use the $onInit hook in
// interimElements. The $mdCompiler simulates the $onInit hook for all versions.
this.$onInit = function() {
var self = this;
if (self.highlightAction) {
$scope.highlightClasses = [
'md-highlight',
self.highlightClass
]
}
$scope.$watch(function() { return activeToastContent; }, function() {
self.content = activeToastContent;
});
this.resolve = function() {
$mdToast.hide( ACTION_RESOLVE );
};
}
}
/* ngInject */
function toastDefaultOptions($animate, $mdToast, $mdUtil, $mdMedia) {
var SWIPE_EVENTS = '$md.swipeleft $md.swiperight $md.swipeup $md.swipedown';
return {
onShow: onShow,
onRemove: onRemove,
toastClass: '',
position: 'bottom left',
themable: true,
hideDelay: 3000,
autoWrap: true,
transformTemplate: function(template, options) {
var shouldAddWrapper = options.autoWrap && template && !/md-toast-content/g.test(template);
if (shouldAddWrapper) {
// Root element of template will be <md-toast>. We need to wrap all of its content inside of
// of <div class="md-toast-content">. All templates provided here should be static, <API key>
// content (meaning we're not attempting to guard against XSS).
var templateRoot = document.createElement('md-template');
templateRoot.innerHTML = template;
// Iterate through all root children, to detect possible md-toast directives.
for (var i = 0; i < templateRoot.children.length; i++) {
if (templateRoot.children[i].nodeName === 'MD-TOAST') {
var wrapper = angular.element('<div class="md-toast-content">');
// Wrap the children of the `md-toast` directive in jqLite, to be able to append multiple
// nodes with the same execution.
wrapper.append(angular.element(templateRoot.children[i].childNodes));
// Append the new wrapped element to the `md-toast` directive.
templateRoot.children[i].appendChild(wrapper[0]);
}
}
// We have to return the innerHTMl, because we do not want to have the `md-template` element to be
// the root element of our interimElement.
return templateRoot.innerHTML;
}
return template || '';
}
};
function onShow(scope, element, options) {
activeToastContent = options.textContent || options.content; // support deprecated #content method
var isSmScreen = !$mdMedia('gt-sm');
element = $mdUtil.<API key>(element, 'md-toast', true);
options.element = element;
options.onSwipe = function(ev, gesture) {
//Add the relevant swipe class to the element so it can animate correctly
var swipe = ev.type.replace('$md.','');
var direction = swipe.replace('swipe', '');
// If the swipe direction is down/up but the toast came from top/bottom don't fade away
// Unless the screen is small, then the toast always on bottom
if ((direction === 'down' && options.position.indexOf('top') != -1 && !isSmScreen) ||
(direction === 'up' && (options.position.indexOf('bottom') != -1 || isSmScreen))) {
return;
}
if ((direction === 'left' || direction === 'right') && isSmScreen) {
return;
}
element.addClass('md-' + swipe);
$mdUtil.nextTick($mdToast.cancel);
};
options.openClass = toastOpenClass(options.position);
element.addClass(options.toastClass);
// 'top left' -> 'md-top md-left'
options.parent.addClass(options.openClass);
// static is the default position
if ($mdUtil.hasComputedStyle(options.parent, 'position', 'static')) {
options.parent.css('position', 'relative');
}
element.on(SWIPE_EVENTS, options.onSwipe);
element.addClass(isSmScreen ? 'md-bottom' : options.position.split(' ').map(function(pos) {
return 'md-' + pos;
}).join(' '));
if (options.parent) options.parent.addClass('md-toast-animating');
return $animate.enter(element, options.parent).then(function() {
if (options.parent) options.parent.removeClass('md-toast-animating');
});
}
function onRemove(scope, element, options) {
element.off(SWIPE_EVENTS, options.onSwipe);
if (options.parent) options.parent.addClass('md-toast-animating');
if (options.openClass) options.parent.removeClass(options.openClass);
return ((options.$destroy == true) ? element.remove() : $animate.leave(element))
.then(function () {
if (options.parent) options.parent.removeClass('md-toast-animating');
if ($mdUtil.hasComputedStyle(options.parent, 'position', 'static')) {
options.parent.css('position', '');
}
});
}
function toastOpenClass(position) {
// For mobile, always open full-width on bottom
if (!$mdMedia('gt-xs')) {
return '<API key>';
}
return 'md-toast-open-' +
(position.indexOf('top') > -1 ? 'top' : 'bottom');
}
}
}
ngmaterial.components.toast = angular.module("material.components.toast"); |
<div>
Select the initial or parent Job in the build pipeline view.
</div> |
import * as http from 'http';
import * as connect from 'connect';
declare interface StaticFiles {
[key: string]: {
content?: string | undefined;
absolutePath: string;
cacheable: boolean;
hash: string;
sourceMapUrl?: string | undefined;
type: string;
};
}
declare module WebApp {
var defaultArch: string;
var clientPrograms: {
[key: string]: {
format: string;
manifest: any;
version: string;
<API key>?: any;
PUBLIC_SETTINGS: any;
};
};
var connectHandlers: connect.Server;
var rawConnectHandlers: connect.Server;
var httpServer: http.Server;
var connectApp: connect.Server;
function <API key>(): void;
function onListening(callback: Function): void;
}
declare module WebAppInternals {
var NpmModules: {
[key: string]: {
version: string;
module: any;
};
};
function identifyBrowser(userAgentString: string): {
name: string;
major: string;
minor: string;
patch: string;
};
function <API key>(key: string, callback: Function): Function;
function <API key>(arch: string, manifest: any, additionalOptions: any): any;
function <API key>(
staticFiles: StaticFiles,
req: http.IncomingMessage,
res: http.ServerResponse,
next: Function,
): void;
function parsePort(port: string): number;
function <API key>(): void;
function generateBoilerplate(): void;
var staticFiles: StaticFiles;
function <API key>(): boolean;
function <API key>(<API key>: boolean): void;
function <API key>(hookFn: (url: string) => string): void;
function <API key>(bundledJsCssPrefix: string): void;
function addStaticJs(): void;
function getBoilerplate(request: http.IncomingMessage, arch: string): string;
var additionalStaticJs: any;
} |
package org.knowm.xchange.coinone.dto.trade;
import com.fasterxml.jackson.annotation.JsonProperty;
public class <API key> {
private final String result;
private final String errorCode;
private final String orderId;
private final String errorMsg;
public <API key>(
@JsonProperty("result") String result,
@JsonProperty("errorCode") String errorCode,
@JsonProperty("orderId") String orderId,
@JsonProperty("errorMsg") String errorMsg) {
this.result = result;
this.errorCode = errorCode;
this.orderId = orderId;
this.errorMsg = errorMsg;
}
public String getErrorMsg() {
return errorMsg;
}
public String getResult() {
return result;
}
public String getErrorCode() {
return errorCode;
}
public String getOrderId() {
return orderId;
}
} |
var APP = {
Player: function () {
var loader = new THREE.ObjectLoader();
var camera, scene, renderer;
var scripts = {};
this.dom = undefined;
this.width = 500;
this.height = 500;
this.load = function ( json ) {
renderer = new THREE.WebGLRenderer( { antialias: true } );
renderer.setPixelRatio( window.devicePixelRatio );
camera = loader.parse( json.camera );
scene = loader.parse( json.scene );
scripts = {
keydown: [],
keyup: [],
mousedown: [],
mouseup: [],
mousemove: [],
update: []
};
for ( var uuid in json.scripts ) {
var object = scene.getObjectByProperty( 'uuid', uuid, true );
var sources = json.scripts[ uuid ];
for ( var i = 0; i < sources.length; i ++ ) {
var script = sources[ i ];
var events = ( new Function( 'player', 'scene', 'keydown', 'keyup', 'mousedown', 'mouseup', 'mousemove', 'update', script.source + '\nreturn { keydown: keydown, keyup: keyup, mousedown: mousedown, mouseup: mouseup, mousemove: mousemove, update: update };' ).bind( object ) )( this, scene );
for ( var name in events ) {
if ( events[ name ] === undefined ) continue;
if ( scripts[ name ] === undefined ) {
console.warn( 'APP.Player: event type not supported (', name, ')' );
continue;
}
scripts[ name ].push( events[ name ].bind( object ) );
}
}
}
this.dom = renderer.domElement;
};
this.setCamera = function ( value ) {
camera = value;
camera.aspect = this.width / this.height;
camera.<API key>();
};
this.setSize = function ( width, height ) {
this.width = width;
this.height = height;
camera.aspect = this.width / this.height;
camera.<API key>();
renderer.setSize( width, height );
};
var dispatch = function ( array, event ) {
for ( var i = 0, l = array.length; i < l; i ++ ) {
array[ i ]( event );
}
};
var request;
var animate = function ( time ) {
request = <API key>( animate );
dispatch( scripts.update, { time: time } );
renderer.render( scene, camera );
};
this.play = function () {
document.addEventListener( 'keydown', onDocumentKeyDown );
document.addEventListener( 'keyup', onDocumentKeyUp );
document.addEventListener( 'mousedown', onDocumentMouseDown );
document.addEventListener( 'mouseup', onDocumentMouseUp );
document.addEventListener( 'mousemove', onDocumentMouseMove );
request = <API key>( animate );
};
this.stop = function () {
document.removeEventListener( 'keydown', onDocumentKeyDown );
document.removeEventListener( 'keyup', onDocumentKeyUp );
document.removeEventListener( 'mousedown', onDocumentMouseDown );
document.removeEventListener( 'mouseup', onDocumentMouseUp );
document.removeEventListener( 'mousemove', onDocumentMouseMove );
<API key>( request );
};
var onDocumentKeyDown = function ( event ) {
dispatch( scripts.keydown, event );
};
var onDocumentKeyUp = function ( event ) {
dispatch( scripts.keyup, event );
};
var onDocumentMouseDown = function ( event ) {
dispatch( scripts.mousedown, event );
};
var onDocumentMouseUp = function ( event ) {
dispatch( scripts.mouseup, event );
};
var onDocumentMouseMove = function ( event ) {
dispatch( scripts.mousemove, event );
};
}
}; |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html><head><meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
<title>TibiaAPI: E:/dev/misc/ta/tibiaapi/Packets/AdlerChecksum.cs File Reference</title>
<link href="tabs.css" rel="stylesheet" type="text/css">
<link href="doxygen.css" rel="stylesheet" type="text/css">
</head><body>
<!-- Generated by Doxygen 1.5.9 -->
<script type="text/javascript">
<!
function changeDisplayState (e){
var num=this.id.replace(/[^[0-9]/g,'');
var button=this.firstChild;
var sectionDiv=document.getElementById('dynsection'+num);
if (sectionDiv.style.display=='none'||sectionDiv.style.display==''){
sectionDiv.style.display='block';
button.src='open.gif';
}else{
sectionDiv.style.display='none';
button.src='closed.gif';
}
}
function initDynSections(){
var divs=document.<API key>('div');
var sectionCounter=1;
for(var i=0;i<divs.length-1;i++){
if(divs[i].className=='dynheader'&&divs[i+1].className=='dynsection'){
var header=divs[i];
var section=divs[i+1];
var button=header.firstChild;
if (button!='IMG'){
divs[i].insertBefore(document.createTextNode(' '),divs[i].firstChild);
button=document.createElement('img');
divs[i].insertBefore(button,divs[i].firstChild);
}
header.style.cursor='pointer';
header.onclick=changeDisplayState;
header.id='dynheader'+sectionCounter;
button.src='closed.gif';
section.id='dynsection'+sectionCounter;
section.style.display='none';
section.style.marginLeft='14px';
sectionCounter++;
}
}
}
window.onload = initDynSections;
</script>
<div class="navigation" id="top">
<div class="tabs">
<ul>
<li><a href="index.html"><span>Main Page</span></a></li>
<li><a href="namespaces.html"><span>Packages</span></a></li>
<li><a href="annotated.html"><span>Classes</span></a></li>
<li class="current"><a href="files.html"><span>Files</span></a></li>
</ul>
</div>
<div class="tabs">
<ul>
<li><a href="files.html"><span>File List</span></a></li>
<li><a href="globals.html"><span>File Members</span></a></li>
</ul>
</div>
</div>
<div class="contents">
<h1>E:/dev/misc/ta/tibiaapi/Packets/AdlerChecksum.cs File Reference</h1><table border="0" cellpadding="0" cellspacing="0">
<tr><td></td></tr>
<tr><td colspan="2"><br><h2>Classes</h2></td></tr>
<tr><td class="memItemLeft" nowrap align="right" valign="top">class </td><td class="memItemRight" valign="bottom"><a class="el" href="<API key>.html">Tibia.Packets.AdlerChecksum</a></td></tr>
<tr><td colspan="2"><br><h2>Packages</h2></td></tr>
<tr><td class="memItemLeft" nowrap align="right" valign="top">package </td><td class="memItemRight" valign="bottom"><a class="el" href="<API key>.html">Tibia.Packets</a></td></tr>
<tr><td colspan="2"><br><h2>Variables</h2></td></tr>
<tr><td class="memItemLeft" nowrap align="right" valign="top">using </td><td class="memItemRight" valign="bottom"><a class="el" href="_adler_checksum_8cs.html#<API key>">System</a></td></tr>
</table>
<hr><h2>Variable Documentation</h2>
<a class="anchor" name="<API key>"></a><!-- doxytag: member="AdlerChecksum.cs::System" ref="<API key>" args="" -->
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">using <a class="el" href="_timer_8cs.html#<API key>">System</a> </td>
</tr>
</table>
</div>
<div class="memdoc">
<p>
</div>
</div><p>
</div>
<hr size="1"><address style="text-align: right;"><small>Generated on Tue Jul 7 18:50:08 2009 for TibiaAPI by
<a href="http:
<img src="doxygen.png" alt="doxygen" align="middle" border="0"></a> 1.5.9 </small></address>
</body>
</html> |
<section class="accordion-section <?= empty($files) && empty($images) ? 'accordion-collapsed' : '' ?>">
<div class="accordion-title">
<h3><a href="#" class="fa accordion-toggle"></a> <?= t('Attachments') ?></h3>
</div>
<div class="accordion-content">
<?php if ($this->user->hasProjectAccess('<API key>', 'create', $project['id'])): ?>
<div class="buttons-header">
<?= $this->modal->mediumButton('plus', t('Upload a file'), '<API key>', 'create', array('project_id' => $project['id'])) ?>
</div>
<?php endif ?>
<?= $this->render('project_overview/images', array('project' => $project, 'images' => $images)) ?>
<?= $this->render('project_overview/files', array('project' => $project, 'files' => $files)) ?>
</div>
</section> |
package lambdasinaction.chap8;
import java.util.function.Consumer;
public class OnlineBankingLambda {
public static void main(String[] args) {
new OnlineBankingLambda().processCustomer(1337, (Customer c) -> System.out.println("Hello!"));
}
public void processCustomer(int id, Consumer<Customer> makeCustomerHappy){
Customer c = Database.getCustomerWithId(id);
makeCustomerHappy.accept(c);
}
// dummy Customer class
static private class Customer {}
// dummy Database class
static private class Database{
static Customer getCustomerWithId(int id){ return new Customer();}
}
} |
// SeqAn - The Library for Sequence Analysis
// modification, are permitted provided that the following conditions are met:
// 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
// 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.
// Implementation of the StringSet specialization Owner.
#ifndef <API key>
#define <API key>
namespace seqan {
// Forwards
// Tags, Classes, Enums
// The tag Owner is defined in string_set_base since it is the default
// specialization.
// template <typename TSpec = Default>
// struct Owner;
// TODO(holtgrew): Change name of specialization to Owner StringSet.
template <typename TString>
class StringSet<TString, Owner<Default> >
{
public:
typedef String<TString> TStrings;
typedef typename StringSetLimits<StringSet>::Type TLimits;
typedef typename Concatenator<StringSet>::Type TConcatenator;
TStrings strings;
TLimits limits;
bool limitsValid; // is true if limits contains the cumulative sum of the sequence lengths
TConcatenator concat;
StringSet()
: limitsValid(true)
{
appendValue(limits, 0);
}
// Subscription operators; have to be defined in class def.
template <typename TPos>
inline typename Reference<StringSet>::Type
operator[] (TPos pos)
{
return value(*this, pos);
}
template <typename TPos>
inline typename Reference<StringSet const>::Type
operator[] (TPos pos) const
{
return value(*this, pos);
}
};
// Metafunctions
// Functions
// Function appendValue()
template <typename TString, typename TString2, typename TExpand >
inline void appendValue(
StringSet<TString, Owner<Default> > & me,
TString2 const & obj,
Tag<TExpand> const & tag)
{
if (<API key>(me))
appendValue(me.limits, lengthSum(me) + length(obj), tag);
appendValue(me.strings, obj, tag);
}
// Function assignValue()
template <typename TString, typename TSpec, typename TPos, typename TSequence >
inline void assignValue(
StringSet<TString, Owner<TSpec> > & me,
TPos pos,
TSequence const & seq)
{
typedef StringSet<TString, Owner<TSpec> > TStringSet;
typedef typename Size<TStringSet>::Type TSize;
typedef typename StringSetLimits<TStringSet>::Type TLimits;
typedef typename Value<TLimits>::Type TLimitValue;
typedef typename MakeSigned<TLimitValue>::Type TSignedLimitValue;
TSignedLimitValue oldSize = length(me[pos]);
assign(me[pos], seq);
if (<API key>(me))
{
TSignedLimitValue delta = (TSignedLimitValue)length(seq) - oldSize;
TSize size = length(me);
while (pos < size)
me.limits[++pos] += delta;
}
}
// Function clear()
template <typename TString >
inline void clear(StringSet<TString, Owner<Default> > & me)
{
SEQAN_CHECKPOINT;
clear(me.strings);
resize(me.limits, 1, Exact());
me.limitsValid = true;
}
// Function value()
template <typename TString, typename TPos >
inline typename Reference<StringSet<TString, Owner<Default> > >::Type
value(StringSet<TString, Owner<Default> > & me, TPos pos)
{
return me.strings[pos];
}
template <typename TString, typename TPos >
inline typename Reference<StringSet<TString, Owner<Default> > const >::Type
value(StringSet<TString, Owner<Default> > const & me, TPos pos)
{
return me.strings[pos];
}
// Function erase()
.Function.erase.param.object.type:Spec.Owner
template <typename TString, typename TPos>
inline typename Size<StringSet<TString, Owner<Default> > >::Type
erase(StringSet<TString, Owner<Default> > & me, TPos pos)
{
erase(me.strings, pos);
me.limitsValid = false;
return length(me);
}
template <typename TString, typename TPos, typename TPosEnd>
inline typename Size<StringSet<TString, Owner<Default> > >::Type
erase(StringSet<TString, Owner<Default> > & me, TPos pos, TPosEnd posEnd)
{
erase(me.strings, pos, posEnd);
me.limitsValid = false;
return length(me);
}
// Function getValueById()
template <typename TString, typename TSpec, typename TId>
inline typename Reference<StringSet<TString, Owner<TSpec> > >::Type
getValueById(StringSet<TString, Owner<TSpec> >& me,
TId const id)
{
SEQAN_CHECKPOINT;
if (id < (TId) length(me)) return value(me, id);
static TString tmp = "";
return tmp;
}
// Function assignValueById()
template <typename TString, typename TSpec, typename TId>
inline typename Id<StringSet<TString, Owner<TSpec> > >::Type
assignValueById(StringSet<TString, Owner<TSpec> > & me,
TString& obj,
TId id)
{
SEQAN_CHECKPOINT;
if (id >= (TId) length(me.strings))
{
resize(me.strings, id+1, TString());
resize(me.limits, length(me.limits) + 1, Generous());
}
assignValue(me, id, obj);
me.limitsValid = false;
return id;
}
// Function removeValueById()
template<typename TString, typename TSpec, typename TId>
inline void
removeValueById(StringSet<TString, Owner<TSpec> > & me, TId const id)
{
SEQAN_CHECKPOINT;
erase(me.strings, id);
resize(me.limits, length(me.limits) - 1, Generous());
me.limitsValid = empty(me);
}
// Function positionToId()
template <typename TString, typename TSpec, typename TPos>
inline typename Id<StringSet<TString, Owner<TSpec> > >::Type
positionToId(StringSet<TString, Owner<TSpec> > &,
TPos const pos)
{
SEQAN_CHECKPOINT;
return pos;
}
// Function positionToId()
template <typename TString, typename TSpec, typename TPos>
inline typename Id<StringSet<TString, Owner<TSpec> > >::Type
positionToId(StringSet<TString, Owner<TSpec> > const &,
TPos const pos)
{
SEQAN_CHECKPOINT;
return pos;
}
// Function idToPosition()
template <typename TString, typename TSpec, typename TId>
inline typename Id<StringSet<TString, Owner<TSpec> > >::Type
idToPosition(StringSet<TString, Owner<TSpec> > const&,
TId const id)
{
SEQAN_CHECKPOINT;
return id;
}
} // namespace seqan
#endif // #ifndef <API key> |
// modification, are permitted provided that the following conditions are
// met:
// with the distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#ifndef V8_STRING_SEARCH_H_
#define V8_STRING_SEARCH_H_
namespace v8 {
namespace internal {
// String Search object.
// Class holding constants and methods that apply to all string search variants,
// independently of subject and pattern char size.
class StringSearchBase {
protected:
// Cap on the maximal shift in the Boyer-Moore implementation. By setting a
// limit, we can fix the size of tables. For a needle longer than this limit,
// search will not be optimal, since we only build tables for a suffix
// of the string, but it is a safe approximation.
static const int kBMMaxShift = Isolate::kBMMaxShift;
// Reduce alphabet to this size.
// One of the tables used by Boyer-Moore and <API key> has size
// proportional to the input alphabet. We reduce the alphabet size by
// equating input characters modulo a smaller alphabet size. This gives
// a potentially less efficient searching, but is a safe approximation.
// For needles using only characters in the same Unicode 256-code point page,
// there is no search speed degradation.
static const int kAsciiAlphabetSize = 256;
static const int kUC16AlphabetSize = Isolate::kUC16AlphabetSize;
// Bad-char shift table stored in the state. It's length is the alphabet size.
// For patterns below this length, the skip length of Boyer-Moore is too short
// to compensate for the algorithmic overhead compared to simple brute force.
static const int kBMMinPatternLength = 7;
static inline bool IsOneByteString(Vector<const uint8_t> string) {
return true;
}
static inline bool IsOneByteString(Vector<const uc16> string) {
return String::IsOneByte(string.start(), string.length());
}
friend class Isolate;
};
template <typename PatternChar, typename SubjectChar>
class StringSearch : private StringSearchBase {
public:
StringSearch(Isolate* isolate, Vector<const PatternChar> pattern)
: isolate_(isolate),
pattern_(pattern),
start_(Max(0, pattern.length() - kBMMaxShift)) {
if (sizeof(PatternChar) > sizeof(SubjectChar)) {
if (!IsOneByteString(pattern_)) {
strategy_ = &FailSearch;
return;
}
}
int pattern_length = pattern_.length();
if (pattern_length < kBMMinPatternLength) {
if (pattern_length == 1) {
strategy_ = &SingleCharSearch;
return;
}
strategy_ = &LinearSearch;
return;
}
strategy_ = &InitialSearch;
}
int Search(Vector<const SubjectChar> subject, int index) {
return strategy_(this, subject, index);
}
static inline int AlphabetSize() {
if (sizeof(PatternChar) == 1) {
// ASCII needle.
return kAsciiAlphabetSize;
} else {
ASSERT(sizeof(PatternChar) == 2);
// UC16 needle.
return kUC16AlphabetSize;
}
}
private:
typedef int (*SearchFunction)( // NOLINT - it's not a cast!
StringSearch<PatternChar, SubjectChar>*,
Vector<const SubjectChar>,
int);
static int FailSearch(StringSearch<PatternChar, SubjectChar>*,
Vector<const SubjectChar>,
int) {
return -1;
}
static int SingleCharSearch(StringSearch<PatternChar, SubjectChar>* search,
Vector<const SubjectChar> subject,
int start_index);
static int LinearSearch(StringSearch<PatternChar, SubjectChar>* search,
Vector<const SubjectChar> subject,
int start_index);
static int InitialSearch(StringSearch<PatternChar, SubjectChar>* search,
Vector<const SubjectChar> subject,
int start_index);
static int <API key>(
StringSearch<PatternChar, SubjectChar>* search,
Vector<const SubjectChar> subject,
int start_index);
static int BoyerMooreSearch(StringSearch<PatternChar, SubjectChar>* search,
Vector<const SubjectChar> subject,
int start_index);
void <API key>();
void <API key>();
static inline bool exceedsOneByte(uint8_t c) {
return false;
}
static inline bool exceedsOneByte(uint16_t c) {
return c > String::<API key>;
}
static inline int CharOccurrence(int* bad_char_occurrence,
SubjectChar char_code) {
if (sizeof(SubjectChar) == 1) {
return bad_char_occurrence[static_cast<int>(char_code)];
}
if (sizeof(PatternChar) == 1) {
if (exceedsOneByte(char_code)) {
return -1;
}
return bad_char_occurrence[static_cast<unsigned int>(char_code)];
}
// Both pattern and subject are UC16. Reduce character to equivalence class.
int equiv_class = char_code % kUC16AlphabetSize;
return bad_char_occurrence[equiv_class];
}
// The following tables are shared by all searches.
// TODO(lrn): Introduce a way for a pattern to keep its tables
// between searches (e.g., for an Atom RegExp).
// Store for the BoyerMoore(Horspool) bad char shift table.
// Return a table covering the last kBMMaxShift+1 positions of
// pattern.
int* bad_char_table() {
return isolate_-><API key>();
}
// Store for the BoyerMoore good suffix shift table.
int* <API key>() {
// Return biased pointer that maps the range [start_..pattern_.length()
// to the <API key> array.
return isolate_-><API key>() - start_;
}
// Table used temporarily while building the BoyerMoore good suffix
// shift table.
int* suffix_table() {
// Return biased pointer that maps the range [start_..pattern_.length()
// to the kSuffixTable array.
return isolate_->suffix_table() - start_;
}
Isolate* isolate_;
// The pattern to search for.
Vector<const PatternChar> pattern_;
// Pointer to implementation of the search.
SearchFunction strategy_;
// Cache value of Max(0, pattern_length() - kBMMaxShift)
int start_;
};
// Single Character Pattern Search Strategy
template <typename PatternChar, typename SubjectChar>
int StringSearch<PatternChar, SubjectChar>::SingleCharSearch(
StringSearch<PatternChar, SubjectChar>* search,
Vector<const SubjectChar> subject,
int index) {
ASSERT_EQ(1, search->pattern_.length());
PatternChar pattern_first_char = search->pattern_[0];
int i = index;
if (sizeof(SubjectChar) == 1 && sizeof(PatternChar) == 1) {
const SubjectChar* pos = reinterpret_cast<const SubjectChar*>(
memchr(subject.start() + i,
pattern_first_char,
subject.length() - i));
if (pos == NULL) return -1;
return static_cast<int>(pos - subject.start());
} else {
if (sizeof(PatternChar) > sizeof(SubjectChar)) {
if (exceedsOneByte(pattern_first_char)) {
return -1;
}
}
SubjectChar search_char = static_cast<SubjectChar>(pattern_first_char);
int n = subject.length();
while (i < n) {
if (subject[i++] == search_char) return i - 1;
}
return -1;
}
}
// Linear Search Strategy
template <typename PatternChar, typename SubjectChar>
inline bool CharCompare(const PatternChar* pattern,
const SubjectChar* subject,
int length) {
ASSERT(length > 0);
int pos = 0;
do {
if (pattern[pos] != subject[pos]) {
return false;
}
pos++;
} while (pos < length);
return true;
}
// Simple linear search for short patterns. Never bails out.
template <typename PatternChar, typename SubjectChar>
int StringSearch<PatternChar, SubjectChar>::LinearSearch(
StringSearch<PatternChar, SubjectChar>* search,
Vector<const SubjectChar> subject,
int index) {
Vector<const PatternChar> pattern = search->pattern_;
ASSERT(pattern.length() > 1);
int pattern_length = pattern.length();
PatternChar pattern_first_char = pattern[0];
int i = index;
int n = subject.length() - pattern_length;
while (i <= n) {
if (sizeof(SubjectChar) == 1 && sizeof(PatternChar) == 1) {
const SubjectChar* pos = reinterpret_cast<const SubjectChar*>(
memchr(subject.start() + i,
pattern_first_char,
n - i + 1));
if (pos == NULL) return -1;
i = static_cast<int>(pos - subject.start()) + 1;
} else {
if (subject[i++] != pattern_first_char) continue;
}
// Loop extracted to separate function to allow using return to do
// a deeper break.
if (CharCompare(pattern.start() + 1,
subject.start() + i,
pattern_length - 1)) {
return i - 1;
}
}
return -1;
}
// Boyer-Moore string search
template <typename PatternChar, typename SubjectChar>
int StringSearch<PatternChar, SubjectChar>::BoyerMooreSearch(
StringSearch<PatternChar, SubjectChar>* search,
Vector<const SubjectChar> subject,
int start_index) {
Vector<const PatternChar> pattern = search->pattern_;
int subject_length = subject.length();
int pattern_length = pattern.length();
// Only preprocess at most kBMMaxShift last characters of pattern.
int start = search->start_;
int* bad_char_occurence = search->bad_char_table();
int* good_suffix_shift = search-><API key>();
PatternChar last_char = pattern[pattern_length - 1];
int index = start_index;
// Continue search from i.
while (index <= subject_length - pattern_length) {
int j = pattern_length - 1;
int c;
while (last_char != (c = subject[index + j])) {
int shift =
j - CharOccurrence(bad_char_occurence, c);
index += shift;
if (index > subject_length - pattern_length) {
return -1;
}
}
while (j >= 0 && pattern[j] == (c = subject[index + j])) j
if (j < 0) {
return index;
} else if (j < start) {
// we have matched more than our tables allow us to be smart about.
// Fall back on BMH shift.
index += pattern_length - 1
- CharOccurrence(bad_char_occurence,
static_cast<SubjectChar>(last_char));
} else {
int gs_shift = good_suffix_shift[j + 1];
int bc_occ =
CharOccurrence(bad_char_occurence, c);
int shift = j - bc_occ;
if (gs_shift > shift) {
shift = gs_shift;
}
index += shift;
}
}
return -1;
}
template <typename PatternChar, typename SubjectChar>
void StringSearch<PatternChar, SubjectChar>::<API key>() {
int pattern_length = pattern_.length();
const PatternChar* pattern = pattern_.start();
// Only look at the last kBMMaxShift characters of pattern (from start_
// to pattern_length).
int start = start_;
int length = pattern_length - start;
// Biased tables so that we can use pattern indices as table indices,
// even if we only cover the part of the pattern from offset start.
int* shift_table = <API key>();
int* suffix_table = this->suffix_table();
// Initialize table.
for (int i = start; i < pattern_length; i++) {
shift_table[i] = length;
}
shift_table[pattern_length] = 1;
suffix_table[pattern_length] = pattern_length + 1;
if (pattern_length <= start) {
return;
}
// Find suffixes.
PatternChar last_char = pattern[pattern_length - 1];
int suffix = pattern_length + 1;
{
int i = pattern_length;
while (i > start) {
PatternChar c = pattern[i - 1];
while (suffix <= pattern_length && c != pattern[suffix - 1]) {
if (shift_table[suffix] == length) {
shift_table[suffix] = suffix - i;
}
suffix = suffix_table[suffix];
}
suffix_table[--i] = --suffix;
if (suffix == pattern_length) {
// No suffix to extend, so we check against last_char only.
while ((i > start) && (pattern[i - 1] != last_char)) {
if (shift_table[pattern_length] == length) {
shift_table[pattern_length] = pattern_length - i;
}
suffix_table[--i] = pattern_length;
}
if (i > start) {
suffix_table[--i] = --suffix;
}
}
}
}
// Build shift table using suffixes.
if (suffix < pattern_length) {
for (int i = start; i <= pattern_length; i++) {
if (shift_table[i] == length) {
shift_table[i] = suffix - start;
}
if (i == suffix) {
suffix = suffix_table[suffix];
}
}
}
}
// <API key> string search.
template <typename PatternChar, typename SubjectChar>
int StringSearch<PatternChar, SubjectChar>::<API key>(
StringSearch<PatternChar, SubjectChar>* search,
Vector<const SubjectChar> subject,
int start_index) {
Vector<const PatternChar> pattern = search->pattern_;
int subject_length = subject.length();
int pattern_length = pattern.length();
int* char_occurrences = search->bad_char_table();
int badness = -pattern_length;
// How bad we are doing without a good-suffix table.
PatternChar last_char = pattern[pattern_length - 1];
int last_char_shift = pattern_length - 1 -
CharOccurrence(char_occurrences, static_cast<SubjectChar>(last_char));
// Perform search
int index = start_index; // No matches found prior to this index.
while (index <= subject_length - pattern_length) {
int j = pattern_length - 1;
int subject_char;
while (last_char != (subject_char = subject[index + j])) {
int bc_occ = CharOccurrence(char_occurrences, subject_char);
int shift = j - bc_occ;
index += shift;
badness += 1 - shift; // at most zero, so badness cannot increase.
if (index > subject_length - pattern_length) {
return -1;
}
}
j
while (j >= 0 && pattern[j] == (subject[index + j])) j
if (j < 0) {
return index;
} else {
index += last_char_shift;
// Badness increases by the number of characters we have
// checked, and decreases by the number of characters we
// can skip by shifting. It's a measure of how we are doing
// compared to reading each character exactly once.
badness += (pattern_length - j) - last_char_shift;
if (badness > 0) {
search-><API key>();
search->strategy_ = &BoyerMooreSearch;
return BoyerMooreSearch(search, subject, index);
}
}
}
return -1;
}
template <typename PatternChar, typename SubjectChar>
void StringSearch<PatternChar, SubjectChar>::<API key>() {
int pattern_length = pattern_.length();
int* bad_char_occurrence = bad_char_table();
// Only preprocess at most kBMMaxShift last characters of pattern.
int start = start_;
// Run forwards to populate bad_char_table, so that *last* instance
// of character equivalence class is the one registered.
// Notice: Doesn't include the last character.
int table_size = AlphabetSize();
if (start == 0) { // All patterns less than kBMMaxShift in length.
memset(bad_char_occurrence,
-1,
table_size * sizeof(*bad_char_occurrence));
} else {
for (int i = 0; i < table_size; i++) {
bad_char_occurrence[i] = start - 1;
}
}
for (int i = start; i < pattern_length - 1; i++) {
PatternChar c = pattern_[i];
int bucket = (sizeof(PatternChar) == 1) ? c : c % AlphabetSize();
bad_char_occurrence[bucket] = i;
}
}
// Linear string search with bailout to BMH.
// Simple linear search for short patterns, which bails out if the string
// isn't found very early in the subject. Upgrades to BoyerMooreHorspool.
template <typename PatternChar, typename SubjectChar>
int StringSearch<PatternChar, SubjectChar>::InitialSearch(
StringSearch<PatternChar, SubjectChar>* search,
Vector<const SubjectChar> subject,
int index) {
Vector<const PatternChar> pattern = search->pattern_;
int pattern_length = pattern.length();
// Badness is a count of how much work we have done. When we have
// done enough work we decide it's probably worth switching to a better
// algorithm.
int badness = -10 - (pattern_length << 2);
// We know our pattern is at least 2 characters, we cache the first so
// the common case of the first character not matching is faster.
PatternChar pattern_first_char = pattern[0];
for (int i = index, n = subject.length() - pattern_length; i <= n; i++) {
badness++;
if (badness <= 0) {
if (sizeof(SubjectChar) == 1 && sizeof(PatternChar) == 1) {
const SubjectChar* pos = reinterpret_cast<const SubjectChar*>(
memchr(subject.start() + i,
pattern_first_char,
n - i + 1));
if (pos == NULL) {
return -1;
}
i = static_cast<int>(pos - subject.start());
} else {
if (subject[i] != pattern_first_char) continue;
}
int j = 1;
do {
if (pattern[j] != subject[i + j]) {
break;
}
j++;
} while (j < pattern_length);
if (j == pattern_length) {
return i;
}
badness += j;
} else {
search-><API key>();
search->strategy_ = &<API key>;
return <API key>(search, subject, i);
}
}
return -1;
}
// Perform a a single stand-alone search.
// If searching multiple times for the same pattern, a search
// object should be constructed once and the Search function then called
// for each search.
template <typename SubjectChar, typename PatternChar>
int SearchString(Isolate* isolate,
Vector<const SubjectChar> subject,
Vector<const PatternChar> pattern,
int start_index) {
StringSearch<PatternChar, SubjectChar> search(isolate, pattern);
return search.Search(subject, start_index);
}
}} // namespace v8::internal
#endif // V8_STRING_SEARCH_H_ |
/* This file contains references to the vendor libraries
we're using in this project. This is used by webpack
in the production build only*. A separate bundle for vendor
code is useful since it's unlikely to change as often
as the application's code. So all the libraries we reference
here will be written to vendor.js so they can be
cached until one of them change. So basically, this avoids
customers having to download a huge JS file anytime a line
of code changes. They only have to download vendor.js when
a vendor library changes which should be less frequent.
Any files that aren't referenced here will be bundled into
main.js for the production build.
*/
/* eslint-disable no-unused-vars */
import fetch from 'whatwg-fetch'; |
require "travis"
require "travis/tools/system"
require "travis/tools/assets"
require "cgi"
module Travis
module Tools
module Notification
extend self
DEFAULT = [:osx, :growl, :libnotify]
ICON = Assets['notifications/icon.png']
def new(*list)
list.concat(DEFAULT) if list.empty?
notification = list.map { |n| get(n) }.detect { |n| n.available? }
raise ArgumentError, "no notification system found (looked for #{list.join(", ")})" unless notification
notification
end
def get(name)
const = constants.detect { |c| c.to_s[/[^:]+$/].downcase == name.to_s }
raise ArgumentError, "unknown notifications type %p" % name unless const
const_get(const).new
end
class Dummy
BIN_PATH = Assets['Travis CI.app/Contents/MacOS/Travis CI']
def notify(title, body)
end
def available?
true
end
end
class OSX
BIN_PATH = Assets["notifications/Travis CI.app/Contents/MacOS/Travis CI"]
def notify(title, body)
system BIN_PATH, '-message', body.to_s, '-title', title.to_s, '-sender', 'org.travis-ci.Travis-CI'
end
def available?
System.mac? and System.recent_version?(System.os_version.to_s, '10.8') and System.running? "NotificationCenter"
end
end
class Growl
def notify(title, body)
system 'growlnotify', '-n', 'Travis', '--image', ICON, '-m', body, title
end
def available?
System.has? 'growlnotify' and System.running? "Growl"
end
end
class LibNotify
def notify(title, body)
system 'notify-send', '--expire-time=10000', '-h', 'int:transient:1', '-i', ICON, title, CGI.escapeHTML(body)
end
def available?
System.has? 'notify-send'
end
end
end
end
end |
<!DOCTYPE html>
<html lang="en">
<head>
<title>three.js webgl - multiple canvases - grid</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
<style>
html, body {
color: #808080;
font-family: Monospace;
font-size: 13px;
text-align: center;
background-color: #fff;
margin: 0px;
overflow: hidden;
width: 100%;
height: 100%;
}
#info {
position: absolute;
top: 0px; width: 100%;
padding: 5px;
}
#centerer {
display: table;
width: 100%;
height: 100%;
}
#centerer-cell {
display: table-cell;
vertical-align: middle;
}
#container {
margin-left: auto;
margin-right: auto;
width: 604px; /* 300*2 + border; */
}
#container div {
float: left;
}
#canvas1, #canvas2, #canvas3, #canvas4 {
position: relative;
width: 300px;
height: 200px;
border: 1px solid red;
float: left;
}
a {
color: #0080ff;
}
</style>
</head>
<body>
<div id="centerer">
<div id="centerer-cell">
<div id="container">
<div class="container-row">
<canvas id="canvas1"></canvas>
<canvas id="canvas2"></canvas>
</div>
<div class="container-row">
<canvas id="canvas3"></canvas>
<canvas id="canvas4"></canvas>
</div>
</div>
</div>
</div>
<div id="info"><a href="http://threejs.org" target="_blank" rel="noopener">three.js</a> webgl - multiple canvases - grid</div>
<script src="../build/three.js"></script>
<script src="js/Detector.js"></script>
<script>
if ( ! Detector.webgl ) Detector.addGetWebGLMessage();
var views = [];
var scene, renderer;
var mouseX = 0, mouseY = 0;
var windowHalfX = window.innerWidth / 2;
var windowHalfY = window.innerHeight / 2;
init();
animate();
function View( canvas, fullWidth, fullHeight, viewX, viewY, viewWidth, viewHeight ) {
canvas.width = viewWidth * window.devicePixelRatio;
canvas.height = viewHeight * window.devicePixelRatio;
var context = canvas.getContext( '2d' );
var camera = new THREE.PerspectiveCamera( 20, viewWidth / viewHeight, 1, 10000 );
camera.setViewOffset( fullWidth, fullHeight, viewX, viewY, viewWidth, viewHeight );
camera.position.z = 1800;
this.render = function () {
camera.position.x += ( mouseX - camera.position.x ) * 0.05;
camera.position.y += ( - mouseY - camera.position.y ) * 0.05;
camera.lookAt( scene.position );
renderer.render( scene, camera );
context.drawImage( renderer.domElement, 0, 0 );
};
}
function init() {
var canvas1 = document.getElementById( 'canvas1' );
var canvas2 = document.getElementById( 'canvas2' );
var canvas3 = document.getElementById( 'canvas3' );
var canvas4 = document.getElementById( 'canvas4' );
var w = 300, h = 200;
var fullWidth = w * 2;
var fullHeight = h * 2;
views.push( new View( canvas1, fullWidth, fullHeight, w * 0, h * 0, w, h ) );
views.push( new View( canvas2, fullWidth, fullHeight, w * 1, h * 0, w, h ) );
views.push( new View( canvas3, fullWidth, fullHeight, w * 0, h * 1, w, h ) );
views.push( new View( canvas4, fullWidth, fullHeight, w * 1, h * 1, w, h ) );
scene = new THREE.Scene();
scene.background = new THREE.Color( 0xffffff );
var light = new THREE.DirectionalLight( 0xffffff );
light.position.set( 0, 0, 1 ).normalize();
scene.add( light );
// shadow
var canvas = document.createElement( 'canvas' );
canvas.width = 128;
canvas.height = 128;
var context = canvas.getContext( '2d' );
var gradient = context.<API key>( canvas.width / 2, canvas.height / 2, 0, canvas.width / 2, canvas.height / 2, canvas.width / 2 );
gradient.addColorStop( 0.1, 'rgba(210,210,210,1)' );
gradient.addColorStop( 1, 'rgba(255,255,255,1)' );
context.fillStyle = gradient;
context.fillRect( 0, 0, canvas.width, canvas.height );
var shadowTexture = new THREE.CanvasTexture( canvas );
var shadowMaterial = new THREE.MeshBasicMaterial( { map: shadowTexture } );
var shadowGeo = new THREE.PlaneBufferGeometry( 300, 300, 1, 1 );
var mesh = new THREE.Mesh( shadowGeo, shadowMaterial );
mesh.position.y = - 250;
mesh.rotation.x = - Math.PI / 2;
scene.add( mesh );
var mesh = new THREE.Mesh( shadowGeo, shadowMaterial );
mesh.position.x = - 400;
mesh.position.y = - 250;
mesh.rotation.x = - Math.PI / 2;
scene.add( mesh );
var mesh = new THREE.Mesh( shadowGeo, shadowMaterial );
mesh.position.x = 400;
mesh.position.y = - 250;
mesh.rotation.x = - Math.PI / 2;
scene.add( mesh );
var faceIndices = [ 'a', 'b', 'c' ];
var radius = 200,
geometry1 = new THREE.IcosahedronGeometry( radius, 1 ),
geometry2 = new THREE.IcosahedronGeometry( radius, 1 ),
geometry3 = new THREE.IcosahedronGeometry( radius, 1 );
for ( var i = 0; i < geometry1.faces.length; i ++ ) {
var f1 = geometry1.faces[ i ];
var f2 = geometry2.faces[ i ];
var f3 = geometry3.faces[ i ];
for ( var j = 0; j < 3; j ++ ) {
var vertexIndex = f1[ faceIndices[ j ] ];
var p = geometry1.vertices[ vertexIndex ];
var color = new THREE.Color( 0xffffff );
color.setHSL( ( p.y / radius + 1 ) / 2, 1.0, 0.5 );
f1.vertexColors[ j ] = color;
var color = new THREE.Color( 0xffffff );
color.setHSL( 0.0, ( p.y / radius + 1 ) / 2, 0.5 );
f2.vertexColors[ j ] = color;
var color = new THREE.Color( 0xffffff );
color.setHSL( 0.125 * vertexIndex / geometry1.vertices.length, 1.0, 0.5 );
f3.vertexColors[ j ] = color;
}
}
var materials = [
new THREE.MeshPhongMaterial( { color: 0xffffff, flatShading: true, vertexColors: THREE.VertexColors, shininess: 0 } ),
new THREE.MeshBasicMaterial( { color: 0x000000, wireframe: true, transparent: true } )
];
var group1 = THREE.SceneUtils.<API key>( geometry1, materials );
group1.position.x = -400;
group1.rotation.x = -1.87;
scene.add( group1 );
var group2 = THREE.SceneUtils.<API key>( geometry2, materials );
group2.position.x = 400;
scene.add( group2 );
var group3 = THREE.SceneUtils.<API key>( geometry3, materials );
scene.add( group3 );
renderer = new THREE.WebGLRenderer( { antialias: true } );
renderer.setPixelRatio( window.devicePixelRatio );
renderer.setSize( 300, 200 );
document.addEventListener( 'mousemove', onDocumentMouseMove, false );
}
function onDocumentMouseMove( event ) {
mouseX = event.clientX - windowHalfX;
mouseY = event.clientY - windowHalfY;
}
function animate() {
for ( var i = 0; i < views.length; ++i ) {
views[ i ].render();
}
<API key>( animate );
}
</script>
</body>
</html> |
module Job::Cms::Binding::Page
extend ActiveSupport::Concern
included do
# page class
mattr_accessor(:page_class, instance_accessor: false) { Cms::Page }
# page
attr_accessor :page_id
end
def page
return nil if page_id.blank?
@page ||= begin
page = self.class.page_class.or({ id: page_id }, { filename: page_id }).first
if page
page = page.becomes_with_route rescue page
end
page
end
end
def bind(bindings)
if bindings['page_id'].present?
self.page_id = bindings['page_id'].to_param
@page = nil
end
super
end
def bindings
ret = super
ret['page_id'] = page_id if page_id.present?
ret
end
end |
// NSArray+<API key>.h
#import <Foundation/Foundation.h>
@interface NSArray (<API key>)
- (NSString *)toXMLValue;
@end |
#if <API key>
namespace Microsoft.XmlSerializer.Generator
#else
namespace System.Xml.Serialization
#endif
{
using System.Reflection;
using System;
using System.Xml.Schema;
using System.Collections;
using System.ComponentModel;
using System.Globalization;
using System.Threading;
using System.Diagnostics;
using System.Linq;
using System.Collections.Generic;
using System.Xml.Extensions;
using System.Xml;
using System.Xml.Serialization;
<internalonly/>
<devdoc>
<para>[To be supplied.]</para>
</devdoc>
public class <API key>
{
private TypeScope _typeScope;
private <API key> _attributeOverrides;
private XmlAttributes _defaultAttributes = new XmlAttributes();
private NameTable _types = new NameTable(); // xmltypename + xmlns -> Mapping
private NameTable _nullables = new NameTable(); // xmltypename + xmlns -> NullableMapping
private NameTable _elements = new NameTable(); // xmlelementname + xmlns -> ElementAccessor
private NameTable _xsdAttributes; // xmlattributetname + xmlns -> AttributeAccessor
private Hashtable _specials; // type -> SpecialMapping
private Hashtable _anonymous = new Hashtable(); // type -> AnonymousMapping
#if !<API key>
private NameTable _serializables; // type name --> new SerializableMapping
#endif
private StructMapping _root;
private string _defaultNs;
private ModelScope _modelScope;
private int _arrayNestingLevel;
private <API key> <API key>;
private string <API key>;
private int _choiceNum = 1;
private enum ImportContext
{
Text,
Attribute,
Element
}
<devdoc>
<para>[To be supplied.]</para>
</devdoc>
public <API key>() : this(null, null)
{
}
<devdoc>
<para>[To be supplied.]</para>
</devdoc>
public <API key>(string defaultNamespace) : this(null, defaultNamespace)
{
}
<devdoc>
<para>[To be supplied.]</para>
</devdoc>
public <API key>(<API key> attributeOverrides) : this(attributeOverrides, null)
{
}
<devdoc>
<para>[To be supplied.]</para>
</devdoc>
public <API key>(<API key> attributeOverrides, string defaultNamespace)
{
if (defaultNamespace == null)
defaultNamespace = String.Empty;
if (attributeOverrides == null)
attributeOverrides = new <API key>();
_attributeOverrides = attributeOverrides;
_defaultNs = defaultNamespace;
_typeScope = new TypeScope();
_modelScope = new ModelScope(_typeScope);
}
<devdoc>
<para>[To be supplied.]</para>
</devdoc>
public void IncludeTypes(<API key> provider)
{
IncludeTypes(provider, new RecursionLimiter());
}
private void IncludeTypes(<API key> provider, RecursionLimiter limiter)
{
object[] attrs = provider.GetCustomAttributes(typeof(XmlIncludeAttribute), false);
for (int i = 0; i < attrs.Length; i++)
{
Type type = ((XmlIncludeAttribute)attrs[i]).Type;
IncludeType(type, limiter);
}
}
<devdoc>
<para>[To be supplied.]</para>
</devdoc>
public void IncludeType(Type type)
{
IncludeType(type, new RecursionLimiter());
}
private void IncludeType(Type type, RecursionLimiter limiter)
{
int <API key> = _arrayNestingLevel;
<API key> <API key> = <API key>;
string <API key> = <API key>;
_arrayNestingLevel = 0;
<API key> = null;
<API key> = null;
TypeMapping mapping = ImportTypeMapping(_modelScope.GetTypeModel(type), _defaultNs, ImportContext.Element, string.Empty, null, limiter);
if (mapping.IsAnonymousType && !mapping.TypeDesc.IsSpecial)
{
//XmlAnonymousInclude=Cannot include anonymous type '{0}'.
throw new <API key>(SR.Format(SR.XmlAnonymousInclude, type.FullName));
}
_arrayNestingLevel = <API key>;
<API key> = <API key>;
<API key> = <API key>;
}
<devdoc>
<para>[To be supplied.]</para>
</devdoc>
public XmlTypeMapping ImportTypeMapping(Type type)
{
return ImportTypeMapping(type, null, null);
}
<devdoc>
<para>[To be supplied.]</para>
</devdoc>
public XmlTypeMapping ImportTypeMapping(Type type, string defaultNamespace)
{
return ImportTypeMapping(type, null, defaultNamespace);
}
<devdoc>
<para>[To be supplied.]</para>
</devdoc>
public XmlTypeMapping ImportTypeMapping(Type type, XmlRootAttribute root)
{
return ImportTypeMapping(type, root, null);
}
<devdoc>
<para>[To be supplied.]</para>
</devdoc>
public XmlTypeMapping ImportTypeMapping(Type type, XmlRootAttribute root, string defaultNamespace)
{
if (type == null)
throw new <API key>(nameof(type));
XmlTypeMapping xmlMapping = new XmlTypeMapping(_typeScope, ImportElement(_modelScope.GetTypeModel(type), root, defaultNamespace, new RecursionLimiter()));
xmlMapping.SetKeyInternal(XmlMapping.GenerateKey(type, root, defaultNamespace));
xmlMapping.GenerateSerializer = true;
return xmlMapping;
}
<devdoc>
<para>[To be supplied.]</para>
</devdoc>
public XmlMembersMapping <API key>(string elementName, string ns, XmlReflectionMember[] members, bool hasWrapperElement)
{
return <API key>(elementName, ns, members, hasWrapperElement, false);
}
<devdoc>
<para>[To be supplied.]</para>
</devdoc>
public XmlMembersMapping <API key>(string elementName, string ns, XmlReflectionMember[] members, bool hasWrapperElement, bool rpc)
{
return <API key>(elementName, ns, members, hasWrapperElement, rpc, false);
}
<devdoc>
<para>[To be supplied.]</para>
</devdoc>
public XmlMembersMapping <API key>(string elementName, string ns, XmlReflectionMember[] members, bool hasWrapperElement, bool rpc, bool openModel)
{
return <API key>(elementName, ns, members, hasWrapperElement, rpc, openModel, XmlMappingAccess.Read | XmlMappingAccess.Write);
}
<devdoc>
<para>[To be supplied.]</para>
</devdoc>
public XmlMembersMapping <API key>(string elementName, string ns, XmlReflectionMember[] members, bool hasWrapperElement, bool rpc, bool openModel, XmlMappingAccess access)
{
ElementAccessor element = new ElementAccessor();
element.Name = elementName == null || elementName.Length == 0 ? elementName : XmlConvert.EncodeLocalName(elementName);
element.Namespace = ns;
MembersMapping membersMapping = <API key>(members, ns, hasWrapperElement, rpc, openModel, new RecursionLimiter());
element.Mapping = membersMapping;
element.Form = XmlSchemaForm.Qualified; // elements within soap:body are always qualified
if (!rpc)
{
if (hasWrapperElement)
element = (ElementAccessor)ReconcileAccessor(element, _elements);
else
{
foreach (MemberMapping mapping in membersMapping.Members)
{
if (mapping.Elements != null && mapping.Elements.Length > 0)
{
mapping.Elements[0] = (ElementAccessor)ReconcileAccessor(mapping.Elements[0], _elements);
}
}
}
}
XmlMembersMapping xmlMapping = new XmlMembersMapping(_typeScope, element, access);
xmlMapping.GenerateSerializer = true;
return xmlMapping;
}
private XmlAttributes GetAttributes(Type type, bool canBeSimpleType)
{
XmlAttributes attrs = _attributeOverrides[type];
if (attrs != null) return attrs;
if (canBeSimpleType && TypeScope.IsKnownType(type))
{
return _defaultAttributes;
}
return new XmlAttributes(type);
}
private XmlAttributes GetAttributes(MemberInfo memberInfo)
{
XmlAttributes attrs = _attributeOverrides[memberInfo.DeclaringType, memberInfo.Name];
if (attrs != null) return attrs;
return new XmlAttributes(memberInfo);
}
private ElementAccessor ImportElement(TypeModel model, XmlRootAttribute root, string defaultNamespace, RecursionLimiter limiter)
{
XmlAttributes a = GetAttributes(model.Type, true);
if (root == null)
root = a.XmlRoot;
string ns = root == null ? null : root.Namespace;
if (ns == null) ns = defaultNamespace;
if (ns == null) ns = _defaultNs;
_arrayNestingLevel = -1;
<API key> = null;
<API key> = null;
ElementAccessor element = <API key>(ImportTypeMapping(model, ns, ImportContext.Element, string.Empty, a, limiter), ns);
if (root != null)
{
if (root.ElementName.Length > 0)
element.Name = XmlConvert.EncodeLocalName(root.ElementName);
if (root.<API key>() && !root.IsNullable && model.TypeDesc.IsOptionalValue)
//<API key>=IsNullable may not be set to 'false' for a Nullable<{0}> type. Consider using '{0}' type or removing the IsNullable property from the XmlElement attribute.
throw new <API key>(SR.Format(SR.<API key>, model.TypeDesc.BaseTypeDesc.FullName, "XmlRoot"));
element.IsNullable = root.<API key>() ? root.IsNullable : model.TypeDesc.IsNullable || model.TypeDesc.IsOptionalValue;
CheckNullable(element.IsNullable, model.TypeDesc, element.Mapping);
}
else
element.IsNullable = model.TypeDesc.IsNullable || model.TypeDesc.IsOptionalValue;
element.Form = XmlSchemaForm.Qualified;
return (ElementAccessor)ReconcileAccessor(element, _elements);
}
private static string GetMappingName(Mapping mapping)
{
if (mapping is MembersMapping)
return "(method)";
else if (mapping is TypeMapping)
return ((TypeMapping)mapping).TypeDesc.FullName;
else
throw new ArgumentException(SR.XmlInternalError, nameof(mapping));
}
private ElementAccessor <API key>(ElementAccessor accessor, string ns)
{
if (accessor.Namespace == ns) return accessor;
return (ElementAccessor)ReconcileAccessor(accessor, _elements);
}
private Accessor ReconcileAccessor(Accessor accessor, NameTable accessors)
{
if (accessor.Any && accessor.Name.Length == 0)
return accessor;
Accessor existing = (Accessor)accessors[accessor.Name, accessor.Namespace];
if (existing == null)
{
accessor.IsTopLevelInSchema = true;
accessors.Add(accessor.Name, accessor.Namespace, accessor);
return accessor;
}
if (existing.Mapping == accessor.Mapping)
return existing;
if (!(accessor.Mapping is MembersMapping) && !(existing.Mapping is MembersMapping))
{
if (accessor.Mapping.TypeDesc == existing.Mapping.TypeDesc
|| (existing.Mapping is NullableMapping && accessor.Mapping.TypeDesc == ((NullableMapping)existing.Mapping).BaseMapping.TypeDesc)
|| (accessor.Mapping is NullableMapping && ((NullableMapping)accessor.Mapping).BaseMapping.TypeDesc == existing.Mapping.TypeDesc))
{
// need to compare default values
string value1 = Convert.ToString(accessor.Default, CultureInfo.InvariantCulture);
string value2 = Convert.ToString(existing.Default, CultureInfo.InvariantCulture);
if (value1 == value2)
{
return existing;
}
throw new <API key>(SR.Format(SR.<API key>, accessor.Name, accessor.Namespace, value1, value2));
}
}
if (accessor.Mapping is MembersMapping || existing.Mapping is MembersMapping)
throw new <API key>(SR.Format(SR.<API key>, accessor.Name, accessor.Namespace));
if (accessor.Mapping is ArrayMapping)
{
if (!(existing.Mapping is ArrayMapping))
{
throw new <API key>(SR.Format(SR.<API key>, accessor.Name, accessor.Namespace, GetMappingName(existing.Mapping), GetMappingName(accessor.Mapping)));
}
ArrayMapping mapping = (ArrayMapping)accessor.Mapping;
ArrayMapping existingMapping = mapping.IsAnonymousType ? null : (ArrayMapping)_types[existing.Mapping.TypeName, existing.Mapping.Namespace];
ArrayMapping first = existingMapping;
while (existingMapping != null)
{
if (existingMapping == accessor.Mapping)
return existing;
existingMapping = existingMapping.Next;
}
mapping.Next = first;
if (!mapping.IsAnonymousType)
_types[existing.Mapping.TypeName, existing.Mapping.Namespace] = mapping;
return existing;
}
if (accessor is AttributeAccessor)
throw new <API key>(SR.Format(SR.<API key>, accessor.Name, accessor.Namespace, GetMappingName(existing.Mapping), GetMappingName(accessor.Mapping)));
else
throw new <API key>(SR.Format(SR.<API key>, accessor.Name, accessor.Namespace, GetMappingName(existing.Mapping), GetMappingName(accessor.Mapping)));
}
private Exception <API key>(string context, Exception e)
{
return new <API key>(SR.Format(SR.XmlReflectionError, context), e);
}
private Exception <API key>(string context, Exception e)
{
return new <API key>(SR.Format(SR.<API key>, context), e);
}
private Exception <API key>(FieldModel model, Exception e)
{
return new <API key>(SR.Format(model.IsProperty ? SR.<API key> : SR.<API key>, model.Name), e);
}
private TypeMapping ImportTypeMapping(TypeModel model, string ns, ImportContext context, string dataType, XmlAttributes a, RecursionLimiter limiter)
{
return ImportTypeMapping(model, ns, context, dataType, a, false, false, limiter);
}
private TypeMapping ImportTypeMapping(TypeModel model, string ns, ImportContext context, string dataType, XmlAttributes a, bool repeats, bool openModel, RecursionLimiter limiter)
{
try
{
if (dataType.Length > 0)
{
TypeDesc modelTypeDesc = TypeScope.IsOptionalValue(model.Type) ? model.TypeDesc.BaseTypeDesc : model.TypeDesc;
if (!modelTypeDesc.IsPrimitive)
{
throw new <API key>(SR.Format(SR.<API key>, dataType, "XmlElementAttribute.DataType"));
}
TypeDesc td = _typeScope.GetTypeDesc(dataType, XmlSchema.Namespace);
if (td == null)
{
throw new <API key>(SR.Format(SR.<API key>, dataType, "XmlElementAttribute.DataType", new XmlQualifiedName(dataType, XmlSchema.Namespace).ToString()));
}
if (modelTypeDesc.FullName != td.FullName)
{
throw new <API key>(SR.Format(SR.XmlDataTypeMismatch, dataType, "XmlElementAttribute.DataType", modelTypeDesc.FullName));
}
}
if (a == null)
a = GetAttributes(model.Type, false);
if ((a.XmlFlags & ~(XmlAttributeFlags.Type | XmlAttributeFlags.Root)) != 0)
throw new <API key>(SR.Format(SR.<API key>, model.Type.FullName));
switch (model.TypeDesc.Kind)
{
case TypeKind.Enum:
return ImportEnumMapping((EnumModel)model, ns, repeats);
case TypeKind.Primitive:
if (a.XmlFlags != 0) throw <API key>(model.Type);
return <API key>((PrimitiveModel)model, context, dataType, repeats);
case TypeKind.Array:
case TypeKind.Collection:
case TypeKind.Enumerable:
//if (a.XmlFlags != 0) throw <API key>(model.Type);
if (context != ImportContext.Element) throw <API key>(model.TypeDesc, context);
_arrayNestingLevel++;
ArrayMapping arrayMapping = <API key>((ArrayModel)model, ns, limiter);
_arrayNestingLevel
return arrayMapping;
case TypeKind.Root:
case TypeKind.Class:
case TypeKind.Struct:
if (context != ImportContext.Element) throw <API key>(model.TypeDesc, context);
if (model.TypeDesc.IsOptionalValue)
{
TypeDesc valueTypeDesc = string.IsNullOrEmpty(dataType) ? model.TypeDesc.BaseTypeDesc : _typeScope.GetTypeDesc(dataType, XmlSchema.Namespace);
string xsdTypeName = valueTypeDesc.DataType == null ? valueTypeDesc.Name : valueTypeDesc.DataType.Name;
TypeMapping baseMapping = GetTypeMapping(xsdTypeName, ns, valueTypeDesc, _types, null);
if (baseMapping == null)
baseMapping = ImportTypeMapping(_modelScope.GetTypeModel(model.TypeDesc.BaseTypeDesc.Type), ns, context, dataType, null, repeats, openModel, limiter);
return <API key>(baseMapping, model.TypeDesc.Type);
}
else
{
return <API key>((StructModel)model, ns, openModel, a, limiter);
}
default:
if (model.TypeDesc.Kind == TypeKind.Serializable)
{
// We allow XmlRoot attribute on IXmlSerializable, but not others
if ((a.XmlFlags & ~XmlAttributeFlags.Root) != 0)
{
throw new <API key>(SR.Format(SR.<API key>, model.TypeDesc.FullName, typeof(<API key>).Name));
}
}
else
{
if (a.XmlFlags != 0) throw <API key>(model.Type);
}
if (model.TypeDesc.IsSpecial)
return <API key>(model.Type, model.TypeDesc, ns, context, limiter);
throw <API key>(model.TypeDesc, context);
}
}
catch (Exception e)
{
if (e is <API key>)
{
throw;
}
throw <API key>(model.TypeDesc.FullName, e);
}
}
internal static MethodInfo <API key>(<API key> provider, Type type)
{
if (provider.IsAny)
{
// do not validate the schema provider method for wildcard types.
return null;
}
else if (provider.MethodName == null)
{
throw new <API key>(nameof(provider.MethodName));
}
if (!CSharpHelpers.<API key>(provider.MethodName))
throw new ArgumentException(SR.Format(SR.<API key>, provider.MethodName), nameof(provider.MethodName));
MethodInfo getMethod = getMethod = type.GetMethod(provider.MethodName, /* BindingFlags.DeclaredOnly | */ BindingFlags.Static | BindingFlags.Public, new Type[] { typeof(XmlSchemaSet) });
if (getMethod == null)
throw new <API key>(SR.Format(SR.<API key>, provider.MethodName, typeof(XmlSchemaSet).Name, type.FullName));
if (!(typeof(XmlQualifiedName).IsAssignableFrom(getMethod.ReturnType)) && !(typeof(XmlSchemaType).IsAssignableFrom(getMethod.ReturnType)))
throw new <API key>(SR.Format(SR.<API key>, type.Name, provider.MethodName, typeof(<API key>).Name, typeof(XmlQualifiedName).FullName, typeof(XmlSchemaType).FullName));
return getMethod;
}
private SpecialMapping <API key>(Type type, TypeDesc typeDesc, string ns, ImportContext context, RecursionLimiter limiter)
{
if (_specials == null)
_specials = new Hashtable();
SpecialMapping mapping = (SpecialMapping)_specials[type];
if (mapping != null)
{
CheckContext(mapping.TypeDesc, context);
return mapping;
}
if (typeDesc.Kind == TypeKind.Serializable)
{
SerializableMapping serializableMapping = null;
// get the schema method info
object[] attrs = type.GetCustomAttributes(typeof(<API key>), false);
if (attrs.Length > 0)
{
// new IXmlSerializable
<API key> provider = (<API key>)attrs[0];
MethodInfo method = <API key>(provider, type);
serializableMapping = new SerializableMapping(method, provider.IsAny, ns);
XmlQualifiedName qname = serializableMapping.XsiType;
if (qname != null && !qname.IsEmpty)
{
#if !<API key>
if (_serializables == null)
_serializables = new NameTable();
SerializableMapping existingMapping = (SerializableMapping)_serializables[qname];
if (existingMapping != null)
{
if (existingMapping.Type == null)
{
serializableMapping = existingMapping;
}
else if (existingMapping.Type != type)
{
SerializableMapping next = existingMapping.Next;
existingMapping.Next = serializableMapping;
serializableMapping.Next = next;
}
}
else
{
XmlSchemaType xsdType = serializableMapping.XsdType;
if (xsdType != null)
SetBase(serializableMapping, xsdType.DerivedFrom);
_serializables[qname] = serializableMapping;
}
#endif
serializableMapping.TypeName = qname.Name;
serializableMapping.Namespace = qname.Namespace;
}
serializableMapping.TypeDesc = typeDesc;
serializableMapping.Type = type;
IncludeTypes(type);
}
else
{
// old IXmlSerializable
serializableMapping = new SerializableMapping();
serializableMapping.TypeDesc = typeDesc;
serializableMapping.Type = type;
}
mapping = serializableMapping;
}
else
{
mapping = new SpecialMapping();
mapping.TypeDesc = typeDesc;
}
CheckContext(typeDesc, context);
_specials.Add(type, mapping);
_typeScope.AddTypeMapping(mapping);
return mapping;
}
#if !<API key>
internal void SetBase(SerializableMapping mapping, XmlQualifiedName baseQname)
{
if (baseQname.IsEmpty) return;
if (baseQname.Namespace == XmlSchema.Namespace) return;
XmlSchemaSet schemas = mapping.Schemas;
ArrayList srcSchemas = (ArrayList)schemas.Schemas(baseQname.Namespace);
if (srcSchemas.Count == 0)
{
throw new <API key>(SR.Format(SR.XmlMissingSchema, baseQname.Namespace));
}
if (srcSchemas.Count > 1)
{
throw new <API key>(SR.Format(SR.XmlGetSchemaInclude, baseQname.Namespace, typeof(IXmlSerializable).Name, "GetSchema"));
}
XmlSchema s = (XmlSchema)srcSchemas[0];
XmlSchemaType t = (XmlSchemaType)s.SchemaTypes[baseQname];
t = t.Redefined != null ? t.Redefined : t;
if (_serializables[baseQname] == null)
{
SerializableMapping baseMapping = new SerializableMapping(baseQname, schemas);
SetBase(baseMapping, t.DerivedFrom);
_serializables.Add(baseQname, baseMapping);
}
mapping.SetBaseMapping((SerializableMapping)_serializables[baseQname]);
}
#endif
private static string GetContextName(ImportContext context)
{
switch (context)
{
case ImportContext.Element: return "element";
case ImportContext.Attribute: return "attribute";
case ImportContext.Text: return "text";
default:
throw new ArgumentException(SR.XmlInternalError, nameof(context));
}
}
private static Exception <API key>(Type type)
{
return new <API key>(SR.Format(SR.<API key>, type.FullName));
}
private static Exception <API key>(TypeDesc typeDesc, ImportContext context)
{
return new <API key>(SR.Format(SR.<API key>, typeDesc.FullName, GetContextName(context)));
}
private StructMapping CreateRootMapping()
{
TypeDesc typeDesc = _typeScope.GetTypeDesc(typeof(object));
StructMapping mapping = new StructMapping();
mapping.TypeDesc = typeDesc;
mapping.TypeName = Soap.UrType;
mapping.Namespace = XmlSchema.Namespace;
mapping.Members = Array.Empty<MemberMapping>();
mapping.IncludeInSchema = false;
return mapping;
}
private NullableMapping <API key>(TypeMapping baseMapping, Type type)
{
TypeDesc typeDesc = baseMapping.TypeDesc.GetNullableTypeDesc(type);
TypeMapping existingMapping;
if (!baseMapping.IsAnonymousType)
{
existingMapping = (TypeMapping)_nullables[baseMapping.TypeName, baseMapping.Namespace];
}
else
{
existingMapping = (TypeMapping)_anonymous[type];
}
NullableMapping mapping;
if (existingMapping != null)
{
if (existingMapping is NullableMapping)
{
mapping = (NullableMapping)existingMapping;
if (mapping.BaseMapping is PrimitiveMapping && baseMapping is PrimitiveMapping)
return mapping;
else if (mapping.BaseMapping == baseMapping)
{
return mapping;
}
else
{
throw new <API key>(SR.Format(SR.XmlTypesDuplicate, typeDesc.FullName, existingMapping.TypeDesc.FullName, typeDesc.Name, existingMapping.Namespace));
}
}
else
{
throw new <API key>(SR.Format(SR.XmlTypesDuplicate, typeDesc.FullName, existingMapping.TypeDesc.FullName, typeDesc.Name, existingMapping.Namespace));
}
}
mapping = new NullableMapping();
mapping.BaseMapping = baseMapping;
mapping.TypeDesc = typeDesc;
mapping.TypeName = baseMapping.TypeName;
mapping.Namespace = baseMapping.Namespace;
mapping.IncludeInSchema = baseMapping.IncludeInSchema;
if (!baseMapping.IsAnonymousType)
{
_nullables.Add(baseMapping.TypeName, baseMapping.Namespace, mapping);
}
else
{
_anonymous[type] = mapping;
}
_typeScope.AddTypeMapping(mapping);
return mapping;
}
private StructMapping GetRootMapping()
{
if (_root == null)
{
_root = CreateRootMapping();
_typeScope.AddTypeMapping(_root);
}
return _root;
}
private TypeMapping GetTypeMapping(string typeName, string ns, TypeDesc typeDesc, NameTable typeLib, Type type)
{
TypeMapping mapping;
if (typeName == null || typeName.Length == 0)
mapping = type == null ? null : (TypeMapping)_anonymous[type];
else
mapping = (TypeMapping)typeLib[typeName, ns];
if (mapping == null) return null;
if (!mapping.IsAnonymousType && mapping.TypeDesc != typeDesc)
throw new <API key>(SR.Format(SR.XmlTypesDuplicate, typeDesc.FullName, mapping.TypeDesc.FullName, typeName, ns));
return mapping;
}
private StructMapping <API key>(StructModel model, string ns, bool openModel, XmlAttributes a, RecursionLimiter limiter)
{
if (model.TypeDesc.Kind == TypeKind.Root) return GetRootMapping();
if (a == null)
a = GetAttributes(model.Type, false);
string typeNs = ns;
if (a.XmlType != null && a.XmlType.Namespace != null)
typeNs = a.XmlType.Namespace;
else if (a.XmlRoot != null && a.XmlRoot.Namespace != null)
typeNs = a.XmlRoot.Namespace;
string typeName = IsAnonymousType(a, ns) ? null : XsdTypeName(model.Type, a, model.TypeDesc.Name);
typeName = XmlConvert.EncodeLocalName(typeName);
StructMapping mapping = (StructMapping)GetTypeMapping(typeName, typeNs, model.TypeDesc, _types, model.Type);
if (mapping == null)
{
mapping = new StructMapping();
mapping.TypeDesc = model.TypeDesc;
mapping.Namespace = typeNs;
mapping.TypeName = typeName;
if (!mapping.IsAnonymousType)
_types.Add(typeName, typeNs, mapping);
else
_anonymous[model.Type] = mapping;
if (a.XmlType != null)
{
mapping.IncludeInSchema = a.XmlType.IncludeInSchema;
}
if (limiter.IsExceededLimit)
{
limiter.DeferredWorkItems.Add(new <API key>(model, mapping));
return mapping;
}
limiter.Depth++;
<API key>(mapping, model, openModel, typeName, limiter);
while (limiter.DeferredWorkItems.Count > 0)
{
int index = limiter.DeferredWorkItems.Count - 1;
<API key> item = limiter.DeferredWorkItems[index];
if (<API key>(item.Mapping, item.Model, openModel, typeName, limiter))
{
// if <API key> returns true, then there were *no* changes to the DeferredWorkItems
#if DEBUG
// use exception in the place of Debug.Assert to avoid throwing asserts from a server process such as aspnet_ewp.exe
if (index != limiter.DeferredWorkItems.Count - 1)
throw new <API key>(SR.Format(SR.<API key>, "DeferredWorkItems.Count have changed"));
if (item != limiter.DeferredWorkItems[index])
throw new <API key>(SR.Format(SR.<API key>, "DeferredWorkItems.Top have changed"));
#endif
// Remove the last work item
limiter.DeferredWorkItems.RemoveAt(index);
}
}
limiter.Depth
}
return mapping;
}
private bool <API key>(StructMapping mapping, StructModel model, bool openModel, string typeName, RecursionLimiter limiter)
{
if (mapping.IsFullyInitialized)
return true;
if (model.TypeDesc.BaseTypeDesc != null)
{
TypeModel baseModel = _modelScope.GetTypeModel(model.Type.BaseType, false);
if (!(baseModel is StructModel))
{
//<API key>=Using '{0}' as a base type for a class is not supported by XmlSerializer.
throw new <API key>(SR.Format(SR.<API key>, model.Type.BaseType.FullName));
}
StructMapping baseMapping = <API key>((StructModel)baseModel, mapping.Namespace, openModel, null, limiter);
// check to see if the import of the baseMapping was deferred
int baseIndex = limiter.DeferredWorkItems.IndexOf(baseMapping);
if (baseIndex < 0)
{
mapping.BaseMapping = baseMapping;
ICollection values = mapping.BaseMapping.LocalAttributes.Values;
foreach (AttributeAccessor attribute in values)
{
AddUniqueAccessor(mapping.LocalAttributes, attribute);
}
if (!mapping.BaseMapping.HasExplicitSequence())
{
values = mapping.BaseMapping.LocalElements.Values;
foreach (ElementAccessor e in values)
{
AddUniqueAccessor(mapping.LocalElements, e);
}
}
}
else
{
// the import of the baseMapping was deferred, make sure that the derived mappings is deferred as well
if (!limiter.DeferredWorkItems.Contains(mapping))
{
limiter.DeferredWorkItems.Add(new <API key>(model, mapping));
}
// make sure that baseMapping get processed before the derived
int top = limiter.DeferredWorkItems.Count - 1;
if (baseIndex < top)
{
<API key> baseMappingWorkItem = limiter.DeferredWorkItems[baseIndex];
limiter.DeferredWorkItems[baseIndex] = limiter.DeferredWorkItems[top];
limiter.DeferredWorkItems[top] = baseMappingWorkItem;
}
return false;
}
}
ArrayList members = new ArrayList();
TextAccessor textAccessor = null;
bool hasElements = false;
bool isSequence = false;
foreach (MemberInfo memberInfo in model.GetMemberInfos())
{
if (!(memberInfo is FieldInfo || memberInfo is PropertyInfo))
continue;
XmlAttributes memberAttrs = GetAttributes(memberInfo);
if (memberAttrs.XmlIgnore) continue;
FieldModel fieldModel = model.GetFieldModel(memberInfo);
if (fieldModel == null) continue;
try
{
MemberMapping member = ImportFieldMapping(model, fieldModel, memberAttrs, mapping.Namespace, limiter);
if (member == null) continue;
if (mapping.BaseMapping != null)
{
if (mapping.BaseMapping.Declares(member, mapping.TypeName)) continue;
}
isSequence |= member.IsSequence;
// add All member accessors to the scope accessors
AddUniqueAccessor(member, mapping.LocalElements, mapping.LocalAttributes, isSequence);
if (member.Text != null)
{
if (!member.Text.Mapping.TypeDesc.CanBeTextValue && member.Text.Mapping.IsList)
throw new <API key>(SR.Format(SR.<API key>, typeName, member.Text.Name, member.Text.Mapping.TypeDesc.FullName));
if (textAccessor != null)
{
throw new <API key>(SR.Format(SR.<API key>, model.Type.FullName));
}
textAccessor = member.Text;
}
if (member.Xmlns != null)
{
if (mapping.XmlnsMember != null)
throw new <API key>(SR.Format(SR.XmlMultipleXmlns, model.Type.FullName));
mapping.XmlnsMember = member;
}
if (member.Elements != null && member.Elements.Length != 0)
{
hasElements = true;
}
members.Add(member);
}
catch (Exception e)
{
if (e is <API key>)
{
throw;
}
throw <API key>(fieldModel, e);
}
}
mapping.SetContentModel(textAccessor, hasElements);
if (isSequence)
{
Hashtable ids = new Hashtable();
for (int i = 0; i < members.Count; i++)
{
MemberMapping member = (MemberMapping)members[i];
if (!member.IsParticle)
continue;
if (member.IsSequence)
{
if (ids[member.SequenceId] != null)
{
throw new <API key>(SR.Format(SR.XmlSequenceUnique, member.SequenceId.ToString(CultureInfo.InvariantCulture), "Order", member.Name));
}
ids[member.SequenceId] = member;
}
else
{
throw new <API key>(SR.Format(SR.<API key>, "Order", member.Name));
}
}
members.Sort(new <API key>());
}
mapping.Members = (MemberMapping[])members.ToArray(typeof(MemberMapping));
if (mapping.BaseMapping == null) mapping.BaseMapping = GetRootMapping();
if (mapping.XmlnsMember != null && mapping.BaseMapping.HasXmlnsMember)
throw new <API key>(SR.Format(SR.XmlMultipleXmlns, model.Type.FullName));
IncludeTypes(model.Type, limiter);
_typeScope.AddTypeMapping(mapping);
if (openModel)
mapping.IsOpenModel = true;
return true;
}
private static bool IsAnonymousType(XmlAttributes a, string contextNs)
{
if (a.XmlType != null && a.XmlType.AnonymousType)
{
// check to see if the anonymous type is used in the original context
// only treat it as Anonymous, if the referencing element's namespace
// matches the original referencing element, otherwise revert to
// non-Anonymous handling for backward compatibility.
string originalNs = a.XmlType.Namespace;
return string.IsNullOrEmpty(originalNs) || originalNs == contextNs;
}
return false;
}
internal string XsdTypeName(Type type)
{
if (type == typeof(object)) return Soap.UrType;
TypeDesc typeDesc = _typeScope.GetTypeDesc(type);
if (typeDesc.IsPrimitive && typeDesc.DataType != null && typeDesc.DataType.Name != null && typeDesc.DataType.Name.Length > 0)
return typeDesc.DataType.Name;
return XsdTypeName(type, GetAttributes(type, false), typeDesc.Name);
}
internal string XsdTypeName(Type type, XmlAttributes a, string name)
{
string typeName = name;
if (a.XmlType != null && a.XmlType.TypeName.Length > 0)
typeName = a.XmlType.TypeName;
if (type.IsGenericType && typeName.IndexOf('{') >= 0)
{
Type genType = type.<API key>();
Type[] names = genType.GetGenericArguments();
Type[] types = type.GetGenericArguments();
for (int i = 0; i < names.Length; i++)
{
string argument = "{" + names[i] + "}";
if (typeName.Contains(argument))
{
typeName = typeName.Replace(argument, XsdTypeName(types[i]));
if (typeName.IndexOf('{') < 0)
{
break;
}
}
}
}
return typeName;
}
private static int CountAtLevel(<API key> attributes, int level)
{
int sum = 0;
for (int i = 0; i < attributes.Count; i++)
if (attributes[i].NestingLevel == level) sum++;
return sum;
}
private void SetArrayMappingType(ArrayMapping mapping, string defaultNs, Type type)
{
XmlAttributes a = GetAttributes(type, false);
bool isAnonymous = IsAnonymousType(a, defaultNs);
if (isAnonymous)
{
mapping.TypeName = null;
mapping.Namespace = defaultNs;
return;
}
string name;
string ns;
TypeMapping itemTypeMapping;
ElementAccessor element = null;
if (mapping.Elements.Length == 1)
{
element = mapping.Elements[0];
itemTypeMapping = element.Mapping;
}
else
{
itemTypeMapping = null;
}
bool generateTypeName = true;
if (a.XmlType != null)
{
ns = a.XmlType.Namespace;
name = XsdTypeName(type, a, a.XmlType.TypeName);
name = XmlConvert.EncodeLocalName(name);
generateTypeName = name == null;
}
else if (itemTypeMapping is EnumMapping)
{
ns = itemTypeMapping.Namespace;
name = itemTypeMapping.DefaultElementName;
}
else if (itemTypeMapping is PrimitiveMapping)
{
ns = defaultNs;
name = itemTypeMapping.TypeDesc.DataType.Name;
}
else if (itemTypeMapping is StructMapping && itemTypeMapping.TypeDesc.IsRoot)
{
ns = defaultNs;
name = Soap.UrType;
}
else if (itemTypeMapping != null)
{
ns = itemTypeMapping.Namespace == XmlSchema.Namespace ? defaultNs : itemTypeMapping.Namespace;
name = itemTypeMapping.DefaultElementName;
}
else
{
ns = defaultNs;
name = "Choice" + (_choiceNum++);
}
if (name == null)
name = "Any";
if (element != null)
ns = element.Namespace;
if (ns == null)
ns = defaultNs;
string uniqueName = name = generateTypeName ? "ArrayOf" + CodeIdentifier.MakePascal(name) : name;
int i = 1;
TypeMapping existingMapping = (TypeMapping)_types[uniqueName, ns];
while (existingMapping != null)
{
if (existingMapping is ArrayMapping)
{
ArrayMapping arrayMapping = (ArrayMapping)existingMapping;
if (AccessorMapping.ElementsMatch(arrayMapping.Elements, mapping.Elements))
{
break;
}
}
// need to re-name the mapping
uniqueName = name + i.ToString(CultureInfo.InvariantCulture);
existingMapping = (TypeMapping)_types[uniqueName, ns];
i++;
}
mapping.TypeName = uniqueName;
mapping.Namespace = ns;
}
private ArrayMapping <API key>(ArrayModel model, string ns, RecursionLimiter limiter)
{
ArrayMapping mapping = new ArrayMapping();
mapping.TypeDesc = model.TypeDesc;
if (<API key> == null)
<API key> = new <API key>();
if (CountAtLevel(<API key>, _arrayNestingLevel) == 0)
<API key>.Add(<API key>(_typeScope.GetTypeDesc(model.Element.Type), _arrayNestingLevel));
<API key>(mapping, <API key>, model.Element.Type, <API key> == null ? ns : <API key>, limiter);
SetArrayMappingType(mapping, ns, model.Type);
// reconcile accessors now that we have the ArrayMapping namespace
for (int i = 0; i < mapping.Elements.Length; i++)
{
mapping.Elements[i] = <API key>(mapping.Elements[i], mapping.Namespace);
}
IncludeTypes(model.Type);
// in the case of an ArrayMapping we can have more that one mapping correspond to a type
// examples of that are ArrayList and object[] both will map tp ArrayOfur-type
// so we create a link list for all mappings of the same XSD type
ArrayMapping existingMapping = (ArrayMapping)_types[mapping.TypeName, mapping.Namespace];
if (existingMapping != null)
{
ArrayMapping first = existingMapping;
while (existingMapping != null)
{
if (existingMapping.TypeDesc == model.TypeDesc)
return existingMapping;
existingMapping = existingMapping.Next;
}
mapping.Next = first;
if (!mapping.IsAnonymousType)
_types[mapping.TypeName, mapping.Namespace] = mapping;
else
_anonymous[model.Type] = mapping;
return mapping;
}
_typeScope.AddTypeMapping(mapping);
if (!mapping.IsAnonymousType)
_types.Add(mapping.TypeName, mapping.Namespace, mapping);
else
_anonymous[model.Type] = mapping;
return mapping;
}
private void CheckContext(TypeDesc typeDesc, ImportContext context)
{
switch (context)
{
case ImportContext.Element:
if (typeDesc.CanBeElementValue) return;
break;
case ImportContext.Attribute:
if (typeDesc.CanBeAttributeValue) return;
break;
case ImportContext.Text:
if (typeDesc.CanBeTextValue || typeDesc.IsEnum || typeDesc.IsPrimitive)
return;
break;
default:
throw new ArgumentException(SR.XmlInternalError, nameof(context));
}
throw <API key>(typeDesc, context);
}
private PrimitiveMapping <API key>(PrimitiveModel model, ImportContext context, string dataType, bool repeats)
{
PrimitiveMapping mapping = new PrimitiveMapping();
if (dataType.Length > 0)
{
mapping.TypeDesc = _typeScope.GetTypeDesc(dataType, XmlSchema.Namespace);
if (mapping.TypeDesc == null)
{
// try it as a non-Xsd type
mapping.TypeDesc = _typeScope.GetTypeDesc(dataType, UrtTypes.Namespace);
if (mapping.TypeDesc == null)
{
throw new <API key>(SR.Format(SR.XmlUdeclaredXsdType, dataType));
}
}
}
else
{
mapping.TypeDesc = model.TypeDesc;
}
mapping.TypeName = mapping.TypeDesc.DataType.Name;
mapping.Namespace = mapping.TypeDesc.IsXsdType ? XmlSchema.Namespace : UrtTypes.Namespace;
mapping.IsList = repeats;
CheckContext(mapping.TypeDesc, context);
return mapping;
}
private EnumMapping ImportEnumMapping(EnumModel model, string ns, bool repeats)
{
XmlAttributes a = GetAttributes(model.Type, false);
string typeNs = ns;
if (a.XmlType != null && a.XmlType.Namespace != null)
typeNs = a.XmlType.Namespace;
string typeName = IsAnonymousType(a, ns) ? null : XsdTypeName(model.Type, a, model.TypeDesc.Name);
typeName = XmlConvert.EncodeLocalName(typeName);
EnumMapping mapping = (EnumMapping)GetTypeMapping(typeName, typeNs, model.TypeDesc, _types, model.Type);
if (mapping == null)
{
mapping = new EnumMapping();
mapping.TypeDesc = model.TypeDesc;
mapping.TypeName = typeName;
mapping.Namespace = typeNs;
mapping.IsFlags = model.Type.IsDefined(typeof(FlagsAttribute), false);
if (mapping.IsFlags && repeats)
throw new <API key>(SR.Format(SR.<API key>, model.TypeDesc.FullName));
mapping.IsList = repeats;
mapping.IncludeInSchema = a.XmlType == null ? true : a.XmlType.IncludeInSchema;
if (!mapping.IsAnonymousType)
_types.Add(typeName, typeNs, mapping);
else
_anonymous[model.Type] = mapping;
ArrayList constants = new ArrayList();
for (int i = 0; i < model.Constants.Length; i++)
{
ConstantMapping constant = <API key>(model.Constants[i]);
if (constant != null) constants.Add(constant);
}
if (constants.Count == 0)
{
throw new <API key>(SR.Format(SR.<API key>, model.TypeDesc.FullName));
}
mapping.Constants = (ConstantMapping[])constants.ToArray(typeof(ConstantMapping));
_typeScope.AddTypeMapping(mapping);
}
return mapping;
}
private ConstantMapping <API key>(ConstantModel model)
{
XmlAttributes a = GetAttributes(model.FieldInfo);
if (a.XmlIgnore) return null;
if ((a.XmlFlags & ~XmlAttributeFlags.Enum) != 0)
throw new <API key>(SR.<API key>);
if (a.XmlEnum == null)
a.XmlEnum = new XmlEnumAttribute();
ConstantMapping constant = new ConstantMapping();
constant.XmlName = a.XmlEnum.Name == null ? model.Name : a.XmlEnum.Name;
constant.Name = model.Name;
constant.Value = model.Value;
return constant;
}
private MembersMapping <API key>(XmlReflectionMember[] <API key>, string ns, bool hasWrapperElement, bool rpc, bool openModel, RecursionLimiter limiter)
{
MembersMapping members = new MembersMapping();
members.TypeDesc = _typeScope.GetTypeDesc(typeof(object[]));
MemberMapping[] mappings = new MemberMapping[<API key>.Length];
NameTable elements = new NameTable();
NameTable attributes = new NameTable();
TextAccessor textAccessor = null;
bool isSequence = false;
for (int i = 0; i < mappings.Length; i++)
{
try
{
MemberMapping mapping = ImportMemberMapping(<API key>[i], ns, <API key>, rpc, openModel, limiter);
if (!hasWrapperElement)
{
if (mapping.Attribute != null)
{
if (rpc)
{
throw new <API key>(SR.<API key>);
}
else
{
throw new <API key>(SR.Format(SR.<API key>, "XmlAttribute"));
}
}
}
if (rpc && <API key>[i].IsReturnValue)
{
if (i > 0) throw new <API key>(SR.<API key>);
mapping.IsReturnValue = true;
}
mappings[i] = mapping;
isSequence |= mapping.IsSequence;
if (!<API key>[i].XmlAttributes.XmlIgnore)
{
// add All member accessors to the scope accessors
AddUniqueAccessor(mapping, elements, attributes, isSequence);
}
mappings[i] = mapping;
if (mapping.Text != null)
{
if (textAccessor != null)
{
throw new <API key>(SR.<API key>);
}
textAccessor = mapping.Text;
}
if (mapping.Xmlns != null)
{
if (members.XmlnsMember != null)
throw new <API key>(SR.<API key>);
members.XmlnsMember = mapping;
}
}
catch (Exception e)
{
if (e is <API key>)
{
throw;
}
throw <API key>(<API key>[i].MemberName, e);
}
}
if (isSequence)
{
throw new <API key>(SR.Format(SR.XmlSequenceMembers, "Order"));
}
members.Members = mappings;
members.HasWrapperElement = hasWrapperElement;
return members;
}
private MemberMapping ImportMemberMapping(XmlReflectionMember xmlReflectionMember, string ns, XmlReflectionMember[] <API key>, bool rpc, bool openModel, RecursionLimiter limiter)
{
XmlSchemaForm form = rpc ? XmlSchemaForm.Unqualified : XmlSchemaForm.Qualified;
XmlAttributes a = xmlReflectionMember.XmlAttributes;
TypeDesc typeDesc = _typeScope.GetTypeDesc(xmlReflectionMember.MemberType);
if (a.XmlFlags == 0)
{
if (typeDesc.IsArrayLike)
{
XmlArrayAttribute xmlArray = <API key>(typeDesc);
xmlArray.ElementName = xmlReflectionMember.MemberName;
xmlArray.Namespace = rpc ? null : ns;
xmlArray.Form = form;
a.XmlArray = xmlArray;
}
else
{
XmlElementAttribute xmlElement = <API key>(typeDesc);
// If there is no metadata specified on a parameter, then see if someone used
// an XmlRoot attribute on the struct or class.
if (typeDesc.IsStructLike)
{
XmlAttributes structAttrs = new XmlAttributes(xmlReflectionMember.MemberType);
if (structAttrs.XmlRoot != null)
{
if (structAttrs.XmlRoot.ElementName.Length > 0)
xmlElement.ElementName = structAttrs.XmlRoot.ElementName;
if (rpc)
{
xmlElement.Namespace = null;
if (structAttrs.XmlRoot.<API key>())
xmlElement.IsNullable = structAttrs.XmlRoot.IsNullable;
}
else
{
xmlElement.Namespace = structAttrs.XmlRoot.Namespace;
xmlElement.IsNullable = structAttrs.XmlRoot.IsNullable;
}
}
}
if (xmlElement.ElementName.Length == 0)
xmlElement.ElementName = xmlReflectionMember.MemberName;
if (xmlElement.Namespace == null && !rpc)
xmlElement.Namespace = ns;
xmlElement.Form = form;
a.XmlElements.Add(xmlElement);
}
}
else if (a.XmlRoot != null)
{
CheckNullable(a.XmlRoot.IsNullable, typeDesc, null);
}
MemberMapping member = new MemberMapping();
member.Name = xmlReflectionMember.MemberName;
bool checkSpecified = FindSpecifiedMember(xmlReflectionMember.MemberName, <API key>) != null;
FieldModel model = new FieldModel(xmlReflectionMember.MemberName, xmlReflectionMember.MemberType, _typeScope.GetTypeDesc(xmlReflectionMember.MemberType), checkSpecified, false);
member.CheckShouldPersist = model.CheckShouldPersist;
member.CheckSpecified = model.CheckSpecified;
member.ReadOnly = model.ReadOnly; // || !model.FieldTypeDesc.<API key>;
Type <API key> = null;
if (a.XmlChoiceIdentifier != null)
{
<API key> = <API key>(a.XmlChoiceIdentifier, <API key>, typeDesc.IsArrayLike, model.Name);
}
<API key>(member, model, a, ns, <API key>, rpc, openModel, limiter);
if (xmlReflectionMember.OverrideIsNullable && member.Elements.Length > 0)
member.Elements[0].IsNullable = false;
return member;
}
internal static XmlReflectionMember FindSpecifiedMember(string memberName, XmlReflectionMember[] reflectionMembers)
{
for (int i = 0; i < reflectionMembers.Length; i++)
if (string.Compare(reflectionMembers[i].MemberName, memberName + "Specified", StringComparison.Ordinal) == 0)
return reflectionMembers[i];
return null;
}
private MemberMapping ImportFieldMapping(StructModel parent, FieldModel model, XmlAttributes a, string ns, RecursionLimiter limiter)
{
MemberMapping member = new MemberMapping();
member.Name = model.Name;
member.CheckShouldPersist = model.CheckShouldPersist;
member.CheckSpecified = model.CheckSpecified;
member.MemberInfo = model.MemberInfo;
member.<API key> = model.<API key>;
member.<API key> = model.<API key>;
member.ReadOnly = model.ReadOnly; // || !model.FieldTypeDesc.<API key>;
Type <API key> = null;
if (a.XmlChoiceIdentifier != null)
{
<API key> = <API key>(a.XmlChoiceIdentifier, parent, model.FieldTypeDesc.IsArrayLike, model.Name);
}
<API key>(member, model, a, ns, <API key>, false, false, limiter);
return member;
}
private Type <API key>(Type type, bool isArrayLike, string identifierName, string memberName)
{
if (type.IsArray)
{
if (!isArrayLike)
{
// Inconsistent type of the choice identifier '{0}'. Please use {1}.
throw new <API key>(SR.Format(SR.<API key>, identifierName, memberName, type.GetElementType().FullName));
}
type = type.GetElementType();
}
else if (isArrayLike)
{
// Inconsistent type of the choice identifier '{0}'. Please use {1}.
throw new <API key>(SR.Format(SR.<API key>, identifierName, memberName, type.FullName));
}
if (!type.IsEnum)
{
// Choice identifier '{0}' must be an enum.
throw new <API key>(SR.Format(SR.<API key>, identifierName));
}
return type;
}
private Type <API key>(<API key> choice, XmlReflectionMember[] <API key>, bool isArrayLike, string accessorName)
{
for (int i = 0; i < <API key>.Length; i++)
{
if (choice.MemberName == <API key>[i].MemberName)
{
return <API key>(<API key>[i].MemberType, isArrayLike, choice.MemberName, accessorName);
}
}
// Missing '{0}' needed for serialization of choice '{1}'.
throw new <API key>(SR.Format(SR.<API key>, choice.MemberName, accessorName));
}
private Type <API key>(<API key> choice, StructModel structModel, bool isArrayLike, string accessorName)
{
// check that the choice field exists
MemberInfo[] infos = structModel.Type.GetMember(choice.MemberName, BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static);
if (infos == null || infos.Length == 0)
{
// if we can not find the choice identifier between fields, check properties
PropertyInfo info = structModel.Type.GetProperty(choice.MemberName, BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static);
if (info == null)
{
// Missing '{0}' needed for serialization of choice '{1}'.
throw new <API key>(SR.Format(SR.<API key>, choice.MemberName, accessorName));
}
infos = new MemberInfo[] { info };
}
else if (infos.Length > 1)
{
// Ambiguous choice identifier: there are several members named '{0}'.
throw new <API key>(SR.Format(SR.<API key>, choice.MemberName));
}
FieldModel member = structModel.GetFieldModel(infos[0]);
if (member == null)
{
// Missing '{0}' needed for serialization of choice '{1}'.
throw new <API key>(SR.Format(SR.<API key>, choice.MemberName, accessorName));
}
choice.SetMemberInfo(member.MemberInfo);
Type enumType = member.FieldType;
enumType = <API key>(enumType, isArrayLike, choice.MemberName, accessorName);
return enumType;
}
private void <API key>(ArrayMapping arrayMapping, <API key> attributes, Type arrayElementType, string arrayElementNs, RecursionLimiter limiter)
{
NameTable arrayItemElements = new NameTable(); // xmlelementname + xmlns -> ElementAccessor
for (int i = 0; attributes != null && i < attributes.Count; i++)
{
<API key> xmlArrayItem = attributes[i];
if (xmlArrayItem.NestingLevel != _arrayNestingLevel)
continue;
Type targetType = xmlArrayItem.Type != null ? xmlArrayItem.Type : arrayElementType;
TypeDesc targetTypeDesc = _typeScope.GetTypeDesc(targetType);
ElementAccessor arrayItemElement = new ElementAccessor();
arrayItemElement.Namespace = xmlArrayItem.Namespace == null ? arrayElementNs : xmlArrayItem.Namespace;
arrayItemElement.Mapping = ImportTypeMapping(_modelScope.GetTypeModel(targetType), arrayItemElement.Namespace, ImportContext.Element, xmlArrayItem.DataType, null, limiter);
arrayItemElement.Name = xmlArrayItem.ElementName.Length == 0 ? arrayItemElement.Mapping.DefaultElementName : XmlConvert.EncodeLocalName(xmlArrayItem.ElementName);
arrayItemElement.IsNullable = xmlArrayItem.<API key>() ? xmlArrayItem.IsNullable : targetTypeDesc.IsNullable || targetTypeDesc.IsOptionalValue;
arrayItemElement.Form = xmlArrayItem.Form == XmlSchemaForm.None ? XmlSchemaForm.Qualified : xmlArrayItem.Form;
CheckForm(arrayItemElement.Form, arrayElementNs != arrayItemElement.Namespace);
CheckNullable(arrayItemElement.IsNullable, targetTypeDesc, arrayItemElement.Mapping);
AddUniqueAccessor(arrayItemElements, arrayItemElement);
}
arrayMapping.Elements = (ElementAccessor[])arrayItemElements.ToArray(typeof(ElementAccessor));
}
private void <API key>(MemberMapping accessor, FieldModel model, XmlAttributes a, string ns, Type <API key>, bool rpc, bool openModel, RecursionLimiter limiter)
{
XmlSchemaForm elementFormDefault = XmlSchemaForm.Qualified;
int <API key> = _arrayNestingLevel;
int sequenceId = -1;
<API key> <API key> = <API key>;
string <API key> = <API key>;
_arrayNestingLevel = 0;
<API key> = null;
<API key> = null;
Type accessorType = model.FieldType;
string accessorName = model.Name;
ArrayList elementList = new ArrayList();
NameTable elements = new NameTable();
accessor.TypeDesc = _typeScope.GetTypeDesc(accessorType);
XmlAttributeFlags flags = a.XmlFlags;
accessor.Ignore = a.XmlIgnore;
if (rpc)
<API key>(a, accessorName);
else
<API key>(a, accessorType, accessorName);
XmlAttributeFlags elemFlags = XmlAttributeFlags.Elements | XmlAttributeFlags.Text | XmlAttributeFlags.AnyElements | XmlAttributeFlags.ChoiceIdentifier;
XmlAttributeFlags attrFlags = XmlAttributeFlags.Attribute | XmlAttributeFlags.AnyAttribute;
XmlAttributeFlags arrayFlags = XmlAttributeFlags.Array | XmlAttributeFlags.ArrayItems;
// special case for byte[]. It can be a primitive (base64Binary or hexBinary), or it can
// be an array of bytes. Our default is primitive; specify [XmlArray] to get array behavior.
if ((flags & arrayFlags) != 0 && accessorType == typeof(byte[]))
accessor.TypeDesc = _typeScope.GetArrayTypeDesc(accessorType);
if (a.XmlChoiceIdentifier != null)
{
accessor.ChoiceIdentifier = new <API key>();
accessor.ChoiceIdentifier.MemberName = a.XmlChoiceIdentifier.MemberName;
accessor.ChoiceIdentifier.MemberInfo = a.XmlChoiceIdentifier.GetMemberInfo();
accessor.ChoiceIdentifier.Mapping = ImportTypeMapping(_modelScope.GetTypeModel(<API key>), ns, ImportContext.Element, String.Empty, null, limiter);
<API key>((EnumMapping)accessor.ChoiceIdentifier.Mapping);
}
if (accessor.TypeDesc.IsArrayLike)
{
Type arrayElementType = TypeScope.GetArrayElementType(accessorType, model.FieldTypeDesc.FullName + "." + model.Name);
if ((flags & attrFlags) != 0)
{
if ((flags & attrFlags) != flags)
throw new <API key>(SR.<API key>);
if (a.XmlAttribute != null && !accessor.TypeDesc.<API key>.IsPrimitive && !accessor.TypeDesc.<API key>.IsEnum)
{
if (accessor.TypeDesc.<API key>.Kind == TypeKind.Serializable)
{
throw new <API key>(SR.Format(SR.<API key>, accessorName, accessor.TypeDesc.<API key>.FullName, typeof(IXmlSerializable).Name));
}
else
{
throw new <API key>(SR.Format(SR.<API key>, accessorName, accessor.TypeDesc.<API key>.FullName));
}
}
bool isList = a.XmlAttribute != null && (accessor.TypeDesc.<API key>.IsPrimitive || accessor.TypeDesc.<API key>.IsEnum);
if (a.XmlAnyAttribute != null)
{
a.XmlAttribute = new <API key>();
}
AttributeAccessor attribute = new AttributeAccessor();
Type targetType = a.XmlAttribute.Type == null ? arrayElementType : a.XmlAttribute.Type;
TypeDesc targetTypeDesc = _typeScope.GetTypeDesc(targetType);
attribute.Name = Accessor.EscapeQName(a.XmlAttribute.AttributeName.Length == 0 ? accessorName : a.XmlAttribute.AttributeName);
attribute.Namespace = a.XmlAttribute.Namespace == null ? ns : a.XmlAttribute.Namespace;
attribute.Form = a.XmlAttribute.Form;
if (attribute.Form == XmlSchemaForm.None && ns != attribute.Namespace)
{
attribute.Form = XmlSchemaForm.Qualified;
}
attribute.CheckSpecial();
CheckForm(attribute.Form, ns != attribute.Namespace);
attribute.Mapping = ImportTypeMapping(_modelScope.GetTypeModel(targetType), ns, ImportContext.Attribute, a.XmlAttribute.DataType, null, isList, false, limiter);
attribute.IsList = isList;
attribute.Default = GetDefaultValue(model.FieldTypeDesc, model.FieldType, a);
attribute.Any = (a.XmlAnyAttribute != null);
if (attribute.Form == XmlSchemaForm.Qualified && attribute.Namespace != ns)
{
if (_xsdAttributes == null)
_xsdAttributes = new NameTable();
attribute = (AttributeAccessor)ReconcileAccessor(attribute, _xsdAttributes);
}
accessor.Attribute = attribute;
}
else if ((flags & elemFlags) != 0)
{
if ((flags & elemFlags) != flags)
throw new <API key>(SR.<API key>);
if (a.XmlText != null)
{
TextAccessor text = new TextAccessor();
Type targetType = a.XmlText.Type == null ? arrayElementType : a.XmlText.Type;
TypeDesc targetTypeDesc = _typeScope.GetTypeDesc(targetType);
text.Name = accessorName; // unused except to make more helpful error messages
text.Mapping = ImportTypeMapping(_modelScope.GetTypeModel(targetType), ns, ImportContext.Text, a.XmlText.DataType, null, true, false, limiter);
if (!(text.Mapping is SpecialMapping) && targetTypeDesc != _typeScope.GetTypeDesc(typeof(string)))
throw new <API key>(SR.Format(SR.<API key>, accessorName));
accessor.Text = text;
}
if (a.XmlText == null && a.XmlElements.Count == 0 && a.XmlAnyElements.Count == 0)
a.XmlElements.Add(<API key>(accessor.TypeDesc));
for (int i = 0; i < a.XmlElements.Count; i++)
{
XmlElementAttribute xmlElement = a.XmlElements[i];
Type targetType = xmlElement.Type == null ? arrayElementType : xmlElement.Type;
TypeDesc targetTypeDesc = _typeScope.GetTypeDesc(targetType);
TypeModel typeModel = _modelScope.GetTypeModel(targetType);
ElementAccessor element = new ElementAccessor();
element.Namespace = rpc ? null : xmlElement.Namespace == null ? ns : xmlElement.Namespace;
element.Mapping = ImportTypeMapping(typeModel, rpc ? ns : element.Namespace, ImportContext.Element, xmlElement.DataType, null, limiter);
if (a.XmlElements.Count == 1)
{
element.Name = XmlConvert.EncodeLocalName(xmlElement.ElementName.Length == 0 ? accessorName : xmlElement.ElementName);
//element.IsUnbounded = element.Mapping is ArrayMapping;
}
else
{
element.Name = xmlElement.ElementName.Length == 0 ? element.Mapping.DefaultElementName : XmlConvert.EncodeLocalName(xmlElement.ElementName);
}
element.Default = GetDefaultValue(model.FieldTypeDesc, model.FieldType, a);
if (xmlElement.<API key>() && !xmlElement.IsNullable && typeModel.TypeDesc.IsOptionalValue)
//<API key>=IsNullable may not be set to 'false' for a Nullable<{0}> type. Consider using '{0}' type or removing the IsNullable property from the XmlElement attribute.
throw new <API key>(SR.Format(SR.<API key>, typeModel.TypeDesc.BaseTypeDesc.FullName, "XmlElement"));
element.IsNullable = xmlElement.<API key>() ? xmlElement.IsNullable : typeModel.TypeDesc.IsOptionalValue;
element.Form = rpc ? XmlSchemaForm.Unqualified : xmlElement.Form == XmlSchemaForm.None ? elementFormDefault : xmlElement.Form;
CheckNullable(element.IsNullable, targetTypeDesc, element.Mapping);
if (!rpc)
{
CheckForm(element.Form, ns != element.Namespace);
element = <API key>(element, ns);
}
if (xmlElement.Order != -1)
{
if (xmlElement.Order != sequenceId && sequenceId != -1)
throw new <API key>(SR.Format(SR.XmlSequenceMatch, "Order"));
sequenceId = xmlElement.Order;
}
AddUniqueAccessor(elements, element);
elementList.Add(element);
}
NameTable anys = new NameTable();
for (int i = 0; i < a.XmlAnyElements.Count; i++)
{
<API key> xmlAnyElement = a.XmlAnyElements[i];
Type targetType = typeof(IXmlSerializable).IsAssignableFrom(arrayElementType) ? arrayElementType : typeof(XmlNode).IsAssignableFrom(arrayElementType) ? arrayElementType : typeof(XmlElement);
if (!arrayElementType.IsAssignableFrom(targetType))
throw new <API key>(SR.Format(SR.<API key>, arrayElementType.FullName));
string anyName = xmlAnyElement.Name.Length == 0 ? xmlAnyElement.Name : XmlConvert.EncodeLocalName(xmlAnyElement.Name);
string anyNs = xmlAnyElement.<API key>() ? xmlAnyElement.Namespace : null;
if (anys[anyName, anyNs] != null)
{
// ignore duplicate anys
continue;
}
anys[anyName, anyNs] = xmlAnyElement;
if (elements[anyName, (anyNs == null ? ns : anyNs)] != null)
{
throw new <API key>(SR.Format(SR.<API key>, accessorName, xmlAnyElement.Name, xmlAnyElement.Namespace == null ? "null" : xmlAnyElement.Namespace));
}
ElementAccessor element = new ElementAccessor();
element.Name = anyName;
element.Namespace = anyNs == null ? ns : anyNs;
element.Any = true;
element.AnyNamespaces = anyNs;
TypeDesc targetTypeDesc = _typeScope.GetTypeDesc(targetType);
TypeModel typeModel = _modelScope.GetTypeModel(targetType);
if (element.Name.Length > 0)
typeModel.TypeDesc.IsMixed = true;
element.Mapping = ImportTypeMapping(typeModel, element.Namespace, ImportContext.Element, String.Empty, null, limiter);
element.Default = GetDefaultValue(model.FieldTypeDesc, model.FieldType, a);
element.IsNullable = false;
element.Form = elementFormDefault;
CheckNullable(element.IsNullable, targetTypeDesc, element.Mapping);
if (!rpc)
{
CheckForm(element.Form, ns != element.Namespace);
element = <API key>(element, ns);
}
elements.Add(element.Name, element.Namespace, element);
elementList.Add(element);
if (xmlAnyElement.Order != -1)
{
if (xmlAnyElement.Order != sequenceId && sequenceId != -1)
throw new <API key>(SR.Format(SR.XmlSequenceMatch, "Order"));
sequenceId = xmlAnyElement.Order;
}
}
}
else
{
if ((flags & arrayFlags) != 0)
{
if ((flags & arrayFlags) != flags)
throw new <API key>(SR.<API key>);
}
TypeDesc <API key> = _typeScope.GetTypeDesc(arrayElementType);
if (a.XmlArray == null)
a.XmlArray = <API key>(accessor.TypeDesc);
if (CountAtLevel(a.XmlArrayItems, _arrayNestingLevel) == 0)
a.XmlArrayItems.Add(<API key>(<API key>, _arrayNestingLevel));
ElementAccessor arrayElement = new ElementAccessor();
arrayElement.Name = XmlConvert.EncodeLocalName(a.XmlArray.ElementName.Length == 0 ? accessorName : a.XmlArray.ElementName);
arrayElement.Namespace = rpc ? null : a.XmlArray.Namespace == null ? ns : a.XmlArray.Namespace;
<API key> = a.XmlArrayItems;
<API key> = arrayElement.Namespace;
ArrayMapping arrayMapping = <API key>(_modelScope.GetArrayModel(accessorType), ns, limiter);
arrayElement.Mapping = arrayMapping;
arrayElement.IsNullable = a.XmlArray.IsNullable;
arrayElement.Form = rpc ? XmlSchemaForm.Unqualified : a.XmlArray.Form == XmlSchemaForm.None ? elementFormDefault : a.XmlArray.Form;
sequenceId = a.XmlArray.Order;
CheckNullable(arrayElement.IsNullable, accessor.TypeDesc, arrayElement.Mapping);
if (!rpc)
{
CheckForm(arrayElement.Form, ns != arrayElement.Namespace);
arrayElement = <API key>(arrayElement, ns);
}
<API key> = null;
<API key> = null;
AddUniqueAccessor(elements, arrayElement);
elementList.Add(arrayElement);
}
}
else if (!accessor.TypeDesc.IsVoid)
{
XmlAttributeFlags allFlags = XmlAttributeFlags.Elements | XmlAttributeFlags.Text | XmlAttributeFlags.Attribute | XmlAttributeFlags.AnyElements | XmlAttributeFlags.ChoiceIdentifier | XmlAttributeFlags.XmlnsDeclarations;
if ((flags & allFlags) != flags)
throw new <API key>(SR.XmlIllegalAttribute);
if (accessor.TypeDesc.IsPrimitive || accessor.TypeDesc.IsEnum)
{
if (a.XmlAnyElements.Count > 0) throw new <API key>(SR.Format(SR.<API key>, accessor.TypeDesc.FullName));
if (a.XmlAttribute != null)
{
if (a.XmlElements.Count > 0) throw new <API key>(SR.XmlIllegalAttribute);
if (a.XmlAttribute.Type != null) throw new <API key>(SR.Format(SR.XmlIllegalType, "XmlAttribute"));
AttributeAccessor attribute = new AttributeAccessor();
attribute.Name = Accessor.EscapeQName(a.XmlAttribute.AttributeName.Length == 0 ? accessorName : a.XmlAttribute.AttributeName);
attribute.Namespace = a.XmlAttribute.Namespace == null ? ns : a.XmlAttribute.Namespace;
attribute.Form = a.XmlAttribute.Form;
if (attribute.Form == XmlSchemaForm.None && ns != attribute.Namespace)
{
attribute.Form = XmlSchemaForm.Qualified;
}
attribute.CheckSpecial();
CheckForm(attribute.Form, ns != attribute.Namespace);
attribute.Mapping = ImportTypeMapping(_modelScope.GetTypeModel(accessorType), ns, ImportContext.Attribute, a.XmlAttribute.DataType, null, limiter);
attribute.Default = GetDefaultValue(model.FieldTypeDesc, model.FieldType, a);
attribute.Any = a.XmlAnyAttribute != null;
if (attribute.Form == XmlSchemaForm.Qualified && attribute.Namespace != ns)
{
if (_xsdAttributes == null)
_xsdAttributes = new NameTable();
attribute = (AttributeAccessor)ReconcileAccessor(attribute, _xsdAttributes);
}
accessor.Attribute = attribute;
}
else
{
if (a.XmlText != null)
{
if (a.XmlText.Type != null && a.XmlText.Type != accessorType)
throw new <API key>(SR.Format(SR.XmlIllegalType, "XmlText"));
TextAccessor text = new TextAccessor();
text.Name = accessorName; // unused except to make more helpful error messages
text.Mapping = ImportTypeMapping(_modelScope.GetTypeModel(accessorType), ns, ImportContext.Text, a.XmlText.DataType, null, limiter);
accessor.Text = text;
}
else if (a.XmlElements.Count == 0)
{
a.XmlElements.Add(<API key>(accessor.TypeDesc));
}
for (int i = 0; i < a.XmlElements.Count; i++)
{
XmlElementAttribute xmlElement = a.XmlElements[i];
if (xmlElement.Type != null)
{
if (_typeScope.GetTypeDesc(xmlElement.Type) != accessor.TypeDesc)
throw new <API key>(SR.Format(SR.XmlIllegalType, "XmlElement"));
}
ElementAccessor element = new ElementAccessor();
element.Name = XmlConvert.EncodeLocalName(xmlElement.ElementName.Length == 0 ? accessorName : xmlElement.ElementName);
element.Namespace = rpc ? null : xmlElement.Namespace == null ? ns : xmlElement.Namespace;
TypeModel typeModel = _modelScope.GetTypeModel(accessorType);
element.Mapping = ImportTypeMapping(typeModel, rpc ? ns : element.Namespace, ImportContext.Element, xmlElement.DataType, null, limiter);
if (element.Mapping.TypeDesc.Kind == TypeKind.Node)
{
element.Any = true;
}
element.Default = GetDefaultValue(model.FieldTypeDesc, model.FieldType, a);
if (xmlElement.<API key>() && !xmlElement.IsNullable && typeModel.TypeDesc.IsOptionalValue)
//<API key>=IsNullable may not be set to 'false' for a Nullable<{0}> type. Consider using '{0}' type or removing the IsNullable property from the XmlElement attribute.
throw new <API key>(SR.Format(SR.<API key>, typeModel.TypeDesc.BaseTypeDesc.FullName, "XmlElement"));
element.IsNullable = xmlElement.<API key>() ? xmlElement.IsNullable : typeModel.TypeDesc.IsOptionalValue;
element.Form = rpc ? XmlSchemaForm.Unqualified : xmlElement.Form == XmlSchemaForm.None ? elementFormDefault : xmlElement.Form;
CheckNullable(element.IsNullable, accessor.TypeDesc, element.Mapping);
if (!rpc)
{
CheckForm(element.Form, ns != element.Namespace);
element = <API key>(element, ns);
}
if (xmlElement.Order != -1)
{
if (xmlElement.Order != sequenceId && sequenceId != -1)
throw new <API key>(SR.Format(SR.XmlSequenceMatch, "Order"));
sequenceId = xmlElement.Order;
}
AddUniqueAccessor(elements, element);
elementList.Add(element);
}
}
}
else if (a.Xmlns)
{
if (flags != XmlAttributeFlags.XmlnsDeclarations)
throw new <API key>(SR.<API key>);
if (accessorType != typeof(System.Xml.Serialization.<API key>))
{
throw new <API key>(SR.Format(SR.XmlXmlnsInvalidType, accessorName, accessorType.FullName, typeof(System.Xml.Serialization.<API key>).FullName));
}
accessor.Xmlns = new XmlnsAccessor();
accessor.Ignore = true;
}
else
{
if (a.XmlAttribute != null || a.XmlText != null)
{
if (accessor.TypeDesc.Kind == TypeKind.Serializable)
{
throw new <API key>(SR.Format(SR.<API key>, accessorName, accessor.TypeDesc.FullName, typeof(IXmlSerializable).Name));
}
else
{
throw new <API key>(SR.Format(SR.<API key>, accessorName, accessor.TypeDesc));
}
}
if (a.XmlElements.Count == 0 && a.XmlAnyElements.Count == 0)
a.XmlElements.Add(<API key>(accessor.TypeDesc));
for (int i = 0; i < a.XmlElements.Count; i++)
{
XmlElementAttribute xmlElement = a.XmlElements[i];
Type targetType = xmlElement.Type == null ? accessorType : xmlElement.Type;
TypeDesc targetTypeDesc = _typeScope.GetTypeDesc(targetType);
ElementAccessor element = new ElementAccessor();
TypeModel typeModel = _modelScope.GetTypeModel(targetType);
element.Namespace = rpc ? null : xmlElement.Namespace == null ? ns : xmlElement.Namespace;
element.Mapping = ImportTypeMapping(typeModel, rpc ? ns : element.Namespace, ImportContext.Element, xmlElement.DataType, null, false, openModel, limiter);
if (a.XmlElements.Count == 1)
{
element.Name = XmlConvert.EncodeLocalName(xmlElement.ElementName.Length == 0 ? accessorName : xmlElement.ElementName);
}
else
{
element.Name = xmlElement.ElementName.Length == 0 ? element.Mapping.DefaultElementName : XmlConvert.EncodeLocalName(xmlElement.ElementName);
}
element.Default = GetDefaultValue(model.FieldTypeDesc, model.FieldType, a);
if (xmlElement.<API key>() && !xmlElement.IsNullable && typeModel.TypeDesc.IsOptionalValue)
//<API key>=IsNullable may not be set to 'false' for a Nullable<{0}> type. Consider using '{0}' type or removing the IsNullable property from the XmlElement attribute.
throw new <API key>(SR.Format(SR.<API key>, typeModel.TypeDesc.BaseTypeDesc.FullName, "XmlElement"));
element.IsNullable = xmlElement.<API key>() ? xmlElement.IsNullable : typeModel.TypeDesc.IsOptionalValue;
element.Form = rpc ? XmlSchemaForm.Unqualified : xmlElement.Form == XmlSchemaForm.None ? elementFormDefault : xmlElement.Form;
CheckNullable(element.IsNullable, targetTypeDesc, element.Mapping);
if (!rpc)
{
CheckForm(element.Form, ns != element.Namespace);
element = <API key>(element, ns);
}
if (xmlElement.Order != -1)
{
if (xmlElement.Order != sequenceId && sequenceId != -1)
throw new <API key>(SR.Format(SR.XmlSequenceMatch, "Order"));
sequenceId = xmlElement.Order;
}
AddUniqueAccessor(elements, element);
elementList.Add(element);
}
NameTable anys = new NameTable();
for (int i = 0; i < a.XmlAnyElements.Count; i++)
{
<API key> xmlAnyElement = a.XmlAnyElements[i];
Type targetType = typeof(IXmlSerializable).IsAssignableFrom(accessorType) ? accessorType : typeof(XmlNode).IsAssignableFrom(accessorType) ? accessorType : typeof(XmlElement);
if (!accessorType.IsAssignableFrom(targetType))
throw new <API key>(SR.Format(SR.<API key>, accessorType.FullName));
string anyName = xmlAnyElement.Name.Length == 0 ? xmlAnyElement.Name : XmlConvert.EncodeLocalName(xmlAnyElement.Name);
string anyNs = xmlAnyElement.<API key>() ? xmlAnyElement.Namespace : null;
if (anys[anyName, anyNs] != null)
{
// ignore duplicate anys
continue;
}
anys[anyName, anyNs] = xmlAnyElement;
if (elements[anyName, (anyNs == null ? ns : anyNs)] != null)
{
throw new <API key>(SR.Format(SR.<API key>, accessorName, xmlAnyElement.Name, xmlAnyElement.Namespace == null ? "null" : xmlAnyElement.Namespace));
}
ElementAccessor element = new ElementAccessor();
element.Name = anyName;
element.Namespace = anyNs == null ? ns : anyNs;
element.Any = true;
element.AnyNamespaces = anyNs;
TypeDesc targetTypeDesc = _typeScope.GetTypeDesc(targetType);
TypeModel typeModel = _modelScope.GetTypeModel(targetType);
if (element.Name.Length > 0)
typeModel.TypeDesc.IsMixed = true;
element.Mapping = ImportTypeMapping(typeModel, element.Namespace, ImportContext.Element, String.Empty, null, false, openModel, limiter);
element.Default = GetDefaultValue(model.FieldTypeDesc, model.FieldType, a);
element.IsNullable = false;
element.Form = elementFormDefault;
CheckNullable(element.IsNullable, targetTypeDesc, element.Mapping);
if (!rpc)
{
CheckForm(element.Form, ns != element.Namespace);
element = <API key>(element, ns);
}
if (xmlAnyElement.Order != -1)
{
if (xmlAnyElement.Order != sequenceId && sequenceId != -1)
throw new <API key>(SR.Format(SR.XmlSequenceMatch, "Order"));
sequenceId = xmlAnyElement.Order;
}
elements.Add(element.Name, element.Namespace, element);
elementList.Add(element);
}
}
}
accessor.Elements = (ElementAccessor[])elementList.ToArray(typeof(ElementAccessor));
accessor.SequenceId = sequenceId;
if (rpc)
{
if (accessor.TypeDesc.IsArrayLike && accessor.Elements.Length > 0 && !(accessor.Elements[0].Mapping is ArrayMapping))
throw new <API key>(SR.Format(SR.<API key>, accessor.Elements[0].Name));
if (accessor.Xmlns != null)
throw new <API key>(SR.Format(SR.XmlRpcLitXmlns, accessor.Name));
}
if (accessor.ChoiceIdentifier != null)
{
// find the enum value corresponding to each element
accessor.ChoiceIdentifier.MemberIds = new string[accessor.Elements.Length];
for (int i = 0; i < accessor.Elements.Length; i++)
{
bool found = false;
ElementAccessor element = accessor.Elements[i];
EnumMapping choiceMapping = (EnumMapping)accessor.ChoiceIdentifier.Mapping;
for (int j = 0; j < choiceMapping.Constants.Length; j++)
{
string xmlName = choiceMapping.Constants[j].XmlName;
if (element.Any && element.Name.Length == 0)
{
string anyNs = element.AnyNamespaces == null ? "##any" : element.AnyNamespaces;
if (xmlName.Substring(0, xmlName.Length - 1) == anyNs)
{
accessor.ChoiceIdentifier.MemberIds[i] = choiceMapping.Constants[j].Name;
found = true;
break;
}
continue;
}
int colon = xmlName.LastIndexOf(':');
string choiceNs = colon < 0 ? choiceMapping.Namespace : xmlName.Substring(0, colon);
string choiceName = colon < 0 ? xmlName : xmlName.Substring(colon + 1);
if (element.Name == choiceName)
{
if ((element.Form == XmlSchemaForm.Unqualified && string.IsNullOrEmpty(choiceNs)) || element.Namespace == choiceNs)
{
accessor.ChoiceIdentifier.MemberIds[i] = choiceMapping.Constants[j].Name;
found = true;
break;
}
}
}
if (!found)
{
if (element.Any && element.Name.Length == 0)
{
// Type {0} is missing enumeration value '##any' for <API key>.
throw new <API key>(SR.Format(SR.<API key>, accessor.ChoiceIdentifier.Mapping.TypeDesc.FullName));
}
else
{
string id = element.Namespace != null && element.Namespace.Length > 0 ? element.Namespace + ":" + element.Name : element.Name;
// Type {0} is missing value for '{1}'.
throw new <API key>(SR.Format(SR.<API key>, accessor.ChoiceIdentifier.Mapping.TypeDesc.FullName, id, element.Name, element.Namespace));
}
}
}
}
_arrayNestingLevel = <API key>;
<API key> = <API key>;
<API key> = <API key>;
}
private void <API key>(XmlAttributes a, string accessorName)
{
XmlAttributeFlags flags = a.XmlFlags;
if ((flags & (XmlAttributeFlags.Attribute | XmlAttributeFlags.AnyAttribute)) != 0)
throw new <API key>(SR.<API key>);
if ((flags & (XmlAttributeFlags.Text | XmlAttributeFlags.AnyElements | XmlAttributeFlags.ChoiceIdentifier)) != 0)
throw new <API key>(SR.XmlRpcLitAttributes);
if (a.XmlElements != null && a.XmlElements.Count > 0)
{
if (a.XmlElements.Count > 1)
{
throw new <API key>(SR.XmlRpcLitElements);
}
XmlElementAttribute xmlElement = a.XmlElements[0];
if (xmlElement.Namespace != null)
{
throw new <API key>(SR.Format(SR.<API key>, "Namespace", xmlElement.Namespace));
}
if (xmlElement.IsNullable)
{
throw new <API key>(SR.Format(SR.<API key>, "IsNullable", "true"));
}
}
if (a.XmlArray != null && a.XmlArray.Namespace != null)
{
throw new <API key>(SR.Format(SR.<API key>, "Namespace", a.XmlArray.Namespace));
}
}
private void <API key>(XmlAttributes a, Type accessorType, string accessorName)
{
Hashtable choiceTypes = new Hashtable();
<API key> elements = a.XmlElements;
if (elements != null && elements.Count >= 2 && a.XmlChoiceIdentifier == null)
{
for (int i = 0; i < elements.Count; i++)
{
Type type = elements[i].Type == null ? accessorType : elements[i].Type;
if (choiceTypes.Contains(type))
{
// You need to add {0} to the '{1}'.
throw new <API key>(SR.Format(SR.<API key>, typeof(<API key>).Name, accessorName));
}
else
{
choiceTypes.Add(type, false);
}
}
}
if (choiceTypes.Contains(typeof(XmlElement)) && a.XmlAnyElements.Count > 0)
{
// You need to add {0} to the '{1}'.
throw new <API key>(SR.Format(SR.<API key>, typeof(<API key>).Name, accessorName));
}
<API key> items = a.XmlArrayItems;
if (items != null && items.Count >= 2)
{
NameTable arrayTypes = new NameTable();
for (int i = 0; i < items.Count; i++)
{
Type type = items[i].Type == null ? accessorType : items[i].Type;
string ns = items[i].NestingLevel.ToString(CultureInfo.InvariantCulture);
<API key> item = (<API key>)arrayTypes[type.FullName, ns];
if (item != null)
{
throw new <API key>(SR.Format(SR.<API key>, accessorName, item.ElementName, items[i].ElementName, typeof(XmlElementAttribute).Name, typeof(<API key>).Name, accessorName));
}
else
{
arrayTypes[type.FullName, ns] = items[i];
}
}
}
}
private void <API key>(EnumMapping choiceMapping)
{
NameTable ids = new NameTable();
for (int i = 0; i < choiceMapping.Constants.Length; i++)
{
string choiceId = choiceMapping.Constants[i].XmlName;
int colon = choiceId.LastIndexOf(':');
string choiceName = colon < 0 ? choiceId : choiceId.Substring(colon + 1);
string choiceNs = colon < 0 ? "" : choiceId.Substring(0, colon);
if (ids[choiceName, choiceNs] != null)
{
// Enum values in the XmlChoiceIdentifier '{0}' have to be unique. Value '{1}' already present.
throw new <API key>(SR.Format(SR.<API key>, choiceMapping.TypeName, choiceId));
}
ids.Add(choiceName, choiceNs, choiceMapping.Constants[i]);
}
}
private object GetDefaultValue(TypeDesc fieldTypeDesc, Type t, XmlAttributes a)
{
if (a.XmlDefaultValue == null || a.XmlDefaultValue == DBNull.Value) return null;
if (!(fieldTypeDesc.Kind == TypeKind.Primitive || fieldTypeDesc.Kind == TypeKind.Enum))
{
a.XmlDefaultValue = null;
return a.XmlDefaultValue;
}
// for enums validate and return a string representation
if (fieldTypeDesc.Kind == TypeKind.Enum)
{
string strValue = Enum.Format(t, a.XmlDefaultValue, "G").Replace(",", " ");
string numValue = Enum.Format(t, a.XmlDefaultValue, "D");
if (strValue == numValue) // means enum value wasn't recognized
throw new <API key>(SR.Format(SR.<API key>, strValue, a.XmlDefaultValue.GetType().FullName));
return strValue;
}
return a.XmlDefaultValue;
}
private static <API key> <API key>(TypeDesc typeDesc, int nestingLevel)
{
<API key> xmlArrayItem = new <API key>();
xmlArrayItem.NestingLevel = nestingLevel;
return xmlArrayItem;
}
private static XmlArrayAttribute <API key>(TypeDesc typeDesc)
{
XmlArrayAttribute xmlArrayItem = new XmlArrayAttribute();
return xmlArrayItem;
}
private static XmlElementAttribute <API key>(TypeDesc typeDesc)
{
XmlElementAttribute xmlElement = new XmlElementAttribute();
xmlElement.IsNullable = typeDesc.IsOptionalValue;
return xmlElement;
}
private static void AddUniqueAccessor(INameScope scope, Accessor accessor)
{
Accessor existing = (Accessor)scope[accessor.Name, accessor.Namespace];
if (existing != null)
{
if (accessor is ElementAccessor)
{
throw new <API key>(SR.Format(SR.<API key>, existing.Name, existing.Namespace));
}
else
{
#if DEBUG
if (!(accessor is AttributeAccessor))
throw new <API key>(SR.Format(SR.<API key>, "Bad accessor type " + accessor.GetType().FullName));
#endif
throw new <API key>(SR.Format(SR.<API key>, existing.Name, existing.Namespace));
}
}
else
{
scope[accessor.Name, accessor.Namespace] = accessor;
}
}
private static void AddUniqueAccessor(MemberMapping member, INameScope elements, INameScope attributes, bool isSequence)
{
if (member.Attribute != null)
{
AddUniqueAccessor(attributes, member.Attribute);
}
else if (!isSequence && member.Elements != null && member.Elements.Length > 0)
{
for (int i = 0; i < member.Elements.Length; i++)
{
AddUniqueAccessor(elements, member.Elements[i]);
}
}
}
private static void CheckForm(XmlSchemaForm form, bool isQualified)
{
if (isQualified && form == XmlSchemaForm.Unqualified) throw new <API key>(SR.<API key>);
}
private static void CheckNullable(bool isNullable, TypeDesc typeDesc, TypeMapping mapping)
{
if (mapping is NullableMapping) return;
if (mapping is SerializableMapping) return;
if (isNullable && !typeDesc.IsNullable) throw new <API key>(SR.Format(SR.<API key>, typeDesc.FullName));
}
private static ElementAccessor <API key>(TypeMapping mapping, string ns)
{
ElementAccessor element = new ElementAccessor();
bool isAny = mapping.TypeDesc.Kind == TypeKind.Node;
if (!isAny && mapping is SerializableMapping)
{
isAny = ((SerializableMapping)mapping).IsAny;
}
if (isAny)
{
element.Any = true;
}
else
{
element.Name = mapping.DefaultElementName;
element.Namespace = ns;
}
element.Mapping = mapping;
return element;
}
// will create a shallow type mapping for a top-level type
internal static XmlTypeMapping GetTopLevelMapping(Type type, string defaultNamespace)
{
defaultNamespace = defaultNamespace ?? string.Empty;
XmlAttributes a = new XmlAttributes(type);
TypeDesc typeDesc = new TypeScope().GetTypeDesc(type);
ElementAccessor element = new ElementAccessor();
if (typeDesc.Kind == TypeKind.Node)
{
element.Any = true;
}
else
{
string ns = a.XmlRoot == null ? defaultNamespace : a.XmlRoot.Namespace;
string typeName = string.Empty;
if (a.XmlType != null)
typeName = a.XmlType.TypeName;
if (typeName.Length == 0)
typeName = type.Name;
element.Name = XmlConvert.EncodeLocalName(typeName);
element.Namespace = ns;
}
XmlTypeMapping mapping = new XmlTypeMapping(null, element);
mapping.SetKeyInternal(XmlMapping.GenerateKey(type, a.XmlRoot, defaultNamespace));
return mapping;
}
}
internal class <API key>
{
private StructModel _model;
private StructMapping _mapping;
internal <API key>(StructModel model, StructMapping mapping)
{
_model = model;
_mapping = mapping;
}
internal StructModel Model { get { return _model; } }
internal StructMapping Mapping { get { return _mapping; } }
}
internal class WorkItems
{
private ArrayList _list = new ArrayList();
internal <API key> this[int index]
{
get
{
return (<API key>)_list[index];
}
set
{
_list[index] = value;
}
}
internal int Count
{
get
{
return _list.Count;
}
}
internal void Add(<API key> item)
{
_list.Add(item);
}
internal bool Contains(StructMapping mapping)
{
return IndexOf(mapping) >= 0;
}
internal int IndexOf(StructMapping mapping)
{
for (int i = 0; i < Count; i++)
{
if (this[i].Mapping == mapping)
return i;
}
return -1;
}
internal void RemoveAt(int index)
{
_list.RemoveAt(index);
}
}
internal class RecursionLimiter
{
private int _maxDepth;
private int _depth;
private WorkItems _deferredWorkItems;
internal RecursionLimiter()
{
_depth = 0;
#if <API key>
_maxDepth = int.MaxValue;
#else
_maxDepth = DiagnosticsSwitches.<API key>.Enabled ? 1 : int.MaxValue;
#endif
}
internal bool IsExceededLimit { get { return _depth > _maxDepth; } }
internal int Depth { get { return _depth; } set { _depth = value; } }
internal WorkItems DeferredWorkItems
{
get
{
if (_deferredWorkItems == null)
{
_deferredWorkItems = new WorkItems();
}
return _deferredWorkItems;
}
}
}
} |
package org.openhab.binding.miele.handler;
import static org.openhab.binding.miele.<API key>.APPLIANCE_ID;
import org.eclipse.smarthome.core.library.types.OnOffType;
import org.eclipse.smarthome.core.thing.ChannelUID;
import org.eclipse.smarthome.core.thing.Thing;
import org.eclipse.smarthome.core.types.Command;
import org.eclipse.smarthome.core.types.RefreshType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.gson.JsonElement;
/**
* The {@link <API key>} is responsible for handling commands,
* which are sent to one of the channels
*
* @author Karel Goderis - Initial contribution
* @author Kai Kreuzer - fixed handling of REFRESH commands
*/
public class <API key> extends <API key><<API key>> {
private final Logger logger = LoggerFactory.getLogger(<API key>.class);
public <API key>(Thing thing) {
super(thing, <API key>.class, "WashingMachine");
}
@Override
public void handleCommand(ChannelUID channelUID, Command command) {
super.handleCommand(channelUID, command);
String channelID = channelUID.getId();
String uid = (String) getThing().getConfiguration().getProperties().get(APPLIANCE_ID);
<API key> selector = (<API key>) <API key>(
channelID);
JsonElement result = null;
try {
if (selector != null) {
switch (selector) {
case SWITCH: {
if (command.equals(OnOffType.ON)) {
result = bridgeHandler.invokeOperation(uid, modelID, "start");
} else if (command.equals(OnOffType.OFF)) {
result = bridgeHandler.invokeOperation(uid, modelID, "stop");
}
break;
}
default: {
if (!(command instanceof RefreshType)) {
logger.debug("{} is a read-only channel that does not accept commands",
selector.getChannelID());
}
}
}
}
// process result
if (result != null) {
logger.debug("Result of operation is {}", result.getAsString());
}
} catch (<API key> e) {
logger.warn(
"An error occurred while trying to set the read-only variable associated with channel '{}' to '{}'",
channelID, command.toString());
}
}
} |
package com.google.gwt.eclipse.core.refactoring;
import com.google.gwt.eclipse.core.test.<API key>;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.<API key>;
import org.eclipse.ltk.core.refactoring.Change;
import org.eclipse.ltk.core.refactoring.RefactoringStatus;
/**
* Tests the {@link <API key>} class.
*/
public class <API key> extends <API key> {
private static class <API key> extends <API key> {
@Override
public Change createChange(IProgressMonitor pm) throws CoreException,
<API key> {
return null;
}
@Override
public String getName() {
return "";
}
@Override
protected <API key> <API key>() {
return null;
}
}
public void testCheckConditions() {
<API key> participant = new <API key>();
RefactoringStatus status = participant.checkConditions(null, null);
assertTrue(status.isOK());
}
public void <API key>() {
<API key> participant = new <API key>();
assertFalse(participant.initialize(getTestProject()));
}
@Override
protected boolean requiresTestProject() {
return true;
}
} |
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.11
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2016.02.17 at 06:25:15 PM CET
package org.openhab.ui.cometvisu.internal.config.beans;
import java.math.BigDecimal;
import java.math.BigInteger;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlType;
import javax.xml.bind.annotation.XmlValue;
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "rrd", propOrder = {
"value"
})
public class Rrd {
@XmlValue
protected String value;
@XmlAttribute(name = "yaxis")
protected String yaxis;
@XmlAttribute(name = "color")
protected String color;
@XmlAttribute(name = "label")
protected String label;
@XmlAttribute(name = "scaling")
protected BigDecimal scaling;
@XmlAttribute(name = "steps")
protected Boolean steps;
@XmlAttribute(name = "fill")
protected Boolean fill;
@XmlAttribute(name = "style")
protected String style;
@XmlAttribute(name = "barWidth")
protected BigInteger barWidth;
@XmlAttribute(name = "align")
protected String align;
@XmlAttribute(name = "datasourceIndex")
protected BigInteger datasourceIndex;
@XmlAttribute(name = "<API key>")
protected String <API key>;
@XmlAttribute(name = "resolution")
protected BigInteger resolution;
@XmlAttribute(name = "offset")
protected BigInteger offset;
/**
* Gets the value of the value property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getValue() {
return value;
}
/**
* Sets the value of the value property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setValue(String value) {
this.value = value;
}
/**
* Gets the value of the yaxis property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getYaxis() {
return yaxis;
}
/**
* Sets the value of the yaxis property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setYaxis(String value) {
this.yaxis = value;
}
/**
* Gets the value of the color property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getColor() {
return color;
}
/**
* Sets the value of the color property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setColor(String value) {
this.color = value;
}
/**
* Gets the value of the label property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getLabel() {
return label;
}
/**
* Sets the value of the label property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setLabel(String value) {
this.label = value;
}
/**
* Gets the value of the scaling property.
*
* @return
* possible object is
* {@link BigDecimal }
*
*/
public BigDecimal getScaling() {
return scaling;
}
/**
* Sets the value of the scaling property.
*
* @param value
* allowed object is
* {@link BigDecimal }
*
*/
public void setScaling(BigDecimal value) {
this.scaling = value;
}
/**
* Gets the value of the steps property.
*
* @return
* possible object is
* {@link Boolean }
*
*/
public Boolean isSteps() {
return steps;
}
/**
* Sets the value of the steps property.
*
* @param value
* allowed object is
* {@link Boolean }
*
*/
public void setSteps(Boolean value) {
this.steps = value;
}
/**
* Gets the value of the fill property.
*
* @return
* possible object is
* {@link Boolean }
*
*/
public Boolean isFill() {
return fill;
}
/**
* Sets the value of the fill property.
*
* @param value
* allowed object is
* {@link Boolean }
*
*/
public void setFill(Boolean value) {
this.fill = value;
}
/**
* Gets the value of the style property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getStyle() {
return style;
}
/**
* Sets the value of the style property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setStyle(String value) {
this.style = value;
}
/**
* Gets the value of the barWidth property.
*
* @return
* possible object is
* {@link BigInteger }
*
*/
public BigInteger getBarWidth() {
return barWidth;
}
/**
* Sets the value of the barWidth property.
*
* @param value
* allowed object is
* {@link BigInteger }
*
*/
public void setBarWidth(BigInteger value) {
this.barWidth = value;
}
/**
* Gets the value of the align property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getAlign() {
return align;
}
/**
* Sets the value of the align property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setAlign(String value) {
this.align = value;
}
/**
* Gets the value of the datasourceIndex property.
*
* @return
* possible object is
* {@link BigInteger }
*
*/
public BigInteger getDatasourceIndex() {
if (datasourceIndex == null) {
return new BigInteger("0");
} else {
return datasourceIndex;
}
}
/**
* Sets the value of the datasourceIndex property.
*
* @param value
* allowed object is
* {@link BigInteger }
*
*/
public void setDatasourceIndex(BigInteger value) {
this.datasourceIndex = value;
}
public String <API key>() {
if (<API key> == null) {
return "AVERAGE";
} else {
return <API key>;
}
}
/**
* Sets the value of the <API key> property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void <API key>(String value) {
this.<API key> = value;
}
/**
* Gets the value of the resolution property.
*
* @return
* possible object is
* {@link BigInteger }
*
*/
public BigInteger getResolution() {
return resolution;
}
/**
* Sets the value of the resolution property.
*
* @param value
* allowed object is
* {@link BigInteger }
*
*/
public void setResolution(BigInteger value) {
this.resolution = value;
}
/**
* Gets the value of the offset property.
*
* @return
* possible object is
* {@link BigInteger }
*
*/
public BigInteger getOffset() {
return offset;
}
/**
* Sets the value of the offset property.
*
* @param value
* allowed object is
* {@link BigInteger }
*
*/
public void setOffset(BigInteger value) {
this.offset = value;
}
} |
package dio.gpio;
import dio.runner.gson.GpioPinCollection;
import dio.runner.gson.GpioPinCollection.GpioData;
import dio.shared.TestBase;
import java.util.ArrayList;
import jdk.dio.DeviceConfig;
import jdk.dio.gpio.GPIOPin;
import jdk.dio.gpio.GPIOPinConfig;
import jdk.dio.gpio.GPIOPortConfig;
/**
* @title GPIOTestBase class to handle common actions for GPIO testing
* @author stanislav.smirnov@oracle.com
*/
public class GPIOTestBase implements TestBase {
protected enum Modes {PIN, PORT}
protected ArrayList<PinConfig> GPIOpins;
protected ArrayList<PortConfig> GPIOports;
protected GPIOPinConfig[][] <API key>;
/**
* Method to validate and decode input arguments
* @param args to decode and use in configuration
* @param mode element of Modes enumerator to detect what arguments to
* decode and what to configure
* @return
*/
protected boolean decodeConfig(String[] args, Modes mode){
boolean result = true;
if(args == null || args.length == 0){
result = false;
System.err.println("No input arguments to decode");
} else {
switch (mode) {
case PIN: {
int index = getDataIndex(args, "-gpins");
if (index == -1) {
result = false;
System.err.println("Wrong input gpins argument");
} else {
setupPinsConfig(args[index+1]);
}
break;
}
case PORT: {
int index = getDataIndex(args, "-gports");
if (index == -1) {
result = false;
System.err.println("Wrong input gports argument");
} else {
setupPinsConfig(args[index - 1]);
setupPortsConfig(args[index + 1]);
}
break;
}
default: {
System.err.println("Undefined GPIO mode");
}
}
}
return result;
}
/**
* Method to setup pins configuration
* @param config input pins configuration wrapped in Json
*/
protected void setupPinsConfig(String config){
GpioPinCollection pinsCollection = GpioPinCollection.deserialize(config, GpioPinCollection.class);
pinsCollection.pins.stream().map((pin) -> {
if(GPIOpins == null){
GPIOpins = new ArrayList<>();
}
return pin;
}).forEach((pin) -> {
GPIOpins.add(new PinConfig(pin.deviceId, pin.deviceName, new GPIOPinConfig(0, pin.pinNumber, pin.direction, pin.mode, pin.trigger, false)));
});
GPIOpins.trimToSize();
}
/**
* Method to get pin config by pin number
* @param pinNumber
* @return GPIOPinConfig instance
*/
protected GPIOPinConfig <API key>(int pinNumber){
GPIOPinConfig result = null;
for(PinConfig config : GPIOpins){
if(config.getPinConfig().getPinNumber() == pinNumber){
result = config.getPinConfig();
break;
}
}
return result;
}
/**
* Method to setup ports configuration
* @param config input ports configuration wrapped in Json
*/
protected void setupPortsConfig(String config){
GpioPinCollection portsCollection = GpioPinCollection.deserialize(config, GpioPinCollection.class);
for (GpioData port : portsCollection.ports) {
if(port.portPins == null || (GPIOpins == null || GPIOpins.size() != port.portPins.size())){
throw new <API key>("No pins were specified for port");
}
if (GPIOports == null) {
GPIOports = new ArrayList<>();
}
GPIOPinConfig[] pinsConfigArray = null;
for (int i = 0; i < port.portPins.size(); i++) {
if (pinsConfigArray == null) {
pinsConfigArray = new GPIOPinConfig[port.portPins.size()];
}
int pinConfigId = Integer.parseInt(port.portPins.get(i));
pinsConfigArray[i] = new GPIOPinConfig(0,
GPIOpins.get(pinConfigId).getPinConfig().getPinNumber(),
GPIOpins.get(pinConfigId).getPinConfig().getDirection(),
GPIOpins.get(pinConfigId).getPinConfig().getDriveMode(),
GPIOpins.get(pinConfigId).getPinConfig().getTrigger(),
false);
}
GPIOports.add(new PortConfig(new GPIOPortConfig(port.direction, port.initValue, pinsConfigArray)));
}
GPIOports.trimToSize();
}
/**
* Method to get literal value from direction decimal value
* @param direction GPIOPinConfig direction
* @return literal value
*/
protected String <API key>(int direction) {
String text;
switch (direction) {
case GPIOPinConfig.DIR_INPUT_ONLY:
text = "DIR_INPUT_ONLY";
break;
case GPIOPinConfig.DIR_OUTPUT_ONLY:
text = "DIR_OUTPUT_ONLY";
break;
case GPIOPinConfig.DIR_BOTH_INIT_INPUT:
text = "DIR_BOTH_INIT_INPUT";
break;
case GPIOPinConfig.<API key>:
text = "<API key>";
break;
default:
text = "Wrong direction: " + direction;
}
return text;
}
/**
* Method to get literal value from direction decimal value
* @param dir GPIOPin direction
* @return literal value
*/
protected String getPinDirection(int dir) {
String text;
switch (dir) {
case GPIOPin.INPUT:
text = "INPUT";
break;
case GPIOPin.OUTPUT:
text = "OUTPUT";
break;
default:
text = "UNKNOWN";
}
return text;
}
/**
* Method to get literal value from drive modes decimal value
* @param driveMode GPIOPinConfig drive mode
* @return literal value
*/
protected String getPinDriveMode(int driveMode) {
String text = "";
if (driveMode == DeviceConfig.DEFAULT) {
text = "DEFAULT";
} else {
if ((driveMode & GPIOPinConfig.MODE_INPUT_PULL_UP) == GPIOPinConfig.MODE_INPUT_PULL_UP) {
text = text + (text.length() > 0 ? " " : "") + "MODE_INPUT_PULL_UP";
}
if ((driveMode & GPIOPinConfig.<API key>) == GPIOPinConfig.<API key>) {
text = text + (text.length() > 0 ? " " : "") + "<API key>";
}
if ((driveMode & GPIOPinConfig.<API key>) == GPIOPinConfig.<API key>) {
text = text + (text.length() > 0 ? " " : "") + "<API key>";
}
if ((driveMode & GPIOPinConfig.<API key>) == GPIOPinConfig.<API key>) {
text = text + (text.length() > 0 ? " " : "") + "<API key>";
}
}
return text;
}
/**
* Method to get literal value from trigger decimal value
* @param intTrigger GPIOPinConfig trigger
* @return literal value
*/
protected String getPinConfigTrigger(int intTrigger) {
String text;
switch (intTrigger) {
case GPIOPinConfig.TRIGGER_NONE:
text = "TRIGGER_NONE";
break;
case GPIOPinConfig.<API key>:
text = "<API key>";
break;
case GPIOPinConfig.TRIGGER_RISING_EDGE:
text = "TRIGGER_RISING_EDGE";
break;
case GPIOPinConfig.TRIGGER_BOTH_EDGES:
text = "TRIGGER_BOTH_EDGES";
break;
case GPIOPinConfig.TRIGGER_HIGH_LEVEL:
text = "TRIGGER_HIGH_LEVEL";
break;
case GPIOPinConfig.TRIGGER_LOW_LEVEL:
text = "TRIGGER_LOW_LEVEL";
break;
case GPIOPinConfig.TRIGGER_BOTH_LEVELS:
text = "TRIGGER_BOTH_LEVELS";
break;
default:
text = "UNKNOWN";
}
return text;
}
} |
package jdk.jshell;
/**
* The superclass of JShell generated exceptions
*
* @since 9
*/
@SuppressWarnings("serial") // serialVersionUID intentionally omitted
public class JShellException extends Exception {
JShellException(String message) {
super(message);
}
JShellException(String message, Throwable cause) {
super(message, cause);
}
} |
require 'rubygems'
require 'rake'
require 'set'
require 'fileutils'
require 'file_path_utils.rb'
class FileSystemUtils
constructor :file_wrapper
# build up path list from input of one or more strings or arrays of (+/-) paths & globs
def collect_paths(*paths)
raw = [] # all paths and globs
plus = Set.new # all paths to expand and add
minus = Set.new # all paths to remove from plus set
# assemble all globs and simple paths, reforming our glob notation to ruby globs
paths.each do |paths_container|
case (paths_container)
when String then raw << (FilePathUtils::reform_glob(paths_container))
when Array then paths_container.each {|path| raw << (FilePathUtils::reform_glob(path))}
else raise "Don't know how to handle #{paths_container.class}"
end
end
# iterate through each path and glob
raw.each do |path|
dirs = [] # container for only (expanded) paths
# if a glob, expand it and slurp up all non-file paths
if path.include?('*')
# grab base directory only if globs are snug up to final path separator
if (path =~ /\/\*+$/)
dirs << FilePathUtils.extract_path(path)
end
# grab expanded sub-directory globs
expanded = @file_wrapper.directory_listing( FilePathUtils.<API key>(path) )
expanded.each do |entry|
dirs << entry if @file_wrapper.directory?(entry)
end
# else just grab simple path
# note: we could just run this through glob expansion but such an
# approach doesn't handle a path not yet on disk)
else
dirs << FilePathUtils.<API key>(path)
end
# add dirs to the appropriate set based on path aggregation modifier if present
FilePathUtils.add_path?(path) ? plus.merge(dirs) : minus.merge(dirs)
end
return (plus - minus).to_a.uniq
end
# given a file list, add to it or remove from it
def revise_file_list(list, revisions)
revisions.each do |revision|
# include or exclude file or glob to file list
file = FilePathUtils.<API key>( revision )
FilePathUtils.add_path?(revision) ? list.include(file) : list.exclude(file)
end
end
end |
<?php
class <API key> extends SiteOrigin_Widget {
function __construct() {
parent::__construct(
'sow-google-map',
__( 'SiteOrigin Google Maps', 'so-widgets-bundle' ),
array(
'description' => __( 'A Google Maps widget.', 'so-widgets-bundle' ),
'help' => 'https://siteorigin.com/widgets-bundle/google-maps-widget/'
),
array(),
false,
plugin_dir_path(__FILE__)
);
}
function initialize() {
$this-><API key>(
array(
array(
'sow-google-map',
plugin_dir_url(__FILE__) . 'js/js-map' . <API key> . '.js',
array( 'jquery' ),
SOW_BUNDLE_VERSION
)
)
);
$this-><API key>(
array(
array(
'sow-google-map',
plugin_dir_url(__FILE__) . 'css/style.css',
array(),
SOW_BUNDLE_VERSION
)
)
);
}
function initialize_form(){
return array(
'map_center' => array(
'type' => 'textarea',
'rows' => 2,
'label' => __( 'Map center', 'so-widgets-bundle' ),
'description' => __( 'The name of a place, town, city, or even a country. Can be an exact address too.', 'so-widgets-bundle' )
),
'settings' => array(
'type' => 'section',
'label' => __( 'Settings', 'so-widgets-bundle' ),
'hide' => false,
'description' => __( 'Set map display options.', 'so-widgets-bundle' ),
'fields' => array(
'map_type' => array(
'type' => 'radio',
'default' => 'interactive',
'label' => __( 'Map type', 'so-widgets-bundle' ),
'state_emitter' => array(
'callback' => 'select',
'args' => array( 'map_type' )
),
'options' => array(
'interactive' => __( 'Interactive', 'so-widgets-bundle' ),
'static' => __( 'Static image', 'so-widgets-bundle' ),
)
),
'width' => array(
'type' => 'text',
'default' => 640,
'hidden' => true,
'state_handler' => array(
'map_type[static]' => array('show'),
'_else[map_type]' => array('hide'),
),
'label' => __( 'Width', 'so-widgets-bundle' )
),
'height' => array(
'type' => 'text',
'default' => 480,
'label' => __( 'Height', 'so-widgets-bundle' )
),
'zoom' => array(
'type' => 'slider',
'label' => __( 'Zoom level', 'so-widgets-bundle' ),
'description' => __( 'A value from 0 (the world) to 21 (street level).', 'so-widgets-bundle' ),
'min' => 0,
'max' => 21,
'default' => 12,
'integer' => true,
),
'scroll_zoom' => array(
'type' => 'checkbox',
'default' => true,
'state_handler' => array(
'map_type[interactive]' => array('show'),
'_else[map_type]' => array('hide'),
),
'label' => __( 'Scroll to zoom', 'so-widgets-bundle' ),
'description' => __( 'Allow scrolling over the map to zoom in or out.', 'so-widgets-bundle' )
),
'draggable' => array(
'type' => 'checkbox',
'default' => true,
'state_handler' => array(
'map_type[interactive]' => array('show'),
'_else[map_type]' => array('hide'),
),
'label' => __( 'Draggable', 'so-widgets-bundle' ),
'description' => __( 'Allow dragging the map to move it around.', 'so-widgets-bundle' )
),
'disable_default_ui' => array(
'type' => 'checkbox',
'default' => false,
'state_handler' => array(
'map_type[interactive]' => array('show'),
'_else[map_type]' => array('hide'),
),
'label' => __( 'Disable default UI', 'so-widgets-bundle' ),
'description' => __( 'Hides the default Google Maps controls.', 'so-widgets-bundle' )
),
'keep_centered' => array(
'type' => 'checkbox',
'default' => false,
'state_handler' => array(
'map_type[interactive]' => array('show'),
'_else[map_type]' => array('hide'),
),
'label' => __( 'Keep map centered', 'so-widgets-bundle' ),
'description' => __( 'Keeps the map centered when it\'s container is resized.', 'so-widgets-bundle' )
)
)
),
'markers' => array(
'type' => 'section',
'label' => __( 'Markers', 'so-widgets-bundle' ),
'hide' => true,
'description' => __( 'Use markers to identify points of interest on the map.', 'so-widgets-bundle' ),
'fields' => array(
'marker_at_center' => array(
'type' => 'checkbox',
'default' => true,
'label' => __( 'Show marker at map center', 'so-widgets-bundle' )
),
'marker_icon' => array(
'type' => 'media',
'default' => '',
'label' => __( 'Marker icon', 'so-widgets-bundle' ),
'description' => __( 'Replaces the default map marker with your own image.', 'so-widgets-bundle' )
),
'markers_draggable' => array(
'type' => 'checkbox',
'default' => false,
'state_handler' => array(
'map_type[interactive]' => array('show'),
'_else[map_type]' => array('hide'),
),
'label' => __( 'Draggable markers', 'so-widgets-bundle' )
),
'marker_positions' => array(
'type' => 'repeater',
'label' => __( 'Marker positions', 'so-widgets-bundle' ),
'description' => __( 'Please be aware that adding more than 10 markers may cause a slight delay before they appear, due to Google Geocoding API rate limits.', 'so-widgets-bundle' ),
'item_name' => __( 'Marker', 'so-widgets-bundle' ),
'item_label' => array(
'selector' => "[id*='<API key>']",
'update_event' => 'change',
'value_method' => 'val'
),
'fields' => array(
'place' => array(
'type' => 'textarea',
'rows' => 2,
'label' => __( 'Place', 'so-widgets-bundle' )
),
'info' => array(
'type' => 'tinymce',
'rows' => 10,
'label' => __( 'Info Window Content', 'so-widgets-bundle' )
),
'info_max_width' => array(
'type' => 'text',
'label' => __( 'Info Window max width', 'so-widgets-bundle' )
),
)
),
'info_display' => array(
'type' => 'radio',
'label' => __( 'When should Info Windows be displayed?', 'so-widgets-bundle' ),
'default' => 'click',
'options' => array(
'click' => __( 'Click', 'so-widgets-bundle' ),
'mouseover' => __( 'Mouse over', 'so-widgets-bundle' ),
'always' => __( 'Always', 'so-widgets-bundle' ),
)
),
)
),
'styles' => array(
'type' => 'section',
'label' => __( 'Styles', 'so-widgets-bundle' ),
'hide' => true,
'description' => __( 'Apply custom colors to map features, or hide them completely.', 'so-widgets-bundle' ),
'fields' => array(
'style_method' => array(
'type' => 'radio',
'default' => 'normal',
'label' => __( 'Map styles', 'so-widgets-bundle' ),
'state_emitter' => array(
'callback' => 'select',
'args' => array( 'style_method' )
),
'options' => array(
'normal' => __( 'Default', 'so-widgets-bundle' ),
'custom' => __( 'Custom', 'so-widgets-bundle' ),
'raw_json' => __( 'Predefined Styles', 'so-widgets-bundle' ),
)
),
'styled_map_name' => array(
'type' => 'text',
'state_handler' => array(
'style_method[default]' => array('hide'),
'_else[style_method]' => array('show'),
),
'label' => __( 'Styled map name', 'so-widgets-bundle' )
),
'raw_json_map_styles' => array(
'type' => 'textarea',
'state_handler' => array(
'style_method[raw_json]' => array('show'),
'_else[style_method]' => array('hide'),
),
'rows' => 5,
'hidden' => true,
'label' => __( 'Raw JSON styles', 'so-widgets-bundle' ),
'description' => __( 'Copy and paste predefined styles here from <a href="http://snazzymaps.com/" target="_blank">Snazzy Maps</a>.', 'so-widgets-bundle' )
),
'custom_map_styles' => array(
'type' => 'repeater',
'state_handler' => array(
'style_method[custom]' => array('show'),
'_else[style_method]' => array('hide'),
),
'label' => __( 'Custom map styles', 'so-widgets-bundle' ),
'item_name' => __( 'Style', 'so-widgets-bundle' ),
'item_label' => array(
'selector' => "[id*='<API key>'] :selected",
'update_event' => 'change',
'value_method' => 'text'
),
'fields' => array(
'map_feature' => array(
'type' => 'select',
'label' => '',
'prompt' => __( 'Select map feature to style', 'so-widgets-bundle' ),
'options' => array(
'water' => __( 'Water', 'so-widgets-bundle' ),
'road_highway' => __( 'Highways', 'so-widgets-bundle' ),
'road_arterial' => __( 'Arterial roads', 'so-widgets-bundle' ),
'road_local' => __( 'Local roads', 'so-widgets-bundle' ),
'transit_line' => __( 'Transit lines', 'so-widgets-bundle' ),
'transit_station' => __( 'Transit stations', 'so-widgets-bundle' ),
'landscape_man-made' => __( 'Man-made landscape', 'so-widgets-bundle' ),
'<API key>' => __( 'Natural landscape landcover', 'so-widgets-bundle' ),
'<API key>' => __( 'Natural landscape terrain', 'so-widgets-bundle' ),
'poi_attraction' => __( 'Point of interest - Attractions', 'so-widgets-bundle' ),
'poi_business' => __( 'Point of interest - Business', 'so-widgets-bundle' ),
'poi_government' => __( 'Point of interest - Government', 'so-widgets-bundle' ),
'poi_medical' => __( 'Point of interest - Medical', 'so-widgets-bundle' ),
'poi_park' => __( 'Point of interest - Parks', 'so-widgets-bundle' ),
'<API key>' => __( 'Point of interest - Places of worship', 'so-widgets-bundle' ),
'poi_school' => __( 'Point of interest - Schools', 'so-widgets-bundle' ),
'poi_sports-complex' => __( 'Point of interest - Sports complexes', 'so-widgets-bundle' ),
)
),
'element_type' => array(
'type' => 'select',
'label' => __( 'Select element type to style', 'so-widgets-bundle' ),
'options' => array(
'geometry' => __( 'Geometry', 'so-widgets-bundle' ),
'labels' => __( 'Labels', 'so-widgets-bundle' ),
'all' => __( 'All', 'so-widgets-bundle' ),
)
),
'visibility' => array(
'type' => 'checkbox',
'default' => true,
'label' => __( 'Visible', 'so-widgets-bundle' )
),
'color' => array(
'type' => 'color',
'label' => __( 'Color', 'so-widgets-bundle' )
)
)
)
)
),
'directions' => array(
'type' => 'section',
'label' => __( 'Directions', 'so-widgets-bundle' ),
'state_handler' => array(
'map_type[interactive]' => array('show'),
'_else[map_type]' => array('hide'),
),
'hide' => true,
'description' => __( 'Display a route on your map, with waypoints between your starting point and destination.', 'so-widgets-bundle' ),
'fields' => array(
'origin' => array(
'type' => 'text',
'label' => __( 'Starting point', 'so-widgets-bundle' )
),
'destination' => array(
'type' => 'text',
'label' => __( 'Destination', 'so-widgets-bundle' )
),
'travel_mode' => array(
'type' => 'select',
'label' => __( 'Travel mode', 'so-widgets-bundle' ),
'default' => 'driving',
'options' => array(
'driving' => __( 'Driving', 'so-widgets-bundle' ),
'walking' => __( 'Walking', 'so-widgets-bundle' ),
'bicycling' => __( 'Bicycling', 'so-widgets-bundle' ),
'transit' => __( 'Transit', 'so-widgets-bundle' )
)
),
'avoid_highways' => array(
'type' => 'checkbox',
'label' => __( 'Avoid highways', 'so-widgets-bundle' ),
),
'avoid_tolls' => array(
'type' => 'checkbox',
'label' => __( 'Avoid tolls', 'so-widgets-bundle' ),
),
'waypoints' => array(
'type' => 'repeater',
'label' => __( 'Waypoints', 'so-widgets-bundle' ),
'item_name' => __( 'Waypoint', 'so-widgets-bundle' ),
'item_label' => array(
'selector' => "[id*='waypoints-location']",
'update_event' => 'change',
'value_method' => 'val'
),
'fields' => array(
'location' => array(
'type' => 'textarea',
'rows' => 2,
'label' => __( 'Location', 'so-widgets-bundle' )
),
'stopover' => array(
'type' => 'checkbox',
'default' => true,
'label' => __( 'Stopover', 'so-widgets-bundle' ),
'description' => __( 'Whether or not this is a stop on the route or just a route preference.', 'so-widgets-bundle' )
)
)
),
'optimize_waypoints' => array(
'type' => 'checkbox',
'label' => __( 'Optimize waypoints', 'so-widgets-bundle' ),
'default' => false,
'description' => __( 'Allow the Google Maps service to reorder waypoints for the shortest travelling distance.', 'so-widgets-bundle' )
)
)
),
'api_key_section' => array(
'type' => 'section',
'label' => __( 'API key', 'so-widgets-bundle' ),
'hide' => true,
'fields' => array(
'api_key' => array(
'type' => 'text',
'label' => __( 'API key', 'so-widgets-bundle' ),
'description' => __( 'Enter your API key if you have one. This enables you to monitor your Google Maps API usage in the Google APIs Console.', 'so-widgets-bundle' ),
'optional' => true
)
)
)
);
}
function get_template_name( $instance ) {
return $instance['settings']['map_type'] == 'static' ? 'static-map' : 'js-map';
}
function get_style_name( $instance ) {
return '';
}
function <API key>( $instance, $args ) {
if( empty( $instance ) ) return array();
$settings = $instance['settings'];
$mrkr_src = <API key>( $instance['markers']['marker_icon'] );
$styles = $this->get_styles( $instance );
if ( $settings['map_type'] == 'static' ) {
$src_url = $this-><API key>( $instance, $settings['width'], $settings['height'], ! empty( $styles ) ? $styles['styles'] : array() );
return array(
'src_url' => sow_esc_url( $src_url )
);
} else {
$markers = $instance['markers'];
$directions = '';
if ( ! empty( $instance['directions']['origin'] ) && ! empty( $instance['directions']['destination'] ) ) {
if ( empty( $instance['directions']['waypoints'] ) ) {
unset( $instance['directions']['waypoints'] );
}
$directions = <API key>( $instance['directions'] );
}
$map_data = <API key>( array(
'address' => $instance['map_center'],
'zoom' => $settings['zoom'],
'scroll_zoom' => $settings['scroll_zoom'],
'draggable' => $settings['draggable'],
'disable_ui' => $settings['disable_default_ui'],
'keep_centered' => $settings['keep_centered'],
'marker_icon' => ! empty( $mrkr_src ) ? $mrkr_src[0] : '',
'markers_draggable' => isset( $markers['markers_draggable'] ) ? $markers['markers_draggable'] : '',
'marker_at_center' => !empty( $markers['marker_at_center'] ),
'marker_info_display' => $markers['info_display'],
'marker_positions' => isset( $markers['marker_positions'] ) ? $markers['marker_positions'] : '',
'map_name' => ! empty( $styles ) ? $styles['map_name'] : '',
'map_styles' => ! empty( $styles ) ? $styles['styles'] : '',
'directions' => $directions,
'api_key' => $instance['api_key_section']['api_key']
));
return array(
'map_id' => md5( $instance['map_center'] ),
'height' => $settings['height'],
'map_data' => $map_data,
);
}
}
private function get_styles( $instance ) {
$style_config = $instance['styles'];
switch ( $style_config['style_method'] ) {
case 'custom':
if ( empty( $style_config['custom_map_styles'] ) ) {
return array();
} else {
$map_name = ! empty( $style_config['styled_map_name'] ) ? $style_config['styled_map_name'] : 'Custom Map';
$map_styles = $style_config['custom_map_styles'];
$styles = array();
foreach ( $map_styles as $style_item ) {
$map_feature = $style_item['map_feature'];
unset( $style_item['map_feature'] );
$element_type = $style_item['element_type'];
unset( $style_item['element_type'] );
$stylers = array();
foreach ( $style_item as $style_name => $style_value ) {
if ( $style_value !== '' && ! is_null( $style_value ) ) {
$style_value = $style_value === false ? 'off' : $style_value;
array_push( $stylers, array( $style_name => $style_value ) );
}
}
$map_feature = str_replace( '_', '.', $map_feature );
$map_feature = str_replace( '-', '_', $map_feature );
array_push( $styles, array(
'featureType' => $map_feature,
'elementType' => $element_type,
'stylers' => $stylers
) );
}
return array( 'map_name' => $map_name, 'styles' => $styles );
}
case 'raw_json':
if ( empty( $style_config['raw_json_map_styles'] ) ) {
return array();
} else {
$map_name = ! empty( $style_config['styled_map_name'] ) ? $style_config['styled_map_name'] : __( 'Custom Map', 'so-widgets-bundle' );
$styles_string = $style_config['raw_json_map_styles'];
return array( 'map_name' => $map_name, 'styles' => json_decode( $styles_string, true ) );
}
case 'normal':
default:
return array();
}
}
private function <API key>( $instance, $width, $height, $styles ) {
$src_url = "https://maps.googleapis.com/maps/api/staticmap?";
$src_url .= "center=" . $instance['map_center'];
$src_url .= "&zoom=" . $instance['settings']['zoom'];
$src_url .= "&size=" . $width . "x" . $height;
if ( ! empty( $instance['api_key_section']['api_key'] ) ) {
$src_url .= "&key=" . $instance['api_key_section']['api_key'];
}
if ( ! empty( $styles ) ) {
foreach ( $styles as $st ) {
if ( empty( $st ) || ! isset( $st['stylers'] ) || empty( $st['stylers'] ) ) {
continue;
}
$st_string = '';
if ( isset ( $st['featureType'] ) ) {
$st_string .= 'feature:' . $st['featureType'];
}
if ( isset ( $st['elementType'] ) ) {
if ( ! empty( $st_string ) ) {
$st_string .= "|";
}
$st_string .= 'element:' . $st['elementType'];
}
foreach ( $st['stylers'] as $style_prop_arr ) {
foreach ( $style_prop_arr as $prop_name => $prop_val ) {
if ( ! empty( $st_string ) ) {
$st_string .= "|";
}
if ( $prop_val[0] == "
$prop_val = "0x" . substr( $prop_val, 1 );
}
if ( is_bool( $prop_val ) ) {
$prop_val = $prop_val ? 'true' : 'false';
}
$st_string .= $prop_name . ":" . $prop_val;
}
}
$st_string = '&style=' . $st_string;
$src_url .= $st_string;
}
}
if ( ! empty( $instance['markers'] ) ) {
$markers = $instance['markers'];
$markers_st = '';
if ( ! empty( $markers['marker_icon'] ) ) {
$mrkr_src = <API key>( $markers['marker_icon'] );
if ( ! empty( $mrkr_src ) ) {
$markers_st .= 'icon:' . $mrkr_src[0];
}
}
if ( !empty( $markers['marker_at_center'] ) ) {
if ( ! empty( $markers_st ) ) {
$markers_st .= "|";
}
$markers_st .= $instance['map_center'];
}
if ( ! empty( $markers['marker_positions'] ) ) {
foreach ( $markers['marker_positions'] as $marker ) {
if ( ! empty( $markers_st ) ) {
$markers_st .= "|";
}
$markers_st .= urlencode( $marker['place'] );
}
}
$markers_st = '&markers=' . $markers_st;
$src_url .= $markers_st;
}
return $src_url;
}
}
<API key>( 'sow-google-map', __FILE__, '<API key>' ); |
/* { dg-do compile { target { powerpc*-*-* } } } */
/* { dg-options "-O2 -<API key>" } */
/* Note that it's required to disable <API key>, otherwise the
loop will be optimized to memset. */
/* Expect loop_iv can know the loop is finite so the doloop_optimize
can perform the doloop transformation. */
typedef struct {
int l;
int b[258];
} S;
void clear (S* s )
{
int i;
int len = s->l + 1;
for (i = 0; i <= len; i++)
s->b[i] = 0;
}
/* { dg-final { scan-assembler {\mbdnz\M} } } */ |
#!/bin/sh
## @test
## @bug 6878713
## @summary Verifier heap corruption, relating to backward jsrs
## @run shell/timeout=120 Test6878713.sh
## some tests require path to find test source dir
if [ "${TESTSRC}" = "" ]
then
TESTSRC=${PWD}
echo "TESTSRC not set. Using "${TESTSRC}" as default"
fi
echo "TESTSRC=${TESTSRC}"
## Adding common setup Variables for running shell tests.
. ${TESTSRC}/../../test_env.sh
${COMPILEJAVA}${FS}bin${FS}jar xvf ${TESTSRC}${FS}testcase.jar
${TESTJAVA}${FS}bin${FS}java ${TESTVMOPTS} OOMCrashClass1960_2 > test.out 2>&1
if [ -s core -o -s "hs_*.log" ]
then
cat hs*.log
echo "Test Failed"
exit 1
else
echo "Test Passed"
exit 0
fi |
//FIXME: most allocations need not be GFP_ATOMIC
/* FIXME: management of mutexes */
/* FIXME: <API key> return values */
/* FIXME: way too many copy to/from user */
/* FIXME: does region->active mean free */
/* FIXME: check limits on command lenghts passed from userspace */
/* FIXME: __msm_release: which queues should we flush when opencnt != 0 */
#include <linux/slab.h>
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/init.h>
#include <mach/board.h>
#include <linux/uaccess.h>
#include <linux/fs.h>
#include <linux/list.h>
#include <linux/uaccess.h>
#include <linux/android_pmem.h>
#include <linux/poll.h>
#include <media/msm_camera-liteon.h>
#include <mach/camera-liteon.h>
#include <linux/syscalls.h>
#include <linux/hrtimer.h>
DEFINE_MUTEX(ctrl_cmd_lock);
#define CAMERA_STOP_VIDEO 58
spinlock_t pp_prev_spinlock;
spinlock_t pp_snap_spinlock;
spinlock_t pp_thumb_spinlock;
spinlock_t <API key>;
spinlock_t st_frame_spinlock;
#define ERR_USER_COPY(to) pr_err("%s(%d): copy %s user\n", \
__func__, __LINE__, ((to) ? "to" : "from"))
#define ERR_COPY_FROM_USER() ERR_USER_COPY(0)
#define ERR_COPY_TO_USER() ERR_USER_COPY(1)
#define <API key> 10
static struct class *msm_class;
static dev_t msm_devno;
static LIST_HEAD(msm_sensors);
struct msm_control_device *<API key>;
int g_v4l2_opencnt;
static int camera_node;
static enum msm_camera_type camera_type[<API key>];
static uint32_t sensor_mount_angle[<API key>];
#ifdef <API key>
static const char *vfe_config_cmd[] = {
"CMD_GENERAL",
"CMD_AXI_CFG_OUT1",
"<API key>",
"CMD_AXI_CFG_OUT2",
"CMD_PICT_T_AXI_CFG",
"CMD_PICT_M_AXI_CFG",
"<API key>",
"<API key>",
"CMD_PREV_BUF_CFG",
"<API key>",
"CMD_SNAP_BUF_CFG",
"CMD_STATS_DISABLE",
"<API key>",
"CMD_STATS_AF_ENABLE",
"<API key>",
"<API key>",
"CMD_STATS_ENABLE",
"CMD_STATS_AXI_CFG",
"<API key>",
"<API key>",
"<API key>",
"<API key>",
"<API key>",
"<API key>",
"<API key>",
"<API key>",
"<API key>",
"<API key>",
"<API key>",
"<API key>",
"<API key>",
"<API key>",
"<API key>",
"<API key>",
"<API key>",
"CMD_AXI_CFG_SNAP",
"CMD_AXI_CFG_PREVIEW",
"CMD_AXI_CFG_VIDEO",
"<API key>",
"CMD_STATS_RS_ENABLE",
"CMD_STATS_CS_ENABLE",
"CMD_VPE",
"CMD_AXI_CFG_VPE",
"<API key>",
"<API key>",
};
#endif
#define __CONTAINS(r, v, l, field) ({ \
typeof(r) __r = r; \
typeof(v) __v = v; \
typeof(v) __e = __v + l; \
int res = __v >= __r->field && \
__e <= __r->field + __r->len; \
res; \
})
#define CONTAINS(r1, r2, field) ({ \
typeof(r2) __r2 = r2; \
__CONTAINS(r1, __r2->field, __r2->len, field); \
})
#define IN_RANGE(r, v, field) ({ \
typeof(r) __r = r; \
typeof(v) __vv = v; \
int res = ((__vv >= __r->field) && \
(__vv < (__r->field + __r->len))); \
res; \
})
#define OVERLAPS(r1, r2, field) ({ \
typeof(r1) __r1 = r1; \
typeof(r2) __r2 = r2; \
typeof(__r2->field) __v = __r2->field; \
typeof(__v) __e = __v + __r2->len - 1; \
int res = (IN_RANGE(__r1, __v, field) || \
IN_RANGE(__r1, __e, field)); \
res; \
})
static inline void free_qcmd(struct msm_queue_cmd *qcmd)
{
if (!qcmd || !atomic_read(&qcmd->on_heap))
return;
if (!atomic_sub_return(1, &qcmd->on_heap))
kfree(qcmd);
}
static void msm_region_init(struct msm_sync *sync)
{
INIT_HLIST_HEAD(&sync->pmem_frames);
INIT_HLIST_HEAD(&sync->pmem_stats);
spin_lock_init(&sync->pmem_frame_spinlock);
spin_lock_init(&sync->pmem_stats_spinlock);
}
static void msm_queue_init(struct msm_device_queue *queue, const char *name)
{
spin_lock_init(&queue->lock);
spin_lock_init(&queue->wait_lock);
queue->len = 0;
queue->max = 0;
queue->name = name;
INIT_LIST_HEAD(&queue->list);
init_waitqueue_head(&queue->wait);
}
static void msm_enqueue(struct msm_device_queue *queue,
struct list_head *entry)
{
unsigned long flags;
spin_lock_irqsave(&queue->lock, flags);
queue->len++;
if (queue->len > queue->max) {
queue->max = queue->len;
CDBG("%s: queue %s new max is %d\n", __func__,
queue->name, queue->max);
}
list_add_tail(entry, &queue->list);
wake_up(&queue->wait);
CDBG("%s: woke up %s\n", __func__, queue->name);
<API key>(&queue->lock, flags);
}
static void msm_enqueue_vpe(struct msm_device_queue *queue,
struct list_head *entry)
{
unsigned long flags;
spin_lock_irqsave(&queue->lock, flags);
queue->len++;
if (queue->len > queue->max) {
queue->max = queue->len;
CDBG("%s: queue %s new max is %d\n", __func__,
queue->name, queue->max);
}
list_add_tail(entry, &queue->list);
CDBG("%s: woke up %s\n", __func__, queue->name);
<API key>(&queue->lock, flags);
}
#define msm_dequeue(queue, member) ({ \
unsigned long flags; \
struct msm_device_queue *__q = (queue); \
struct msm_queue_cmd *qcmd = 0; \
spin_lock_irqsave(&__q->lock, flags); \
if (!list_empty(&__q->list)) { \
__q->len
qcmd = list_first_entry(&__q->list, \
struct msm_queue_cmd, member); \
if ((qcmd) && (&qcmd->member) && (&qcmd->member.next)) \
list_del_init(&qcmd->member); \
} \
<API key>(&__q->lock, flags); \
qcmd; \
})
#define msm_delete_entry(queue, member, q_cmd) ({ \
unsigned long __flags; \
struct msm_device_queue *__q = (queue); \
struct msm_queue_cmd *__qcmd = 0; \
pr_info("msm_delete_entry\n"); \
spin_lock_irqsave(&__q->lock, __flags); \
if (!list_empty(&__q->list)) { \
list_for_each_entry(__qcmd, &__q->list, member) \
if (__qcmd == q_cmd) { \
__q->len
list_del_init(&__qcmd->member); \
pr_info("msm_delete_entry, match found\n");\
kfree(q_cmd); \
q_cmd = NULL; \
break; \
} \
} \
<API key>(&__q->lock, __flags); \
q_cmd; \
})
#define msm_queue_drain(queue, member) do { \
unsigned long flags; \
struct msm_device_queue *__q = (queue); \
struct msm_queue_cmd *qcmd; \
spin_lock_irqsave(&__q->lock, flags); \
while (!list_empty(&__q->list)) { \
__q->len
qcmd = list_first_entry(&__q->list, \
struct msm_queue_cmd, member); \
if (qcmd) { \
if ((&qcmd->member) && (&qcmd->member.next)) \
list_del_init(&qcmd->member); \
free_qcmd(qcmd); \
} \
} \
<API key>(&__q->lock, flags); \
} while (0)
static int check_overlap(struct hlist_head *ptype,
unsigned long paddr,
unsigned long len)
{
struct msm_pmem_region *region;
struct msm_pmem_region t = { .paddr = paddr, .len = len };
struct hlist_node *node;
<API key>(region, node, ptype, list) {
if (CONTAINS(region, &t, paddr) ||
CONTAINS(&t, region, paddr) ||
OVERLAPS(region, &t, paddr)) {
CDBG(" region (PHYS %p len %ld)"
" clashes with registered region"
" (paddr %p len %ld)\n",
(void *)t.paddr, t.len,
(void *)region->paddr, region->len);
return -1;
}
}
return 0;
}
static int check_pmem_info(struct msm_pmem_info *info, int len)
{
if (info->offset < len &&
info->offset + info->len <= len &&
info->y_off < len &&
info->cbcr_off < len)
return 0;
pr_err("%s: check failed: off %d len %d y %d cbcr %d (total len %d)\n",
__func__,
info->offset,
info->len,
info->y_off,
info->cbcr_off,
len);
return -EINVAL;
}
static int msm_pmem_table_add(struct hlist_head *ptype,
struct msm_pmem_info *info, spinlock_t* pmem_spinlock,
struct msm_sync *sync)
{
struct file *file;
unsigned long paddr;
unsigned long kvstart;
unsigned long len;
int rc;
struct msm_pmem_region *region;
unsigned long flags;
rc = get_pmem_file(info->fd, &paddr, &kvstart, &len, &file);
if (rc < 0) {
pr_err("%s: get_pmem_file fd %d error %d\n",
__func__,
info->fd, rc);
return rc;
}
if (!info->len)
info->len = len;
rc = check_pmem_info(info, len);
if (rc < 0)
return rc;
paddr += info->offset;
len = info->len;
spin_lock_irqsave(pmem_spinlock, flags);
if (check_overlap(ptype, paddr, len) < 0) {
<API key>(pmem_spinlock, flags);
return -EINVAL;
}
<API key>(pmem_spinlock, flags);
region = kmalloc(sizeof(struct msm_pmem_region), GFP_KERNEL);
if (!region)
return -ENOMEM;
spin_lock_irqsave(pmem_spinlock, flags);
INIT_HLIST_NODE(®ion->list);
region->paddr = paddr;
region->len = len;
region->file = file;
memcpy(®ion->info, info, sizeof(region->info));
hlist_add_head(&(region->list), ptype);
<API key>(pmem_spinlock, flags);
pr_err("%s: type %d, paddr 0x%lx, vaddr 0x%lx fd %d cbcr_off 0x%x\n",
__func__, info->type, paddr, (unsigned long)info->vaddr, info->fd, info->cbcr_off);
return 0;
}
/* return of 0 means failure */
static uint8_t <API key>(struct hlist_head *ptype,
int pmem_type, struct msm_pmem_region *reg, uint8_t maxcount,
spinlock_t *pmem_spinlock)
{
struct msm_pmem_region *region;
struct msm_pmem_region *regptr;
struct hlist_node *node, *n;
unsigned long flags = 0;
uint8_t rc = 0;
regptr = reg;
spin_lock_irqsave(pmem_spinlock, flags);
<API key>(region, node, n, ptype, list) {
if (region->info.type == pmem_type && region->info.active) {
*regptr = *region;
rc += 1;
if (rc >= maxcount)
break;
regptr++;
}
}
<API key>(pmem_spinlock, flags);
/* After lookup failure, dump all the list entries...*/
if (rc == 0) {
pr_err("%s: pmem_type = %d\n", __func__, pmem_type);
<API key>(region, node, n, ptype, list) {
pr_err("listed region->info.type = %d, active = %d",
region->info.type, region->info.active);
}
}
return rc;
}
static uint8_t <API key>(struct hlist_head *ptype,
int pmem_type,
struct msm_pmem_region *reg,
uint8_t maxcount,
spinlock_t *pmem_spinlock)
{
struct msm_pmem_region *region;
struct msm_pmem_region *regptr;
struct hlist_node *node, *n;
uint8_t rc = 0;
unsigned long flags = 0;
regptr = reg;
spin_lock_irqsave(pmem_spinlock, flags);
<API key>(region, node, n, ptype, list) {
CDBG("%s:info.type=%d, pmem_type = %d,"
"info.active = %d\n",
__func__, region->info.type, pmem_type, region->info.active);
if (region->info.type == pmem_type && region->info.active) {
CDBG("%s:info.type=%d, pmem_type = %d,"
"info.active = %d,\n",
__func__, region->info.type, pmem_type,
region->info.active);
*regptr = *region;
region->info.type = MSM_PMEM_VIDEO;
rc += 1;
if (rc >= maxcount)
break;
regptr++;
}
}
<API key>(pmem_spinlock, flags);
return rc;
}
static int <API key>(struct msm_sync *sync,
unsigned long pyaddr,
unsigned long pcbcraddr,
struct msm_pmem_info *pmem_info,
int clear_active)
{
struct msm_pmem_region *region;
struct hlist_node *node, *n;
unsigned long flags = 0;
spin_lock_irqsave(&sync->pmem_frame_spinlock, flags);
<API key>(region, node, n, &sync->pmem_frames, list) {
if (pyaddr == (region->paddr + region->info.y_off) &&
pcbcraddr == (region->paddr +
region->info.cbcr_off) &&
region->info.active) {
/* offset since we could pass vaddr inside
* a registerd pmem buffer
*/
memcpy(pmem_info, ®ion->info, sizeof(*pmem_info));
if (clear_active)
region->info.active = 0;
<API key>(&sync->pmem_frame_spinlock,
flags);
return 0;
}
}
/* After lookup failure, dump all the list entries... */
pr_err("%s, for pyaddr 0x%lx, pcbcraddr 0x%lx\n",
__func__, pyaddr, pcbcraddr);
<API key>(region, node, n, &sync->pmem_frames, list) {
pr_err("listed pyaddr 0x%lx, pcbcraddr 0x%lx, active = %d",
(region->paddr + region->info.y_off),
(region->paddr + region->info.cbcr_off),
region->info.active);
}
<API key>(&sync->pmem_frame_spinlock, flags);
return -EINVAL;
}
static int <API key>(struct msm_sync *sync,
unsigned long pyaddr,
struct msm_pmem_info *pmem_info,
int clear_active)
{
struct msm_pmem_region *region;
struct hlist_node *node, *n;
unsigned long flags = 0;
spin_lock_irqsave(&sync->pmem_frame_spinlock, flags);
<API key>(region, node, n, &sync->pmem_frames, list) {
if (pyaddr == (region->paddr + region->info.y_off) &&
region->info.active) {
/* offset since we could pass vaddr inside
* a registerd pmem buffer
*/
memcpy(pmem_info, ®ion->info, sizeof(*pmem_info));
if (clear_active)
region->info.active = 0;
<API key>(&sync->pmem_frame_spinlock,
flags);
return 0;
}
}
<API key>(&sync->pmem_frame_spinlock, flags);
return -EINVAL;
}
static unsigned long <API key>(struct msm_sync *sync,
unsigned long addr, int *fd)
{
struct msm_pmem_region *region;
struct hlist_node *node, *n;
unsigned long flags = 0;
spin_lock_irqsave(&sync->pmem_stats_spinlock, flags);
<API key>(region, node, n, &sync->pmem_stats, list) {
if (addr == region->paddr && region->info.active) {
/* offset since we could pass vaddr inside a
* registered pmem buffer */
*fd = region->info.fd;
region->info.active = 0;
<API key>(&sync->pmem_stats_spinlock,
flags);
return (unsigned long)(region->info.vaddr);
}
}
/* After lookup failure, dump all the list entries... */
pr_err("%s, for paddr 0x%lx\n",
__func__, addr);
<API key>(region, node, n, &sync->pmem_stats, list) {
pr_err("listed paddr 0x%lx, active = %d",
region->paddr,
region->info.active);
}
<API key>(&sync->pmem_stats_spinlock, flags);
return 0;
}
static unsigned long <API key>(struct msm_sync *sync,
unsigned long buffer,
uint32_t yoff, uint32_t cbcroff, int fd, int change_flag)
{
struct msm_pmem_region *region;
struct hlist_node *node, *n;
unsigned long flags = 0;
spin_lock_irqsave(&sync->pmem_frame_spinlock, flags);
<API key>(region,
node, n, &sync->pmem_frames, list) {
if (((unsigned long)(region->info.vaddr) == buffer) &&
(region->info.y_off == yoff) &&
(region->info.cbcr_off == cbcroff) &&
(region->info.fd == fd) &&
(region->info.active == 0)) {
if (change_flag)
region->info.active = 1;
<API key>(&sync->pmem_frame_spinlock,
flags);
return region->paddr;
}
}
/* After lookup failure, dump all the list entries... */
pr_err("%s, failed for vaddr 0x%lx, yoff %d cbcroff %d\n",
__func__, buffer, yoff, cbcroff);
<API key>(region, node, n, &sync->pmem_frames, list) {
pr_err("listed vaddr 0x%p, cbcroff %d, active = %d",
(region->info.vaddr),
(region->info.cbcr_off),
region->info.active);
}
<API key>(&sync->pmem_frame_spinlock, flags);
return 0;
}
static unsigned long <API key>(
struct msm_sync *sync,
unsigned long buffer,
int fd)
{
struct msm_pmem_region *region;
struct hlist_node *node, *n;
unsigned long flags = 0;
spin_lock_irqsave(&sync->pmem_stats_spinlock, flags);
<API key>(region, node, n, &sync->pmem_stats, list) {
if (((unsigned long)(region->info.vaddr) == buffer) &&
(region->info.fd == fd) &&
region->info.active == 0) {
region->info.active = 1;
<API key>(&sync->pmem_stats_spinlock,
flags);
return region->paddr;
}
}
/* After lookup failure, dump all the list entries... */
pr_err("%s, for vaddr %ld\n",
__func__, buffer);
<API key>(region, node, n, &sync->pmem_stats, list) {
pr_err("listed vaddr 0x%p, active = %d",
region->info.vaddr,
region->info.active);
}
<API key>(&sync->pmem_stats_spinlock, flags);
return 0;
}
static int <API key>(struct msm_sync *sync,
struct msm_pmem_info *pinfo)
{
int rc = 0;
struct msm_pmem_region *region;
struct hlist_node *node, *n;
unsigned long flags = 0;
switch (pinfo->type) {
case MSM_PMEM_VIDEO:
case MSM_PMEM_PREVIEW:
case MSM_PMEM_THUMBNAIL:
case MSM_PMEM_MAINIMG:
case <API key>:
case MSM_PMEM_VIDEO_VPE:
case MSM_PMEM_C2D:
case <API key>:
case <API key>:
spin_lock_irqsave(&sync->pmem_frame_spinlock, flags);
<API key>(region, node, n,
&sync->pmem_frames, list) {
if (pinfo->type == region->info.type &&
pinfo->vaddr == region->info.vaddr &&
pinfo->fd == region->info.fd) {
hlist_del(node);
put_pmem_file(region->file);
kfree(region);
CDBG("%s: type %d, vaddr 0x%p\n",
__func__, pinfo->type, pinfo->vaddr);
}
}
<API key>(&sync->pmem_frame_spinlock, flags);
break;
case MSM_PMEM_AEC_AWB:
case MSM_PMEM_AF:
spin_lock_irqsave(&sync->pmem_stats_spinlock, flags);
<API key>(region, node, n,
&sync->pmem_stats, list) {
if (pinfo->type == region->info.type &&
pinfo->vaddr == region->info.vaddr &&
pinfo->fd == region->info.fd) {
hlist_del(node);
put_pmem_file(region->file);
kfree(region);
CDBG("%s: type %d, vaddr 0x%p\n",
__func__, pinfo->type, pinfo->vaddr);
}
}
<API key>(&sync->pmem_stats_spinlock, flags);
break;
default:
rc = -EINVAL;
break;
}
return rc;
}
static int msm_pmem_table_del(struct msm_sync *sync, void __user *arg)
{
struct msm_pmem_info info;
if (copy_from_user(&info, arg, sizeof(info))) {
ERR_COPY_FROM_USER();
return -EFAULT;
}
return <API key>(sync, &info);
}
static int __msm_get_frame(struct msm_sync *sync,
struct msm_frame *frame)
{
int rc = 0;
struct msm_pmem_info pmem_info;
struct msm_queue_cmd *qcmd = NULL;
struct msm_vfe_resp *vdata;
struct msm_vfe_phy_info *pphy;
qcmd = msm_dequeue(&sync->frame_q, list_frame);
if (!qcmd) {
pr_err("%s: no preview frame.\n", __func__);
return -EAGAIN;
}
if ((!qcmd->command) && (qcmd->error_code & MSM_CAMERA_ERR_MASK)) {
frame->error_code = qcmd->error_code;
pr_err("%s: fake frame with camera error code = %d\n",
__func__, frame->error_code);
goto err;
}
vdata = (struct msm_vfe_resp *)(qcmd->command);
pphy = &vdata->phy;
if (!pphy) {
pr_err("%s: Avoid accessing NULL pointer!\n", __func__);
goto err;
}
rc = <API key>(sync,
pphy->y_phy,
pphy->cbcr_phy,
&pmem_info,
1); /* Clear the active flag */
if (rc < 0) {
pr_err("%s: cannot get frame, invalid lookup address "
"y %x cbcr %x\n",
__func__,
pphy->y_phy,
pphy->cbcr_phy);
goto err;
}
frame->ts = qcmd->ts;
frame->buffer = (unsigned long)pmem_info.vaddr;
frame->y_off = pmem_info.y_off;
frame->cbcr_off = pmem_info.cbcr_off;
frame->fd = pmem_info.fd;
frame->path = vdata->phy.output_id;
frame->frame_id = vdata->phy.frame_id;
CDBG("%s: y %x, cbcr %x, qcmd %x, virt_addr %x\n",
__func__,
pphy->y_phy, pphy->cbcr_phy, (int) qcmd, (int) frame->buffer);
err:
free_qcmd(qcmd);
return rc;
}
static int msm_get_frame(struct msm_sync *sync, void __user *arg)
{
int rc = 0;
struct msm_frame frame;
if (copy_from_user(&frame,
arg,
sizeof(struct msm_frame))) {
ERR_COPY_FROM_USER();
return -EFAULT;
}
rc = __msm_get_frame(sync, &frame);
if (rc < 0)
return rc;
mutex_lock(&sync->lock);
if (sync->croplen && (!sync->stereocam_enabled)) {
if (frame.croplen != sync->croplen) {
pr_err("%s: invalid frame croplen %d,"
"expecting %d\n",
__func__,
frame.croplen,
sync->croplen);
mutex_unlock(&sync->lock);
return -EINVAL;
}
if (copy_to_user((void *)frame.cropinfo,
sync->cropinfo,
sync->croplen)) {
ERR_COPY_TO_USER();
mutex_unlock(&sync->lock);
return -EFAULT;
}
}
if (sync->fdroiinfo.info) {
if (copy_to_user((void *)frame.roi_info.info,
sync->fdroiinfo.info,
sync->fdroiinfo.info_len)) {
ERR_COPY_TO_USER();
mutex_unlock(&sync->lock);
return -EFAULT;
}
}
if (sync->stereocam_enabled) {
frame.stcam_conv_value = sync->stcam_conv_value;
frame.stcam_quality_ind = sync->stcam_quality_ind;
}
if (copy_to_user((void *)arg,
&frame, sizeof(struct msm_frame))) {
ERR_COPY_TO_USER();
rc = -EFAULT;
}
mutex_unlock(&sync->lock);
CDBG("%s: got frame\n", __func__);
return rc;
}
static int msm_enable_vfe(struct msm_sync *sync, void __user *arg)
{
int rc = -EIO;
struct camera_enable_cmd cfg;
if (copy_from_user(&cfg,
arg,
sizeof(struct camera_enable_cmd))) {
ERR_COPY_FROM_USER();
return -EFAULT;
}
if (sync->vfefn.vfe_enable)
rc = sync->vfefn.vfe_enable(&cfg);
return rc;
}
static int msm_disable_vfe(struct msm_sync *sync, void __user *arg)
{
int rc = -EIO;
struct camera_enable_cmd cfg;
if (copy_from_user(&cfg,
arg,
sizeof(struct camera_enable_cmd))) {
ERR_COPY_FROM_USER();
return -EFAULT;
}
if (sync->vfefn.vfe_disable)
rc = sync->vfefn.vfe_disable(&cfg, NULL);
return rc;
}
static struct msm_queue_cmd *__msm_control(struct msm_sync *sync,
struct msm_device_queue *queue,
struct msm_queue_cmd *qcmd,
int timeout)
{
int rc;
int loop = 0;
unsigned long flags = 0;
// get the command type first - prevent NULL pointer after <API key>
int16_t ignore_qcmd_type = (int16_t)((struct msm_ctrl_cmd *)
(qcmd->command))->type;
CDBG("Inside __msm_control\n");
if (sync->event_q.len <= 100 && sync->frame_q.len <= 100) {
/* wake up config thread */
msm_enqueue(&sync->event_q, &qcmd->list_config);
} else {
pr_err("%s, Error Queue limit exceeded e_q = %d, f_q = %d\n",
__func__, sync->event_q.len, sync->frame_q.len);
free_qcmd(qcmd);
return NULL;
}
if (!queue)
return NULL;
wait_event:
/* wait for config status */
CDBG("Waiting for config status \n");
rc = <API key>(
queue->wait,
!list_empty_careful(&queue->list),
timeout);
CDBG("Waiting over for config status\n");
if (list_empty_careful(&queue->list)) {
if (!rc) {
rc = -ETIMEDOUT;
pr_err("%s: wait_event error %d\n", __func__, rc);
return ERR_PTR(rc);
}
else if (rc < 0) {
spin_lock_irqsave(&queue->wait_lock, flags);
if (sync->qcmd_done) {
pr_info("%s: qcmd_done, continue to wait\n",
__func__);
<API key>(&queue->wait_lock, flags);
goto wait_event;
} else if (rc == -512 && loop < 20) {
/* loop 20 times if rc is - 512,
* to avoid ignoring command */
<API key>(&queue->wait_lock,
flags);
loop++;
msleep(5);
pr_info("%s: wait_event err %d\n",
__func__, rc);
pr_info("in loop %d time\n", loop);
goto wait_event;
} else {
pr_info("%s: wait_event err %d\n",
__func__, rc);
pr_info("%s: ignore cmd %d\n",
__func__, ignore_qcmd_type);
if (msm_delete_entry(&sync->event_q,
list_config, qcmd)) {
sync->ignore_qcmd = true;
sync->ignore_qcmd_type = ignore_qcmd_type;
}
<API key>(&queue->wait_lock, flags);
return ERR_PTR(rc);
}
}
}
sync->qcmd_done = false;
qcmd = msm_dequeue(queue, list_control);
BUG_ON(!qcmd);
CDBG("__msm_control done \n");
return qcmd;
}
static struct msm_queue_cmd *__msm_control_nb(struct msm_sync *sync,
struct msm_queue_cmd *qcmd_to_copy)
{
/* Since this is a non-blocking command, we cannot use qcmd_to_copy and
* its data, since they are on the stack. We replicate them on the heap
* and mark them on_heap so that they get freed when the config thread
* dequeues them.
*/
struct msm_ctrl_cmd *udata;
struct msm_ctrl_cmd *udata_to_copy = qcmd_to_copy->command;
struct msm_queue_cmd *qcmd =
kmalloc(sizeof(*qcmd_to_copy) +
sizeof(*udata_to_copy) +
udata_to_copy->length,
GFP_KERNEL);
if (!qcmd) {
pr_err("%s: out of memory\n", __func__);
return ERR_PTR(-ENOMEM);
}
*qcmd = *qcmd_to_copy;
udata = qcmd->command = qcmd + 1;
memcpy(udata, udata_to_copy, sizeof(*udata));
udata->value = udata + 1;
memcpy(udata->value, udata_to_copy->value, udata_to_copy->length);
atomic_set(&qcmd->on_heap, 1);
/* qcmd_resp will be set to NULL */
return __msm_control(sync, NULL, qcmd, 0);
}
static int msm_control(struct msm_control_device *ctrl_pmsm,
int block,
void __user *arg)
{
int rc = 0;
struct msm_sync *sync = ctrl_pmsm->pmsm->sync;
void __user *uptr;
struct msm_ctrl_cmd udata_resp;
struct msm_queue_cmd *qcmd_resp = NULL;
uint8_t data[<API key>];
struct msm_ctrl_cmd *udata;
struct msm_queue_cmd *qcmd =
kmalloc(sizeof(struct msm_queue_cmd) +
sizeof(struct msm_ctrl_cmd), GFP_ATOMIC);
if (!qcmd) {
pr_err("%s: out of memory\n", __func__);
return -ENOMEM;
}
udata = (struct msm_ctrl_cmd *)(qcmd + 1);
atomic_set(&(qcmd->on_heap), 1);
CDBG("Inside msm_control\n");
if (copy_from_user(udata, arg, sizeof(struct msm_ctrl_cmd))) {
ERR_COPY_FROM_USER();
rc = -EFAULT;
goto end;
}
uptr = udata->value;
udata->value = data;
qcmd->type = MSM_CAM_Q_CTRL;
qcmd->command = udata;
if (udata->length) {
if (udata->length > sizeof(data)) {
pr_err("%s: user data too large (%d, max is %d)\n",
__func__,
udata->length,
sizeof(data));
rc = -EIO;
goto end;
}
if (copy_from_user(udata->value, uptr, udata->length)) {
ERR_COPY_FROM_USER();
rc = -EFAULT;
goto end;
}
}
if (unlikely(!block)) {
qcmd_resp = __msm_control_nb(sync, qcmd);
goto end;
}
qcmd_resp = __msm_control(sync,
&ctrl_pmsm->ctrl_q,
qcmd, msecs_to_jiffies(10000));
/* ownership of qcmd will be transfered to event queue */
qcmd = NULL;
if (!qcmd_resp || IS_ERR(qcmd_resp)) {
/* Do not free qcmd_resp here. If the config thread read it,
* then it has already been freed, and we timed out because
* we did not receive a <API key>. If the
* config thread itself is blocked and not dequeueing commands,
* then it will either eventually unblock and process them,
* or when it is killed, qcmd will be freed in
* msm_release_config.
*/
rc = PTR_ERR(qcmd_resp);
qcmd_resp = NULL;
goto end;
}
if (qcmd_resp->command) {
udata_resp = *(struct msm_ctrl_cmd *)qcmd_resp->command;
if (udata_resp.length > 0) {
if (copy_to_user(uptr,
udata_resp.value,
udata_resp.length)) {
ERR_COPY_TO_USER();
rc = -EFAULT;
goto end;
}
}
udata_resp.value = uptr;
if (copy_to_user((void *)arg, &udata_resp,
sizeof(struct msm_ctrl_cmd))) {
ERR_COPY_TO_USER();
rc = -EFAULT;
goto end;
}
}
end:
free_qcmd(qcmd);
CDBG("%s: done rc = %d\n", __func__, rc);
return rc;
}
/* Divert frames for post-processing by delivering them to the config thread;
* when post-processing is done, it will return the frame to the frame thread.
*/
static int msm_divert_frame(struct msm_sync *sync,
struct msm_vfe_resp *data,
struct <API key> *se)
{
struct msm_pmem_info pinfo;
struct msm_postproc buf;
int rc;
CDBG("%s: Frame PP sync->pp_mask %d\n", __func__, sync->pp_mask);
if (!(sync->pp_mask & PP_PREV) && !(sync->pp_mask & PP_SNAP)) {
pr_err("%s: diverting frame, not in PP_PREV or PP_SNAP!\n",
__func__);
return -EINVAL;
}
rc = <API key>(sync, data->phy.y_phy,
data->phy.cbcr_phy, &pinfo,
0); /* do not clear the active flag */
if (rc < 0) {
pr_err("%s: <API key> failed\n", __func__);
return rc;
}
buf.fmain.buffer = (unsigned long)pinfo.vaddr;
buf.fmain.y_off = pinfo.y_off;
buf.fmain.cbcr_off = pinfo.cbcr_off;
buf.fmain.fd = pinfo.fd;
CDBG("%s: buf 0x%x fd %d\n", __func__, (unsigned int)buf.fmain.buffer,
buf.fmain.fd);
if (copy_to_user((void *)(se->stats_event.data),
&(buf.fmain), sizeof(struct msm_frame))) {
ERR_COPY_TO_USER();
return -EFAULT;
}
return 0;
}
/* Divert stereo frames for post-processing by delivering
* them to the config thread.
*/
static int msm_divert_st_frame(struct msm_sync *sync,
struct msm_vfe_resp *data, struct <API key> *se, int path)
{
struct msm_pmem_info pinfo;
struct msm_st_frame buf;
struct video_crop_t *crop = NULL;
int rc = 0;
memset(&pinfo, 0x00, sizeof(struct msm_pmem_info));
memset(&buf, 0x00, sizeof(struct msm_st_frame));
if (se->stats_event.msg_id == OUTPUT_TYPE_ST_L) {
buf.type = OUTPUT_TYPE_ST_L;
} else if (se->stats_event.msg_id == OUTPUT_TYPE_ST_R) {
buf.type = OUTPUT_TYPE_ST_R;
} else {
if (se->resptype == <API key>) {
rc = <API key>(sync, data->phy.y_phy,
data->phy.cbcr_phy, &pinfo,
1); /* do clear the active flag */
buf.buf_info.path = path;
} else if (se->resptype == <API key>) {
rc = <API key>(sync, data->phy.y_phy,
data->phy.cbcr_phy, &pinfo,
0); /* do not clear the active flag */
buf.buf_info.path = path;
} else
pr_err("%s: Invalid resptype = %d\n", __func__,
se->resptype);
if (rc < 0) {
pr_err("%s: <API key> failed\n",
__func__);
return rc;
}
buf.type = OUTPUT_TYPE_ST_D;
if (sync->cropinfo != NULL) {
crop = sync->cropinfo;
switch (path) {
case OUTPUT_TYPE_P:
case OUTPUT_TYPE_T: {
buf.L.stCropInfo.in_w = crop->in1_w;
buf.L.stCropInfo.in_h = crop->in1_h;
buf.L.stCropInfo.out_w = crop->out1_w;
buf.L.stCropInfo.out_h = crop->out1_h;
buf.R.stCropInfo = buf.L.stCropInfo;
break;
}
case OUTPUT_TYPE_V:
case OUTPUT_TYPE_S: {
buf.L.stCropInfo.in_w = crop->in2_w;
buf.L.stCropInfo.in_h = crop->in2_h;
buf.L.stCropInfo.out_w = crop->out2_w;
buf.L.stCropInfo.out_h = crop->out2_h;
buf.R.stCropInfo = buf.L.stCropInfo;
break;
}
default: {
pr_warning("%s: invalid frame path %d\n",
__func__, path);
break;
}
}
} else {
buf.L.stCropInfo.in_w = 0;
buf.L.stCropInfo.in_h = 0;
buf.L.stCropInfo.out_w = 0;
buf.L.stCropInfo.out_h = 0;
buf.R.stCropInfo = buf.L.stCropInfo;
}
/* hardcode for now. */
if ((path == OUTPUT_TYPE_S) || (path == OUTPUT_TYPE_T))
buf.packing = sync->sctrl.s_snap_packing;
else
buf.packing = sync->sctrl.s_video_packing;
buf.buf_info.buffer = (unsigned long)pinfo.vaddr;
buf.buf_info.phy_offset = pinfo.offset;
buf.buf_info.y_off = pinfo.y_off;
buf.buf_info.cbcr_off = pinfo.cbcr_off;
buf.buf_info.fd = pinfo.fd;
CDBG("%s: buf 0x%x fd %d\n", __func__,
(unsigned int)buf.buf_info.buffer, buf.buf_info.fd);
}
if (copy_to_user((void *)(se->stats_event.data),
&buf, sizeof(struct msm_st_frame))) {
ERR_COPY_TO_USER();
return -EFAULT;
}
return 0;
}
static int msm_get_stats(struct msm_sync *sync, void __user *arg)
{
int rc = 0;
struct <API key> se;
struct msm_queue_cmd *qcmd = NULL;
struct msm_ctrl_cmd *ctrl = NULL;
struct msm_vfe_resp *data = NULL;
struct msm_vpe_resp *vpe_data = NULL;
struct msm_stats_buf stats;
if (copy_from_user(&se, arg,
sizeof(struct <API key>))) {
ERR_COPY_FROM_USER();
pr_err("%s, ERR_COPY_FROM_USER\n", __func__);
return -EFAULT;
}
rc = 0;
qcmd = msm_dequeue(&sync->event_q, list_config);
if (!qcmd) {
/* Should be associated with wait_event
error -512 from __msm_control*/
pr_err("%s, qcmd is Null\n", __func__);
rc = -ETIMEDOUT;
return rc;
}
CDBG("%s: received from DSP %d\n", __func__, qcmd->type);
switch (qcmd->type) {
case MSM_CAM_Q_VPE_MSG:
/* Complete VPE response. */
vpe_data = (struct msm_vpe_resp *)(qcmd->command);
se.resptype = <API key>;
se.stats_event.type = vpe_data->evt_msg.type;
se.stats_event.msg_id = vpe_data->evt_msg.msg_id;
se.stats_event.len = vpe_data->evt_msg.len;
if (vpe_data->type == VPE_MSG_OUTPUT_ST_L) {
CDBG("%s: Change msg_id to OUTPUT_TYPE_ST_L\n",
__func__);
se.stats_event.msg_id = OUTPUT_TYPE_ST_L;
rc = msm_divert_st_frame(sync, data, &se,
OUTPUT_TYPE_V);
} else if (vpe_data->type == VPE_MSG_OUTPUT_ST_R) {
CDBG("%s: Change msg_id to OUTPUT_TYPE_ST_R\n",
__func__);
se.stats_event.msg_id = OUTPUT_TYPE_ST_R;
rc = msm_divert_st_frame(sync, data, &se,
OUTPUT_TYPE_V);
} else {
pr_warning("%s: invalid vpe_data->type = %d\n",
__func__, vpe_data->type);
}
break;
case MSM_CAM_Q_VFE_EVT:
case MSM_CAM_Q_VFE_MSG:
data = (struct msm_vfe_resp *)(qcmd->command);
/* adsp event and message */
se.resptype = <API key>;
/* 0 - msg from aDSP, 1 - event from mARM */
se.stats_event.type = data->evt_msg.type;
se.stats_event.msg_id = data->evt_msg.msg_id;
se.stats_event.len = data->evt_msg.len;
se.stats_event.frame_id = data->evt_msg.frame_id;
CDBG("%s: qcmd->type %d length %d msd_id %d\n", __func__,
qcmd->type,
se.stats_event.len,
se.stats_event.msg_id);
if ((data->type >= VFE_MSG_STATS_AEC) &&
(data->type <= VFE_MSG_STATS_WE)) {
/* the check above includes all stats type. */
stats.buffer =
<API key>(sync,
data->phy.sbuf_phy,
&(stats.fd));
if (!stats.buffer) {
pr_err("%s: <API key> error\n",
__func__);
rc = -EINVAL;
goto failure;
}
if (copy_to_user((void *)(se.stats_event.data),
&stats,
sizeof(struct msm_stats_buf))) {
ERR_COPY_TO_USER();
rc = -EFAULT;
goto failure;
}
} else if ((data->evt_msg.len > 0) &&
(data->type == VFE_MSG_GENERAL)) {
if (copy_to_user((void *)(se.stats_event.data),
data->evt_msg.data,
data->evt_msg.len)) {
ERR_COPY_TO_USER();
rc = -EFAULT;
goto failure;
}
} else {
if (sync->stereocam_enabled) {
if (data->type == VFE_MSG_OUTPUT_P) {
CDBG("%s: Preview mark as st op 1\n",
__func__);
se.resptype = <API key>;
rc = msm_divert_st_frame(sync, data,
&se, OUTPUT_TYPE_P);
break;
} else if (data->type == VFE_MSG_OUTPUT_V) {
CDBG("%s: Video mark as st op 2\n",
__func__);
se.resptype = <API key>;
rc = msm_divert_st_frame(sync, data,
&se, OUTPUT_TYPE_V);
break;
} else if (data->type == VFE_MSG_OUTPUT_S) {
pr_err("%s: Main img mark as st op 2\n",
__func__);
se.resptype = <API key>;
rc = msm_divert_st_frame(sync, data,
&se, OUTPUT_TYPE_S);
break;
} else if (data->type == VFE_MSG_OUTPUT_T) {
pr_err("%s: Thumb img mark as st op 2\n",
__func__);
se.resptype = <API key>;
rc = msm_divert_st_frame(sync, data,
&se, OUTPUT_TYPE_T);
break;
} else
CDBG("%s: VFE_MSG Fall Through\n",
__func__);
}
if ((sync->pp_frame_avail == 1) &&
(sync->pp_mask & PP_PREV) &&
(data->type == VFE_MSG_OUTPUT_P)) {
CDBG("%s:%d:preiew PP\n",
__func__, __LINE__);
rc = msm_divert_frame(sync, data, &se);
sync->pp_frame_avail = 0;
} else {
if ((sync->pp_mask & PP_PREV) &&
(data->type == VFE_MSG_OUTPUT_P)) {
free_qcmd(qcmd);
return 0;
} else
CDBG("%s:indication type is %d\n",
__func__, data->type);
}
if (sync->pp_mask & PP_SNAP)
if (data->type == VFE_MSG_OUTPUT_S ||
data->type == VFE_MSG_OUTPUT_T)
rc = msm_divert_frame(sync, data, &se);
}
break;
case MSM_CAM_Q_CTRL:
/* control command from control thread */
ctrl = (struct msm_ctrl_cmd *)(qcmd->command);
CDBG("%s: qcmd->type %d length %d\n", __func__,
qcmd->type, ctrl->length);
if (ctrl->length > 0) {
if (copy_to_user((void *)(se.ctrl_cmd.value),
ctrl->value,
ctrl->length)) {
ERR_COPY_TO_USER();
rc = -EFAULT;
goto failure;
}
}
se.resptype = MSM_CAM_RESP_CTRL;
/* what to control */
se.ctrl_cmd.type = ctrl->type;
se.ctrl_cmd.length = ctrl->length;
se.ctrl_cmd.resp_fd = ctrl->resp_fd;
break;
case MSM_CAM_Q_V4L2_REQ:
/* control command from v4l2 client */
ctrl = (struct msm_ctrl_cmd *)(qcmd->command);
if (ctrl->length > 0) {
if (copy_to_user((void *)(se.ctrl_cmd.value),
ctrl->value, ctrl->length)) {
ERR_COPY_TO_USER();
rc = -EFAULT;
goto failure;
}
}
/* 2 tells config thread this is v4l2 request */
se.resptype = MSM_CAM_RESP_V4L2;
/* what to control */
se.ctrl_cmd.type = ctrl->type;
se.ctrl_cmd.length = ctrl->length;
break;
default:
rc = -EFAULT;
goto failure;
} /* switch qcmd->type */
if (copy_to_user((void *)arg, &se, sizeof(se))) {
ERR_COPY_TO_USER();
rc = -EFAULT;
goto failure;
}
failure:
free_qcmd(qcmd);
CDBG("%s: %d\n", __func__, rc);
return rc;
}
static int msm_ctrl_cmd_done(struct msm_control_device *ctrl_pmsm,
void __user *arg)
{
void __user *uptr;
struct msm_queue_cmd *qcmd = &ctrl_pmsm->qcmd;
struct msm_ctrl_cmd *command = &ctrl_pmsm->ctrl;
unsigned long flags = 0;
struct msm_device_queue *queue = &ctrl_pmsm->ctrl_q;
if (copy_from_user(command, arg, sizeof(*command))) {
ERR_COPY_FROM_USER();
return -EFAULT;
}
atomic_set(&qcmd->on_heap, 0);
qcmd->command = command;
uptr = command->value;
if (command->length > 0) {
command->value = ctrl_pmsm->ctrl_data;
if (command->length > sizeof(ctrl_pmsm->ctrl_data)) {
pr_err("%s: user data %d is too big (max %d)\n",
__func__, command->length,
sizeof(ctrl_pmsm->ctrl_data));
return -EINVAL;
}
if (copy_from_user(command->value,
uptr,
command->length)) {
ERR_COPY_FROM_USER();
return -EFAULT;
}
} else
command->value = NULL;
spin_lock_irqsave(&queue->wait_lock, flags);
/* wake up control thread */
/*msm_enqueue(&ctrl_pmsm->ctrl_q, &qcmd->list_control);*/
/* Ignore the command if the ctrl cmd has
return back due to signaling */
/* Should be associated with wait_event
error -512 from __msm_control*/
if (ctrl_pmsm->pmsm->sync->ignore_qcmd == true &&
ctrl_pmsm->pmsm->sync->ignore_qcmd_type == (int16_t)command->type) {
printk("%s: ignore this command %d\n", __func__, command->type);
ctrl_pmsm->pmsm->sync->ignore_qcmd = false;
ctrl_pmsm->pmsm->sync->ignore_qcmd_type = -1;
<API key>(&queue->wait_lock, flags);
} else /* wake up control thread */{
ctrl_pmsm->pmsm->sync->qcmd_done = true;
<API key>(&queue->wait_lock, flags);
msm_enqueue(&ctrl_pmsm->ctrl_q, &qcmd->list_control);
}
return 0;
}
static int msm_config_vpe(struct msm_sync *sync, void __user *arg)
{
struct msm_vpe_cfg_cmd cfgcmd;
if (copy_from_user(&cfgcmd, arg, sizeof(cfgcmd))) {
ERR_COPY_FROM_USER();
return -EFAULT;
}
CDBG("%s: cmd_type %s\n", __func__, vfe_config_cmd[cfgcmd.cmd_type]);
switch (cfgcmd.cmd_type) {
case CMD_VPE:
return sync->vpefn.vpe_config(&cfgcmd, NULL);
default:
pr_err("%s: unknown command type %d\n",
__func__, cfgcmd.cmd_type);
}
return -EINVAL;
}
static int msm_config_vfe(struct msm_sync *sync, void __user *arg)
{
struct msm_vfe_cfg_cmd cfgcmd;
struct msm_pmem_region region[8];
struct axidata axi_data;
if (!sync->vfefn.vfe_config) {
pr_err("%s: no vfe_config!\n", __func__);
return -EIO;
}
if (copy_from_user(&cfgcmd, arg, sizeof(cfgcmd))) {
ERR_COPY_FROM_USER();
return -EFAULT;
}
memset(&axi_data, 0, sizeof(axi_data));
CDBG("%s: cmd_type %s\n", __func__, vfe_config_cmd[cfgcmd.cmd_type]);
switch (cfgcmd.cmd_type) {
case CMD_STATS_ENABLE:
axi_data.bufnum1 =
<API key>(&sync->pmem_stats,
MSM_PMEM_AEC_AWB, ®ion[0],
<API key>,
&sync->pmem_stats_spinlock);
axi_data.bufnum2 =
<API key>(&sync->pmem_stats,
MSM_PMEM_AF, ®ion[axi_data.bufnum1],
<API key>,
&sync->pmem_stats_spinlock);
if (!axi_data.bufnum1 || !axi_data.bufnum2) {
pr_err("%s: pmem region lookup error\n", __func__);
return -EINVAL;
}
axi_data.region = ®ion[0];
return sync->vfefn.vfe_config(&cfgcmd, &axi_data);
case CMD_STATS_AF_ENABLE:
axi_data.bufnum1 =
<API key>(&sync->pmem_stats,
MSM_PMEM_AF, ®ion[0],
<API key>,
&sync->pmem_stats_spinlock);
if (!axi_data.bufnum1) {
pr_err("%s %d: pmem region lookup error\n",
__func__, __LINE__);
return -EINVAL;
}
axi_data.region = ®ion[0];
return sync->vfefn.vfe_config(&cfgcmd, &axi_data);
case <API key>:
axi_data.bufnum1 =
<API key>(&sync->pmem_stats,
MSM_PMEM_AEC_AWB, ®ion[0],
<API key>,
&sync->pmem_stats_spinlock);
if (!axi_data.bufnum1) {
pr_err("%s %d: pmem region lookup error\n",
__func__, __LINE__);
return -EINVAL;
}
axi_data.region = ®ion[0];
return sync->vfefn.vfe_config(&cfgcmd, &axi_data);
case <API key>:
axi_data.bufnum1 =
<API key>(&sync->pmem_stats,
MSM_PMEM_AEC, ®ion[0],
<API key>,
&sync->pmem_stats_spinlock);
if (!axi_data.bufnum1) {
pr_err("%s %d: pmem region lookup error\n",
__func__, __LINE__);
return -EINVAL;
}
axi_data.region = ®ion[0];
return sync->vfefn.vfe_config(&cfgcmd, &axi_data);
case <API key>:
axi_data.bufnum1 =
<API key>(&sync->pmem_stats,
MSM_PMEM_AWB, ®ion[0],
<API key>,
&sync->pmem_stats_spinlock);
if (!axi_data.bufnum1) {
pr_err("%s %d: pmem region lookup error\n",
__func__, __LINE__);
return -EINVAL;
}
axi_data.region = ®ion[0];
return sync->vfefn.vfe_config(&cfgcmd, &axi_data);
case <API key>:
axi_data.bufnum1 =
<API key>(&sync->pmem_stats,
MSM_PMEM_IHIST, ®ion[0],
<API key>,
&sync->pmem_stats_spinlock);
if (!axi_data.bufnum1) {
pr_err("%s %d: pmem region lookup error\n",
__func__, __LINE__);
return -EINVAL;
}
axi_data.region = ®ion[0];
return sync->vfefn.vfe_config(&cfgcmd, &axi_data);
case CMD_STATS_RS_ENABLE:
axi_data.bufnum1 =
<API key>(&sync->pmem_stats,
MSM_PMEM_RS, ®ion[0],
<API key>,
&sync->pmem_stats_spinlock);
if (!axi_data.bufnum1) {
pr_err("%s %d: pmem region lookup error\n",
__func__, __LINE__);
return -EINVAL;
}
axi_data.region = ®ion[0];
return sync->vfefn.vfe_config(&cfgcmd, &axi_data);
case CMD_STATS_CS_ENABLE:
axi_data.bufnum1 =
<API key>(&sync->pmem_stats,
MSM_PMEM_CS, ®ion[0],
<API key>,
&sync->pmem_stats_spinlock);
if (!axi_data.bufnum1) {
pr_err("%s %d: pmem region lookup error\n",
__func__, __LINE__);
return -EINVAL;
}
axi_data.region = ®ion[0];
return sync->vfefn.vfe_config(&cfgcmd, &axi_data);
case CMD_GENERAL:
case CMD_STATS_DISABLE:
return sync->vfefn.vfe_config(&cfgcmd, NULL);
default:
pr_err("%s: unknown command type %d\n",
__func__, cfgcmd.cmd_type);
}
return -EINVAL;
}
static int msm_vpe_frame_cfg(struct msm_sync *sync,
void *cfgcmdin)
{
int rc = -EIO;
struct axidata axi_data;
void *data = &axi_data;
struct msm_pmem_region region[8];
int pmem_type;
struct msm_vpe_cfg_cmd *cfgcmd;
cfgcmd = (struct msm_vpe_cfg_cmd *)cfgcmdin;
memset(&axi_data, 0, sizeof(axi_data));
CDBG("In vpe_frame_cfg cfgcmd->cmd_type = %s\n",
vfe_config_cmd[cfgcmd->cmd_type]);
switch (cfgcmd->cmd_type) {
case CMD_AXI_CFG_VPE:
pmem_type = MSM_PMEM_VIDEO_VPE;
axi_data.bufnum1 =
<API key>(&sync->pmem_frames, pmem_type,
®ion[0], 8, &sync->pmem_frame_spinlock);
CDBG("axi_data.bufnum1 = %d\n", axi_data.bufnum1);
if (!axi_data.bufnum1) {
pr_err("%s %d: pmem region lookup error\n",
__func__, __LINE__);
return -EINVAL;
}
pmem_type = MSM_PMEM_VIDEO;
break;
case <API key>:
CDBG("%s: <API key>", __func__);
pmem_type = <API key>;
axi_data.bufnum1 =
<API key>(&sync->pmem_frames, pmem_type,
®ion[0], 8, &sync->pmem_frame_spinlock);
if (!axi_data.bufnum1) {
pr_err("%s: THUMBNAIL_VPE pmem region lookup error\n",
__func__);
return -EINVAL;
}
break;
case <API key>:
CDBG("%s: <API key>", __func__);
pmem_type = <API key>;
axi_data.bufnum1 =
<API key>(&sync->pmem_frames, pmem_type,
®ion[0], 8, &sync->pmem_frame_spinlock);
if (!axi_data.bufnum1) {
pr_err("%s: MAINIMG_VPE pmem region lookup error\n",
__func__);
return -EINVAL;
}
break;
default:
pr_err("%s: unknown command type %d\n",
__func__, cfgcmd->cmd_type);
break;
}
axi_data.region = ®ion[0];
CDBG("out vpe_frame_cfg cfgcmd->cmd_type = %s\n",
vfe_config_cmd[cfgcmd->cmd_type]);
/* send the AXI configuration command to driver */
if (sync->vpefn.vpe_config)
rc = sync->vpefn.vpe_config(cfgcmd, data);
return rc;
}
static int msm_frame_axi_cfg(struct msm_sync *sync,
struct msm_vfe_cfg_cmd *cfgcmd)
{
int rc = -EIO;
struct axidata axi_data;
void *data = &axi_data;
struct msm_pmem_region region[<API key> + 1];
int pmem_type;
memset(&axi_data, 0, sizeof(axi_data));
switch (cfgcmd->cmd_type) {
case CMD_AXI_CFG_PREVIEW:
pmem_type = MSM_PMEM_PREVIEW;
axi_data.bufnum2 =
<API key>(&sync->pmem_frames, pmem_type,
®ion[0], <API key>,
&sync->pmem_frame_spinlock);
if (!axi_data.bufnum2) {
pr_err("%s %d: pmem region lookup error (empty %d)\n",
__func__, __LINE__,
hlist_empty(&sync->pmem_frames));
return -EINVAL;
}
break;
case CMD_AXI_CFG_VIDEO:
pmem_type = MSM_PMEM_PREVIEW;
axi_data.bufnum1 =
<API key>(&sync->pmem_frames, pmem_type,
®ion[0], <API key>,
&sync->pmem_frame_spinlock);
if (!axi_data.bufnum1) {
pr_err("%s %d: pmem region lookup error\n",
__func__, __LINE__);
return -EINVAL;
}
pmem_type = MSM_PMEM_VIDEO;
axi_data.bufnum2 =
<API key>(&sync->pmem_frames, pmem_type,
®ion[axi_data.bufnum1],
(<API key>-(axi_data.bufnum1)),
&sync->pmem_frame_spinlock);
if (!axi_data.bufnum2) {
pr_err("%s %d: pmem region lookup error\n",
__func__, __LINE__);
return -EINVAL;
}
break;
case CMD_AXI_CFG_SNAP:
CDBG("%s, CMD_AXI_CFG_SNAP, type=%d\n", __func__,
cfgcmd->cmd_type);
pmem_type = MSM_PMEM_THUMBNAIL;
axi_data.bufnum1 =
<API key>(&sync->pmem_frames, pmem_type,
®ion[0], <API key>,
&sync->pmem_frame_spinlock);
if (!axi_data.bufnum1) {
pr_err("%s %d: pmem region lookup error\n",
__func__, __LINE__);
return -EINVAL;
}
pmem_type = MSM_PMEM_MAINIMG;
axi_data.bufnum2 =
<API key>(&sync->pmem_frames, pmem_type,
®ion[axi_data.bufnum1],
(<API key>-(axi_data.bufnum1)),
&sync->pmem_frame_spinlock);
if (!axi_data.bufnum2) {
pr_err("%s %d: pmem region lookup error\n",
__func__, __LINE__);
return -EINVAL;
}
break;
case CMD_AXI_CFG_ZSL:
CDBG("%s, CMD_AXI_CFG_ZSL, type = %d\n", __func__,
cfgcmd->cmd_type);
pmem_type = MSM_PMEM_PREVIEW;
axi_data.bufnum1 =
<API key>(&sync->pmem_frames, pmem_type,
®ion[0], <API key>,
&sync->pmem_frame_spinlock);
if (!axi_data.bufnum1) {
pr_err("%s %d: pmem region lookup error\n",
__func__, __LINE__);
return -EINVAL;
}
pmem_type = MSM_PMEM_THUMBNAIL;
axi_data.bufnum2 =
<API key>(&sync->pmem_frames, pmem_type,
®ion[axi_data.bufnum1],
(<API key>-(axi_data.bufnum1)),
&sync->pmem_frame_spinlock);
if (!axi_data.bufnum2) {
pr_err("%s %d: pmem region lookup error\n",
__func__, __LINE__);
return -EINVAL;
}
pmem_type = MSM_PMEM_MAINIMG;
axi_data.bufnum3 =
<API key>(&sync->pmem_frames, pmem_type,
®ion[axi_data.bufnum1 + axi_data.bufnum2],
(<API key> - axi_data.bufnum1 -
axi_data.bufnum2), &sync->pmem_frame_spinlock);
if (!axi_data.bufnum3) {
pr_err("%s %d: pmem region lookup error\n",
__func__, __LINE__);
return -EINVAL;
}
break;
case <API key>:
pmem_type = <API key>;
axi_data.bufnum2 =
<API key>(&sync->pmem_frames, pmem_type,
®ion[0], <API key>,
&sync->pmem_frame_spinlock);
if (!axi_data.bufnum2) {
pr_err("%s %d: pmem region lookup error\n",
__func__, __LINE__);
return -EINVAL;
}
break;
case CMD_GENERAL:
data = NULL;
break;
default:
pr_err("%s: unknown command type %d\n",
__func__, cfgcmd->cmd_type);
return -EINVAL;
}
axi_data.region = ®ion[0];
/* send the AXI configuration command to driver */
if (sync->vfefn.vfe_config)
rc = sync->vfefn.vfe_config(cfgcmd, data);
return rc;
}
static int msm_get_sensor_info(struct msm_sync *sync, void __user *arg)
{
int rc = 0;
struct msm_camsensor_info info;
struct <API key> *sdata;
if (copy_from_user(&info,
arg,
sizeof(struct msm_camsensor_info))) {
ERR_COPY_FROM_USER();
return -EFAULT;
}
sdata = sync->pdev->dev.platform_data;
if (sync->sctrl.s_camera_type == BACK_CAMERA_3D)
info.support_3d = true;
else
info.support_3d = false;
memcpy(&info.name[0],
sdata->sensor_name,
MAX_SENSOR_NAME);
info.flash_enabled = sdata->flash_data->flash_type !=
<API key>;
/* copy back to user space */
if (copy_to_user((void *)arg,
&info,
sizeof(struct msm_camsensor_info))) {
ERR_COPY_TO_USER();
rc = -EFAULT;
}
return rc;
}
static int msm_get_camera_info(void __user *arg)
{
int rc = 0;
int i = 0;
struct msm_camera_info info;
if (copy_from_user(&info, arg, sizeof(struct msm_camera_info))) {
ERR_COPY_FROM_USER();
return -EFAULT;
}
CDBG("%s: camera_node %d\n", __func__, camera_node);
info.num_cameras = camera_node;
for (i = 0; i < camera_node; i++) {
info.has_3d_support[i] = 0;
info.is_internal_cam[i] = 0;
info.s_mount_angle[i] = sensor_mount_angle[i];
switch (camera_type[i]) {
case FRONT_CAMERA_2D:
info.is_internal_cam[i] = 1;
break;
case BACK_CAMERA_3D:
info.has_3d_support[i] = 1;
break;
case BACK_CAMERA_2D:
default:
break;
}
}
/* copy back to user space */
if (copy_to_user((void *)arg, &info, sizeof(struct msm_camera_info))) {
ERR_COPY_TO_USER();
rc = -EFAULT;
}
return rc;
}
static int __msm_put_frame_buf(struct msm_sync *sync,
struct msm_frame *pb)
{
unsigned long pphy;
struct msm_vfe_cfg_cmd cfgcmd;
int rc = -EIO;
/* Change the active flag. */
pphy = <API key>(sync,
pb->buffer,
pb->y_off, pb->cbcr_off, pb->fd, 1);
if (pphy != 0) {
CDBG("%s: rel: vaddr %lx, paddr %lx\n",
__func__,
pb->buffer, pphy);
cfgcmd.cmd_type = <API key>;
cfgcmd.value = (void *)pb;
if (sync->vfefn.vfe_config)
rc = sync->vfefn.vfe_config(&cfgcmd, &pphy);
} else {
pr_err("%s: <API key> failed\n",
__func__);
rc = -EINVAL;
}
return rc;
}
static int __msm_put_pic_buf(struct msm_sync *sync,
struct msm_frame *pb)
{
unsigned long pphy;
struct msm_vfe_cfg_cmd cfgcmd;
int rc = -EIO;
pphy = <API key>(sync,
pb->buffer,
pb->y_off, pb->cbcr_off, pb->fd, 1);
if (pphy != 0) {
CDBG("%s: rel: vaddr %lx, paddr %lx\n",
__func__,
pb->buffer, pphy);
cfgcmd.cmd_type = <API key>;
cfgcmd.value = (void *)pb;
if (sync->vfefn.vfe_config)
rc = sync->vfefn.vfe_config(&cfgcmd, &pphy);
} else {
pr_err("%s: <API key> failed\n",
__func__);
rc = -EINVAL;
}
return rc;
}
static int <API key>(struct msm_sync *sync, void __user *arg)
{
struct msm_frame buf_t;
if (copy_from_user(&buf_t,
arg,
sizeof(struct msm_frame))) {
ERR_COPY_FROM_USER();
return -EFAULT;
}
return __msm_put_frame_buf(sync, &buf_t);
}
static int msm_put_pic_buffer(struct msm_sync *sync, void __user *arg)
{
struct msm_frame buf_t;
if (copy_from_user(&buf_t,
arg,
sizeof(struct msm_frame))) {
ERR_COPY_FROM_USER();
return -EFAULT;
}
return __msm_put_pic_buf(sync, &buf_t);
}
static int __msm_register_pmem(struct msm_sync *sync,
struct msm_pmem_info *pinfo)
{
int rc = 0;
switch (pinfo->type) {
case MSM_PMEM_VIDEO:
case MSM_PMEM_PREVIEW:
case MSM_PMEM_THUMBNAIL:
case MSM_PMEM_MAINIMG:
case <API key>:
case MSM_PMEM_VIDEO_VPE:
case MSM_PMEM_C2D:
case <API key>:
case <API key>:
rc = msm_pmem_table_add(&sync->pmem_frames, pinfo,
&sync->pmem_frame_spinlock, sync);
break;
case MSM_PMEM_AEC_AWB:
case MSM_PMEM_AF:
case MSM_PMEM_AEC:
case MSM_PMEM_AWB:
case MSM_PMEM_RS:
case MSM_PMEM_CS:
case MSM_PMEM_IHIST:
case MSM_PMEM_SKIN:
rc = msm_pmem_table_add(&sync->pmem_stats, pinfo,
&sync->pmem_stats_spinlock, sync);
break;
default:
rc = -EINVAL;
break;
}
return rc;
}
static int msm_register_pmem(struct msm_sync *sync, void __user *arg)
{
struct msm_pmem_info info;
if (copy_from_user(&info, arg, sizeof(info))) {
ERR_COPY_FROM_USER();
return -EFAULT;
}
return __msm_register_pmem(sync, &info);
}
static int msm_stats_axi_cfg(struct msm_sync *sync,
struct msm_vfe_cfg_cmd *cfgcmd)
{
int rc = -EIO;
struct axidata axi_data;
void *data = &axi_data;
struct msm_pmem_region region[3];
int pmem_type = MSM_PMEM_MAX;
memset(&axi_data, 0, sizeof(axi_data));
switch (cfgcmd->cmd_type) {
case CMD_STATS_AXI_CFG:
pmem_type = MSM_PMEM_AEC_AWB;
break;
case <API key>:
pmem_type = MSM_PMEM_AF;
break;
case CMD_GENERAL:
data = NULL;
break;
default:
pr_err("%s: unknown command type %d\n",
__func__, cfgcmd->cmd_type);
return -EINVAL;
}
if (cfgcmd->cmd_type != CMD_GENERAL) {
axi_data.bufnum1 =
<API key>(&sync->pmem_stats, pmem_type,
®ion[0], <API key>,
&sync->pmem_stats_spinlock);
if (!axi_data.bufnum1) {
pr_err("%s %d: pmem region lookup error\n",
__func__, __LINE__);
return -EINVAL;
}
axi_data.region = ®ion[0];
}
/* send the AEC/AWB STATS configuration command to driver */
if (sync->vfefn.vfe_config)
rc = sync->vfefn.vfe_config(cfgcmd, &axi_data);
return rc;
}
static int <API key>(struct msm_sync *sync, void __user *arg)
{
int rc = -EIO;
struct msm_stats_buf buf;
unsigned long pphy;
struct msm_vfe_cfg_cmd cfgcmd;
if (copy_from_user(&buf, arg,
sizeof(struct msm_stats_buf))) {
ERR_COPY_FROM_USER();
return -EFAULT;
}
CDBG("%s\n", __func__);
pphy = <API key>(sync, buf.buffer, buf.fd);
if (pphy != 0) {
if (buf.type == STAT_AEAW)
cfgcmd.cmd_type = <API key>;
else if (buf.type == STAT_AF)
cfgcmd.cmd_type = <API key>;
else if (buf.type == STAT_AEC)
cfgcmd.cmd_type = <API key>;
else if (buf.type == STAT_AWB)
cfgcmd.cmd_type = <API key>;
else if (buf.type == STAT_IHIST)
cfgcmd.cmd_type = <API key>;
else if (buf.type == STAT_RS)
cfgcmd.cmd_type = <API key>;
else if (buf.type == STAT_CS)
cfgcmd.cmd_type = <API key>;
else {
pr_err("%s: invalid buf type %d\n",
__func__,
buf.type);
rc = -EINVAL;
goto put_done;
}
cfgcmd.value = (void *)&buf;
if (sync->vfefn.vfe_config) {
rc = sync->vfefn.vfe_config(&cfgcmd, &pphy);
if (rc < 0)
pr_err("%s: vfe_config error %d\n",
__func__, rc);
} else
pr_err("%s: vfe_config is NULL\n", __func__);
} else {
pr_err("%s: NULL physical address\n", __func__);
rc = -EINVAL;
}
put_done:
return rc;
}
static int msm_axi_config(struct msm_sync *sync, void __user *arg)
{
struct msm_vfe_cfg_cmd cfgcmd;
if (copy_from_user(&cfgcmd, arg, sizeof(cfgcmd))) {
ERR_COPY_FROM_USER();
return -EFAULT;
}
switch (cfgcmd.cmd_type) {
case CMD_AXI_CFG_VIDEO:
case CMD_AXI_CFG_PREVIEW:
case CMD_AXI_CFG_SNAP:
case <API key>:
case CMD_AXI_CFG_ZSL:
CDBG("%s, cfgcmd.cmd_type = %d\n", __func__, cfgcmd.cmd_type);
return msm_frame_axi_cfg(sync, &cfgcmd);
case CMD_AXI_CFG_VPE:
case <API key>:
case <API key>:
return msm_vpe_frame_cfg(sync, (void *)&cfgcmd);
case CMD_STATS_AXI_CFG:
case <API key>:
return msm_stats_axi_cfg(sync, &cfgcmd);
default:
pr_err("%s: unknown command type %d\n",
__func__,
cfgcmd.cmd_type);
return -EINVAL;
}
return 0;
}
static int __msm_get_pic(struct msm_sync *sync,
struct msm_frame *frame)
{
int rc = 0;
struct msm_queue_cmd *qcmd = NULL;
struct msm_vfe_resp *vdata;
struct msm_vfe_phy_info *pphy;
struct msm_pmem_info pmem_info;
qcmd = msm_dequeue(&sync->pict_q, list_pict);
if (!qcmd) {
pr_err("%s: no pic frame.\n", __func__);
return -EAGAIN;
}
vdata = (struct msm_vfe_resp *)(qcmd->command);
pphy = &vdata->phy;
rc = <API key>(sync,
pphy->y_phy,
&pmem_info,
1); /* mark pic frame in use */
if (rc < 0) {
pr_err("%s: cannot get pic frame, invalid lookup address y %x"
" cbcr %x\n", __func__, pphy->y_phy, pphy->cbcr_phy);
goto err;
}
frame->ts = qcmd->ts;
frame->buffer = (unsigned long)pmem_info.vaddr;
frame->y_off = pmem_info.y_off;
frame->cbcr_off = pmem_info.cbcr_off;
frame->fd = pmem_info.fd;
if (sync->stereocam_enabled &&
sync->stereo_state != <API key>) {
if (pmem_info.type == <API key>)
frame->path = OUTPUT_TYPE_T;
else
frame->path = OUTPUT_TYPE_S;
} else
frame->path = vdata->phy.output_id;
CDBG("%s: y %x, cbcr %x, qcmd %x, virt_addr %x\n",
__func__,
pphy->y_phy, pphy->cbcr_phy, (int) qcmd, (int) frame->buffer);
err:
free_qcmd(qcmd);
return rc;
}
static int msm_get_pic(struct msm_sync *sync, void __user *arg)
{
int rc = 0;
struct msm_frame frame;
if (copy_from_user(&frame,
arg,
sizeof(struct msm_frame))) {
ERR_COPY_FROM_USER();
return -EFAULT;
}
rc = __msm_get_pic(sync, &frame);
if (rc < 0)
return rc;
if (sync->croplen && (!sync->stereocam_enabled)) {
if (frame.croplen != sync->croplen) {
pr_err("%s: invalid frame croplen %d,"
"expecting %d\n",
__func__,
frame.croplen,
sync->croplen);
return -EINVAL;
}
if (copy_to_user((void *)frame.cropinfo,
sync->cropinfo,
sync->croplen)) {
ERR_COPY_TO_USER();
return -EFAULT;
}
}
CDBG("%s: copy snapshot frame to user\n", __func__);
if (copy_to_user((void *)arg,
&frame, sizeof(struct msm_frame))) {
ERR_COPY_TO_USER();
rc = -EFAULT;
}
CDBG("%s: got pic frame\n", __func__);
return rc;
}
static int msm_set_crop(struct msm_sync *sync, void __user *arg)
{
struct crop_info crop;
mutex_lock(&sync->lock);
if (copy_from_user(&crop,
arg,
sizeof(struct crop_info))) {
ERR_COPY_FROM_USER();
mutex_unlock(&sync->lock);
return -EFAULT;
}
if (crop.len != CROP_LEN) {
mutex_unlock(&sync->lock);
return -EINVAL;
}
if (!sync->croplen) {
sync->cropinfo = kmalloc(crop.len, GFP_KERNEL);
if (!sync->cropinfo) {
mutex_unlock(&sync->lock);
return -ENOMEM;
}
}
if (copy_from_user(sync->cropinfo,
crop.info,
crop.len)) {
ERR_COPY_FROM_USER();
sync->croplen = 0;
kfree(sync->cropinfo);
mutex_unlock(&sync->lock);
return -EFAULT;
}
sync->croplen = crop.len;
mutex_unlock(&sync->lock);
return 0;
}
static int msm_error_config(struct msm_sync *sync, void __user *arg)
{
struct msm_queue_cmd *qcmd =
kmalloc(sizeof(struct msm_queue_cmd), GFP_KERNEL);
if (!qcmd) {
pr_info("%s: kmalloc for qcmd failed.\n", __func__);
return -EFAULT;
}
qcmd->command = NULL;
if (qcmd)
atomic_set(&(qcmd->on_heap), 1);
if (copy_from_user(&(qcmd->error_code), arg, sizeof(uint32_t))) {
ERR_COPY_FROM_USER();
free_qcmd(qcmd);
return -EFAULT;
}
pr_err("%s: Enqueue Fake Frame with error code = %d\n", __func__,
qcmd->error_code);
msm_enqueue(&sync->frame_q, &qcmd->list_frame);
return 0;
}
static int msm_set_fd_roi(struct msm_sync *sync, void __user *arg)
{
struct fd_roi_info fd_roi;
mutex_lock(&sync->lock);
if (copy_from_user(&fd_roi,
arg,
sizeof(struct fd_roi_info))) {
ERR_COPY_FROM_USER();
mutex_unlock(&sync->lock);
return -EFAULT;
}
if (fd_roi.info_len <= 0) {
mutex_unlock(&sync->lock);
return -EFAULT;
}
if (!sync->fdroiinfo.info) {
sync->fdroiinfo.info = kmalloc(fd_roi.info_len, GFP_KERNEL);
if (!sync->fdroiinfo.info) {
mutex_unlock(&sync->lock);
return -ENOMEM;
}
sync->fdroiinfo.info_len = fd_roi.info_len;
} else if (sync->fdroiinfo.info_len < fd_roi.info_len) {
mutex_unlock(&sync->lock);
return -EINVAL;
}
if (copy_from_user(sync->fdroiinfo.info,
fd_roi.info,
fd_roi.info_len)) {
ERR_COPY_FROM_USER();
kfree(sync->fdroiinfo.info);
sync->fdroiinfo.info = NULL;
mutex_unlock(&sync->lock);
return -EFAULT;
}
mutex_unlock(&sync->lock);
return 0;
}
static int msm_pp_grab(struct msm_sync *sync, void __user *arg)
{
uint32_t enable;
if (copy_from_user(&enable, arg, sizeof(enable))) {
ERR_COPY_FROM_USER();
return -EFAULT;
} else {
enable &= PP_MASK;
if (enable & (enable - 1)) {
pr_err("%s: error: more than one PP request!\n",
__func__);
return -EINVAL;
}
if (sync->pp_mask) {
if (enable) {
pr_err("%s: postproc %x is already enabled\n",
__func__, sync->pp_mask & enable);
return -EINVAL;
} else {
sync->pp_mask &= enable;
CDBG("%s: sync->pp_mask %d enable %d\n",
__func__, sync->pp_mask, enable);
return 0;
}
}
CDBG("%s: sync->pp_mask %d enable %d\n", __func__,
sync->pp_mask, enable);
sync->pp_mask |= enable;
}
return 0;
}
static int msm_put_st_frame(struct msm_sync *sync, void __user *arg)
{
unsigned long flags;
unsigned long st_pphy;
if (sync->stereocam_enabled) {
/* Make stereo frame ready for VPE. */
struct msm_st_frame stereo_frame_half;
if (copy_from_user(&stereo_frame_half, arg,
sizeof(stereo_frame_half))) {
ERR_COPY_FROM_USER();
return -EFAULT;
}
if (stereo_frame_half.type == OUTPUT_TYPE_ST_L) {
struct msm_vfe_resp *vfe_rp;
struct msm_queue_cmd *qcmd;
spin_lock_irqsave(&<API key>, flags);
if (!sync->pp_stereocam) {
pr_warning("%s: no stereo frame to deliver!\n",
__func__);
<API key>(&<API key>,
flags);
return -EINVAL;
}
CDBG("%s: delivering left frame to VPE\n", __func__);
qcmd = sync->pp_stereocam;
sync->pp_stereocam = NULL;
<API key>(&<API key>, flags);
vfe_rp = (struct msm_vfe_resp *)qcmd->command;
CDBG("%s: Left Py = 0x%x y_off = %d cbcr_off = %d\n",
__func__, vfe_rp->phy.y_phy,
stereo_frame_half.L.buf_y_off,
stereo_frame_half.L.buf_cbcr_off);
sync->vpefn.vpe_cfg_offset(stereo_frame_half.packing,
vfe_rp->phy.y_phy + stereo_frame_half.L.buf_y_off,
vfe_rp->phy.y_phy + stereo_frame_half.L.buf_cbcr_off,
&(qcmd->ts), OUTPUT_TYPE_ST_L, stereo_frame_half.L,
stereo_frame_half.frame_id);
free_qcmd(qcmd);
} else if (stereo_frame_half.type == OUTPUT_TYPE_ST_R) {
CDBG("%s: delivering right frame to VPE\n", __func__);
spin_lock_irqsave(&st_frame_spinlock, flags);
sync->stcam_conv_value =
stereo_frame_half.buf_info.stcam_conv_value;
sync->stcam_quality_ind =
stereo_frame_half.buf_info.stcam_quality_ind;
st_pphy = <API key>(sync,
stereo_frame_half.buf_info.buffer,
stereo_frame_half.buf_info.y_off,
stereo_frame_half.buf_info.cbcr_off,
stereo_frame_half.buf_info.fd,
0); /* Do not change the active flag. */
sync->vpefn.vpe_cfg_offset(stereo_frame_half.packing,
st_pphy + stereo_frame_half.R.buf_y_off,
st_pphy + stereo_frame_half.R.buf_cbcr_off,
NULL, OUTPUT_TYPE_ST_R, stereo_frame_half.R,
stereo_frame_half.frame_id);
<API key>(&st_frame_spinlock, flags);
} else {
pr_info("%s: Invalid Msg\n", __func__);
}
}
return 0;
}
static int msm_pp_release(struct msm_sync *sync, void __user *arg)
{
unsigned long flags;
if (!sync->pp_mask) {
pr_warning("%s: pp not in progress for\n", __func__);
return -EINVAL;
}
if (sync->pp_mask & PP_PREV) {
spin_lock_irqsave(&pp_prev_spinlock, flags);
if (!sync->pp_prev) {
pr_err("%s: no preview frame to deliver!\n",
__func__);
<API key>(&pp_prev_spinlock,
flags);
return -EINVAL;
}
CDBG("%s: delivering pp_prev\n", __func__);
if (sync->frame_q.len <= 100 &&
sync->event_q.len <= 100) {
msm_enqueue(&sync->frame_q,
&sync->pp_prev->list_frame);
} else {
pr_err("%s, Error Queue limit exceeded f_q=%d,\
e_q = %d\n",
__func__, sync->frame_q.len,
sync->event_q.len);
free_qcmd(sync->pp_prev);
goto done;
}
sync->pp_prev = NULL;
<API key>(&pp_prev_spinlock, flags);
goto done;
}
if ((sync->pp_mask & PP_SNAP) ||
(sync->pp_mask & PP_RAW_SNAP)) {
spin_lock_irqsave(&pp_snap_spinlock, flags);
if (!sync->pp_snap) {
pr_err("%s: no snapshot to deliver!\n", __func__);
<API key>(&pp_snap_spinlock, flags);
return -EINVAL;
}
CDBG("%s: delivering pp_snap\n", __func__);
msm_enqueue(&sync->pict_q, &sync->pp_snap->list_pict);
msm_enqueue(&sync->pict_q, &sync->pp_thumb->list_pict);
sync->pp_snap = NULL;
sync->pp_thumb = NULL;
<API key>(&pp_snap_spinlock, flags);
}
done:
return 0;
}
static long msm_ioctl_common(struct msm_cam_device *pmsm,
unsigned int cmd,
void __user *argp)
{
switch (cmd) {
case <API key>:
CDBG("%s cmd = <API key>\n", __func__);
return msm_register_pmem(pmsm->sync, argp);
case <API key>:
CDBG("%s cmd = <API key>\n", __func__);
return msm_pmem_table_del(pmsm->sync, argp);
case <API key>:
CDBG("%s cmd = <API key>\n", __func__);
return <API key>(pmsm->sync, argp);
break;
default:
CDBG("%s cmd invalid\n", __func__);
return -EINVAL;
}
}
static long msm_ioctl_config(struct file *filep, unsigned int cmd,
unsigned long arg)
{
int rc = -EINVAL;
void __user *argp = (void __user *)arg;
struct msm_cam_device *pmsm = filep->private_data;
CDBG("%s: cmd %d\n", __func__, _IOC_NR(cmd));
switch (cmd) {
case <API key>:
rc = msm_get_sensor_info(pmsm->sync, argp);
break;
case <API key>:
/* Coming from config thread for update */
rc = msm_config_vfe(pmsm->sync, argp);
break;
case <API key>:
/* Coming from config thread for update */
rc = msm_config_vpe(pmsm->sync, argp);
break;
case <API key>:
/* Coming from config thread wait
* for vfe statistics and control requests */
rc = msm_get_stats(pmsm->sync, argp);
break;
case <API key>:
/* This request comes from control thread:
* enable either QCAMTASK or VFETASK */
rc = msm_enable_vfe(pmsm->sync, argp);
break;
case <API key>:
/* This request comes from control thread:
* disable either QCAMTASK or VFETASK */
rc = msm_disable_vfe(pmsm->sync, argp);
break;
case <API key>:
<API key>();
rc = 0;
break;
case <API key>:
rc = <API key>(pmsm->sync, argp);
break;
case <API key>:
case <API key>:
rc = msm_axi_config(pmsm->sync, argp);
break;
case <API key>:
rc = msm_set_crop(pmsm->sync, argp);
break;
case <API key>:
rc = msm_set_fd_roi(pmsm->sync, argp);
break;
case <API key>:
/* Grab one preview frame or one snapshot
* frame.
*/
rc = msm_pp_grab(pmsm->sync, argp);
break;
case <API key>:
/* Release the preview of snapshot frame
* that was grabbed.
*/
rc = msm_pp_release(pmsm->sync, argp);
break;
case <API key>:
/* Release the left or right frame
* that was sent for stereo processing.
*/
rc = msm_put_st_frame(pmsm->sync, argp);
break;
case <API key>:
rc = pmsm->sync->sctrl.s_config(argp);
break;
case <API key>: {
uint32_t led_state;
if (copy_from_user(&led_state, argp, sizeof(led_state))) {
ERR_COPY_FROM_USER();
rc = -EFAULT;
} else
rc = <API key>(pmsm->sync->
sdata->flash_data, led_state);
break;
}
case <API key>: {
uint32_t flash_type;
if (copy_from_user(&flash_type, argp, sizeof(flash_type))) {
pr_err("<API key> failed");
ERR_COPY_FROM_USER();
rc = -EFAULT;
} else {
CDBG("<API key> enter");
rc = <API key>(pmsm->sync, flash_type);
}
break;
}
case <API key>:
if (pmsm->sync->sdata->strobe_flash_data) {
rc = pmsm->sync->sfctrl.<API key>(
pmsm->sync->sdata->strobe_flash_data, 0);
}
break;
case <API key>: {
uint32_t charge_en;
if (copy_from_user(&charge_en, argp, sizeof(charge_en))) {
ERR_COPY_FROM_USER();
rc = -EFAULT;
} else
rc = pmsm->sync->sfctrl.strobe_flash_charge(
pmsm->sync->sdata->strobe_flash_data->flash_charge,
charge_en, pmsm->sync->sdata->strobe_flash_data->
<API key>);
break;
}
case <API key>: {
struct flash_ctrl_data flash_info;
if (copy_from_user(&flash_info, argp, sizeof(flash_info))) {
ERR_COPY_FROM_USER();
rc = -EFAULT;
} else
rc = msm_flash_ctrl(pmsm->sync->sdata, &flash_info);
break;
}
case <API key>:
rc = msm_error_config(pmsm->sync, argp);
break;
case <API key>: {
unsigned long flags = 0;
CDBG("get_pic:<API key>\n");
spin_lock_irqsave(&pmsm->sync->abort_pict_lock, flags);
pmsm->sync->get_pic_abort = 1;
<API key>(&pmsm->sync->abort_pict_lock, flags);
wake_up(&(pmsm->sync->pict_q.wait));
rc = 0;
break;
}
default:
rc = msm_ioctl_common(pmsm, cmd, argp);
break;
}
CDBG("%s: cmd %d DONE\n", __func__, _IOC_NR(cmd));
return rc;
}
static int <API key>(struct msm_sync *);
static long msm_ioctl_frame(struct file *filep, unsigned int cmd,
unsigned long arg)
{
int rc = -EINVAL;
void __user *argp = (void __user *)arg;
struct msm_cam_device *pmsm = filep->private_data;
switch (cmd) {
case <API key>:
/* Coming from frame thread to get frame
* after SELECT is done */
rc = msm_get_frame(pmsm->sync, argp);
break;
case <API key>:
rc = <API key>(pmsm->sync, argp);
break;
case <API key>:
rc = <API key>(pmsm->sync);
break;
default:
break;
}
return rc;
}
static int <API key>(struct msm_sync *sync);
static long msm_ioctl_pic(struct file *filep, unsigned int cmd,
unsigned long arg)
{
int rc = -EINVAL;
void __user *argp = (void __user *)arg;
struct msm_cam_device *pmsm = filep->private_data;
switch (cmd) {
case <API key>:
rc = msm_get_pic(pmsm->sync, argp);
break;
case <API key>:
rc = msm_put_pic_buffer(pmsm->sync, argp);
break;
case <API key>:
rc = <API key>(pmsm->sync);
break;
default:
break;
}
return rc;
}
static long msm_ioctl_control(struct file *filep, unsigned int cmd,
unsigned long arg)
{
int rc = -EINVAL;
void __user *argp = (void __user *)arg;
struct msm_control_device *ctrl_pmsm = filep->private_data;
struct msm_cam_device *pmsm = ctrl_pmsm->pmsm;
switch (cmd) {
case <API key>:
/* Coming from control thread, may need to wait for
* command status */
CDBG("calling msm_control kernel msm_ioctl_control\n");
mutex_lock(&ctrl_cmd_lock);
rc = msm_control(ctrl_pmsm, 1, argp);
mutex_unlock(&ctrl_cmd_lock);
break;
case <API key>:
/* Sends a message, returns immediately */
rc = msm_control(ctrl_pmsm, 0, argp);
break;
case <API key>:
/* Config thread calls the control thread to notify it
* of the result of a <API key>.
*/
rc = msm_ctrl_cmd_done(ctrl_pmsm, argp);
break;
case <API key>:
rc = msm_get_sensor_info(pmsm->sync, argp);
break;
case <API key>:
rc = msm_get_camera_info(argp);
break;
default:
rc = msm_ioctl_common(pmsm, cmd, argp);
break;
}
return rc;
}
static int __msm_release(struct msm_sync *sync)
{
struct msm_pmem_region *region;
struct hlist_node *hnode;
struct hlist_node *n;
mutex_lock(&sync->lock);
if (sync->opencnt)
sync->opencnt
pr_info("%s, open count =%d\n", __func__, sync->opencnt);
if (!sync->opencnt) {
/* need to clean up system resource */
pr_info("%s, release VFE\n", __func__);
if (sync->core_powered_on) {
if (sync->vfefn.vfe_release)
sync->vfefn.vfe_release(sync->pdev);
/*sensor release */
pr_info("%s, release Sensor\n", __func__);
sync->sctrl.s_release();
CDBG("%s, <API key>\n", __func__);
<API key>(sync->pdev);
if (sync->sfctrl.<API key>) {
CDBG("%s, <API key>\n", __func__);
sync->sfctrl.<API key>(
sync->sdata->strobe_flash_data, 1);
}
}
kfree(sync->cropinfo);
sync->cropinfo = NULL;
sync->croplen = 0;
/*re-init flag*/
sync->ignore_qcmd = false;
sync->ignore_qcmd_type = -1;
sync->qcmd_done = false;
CDBG("%s, free frame pmem region\n", __func__);
<API key>(region, hnode, n,
&sync->pmem_frames, list) {
hlist_del(hnode);
put_pmem_file(region->file);
kfree(region);
}
CDBG("%s, free stats pmem region\n", __func__);
<API key>(region, hnode, n,
&sync->pmem_stats, list) {
hlist_del(hnode);
put_pmem_file(region->file);
kfree(region);
}
msm_queue_drain(&sync->pict_q, list_pict);
wake_unlock(&sync->wake_lock);
sync->apps_id = NULL;
sync->core_powered_on = 0;
}
mutex_unlock(&sync->lock);
return 0;
}
static int msm_release_config(struct inode *node, struct file *filep)
{
int rc;
struct msm_cam_device *pmsm = filep->private_data;
pr_info("%s: %s\n", __func__, filep->f_path.dentry->d_name.name);
rc = __msm_release(pmsm->sync);
if (!rc) {
msm_queue_drain(&pmsm->sync->event_q, list_config);
atomic_set(&pmsm->opened, 0);
}
return rc;
}
static int msm_release_control(struct inode *node, struct file *filep)
{
int rc;
struct msm_control_device *ctrl_pmsm = filep->private_data;
struct msm_cam_device *pmsm = ctrl_pmsm->pmsm;
pr_info("%s: %s\n", __func__, filep->f_path.dentry->d_name.name);
g_v4l2_opencnt
mutex_lock(&pmsm->sync->lock);
if (pmsm->sync->core_powered_on && pmsm->sync->vfefn.vfe_stop) {
pr_info("%s, stop vfe if active\n", __func__);
pmsm->sync->vfefn.vfe_stop();
}
mutex_unlock(&pmsm->sync->lock);
rc = __msm_release(pmsm->sync);
if (!rc) {
msm_queue_drain(&ctrl_pmsm->ctrl_q, list_control);
kfree(ctrl_pmsm);
}
return rc;
}
static int msm_release_frame(struct inode *node, struct file *filep)
{
int rc;
struct msm_cam_device *pmsm = filep->private_data;
pr_info("%s: %s\n", __func__, filep->f_path.dentry->d_name.name);
rc = __msm_release(pmsm->sync);
if (!rc) {
msm_queue_drain(&pmsm->sync->frame_q, list_frame);
atomic_set(&pmsm->opened, 0);
}
return rc;
}
static int msm_release_pic(struct inode *node, struct file *filep)
{
int rc;
struct msm_cam_device *pmsm = filep->private_data;
CDBG("%s: %s\n", __func__, filep->f_path.dentry->d_name.name);
rc = __msm_release(pmsm->sync);
if (!rc) {
msm_queue_drain(&pmsm->sync->pict_q, list_pict);
atomic_set(&pmsm->opened, 0);
}
return rc;
}
static int <API key>(struct msm_sync *sync)
{
unsigned long flags;
CDBG("%s\n", __func__);
spin_lock_irqsave(&sync->pict_q.lock, flags);
sync-><API key> = 1;
wake_up(&sync->pict_q.wait);
<API key>(&sync->pict_q.lock, flags);
return 0;
}
static int <API key>(struct msm_sync *sync)
{
unsigned long flags;
CDBG("%s\n", __func__);
spin_lock_irqsave(&sync->frame_q.lock, flags);
sync->unblock_poll_frame = 1;
wake_up(&sync->frame_q.wait);
<API key>(&sync->frame_q.lock, flags);
return 0;
}
static unsigned int __msm_poll_frame(struct msm_sync *sync,
struct file *filep,
struct poll_table_struct *pll_table)
{
int rc = 0;
unsigned long flags;
poll_wait(filep, &sync->frame_q.wait, pll_table);
spin_lock_irqsave(&sync->frame_q.lock, flags);
if (!list_empty_careful(&sync->frame_q.list))
/* frame ready */
rc = POLLIN | POLLRDNORM;
if (sync->unblock_poll_frame) {
CDBG("%s: sync->unblock_poll_frame is true\n", __func__);
rc |= POLLPRI;
sync->unblock_poll_frame = 0;
}
<API key>(&sync->frame_q.lock, flags);
return rc;
}
static unsigned int __msm_poll_pic(struct msm_sync *sync,
struct file *filep,
struct poll_table_struct *pll_table)
{
int rc = 0;
unsigned long flags;
poll_wait(filep, &sync->pict_q.wait , pll_table);
spin_lock_irqsave(&sync->abort_pict_lock, flags);
if (sync->get_pic_abort == 1) {
/* TODO: need to pass an error case */
sync->get_pic_abort = 0;
}
<API key>(&sync->abort_pict_lock, flags);
spin_lock_irqsave(&sync->pict_q.lock, flags);
if (!list_empty_careful(&sync->pict_q.list))
/* frame ready */
rc = POLLIN | POLLRDNORM;
if (sync-><API key>) {
CDBG("%s: sync-><API key> is true\n", __func__);
rc |= POLLPRI;
sync-><API key> = 0;
}
<API key>(&sync->pict_q.lock, flags);
return rc;
}
static unsigned int msm_poll_frame(struct file *filep,
struct poll_table_struct *pll_table)
{
struct msm_cam_device *pmsm = filep->private_data;
return __msm_poll_frame(pmsm->sync, filep, pll_table);
}
static unsigned int msm_poll_pic(struct file *filep,
struct poll_table_struct *pll_table)
{
struct msm_cam_device *pmsm = filep->private_data;
return __msm_poll_pic(pmsm->sync, filep, pll_table);
}
static unsigned int __msm_poll_config(struct msm_sync *sync,
struct file *filep,
struct poll_table_struct *pll_table)
{
int rc = 0;
unsigned long flags;
poll_wait(filep, &sync->event_q.wait, pll_table);
spin_lock_irqsave(&sync->event_q.lock, flags);
if (!list_empty_careful(&sync->event_q.list))
/* event ready */
rc = POLLIN | POLLRDNORM;
<API key>(&sync->event_q.lock, flags);
return rc;
}
static unsigned int msm_poll_config(struct file *filep,
struct poll_table_struct *pll_table)
{
struct msm_cam_device *pmsm = filep->private_data;
return __msm_poll_config(pmsm->sync, filep, pll_table);
}
/*
* This function executes in interrupt context.
*/
static void *msm_vfe_sync_alloc(int size,
void *syncdata __attribute__((unused)),
gfp_t gfp)
{
struct msm_queue_cmd *qcmd =
kmalloc(sizeof(struct msm_queue_cmd) + size, gfp);
if (qcmd) {
atomic_set(&qcmd->on_heap, 1);
return qcmd + 1;
}
return NULL;
}
static void *msm_vpe_sync_alloc(int size,
void *syncdata __attribute__((unused)),
gfp_t gfp)
{
struct msm_queue_cmd *qcmd =
kzalloc(sizeof(struct msm_queue_cmd) + size, gfp);
if (qcmd) {
atomic_set(&qcmd->on_heap, 1);
return qcmd + 1;
}
return NULL;
}
static void msm_vfe_sync_free(void *ptr)
{
if (ptr) {
struct msm_queue_cmd *qcmd =
(struct msm_queue_cmd *)ptr;
qcmd
if (atomic_read(&qcmd->on_heap))
kfree(qcmd);
}
}
static void msm_vpe_sync_free(void *ptr)
{
if (ptr) {
struct msm_queue_cmd *qcmd =
(struct msm_queue_cmd *)ptr;
qcmd
if (atomic_read(&qcmd->on_heap))
kfree(qcmd);
}
}
/*
* This function executes in interrupt context.
*/
static void msm_vfe_sync(struct msm_vfe_resp *vdata,
enum msm_queue qtype, void *syncdata,
gfp_t gfp)
{
struct msm_queue_cmd *qcmd = NULL;
struct msm_sync *sync = (struct msm_sync *)syncdata;
unsigned long flags;
if (!sync) {
pr_err("%s: no context in dsp callback.\n", __func__);
return;
}
qcmd = ((struct msm_queue_cmd *)vdata) - 1;
qcmd->type = qtype;
qcmd->command = vdata;
ktime_get_ts(&(qcmd->ts));
if (qtype != MSM_CAM_Q_VFE_MSG)
goto vfe_for_config;
CDBG("%s: vdata->type %d\n", __func__, vdata->type);
switch (vdata->type) {
case VFE_MSG_OUTPUT_P:
if (sync->pp_mask & PP_PREV) {
CDBG("%s: PP_PREV in progress: phy_y %x phy_cbcr %x\n",
__func__,
vdata->phy.y_phy,
vdata->phy.cbcr_phy);
spin_lock_irqsave(&pp_prev_spinlock, flags);
if (sync->pp_prev)
CDBG("%s: overwriting pp_prev!\n",
__func__);
CDBG("%s: sending preview to config\n", __func__);
sync->pp_prev = qcmd;
<API key>(&pp_prev_spinlock, flags);
sync->pp_frame_avail = 1;
if (atomic_read(&qcmd->on_heap))
atomic_add(1, &qcmd->on_heap);
break;
}
CDBG("%s: msm_enqueue frame_q\n", __func__);
if (sync->stereocam_enabled)
CDBG("%s: Enqueue VFE_MSG_OUTPUT_P to event_q for "
"stereo processing\n", __func__);
else {
if (sync->frame_q.len <= 100 &&
sync->event_q.len <= 100) {
if (atomic_read(&qcmd->on_heap))
atomic_add(1, &qcmd->on_heap);
msm_enqueue(&sync->frame_q, &qcmd->list_frame);
} else {
pr_err("%s, Error Queue limit exceeded "
"f_q = %d, e_q = %d\n", __func__,
sync->frame_q.len, sync->event_q.len);
free_qcmd(qcmd);
return;
}
}
break;
case VFE_MSG_OUTPUT_T:
if (sync->stereocam_enabled) {
spin_lock_irqsave(&<API key>, flags);
/* if out1/2 is currently in progress, save the qcmd
and issue only ionce the 1st one completes the 3D
pipeline */
if (<API key> ==
sync->stereo_state) {
sync->pp_stereocam2 = qcmd;
<API key>(&<API key>,
flags);
if (atomic_read(&qcmd->on_heap))
atomic_add(1, &qcmd->on_heap);
pr_err("%s: snapshot stereo in progress\n",
__func__);
return;
}
if (sync->pp_stereocam)
CDBG("%s: overwriting pp_stereocam!\n",
__func__);
pr_err("%s: sending stereo frame to config\n", __func__);
sync->pp_stereocam = qcmd;
sync->stereo_state =
<API key>;
<API key>(&<API key>, flags);
/* Increament on_heap by one because the same qcmd will
be used for VPE in msm_pp_release. */
if (atomic_read(&qcmd->on_heap))
atomic_add(1, &qcmd->on_heap);
pr_err("%s: Enqueue VFE_MSG_OUTPUT_T to event_q for "
"stereo processing.\n", __func__);
break;
}
if (sync->pp_mask & PP_SNAP) {
spin_lock_irqsave(&pp_thumb_spinlock, flags);
sync->thumb_count
if (!sync->pp_thumb && (0 >= sync->thumb_count)) {
CDBG("%s: pp sending thumbnail to config\n",
__func__);
sync->pp_thumb = qcmd;
<API key>(&pp_thumb_spinlock,
flags);
if (atomic_read(&qcmd->on_heap))
atomic_add(1, &qcmd->on_heap);
} else {
<API key>(&pp_thumb_spinlock,
flags);
}
break;
} else {
msm_enqueue(&sync->pict_q, &qcmd->list_pict);
return;
}
case VFE_MSG_OUTPUT_S:
if (sync->stereocam_enabled &&
sync->stereo_state != <API key>) {
spin_lock_irqsave(&<API key>, flags);
/* if out1/2 is currently in progress, save the qcmd
and issue only once the 1st one completes the 3D
pipeline */
if (<API key> ==
sync->stereo_state) {
sync->pp_stereocam2 = qcmd;
<API key>(&<API key>,
flags);
if (atomic_read(&qcmd->on_heap))
atomic_add(1, &qcmd->on_heap);
pr_err("%s: snapshot stereo in progress\n",
__func__);
return;
}
if (sync->pp_stereocam)
CDBG("%s: overwriting pp_stereocam!\n",
__func__);
pr_err("%s: sending stereo frame to config\n", __func__);
sync->pp_stereocam = qcmd;
sync->stereo_state =
<API key>;
<API key>(&<API key>, flags);
/* Increament on_heap by one because the same qcmd will
be used for VPE in msm_pp_release. */
if (atomic_read(&qcmd->on_heap))
atomic_add(1, &qcmd->on_heap);
pr_err("%s: Enqueue VFE_MSG_OUTPUT_S to event_q for "
"stereo processing.\n", __func__);
break;
}
if (sync->pp_mask & PP_SNAP) {
spin_lock_irqsave(&pp_snap_spinlock, flags);
sync->snap_count
if (!sync->pp_snap && (0 >= sync->snap_count)) {
CDBG("%s: pp sending main image to config\n",
__func__);
sync->pp_snap = qcmd;
<API key>(&pp_snap_spinlock,
flags);
if (atomic_read(&qcmd->on_heap))
atomic_add(1, &qcmd->on_heap);
} else {
<API key>(&pp_snap_spinlock,
flags);
}
break;
} else {
CDBG("%s: enqueue to picture queue\n", __func__);
msm_enqueue(&sync->pict_q, &qcmd->list_pict);
return;
}
break;
case VFE_MSG_OUTPUT_V:
if (sync->stereocam_enabled) {
spin_lock_irqsave(&<API key>, flags);
if (sync->pp_stereocam)
CDBG("%s: overwriting pp_stereocam!\n",
__func__);
CDBG("%s: sending stereo frame to config\n", __func__);
sync->pp_stereocam = qcmd;
<API key>(&<API key>, flags);
/* Increament on_heap by one because the same qcmd will
be used for VPE in msm_pp_release. */
if (atomic_read(&qcmd->on_heap))
atomic_add(1, &qcmd->on_heap);
CDBG("%s: Enqueue VFE_MSG_OUTPUT_V to event_q for "
"stereo processing.\n", __func__);
break;
}
if (sync->vpefn.vpe_cfg_update) {
CDBG("dis_en = %d\n", *sync->vpefn.dis);
if (*(sync->vpefn.dis)) {
memset(&(vdata->vpe_bf), 0,
sizeof(vdata->vpe_bf));
if (sync->cropinfo != NULL)
vdata->vpe_bf.vpe_crop =
*(struct video_crop_t *)(sync->cropinfo);
vdata->vpe_bf.y_phy = vdata->phy.y_phy;
vdata->vpe_bf.cbcr_phy = vdata->phy.cbcr_phy;
vdata->vpe_bf.ts = (qcmd->ts);
vdata->vpe_bf.frame_id = vdata->phy.frame_id;
qcmd->command = vdata;
msm_enqueue_vpe(&sync->vpe_q,
&qcmd->list_vpe_frame);
return;
} else if (sync->vpefn.vpe_cfg_update(sync->cropinfo)) {
CDBG("%s: msm_enqueue video frame to vpe time "
"= %ld\n", __func__, qcmd->ts.tv_nsec);
sync->vpefn.send_frame_to_vpe(
vdata->phy.y_phy,
vdata->phy.cbcr_phy,
&(qcmd->ts), OUTPUT_TYPE_V);
free_qcmd(qcmd);
return;
} else {
CDBG("%s: msm_enqueue video frame_q\n",
__func__);
if (sync->liveshot_enabled) {
CDBG("%s: msm_enqueue liveshot\n",
__func__);
vdata->phy.output_id |= OUTPUT_TYPE_L;
sync->liveshot_enabled = false;
}
if (sync->frame_q.len <= 100 &&
sync->event_q.len <= 100) {
msm_enqueue(&sync->frame_q,
&qcmd->list_frame);
} else {
pr_err("%s, Error Queue limit exceeded\
f_q = %d, e_q = %d\n",
__func__, sync->frame_q.len,
sync->event_q.len);
free_qcmd(qcmd);
}
return;
}
} else {
CDBG("%s: msm_enqueue video frame_q\n", __func__);
if (sync->frame_q.len <= 100 &&
sync->event_q.len <= 100) {
msm_enqueue(&sync->frame_q, &qcmd->list_frame);
} else {
pr_err("%s, Error Queue limit exceeded\
f_q = %d, e_q = %d\n",
__func__, sync->frame_q.len,
sync->event_q.len);
free_qcmd(qcmd);
}
return;
}
case VFE_MSG_SNAPSHOT:
if (sync->pp_mask & (PP_SNAP | PP_RAW_SNAP)) {
CDBG("%s: PP_SNAP in progress: pp_mask %x\n",
__func__, sync->pp_mask);
spin_lock_irqsave(&pp_snap_spinlock, flags);
if (sync->pp_snap)
pr_warning("%s: overwriting pp_snap!\n",
__func__);
CDBG("%s: sending snapshot to config\n",
__func__);
<API key>(&pp_snap_spinlock, flags);
} else {
if (atomic_read(&qcmd->on_heap))
atomic_add(1, &qcmd->on_heap);
CDBG("%s: VFE_MSG_SNAPSHOT store\n",
__func__);
if (sync->stereocam_enabled &&
sync->stereo_state != <API key>) {
sync->pp_stereosnap = qcmd;
return;
}
}
break;
case VFE_MSG_STATS_AWB:
CDBG("%s: qtype %d, AWB stats, enqueue event_q.\n",
__func__, vdata->type);
break;
case VFE_MSG_STATS_AEC:
CDBG("%s: qtype %d, AEC stats, enqueue event_q.\n",
__func__, vdata->type);
break;
case VFE_MSG_STATS_IHIST:
CDBG("%s: qtype %d, ihist stats, enqueue event_q.\n",
__func__, vdata->type);
break;
case VFE_MSG_STATS_RS:
CDBG("%s: qtype %d, rs stats, enqueue event_q.\n",
__func__, vdata->type);
break;
case VFE_MSG_STATS_CS:
CDBG("%s: qtype %d, cs stats, enqueue event_q.\n",
__func__, vdata->type);
break;
case VFE_MSG_GENERAL:
CDBG("%s: qtype %d, general msg, enqueue event_q.\n",
__func__, vdata->type);
break;
default:
CDBG("%s: qtype %d not handled\n", __func__, vdata->type);
/* fall through, send to config. */
}
vfe_for_config:
CDBG("%s: msm_enqueue event_q\n", __func__);
if (sync->frame_q.len <= 100 && sync->event_q.len <= 100) {
msm_enqueue(&sync->event_q, &qcmd->list_config);
} else {
pr_err("%s, Error Queue limit exceeded f_q = %d, e_q = %d\n",
__func__, sync->frame_q.len, sync->event_q.len);
free_qcmd(qcmd);
}
}
static void msm_vpe_sync(struct msm_vpe_resp *vdata,
enum msm_queue qtype, void *syncdata, void *ts, gfp_t gfp)
{
struct msm_queue_cmd *qcmd = NULL;
unsigned long flags;
struct msm_sync *sync = (struct msm_sync *)syncdata;
if (!sync) {
pr_err("%s: no context in dsp callback.\n", __func__);
return;
}
qcmd = ((struct msm_queue_cmd *)vdata) - 1;
qcmd->type = qtype;
qcmd->command = vdata;
qcmd->ts = *((struct timespec *)ts);
if (qtype != MSM_CAM_Q_VPE_MSG) {
pr_err("%s: Invalid qcmd type = %d.\n", __func__, qcmd->type);
free_qcmd(qcmd);
return;
}
CDBG("%s: vdata->type %d\n", __func__, vdata->type);
switch (vdata->type) {
case VPE_MSG_OUTPUT_V:
if (sync->liveshot_enabled) {
CDBG("%s: msm_enqueue liveshot %d\n", __func__,
sync->liveshot_enabled);
vdata->phy.output_id |= OUTPUT_TYPE_L;
sync->liveshot_enabled = false;
}
if (sync->frame_q.len <= 100 && sync->event_q.len <= 100) {
CDBG("%s: enqueue to frame_q from VPE\n", __func__);
msm_enqueue(&sync->frame_q, &qcmd->list_frame);
} else {
pr_err("%s, Error Queue limit exceeded f_q = %d, "
"e_q = %d\n", __func__, sync->frame_q.len,
sync->event_q.len);
free_qcmd(qcmd);
}
return;
case VPE_MSG_OUTPUT_ST_L:
CDBG("%s: enqueue left frame done msg to event_q from VPE\n",
__func__);
msm_enqueue(&sync->event_q, &qcmd->list_config);
return;
case VPE_MSG_OUTPUT_ST_R:
spin_lock_irqsave(&<API key>, flags);
CDBG("%s: received VPE_MSG_OUTPUT_ST_R state %d\n", __func__,
sync->stereo_state);
if (<API key> == sync->stereo_state) {
msm_enqueue(&sync->pict_q, &qcmd->list_pict);
qcmd = sync->pp_stereocam2;
sync->pp_stereocam = sync->pp_stereocam2;
sync->pp_stereocam2 = NULL;
msm_enqueue(&sync->event_q, &qcmd->list_config);
sync->stereo_state =
<API key>;
} else if (<API key> ==
sync->stereo_state) {
sync->stereo_state = STEREO_SNAP_IDLE;
/* Send snapshot DONE */
msm_enqueue(&sync->pict_q, &qcmd->list_pict);
qcmd = sync->pp_stereosnap;
sync->pp_stereosnap = NULL;
CDBG("%s: send SNAPSHOT_DONE message\n", __func__);
msm_enqueue(&sync->event_q, &qcmd->list_config);
} else {
if (atomic_read(&qcmd->on_heap))
atomic_add(1, &qcmd->on_heap);
msm_enqueue(&sync->event_q, &qcmd->list_config);
if (sync->stereo_state == STEREO_VIDEO_ACTIVE) {
CDBG("%s: st frame to frame_q from VPE\n",
__func__);
msm_enqueue(&sync->frame_q, &qcmd->list_frame);
}
}
<API key>(&<API key>, flags);
return;
default:
pr_err("%s: qtype %d not handled\n", __func__, vdata->type);
}
pr_err("%s: Should not come here. Error.\n", __func__);
}
static struct msm_vpe_callback msm_vpe_s = {
.vpe_resp = msm_vpe_sync,
.vpe_alloc = msm_vpe_sync_alloc,
.vpe_free = msm_vpe_sync_free,
};
static struct msm_vfe_callback msm_vfe_s = {
.vfe_resp = msm_vfe_sync,
.vfe_alloc = msm_vfe_sync_alloc,
.vfe_free = msm_vfe_sync_free,
};
static int __msm_open(struct msm_sync *sync, const char *const apps_id,
int is_controlnode)
{
int rc = 0;
mutex_lock(&sync->lock);
if (sync->apps_id && strcmp(sync->apps_id, apps_id)
&& (!strcmp(MSM_APPS_ID_V4L2, apps_id))) {
pr_err("%s(%s): sensor %s is already opened for %s\n",
__func__,
apps_id,
sync->sdata->sensor_name,
sync->apps_id);
rc = -EBUSY;
goto msm_open_done;
}
sync->apps_id = apps_id;
if (!sync->core_powered_on && !is_controlnode) {
wake_lock(&sync->wake_lock);
msm_camvfe_fn_init(&sync->vfefn, sync);
if (sync->vfefn.vfe_init) {
sync->pp_frame_avail = 0;
sync->get_pic_abort = 0;
rc = <API key>(sync->pdev);
if (rc < 0) {
pr_err("%s: setting sensor clocks failed: %d\n",
__func__, rc);
goto msm_open_done;
}
rc = sync->sctrl.s_init(sync->sdata);
if (rc < 0) {
pr_err("%s: sensor init failed: %d\n",
__func__, rc);
goto msm_open_done;
}
rc = sync->vfefn.vfe_init(&msm_vfe_s,
sync->pdev);
if (rc < 0) {
pr_err("%s: vfe_init failed at %d\n",
__func__, rc);
goto msm_open_done;
}
} else {
pr_err("%s: no sensor init func\n", __func__);
rc = -ENODEV;
goto msm_open_done;
}
msm_camvpe_fn_init(&sync->vpefn, sync);
spin_lock_init(&sync->abort_pict_lock);
if (rc >= 0) {
msm_region_init(sync);
if (sync->vpefn.vpe_reg)
sync->vpefn.vpe_reg(&msm_vpe_s);
sync->unblock_poll_frame = 0;
sync-><API key> = 0;
}
sync->core_powered_on = 1;
}
sync->opencnt++;
msm_open_done:
mutex_unlock(&sync->lock);
return rc;
}
static int msm_open_common(struct inode *inode, struct file *filep,
int once, int is_controlnode)
{
int rc;
struct msm_cam_device *pmsm =
container_of(inode->i_cdev, struct msm_cam_device, cdev);
CDBG("%s: open %s\n", __func__, filep->f_path.dentry->d_name.name);
if (atomic_cmpxchg(&pmsm->opened, 0, 1) && once) {
pr_err("%s: %s is already opened.\n",
__func__,
filep->f_path.dentry->d_name.name);
return -EBUSY;
}
rc = nonseekable_open(inode, filep);
if (rc < 0) {
pr_err("%s: nonseekable_open error %d\n", __func__, rc);
return rc;
}
rc = __msm_open(pmsm->sync, MSM_APPS_ID_PROP, is_controlnode);
if (rc < 0)
return rc;
filep->private_data = pmsm;
CDBG("%s: rc %d\n", __func__, rc);
return rc;
}
static int msm_open(struct inode *inode, struct file *filep)
{
return msm_open_common(inode, filep, 1, 0);
}
static int msm_open_control(struct inode *inode, struct file *filep)
{
int rc;
struct msm_control_device *ctrl_pmsm =
kmalloc(sizeof(struct msm_control_device), GFP_KERNEL);
if (!ctrl_pmsm)
return -ENOMEM;
rc = msm_open_common(inode, filep, 0, 1);
if (rc < 0) {
kfree(ctrl_pmsm);
return rc;
}
ctrl_pmsm->pmsm = filep->private_data;
filep->private_data = ctrl_pmsm;
msm_queue_init(&ctrl_pmsm->ctrl_q, "control");
if (!g_v4l2_opencnt)
<API key> = ctrl_pmsm;
g_v4l2_opencnt++;
CDBG("%s: rc %d\n", __func__, rc);
return rc;
}
static const struct file_operations msm_fops_config = {
.owner = THIS_MODULE,
.open = msm_open,
.unlocked_ioctl = msm_ioctl_config,
.release = msm_release_config,
.poll = msm_poll_config,
};
static const struct file_operations msm_fops_control = {
.owner = THIS_MODULE,
.open = msm_open_control,
.unlocked_ioctl = msm_ioctl_control,
.release = msm_release_control,
};
static const struct file_operations msm_fops_frame = {
.owner = THIS_MODULE,
.open = msm_open,
.unlocked_ioctl = msm_ioctl_frame,
.release = msm_release_frame,
.poll = msm_poll_frame,
};
static const struct file_operations msm_fops_pic = {
.owner = THIS_MODULE,
.open = msm_open,
.unlocked_ioctl = msm_ioctl_pic,
.release = msm_release_pic,
.poll = msm_poll_pic,
};
static int msm_setup_cdev(struct msm_cam_device *msm,
int node,
dev_t devno,
const char *suffix,
const struct file_operations *fops)
{
int rc = -ENODEV;
struct device *device =
device_create(msm_class, NULL,
devno, NULL,
"%s%d", suffix, node);
if (IS_ERR(device)) {
rc = PTR_ERR(device);
pr_err("%s: error creating device: %d\n", __func__, rc);
return rc;
}
cdev_init(&msm->cdev, fops);
msm->cdev.owner = THIS_MODULE;
rc = cdev_add(&msm->cdev, devno, 1);
if (rc < 0) {
pr_err("%s: error adding cdev: %d\n", __func__, rc);
device_destroy(msm_class, devno);
return rc;
}
return rc;
}
static int msm_tear_down_cdev(struct msm_cam_device *msm, dev_t devno)
{
cdev_del(&msm->cdev);
device_destroy(msm_class, devno);
return 0;
}
static uint32_t <API key>;
static uint32_t <API key>;
static uint32_t <API key>;
static uint16_t led_low_temp_limit;
static uint16_t led_low_cap_limit;
static struct kobject *led_status_obj;
static ssize_t led_ril_status_get(struct device *dev,
struct device_attribute *attr, char *buf)
{
ssize_t length;
length = sprintf(buf, "%d\n", <API key>);
return length;
}
static ssize_t led_ril_status_set(struct device *dev,
struct device_attribute *attr, const char *buf, size_t count)
{
uint32_t tmp = 0;
if (buf[1] == '\n')
tmp = buf[0] - 0x30;
<API key> = tmp;
pr_info("[CAM]<API key> = %d\n", <API key>);
return count;
}
static ssize_t <API key>(struct device *dev,
struct device_attribute *attr, char *buf)
{
ssize_t length;
length = sprintf(buf, "%d\n", <API key>);
return length;
}
static ssize_t <API key>(struct device *dev,
struct device_attribute *attr, const char *buf, size_t count)
{
uint32_t tmp = 0;
if (buf[1] == '\n')
tmp = buf[0] - 0x30;
<API key> = tmp;
pr_info("[CAM]<API key> = %d\n", <API key>);
return count;
}
static ssize_t <API key>(struct device *dev,
struct device_attribute *attr, char *buf)
{
ssize_t length;
length = sprintf(buf, "%d\n", <API key>);
return length;
}
static ssize_t <API key>(struct device *dev,
struct device_attribute *attr, const char *buf, size_t count)
{
uint32_t tmp = 0;
tmp = buf[0] - 0x30; /* only get the first char */
<API key> = tmp;
pr_info("[CAM]<API key> = %d\n", <API key>);
return count;
}
static ssize_t low_temp_limit_get(struct device *dev,
struct device_attribute *attr, char *buf)
{
ssize_t length;
length = sprintf(buf, "%d\n", led_low_temp_limit);
return length;
}
static ssize_t low_cap_limit_get(struct device *dev,
struct device_attribute *attr, char *buf)
{
ssize_t length;
length = sprintf(buf, "%d\n", led_low_cap_limit);
return length;
}
static DEVICE_ATTR(led_ril_status, 0644,
led_ril_status_get,
led_ril_status_set);
static DEVICE_ATTR(led_wimax_status, 0644,
<API key>,
<API key>);
static DEVICE_ATTR(led_hotspot_status, 0644,
<API key>,
<API key>);
static DEVICE_ATTR(low_temp_limit, 0444,
low_temp_limit_get,
NULL);
static DEVICE_ATTR(low_cap_limit, 0444,
low_cap_limit_get,
NULL);
static int <API key>(struct msm_sync *sync)
{
int ret = 0;
CDBG("msm_camera:kobject creat and add\n");
led_status_obj = <API key>("camera_led_status", NULL);
if (led_status_obj == NULL) {
pr_info("[CAM]msm_camera: subsystem_register failed\n");
ret = -ENOMEM;
goto error;
}
ret = sysfs_create_file(led_status_obj,
&<API key>.attr);
if (ret) {
pr_info("[CAM]msm_camera: sysfs_create_file ril failed\n");
ret = -EFAULT;
goto error;
}
ret = sysfs_create_file(led_status_obj,
&<API key>.attr);
if (ret) {
pr_info("[CAM]msm_camera: sysfs_create_file wimax failed\n");
ret = -EFAULT;
goto error;
}
ret = sysfs_create_file(led_status_obj,
&<API key>.attr);
if (ret) {
pr_info("[CAM]msm_camera: sysfs_create_file hotspot failed\n");
ret = -EFAULT;
goto error;
}
ret = sysfs_create_file(led_status_obj,
&<API key>.attr);
if (ret) {
pr_info("[CAM]msm_camera:sysfs_create_file low_temp_limit failed\n");
ret = -EFAULT;
goto error;
}
ret = sysfs_create_file(led_status_obj,
&<API key>.attr);
if (ret) {
pr_info("[CAM]msm_camera: sysfs_create_file low_cap_limit failed\n");
ret = -EFAULT;
goto error;
}
led_low_temp_limit = sync->sdata->flash_cfg->low_temp_limit;
led_low_cap_limit = sync->sdata->flash_cfg->low_cap_limit;
return ret;
error:
kobject_del(led_status_obj);
return ret;
}
static int msm_sync_init(struct msm_sync *sync,
struct platform_device *pdev,
int (*sensor_probe)( struct <API key> *,
struct msm_sensor_ctrl *))
{
int rc = 0;
struct msm_sensor_ctrl sctrl;
sync->sdata = pdev->dev.platform_data;
msm_queue_init(&sync->event_q, "event");
msm_queue_init(&sync->frame_q, "frame");
msm_queue_init(&sync->pict_q, "pict");
msm_queue_init(&sync->vpe_q, "vpe");
wake_lock_init(&sync->wake_lock, WAKE_LOCK_IDLE, "msm_camera");
rc = msm_camio_probe_on(pdev);
if (rc < 0) {
wake_lock_destroy(&sync->wake_lock);
return rc;
}
rc = sensor_probe(sync->sdata, &sctrl);
if (rc >= 0) {
sync->pdev = pdev;
sync->sctrl = sctrl;
}
msm_camio_probe_off(pdev);
if (rc < 0) {
pr_err("%s: failed to initialize %s\n",
__func__,
sync->sdata->sensor_name);
wake_lock_destroy(&sync->wake_lock);
return rc;
}
camera_node = sync->sdata->dev_node;
sync->opencnt = 0;
sync->core_powered_on = 0;
sync->ignore_qcmd = false;
sync->ignore_qcmd_type = -1;
sync->qcmd_done = false;
mutex_init(&sync->lock);
if (sync->sdata->strobe_flash_data) {
sync->sdata->strobe_flash_data->state = 0;
spin_lock_init(&sync->sdata->strobe_flash_data->spin_lock);
}
CDBG("%s: initialized %s\n", __func__, sync->sdata->sensor_name);
return rc;
}
static int msm_sync_destroy(struct msm_sync *sync)
{
wake_lock_destroy(&sync->wake_lock);
return 0;
}
static int msm_device_init(struct msm_cam_device *pmsm,
struct msm_sync *sync,
int node)
{
int dev_num = 4 * node;
int rc = msm_setup_cdev(pmsm, node,
MKDEV(MAJOR(msm_devno), dev_num),
"control", &msm_fops_control);
if (rc < 0) {
pr_err("%s: error creating control node: %d\n", __func__, rc);
return rc;
}
rc = msm_setup_cdev(pmsm + 1, node,
MKDEV(MAJOR(msm_devno), dev_num + 1),
"config", &msm_fops_config);
if (rc < 0) {
pr_err("%s: error creating config node: %d\n", __func__, rc);
msm_tear_down_cdev(pmsm, MKDEV(MAJOR(msm_devno),
dev_num));
return rc;
}
rc = msm_setup_cdev(pmsm + 2, node,
MKDEV(MAJOR(msm_devno), dev_num + 2),
"frame", &msm_fops_frame);
if (rc < 0) {
pr_err("%s: error creating frame node: %d\n", __func__, rc);
msm_tear_down_cdev(pmsm,
MKDEV(MAJOR(msm_devno), dev_num));
msm_tear_down_cdev(pmsm + 1,
MKDEV(MAJOR(msm_devno), dev_num + 1));
return rc;
}
rc = msm_setup_cdev(pmsm + 3, node,
MKDEV(MAJOR(msm_devno), dev_num + 3),
"pic", &msm_fops_pic);
if (rc < 0) {
pr_err("%s: error creating pic node: %d\n", __func__, rc);
msm_tear_down_cdev(pmsm,
MKDEV(MAJOR(msm_devno), dev_num));
msm_tear_down_cdev(pmsm + 1,
MKDEV(MAJOR(msm_devno), dev_num + 1));
msm_tear_down_cdev(pmsm + 2,
MKDEV(MAJOR(msm_devno), dev_num + 2));
return rc;
}
atomic_set(&pmsm[0].opened, 0);
atomic_set(&pmsm[1].opened, 0);
atomic_set(&pmsm[2].opened, 0);
atomic_set(&pmsm[3].opened, 0);
pmsm[0].sync = sync;
pmsm[1].sync = sync;
pmsm[2].sync = sync;
pmsm[3].sync = sync;
return rc;
}
int <API key>(struct platform_device *dev,
int (*sensor_probe)(struct <API key> *,
struct msm_sensor_ctrl *))
{
struct msm_cam_device *pmsm = NULL;
struct msm_sync *sync;
int rc = -ENODEV;
if (camera_node >= <API key>) {
pr_err("%s: too many camera sensors\n", __func__);
return rc;
}
if (!msm_class) {
/* There are three device nodes per sensor */
rc = alloc_chrdev_region(&msm_devno, 0,
4 * <API key>,
"msm_camera");
if (rc < 0) {
pr_err("%s: failed to allocate chrdev: %d\n", __func__,
rc);
return rc;
}
msm_class = class_create(THIS_MODULE, "msm_camera");
if (IS_ERR(msm_class)) {
rc = PTR_ERR(msm_class);
pr_err("%s: create device class failed: %d\n",
__func__, rc);
return rc;
}
}
pmsm = kzalloc(sizeof(struct msm_cam_device) * 4 +
sizeof(struct msm_sync), GFP_ATOMIC);
if (!pmsm)
return -ENOMEM;
sync = (struct msm_sync *)(pmsm + 4);
rc = msm_sync_init(sync, dev, sensor_probe);
if (rc < 0) {
kfree(pmsm);
return rc;
}
CDBG("%s: setting camera node %d\n", __func__, camera_node);
rc = msm_device_init(pmsm, sync, camera_node);
if (rc < 0) {
msm_sync_destroy(sync);
kfree(pmsm);
return rc;
}
if (!!sync->sdata->flash_cfg)
{
<API key>(sync);
}
camera_type[camera_node] = sync->sctrl.s_camera_type;
sensor_mount_angle[camera_node] = sync->sctrl.s_mount_angle;
camera_node++;
list_add(&sync->list, &msm_sensors);
return rc;
}
EXPORT_SYMBOL(<API key>); |
package nsk.jdi.ObjectReference.invokeMethod;
import nsk.share.*;
import nsk.share.jpda.*;
import nsk.share.jdi.*;
// THIS TEST IS LINE NUMBER SENSITIVE
/**
* This is a debuggee class.
*/
public class invokemethod008t {
static Log log;
public static void main(String args[]) {
System.exit(run(args) + Consts.JCK_STATUS_BASE);
}
public static int run(String args[]) {
return new invokemethod008t().runIt(args);
}
private int runIt(String args[]) {
ArgumentHandler argHandler = new ArgumentHandler(args);
IOPipe pipe = argHandler.createDebugeeIOPipe();
log = argHandler.createDebugeeLog();
// force debuggee VM to load dummy classes
<API key> <API key> =
new <API key>();
<API key> <API key> =
new <API key>();
<API key> <API key> =
new <API key>();
Thread.currentThread().setName(invokemethod008.DEBUGGEE_THRNAME);
pipe.println(invokemethod008.COMMAND_READY);
String cmd = pipe.readln();
if (cmd.equals(invokemethod008.COMMAND_QUIT)) {
log.complain("Debuggee: exiting due to the command "
+ cmd);
return Consts.TEST_PASSED;
}
int stopMeHere = 0; // invokemethod008.DEBUGGEE_STOPATLINE
cmd = pipe.readln();
if (!cmd.equals(invokemethod008.COMMAND_QUIT)) {
log.complain("TEST BUG: unknown debugger command: "
+ cmd);
System.exit(Consts.JCK_STATUS_BASE +
Consts.TEST_FAILED);
}
return Consts.TEST_PASSED;
}
}
// Dummy super super class used to check the flag
// ObjectReference.INVOKE_NONVIRTUAL in the debugger
class <API key> {
protected long longProtMeth(long l) {
invokemethod008t.log.display("<API key>: longProtMeth invoked");
return (l - 2);
}
long longMeth(long l) {
invokemethod008t.log.display("<API key>: longMeth invoked");
return (l - 2);
}
}
// Dummy super class used to check the flag
// ObjectReference.INVOKE_NONVIRTUAL in the debugger
class <API key> extends <API key> {
protected long longProtMeth(long l) {
invokemethod008t.log.display("<API key>: longProtMeth invoked");
return (l - 1);
}
long longMeth(long l) {
invokemethod008t.log.display("<API key>: longMeth invoked");
return (l - 1);
}
}
// Dummy class used to check the flag
// ObjectReference.INVOKE_NONVIRTUAL in the debugger
class <API key> extends <API key> {
protected long longProtMeth(long l) {
invokemethod008t.log.display("<API key>: longProtMeth invoked");
return l;
}
long longMeth(long l) {
invokemethod008t.log.display("<API key>: longMeth invoked");
return l;
}
} |
<?php
/**
* @file
* Contains \Drupal\Console\Command\Debug\TestCommand.
*/
namespace Drupal\Console\Command\Debug;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Drupal\Component\Serialization\Yaml;
use Drupal\Console\Core\Command\Command;
use Drupal\Console\Annotations\DrupalCommand;
use Drupal\simpletest\TestDiscovery;
/**
* @DrupalCommand(
* extension = "simpletest",
* extensionType = "module",
* )
*/
class TestCommand extends Command
{
/**
* @var TestDiscovery
*/
protected $test_discovery;
/**
* TestCommand constructor.
*
* @param TestDiscovery $test_discovery
*/
public function __construct(
TestDiscovery $test_discovery
) {
$this->test_discovery = $test_discovery;
parent::__construct();
}
protected function configure()
{
$this
->setName('debug:test')
->setDescription($this->trans('commands.debug.test.description'))
->addArgument(
'group',
InputArgument::OPTIONAL,
$this->trans('commands.debug.test.options.group'),
null
)
->addOption(
'test-class',
null,
InputOption::VALUE_OPTIONAL,
$this->trans('commands.debug.test.arguments.test-class')
)
->setAliases(['td']);
}
/**
* {@inheritdoc}
*/
protected function execute(InputInterface $input, OutputInterface $output)
{
//Registers namespaces for disabled modules.
$this->test_discovery-><API key>();
$testClass = $input->getOption('test-class');
$group = $input->getArgument('group');
if ($testClass) {
$this->testDetail($testClass);
} else {
$this->testList($group);
}
}
private function testDetail($test_class)
{
$testingGroups = $this->test_discovery->getTestClasses(null);
$testDetails = null;
foreach ($testingGroups as $testing_group => $tests) {
foreach ($tests as $key => $test) {
if ($test['name'] == $test_class) {
$testDetails = $test;
break;
}
}
if ($testDetails !== null) {
break;
}
}
$class = null;
if ($testDetails) {
$class = new \ReflectionClass($test['name']);
if (is_subclass_of($testDetails['name'], '<API key>')) {
$testDetails['type'] = 'phpunit';
} else {
$testDetails = $this->test_discovery
->getTestInfo($testDetails['name']);
$testDetails['type'] = 'simpletest';
}
$this->getIo()->comment($testDetails['name']);
$testInfo = [];
foreach ($testDetails as $key => $value) {
$testInfo [] = [$key, $value];
}
$this->getIo()->table([], $testInfo);
if ($class) {
$methods = $class->getMethods(\ReflectionMethod::IS_PUBLIC);
$this->getIo()->info($this->trans('commands.debug.test.messages.methods'));
foreach ($methods as $method) {
if ($method->class == $testDetails['name'] && strpos($method->name, 'test') === 0) {
$this->getIo()->simple($method->name);
}
}
}
} else {
$this->getIo()->error($this->trans('commands.debug.test.messages.not-found'));
}
}
protected function testList($group)
{
$testingGroups = $this->test_discovery
->getTestClasses(null);
if (empty($group)) {
$tableHeader = [$this->trans('commands.debug.test.messages.group')];
} else {
$tableHeader = [
$this->trans('commands.debug.test.messages.class'),
$this->trans('commands.debug.test.messages.type')
];
$this->getIo()->writeln(
sprintf(
'%s: %s',
$this->trans('commands.debug.test.messages.group'),
$group
)
);
}
$tableRows = [];
foreach ($testingGroups as $testing_group => $tests) {
if (empty($group)) {
$tableRows[] =[$testing_group];
continue;
}
if (!empty($group) && $group != $testing_group) {
continue;
}
foreach ($tests as $test) {
if (is_subclass_of($test['name'], '<API key>')) {
$test['type'] = 'phpunit';
} else {
$test['type'] = 'simpletest';
}
$tableRows[] =[
$test['name'],
$test['type']
];
}
}
$this->getIo()->table($tableHeader, $tableRows, 'compact');
if ($group) {
$this->getIo()->success(
sprintf(
$this->trans('commands.debug.test.messages.success-group'),
$group
)
);
} else {
$this->getIo()->success(
$this->trans('commands.debug.test.messages.success-groups')
);
}
}
} |
/**
* @file
* Tablesort indicator styles.
*/
.tablesort {
position: absolute;
top: 50%;
right: 1rem;
width: 0.875rem; /* 14px */
height: 1rem; /* 16px */
margin-top: -0.5rem; /* -8px */
opacity: 0.5;
background: url("data:image/svg+xml,%3Csvg xmlns='http:
background-size: auto;
}
/* <API key> <API key> */
_:-ms-fullscreen, /* Only IE 11 */
.tablesort {
position: static;
float: right;
margin-top: 0.125rem; /* 2px */
margin-right: -1.5rem; /* -24px */
}
[dir="rtl"] .tablesort {
right: auto;
left: 1rem; /* 16px */
background-image: url("data:image/svg+xml,%3Csvg xmlns='http:
}
/* <API key> <API key> */
_:-ms-fullscreen, /* Only IE 11 */
[dir="rtl"] .tablesort {
float: left;
margin-right: 0;
margin-left: -1.5rem; /* -24px */
}
.tablesort--asc,
[dir="rtl"] .tablesort--asc {
opacity: 1;
background-image: url("data:image/svg+xml,%3Csvg xmlns='http:
}
.tablesort--desc,
[dir="rtl"] .tablesort--desc {
opacity: 1;
background-image: url("data:image/svg+xml,%3Csvg xmlns='http:
} |
/* $NetBSD: byte_swap.h,v 1.10 2006/01/30 22:46:36 dsl Exp $ */
#ifndef _I386_BYTE_SWAP_H_
#define _I386_BYTE_SWAP_H_
#include <sys/types.h>
#if defined(_KERNEL_OPT)
#include "opt_cputype.h"
#endif
#ifdef __GNUC__
#include <sys/types.h>
__BEGIN_DECLS
#define <API key> <API key>
static __inline uint32_t <API key>(uint32_t);
static __inline uint32_t
<API key>(uint32_t x)
{
__asm volatile (
#if defined(_KERNEL) && !defined(_LKM) && !defined(I386_CPU)
"bswap %1"
#else
"rorw $8, %w1\n\trorl $16, %1\n\trorw $8, %w1"
#endif
: "=r" (x) : "0" (x));
return (x);
}
#define <API key> <API key>
static __inline uint16_t <API key>(uint16_t);
static __inline uint16_t
<API key>(uint16_t x)
{
__asm volatile ("rorw $8, %w1" : "=r" (x) : "0" (x));
return (x);
}
__END_DECLS
#endif
#endif /* !_I386_BYTE_SWAP_H_ */ |
#include "GamePad.h"
#ifdef SDL_BUILD
#include "SDL/joystick.h"
#endif
vector<GamePad*> s_vgamePad;
bool <API key>(int GamePadId)
{
return ((GamePadId >= 0) && (GamePadId < (int)s_vgamePad.size()));
}
/**
* Following static methods are just forwarders to their backend
* This is where link between agnostic and specific code is done
**/
/**
* Find every interesting devices and create right structure for them(depend on backend)
**/
void GamePad::EnumerateGamePads(vector<GamePad*>& vgamePad)
{
#ifdef SDL_BUILD
JoystickInfo::EnumerateJoysticks(vgamePad);
#endif
}
void GamePad::UpdateReleaseState()
{
#ifdef SDL_BUILD
JoystickInfo::UpdateReleaseState();
#endif
}
/**
* Safely dispatch to the Rumble method above
**/
void GamePad::DoRumble(int type, int pad)
{
u32 id = conf->get_joyid(pad);
if (<API key>(id)) {
GamePad* gamePad = s_vgamePad[id];
if (gamePad)
gamePad->Rumble(type, pad);
}
}
/**
* Update state of every attached devices
**/
void GamePad::UpdateGamePadState()
{
#ifdef SDL_BUILD
SDL_JoystickUpdate(); // No need to make yet another function call for that
#endif
} |
<?php
class <API key> extends <API key> {
/**
* Creates a new <API key> instance
*
* Example usage:
*
* .. code-block:: php
*
* $client->account->sip->domains->get('SDXXX')-><API key>->create("<API key>");
*
* :param string $<API key>: the sid of the IpAccessControList
* you're adding to this domain.
* :param array $params: a single array of parameters which is serialized and
* sent directly to the Twilio API.
*/
public function create($<API key>, $params = array()) {
return parent::_create(array(
'<API key>' => $<API key>,
) + $params);
}
} |
#include "../../SDL_internal.h"
#ifndef SDL_POWER_DISABLED
#if SDL_POWER_WINDOWS
#include "../../core/windows/SDL_windows.h"
#include "SDL_power.h"
SDL_bool
<API key>(SDL_PowerState * state, int *seconds, int *percent)
{
SYSTEM_POWER_STATUS status;
SDL_bool need_details = SDL_FALSE;
/* This API should exist back to Win95. */
if (!<API key>(&status))
{
/* !!! FIXME: push GetLastError() into SDL_GetError() */
*state = <API key>;
} else if (status.BatteryFlag == 0xFF) { /* unknown state */
*state = <API key>;
} else if (status.BatteryFlag & (1 << 7)) { /* no battery */
*state = <API key>;
} else if (status.BatteryFlag & (1 << 3)) { /* charging */
*state = <API key>;
need_details = SDL_TRUE;
} else if (status.ACLineStatus == 1) {
*state = <API key>; /* on AC, not charging. */
need_details = SDL_TRUE;
} else {
*state = <API key>; /* not on AC. */
need_details = SDL_TRUE;
}
*percent = -1;
*seconds = -1;
if (need_details) {
const int pct = (int) status.BatteryLifePercent;
const int secs = (int) status.BatteryLifeTime;
if (pct != 255) { /* 255 == unknown */
*percent = (pct > 100) ? 100 : pct; /* clamp between 0%, 100% */
}
if (secs != 0xFFFFFFFF) { /* ((DWORD)-1) == unknown */
*seconds = secs;
}
}
return SDL_TRUE; /* always the definitive answer on Windows. */
}
#endif /* SDL_POWER_WINDOWS */
#endif /* SDL_POWER_DISABLED */
/* vi: set ts=4 sw=4 expandtab: */ |
#include "alloc-util.h"
#include "fd-util.h"
#include "<API key>.h"
#include "journald-native.h"
#include "parse-util.h"
#include "string-util.h"
void source_free(RemoteSource *source) {
if (!source)
return;
<API key>(&source->importer);
log_debug("Writer ref count %i", source->writer->n_ref);
writer_unref(source->writer);
<API key>(source->event);
<API key>(source->buffer_event);
free(source);
}
/**
* Initialize zero-filled source with given values. On success, takes
* ownership of fd, name, and writer, otherwise does not touch them.
*/
RemoteSource* source_new(int fd, bool passive_fd, char *name, Writer *writer) {
RemoteSource *source;
log_debug("Creating source for %sfd:%d (%s)",
passive_fd ? "passive " : "", fd, name);
assert(fd >= 0);
source = new0(RemoteSource, 1);
if (!source)
return NULL;
source->importer.fd = fd;
source->importer.passive_fd = passive_fd;
source->importer.name = name;
source->writer = writer;
return source;
}
int process_source(RemoteSource *source, bool compress, bool seal) {
int r;
assert(source);
assert(source->writer);
r = <API key>(&source->importer);
if (r <= 0)
return r;
/* We have a full event */
log_trace("Received full event from source@%p fd:%d (%s)",
source, source->importer.fd, source->importer.name);
if (source->importer.iovw.count == 0) {
log_warning("Entry with no payload, skipping");
goto freeing;
}
assert(source->importer.iovw.iovec);
r = writer_write(source->writer, &source->importer.iovw, &source->importer.ts, compress, seal);
if (r < 0)
log_error_errno(r, "Failed to write entry of %zu bytes: %m",
iovw_size(&source->importer.iovw));
else
r = 1;
freeing:
<API key>(&source->importer);
return r;
} |
/**
** @file
** integer misc ops.
**/
#include "config.h"
#if HAVE_ALTIVEC_H
#include <altivec.h>
#endif
#include "libavutil/attributes.h"
#include "libavutil/ppc/types_altivec.h"
#include "libavcodec/dsputil.h"
#include "dsputil_altivec.h"
static int <API key>(const int8_t *pix1, const int16_t *pix2,
int size) {
int i, size16;
vector signed char vpix1;
vector signed short vpix2, vdiff, vpix1l,vpix1h;
union { vector signed int vscore;
int32_t score[4];
} u;
u.vscore = vec_splat_s32(0);
//XXX lazy way, fix it later
#define vec_unaligned_load(b) \
vec_perm(vec_ld(0,b),vec_ld(15,b),vec_lvsl(0, b));
size16 = size >> 4;
while(size16) {
// score += (pix1[i]-pix2[i])*(pix1[i]-pix2[i]);
//load pix1 and the first batch of pix2
vpix1 = vec_unaligned_load(pix1);
vpix2 = vec_unaligned_load(pix2);
pix2 += 8;
//unpack
vpix1h = vec_unpackh(vpix1);
vdiff = vec_sub(vpix1h, vpix2);
vpix1l = vec_unpackl(vpix1);
// load another batch from pix2
vpix2 = vec_unaligned_load(pix2);
u.vscore = vec_msum(vdiff, vdiff, u.vscore);
vdiff = vec_sub(vpix1l, vpix2);
u.vscore = vec_msum(vdiff, vdiff, u.vscore);
pix1 += 16;
pix2 += 8;
size16
}
u.vscore = vec_sums(u.vscore, vec_splat_s32(0));
size %= 16;
for (i = 0; i < size; i++) {
u.score[3] += (pix1[i]-pix2[i])*(pix1[i]-pix2[i]);
}
return u.score[3];
}
static int32_t <API key>(const int16_t *v1, const int16_t *v2,
int order)
{
int i;
LOAD_ZERO;
const vec_s16 *pv;
register vec_s16 vec1;
register vec_s32 res = vec_splat_s32(0), t;
int32_t ires;
for(i = 0; i < order; i += 8){
pv = (const vec_s16*)v1;
vec1 = vec_perm(pv[0], pv[1], vec_lvsl(0, v1));
t = vec_msum(vec1, vec_ld(0, v2), zero_s32v);
res = vec_sums(t, res);
v1 += 8;
v2 += 8;
}
res = vec_splat(res, 3);
vec_ste(res, 0, &ires);
return ires;
}
static int32_t <API key>(int16_t *v1, const int16_t *v2, const int16_t *v3, int order, int mul)
{
LOAD_ZERO;
vec_s16 *pv1 = (vec_s16*)v1;
register vec_s16 muls = {mul,mul,mul,mul,mul,mul,mul,mul};
register vec_s16 t0, t1, i0, i1, i4;
register vec_s16 i2 = vec_ld(0, v2), i3 = vec_ld(0, v3);
register vec_s32 res = zero_s32v;
register vec_u8 align = vec_lvsl(0, v2);
int32_t ires;
order >>= 4;
do {
i1 = vec_ld(16, v2);
t0 = vec_perm(i2, i1, align);
i2 = vec_ld(32, v2);
t1 = vec_perm(i1, i2, align);
i0 = pv1[0];
i1 = pv1[1];
res = vec_msum(t0, i0, res);
res = vec_msum(t1, i1, res);
i4 = vec_ld(16, v3);
t0 = vec_perm(i3, i4, align);
i3 = vec_ld(32, v3);
t1 = vec_perm(i4, i3, align);
pv1[0] = vec_mladd(t0, muls, i0);
pv1[1] = vec_mladd(t1, muls, i1);
pv1 += 2;
v2 += 8;
v3 += 8;
} while(--order);
res = vec_splat(vec_sums(res, zero_s32v), 3);
vec_ste(res, 0, &ires);
return ires;
}
av_cold void ff_int_init_altivec(DSPContext *c, AVCodecContext *avctx)
{
c->ssd_int8_vs_int16 = <API key>;
c->scalarproduct_int16 = <API key>;
c-><API key> = <API key>;
} |
#include "config.h"
#include "system.h"
#include "coretypes.h"
#include "tm.h"
#include "alias.h"
#include "tree.h"
#include "stringpool.h"
#include "stor-layout.h"
#include "c-common.h"
#include "c-indentation.h"
extern cpp_options *cpp_opts;
/* Convert libcpp's notion of a column (a 1-based char count) to
the "visual column" (0-based column, respecting tabs), by reading the
relevant line.
Returns true if a conversion was possible, writing the result to OUT,
otherwise returns false. If FIRST_NWS is not NULL, then write to it
the visual column corresponding to the first non-whitespace character
on the line. */
static bool
get_visual_column (expanded_location exploc,
unsigned int *out,
unsigned int *first_nws = NULL)
{
int line_len;
const char *line = <API key> (exploc, &line_len);
if (!line)
return false;
unsigned int vis_column = 0;
for (int i = 1; i < exploc.column; i++)
{
unsigned char ch = line[i - 1];
if (first_nws != NULL && !ISSPACE (ch))
{
*first_nws = vis_column;
first_nws = NULL;
}
if (ch == '\t')
{
/* Round up to nearest tab stop. */
const unsigned int tab_width = cpp_opts->tabstop;
vis_column = ((vis_column + tab_width) / tab_width) * tab_width;
}
else
vis_column++;
}
if (first_nws != NULL)
*first_nws = vis_column;
*out = vis_column;
return true;
}
/* Does the given source line appear to contain a #if directive?
(or #ifdef/#ifndef). Ignore the possibility of it being inside a
comment, for simplicity.
Helper function for <API key>. */
static bool
<API key> (const char *file, int line_num)
{
expanded_location exploc;
exploc.file = file;
exploc.line = line_num;
exploc.column = 1;
int line_len;
const char *line = <API key> (exploc, &line_len);
if (!line)
return false;
int idx;
/* Skip leading whitespace. */
for (idx = 0; idx < line_len; idx++)
if (!ISSPACE (line[idx]))
break;
if (idx == line_len)
return false;
/* Require a '#' character. */
if (line[idx] != '
return false;
idx++;
/* Skip whitespace. */
while (idx < line_len)
{
if (!ISSPACE (line[idx]))
break;
idx++;
}
/* Match #if/#ifdef/#ifndef. */
if (idx + 2 <= line_len)
if (line[idx] == 'i')
if (line[idx + 1] == 'f')
return true;
return false;
}
/* Determine if there is preprocessor logic between
BODY_EXPLOC and NEXT_STMT_EXPLOC, to ensure that we don't
issue a warning for cases like this:
if (flagA)
foo ();
^ BODY_EXPLOC
#if <API key>
if (flagB)
#endif
bar ();
^ NEXT_STMT_EXPLOC
despite "bar ();" being visually aligned below "foo ();" and
being (as far as the parser sees) the next token.
Return true if such logic is detected. */
static bool
<API key> (expanded_location body_exploc,
expanded_location next_stmt_exploc)
{
gcc_assert (next_stmt_exploc.file == body_exploc.file);
gcc_assert (next_stmt_exploc.line > body_exploc.line);
if (next_stmt_exploc.line - body_exploc.line < 4)
return false;
/* Is there a #if/#ifdef/#ifndef directive somewhere in the lines
between the given locations?
This is something of a layering violation, but by necessity,
given the nature of what we're testing for. For example,
in theory we could be fooled by a #if within a comment, but
it's unlikely to matter. */
for (int line = body_exploc.line + 1; line < next_stmt_exploc.line; line++)
if (<API key> (body_exploc.file, line))
return true;
/* Not found. */
return false;
}
/* Helper function for <API key>; see
description of that function below. */
static bool
<API key> (const token_indent_info &guard_tinfo,
const token_indent_info &body_tinfo,
const token_indent_info &next_tinfo)
{
location_t guard_loc = guard_tinfo.location;
location_t body_loc = body_tinfo.location;
location_t next_stmt_loc = next_tinfo.location;
enum cpp_ttype body_type = body_tinfo.type;
enum cpp_ttype next_tok_type = next_tinfo.type;
/* Don't attempt to compare the indentation of BODY_LOC and NEXT_STMT_LOC
if either are within macros. */
if (<API key> (line_table, body_loc)
|| <API key> (line_table, next_stmt_loc))
return false;
/* Don't attempt to compare indentation if #line or # 44 "file"-style
directives are present, suggesting generated code.
All bets are off if these are present: the file that the #line
directive could have an entirely different coding layout to C/C++
(e.g. .md files).
To determine if a #line is present, in theory we could look for a
map with reason == LC_RENAME_VERBATIM. However, if there has
subsequently been a long line requiring a column number larger than
that representable by the original LC_RENAME_VERBATIM map, then
we'll have a map with reason LC_RENAME.
Rather than attempting to search all of the maps for a
LC_RENAME_VERBATIM, instead we have libcpp set a flag whenever one
is seen, and we check for the flag here.
*/
if (line_table->seen_line_directive)
return false;
/* If the token following the body is a close brace or an "else"
then while indentation may be sloppy, there is not much ambiguity
about control flow, e.g.
if (foo) <- GUARD
bar (); <- BODY
else baz (); <- NEXT
{
while (foo) <- GUARD
bar (); <- BODY
} <- NEXT
baz ();
*/
if (next_tok_type == CPP_CLOSE_BRACE
|| next_tinfo.keyword == RID_ELSE)
return false;
/* Likewise, if the body of the guard is a compound statement then control
flow is quite visually explicit regardless of the code's possibly poor
indentation, e.g.
while (foo) <- GUARD
{ <- BODY
bar ();
}
baz (); <- NEXT
Things only get muddy when the body of the guard does not have
braces, e.g.
if (foo) <- GUARD
bar (); <- BODY
baz (); <- NEXT
*/
if (body_type == CPP_OPEN_BRACE)
return false;
/* Don't warn here about spurious semicolons. */
if (next_tok_type == CPP_SEMICOLON)
return false;
expanded_location body_exploc = expand_location (body_loc);
expanded_location next_stmt_exploc = expand_location (next_stmt_loc);
expanded_location guard_exploc = expand_location (guard_loc);
/* They must be in the same file. */
if (next_stmt_exploc.file != body_exploc.file)
return false;
/* If NEXT_STMT_LOC and BODY_LOC are on the same line, consider
the location of the guard.
Cases where we want to issue a warning:
if (flag)
foo (); bar ();
^ WARN HERE
if (flag) foo (); bar ();
^ WARN HERE
if (flag) ; {
^ WARN HERE
if (flag)
; {
^ WARN HERE
Cases where we don't want to issue a warning:
various_code (); if (flag) foo (); bar (); more_code ();
^ DON'T WARN HERE. */
if (next_stmt_exploc.line == body_exploc.line)
{
if (guard_exploc.file != body_exploc.file)
return true;
if (guard_exploc.line < body_exploc.line)
/* The guard is on a line before a line that contains both
the body and the next stmt. */
return true;
else if (guard_exploc.line == body_exploc.line)
{
/* They're all on the same line. */
gcc_assert (guard_exploc.file == next_stmt_exploc.file);
gcc_assert (guard_exploc.line == next_stmt_exploc.line);
unsigned int guard_vis_column;
unsigned int <API key>;
if (!get_visual_column (guard_exploc,
&guard_vis_column,
&<API key>))
return false;
/* Heuristic: only warn if the guard is the first thing
on its line. */
if (guard_vis_column == <API key>)
return true;
}
}
/* If NEXT_STMT_LOC is on a line after BODY_LOC, consider
their relative locations, and of the guard.
Cases where we want to issue a warning:
if (flag)
foo ();
bar ();
^ WARN HERE
Cases where we don't want to issue a warning:
if (flag)
foo ();
bar ();
^ DON'T WARN HERE (autogenerated code?)
if (flagA)
foo ();
#if <API key>
if (flagB)
#endif
bar ();
^ DON'T WARN HERE
if (flag)
;
foo ();
^ DON'T WARN HERE
*/
if (next_stmt_exploc.line > body_exploc.line)
{
/* Determine if GUARD_LOC and NEXT_STMT_LOC are aligned on the same
"visual column"... */
unsigned int <API key>;
unsigned int body_vis_column;
unsigned int body_line_first_nws;
/* If we can't determine it, don't issue a warning. This is sometimes
the case for input files containing #line directives, and these
are often for autogenerated sources (e.g. from .md files), where
it's not clear that it's meaningful to look at indentation. */
if (!get_visual_column (next_stmt_exploc, &<API key>))
return false;
if (!get_visual_column (body_exploc,
&body_vis_column,
&body_line_first_nws))
return false;
if ((body_type != CPP_SEMICOLON
&& <API key> == body_vis_column)
/* As a special case handle the case where the body is a semicolon
that may be hidden by a preceding comment, e.g. */
// if (p)
// /* blah */;
// foo (1);
/* by looking instead at the column of the first non-whitespace
character on the body line. */
|| (body_type == CPP_SEMICOLON
&& body_exploc.line > guard_exploc.line
&& body_line_first_nws != body_vis_column
&& <API key> == body_line_first_nws))
{
/* Don't warn if they are aligned on the same column
as the guard itself (suggesting autogenerated code that doesn't
bother indenting at all). We consider the column of the first
non-whitespace character on the guard line instead of the column
of the actual guard token itself because it is more sensible.
Consider:
if (p) {
foo (1);
} else // GUARD
foo (2); // BODY
foo (3); // NEXT
and:
if (p)
foo (1);
} else // GUARD
foo (2); // BODY
foo (3); // NEXT
If we just used the column of the guard token, we would warn on
the first example and not warn on the second. But we want the
exact opposite to happen: to not warn on the first example (which
is probably autogenerated) and to warn on the second (whose
indentation is misleading). Using the column of the first
non-whitespace character on the guard line makes that
happen. */
unsigned int guard_vis_column;
unsigned int <API key>;
if (!get_visual_column (guard_exploc,
&guard_vis_column,
&<API key>))
return false;
if (<API key> == body_vis_column)
return false;
/* We may have something like:
if (p)
{
foo (1);
} else // GUARD
foo (2); // BODY
foo (3); // NEXT
in which case the columns are not aligned but the code is not
misleadingly indented. If the column of the body is less than
that of the guard line then don't warn. */
if (body_vis_column < <API key>)
return false;
/* Don't warn if there is multiline preprocessor logic between
the two statements. */
if (<API key> (body_exploc, next_stmt_exploc))
return false;
/* Otherwise, they are visually aligned: issue a warning. */
return true;
}
/* Also issue a warning for code having the form:
if (flag);
foo ();
while (flag);
{
}
for (...);
{
}
if (flag)
;
else if (flag);
foo ();
where the semicolon at the end of each guard is most likely spurious.
But do not warn on:
for (..);
foo ();
where the next statement is aligned with the guard.
*/
if (body_type == CPP_SEMICOLON)
{
if (body_exploc.line == guard_exploc.line)
{
unsigned int guard_vis_column;
unsigned int <API key>;
if (!get_visual_column (guard_exploc,
&guard_vis_column,
&<API key>))
return false;
if (<API key> > <API key>
|| (next_tok_type == CPP_OPEN_BRACE
&& <API key> == guard_vis_column))
return true;
}
}
}
return false;
}
/* Return the string identifier corresponding to the given guard token. */
static const char *
<API key> (const token_indent_info &guard_tinfo)
{
switch (guard_tinfo.keyword)
{
case RID_FOR:
return "for";
case RID_ELSE:
return "else";
case RID_IF:
return "if";
case RID_WHILE:
return "while";
case RID_DO:
return "do";
default:
gcc_unreachable ();
}
}
/* Called by the C/C++ frontends when we have a guarding statement at
GUARD_LOC containing a statement at BODY_LOC, where the block wasn't
written using braces, like this:
if (flag)
foo ();
along with the location of the next token, at NEXT_STMT_LOC,
so that we can detect followup statements that are within
the same "visual block" as the guarded statement, but which
aren't logically grouped within the guarding statement, such
as:
GUARD_LOC
|
V
if (flag)
foo (); <- BODY_LOC
bar (); <- NEXT_STMT_LOC
In the above, "bar ();" isn't guarded by the "if", but
is indented to misleadingly suggest that it is in the same
block as "foo ();".
GUARD_KIND identifies the kind of clause e.g. "if", "else" etc. */
void
<API key> (const token_indent_info &guard_tinfo,
const token_indent_info &body_tinfo,
const token_indent_info &next_tinfo)
{
/* Early reject for the case where -<API key> is disabled,
to avoid doing work only to have the warning suppressed inside the
diagnostic machinery. */
if (!<API key>)
return;
if (<API key> (guard_tinfo,
body_tinfo,
next_tinfo))
{
if (warning_at (next_tinfo.location, <API key>,
"statement is indented as if it were guarded by..."))
inform (guard_tinfo.location,
"...this %qs clause, but it is not",
<API key> (guard_tinfo));
}
} |
/* ScriptData
SDName: Boss_DrekThar
SD%Complete: 50%
SDComment:
EndScriptData */
#include "ScriptPCH.h"
enum Spells
{
SPELL_WHIRLWIND = 15589,
SPELL_WHIRLWIND2 = 13736,
SPELL_KNOCKDOWN = 19128,
SPELL_FRENZY = 8269,
<API key> = 18765, // not sure
SPELL_CLEAVE = 20677, // not sure
SPELL_WINDFURY = 35886, // not sure
SPELL_STORMPIKE = 51876 // not sure
};
enum Yells
{
YELL_AGGRO = -1810000,
YELL_EVADE = -1810001,
YELL_RESPAWN = -1810002,
YELL_RANDOM1 = -1810003,
YELL_RANDOM2 = -1810004,
YELL_RANDOM3 = -1810005,
YELL_RANDOM4 = -1810006,
YELL_RANDOM5 = -1810007
};
struct boss_drektharAI : public ScriptedAI
{
boss_drektharAI(Creature *c) : ScriptedAI(c) {}
uint32 uiWhirlwindTimer;
uint32 uiWhirlwind2Timer;
uint32 uiKnockdownTimer;
uint32 uiFrenzyTimer;
uint32 uiYellTimer;
uint32 uiResetTimer;
void Reset()
{
uiWhirlwindTimer = urand(1*IN_MILLISECONDS,20*IN_MILLISECONDS);
uiWhirlwind2Timer = urand(1*IN_MILLISECONDS,20*IN_MILLISECONDS);
uiKnockdownTimer = 12*IN_MILLISECONDS;
uiFrenzyTimer = 6*IN_MILLISECONDS;
uiResetTimer = 5*IN_MILLISECONDS;
uiYellTimer = urand(20*IN_MILLISECONDS,30*IN_MILLISECONDS); //20 to 30 seconds
}
void EnterCombat(Unit * /*who*/)
{
DoScriptText(YELL_AGGRO, me);
}
void JustRespawned()
{
Reset();
DoScriptText(YELL_RESPAWN, me);
}
void UpdateAI(const uint32 diff)
{
if (!UpdateVictim())
return;
if (uiWhirlwindTimer <= diff)
{
DoCast(me->getVictim(), SPELL_WHIRLWIND);
uiWhirlwindTimer = urand(8*IN_MILLISECONDS,18*IN_MILLISECONDS);
} else uiWhirlwindTimer -= diff;
if (uiWhirlwind2Timer <= diff)
{
DoCast(me->getVictim(), SPELL_WHIRLWIND2);
uiWhirlwind2Timer = urand(7*IN_MILLISECONDS,25*IN_MILLISECONDS);
} else uiWhirlwind2Timer -= diff;
if (uiKnockdownTimer <= diff)
{
DoCast(me->getVictim(), SPELL_KNOCKDOWN);
uiKnockdownTimer = urand(10*IN_MILLISECONDS,15*IN_MILLISECONDS);
} else uiKnockdownTimer -= diff;
if (uiFrenzyTimer <= diff)
{
DoCast(me->getVictim(), SPELL_FRENZY);
uiFrenzyTimer = urand(20*IN_MILLISECONDS,30*IN_MILLISECONDS);
} else uiFrenzyTimer -= diff;
if (uiYellTimer <= diff)
{
DoScriptText(RAND(YELL_RANDOM1,YELL_RANDOM2,YELL_RANDOM3,YELL_RANDOM4,YELL_RANDOM5), me);
uiYellTimer = urand(20*IN_MILLISECONDS,30*IN_MILLISECONDS); //20 to 30 seconds
} else uiYellTimer -= diff;
// check if creature is not outside of building
if (uiResetTimer <= diff)
{
if (me->GetDistance2d(me->GetHomePosition().GetPositionX(), me->GetHomePosition().GetPositionY()) > 50)
{
EnterEvadeMode();
DoScriptText(YELL_EVADE, me);
}
uiResetTimer = 5*IN_MILLISECONDS;
} else uiResetTimer -= diff;
<API key>();
}
};
CreatureAI* GetAI_boss_drekthar(Creature* pCreature)
{
return new boss_drektharAI (pCreature);
}
void AddSC_boss_drekthar()
{
Script *newscript;
newscript = new Script;
newscript->Name = "boss_drekthar";
newscript->GetAI = &GetAI_boss_drekthar;
newscript->RegisterSelf();
} |
/*
* VESA text modes
*/
#include "boot.h"
#include "video.h"
#include "vesa.h"
/* VESA information */
static struct vesa_general_info vginfo;
static struct vesa_mode_info vminfo;
static __videocard video_vesa;
#ifndef _WAKEUP
static void <API key>(void);
#else /* _WAKEUP */
static inline void <API key>(void) {}
#endif /* _WAKEUP */
static int vesa_probe(void)
{
struct biosregs ireg, oreg;
u16 mode;
addr_t mode_ptr;
struct mode_info *mi;
int nmodes = 0;
video_vesa.modes = GET_HEAP(struct mode_info, 0);
initregs(&ireg);
ireg.ax = 0x4f00;
ireg.di = (size_t)&vginfo;
intcall(0x10, &ireg, &oreg);
if (oreg.ax != 0x004f ||
vginfo.signature != VESA_MAGIC ||
vginfo.version < 0x0102)
return 0; /* Not present */
set_fs(vginfo.video_mode_ptr.seg);
mode_ptr = vginfo.video_mode_ptr.off;
while ((mode = rdfs16(mode_ptr)) != 0xffff) {
mode_ptr += 2;
if (!heap_free(sizeof(struct mode_info)))
break; /* Heap full, can't save mode info */
if (mode & ~0x1ff)
continue;
memset(&vminfo, 0, sizeof vminfo); /* Just in case... */
ireg.ax = 0x4f01;
ireg.cx = mode;
ireg.di = (size_t)&vminfo;
intcall(0x10, &ireg, &oreg);
if (oreg.ax != 0x004f)
continue;
if ((vminfo.mode_attr & 0x15) == 0x05) {
/* Text Mode, TTY BIOS supported,
supported by hardware */
mi = GET_HEAP(struct mode_info, 1);
mi->mode = mode + VIDEO_FIRST_VESA;
mi->depth = 0; /* text */
mi->x = vminfo.h_res;
mi->y = vminfo.v_res;
nmodes++;
} else if ((vminfo.mode_attr & 0x99) == 0x99 &&
(vminfo.memory_layout == 4 ||
vminfo.memory_layout == 6) &&
vminfo.memory_planes == 1) {
#ifdef <API key>
/* Graphics mode, color, linear frame buffer
supported. Only register the mode if
if framebuffer is configured, however,
otherwise the user will be left without a screen. */
mi = GET_HEAP(struct mode_info, 1);
mi->mode = mode + VIDEO_FIRST_VESA;
mi->depth = vminfo.bpp;
mi->x = vminfo.h_res;
mi->y = vminfo.v_res;
nmodes++;
#endif
}
}
return nmodes;
}
static int vesa_set_mode(struct mode_info *mode)
{
struct biosregs ireg, oreg;
int is_graphic;
u16 vesa_mode = mode->mode - VIDEO_FIRST_VESA;
memset(&vminfo, 0, sizeof vminfo); /* Just in case... */
initregs(&ireg);
ireg.ax = 0x4f01;
ireg.cx = vesa_mode;
ireg.di = (size_t)&vminfo;
intcall(0x10, &ireg, &oreg);
if (oreg.ax != 0x004f)
return -1;
if ((vminfo.mode_attr & 0x15) == 0x05) {
/* It's a supported text mode */
is_graphic = 0;
#ifdef <API key>
} else if ((vminfo.mode_attr & 0x99) == 0x99) {
/* It's a graphics mode with linear frame buffer */
is_graphic = 1;
vesa_mode |= 0x4000; /* Request linear frame buffer */
#endif
} else {
return -1; /* Invalid mode */
}
initregs(&ireg);
ireg.ax = 0x4f02;
ireg.bx = vesa_mode;
intcall(0x10, &ireg, &oreg);
if (oreg.ax != 0x004f)
return -1;
graphic_mode = is_graphic;
if (!is_graphic) {
/* Text mode */
force_x = mode->x;
force_y = mode->y;
do_restore = 1;
} else {
/* Graphics mode */
<API key>();
}
return 0;
}
#ifndef _WAKEUP
/* Switch DAC to 8-bit mode */
static void vesa_dac_set_8bits(void)
{
struct biosregs ireg, oreg;
u8 dac_size = 6;
/* If possible, switch the DAC to 8-bit mode */
if (vginfo.capabilities & 1) {
initregs(&ireg);
ireg.ax = 0x4f08;
ireg.bh = 0x08;
intcall(0x10, &ireg, &oreg);
if (oreg.ax == 0x004f)
dac_size = oreg.bh;
}
/* Set the color sizes to the DAC size, and offsets to 0 */
boot_params.screen_info.red_size = dac_size;
boot_params.screen_info.green_size = dac_size;
boot_params.screen_info.blue_size = dac_size;
boot_params.screen_info.rsvd_size = dac_size;
boot_params.screen_info.red_pos = 0;
boot_params.screen_info.green_pos = 0;
boot_params.screen_info.blue_pos = 0;
boot_params.screen_info.rsvd_pos = 0;
}
/* Save the VESA protected mode info */
static void vesa_store_pm_info(void)
{
struct biosregs ireg, oreg;
initregs(&ireg);
ireg.ax = 0x4f0a;
intcall(0x10, &ireg, &oreg);
if (oreg.ax != 0x004f)
return;
boot_params.screen_info.vesapm_seg = oreg.es;
boot_params.screen_info.vesapm_off = oreg.di;
boot_params.screen_info.vesapm_size = oreg.cx;
}
/*
* Save video mode parameters for graphics mode
*/
static void <API key>(void)
{
/* Tell the kernel we're in VESA graphics mode */
boot_params.screen_info.orig_video_isVGA = VIDEO_TYPE_VLFB;
/* Mode parameters */
boot_params.screen_info.vesa_attributes = vminfo.mode_attr;
boot_params.screen_info.lfb_linelength = vminfo.logical_scan;
boot_params.screen_info.lfb_width = vminfo.h_res;
boot_params.screen_info.lfb_height = vminfo.v_res;
boot_params.screen_info.lfb_depth = vminfo.bpp;
boot_params.screen_info.pages = vminfo.image_planes;
boot_params.screen_info.lfb_base = vminfo.lfb_ptr;
memcpy(&boot_params.screen_info.red_size,
&vminfo.rmask, 8);
/* General parameters */
boot_params.screen_info.lfb_size = vginfo.total_memory;
if (vminfo.bpp <= 8)
vesa_dac_set_8bits();
vesa_store_pm_info();
}
/*
* Save EDID information for the kernel; this is invoked, separately,
* after mode-setting.
*/
void vesa_store_edid(void)
{
#ifdef <API key>
struct biosregs ireg, oreg;
/* Apparently used as a nonsense token... */
memset(&boot_params.edid_info, 0x13, sizeof boot_params.edid_info);
if (vginfo.version < 0x0200)
return; /* EDID requires VBE 2.0+ */
initregs(&ireg);
ireg.ax = 0x4f15; /* VBE DDC */
/* ireg.bx = 0x0000; */ /* Report DDC capabilities */
/* ireg.cx = 0; */ /* Controller 0 */
ireg.es = 0; /* ES:DI must be 0 by spec */
intcall(0x10, &ireg, &oreg);
if (oreg.ax != 0x004f)
return; /* No EDID */
/* BH = time in seconds to transfer EDD information */
/* BL = DDC level supported */
ireg.ax = 0x4f15; /* VBE DDC */
ireg.bx = 0x0001; /* Read EDID */
/* ireg.cx = 0; */ /* Controller 0 */
/* ireg.dx = 0; */ /* EDID block number */
ireg.es = ds();
ireg.di =(size_t)&boot_params.edid_info; /* (ES:)Pointer to block */
intcall(0x10, &ireg, &oreg);
#endif /* <API key> */
}
#endif /* not _WAKEUP */
static __videocard video_vesa =
{
.card_name = "VESA",
.probe = vesa_probe,
.set_mode = vesa_set_mode,
.xmode_first = VIDEO_FIRST_VESA,
.xmode_n = 0x200,
}; |
# This file is part of Buildbot. Buildbot is free software: you can
# redistribute it and/or modify it under the terms of the GNU General Public
# This program is distributed in the hope that it will be useful, but WITHOUT
# details.
# this program; if not, write to the Free Software Foundation, Inc., 51
# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
from __future__ import absolute_import
from __future__ import print_function
from sqlalchemy.exc import OperationalError
from sqlalchemy.exc import ProgrammingError
from buildbot.config import MasterConfig
from buildbot.db import enginestrategy
from buildbot.db import model
from buildbot.db import state
class FakeDBConnector(object):
pass
class FakeCacheManager(object):
def get_cache(self, cache_name, miss_fn):
return None
class FakeMaster(object):
pass
class FakePool(object):
pass
class DbConfig(object):
def __init__(self, BuildmasterConfig, basedir, name="config"):
self.db_url = MasterConfig.getDbUrlFromConfig(
BuildmasterConfig, throwErrors=False)
self.basedir = basedir
self.name = name
def getDb(self):
try:
db_engine = enginestrategy.create_engine(self.db_url,
basedir=self.basedir)
except Exception:
# db_url is probably trash. Just ignore, config.py db part will
# create proper message
return None
db = FakeDBConnector()
db.master = FakeMaster()
db.pool = FakePool()
db.pool.engine = db_engine
db.master.caches = FakeCacheManager()
db.model = model.Model(db)
db.state = state.<API key>(db)
try:
self.objectid = db.state.thdGetObjectId(
db_engine, self.name, "DbConfig")['id']
except (ProgrammingError, OperationalError):
# ProgrammingError: mysql&pg, OperationalError: sqlite
# assume db is not initialized
db.pool.engine.close()
return None
return db
def get(self, name, default=state.<API key>.Thunk):
db = self.getDb()
if db is not None:
ret = db.state.thdGetState(
db.pool.engine, self.objectid, name, default=default)
db.pool.engine.close()
else:
if default is not state.<API key>.Thunk:
return default
raise KeyError("Db not yet initialized")
return ret
def set(self, name, value):
db = self.getDb()
if db is not None:
db.state.thdSetState(db.pool.engine, self.objectid, name, value)
db.pool.engine.close() |
<?php
/**
* BuddyPress - Create Group
*
* @package BuddyPress
* @subpackage bp-default
*/
get_header( 'buddypress' ); ?>
<div id="content" role="main" class="<?php do_action( 'content_class' ); ?>">
<div class="padder">
<?php do_action( '<API key>' ); ?>
<form action="<?php <API key>(); ?>" method="post" id="create-group-form" class="standard-form" enctype="multipart/form-data">
<h3><?php _e( 'Create a Group', 'buddypress' ); ?> <a class="button" href="<?php echo trailingslashit( bp_get_root_domain() . '/' . <API key>() ); ?>"><?php _e( 'Groups Directory', 'buddypress' ); ?></a></h3>
<?php do_action( '<API key>' ); ?>
<div class="item-list-tabs no-ajax" id="group-create-tabs" role="navigation">
<ul>
<?php <API key>(); ?>
</ul>
</div>
<?php do_action( 'template_notices' ); ?>
<div class="item-body" id="group-create-body">
<?php /* Group creation step 1: Basic group details */ ?>
<?php if ( <API key>( 'group-details' ) ) : ?>
<?php do_action( '<API key>' ); ?>
<label for="group-name"><?php _e( 'Group Name (required)', 'buddypress' ); ?></label>
<input type="text" name="group-name" id="group-name" aria-required="true" value="<?php bp_new_group_name(); ?>" />
<label for="group-desc"><?php _e( 'Group Description (required)', 'buddypress' ); ?></label>
<textarea name="group-desc" id="group-desc" aria-required="true"><?php <API key>(); ?></textarea>
<?php
do_action( '<API key>' );
do_action( '<API key>' ); // @Deprecated
wp_nonce_field( '<API key>' ); ?>
<?php endif; ?>
<?php /* Group creation step 2: Group settings */ ?>
<?php if ( <API key>( 'group-settings' ) ) : ?>
<?php do_action( '<API key>' ); ?>
<h4><?php _e( 'Privacy Options', 'buddypress' ); ?></h4>
<div class="radio">
<label><input type="radio" name="group-status" value="public"<?php if ( 'public' == <API key>() || !<API key>() ) { ?> checked="checked"<?php } ?> />
<strong><?php _e( 'This is a public group', 'buddypress' ); ?></strong>
<ul>
<li><?php _e( 'Any site member can join this group.', 'buddypress' ); ?></li>
<li><?php _e( 'This group will be listed in the groups directory and in search results.', 'buddypress' ); ?></li>
<li><?php _e( 'Group content and activity will be visible to any site member.', 'buddypress' ); ?></li>
</ul>
</label>
<label><input type="radio" name="group-status" value="private"<?php if ( 'private' == <API key>() ) { ?> checked="checked"<?php } ?> />
<strong><?php _e( 'This is a private group', 'buddypress' ); ?></strong>
<ul>
<li><?php _e( 'Only users who request membership and are accepted can join the group.', 'buddypress' ); ?></li>
<li><?php _e( 'This group will be listed in the groups directory and in search results.', 'buddypress' ); ?></li>
<li><?php _e( 'Group content and activity will only be visible to members of the group.', 'buddypress' ); ?></li>
</ul>
</label>
<label><input type="radio" name="group-status" value="hidden"<?php if ( 'hidden' == <API key>() ) { ?> checked="checked"<?php } ?> />
<strong><?php _e('This is a hidden group', 'buddypress'); ?></strong>
<ul>
<li><?php _e( 'Only users who are invited can join the group.', 'buddypress' ); ?></li>
<li><?php _e( 'This group will not be listed in the groups directory or search results.', 'buddypress' ); ?></li>
<li><?php _e( 'Group content and activity will only be visible to members of the group.', 'buddypress' ); ?></li>
</ul>
</label>
</div>
<h4><?php _e( 'Group Invitations', 'buddypress' ); ?></h4>
<p><?php _e( 'Which members of this group are allowed to invite others?', 'buddypress' ); ?></p>
<div class="radio">
<label>
<input type="radio" name="group-invite-status" value="members"<?php <API key>( 'members' ); ?> />
<strong><?php _e( 'All group members', 'buddypress' ); ?></strong>
</label>
<label>
<input type="radio" name="group-invite-status" value="mods"<?php <API key>( 'mods' ); ?> />
<strong><?php _e( 'Group admins and mods only', 'buddypress' ); ?></strong>
</label>
<label>
<input type="radio" name="group-invite-status" value="admins"<?php <API key>( 'admins' ); ?> />
<strong><?php _e( 'Group admins only', 'buddypress' ); ?></strong>
</label>
</div>
<?php if ( bp_is_active( 'forums' ) ) : ?>
<h4><?php _e( 'Group Forums', 'buddypress' ); ?></h4>
<?php if ( <API key>() ) : ?>
<p><?php _e( 'Should this group have a forum?', 'buddypress' ); ?></p>
<div class="checkbox">
<label><input type="checkbox" name="group-show-forum" id="group-show-forum" value="1"<?php checked( <API key>(), true, true ); ?> /> <?php _e( 'Enable discussion forum', 'buddypress' ); ?></label>
</div>
<?php elseif ( is_super_admin() ) : ?>
<p><?php printf( __( '<strong>Attention Site Admin:</strong> Group forums require the <a href="%s">correct setup and configuration</a> of a bbPress installation.', 'buddypress' ), <API key>() ? network_admin_url( 'settings.php?page=bb-forums-setup' ) : admin_url( 'admin.php?page=bb-forums-setup' ) ); ?></p>
<?php endif; ?>
<?php endif; ?>
<?php do_action( '<API key>' ); ?>
<?php wp_nonce_field( '<API key>' ); ?>
<?php endif; ?>
<?php /* Group creation step 3: Avatar Uploads */ ?>
<?php if ( <API key>( 'group-avatar' ) ) : ?>
<?php do_action( '<API key>' ); ?>
<?php if ( 'upload-image' == <API key>() ) : ?>
<div class="left-menu">
<?php bp_new_group_avatar(); ?>
</div><!-- .left-menu -->
<div class="main-column">
<p><?php _e( "Upload an image to use as an avatar for this group. The image will be shown on the main group page, and in search results.", 'buddypress' ); ?></p>
<p>
<input type="file" name="file" id="file" />
<input type="submit" name="upload" id="upload" value="<?php _e( 'Upload Image', 'buddypress' ); ?>" />
<input type="hidden" name="action" id="action" value="bp_avatar_upload" />
</p>
<p><?php _e( 'To skip the avatar upload process, hit the "Next Step" button.', 'buddypress' ); ?></p>
</div><!-- .main-column -->
<?php endif; ?>
<?php if ( 'crop-image' == <API key>() ) : ?>
<h3><?php _e( 'Crop Group Avatar', 'buddypress' ); ?></h3>
<img src="<?php bp_avatar_to_crop(); ?>" id="avatar-to-crop" class="avatar" alt="<?php _e( 'Avatar to crop', 'buddypress' ); ?>" />
<div id="avatar-crop-pane">
<img src="<?php bp_avatar_to_crop(); ?>" id="avatar-crop-preview" class="avatar" alt="<?php _e( 'Avatar preview', 'buddypress' ); ?>" />
</div>
<input type="submit" name="avatar-crop-submit" id="avatar-crop-submit" value="<?php _e( 'Crop Image', 'buddypress' ); ?>" />
<input type="hidden" name="image_src" id="image_src" value="<?php <API key>(); ?>" />
<input type="hidden" name="upload" id="upload" />
<input type="hidden" id="x" name="x" />
<input type="hidden" id="y" name="y" />
<input type="hidden" id="w" name="w" />
<input type="hidden" id="h" name="h" />
<?php endif; ?>
<?php do_action( '<API key>' ); ?>
<?php wp_nonce_field( '<API key>' ); ?>
<?php endif; ?>
<?php /* Group creation step 4: Invite friends to group */ ?>
<?php if ( <API key>( 'group-invites' ) ) : ?>
<?php do_action( '<API key>' ); ?>
<?php if ( bp_is_active( 'friends' ) && <API key>( bp_loggedin_user_id() ) ) : ?>
<div class="left-menu">
<div id="invite-list">
<ul>
<?php <API key>(); ?>
</ul>
<?php wp_nonce_field( '<API key>', '<API key>' ); ?>
</div>
</div><!-- .left-menu -->
<div class="main-column">
<div id="message" class="info">
<p><?php _e('Select people to invite from your friends list.', 'buddypress'); ?></p>
</div>
<?php /* The ID 'friend-list' is important for AJAX support. */ ?>
<ul id="friend-list" class="item-list" role="main">
<?php if ( <API key>() ) : ?>
<?php while ( bp_group_invites() ) : bp_group_the_invite(); ?>
<li id="<?php <API key>(); ?>">
<?php <API key>(); ?>
<h4><?php <API key>(); ?></h4>
<span class="activity"><?php <API key>(); ?></span>
<div class="action">
<a class="remove" href="<?php <API key>(); ?>" id="<?php <API key>(); ?>"><?php _e( 'Remove Invite', 'buddypress' ); ?></a>
</div>
</li>
<?php endwhile; ?>
<?php wp_nonce_field( 'groups_send_invites', '<API key>' ); ?>
<?php endif; ?>
</ul>
</div><!-- .main-column -->
<?php else : ?>
<div id="message" class="info">
<p><?php _e( 'Once you have built up friend connections you will be able to invite others to your group.', 'buddypress' ); ?></p>
</div>
<?php endif; ?>
<?php wp_nonce_field( '<API key>' ); ?>
<?php do_action( '<API key>' ); ?>
<?php endif; ?>
<?php do_action( '<API key>' ); // Allow plugins to add custom group creation steps ?>
<?php do_action( '<API key>' ); ?>
<?php if ( 'crop-image' != <API key>() ) : ?>
<div class="submit" id="previous-next">
<?php /* Previous Button */ ?>
<?php if ( !<API key>() ) : ?>
<input type="button" value="<?php _e( 'Back to Previous Step', 'buddypress' ); ?>" id="<API key>" name="previous" onclick="location.href='<?php <API key>(); ?>'" />
<?php endif; ?>
<?php /* Next Button */ ?>
<?php if ( !<API key>() && !<API key>() ) : ?>
<input type="submit" value="<?php _e( 'Next Step', 'buddypress' ); ?>" id="group-creation-next" name="save" />
<?php endif;?>
<?php /* Create Button */ ?>
<?php if ( <API key>() ) : ?>
<input type="submit" value="<?php _e( 'Create Group and Continue', 'buddypress' ); ?>" id="<API key>" name="save" />
<?php endif; ?>
<?php /* Finish Button */ ?>
<?php if ( <API key>() ) : ?>
<input type="submit" value="<?php _e( 'Finish', 'buddypress' ); ?>" id="<API key>" name="save" />
<?php endif; ?>
</div>
<?php endif;?>
<?php do_action( '<API key>' ); ?>
<?php /* Don't leave out this hidden field */ ?>
<input type="hidden" name="group_id" id="group_id" value="<?php bp_new_group_id(); ?>" />
<?php do_action( '<API key>' ); ?>
</div><!-- .item-body -->
<?php do_action( '<API key>' ); ?>
</form>
<?php do_action( '<API key>' ); ?>
</div><!-- .padder -->
</div><!-- #content -->
<?php get_sidebar( 'buddypress' ); ?>
<?php get_footer( 'buddypress' ); ?> |
import maya.cmds as cmds
import maya.utils as utils
import threading
import time
import sys
from PyQt4 import QtCore, QtGui
pumpedThread = None
app = None
def pumpQt():
global app
def processor():
app.processEvents()
while 1:
time.sleep(0.01)
utils.executeDeferred( processor )
def <API key>():
global pumpedThread
global app
if pumpedThread == None:
app = QtGui.QApplication(sys.argv)
pumpedThread = threading.Thread( target = pumpQt, args = () )
pumpedThread.start() |
#!/usr/bin/env python
# This program is free software; you can redistribute it and/or modify it
# option) any later version.
# This program is distributed in the hope that it will be useful, but
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
"""Prints an RST table of available distributions from the distributions
module.
"""
from __future__ import (print_function, absolute_import)
from pycbc.distributions import distribs
from _dict_to_rst import (rst_dict_table, format_class)
tbl = rst_dict_table(distribs, key_format='``\'{0}\'``'.format,
header=('Name', 'Class'),
val_format=format_class)
filename = 'distributions-table.rst'
with open(filename, 'w') as fp:
print(tbl, file=fp) |
-*- tab-width: 4; Mode: C++; c-basic-offset: 4; indent-tabs-mode: nil -*-
#include <AP_HAL.h>
#include <AC_Fence.h>
extern const AP_HAL::HAL& hal;
const AP_Param::GroupInfo AC_Fence::var_info[] PROGMEM = {
// @Param: ENABLE
// @DisplayName: Fence enable/disable
// @Description: Allows you to enable (1) or disable (0) the fence functionality
// @Values: 0:Disabled,1:Enabled
// @User: Standard
AP_GROUPINFO("ENABLE", 0, AC_Fence, _enabled, 0),
// @Param: TYPE
// @DisplayName: Fence Type
// @Description: Enabled fence types held as bitmask
// @Values: 0:None,1:Altitude,2:Circle,3:Altitude and Circle
// @User: Standard
AP_GROUPINFO("TYPE", 1, AC_Fence, _enabled_fences, <API key> | <API key>),
// @Param: ACTION
// @DisplayName: Action to perform when the limit is breached
// @Description: What to do on fence breach
// @Values: 0:Report Only,1:RTL or Land
// @User: Standard
AP_GROUPINFO("ACTION", 2, AC_Fence, _action, <API key>),
// @Param: ALT_MAX
// @DisplayName: Fence Maximum Altitude
// @Description: Maximum altitude allowed before geofence triggers
// @Units: Meters
// @Range: 10 1000
// @Increment: 1
// @User: Standard
AP_GROUPINFO("ALT_MAX", 3, AC_Fence, _alt_max, <API key>),
// @Param: RADIUS
// @DisplayName: Circular Fence Radius
// @Description: Circle fence radius which when breached will cause an RTL
// @Units: Meters
// @Range: 0 10000
// @User: Standard
AP_GROUPINFO("RADIUS", 4, AC_Fence, _circle_radius, <API key>),
AP_GROUPEND
};
Default constructor.
AC_Fence::AC_Fence(AP_InertialNav* inav) :
_inav(inav),
_alt_max_backup(0),
<API key>(0),
<API key>(0),
<API key>(0),
_home_distance(0),
_breached_fences(AC_FENCE_TYPE_NONE),
_breach_time(0),
_breach_count(0)
{
AP_Param::<API key>(this, var_info);
// check for silly fence values
if (_alt_max < 0) {
_alt_max.set_and_save(<API key>);
}
if (_circle_radius < 0) {
_circle_radius.set_and_save(<API key>);
}
}
get_enabled_fences - returns bitmask of enabled fences
uint8_t AC_Fence::get_enabled_fences() const
{
if (!_enabled) {
return AC_FENCE_TYPE_NONE;
}else{
return _enabled_fences;
}
}
pre_arm_check - returns true if all pre-takeoff checks have completed successfully
bool AC_Fence::pre_arm_check() const
{
// if not enabled or not fence set-up always return true
if (!_enabled || _enabled_fences == AC_FENCE_TYPE_NONE) {
return true;
}
// check no limits are currently breached
if (_breached_fences != AC_FENCE_TYPE_NONE) {
return false;
}
// if we have horizontal limits enabled, check inertial nav position is ok
if ((_enabled_fences & <API key>)!=0 && !_inav->position_ok()) {
return false;
}
// if we got this far everything must be ok
return true;
}
check_fence - returns the fence type that has been breached (if any)
uint8_t AC_Fence::check_fence()
{
uint8_t ret = AC_FENCE_TYPE_NONE;
// return immediately if disabled
if (!_enabled || _enabled_fences == AC_FENCE_TYPE_NONE) {
return AC_FENCE_TYPE_NONE;
}
// get current altitude in meters
float curr_alt = _inav->get_position().z * 0.01f;
// altitude fence check
if ((_enabled_fences & <API key>) != 0) {
// check if we are over the altitude fence
if( curr_alt >= _alt_max ) {
// record distance above breach
<API key> = curr_alt - _alt_max;
// check for a new breach or a breach of the backup fence
if ((_breached_fences & <API key>) == 0 || (_alt_max_backup != 0 && curr_alt >= _alt_max_backup)) {
// record that we have breached the upper limit
record_breach(<API key>);
ret = ret | <API key>;
// create a backup fence 20m higher up
_alt_max_backup = curr_alt + <API key>;
}
}else{
// clear alt breach if present
if ((_breached_fences & <API key>) != 0) {
clear_breach(<API key>);
_alt_max_backup = 0;
<API key> = 0;
}
}
}
// circle fence check
if ((_enabled_fences & <API key>) != 0 ) {
// check if we are outside the fence
if (_home_distance >= _circle_radius) {
// record distance outside the fence
<API key> = _home_distance - _circle_radius;
// check for a new breach or a breach of the backup fence
if ((_breached_fences & <API key>) == 0 || (<API key> != 0 && _home_distance >= <API key>)) {
// record that we have breached the circular distance limit
record_breach(<API key>);
ret = ret | <API key>;
// create a backup fence 20m further out
<API key> = _home_distance + <API key>;
}
}else{
// clear circle breach if present
if ((_breached_fences & <API key>) != 0) {
clear_breach(<API key>);
<API key> = 0;
<API key> = 0;
}
}
}
// return any new breaches that have occurred
return ret;
// To-Do: add min alt and polygon check
//outside = Polygon_outside(location, &geofence_state->boundary[1], geofence_state->num_points-1);
}
record_breach - update breach bitmask, time and count
void AC_Fence::record_breach(uint8_t fence_type)
{
// if we haven't already breached a limit, update the breach time
if (_breached_fences == AC_FENCE_TYPE_NONE) {
_breach_time = hal.scheduler->millis();
}
// update breach count
if (_breach_count < 65500) {
_breach_count++;
}
// update bitmask
_breached_fences |= fence_type;
}
clear_breach - update breach bitmask, time and count
void AC_Fence::clear_breach(uint8_t fence_type)
{
// return immediately if this fence type was not breached
if ((_breached_fences & fence_type) == 0) {
return;
}
// update bitmask
_breached_fences &= ~fence_type;
}
get_breach_distance - returns distance in meters outside of the given fence
float AC_Fence::get_breach_distance(uint8_t fence_type) const
{
switch (fence_type) {
case <API key>:
return <API key>;
break;
case <API key>:
return <API key>;
break;
case <API key> | <API key>:
return max(<API key>,<API key>);
}
// we don't recognise the fence type so just return 0
return 0;
} |
#ifndef <API key>
#define <API key>
#include "force.H"
namespace Foam
{
namespace regionModels
{
namespace surfaceFilmModels
{
class <API key>
:
public force
{
private:
// Private member functions
//- Disallow default bitwise copy construct
<API key>(const <API key>&);
//- Disallow default bitwise assignment
void operator=(const <API key>&);
public:
//- Runtime type information
TypeName("thermocapillary");
// Constructors
//- Construct from surface film model
<API key>
(
const surfaceFilmModel& owner,
const dictionary& dict
);
//- Destructor
virtual ~<API key>();
// Member Functions
// Evolution
//- Correct
virtual tmp<fvVectorMatrix> correct(volVectorField& U);
};
} // End namespace surfaceFilmModels
} // End namespace regionModels
} // End namespace Foam
#endif |
#ifndef UCI_H_INCLUDED
#define UCI_H_INCLUDED
#include <map>
#include <string>
#include "types.h"
namespace Stockfish {
class Position;
namespace UCI {
class Option;
Custom comparator because UCI options should be case insensitive
struct CaseInsensitiveLess {
bool operator() (const std::string&, const std::string&) const;
};
Our options container is actually a std::map
typedef std::map<std::string, Option, CaseInsensitiveLess> OptionsMap;
Option class implements an option as defined by UCI protocol
class Option {
typedef void (*OnChange)(const Option&);
public:
Option(OnChange = nullptr);
Option(bool v, OnChange = nullptr);
Option(const char* v, OnChange = nullptr);
Option(double v, int minv, int maxv, OnChange = nullptr);
Option(const char* v, const char* cur, OnChange = nullptr);
Option& operator=(const std::string&);
void operator<<(const Option&);
operator double() const;
operator std::string() const;
bool operator==(const char*) const;
private:
friend std::ostream& operator<<(std::ostream&, const OptionsMap&);
std::string defaultValue, currentValue, type;
int min, max;
size_t idx;
OnChange on_change;
};
void init(OptionsMap&);
void loop(int argc, char* argv[]);
std::string value(Value v);
std::string square(Square s);
std::string move(Move m, bool chess960);
std::string pv(const Position& pos, Depth depth, Value alpha, Value beta);
std::string wdl(Value v, int ply);
Move to_move(const Position& pos, std::string& str);
} // namespace UCI
extern UCI::OptionsMap Options;
} // namespace Stockfish
#endif // #ifndef UCI_H_INCLUDED |
module.exports={A:{A:{"2":"J C G VB","388":"E B A"},B:{"260":"D Y g H L"},C:{"1":"0 1 3 4 5 F I J C G E B A D Y g H L M N O P Q R S T U V W X v Z a b c d e f K h i j k l m n o p q r s x y u t RB QB","2":"TB","4":"z"},D:{"4":"0 1 3 4 5 9 F I J C G E B A D Y g H L M N O P Q R S T U V W X v Z a b c d e f K h i j k l m n o p q r s x y u t FB BB UB CB DB"},E:{"2":"8 EB","4":"F I J C G E B A GB HB IB JB KB LB"},F:{"4":"6 7 E A D H L M N O P Q R S T U V W X v Z a b c d e f K h i j k l m n o p q r s MB NB OB PB SB w"},G:{"4":"2 8 G A AB WB XB YB ZB aB bB cB dB"},H:{"2":"eB"},I:{"2":"2 z F fB gB hB iB","4":"t jB kB"},J:{"1":"B","2":"C"},K:{"4":"6 7 B A D K w"},L:{"4":"9"},M:{"1":"u"},N:{"2":"B A"},O:{"2":"lB"},P:{"4":"F I"},Q:{"4":"mB"},R:{"4":"nB"}},B:2,C:"SVG effects for HTML"}; |
#ifndef <API key>
#define <API key>
#include "../bus/SPIDevice.h"
#include <string>
namespace exploringBB {
/**
* @class LCDCharacterDisplay
* @brief A class that provides an interface to an LCD character module. It provices support
* for multiple rows and columns and provides methods for formatting and printing text. You
* should use a 4 wire interface and a 74XX595 to communicate with the display module.
*/
class LCDCharacterDisplay {
private:
SPIDevice *device; //!< a pointer to the SPI device
int width, height; //!< the width and height of the module in characters
void command(char i);
void setup4bit();
unsigned char cursorState;
unsigned char displayState;
unsigned char entryState;
void writeCursorState();
void writeDisplayState();
void writeEntryState();
public:
LCDCharacterDisplay(SPIDevice *device, int width, int height);
virtual void write(char c);
virtual void print(std::string message);
virtual void clear();
virtual void home();
virtual int setCursorPosition(int row, int column);
virtual void setDisplayOff(bool displayOff);
virtual void setCursorOff(bool cursorOff);
virtual void setCursorBlink(bool isBlink);
virtual void setCursorMoveOff(bool cursorMoveOff);
virtual void setCursorMoveLeft(bool cursorMoveLeft);
virtual void setAutoscroll(bool isAutoscroll);
virtual void <API key>(bool scrollLeft);
virtual ~LCDCharacterDisplay();
};
} /* namespace exploringBB */
#endif /* <API key> */ |
var zrUtil = require('zrender/lib/core/util');
var Axis = require('../Axis');
/**
* @constructor module:echarts/coord/parallel/ParallelAxis
* @extends {module:echarts/coord/Axis}
* @param {string} dim
* @param {*} scale
* @param {Array.<number>} coordExtent
* @param {string} axisType
*/
var ParallelAxis = function (dim, scale, coordExtent, axisType, axisIndex) {
Axis.call(this, dim, scale, coordExtent);
/**
* Axis type
* - 'category'
* - 'value'
* - 'time'
* - 'log'
* @type {string}
*/
this.type = axisType || 'value';
/**
* @type {number}
* @readOnly
*/
this.axisIndex = axisIndex;
};
ParallelAxis.prototype = {
constructor: ParallelAxis,
/**
* Axis model
* @param {module:echarts/coord/parallel/AxisModel}
*/
model: null
};
zrUtil.inherits(ParallelAxis, Axis);
module.exports = ParallelAxis; |
#include "TestState.h"
#include <iostream>
#include <fstream>
#include <SDL.h>
#include "../Engine/Game.h"
#include "../Mod/Mod.h"
#include "../Engine/LocalizedText.h"
#include "../Engine/Palette.h"
#include "../Engine/Screen.h"
#include "../Engine/SurfaceSet.h"
#include "../Engine/Surface.h"
#include "../Engine/Exception.h"
#include "../Interface/TextButton.h"
#include "../Interface/Window.h"
#include "../Interface/Text.h"
#include "../Interface/TextList.h"
#include "../Interface/NumberText.h"
#include "../Interface/Slider.h"
#include "../Interface/ComboBox.h"
namespace OpenXcom
{
/**
* Initializes all the elements in the test screen.
* @param game Pointer to the core game.
*/
TestState::TestState()
{
// Create objects
_window = new Window(this, 300, 180, 10, 10);
_text = new Text(280, 120, 20, 50);
_button = new TextButton(100, 20, 110, 150);
_list = new TextList(300, 180, 10, 10);
_number = new NumberText(50, 5, 200, 25);
_set = _game->getMod()->getSurfaceSet("BASEBITS.PCK");
_set->getFrame(1);
_slider = new Slider(100, 15, 50, 50);
_comboBox = new ComboBox(this, 80, 16, 98, 100);
// Set palette
setPalette("PAL_BASESCAPE", 2);
add(_window);
add(_button);
add(_text);
add(_list);
add(_number);
add(_slider);
add(_comboBox);
centerAllSurfaces();
// Set up objects
_window->setColor(Palette::blockOffset(15)+1);
_window->setBackground(_game->getMod()->getSurface("BACK04.SCR"));
_button->setColor(Palette::blockOffset(15)+1);
_button->setText("LOLOLOL");
_text->setColor(Palette::blockOffset(15)+1);
//_text->setBig();
_text->setWordWrap(true);
_text->setAlign(ALIGN_CENTER);
_text->setVerticalAlign(ALIGN_MIDDLE);
//_text->setText(tr("<API key>"));
_list->setColor(Palette::blockOffset(15)+1);
_list->setColumns(3, 100, 50, 100);
_list->addRow(2, "a", "b");
_list->addRow(3, "lol", "welp", "yo");
_list->addRow(1, "0123456789");
_number->setColor(Palette::blockOffset(15) + 1);
_number->setValue(1234567890);
_slider->setColor(Palette::blockOffset(15)+1);
std::vector<std::string> difficulty;
for (int i = 0; i != 3; ++i)
{
difficulty.push_back(tr("STR_1_BEGINNER"));
difficulty.push_back(tr("STR_2_EXPERIENCED"));
difficulty.push_back(tr("STR_3_VETERAN"));
difficulty.push_back(tr("STR_4_GENIUS"));
difficulty.push_back(tr("STR_5_SUPERHUMAN"));
}
_comboBox->setColor(Palette::blockOffset(15)+1);
_comboBox->setOptions(difficulty);
_i = 0;
//_game->getMod()->getPalette("PAL_GEOSCAPE")->savePal("../../../Geoscape.pal");
//_game->getMod()->getPalette("PAL_BASESCAPE")->savePal("../../../Basescape.pal");
//_game->getMod()->getPalette("PAL_UFOPAEDIA")->savePal("../../../Ufopaedia.pal");
//_game->getMod()->getPalette("PAL_BATTLESCAPE")->savePal("../../../Battlescape.pal");
//_game->getMod()->getFont("FONT_BIG")->fix("../../../Big.bmp", 256);
//_game->getMod()->getFont("FONT_SMALL")->fix("../../../Small.bmp", 128);
}
TestState::~TestState()
{
}
void TestState::think()
{
State::think();
/*
_text->setText(tr(_i));
_i++;
*/
}
void TestState::blit()
{
State::blit();
_set->getFrame(0)->blit(_game->getScreen()->getSurface());
}
/**
* Generates a surface with a row of every single color currently
* loaded in the game palette (like a rainbow). First used for
* testing 8bpp functionality, still useful for debugging palette issues.
* @return Test surface.
*/
SDL_Surface *TestState::testSurface()
{
SDL_Surface *surface;
// Create surface
surface = <API key>(SDL_HWSURFACE, 256, 25, 8, 0, 0, 0, 0);
if (surface == 0)
{
throw Exception(SDL_GetError());
}
// Lock the surface
SDL_LockSurface(surface);
Uint8 *index = (Uint8 *)surface->pixels;
for (int j = 0; j < 25; ++j)
for (int i = 0; i < 256; i++, ++index)
*index = i;
// Unlock the surface
SDL_UnlockSurface(surface);
return surface;
}
} |
# revision identifiers, used by Alembic.
revision = '223041bb858b'
down_revision = '2c9f3a06de09'
from alembic import op
import sqlalchemy as sa
def upgrade():
op.create_table(
'<API key>',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('contact_id', sa.Integer(), nullable=False),
sa.Column('message_id', sa.Integer(), nullable=False),
sa.Column('field',
sa.Enum('from_addr', 'to_addr', 'cc_addr', 'bcc_addr'),
nullable=True),
sa.<API key>(['contact_id'], ['contact.id'], ),
sa.<API key>(['message_id'], ['message.id'], ),
sa.<API key>('id', 'contact_id', 'message_id')
)
# Yes, this is a terrible hack. But tools/rerank_contacts.py already
# contains a script to process contacts from messages, so it's very
# expedient.
import sys
sys.path.append('./tools')
from rerank_contacts import rerank_contacts
rerank_contacts()
def downgrade():
op.drop_table('<API key>') |
module FeatureFlags
extend ActiveSupport::Concern
class_methods do
def feature_flag(name, *options)
before_action(*options) do
check_feature_flag(name)
end
end
end
def check_feature_flag(name)
raise FeatureDisabled, name unless Setting["feature.#{name}"]
end
class FeatureDisabled < Exception
def initialize(name)
@name = name
end
def message
"Feature disabled: #{@name}"
end
end
end |
#include "<API key>.h"
#include <moses/comboreduct/type_checker/type_tree.h>
using namespace opencog::combo;
using namespace <API key>;
<API key>::<API key>() { }
const <API key>* <API key>::<API key>() const
{
return asbd;
}
unsigned int <API key>::<API key>() const
{
return sizeof(asbd) / sizeof(basic_description);
}
const <API key>* <API key>::init_action_symbol()
{
static <API key>* action_symbols =
new <API key>[id::<API key>];
for (unsigned int i = 0; i < id::<API key>; i++)
action_symbols[i].set_action_symbol((<API key>)i);
return action_symbols;
}
void <API key>::set_action_symbol(<API key> pase)
{
OC_ASSERT(pase < id::<API key>);
_enum = pase;
//fill the various properties using the arrays edited by the developer
<API key>(pase);
}
action_symbol <API key>::get_instance(const std::string& name)
{
//look up for <API key> corresponding to that name
bool found = false;
action_symbol as = NULL;
for (unsigned int i = 0; i < id::<API key> && !found; i++) {
as = <API key>::get_instance((<API key>)i);
found = as->get_name() == name;
}
return (found ? as : NULL);
}
action_symbol <API key>::get_instance(<API key> pase)
{
static const <API key>* action_symbols = init_action_symbol();
OC_ASSERT(pase < id::<API key>);
return static_cast<action_symbol>(&action_symbols[pase]);
}
const std::string& <API key>::get_name() const
{
return _name;
}
const type_tree& <API key>::get_type_tree() const
{
return _type_tree;
}
arity_t <API key>::arity() const
{
return _arity;
}
type_tree <API key>::<API key>() const
{
return _output_type;
}
const type_tree& <API key>::get_input_type_tree(arity_t i) const
{
return <API key>(_arg_type_tree, _arity, i);
} |
#include "PreCompiled.h"
#ifndef _PreComp_
#endif
#include <QTimer>
#include "TrajectorySimulate.h"
#include <Gui/Application.h>
#include <Gui/Document.h>
#include <Gui/BitmapFactory.h>
#include <Gui/ViewProvider.h>
#include <Gui/WaitCursor.h>
#include <Base/Console.h>
#include <Gui/Selection.h>
#include <Mod/Robot/App/Waypoint.h>
using namespace RobotGui;
using namespace Gui;
TrajectorySimulate::TrajectorySimulate(Robot::RobotObject *pcRobotObject,Robot::TrajectoryObject *pcTrajectoryObject,QWidget *parent)
: QDialog( parent),
sim(pcTrajectoryObject->Trajectory.getValue(),pcRobotObject->getRobot()),
Run(false),
block(false),
timePos(0.0)
{
this->setupUi(this);
QMetaObject::connectSlotsByName(this);
// set Tool
sim.Tool = pcRobotObject->Tool.getValue();
trajectoryTable->setSortingEnabled(false);
Robot::Trajectory trac = pcTrajectoryObject->Trajectory.getValue();
trajectoryTable->setRowCount(trac.getSize());
duration = trac.getDuration();
timeSpinBox->setMaximum(duration);
for(unsigned int i=0;i<trac.getSize();i++){
Robot::Waypoint pt = trac.getWaypoint(i);
switch(pt.Type){
case Robot::Waypoint::UNDEF: trajectoryTable->setItem(i, 0, new QTableWidgetItem(QString::fromLatin1("UNDEF")));break;
case Robot::Waypoint::CIRC: trajectoryTable->setItem(i, 0, new QTableWidgetItem(QString::fromLatin1("CIRC")));break;
case Robot::Waypoint::PTP: trajectoryTable->setItem(i, 0, new QTableWidgetItem(QString::fromLatin1("PTP")));break;
case Robot::Waypoint::LINE: trajectoryTable->setItem(i, 0, new QTableWidgetItem(QString::fromLatin1("LIN")));break;
default: trajectoryTable->setItem(i, 0, new QTableWidgetItem(QString::fromLatin1("UNDEF")));break;
}
trajectoryTable->setItem(i, 1, new QTableWidgetItem(QString::fromUtf8(pt.Name.c_str())));
if(pt.Cont)
trajectoryTable->setItem(i, 2, new QTableWidgetItem(QString::fromLatin1("|")));
else
trajectoryTable->setItem(i, 2, new QTableWidgetItem(QString::fromLatin1("-")));
trajectoryTable->setItem(i, 3, new QTableWidgetItem(QString::number(pt.Velocity)));
trajectoryTable->setItem(i, 4, new QTableWidgetItem(QString::number(pt.Accelaration)));
}
QObject::connect(ButtonStepStart ,SIGNAL(clicked()),this,SLOT(start()));
QObject::connect(ButtonStepStop ,SIGNAL(clicked()),this,SLOT(stop()));
QObject::connect(ButtonStepRun ,SIGNAL(clicked()),this,SLOT(run()));
QObject::connect(ButtonStepBack ,SIGNAL(clicked()),this,SLOT(back()));
QObject::connect(ButtonStepForward ,SIGNAL(clicked()),this,SLOT(forward()));
QObject::connect(ButtonStepEnd ,SIGNAL(clicked()),this,SLOT(end()));
// set up timer
timer = new QTimer( this );
timer->setInterval(100);
QObject::connect(timer ,SIGNAL(timeout ()),this,SLOT(timerDone()));
QObject::connect( timeSpinBox ,SIGNAL(valueChanged(double)), this, SLOT(valueChanged(double)) );
QObject::connect( timeSlider ,SIGNAL(valueChanged(int) ), this, SLOT(valueChanged(int)) );
// get the view provider
ViewProv = static_cast<<API key>*>(Gui::Application::Instance->activeDocument()->getViewProvider(pcRobotObject) );
setTo();
}
TrajectorySimulate::~TrajectorySimulate()
{
}
void TrajectorySimulate::setTo(void)
{
sim.setToTime(timePos);
ViewProv->setAxisTo(sim.Axis[0],sim.Axis[1],sim.Axis[2],sim.Axis[3],sim.Axis[4],sim.Axis[5],sim.Rob.getTcp());
}
void TrajectorySimulate::start(void)
{
timePos = 0.0f;
timeSpinBox->setValue(timePos);
timeSlider->setValue(int((timePos/duration)*1000));
setTo();
}
void TrajectorySimulate::stop(void)
{
timer->stop();
Run = false;
}
void TrajectorySimulate::run(void)
{
timer->start();
Run = true;
}
void TrajectorySimulate::back(void)
{
}
void TrajectorySimulate::forward(void)
{
}
void TrajectorySimulate::end(void)
{
timePos = duration;
timeSpinBox->setValue(timePos);
timeSlider->setValue(int((timePos/duration)*1000));
setTo();
}
void TrajectorySimulate::timerDone(void)
{
if(timePos < duration){
timePos += .1f;
timeSpinBox->setValue(timePos);
timeSlider->setValue(int((timePos/duration)*1000));
setTo();
timer->start();
}else{
timer->stop();
Run = false;
}
}
void TrajectorySimulate::valueChanged ( int value )
{
if(!block){
timePos = duration*(value/1000.0);
block=true;
timeSpinBox->setValue(timePos);
block=false;
setTo();
}
}
void TrajectorySimulate::valueChanged ( double value )
{
if(!block){
timePos = value;
block=true;
timeSlider->setValue(int((timePos/duration)*1000));
block=false;
setTo();
}
}
#include "<API key>.cpp" |
#ifndef __history_glob_hh__
#define __history_glob_hh__
#include "history.hh"
#include "alphabet.hh"
#include <vector>
#include <glob.h>
class History_glob: public History {
public:
History_glob(Log& l, std::string _params = "");
virtual ~History_glob() {
globfree(&gl);
}
virtual Alphabet* set_coverage(Coverage*,Alphabet* alpha,Learning* learn=NULL);
protected:
glob_t gl;
std::string params;
};
#endif |
<?php
/**
* @see <API key>
*/
// require_once "PHPUnit/Extensions/Database/Operation/IDatabaseOperation.php";
/**
* @see <API key>
*/
// require_once "PHPUnit/Extensions/Database/DB/IDatabaseConnection.php";
/**
* @see <API key>
*/
// require_once "PHPUnit/Extensions/Database/DataSet/IDataSet.php";
/**
* @see <API key>
*/
// require_once "PHPUnit/Extensions/Database/Operation/Exception.php";
/**
* @see <API key>
*/
// require_once "Zend/Test/PHPUnit/Db/Connection.php";
class <API key> implements <API key>
{
/**
*
* @param <API key> $connection
* @param <API key> $dataSet
* @return void
*/
public function execute(<API key> $connection, <API key> $dataSet)
{
if(!($connection instanceof <API key>)) {
// require_once "Zend/Test/PHPUnit/Db/Exception.php";
throw new <API key>("Not a valid <API key> instance, ".get_class($connection)." given!");
}
foreach ($dataSet->getReverseIterator() AS $table) {
try {
$tableName = $table->getTableMetaData()->getTableName();
$this->_truncate($connection->getConnection(), $tableName);
} catch (Exception $e) {
throw new <API key>('TRUNCATE', 'TRUNCATE '.$tableName.'', array(), $table, $e->getMessage());
}
}
}
/**
* Truncate a given table.
*
* @param <API key> $db
* @param string $tableName
* @return void
*/
protected function _truncate(<API key> $db, $tableName)
{
$tableName = $db->quoteIdentifier($tableName, true);
if($db instanceof <API key>) {
$db->query('DELETE FROM '.$tableName);
} else if($db instanceof Zend_Db_Adapter_Db2) {
/*if(strstr(PHP_OS, "WIN")) {
$file = tempnam(sys_get_temp_dir(), "zendtestdbibm_");
file_put_contents($file, "");
$db->query('IMPORT FROM '.$file.' OF DEL REPLACE INTO '.$tableName);
unlink($file);
} else {
$db->query('IMPORT FROM /dev/null OF DEL REPLACE INTO '.$tableName);
}*/
// require_once "Zend/Exception.php";
throw Zend_Exception("IBM Db2 TRUNCATE not supported.");
} else if($this->_isMssqlOrOracle($db)) {
$db->query('TRUNCATE TABLE '.$tableName);
} else if($db instanceof <API key>) {
$db->query('TRUNCATE '.$tableName.' CASCADE');
} else {
$db->query('TRUNCATE '.$tableName);
}
}
/**
* Detect if an adapter is for Mssql or Oracle Databases.
*
* @param <API key> $db
* @return bool
*/
private function _isMssqlOrOracle($db)
{
return (
$db instanceof <API key> ||
$db instanceof <API key> ||
$db instanceof <API key> ||
$db instanceof <API key>
);
}
} |
package org.exist.xquery.functions.array;
import org.exist.xquery.*;
import org.exist.xquery.util.ExpressionDumper;
import org.exist.xquery.value.Item;
import org.exist.xquery.value.Sequence;
import org.exist.xquery.value.Type;
import java.util.ArrayList;
import java.util.List;
/**
* A literal array constructor (XQuery 3.1)
*/
public class ArrayConstructor extends AbstractExpression {
public enum ConstructorType { SQUARE_ARRAY, CURLY_ARRAY }
private ConstructorType type;
private List<Expression> arguments = new ArrayList<Expression>();
public ArrayConstructor(XQueryContext context, ConstructorType type) {
super(context);
this.type = type;
}
public void addArgument(Expression expression) {
arguments.add(expression);
}
@Override
public void analyze(AnalyzeContextInfo contextInfo) throws XPathException {
contextInfo.setParent(this);
for (Expression expr: arguments) {
expr.analyze(contextInfo);
}
}
@Override
public Sequence eval(Sequence contextSequence, Item contextItem) throws XPathException {
if (context.getXQueryVersion() < 31) {
throw new XPathException(this, ErrorCodes.EXXQDY0004, "arrays are only available in XQuery 3.1, but version declaration states " +
context.getXQueryVersion());
}
switch(type) {
case SQUARE_ARRAY:
final List<Sequence> items = new ArrayList<Sequence>(arguments.size());
for (Expression arg: arguments) {
final Sequence result = arg.eval(contextSequence, contextItem);
if (result != null) {
items.add(result);
}
}
return new ArrayType(context, items);
default:
final Sequence result = arguments.get(0).eval(contextSequence, contextItem);
return new ArrayType(context, result);
}
}
@Override
public int returnsType() {
return Type.ARRAY;
}
@Override
public void resetState(boolean postOptimization) {
super.resetState(postOptimization);
for (Expression expr: arguments) {
expr.resetState(postOptimization);
}
}
@Override
public void dump(ExpressionDumper dumper) {
dumper.display("array {");
dumper.display('}');
}
@Override
public void accept(ExpressionVisitor visitor) {
for (Expression expr: arguments) {
expr.accept(visitor);
}
}
} |
//Draw arrows
TCanvas *arrow(){
TCanvas *c1 = new TCanvas("c1");
c1->Range(0,0,1,1);
TPaveLabel *par = new TPaveLabel(0.1,0.8,0.9,0.95,"Examples of various arrow formats");
par->SetFillColor(42);
par->Draw();
TArrow *ar1 = new TArrow(0.1,0.1,0.1,0.7);
ar1->Draw();
TArrow *ar2 = new TArrow(0.2,0.1,0.2,0.7,0.05,"|>");
ar2->SetAngle(40);
ar2->SetLineWidth(2);
ar2->Draw();
TArrow *ar3 = new TArrow(0.3,0.1,0.3,0.7,0.05,"<|>");
ar3->SetAngle(40);
ar3->SetLineWidth(2);
ar3->Draw();
TArrow *ar4 = new TArrow(0.46,0.7,0.82,0.42,0.07,"|>");
ar4->SetAngle(60);
ar4->SetLineWidth(2);
ar4->SetFillColor(2);
ar4->Draw();
TArrow *ar5 = new TArrow(0.4,0.25,0.95,0.25,0.15,"<|>");
ar5->SetAngle(60);
ar5->SetLineWidth(4);
ar5->SetLineColor(4);
ar5->SetFillStyle(3008);
ar5->SetFillColor(2);
ar5->Draw();
return c1;
} |
({"<API key>":["","","","","","",""],"timeFormat-full":"H''mm''ss''z","eras":["",""],"timeFormat-medium":"H:mm:ss","dateFormat-medium":"yyyy/MM/dd","am":"","months-format-abbr":["1 ","2 ","3 ","4 ","5 ","6 ","7 ","8 ","9 ","10 ","11 ","12 "],"dateFormat-full":"yyyy''M''d''EEEE","days-format-abbr":["","","","","","",""],"timeFormat-long":"H:mm:ss:z","timeFormat-short":"H:mm","pm":"","months-format-wide":["1 ","2 ","3 ","4 ","5 ","6 ","7 ","8 ","9 ","10 ","11 ","12 "],"dateFormat-long":"yyyy''M''d''","days-format-wide":["","","","","","",""],"field-weekday":"Day of the Week","field-second":"Second","field-week":"Week","<API key>":["1","2","3","4","5","6","7","8","9","10","11","12"],"field-year":"Year","field-minute":"Minute","field-hour":"Hour","field-day":"Day","field-dayperiod":"Dayperiod","field-month":"Month","dateFormat-short":"yy/MM/dd","field-era":"Era","field-zone":"Zone"}) |
package xades4j.xml.unmarshalling;
import org.w3c.dom.Element;
import xades4j.utils.DOMHelper;
import xades4j.xml.bind.xades.<API key>;
import xades4j.xml.bind.xades.<API key>;
import xades4j.xml.bind.xades.<API key>;
class <API key> extends UnmarshallerModule<<API key>>
{
private final <API key> <API key>;
<API key>()
{
super(5);
super.addConverter(new <API key>());
super.addConverter(new <API key>());
super.addConverter(new <API key>());
this.<API key> = new <API key>();
super.addConverter(<API key>);
super.addConverter(new <API key>());
super.addConverter(new <API key>());
}
@Override
protected <API key> getXmlProps(
<API key> xmlQualifProps)
{
<API key> xmlUnsignedProps = xmlQualifProps.<API key>();
return null == xmlUnsignedProps ? null : xmlUnsignedProps.<API key>();
}
@Override
protected Element getProps(Element qualifProps)
{
// This method is invoked only if the specific properties element is present.
return DOMHelper.getLastChildElement(DOMHelper.getLastChildElement(qualifProps));
}
@Override
protected void <API key>(boolean accept)
{
this.<API key>.<API key>(accept);
}
} |
package info.ata4.disunity.cli.command;
import com.beust.jcommander.Parameters;
import info.ata4.disunity.cli.util.TablePrinter;
import info.ata4.unity.asset.AssetFile;
import info.ata4.unity.asset.AssetHeader;
import info.ata4.unity.asset.FileIdentifier;
import info.ata4.unity.assetbundle.AssetBundleReader;
import java.io.IOException;
import java.io.PrintWriter;
import org.json.JSONArray;
import org.json.JSONObject;
import org.json.JSONObject2;
/**
*
* @author Nico Bergemann <barracuda415 at yahoo.de>
*/
@Parameters(
commandNames = "info",
commandDescription = "Shows basic information about asset files."
)
public class InfoCommand extends AssetFileCommand {
@Override
public void handleAssetFile(AssetFile asset) throws IOException {
switch (getOptions().getOutputFormat()) {
case JSON:
printJSON(asset);
break;
default:
printText(asset);
}
}
private void printText(AssetFile asset) {
PrintWriter out = getOutputWriter();
AssetHeader header = asset.header();
TablePrinter tbl = new TablePrinter(2);
tbl.addRow("Field", "Value");
tbl.addRow("metadataSize", header.metadataSize());
tbl.addRow("fileSize", header.fileSize());
tbl.addRow("version", header.version());
tbl.addRow("dataOffset", header.dataOffset());
if (header.version() >= 9) {
tbl.addRow("endianness", header.endianness());
}
out.println("Header:");
tbl.print(out);
out.println();
tbl = new TablePrinter(2);
tbl.addRow("Field", "Value");
tbl.addRow("signature", asset.versionInfo().unityRevision());
tbl.addRow("attributes", asset.typeTreeAttributes());
tbl.addRow("numBaseClasses", asset.typeTree().size());
out.println("Type tree:");
tbl.print(out);
out.println();
tbl = new TablePrinter(4);
tbl.addRow("File path", "Asset path", "GUID", "Type");
for (FileIdentifier external : asset.externals()) {
tbl.addRow(external.filePath(), external.assetPath(), external.guid(), external.type());
}
out.println("Externals:");
tbl.print(out);
}
private void printJSON(AssetFile asset) {
JSONObject2 root = new JSONObject2();
AssetBundleReader assetBundle = <API key>();
if (assetBundle != null) {
root.put("file", getCurrentFile().resolve(<API key>().name()));
} else {
root.put("file", getCurrentFile());
}
AssetHeader header = asset.header();
JSONObject headerJson = new JSONObject();
headerJson.put("metadataSize", header.metadataSize());
headerJson.put("fileSize", header.fileSize());
headerJson.put("version", header.version());
headerJson.put("dataOffset", header.dataOffset());
root.put("header", headerJson);
JSONObject typeTreeJson = new JSONObject();
typeTreeJson.put("signature", asset.versionInfo().unityRevision());
typeTreeJson.put("attributes", asset.typeTreeAttributes());
typeTreeJson.put("numBaseClasses", asset.typeTree().size());
root.put("typeTree", typeTreeJson);
JSONArray externalsJson = new JSONArray();
for (FileIdentifier external : asset.externals()) {
JSONObject externalJson = new JSONObject();
externalJson.put("assetPath", external.assetPath());
externalJson.put("guid", external.guid());
externalJson.put("filePath", external.filePath());
externalJson.put("type", external.type());
externalsJson.put(externalJson);
}
root.put("externals", externalsJson);
root.write(getOutputWriter(), 2);
}
} |
{% macro render_blog_post(post, from_index=false) %}
<div class="blog-post">
{% if from_index %}
<h2><a href="{{ post|url }}">{{ post.title }}</a></h2>
{% else %}
<h2>{{ post.title }}</h2>
{% endif %}
<p class="meta">
written by
{% if post.twitter_handle %}
<a href="https://twitter.com/{{ post.twitter_handle
}}">{{ post.author or post.twitter_handle }}</a>
{% else %}
{{ post.author }}
{% endif %}
on {{ post.pub_date }}
</p>
{{ post.body }}
</div>
{% endmacro %} |
// Flags: --<API key>
function foo() {}
var invalidAsmFunction = (function() {
"use asm";
return function() {
with (foo) foo();
}
})();
%<API key>(invalidAsmFunction);
invalidAsmFunction();
%<API key>(invalidAsmFunction);
invalidAsmFunction(); |
<reference path='fourslash.ts' />
// @Filename: f1.ts
/0./*<API key>*/
// @Filename: f2.ts
/0.0./*<API key>*/
// @Filename: f3.ts
/0.0.0./*<API key>*/
// @Filename: f4.ts
/0./** comment *//*<API key>*/
// @Filename: f5.ts
/(0)./*<API key>*/
// @Filename: f6.ts
/(0.)./*<API key>*/
// @Filename: f7.ts
/(0.0)./*<API key>*/
verify.completions(
{ marker: ["<API key>", "<API key>"], exact: undefined },
{
marker: ["<API key>", "<API key>", "<API key>", "<API key>", "<API key>"],
includes: "toExponential"
},
); |
package cgeo;
import cgeo.geocaching.CgeoApplication;
import cgeo.geocaching.DataStore;
import cgeo.geocaching.Geocache;
import cgeo.geocaching.enumerations.LoadFlags;
import cgeo.geocaching.enumerations.LoadFlags.RemoveFlag;
import cgeo.geocaching.settings.Settings;
import cgeo.geocaching.settings.TestSettings;
import android.test.ApplicationTestCase;
import java.util.EnumSet;
public abstract class CGeoTestCase extends ApplicationTestCase<CgeoApplication> {
private boolean oldStoreMapsFlag;
private boolean oldStoreWpMapsFlag;
private boolean <API key> = false;
public CGeoTestCase() {
super(CgeoApplication.class);
}
@Override
protected void setUp() throws Exception {
super.setUp();
createApplication();
}
/** Remove cache from DB and cache to ensure that the cache is not loaded from the database */
protected static void deleteCacheFromDB(final String geocode) {
DataStore.removeCache(geocode, LoadFlags.REMOVE_ALL);
}
/**
* remove cache from database and file system
*/
protected static void <API key>(final String geocode) {
final EnumSet<RemoveFlag> flags = EnumSet.copyOf(LoadFlags.REMOVE_ALL);
flags.add(RemoveFlag.<API key>);
DataStore.removeCache(geocode, flags);
}
/**
* Remove completely the previous instance of a cache, then save this object into the database
* and the cache cache.
*
* @param cache the fresh cache to save
*/
protected static void saveFreshCacheToDB(final Geocache cache) {
<API key>(cache.getGeocode());
DataStore.saveCache(cache, LoadFlags.SAVE_ALL);
}
/**
* must be called once before setting the flags
* can be called again after restoring the flags
*/
protected void recordMapStoreFlags() {
if (<API key>) {
throw new <API key>("MapStoreFlags already recorded!");
}
oldStoreMapsFlag = Settings.isStoreOfflineMaps();
oldStoreWpMapsFlag = Settings.<API key>();
<API key> = true;
}
/**
* can be called after recordMapStoreFlags,
* to set the flags for map storing as necessary
*/
protected void setMapStoreFlags(final boolean storeCacheMap, final boolean storeWpMaps) {
if (!<API key>) {
throw new <API key>("Previous MapStoreFlags havn't been recorded! Setting not allowed");
}
TestSettings.setStoreOfflineMaps(storeCacheMap);
TestSettings.<API key>(storeWpMaps);
}
/**
* has to be called after completion of the test (preferably in the finally part of a try statement)
*/
protected void <API key>() {
if (!<API key>) {
throw new <API key>("Previous MapStoreFlags havn't been recorded. Restore not possible");
}
TestSettings.setStoreOfflineMaps(oldStoreMapsFlag);
TestSettings.<API key>(oldStoreWpMapsFlag);
<API key> = false;
}
} |
// Flags: --<API key>
var foo = { x : 0, y : 1 }
function f(b) {
h(b);
return foo.x;
}
function h(b) {
g(b);
return foo.x;
}
function g(b) {
if (b) {
foo = { x : 536 };
} // It should trigger an eager deoptimization when b=true.
}
%<API key>(f);
f(false); f(false);
%<API key>(f);
f(false);
assertEquals(f(true), 536); |
angular.module('openshiftConsole')
.directive('alerts', function() {
return {
restrict: 'E',
scope: {
alerts: '='
},
templateUrl: 'views/_alerts.html'
};
}); |
package org.elasticsearch.client.transform.transforms;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.test.ESTestCase;
import java.io.IOException;
import static org.elasticsearch.test.<API key>.xContentTester;
public class <API key> extends ESTestCase {
public void testFromXContent() throws IOException {
xContentTester(this::createParser,
<API key>::randomInstance,
<API key>::toXContent,
TransformProgress::fromXContent)
.<API key>(true)
.test();
}
public static TransformProgress randomInstance() {
return new TransformProgress(
randomBoolean() ? null : <API key>(),
randomBoolean() ? null : <API key>(),
randomBoolean() ? null : randomDouble(),
randomBoolean() ? null : <API key>(),
randomBoolean() ? null : <API key>());
}
public static void toXContent(TransformProgress progress, XContentBuilder builder) throws IOException {
builder.startObject();
if (progress.getTotalDocs() != null) {
builder.field(TransformProgress.TOTAL_DOCS.getPreferredName(), progress.getTotalDocs());
}
if (progress.getPercentComplete() != null) {
builder.field(TransformProgress.PERCENT_COMPLETE.getPreferredName(), progress.getPercentComplete());
}
if (progress.getRemainingDocs() != null) {
builder.field(TransformProgress.DOCS_REMAINING.getPreferredName(), progress.getRemainingDocs());
}
builder.field(TransformProgress.DOCS_INDEXED.getPreferredName(), progress.getDocumentsIndexed());
builder.field(TransformProgress.DOCS_PROCESSED.getPreferredName(), progress.<API key>());
builder.endObject();
}
} |
package org.elasticsearch.search.fetch.subphase;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.common.bytes.BytesReference;
import org.elasticsearch.common.xcontent.XContentHelper;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.MatchQueryBuilder;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.TermQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.test.ESIntegTestCase;
import static org.elasticsearch.index.query.QueryBuilders.boolQuery;
import static org.elasticsearch.index.query.QueryBuilders.constantScoreQuery;
import static org.elasticsearch.index.query.QueryBuilders.matchAllQuery;
import static org.elasticsearch.index.query.QueryBuilders.matchQuery;
import static org.elasticsearch.index.query.QueryBuilders.queryStringQuery;
import static org.elasticsearch.index.query.QueryBuilders.rangeQuery;
import static org.elasticsearch.index.query.QueryBuilders.termQuery;
import static org.elasticsearch.index.query.QueryBuilders.termsQuery;
import static org.elasticsearch.index.query.QueryBuilders.wrapperQuery;
import static org.elasticsearch.test.hamcrest.<API key>.assertHitCount;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasItemInArray;
public class MatchedQueriesIT extends ESIntegTestCase {
public void <API key>() throws Exception {
createIndex("test");
ensureGreen();
client().prepareIndex("test").setId("1").setSource("name", "test1", "number", 1).get();
client().prepareIndex("test").setId("2").setSource("name", "test2", "number", 2).get();
client().prepareIndex("test").setId("3").setSource("name", "test3", "number", 3).get();
refresh();
SearchResponse searchResponse = client().prepareSearch()
.setQuery(boolQuery().must(matchAllQuery()).filter(boolQuery()
.should(rangeQuery("number").lt(2).queryName("test1")).should(rangeQuery("number").gte(2).queryName("test2"))))
.get();
assertHitCount(searchResponse, 3L);
for (SearchHit hit : searchResponse.getHits()) {
if (hit.getId().equals("3") || hit.getId().equals("2")) {
assertThat(hit.getMatchedQueries().length, equalTo(1));
assertThat(hit.getMatchedQueries(), hasItemInArray("test2"));
} else if (hit.getId().equals("1")) {
assertThat(hit.getMatchedQueries().length, equalTo(1));
assertThat(hit.getMatchedQueries(), hasItemInArray("test1"));
} else {
fail("Unexpected document returned with id " + hit.getId());
}
}
searchResponse = client().prepareSearch().setQuery(
boolQuery()
.should(rangeQuery("number").lte(2).queryName("test1"))
.should(rangeQuery("number").gt(2).queryName("test2"))).get();
assertHitCount(searchResponse, 3L);
for (SearchHit hit : searchResponse.getHits()) {
if (hit.getId().equals("1") || hit.getId().equals("2")) {
assertThat(hit.getMatchedQueries().length, equalTo(1));
assertThat(hit.getMatchedQueries(), hasItemInArray("test1"));
} else if (hit.getId().equals("3")) {
assertThat(hit.getMatchedQueries().length, equalTo(1));
assertThat(hit.getMatchedQueries(), hasItemInArray("test2"));
} else {
fail("Unexpected document returned with id " + hit.getId());
}
}
}
public void <API key>() throws Exception {
createIndex("test");
ensureGreen();
client().prepareIndex("test").setId("1").setSource("name", "test", "title", "title1").get();
client().prepareIndex("test").setId("2").setSource("name", "test").get();
client().prepareIndex("test").setId("3").setSource("name", "test").get();
refresh();
SearchResponse searchResponse = client().prepareSearch()
.setQuery(matchAllQuery())
.setPostFilter(boolQuery().should(
termQuery("name", "test").queryName("name")).should(
termQuery("title", "title1").queryName("title"))).get();
assertHitCount(searchResponse, 3L);
for (SearchHit hit : searchResponse.getHits()) {
if (hit.getId().equals("1")) {
assertThat(hit.getMatchedQueries().length, equalTo(2));
assertThat(hit.getMatchedQueries(), hasItemInArray("name"));
assertThat(hit.getMatchedQueries(), hasItemInArray("title"));
} else if (hit.getId().equals("2") || hit.getId().equals("3")) {
assertThat(hit.getMatchedQueries().length, equalTo(1));
assertThat(hit.getMatchedQueries(), hasItemInArray("name"));
} else {
fail("Unexpected document returned with id " + hit.getId());
}
}
searchResponse = client().prepareSearch()
.setQuery(matchAllQuery())
.setPostFilter(boolQuery()
.should(termQuery("name", "test").queryName("name"))
.should(termQuery("title", "title1").queryName("title"))).get();
assertHitCount(searchResponse, 3L);
for (SearchHit hit : searchResponse.getHits()) {
if (hit.getId().equals("1")) {
assertThat(hit.getMatchedQueries().length, equalTo(2));
assertThat(hit.getMatchedQueries(), hasItemInArray("name"));
assertThat(hit.getMatchedQueries(), hasItemInArray("title"));
} else if (hit.getId().equals("2") || hit.getId().equals("3")) {
assertThat(hit.getMatchedQueries().length, equalTo(1));
assertThat(hit.getMatchedQueries(), hasItemInArray("name"));
} else {
fail("Unexpected document returned with id " + hit.getId());
}
}
}
public void <API key>() throws Exception {
createIndex("test");
ensureGreen();
client().prepareIndex("test").setId("1").setSource("name", "test", "title", "title1").get();
client().prepareIndex("test").setId("2").setSource("name", "test", "title", "title2").get();
client().prepareIndex("test").setId("3").setSource("name", "test", "title", "title3").get();
refresh();
SearchResponse searchResponse = client().prepareSearch()
.setQuery(boolQuery().must(matchAllQuery()).filter(termsQuery("title", "title1", "title2", "title3").queryName("title")))
.setPostFilter(termQuery("name", "test").queryName("name")).get();
assertHitCount(searchResponse, 3L);
for (SearchHit hit : searchResponse.getHits()) {
if (hit.getId().equals("1") || hit.getId().equals("2") || hit.getId().equals("3")) {
assertThat(hit.getMatchedQueries().length, equalTo(2));
assertThat(hit.getMatchedQueries(), hasItemInArray("name"));
assertThat(hit.getMatchedQueries(), hasItemInArray("title"));
} else {
fail("Unexpected document returned with id " + hit.getId());
}
}
searchResponse = client().prepareSearch()
.setQuery(termsQuery("title", "title1", "title2", "title3").queryName("title"))
.setPostFilter(matchQuery("name", "test").queryName("name")).get();
assertHitCount(searchResponse, 3L);
for (SearchHit hit : searchResponse.getHits()) {
if (hit.getId().equals("1") || hit.getId().equals("2") || hit.getId().equals("3")) {
assertThat(hit.getMatchedQueries().length, equalTo(2));
assertThat(hit.getMatchedQueries(), hasItemInArray("name"));
assertThat(hit.getMatchedQueries(), hasItemInArray("title"));
} else {
fail("Unexpected document returned with id " + hit.getId());
}
}
}
public void <API key>() {
createIndex("test1");
ensureGreen();
client().prepareIndex("test1").setId("1").setSource("title", "title1").get();
refresh();
SearchResponse searchResponse = client().prepareSearch()
.setQuery(QueryBuilders.regexpQuery("title", "title1").queryName("regex")).get();
assertHitCount(searchResponse, 1L);
for (SearchHit hit : searchResponse.getHits()) {
if (hit.getId().equals("1")) {
assertThat(hit.getMatchedQueries().length, equalTo(1));
assertThat(hit.getMatchedQueries(), hasItemInArray("regex"));
} else {
fail("Unexpected document returned with id " + hit.getId());
}
}
}
public void <API key>() {
createIndex("test1");
ensureGreen();
client().prepareIndex("test1").setId("1").setSource("title", "title1").get();
refresh();
SearchResponse searchResponse = client().prepareSearch()
.setQuery(QueryBuilders.prefixQuery("title", "title").queryName("prefix")).get();
assertHitCount(searchResponse, 1L);
for (SearchHit hit : searchResponse.getHits()) {
if (hit.getId().equals("1")) {
assertThat(hit.getMatchedQueries().length, equalTo(1));
assertThat(hit.getMatchedQueries(), hasItemInArray("prefix"));
} else {
fail("Unexpected document returned with id " + hit.getId());
}
}
}
public void <API key>() {
createIndex("test1");
ensureGreen();
client().prepareIndex("test1").setId("1").setSource("title", "title1").get();
refresh();
SearchResponse searchResponse = client().prepareSearch()
.setQuery(QueryBuilders.fuzzyQuery("title", "titel1").queryName("fuzzy")).get();
assertHitCount(searchResponse, 1L);
for (SearchHit hit : searchResponse.getHits()) {
if (hit.getId().equals("1")) {
assertThat(hit.getMatchedQueries().length, equalTo(1));
assertThat(hit.getMatchedQueries(), hasItemInArray("fuzzy"));
} else {
fail("Unexpected document returned with id " + hit.getId());
}
}
}
public void <API key>() {
createIndex("test1");
ensureGreen();
client().prepareIndex("test1").setId("1").setSource("title", "title1").get();
refresh();
SearchResponse searchResponse = client().prepareSearch()
.setQuery(QueryBuilders.wildcardQuery("title", "titl*").queryName("wildcard")).get();
assertHitCount(searchResponse, 1L);
for (SearchHit hit : searchResponse.getHits()) {
if (hit.getId().equals("1")) {
assertThat(hit.getMatchedQueries().length, equalTo(1));
assertThat(hit.getMatchedQueries(), hasItemInArray("wildcard"));
} else {
fail("Unexpected document returned with id " + hit.getId());
}
}
}
public void <API key>() {
createIndex("test1");
ensureGreen();
client().prepareIndex("test1").setId("1").setSource("title", "title1 title2").get();
refresh();
SearchResponse searchResponse = client().prepareSearch()
.setQuery(QueryBuilders.spanFirstQuery(QueryBuilders.spanTermQuery("title", "title1"), 10).queryName("span")).get();
assertHitCount(searchResponse, 1L);
for (SearchHit hit : searchResponse.getHits()) {
if (hit.getId().equals("1")) {
assertThat(hit.getMatchedQueries().length, equalTo(1));
assertThat(hit.getMatchedQueries(), hasItemInArray("span"));
} else {
fail("Unexpected document returned with id " + hit.getId());
}
}
}
public void <API key>() throws Exception {
createIndex("test");
ensureGreen();
client().prepareIndex("test").setId("1").setSource("content", "Lorem ipsum dolor sit amet").get();
client().prepareIndex("test").setId("2").setSource("content", "consectetur adipisicing elit").get();
refresh();
// Execute search at least two times to load it in cache
int iter = <API key>(2, 10);
for (int i = 0; i < iter; i++) {
SearchResponse searchResponse = client().prepareSearch()
.setQuery(
boolQuery()
.minimumShouldMatch(1)
.should(queryStringQuery("dolor").queryName("dolor"))
.should(queryStringQuery("elit").queryName("elit"))
)
.get();
assertHitCount(searchResponse, 2L);
for (SearchHit hit : searchResponse.getHits()) {
if (hit.getId().equals("1")) {
assertThat(hit.getMatchedQueries().length, equalTo(1));
assertThat(hit.getMatchedQueries(), hasItemInArray("dolor"));
} else if (hit.getId().equals("2")) {
assertThat(hit.getMatchedQueries().length, equalTo(1));
assertThat(hit.getMatchedQueries(), hasItemInArray("elit"));
} else {
fail("Unexpected document returned with id " + hit.getId());
}
}
}
}
public void <API key>() throws Exception {
createIndex("test");
ensureGreen();
client().prepareIndex("test").setId("1").setSource("content", "Lorem ipsum dolor sit amet").get();
refresh();
MatchQueryBuilder matchQueryBuilder = matchQuery("content", "amet").queryName("abc");
BytesReference matchBytes = XContentHelper.toXContent(matchQueryBuilder, XContentType.JSON, false);
TermQueryBuilder termQueryBuilder = termQuery("content", "amet").queryName("abc");
BytesReference termBytes = XContentHelper.toXContent(termQueryBuilder, XContentType.JSON, false);
QueryBuilder[] queries = new QueryBuilder[]{
wrapperQuery(matchBytes),
constantScoreQuery(wrapperQuery(termBytes))
};
for (QueryBuilder query : queries) {
SearchResponse searchResponse = client().prepareSearch()
.setQuery(query)
.get();
assertHitCount(searchResponse, 1L);
assertThat(searchResponse.getHits().getAt(0).getMatchedQueries()[0], equalTo("abc"));
}
}
} |
package org.elasticsearch.xpack.slm.action;
import org.elasticsearch.client.node.NodeClient;
import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.rest.BaseRestHandler;
import org.elasticsearch.rest.RestRequest;
import org.elasticsearch.rest.action.<API key>;
import org.elasticsearch.xpack.core.slm.action.<API key>;
import java.io.IOException;
import java.util.List;
import static org.elasticsearch.rest.RestRequest.Method.PUT;
public class <API key> extends BaseRestHandler {
@Override
public List<Route> routes() {
return List.of(new Route(PUT, "/_slm/policy/{name}"));
}
@Override
public String getName() {
return "slm_put_lifecycle";
}
@Override
protected RestChannelConsumer prepareRequest(RestRequest request, NodeClient client) throws IOException {
String snapLifecycleName = request.param("name");
try (XContentParser parser = request.contentParser()) {
<API key>.Request req = <API key>.Request.parseRequest(snapLifecycleName, parser);
req.timeout(request.paramAsTime("timeout", req.timeout()));
req.masterNodeTimeout(request.paramAsTime("master_timeout", req.masterNodeTimeout()));
return channel -> client.execute(<API key>.INSTANCE, req, new <API key><>(channel));
}
}
} |
.mail4 {
display: inline-block;
height: 48px;
width: 48px;
border: 4px solid purple;
background-image: url(../../images/more/mail.png);
} |
#ifndef <API key>
#define <API key>
#include "components/sessions/core/<API key>.h"
#include "components/sessions/core/sessions_export.h"
#include "components/sessions/core/tab_restore_service.h"
namespace sessions {
// Interface that represents a currently-live tab to the core sessions code, and
// in particular, the tab restore service. This interface abstracts the concrete
// representation of a live tab on different platforms (e.g., WebContents on
// //content-based platforms).
class SESSIONS_EXPORT LiveTab {
public:
virtual ~LiveTab();
// Methods that return information about the navigation state of the tab.
virtual bool <API key>() = 0;
virtual int <API key>() = 0;
virtual int <API key>() = 0;
virtual <API key> GetEntryAtIndex(int index) = 0;
virtual <API key> GetPendingEntry() = 0;
virtual int GetEntryCount() = 0;
// Returns any platform-specific data that should be associated with the
// TabRestoreService::Tab corresponding to this instance. The default
// implementation returns null.
virtual std::unique_ptr<<API key>> <API key>();
// Loads the current page if necessary (where "necessary" is defined on a
// platform-specific basis).
virtual void LoadIfNecessary() = 0;
// Returns the user agent override, if any.
virtual const std::string& <API key>() const = 0;
};
} // namespace sessions
#endif // <API key> |
.a ~ x, .a.b ~ y {
a: b;
} |
#ifndef <API key>
#define <API key>
#include "core/frame/DOMWindowProperty.h"
#include "modules/indexeddb/IndexedDBClient.h"
#include "platform/Supplementable.h"
namespace blink {
class IDBFactory;
class DOMWindow;
class <API key> final : public <API key><<API key>>, public <API key><LocalDOMWindow>, public DOMWindowProperty {
<API key>(<API key>);
<API key>(<API key>);
<API key>(<API key>);
public:
static <API key>& from(LocalDOMWindow&);
static IDBFactory* indexedDB(DOMWindow&);
void <API key>() override;
void <API key>() override;
DECLARE_TRACE();
private:
explicit <API key>(LocalDOMWindow&);
IDBFactory* indexedDB();
static const char* supplementName();
RawPtrWillBeMember<LocalDOMWindow> m_window;
<API key><IDBFactory> m_idbFactory;
};
} // namespace blink
#endif // <API key> |
/**
* @fileoverview Implements a low-level gnubby driver based on chrome.hid.
*/
'use strict';
/**
* Low level gnubby 'driver'. One per physical USB device.
* @param {Gnubbies} gnubbies The gnubbies instances this device is enumerated
* in.
* @param {!chrome.hid.HidConnectInfo} dev The connection to the device.
* @param {number} id The device's id.
* @constructor
* @implements {GnubbyDevice}
*/
function HidGnubbyDevice(gnubbies, dev, id) {
/** @private {Gnubbies} */
this.gnubbies_ = gnubbies;
this.dev = dev;
this.id = id;
this.txqueue = [];
this.clients = [];
this.lockCID = 0; // channel ID of client holding a lock, if != 0.
this.lockMillis = 0; // current lock period.
this.lockTID = null; // timer id of lock timeout.
this.closing = false; // device to be closed by receive loop.
this.updating = false; // device firmware is in final stage of updating.
}
/**
* Namespace for the HidGnubbyDevice implementation.
* @const
*/
HidGnubbyDevice.NAMESPACE = 'hid';
/** Destroys this low-level device instance. */
HidGnubbyDevice.prototype.destroy = function() {
if (!this.dev) return; // Already dead.
this.gnubbies_.removeOpenDevice(
{namespace: HidGnubbyDevice.NAMESPACE, device: this.id});
this.closing = true;
console.log(UTIL_fmt('HidGnubbyDevice.destroy()'));
// Synthesize a close error frame to alert all clients,
// some of which might be in read state.
// Use magic CID 0 to address all.
this.publishFrame_(new Uint8Array([
0, 0, 0, 0, // broadcast CID
GnubbyDevice.CMD_ERROR,
0, 1, // length
GnubbyDevice.GONE]).buffer);
// Set all clients to closed status and remove them.
while (this.clients.length != 0) {
var client = this.clients.shift();
if (client) client.closed = true;
}
if (this.lockTID) {
window.clearTimeout(this.lockTID);
this.lockTID = null;
}
var dev = this.dev;
this.dev = null;
chrome.hid.disconnect(dev.connectionId, function() {
if (chrome.runtime.lastError) {
console.warn(UTIL_fmt('Device ' + dev.connectionId +
' couldn\'t be disconnected:'));
console.warn(UTIL_fmt(chrome.runtime.lastError.message));
return;
}
console.log(UTIL_fmt('Device ' + dev.connectionId + ' closed'));
});
};
/**
* Push frame to all clients.
* @param {ArrayBuffer} f Data to push
* @private
*/
HidGnubbyDevice.prototype.publishFrame_ = function(f) {
var old = this.clients;
var remaining = [];
var changes = false;
for (var i = 0; i < old.length; ++i) {
var client = old[i];
if (client.receivedFrame(f)) {
// Client still alive; keep on list.
remaining.push(client);
} else {
changes = true;
console.log(UTIL_fmt(
'[' + Gnubby.hexCid(client.cid) + '] left?'));
}
}
if (changes) this.clients = remaining;
};
/**
* Register a client for this gnubby.
* @param {*} who The client.
*/
HidGnubbyDevice.prototype.registerClient = function(who) {
for (var i = 0; i < this.clients.length; ++i) {
if (this.clients[i] === who) return; // Already registered.
}
this.clients.push(who);
if (this.clients.length == 1) {
// First client? Kick off read loop.
this.readLoop_();
}
};
/**
* De-register a client.
* @param {*} who The client.
* @return {number} The number of remaining listeners for this device, or -1
* Returns number of remaining listeners for this device.
* if this had no clients to start with.
*/
HidGnubbyDevice.prototype.deregisterClient = function(who) {
var current = this.clients;
if (current.length == 0) return -1;
this.clients = [];
for (var i = 0; i < current.length; ++i) {
var client = current[i];
if (client !== who) this.clients.push(client);
}
return this.clients.length;
};
/**
* @param {*} who The client.
* @return {boolean} Whether this device has who as a client.
*/
HidGnubbyDevice.prototype.hasClient = function(who) {
if (this.clients.length == 0) return false;
for (var i = 0; i < this.clients.length; ++i) {
if (who === this.clients[i])
return true;
}
return false;
};
/**
* Reads all incoming frames and notifies clients of their receipt.
* @private
*/
HidGnubbyDevice.prototype.readLoop_ = function() {
//console.log(UTIL_fmt('entering readLoop'));
if (!this.dev) return;
if (this.closing) {
this.destroy();
return;
}
// No interested listeners, yet we hit readLoop().
// Must be clean-up. We do this here to make sure no transfer is pending.
if (!this.clients.length) {
this.closing = true;
this.destroy();
return;
}
// firmwareUpdate() sets this.updating when writing the last block before
// the signature. We process that reply with the already pending
// read transfer but we do not want to start another read transfer for the
// signature block, since that request will have no reply.
// Instead we will see the device drop and re-appear on the bus.
// Current libusb on some platforms gets unhappy when transfer are pending
// when that happens.
// TODO: revisit once Chrome stabilizes its behavior.
if (this.updating) {
console.log(UTIL_fmt('device updating. Ending readLoop()'));
return;
}
var self = this;
chrome.hid.receive(
this.dev.connectionId,
function(report_id, data) {
if (chrome.runtime.lastError || !data) {
console.log(UTIL_fmt('receive got lastError:'));
console.log(UTIL_fmt(chrome.runtime.lastError.message));
window.setTimeout(function() { self.destroy(); }, 0);
return;
}
var u8 = new Uint8Array(data);
console.log(UTIL_fmt('<' + UTIL_BytesToHex(u8)));
self.publishFrame_(data);
// Read more.
window.setTimeout(function() { self.readLoop_(); }, 0);
}
);
};
/**
* Check whether channel is locked for this request or not.
* @param {number} cid Channel id
* @param {number} cmd Request command
* @return {boolean} true if not locked for this request.
* @private
*/
HidGnubbyDevice.prototype.checkLock_ = function(cid, cmd) {
if (this.lockCID) {
// We have an active lock.
if (this.lockCID != cid) {
// Some other channel has active lock.
if (cmd != GnubbyDevice.CMD_SYNC &&
cmd != GnubbyDevice.CMD_INIT) {
// Anything but SYNC|INIT gets an immediate busy.
var busy = new Uint8Array(
[(cid >> 24) & 255,
(cid >> 16) & 255,
(cid >> 8) & 255,
cid & 255,
GnubbyDevice.CMD_ERROR,
0, 1, // length
GnubbyDevice.BUSY]);
// Log the synthetic busy too.
console.log(UTIL_fmt('<' + UTIL_BytesToHex(busy)));
this.publishFrame_(busy.buffer);
return false;
}
// SYNC|INIT gets to go to the device to flush OS tx/rx queues.
// The usb firmware is to alway respond to SYNC/INIT,
// regardless of lock status.
}
}
return true;
};
/**
* Update or grab lock.
* @param {number} cid Channel ID
* @param {number} cmd Command
* @param {number} arg Command argument
* @private
*/
HidGnubbyDevice.prototype.updateLock_ = function(cid, cmd, arg) {
if (this.lockCID == 0 || this.lockCID == cid) {
// It is this caller's or nobody's lock.
if (this.lockTID) {
window.clearTimeout(this.lockTID);
this.lockTID = null;
}
if (cmd == GnubbyDevice.CMD_LOCK) {
var nseconds = arg;
if (nseconds != 0) {
this.lockCID = cid;
// Set tracking time to be .1 seconds longer than usb device does.
this.lockMillis = nseconds * 1000 + 100;
} else {
// Releasing lock voluntarily.
this.lockCID = 0;
}
}
// (re)set the lock timeout if we still hold it.
if (this.lockCID) {
var self = this;
this.lockTID = window.setTimeout(
function() {
console.warn(UTIL_fmt(
'lock for CID ' + Gnubby.hexCid(cid) + ' expired!'));
self.lockTID = null;
self.lockCID = 0;
},
this.lockMillis);
}
}
};
/**
* Queue command to be sent.
* If queue was empty, initiate the write.
* @param {number} cid The client's channel ID.
* @param {number} cmd The command to send.
* @param {ArrayBuffer|Uint8Array} data Command arguments
*/
HidGnubbyDevice.prototype.queueCommand = function(cid, cmd, data) {
if (!this.dev) return;
if (!this.checkLock_(cid, cmd)) return;
var u8 = new Uint8Array(data);
var f = new Uint8Array(64);
HidGnubbyDevice.setCid_(f, cid);
f[4] = cmd;
f[5] = (u8.length >> 8);
f[6] = (u8.length & 255);
var lockArg = (u8.length > 0) ? u8[0] : 0;
// Fragment over our 64 byte frames.
var n = 7;
var seq = 0;
for (var i = 0; i < u8.length; ++i) {
f[n++] = u8[i];
if (n == f.length) {
this.queueFrame_(f.buffer, cid, cmd, lockArg);
f = new Uint8Array(64);
HidGnubbyDevice.setCid_(f, cid);
cmd = f[4] = seq++;
n = 5;
}
}
if (n != 5) {
this.queueFrame_(f.buffer, cid, cmd, lockArg);
}
};
/**
* Sets the channel id in the frame.
* @param {Uint8Array} frame Data frame
* @param {number} cid The client's channel ID.
* @private
*/
HidGnubbyDevice.setCid_ = function(frame, cid) {
frame[0] = cid >>> 24;
frame[1] = cid >>> 16;
frame[2] = cid >>> 8;
frame[3] = cid;
};
/**
* Updates the lock, and queues the frame for sending. Also begins sending if
* no other writes are outstanding.
* @param {ArrayBuffer} frame Data frame
* @param {number} cid The client's channel ID.
* @param {number} cmd The command to send.
* @param {number} arg Command argument
* @private
*/
HidGnubbyDevice.prototype.queueFrame_ = function(frame, cid, cmd, arg) {
this.updateLock_(cid, cmd, arg);
var wasEmpty = (this.txqueue.length == 0);
this.txqueue.push(frame);
if (wasEmpty) this.writePump_();
};
/**
* Stuff queued frames from txqueue[] to device, one by one.
* @private
*/
HidGnubbyDevice.prototype.writePump_ = function() {
if (!this.dev) return; // Ignore.
if (this.txqueue.length == 0) return; // Done with current queue.
var frame = this.txqueue[0];
var self = this;
function transferComplete() {
if (chrome.runtime.lastError) {
console.log(UTIL_fmt('send got lastError:'));
console.log(UTIL_fmt(chrome.runtime.lastError.message));
window.setTimeout(function() { self.destroy(); }, 0);
return;
}
self.txqueue.shift(); // drop sent frame from queue.
if (self.txqueue.length != 0) {
window.setTimeout(function() { self.writePump_(); }, 0);
}
};
var u8 = new Uint8Array(frame);
// See whether this requires scrubbing before logging.
var alternateLog = Gnubby.hasOwnProperty('redactRequestLog') &&
Gnubby['redactRequestLog'](u8);
if (alternateLog) {
console.log(UTIL_fmt('>' + alternateLog));
} else {
console.log(UTIL_fmt('>' + UTIL_BytesToHex(u8)));
}
var u8f = new Uint8Array(64);
for (var i = 0; i < u8.length; ++i) {
u8f[i] = u8[i];
}
chrome.hid.send(
this.dev.connectionId,
0, // report Id. Must be 0 for our use.
u8f.buffer,
transferComplete
);
};
/**
* List of legacy HID devices that do not support the F1D0 usage page as
* mandated by the spec, but still need to be supported.
* TODO: remove when these devices no longer need to be supported.
* @const
*/
HidGnubbyDevice.HID_VID_PIDS = [
{'vendorId': 4176, 'productId': 512} // Google-specific Yubico HID
];
/**
* @param {function(Array)} cb Enumeration callback
*/
HidGnubbyDevice.enumerate = function(cb) {
/**
* One pass using getDevices, and one for each of the hardcoded vid/pids.
* @const
*/
var ENUMERATE_PASSES = 1 + HidGnubbyDevice.HID_VID_PIDS.length;
var numEnumerated = 0;
var allDevs = [];
function enumerated(f1d0Enumerated, devs) {
// Don't double-add a device; it'll just confuse things.
// We assume the various calls to getDevices() return from the same
// deviceId pool.
for (var i = 0; i < devs.length; i++) {
var dev = devs[i];
dev.f1d0Only = f1d0Enumerated;
// Unfortunately indexOf is not usable, since the two calls produce
// different objects. Compare their deviceIds instead.
var found = false;
for (var j = 0; j < allDevs.length; j++) {
if (allDevs[j].deviceId == dev.deviceId) {
found = true;
allDevs[j].f1d0Only &= f1d0Enumerated;
break;
}
}
if (!found) {
allDevs.push(dev);
}
}
if (++numEnumerated == ENUMERATE_PASSES) {
cb(allDevs);
}
}
// Pass 1: usagePage-based enumeration.
chrome.hid.getDevices({filters: [{usagePage: 0xf1d0}]},
enumerated.bind(null, true));
// Pass 2: vid/pid-based enumeration, for legacy devices.
for (var i = 0; i < HidGnubbyDevice.HID_VID_PIDS.length; i++) {
var dev = HidGnubbyDevice.HID_VID_PIDS[i];
chrome.hid.getDevices({filters: [dev]}, enumerated.bind(null, false));
}
};
/**
* @param {Gnubbies} gnubbies The gnubbies instances this device is enumerated
* in.
* @param {number} which The index of the device to open.
* @param {!chrome.hid.HidDeviceInfo} dev The device to open.
* @param {function(number, GnubbyDevice=)} cb Called back with the
* result of opening the device.
*/
HidGnubbyDevice.open = function(gnubbies, which, dev, cb) {
chrome.hid.connect(dev.deviceId, function(handle) {
if (chrome.runtime.lastError) {
console.log(UTIL_fmt('connect got lastError:'));
console.log(UTIL_fmt(chrome.runtime.lastError.message));
}
if (!handle) {
console.warn(UTIL_fmt('failed to connect device. permissions issue?'));
cb(-GnubbyDevice.NODEVICE);
return;
}
var nonNullHandle = /** @type {!chrome.hid.HidConnectInfo} */ (handle);
var gnubby = new HidGnubbyDevice(gnubbies, nonNullHandle, which);
cb(-GnubbyDevice.OK, gnubby);
});
};
/**
* @param {*} dev A browser API device object
* @return {GnubbyDeviceId} A device identifier for the device.
*/
HidGnubbyDevice.deviceToDeviceId = function(dev) {
var hidDev = /** @type {!chrome.hid.HidDeviceInfo} */ (dev);
var deviceId = {
namespace: HidGnubbyDevice.NAMESPACE,
device: hidDev.deviceId
};
return deviceId;
};
/**
* Registers this implementation with gnubbies.
* @param {Gnubbies} gnubbies Gnubbies registry
*/
HidGnubbyDevice.register = function(gnubbies) {
var HID_GNUBBY_IMPL = {
isSharedAccess: true,
enumerate: HidGnubbyDevice.enumerate,
deviceToDeviceId: HidGnubbyDevice.deviceToDeviceId,
open: HidGnubbyDevice.open
};
gnubbies.registerNamespace(HidGnubbyDevice.NAMESPACE, HID_GNUBBY_IMPL);
}; |
body {
color: #40658A;
background: url(Logo_DevCamp.png);
background-position: 100% 60px;
background-repeat: no-repeat;
}
li > a[selected], li > a:active {
background-image: url(../default/listArrowSel.png), url(../default/selection.png) !important;
}
li > a[selected="progress"] {
background-image: url(../default/loading.gif), url(../default/selection.png) !important;
}
body > .toolbar {
border-top: 1px solid #585858;
background: url(toolbar.png) #6d84a2 repeat-x;
}
.button {
-webkit-border-image: url(toolButton.png) 0 5 0 5;
-moz-border-image: url(toolButton.png) 0 5 0 5;
}
.blueButton {
-webkit-border-image: url(blueButton.png) 0 5 0 5;
-moz-border-image: url(blueButton.png) 0 5 0 5;
}
#backButton {
-webkit-border-image: url(backButton.png) 0 8 0 14;
-moz-border-image: url(backButton.png) 0 8 0 14;
}
.whiteButton {
-webkit-border-image: url(../default/whiteButton.png) 0 12 0 12;
-moz-border-image: url(../default/whiteButton.png) 0 12 0 12;
text-shadow: rgba(255, 255, 255, 0.7) 0 1px 0;
}
.redButton {
-webkit-border-image: url(redButton.png) 0 12 0 12;
-moz-border-image: url(redButton.png) 0 12 0 12;
}
.grayButton {
-webkit-border-image: url(../default/grayButton.png) 0 12 0 12;
-moz-border-image: url(../default/grayButton.png) 0 12 0 12;
color: #FFFFFF;
}
body > ul > li.group {
opacity:0.7;
background: url(listGroup.png) repeat-x;
}
body > ul > li > a {
background: url(../default/listArrow.png) no-repeat right center;
}
.dialog > fieldset {
background: #585858 url(toolbar.png) repeat-x;
}
.dialog > fieldset h1 {
height: 32px;
}
.dialog > fieldset > label {
margin-top: 17px;
}
body > .panel {
background: #c5ccd4 url(pinstripes.png);
}
.toggle {
border: 1px solid #888888;
background: #FFFFFF url(../default/toggle.png) repeat-x;
}
.toggle[toggled="true"] {
background: #194fdb url(toggleOn.png) repeat-x;
}
.thumb {
background: #ffffff url(../default/thumb.png) repeat-x;
}
#preloader {
background-image: url(../default/loading.gif), url(../default/selection.png),
url(blueButton.png), url(../default/listArrowSel.png), url(listGroup.png);
} |
<!DOCTYPE html>
<html>
<!
Copyright 2008 The Closure Library Authors. All Rights Reserved.
Use of this source code is governed by the Apache License, Version 2.0.
See the COPYING file for details.
<!
@author nicksantos@google.com (Nick Santos)
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Closure Unit Tests - goog.ui.MenuButton</title>
<style type='text/css'>
.goog-menu {
position: absolute;
color: #aaa;
}
</style>
<script src="../base.js"></script>
<script>
goog.require('goog.Timer');
goog.require('goog.a11y.aria');
goog.require('goog.a11y.aria.State');
goog.require('goog.dom');
goog.require('goog.events');
goog.require('goog.events.Event');
goog.require('goog.events.EventType');
goog.require('goog.events.KeyCodes');
goog.require('goog.positioning');
goog.require('goog.positioning.<API key>');
goog.require('goog.positioning.Overflow');
goog.require('goog.style');
goog.require('goog.testing.ExpectedFailures');
goog.require('goog.testing.PropertyReplacer');
goog.require('goog.testing.events');
goog.require('goog.testing.jsunit');
goog.require('goog.testing.recordFunction');
goog.require('goog.ui.Menu');
goog.require('goog.ui.MenuButton');
goog.require('goog.ui.MenuItem');
goog.require('goog.userAgent');
goog.require('goog.userAgent.product');
goog.require('goog.userAgent.product.isVersion');
</script>
</head>
<body>
<iframe id="iframe1" src="<API key>.html" width="400" height="400">
</iframe>
<div id="positionElement" style="position: absolute; left: 205px"></div>
<script>
var menuButton;
var clonedMenuButtonDom;
var expectedFailures = new goog.testing.ExpectedFailures();
// Mock out goog.positioning.<API key> to always ignore failure when
// the window is too small, since we don't care about the viewport size on
// the selenium farm.
// TODO(nicksantos): Move this into a common location if we ever have enough
// code for a general goog.testing.ui library.
var <API key> = goog.positioning.<API key>;
goog.positioning.<API key> = function(absolutePos, movableElement,
<API key>, opt_margin, opt_viewport, opt_overflow,
opt_preferredSize) {
return <API key>.call(this, absolutePos, movableElement,
<API key>, opt_margin, opt_viewport,
goog.positioning.Overflow.IGNORE, opt_preferredSize);
};
function MyFakeEvent(keyCode, opt_eventType) {
this.type = opt_eventType || goog.events.KeyHandler.EventType.KEY;
this.keyCode = keyCode;
this.propagationStopped = false;
this.preventDefault = goog.nullFunction;
this.stopPropagation = function() {
this.propagationStopped = true;
};
}
function setUp() {
window.scrollTo(0, 0);
var viewportSize = goog.dom.getViewportSize();
// Some tests need enough size viewport.
if (viewportSize.width < 600 || viewportSize.height < 600) {
window.moveTo(0, 0);
window.resizeTo(640, 640);
}
clonedMenuButtonDom = goog.dom.getElement('demoMenuButton').cloneNode(true);
menuButton = new goog.ui.MenuButton();
}
function tearDown() {
expectedFailures.handleTearDown();
menuButton.dispose();
var element = goog.dom.getElement('demoMenuButton');
element.parentNode.replaceChild(clonedMenuButtonDom, element);
}
/**
* Check if the aria-haspopup property is set correctly.
*/
function checkHasPopUp() {
menuButton.enterDocument();
assertFalse('Menu button must have aria-haspopup attribute set to false',
goog.a11y.aria.getState(menuButton.getElement(),
goog.a11y.aria.State.HASPOPUP));
var menu = new goog.ui.Menu();
menu.createDom();
menuButton.setMenu(menu);
assertTrue('Menu button must have aria-haspopup attribute set to true',
goog.a11y.aria.getState(menuButton.getElement(),
goog.a11y.aria.State.HASPOPUP));
menuButton.setMenu(null);
assertFale('Menu button must have aria-haspopup attribute set to false',
goog.a11y.aria.getState(menuButton.getElement(),
goog.a11y.aria.State.HASPOPUP));
}
/**
* Open the menu and click on the menu item inside.
* Check if the aria-haspopup property is set correctly.
*/
function <API key>() {
var node = goog.dom.getElement('demoMenuButton');
menuButton.decorate(node);
assertEquals('Menu button must have aria-haspopup attribute set to true',
'true', goog.a11y.aria.getState(menuButton.getElement(),
goog.a11y.aria.State.HASPOPUP));
goog.testing.events.fireClickSequence(node);
assertTrue('Menu must open after click', menuButton.isOpen());
var menuItemClicked = 0;
var lastMenuItemClicked = null;
goog.events.listen(menuButton.getMenu(),
goog.ui.Component.EventType.ACTION,
function(e) {
menuItemClicked++;
lastMenuItemClicked = e.target;
});
var menuItem2 = goog.dom.getElement('menuItem2');
goog.testing.events.fireClickSequence(menuItem2);
assertFalse('Menu must close on clicking when open', menuButton.isOpen());
assertEquals('Number of menu items clicked should be 1', 1, menuItemClicked);
assertEquals('menuItem2 should be the last menuitem clicked', menuItem2,
lastMenuItemClicked.getElement());
}
/**
* Open the menu, highlight first menuitem and then the second.
* Check if the <API key> property is set correctly.
*/
function <API key>() {
var node = goog.dom.getElement('demoMenuButton');
menuButton.decorate(node);
goog.testing.events.fireClickSequence(node);
assertTrue('Menu must open after click', menuButton.isOpen());
menuButton.handleKeyEvent(new MyFakeEvent(goog.events.KeyCodes.DOWN));
assertNotNull(menuButton.getElement());
assertEquals('First menuitem must be the <API key>',
'menuItem1', goog.a11y.aria.getState(menuButton.getElement(),
goog.a11y.aria.State.ACTIVEDESCENDANT));
menuButton.handleKeyEvent(new MyFakeEvent(goog.events.KeyCodes.DOWN));
assertEquals('Second menuitem must be the <API key>',
'menuItem2', goog.a11y.aria.getState(menuButton.getElement(),
goog.a11y.aria.State.ACTIVEDESCENDANT));
}
/**
* Make sure the menu opens when enter is pressed.
*/
function testEnterOpensMenu() {
var node = goog.dom.getElement('demoMenuButton');
menuButton.decorate(node);
menuButton.handleKeyEvent(new MyFakeEvent(goog.events.KeyCodes.ENTER));
assertTrue('Menu must open after enter', menuButton.isOpen());
}
/**
* Tests that a keydown event of the escape key propagates normally when the
* menu is closed.
*/
function <API key>() {
var node = goog.dom.getElement('demoMenuButton');
var fakeEvent = new MyFakeEvent(
goog.events.KeyCodes.ESCAPE, goog.events.EventType.KEYDOWN);
menuButton.decorate(node);
menuButton.setOpen(false);
menuButton.handleKeyDownEvent_(fakeEvent);
assertFalse('Event propagation was erroneously stopped.',
fakeEvent.propagationStopped);
}
/**
* Tests that a keydown event of the escape key is prevented from propagating
* when the menu is open.
*/
function <API key>() {
var node = goog.dom.getElement('demoMenuButton');
var fakeEvent = new MyFakeEvent(
goog.events.KeyCodes.ESCAPE, goog.events.EventType.KEYDOWN);
menuButton.decorate(node);
menuButton.setOpen(true);
menuButton.handleKeyDownEvent_(fakeEvent);
assertTrue(
'Event propagation was not stopped.', fakeEvent.propagationStopped);
}
/**
* Open the menu and click on the menu item inside after exiting and entering
* the document once, to test proper setup/teardown behavior of MenuButton.
*/
function <API key>() {
var node = goog.dom.getElement('demoMenuButton');
menuButton.decorate(node);
menuButton.exitDocument();
menuButton.enterDocument();
goog.testing.events.fireClickSequence(node);
assertTrue('Menu must open after click', menuButton.isOpen());
var menuItem2 = goog.dom.getElement('menuItem2');
goog.testing.events.fireClickSequence(menuItem2);
assertFalse('Menu must close on clicking when open', menuButton.isOpen());
}
/**
* Renders the menu button, moves its menu and then repositions to make sure the
* position is more or less ok.
*/
function testPositionMenu() {
var node = goog.dom.getElement('demoMenuButton');
menuButton.decorate(node);
var menu = menuButton.getMenu();
menu.setVisible(true, true);
// Move to 500, 500
menu.setPosition(500, 500);
// Now reposition and make sure position is more or less ok.
menuButton.positionMenu();
var menuNode = goog.dom.getElement('demoMenu');
assertRoughlyEquals(menuNode.offsetTop, node.offsetTop + node.offsetHeight,
20);
assertRoughlyEquals(menuNode.offsetLeft, node.offsetLeft, 20);
}
/**
* Tests that calling positionMenu when the menu is not in the document does not
* throw an exception.
*/
function <API key>() {
var menu = new goog.ui.Menu();
menu.createDom();
menuButton.setMenu(menu);
menuButton.positionMenu();
}
/**
* Shows the menu and moves the menu button, a timer correct the menu position.
*/
function <API key>() {
var iframe = goog.dom.getElement('iframe1');
var iframeDoc = goog.dom.<API key>(iframe);
var iframeDom = goog.dom.getDomHelper(iframeDoc);
var iframeWindow = goog.dom.getWindow(iframeDoc);
var button = new goog.ui.MenuButton();
iframeWindow.scrollTo(0, 0);
var node = iframeDom.getElement('demoMenuButton');
button.decorate(node);
var mockTimer = new goog.Timer();
// Don't start the timer. We manually dispatch the Tick event.
mockTimer.start = goog.nullFunction;
button.timer_ = mockTimer;
var replacer = new goog.testing.PropertyReplacer();
var positionMenuCalled;
var origPositionMenu = goog.bind(button.positionMenu, button);
replacer.set(button, 'positionMenu', function() {
positionMenuCalled = true;
origPositionMenu();
});
// Show the menu.
button.setOpen(true);
// Confirm the menu position
var menuNode = iframeDom.getElement('demoMenu');
assertRoughlyEquals(menuNode.offsetTop, node.offsetTop + node.offsetHeight,
20);
assertRoughlyEquals(menuNode.offsetLeft, node.offsetLeft, 20);
positionMenuCalled = false;
// A Tick event is dispatched.
mockTimer.dispatchEvent(goog.Timer.TICK);
assertFalse('positionMenu() shouldn\'t be called.', positionMenuCalled);
// Move the menu button by DOM structure change
var p1 = iframeDom.createDom('p', null, iframeDom.createTextNode('foo'));
var p2 = iframeDom.createDom('p', null, iframeDom.createTextNode('foo'));
var p3 = iframeDom.createDom('p', null, iframeDom.createTextNode('foo'));
iframeDom.insertSiblingBefore(p1, node);
iframeDom.insertSiblingBefore(p2, node);
iframeDom.insertSiblingBefore(p3, node);
// Confirm the menu is detached from the button.
assertTrue(Math.abs(node.offsetTop + node.offsetHeight -
menuNode.offsetTop) > 20);
positionMenuCalled = false;
// A Tick event is dispatched.
mockTimer.dispatchEvent(goog.Timer.TICK);
assertTrue('positionMenu() should be called.', positionMenuCalled);
// The menu is moved to appropriate position again.
assertRoughlyEquals(menuNode.offsetTop, node.offsetTop + node.offsetHeight,
20);
// Make the frame page scrollable.
var viewportHeight = iframeDom.getViewportSize().height;
var footer = iframeDom.getElement('footer');
goog.style.setSize(footer, 1, viewportHeight * 2);
// Change the viewport offset.
iframeWindow.scrollTo(0, viewportHeight);
// A Tick event is dispatched and positionMenu() should be called.
positionMenuCalled = false;
mockTimer.dispatchEvent(goog.Timer.TICK);
assertTrue('positionMenu() should be called.', positionMenuCalled);
goog.style.setSize(footer, 1, 1);
// Tear down.
iframeDom.removeNode(p1);
iframeDom.removeNode(p2);
iframeDom.removeNode(p3);
replacer.reset();
button.dispose();
}
/**
* Use a different button to position the menu and make sure it does so
* correctly.
*/
function <API key>() {
var node = goog.dom.getElement('demoMenuButton');
menuButton.decorate(node);
var posElement = goog.dom.getElement('positionElement');
menuButton.setPositionElement(posElement);
// Show the menu.
menuButton.setOpen(true);
// Confirm the menu position
var menuNode = menuButton.getMenu().getElement();
assertRoughlyEquals(menuNode.offsetTop, posElement.offsetTop
+ posElement.offsetHeight, 20);
assertRoughlyEquals(menuNode.offsetLeft, posElement.offsetLeft, 20);
}
/**
* Test forced positioning above the button.
*/
function <API key>() {
var node = goog.dom.getElement('demoMenuButton');
menuButton.decorate(node);
// Show the menu.
menuButton.setAlignMenuToStart(true); // Should get overridden below
menuButton.setScrollOnOverflow(true); // Should get overridden below
var position = new goog.positioning.<API key>(
menuButton.getElement(),
goog.positioning.Corner.TOP_START,
/* opt_adjust */ false, /* opt_resize */ false);
menuButton.setMenuPosition(position);
menuButton.setOpen(true);
// Confirm the menu position
var buttonBounds = goog.style.getBounds(node);
var menuNode = menuButton.getMenu().getElement();
var menuBounds = goog.style.getBounds(menuNode);
assertRoughlyEquals(menuBounds.top + menuBounds.height,
buttonBounds.top, 3);
assertRoughlyEquals(menuBounds.left, buttonBounds.left, 3);
// For this test to be valid, the node must have non-trival height.
assertRoughlyEquals(node.offsetHeight, 19, 3);
}
/**
* Test forced positioning below the button.
*/
function <API key>() {
var node = goog.dom.getElement('demoMenuButton');
menuButton.decorate(node);
// Show the menu.
menuButton.setAlignMenuToStart(true); // Should get overridden below
menuButton.setScrollOnOverflow(true); // Should get overridden below
var position = new goog.positioning.<API key>(
menuButton.getElement(),
goog.positioning.Corner.BOTTOM_START,
/* opt_adjust */ false, /* opt_resize */ false);
menuButton.setMenuPosition(position);
menuButton.setOpen(true);
// Confirm the menu position
var buttonBounds = goog.style.getBounds(node);
var menuNode = menuButton.getMenu().getElement();
var menuBounds = goog.style.getBounds(menuNode);
expectedFailures.expectFailureFor(isWinSafariBefore5());
try {
assertRoughlyEquals(menuBounds.top,
buttonBounds.top + buttonBounds.height, 3);
assertRoughlyEquals(menuBounds.left, buttonBounds.left, 3);
} catch (e) {
expectedFailures.handleException(e);
}
// For this test to be valid, the node must have non-trival height.
assertRoughlyEquals(node.offsetHeight, 19, 3);
}
function isWinSafariBefore5() {
return goog.userAgent.WINDOWS && goog.userAgent.product.SAFARI &&
goog.userAgent.product.isVersion(4) && !goog.userAgent.product.isVersion(5);
}
/**
* Tests that space, and only space, fire on key up.
*/
function <API key>() {
var node = goog.dom.getElement('demoMenuButton');
menuButton.decorate(node);
e = new goog.events.Event(goog.events.KeyHandler.EventType.KEY, menuButton);
e.preventDefault = goog.testing.recordFunction();
e.keyCode = goog.events.KeyCodes.SPACE;
menuButton.handleKeyEvent(e);
assertFalse('Menu must not have been triggered by Space keypress',
menuButton.isOpen());
assertNotNull('Page scrolling is prevented', e.preventDefault.getLastCall());
e = new goog.events.Event(goog.events.EventType.KEYUP, menuButton);
e.keyCode = goog.events.KeyCodes.SPACE;
menuButton.handleKeyEvent(e);
assertTrue('Menu must have been triggered by Space keyup',
menuButton.isOpen());
menuButton.getMenu().setHighlightedIndex(0);
e = new goog.events.Event(goog.events.KeyHandler.EventType.KEY, menuButton);
e.keyCode = goog.events.KeyCodes.DOWN;
menuButton.handleKeyEvent(e);
assertEquals('Highlighted menu item must have hanged by Down keypress',
1,
menuButton.getMenu().getHighlightedIndex());
menuButton.getMenu().setHighlightedIndex(0);
e = new goog.events.Event(goog.events.EventType.KEYUP, menuButton);
e.keyCode = goog.events.KeyCodes.DOWN;
menuButton.handleKeyEvent(e);
assertEquals('Highlighted menu item must not have changed by Down keyup',
0,
menuButton.getMenu().getHighlightedIndex());
}
/**
* Tests that preventing the button from closing also prevents the menu from
* being hidden.
*/
function testPreventHide() {
var node = goog.dom.getElement('demoMenuButton');
menuButton.decorate(node);
menuButton.<API key>(goog.ui.Component.State.OPENED, true);
// Show the menu.
menuButton.setOpen(true);
assertTrue('Menu button should be open.', menuButton.isOpen());
assertTrue('Menu should be visible.', menuButton.getMenu().isVisible());
var key = goog.events.listen(menuButton,
goog.ui.Component.EventType.CLOSE,
function(event) { event.preventDefault(); });
// Try to hide the menu.
menuButton.setOpen(false);
assertTrue('Menu button should still be open.', menuButton.isOpen());
assertTrue('Menu should still be visible.', menuButton.getMenu().isVisible());
// Remove listener and try again.
goog.events.unlistenByKey(key);
menuButton.setOpen(false);
assertFalse('Menu button should not be open.', menuButton.isOpen());
assertFalse('Menu should not be visible.', menuButton.getMenu().isVisible());
}
/**
* Tests that opening and closing the menu does not affect how adding or
* removing menu items changes the size of the menu.
*/
function <API key>() {
var node = goog.dom.getElement('demoMenuButton');
menuButton.decorate(node);
var menu = menuButton.getMenu();
// Show the menu.
menuButton.setOpen(true);
var originalSize = goog.style.getSize(menu.getElement());
// Check that removing an item while the menu is left open correctly changes
// the size of the menu.
// Remove an item using a method on Menu.
var item = menu.removeChildAt(0, true);
// Confirm size of menu changed.
var afterRemoveSize = goog.style.getSize(menu.getElement());
assertTrue('Height of menu must decrease after removing a menu item.',
afterRemoveSize.height < originalSize.height);
// Check that removing an item while the menu is closed, then opened
// (so that reposition is called) correctly changes the size of the menu.
// Hide menu.
menuButton.setOpen(false);
var item2 = menu.removeChildAt(0, true);
menuButton.setOpen(true);
// Confirm size of menu changed.
var <API key> = goog.style.getSize(menu.getElement());
assertTrue('Height of menu must decrease after removing a second menu item.',
<API key>.height < afterRemoveSize.height);
// Check that adding an item while the menu is opened, then closed, then
// opened, correctly changes the size of the menu.
// Add an item, this time using a MenuButton method.
menuButton.setOpen(true);
menuButton.addItem(item2);
menuButton.setOpen(false);
menuButton.setOpen(true);
// Confirm size of menu changed.
var afterAddSize = goog.style.getSize(menu.getElement());
assertTrue('Height of menu must increase after adding a menu item.',
<API key>.height < afterAddSize.height);
assertEquals(
'Removing and adding back items must not change the height of a menu.',
afterRemoveSize.height, afterAddSize.height);
// Add back the last item to keep state consistent.
menuButton.addItem(item);
}
/**
* Tests that adding and removing items from a menu with scrollOnOverflow is on
* correctly resizes the menu.
*/
function <API key>() {
var node = goog.dom.getElement('demoMenuButton');
menuButton.decorate(node);
var menu = menuButton.getMenu();
// Show the menu.
menuButton.setScrollOnOverflow(true);
menuButton.setOpen(true);
var originalSize = goog.style.getSize(menu.getElement());
// Check that removing an item while the menu is left open correctly changes
// the size of the menu.
// Remove an item using a method on Menu.
var item = menu.removeChildAt(0, true);
menuButton.invalidateMenuSize();
menuButton.positionMenu();
// Confirm size of menu changed.
var afterRemoveSize = goog.style.getSize(menu.getElement());
assertTrue('Height of menu must decrease after removing a menu item.',
afterRemoveSize.height < originalSize.height);
var item2 = menu.removeChildAt(0, true);
menuButton.invalidateMenuSize();
menuButton.positionMenu();
// Confirm size of menu changed.
var <API key> = goog.style.getSize(menu.getElement());
assertTrue('Height of menu must decrease after removing a second menu item.',
<API key>.height < afterRemoveSize.height);
// Check that adding an item while the menu is opened correctly changes the
// size of the menu.
menuButton.addItem(item2);
menuButton.invalidateMenuSize();
menuButton.positionMenu();
// Confirm size of menu changed.
var afterAddSize = goog.style.getSize(menu.getElement());
assertTrue('Height of menu must increase after adding a menu item.',
<API key>.height < afterAddSize.height);
assertEquals(
'Removing and adding back items must not change the height of a menu.',
afterRemoveSize.height, afterAddSize.height);
}
/**
* Try rendering the menu as a sibling rather than as a child of the dom.
*/
function <API key>() {
menuButton.<API key>(true);
menuButton.addItem(new goog.ui.MenuItem('Menu item 1'));
menuButton.addItem(new goog.ui.MenuItem('Menu item 2'));
// By default the menu is rendered into the top level dom and the button
// is rendered into whatever parent we provide. If we don't provide a
// parent then we aren't really testing anything, since both would be, by
// default, rendered into the top level dom, and therefore siblings.
menuButton.render(goog.dom.getElement('siblingTest'));
menuButton.setOpen(true);
assertEquals(
menuButton.getElement().parentNode,
menuButton.getMenu().getElement().parentNode);
}
function <API key>() {
assertTrue(menuButton.isAlignMenuToStart());
menuButton.setAlignMenuToStart(false);
assertFalse(menuButton.isAlignMenuToStart());
menuButton.setAlignMenuToStart(true);
assertTrue(menuButton.isAlignMenuToStart());
}
function <API key>() {
assertFalse(menuButton.isScrollOnOverflow());
menuButton.setScrollOnOverflow(true);
assertTrue(menuButton.isScrollOnOverflow());
menuButton.setScrollOnOverflow(false);
assertFalse(menuButton.isScrollOnOverflow());
}
</script>
<p>
Here's a menubutton defined in markup:
</p>
<div id="siblingTest"></div>
<div id="demoMenuButton" class="goog-menu-button">
<div id="demoMenu" class="goog-menu">
<div id='menuItem1' class="goog-menuitem">Annual Report.pdf</div>
<div id='menuItem2' class="goog-menuitem">Quarterly Update.pdf</div>
<div id='menuItem3' class="goog-menuitem">Enemies List.txt</div>
</div>
</div>
<div id="footer"></div>
</body>
</html> |
var step = '<font class="fontSize">'
+'<p>Test Steps</p>'
+'<ol>'
+'<li>Click "Hello, World!".</li>'
+'<li>Click "WeChat".</li>'
+'</ol>'
+'<p>Expected Result</p>'
+'<ol>'
+'<li>If WhatsApp was installed, it will be launched, and can send "Hello, World!" to your contacts if you have. If it was not installed, will report "<API key>".</li>'
+'<li>If WeChat(WeiXin) was installed, it will be launched. If it was not installed, XWalkView will load its download page.</li>'
+'</ol>'
+'</font>'; |
.result {
output: 'squoted';
output: squoted;
output: "[squoted]";
output: "squoted";
output: "squoted";
output: "['squoted']"; } |
// This file is part of the GNU ISO C++ Library. This library is free
// software; you can redistribute it and/or modify it under the
// Free Software Foundation; either version 2, or (at your option)
// any later version.
// This library is distributed in the hope that it will be useful,
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// with this library; see the file COPYING. If not, write to the Free
// Software Foundation, 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
// USA.
#include <deque>
#include <ext/new_allocator.h>
using namespace std;
using __gnu_cxx::new_allocator;
template<typename T>
class clear_alloc : public new_allocator<T>
{
public:
template <typename T1>
struct rebind
{ typedef clear_alloc<T1> other; };
virtual void clear() throw()
{ }
clear_alloc() throw()
{ }
clear_alloc(clear_alloc const&) throw() : new_allocator<T>()
{ }
template<typename T1>
clear_alloc(clear_alloc<T1> const&) throw()
{ }
virtual ~clear_alloc() throw()
{ this->clear(); }
T* allocate(typename new_allocator<T>::size_type n, const void *hint = 0)
{
this->clear();
return new_allocator<T>::allocate(n, hint);
}
void deallocate(T *ptr, typename new_allocator<T>::size_type n)
{
this->clear();
new_allocator<T>::deallocate(ptr, n);
}
};
template<typename Container>
void Check_Container()
{
Container* pic = new Container;
int x = 230;
while (x
{
pic->push_back(x);
}
pic->get_allocator();
// The following has led to infinite recursions or cores.
pic->clear();
delete pic;
}
int main()
{
Check_Container<std::deque<int, clear_alloc<int> > >();
return 0;
} |
package com.thaiopensource.relaxng.output.xsd.basic;
import com.thaiopensource.xml.util.Name;
public interface Structure {
Name getName();
<T> T accept(StructureVisitor<T> visitor);
} |
// <API key>: Apache-2.0 WITH LLVM-exception
// This file contains the declarations of the VEMCAsmInfo properties.
#include "VEMCAsmInfo.h"
#include "llvm/ADT/Triple.h"
#include "llvm/BinaryFormat/Dwarf.h"
#include "llvm/MC/MCExpr.h"
#include "llvm/MC/MCStreamer.h"
#include "llvm/MC/MCTargetOptions.h"
using namespace llvm;
void VEELFMCAsmInfo::anchor() {}
VEELFMCAsmInfo::VEELFMCAsmInfo(const Triple &TheTriple) {
CodePointerSize = <API key> = 8;
MaxInstLength = MinInstAlignment = 8;
// VE uses ".*byte" directive for unaligned data.
Data8bitsDirective = "\t.byte\t";
Data16bitsDirective = "\t.2byte\t";
Data32bitsDirective = "\t.4byte\t";
Data64bitsDirective = "\t.8byte\t";
// Uses '.section' before '.bss' directive. VE requires this although
// assembler manual says sinple '.bss' is supported.
<API key> = true;
<API key> = true;
} |
#include <signal.h>
#include <stdarg.h>
#include "webrtc/base/gunit.h"
#include "webrtc/base/logging.h"
#include "webrtc/base/<API key>.h"
#include "webrtc/base/scoped_ptr.h"
#include "webrtc/base/socket_unittest.h"
#include "webrtc/base/testutils.h"
#include "webrtc/base/thread.h"
#include "webrtc/test/testsupport/gtest_disable.h"
namespace rtc {
class PhysicalSocketTest : public SocketTest {
};
TEST_F(PhysicalSocketTest, TestConnectIPv4) {
SocketTest::TestConnectIPv4();
}
TEST_F(PhysicalSocketTest, TestConnectIPv6) {
SocketTest::TestConnectIPv6();
}
TEST_F(PhysicalSocketTest, <API key>) {
SocketTest::<API key>();
}
TEST_F(PhysicalSocketTest, <API key>) {
SocketTest::<API key>();
}
TEST_F(PhysicalSocketTest, TestConnectFailIPv4) {
SocketTest::TestConnectFailIPv4();
}
TEST_F(PhysicalSocketTest, TestConnectFailIPv6) {
SocketTest::TestConnectFailIPv6();
}
TEST_F(PhysicalSocketTest, <API key>) {
SocketTest::<API key>();
}
TEST_F(PhysicalSocketTest, <API key>) {
SocketTest::<API key>();
}
TEST_F(PhysicalSocketTest, <API key>) {
SocketTest::<API key>();
}
TEST_F(PhysicalSocketTest, <API key>) {
SocketTest::<API key>();
}
TEST_F(PhysicalSocketTest, <API key>) {
SocketTest::<API key>();
}
TEST_F(PhysicalSocketTest, <API key>) {
SocketTest::<API key>();
}
TEST_F(PhysicalSocketTest, <API key>) {
SocketTest::<API key>();
}
TEST_F(PhysicalSocketTest, <API key>) {
SocketTest::<API key>();
}
TEST_F(PhysicalSocketTest, <API key>) {
SocketTest::<API key>();
}
TEST_F(PhysicalSocketTest, <API key>) {
SocketTest::<API key>();
}
TEST_F(PhysicalSocketTest, TestServerCloseIPv4) {
SocketTest::TestServerCloseIPv4();
}
TEST_F(PhysicalSocketTest, TestServerCloseIPv6) {
SocketTest::TestServerCloseIPv6();
}
TEST_F(PhysicalSocketTest, <API key>) {
SocketTest::<API key>();
}
TEST_F(PhysicalSocketTest, <API key>) {
SocketTest::<API key>();
}
TEST_F(PhysicalSocketTest, <API key>) {
SocketTest::<API key>();
}
TEST_F(PhysicalSocketTest, <API key>) {
SocketTest::<API key>();
}
TEST_F(PhysicalSocketTest, TestTcpIPv4) {
SocketTest::TestTcpIPv4();
}
TEST_F(PhysicalSocketTest, TestTcpIPv6) {
SocketTest::TestTcpIPv6();
}
TEST_F(PhysicalSocketTest, TestUdpIPv4) {
SocketTest::TestUdpIPv4();
}
TEST_F(PhysicalSocketTest, TestUdpIPv6) {
SocketTest::TestUdpIPv6();
}
// Disable for TSan v2, see
#if !defined(THREAD_SANITIZER)
TEST_F(PhysicalSocketTest, <API key>) {
SocketTest::<API key>();
}
#endif // if !defined(THREAD_SANITIZER)
TEST_F(PhysicalSocketTest, <API key>) {
SocketTest::<API key>();
}
TEST_F(PhysicalSocketTest, <API key>) {
SocketTest::<API key>();
}
TEST_F(PhysicalSocketTest, <API key>) {
SocketTest::<API key>();
}
#if defined(WEBRTC_POSIX)
class <API key> : public testing::Test {
public:
static void RecordSignal(int signum) {
signals_received_.push_back(signum);
signaled_thread_ = Thread::Current();
}
protected:
void SetUp() {
ss_.reset(new <API key>());
}
void TearDown() {
ss_.reset(NULL);
signals_received_.clear();
signaled_thread_ = NULL;
}
bool ExpectSignal(int signum) {
if (signals_received_.empty()) {
LOG(LS_ERROR) << "ExpectSignal(): No signal received";
return false;
}
if (signals_received_[0] != signum) {
LOG(LS_ERROR) << "ExpectSignal(): Received signal " <<
signals_received_[0] << ", expected " << signum;
return false;
}
signals_received_.erase(signals_received_.begin());
return true;
}
bool ExpectNone() {
bool ret = signals_received_.empty();
if (!ret) {
LOG(LS_ERROR) << "ExpectNone(): Received signal " << signals_received_[0]
<< ", expected none";
}
return ret;
}
static std::vector<int> signals_received_;
static Thread *signaled_thread_;
scoped_ptr<<API key>> ss_;
};
std::vector<int> <API key>::signals_received_;
Thread *<API key>::signaled_thread_ = NULL;
// Test receiving a synchronous signal while not in Wait() and then entering
// Wait() afterwards.
TEST_F(<API key>, RaiseThenWait) {
ASSERT_TRUE(ss_-><API key>(SIGTERM, &RecordSignal));
raise(SIGTERM);
EXPECT_TRUE(ss_->Wait(0, true));
EXPECT_TRUE(ExpectSignal(SIGTERM));
EXPECT_TRUE(ExpectNone());
}
// Test that we can handle getting tons of repeated signals and that we see all
// the different ones.
TEST_F(<API key>, InsanelyManySignals) {
ss_-><API key>(SIGTERM, &RecordSignal);
ss_-><API key>(SIGINT, &RecordSignal);
for (int i = 0; i < 10000; ++i) {
raise(SIGTERM);
}
raise(SIGINT);
EXPECT_TRUE(ss_->Wait(0, true));
// Order will be lowest signal numbers first.
EXPECT_TRUE(ExpectSignal(SIGINT));
EXPECT_TRUE(ExpectSignal(SIGTERM));
EXPECT_TRUE(ExpectNone());
}
// Test that a signal during a Wait() call is detected.
TEST_F(<API key>, SignalDuringWait) {
ss_-><API key>(SIGALRM, &RecordSignal);
alarm(1);
EXPECT_TRUE(ss_->Wait(1500, true));
EXPECT_TRUE(ExpectSignal(SIGALRM));
EXPECT_TRUE(ExpectNone());
}
class <API key> : public Runnable {
void Run(Thread *thread) {
thread->socketserver()->Wait(1000, false);
// Allow SIGTERM. This will be the only thread with it not masked so it will
// be delivered to us.
sigset_t mask;
sigemptyset(&mask);
pthread_sigmask(SIG_SETMASK, &mask, NULL);
// Raise it.
raise(SIGTERM);
}
};
// Test that it works no matter what thread the kernel chooses to give the
// signal to (since it's not guaranteed to be the one that Wait() runs on).
TEST_F(<API key>, <API key>) {
ss_-><API key>(SIGTERM, &RecordSignal);
// Mask out SIGTERM so that it can't be delivered to this thread.
sigset_t mask;
sigemptyset(&mask);
sigaddset(&mask, SIGTERM);
EXPECT_EQ(0, pthread_sigmask(SIG_SETMASK, &mask, NULL));
// Start a new thread that raises it. It will have to be delivered to that
// thread. Our implementation should safely handle it and dispatch
// RecordSignal() on this thread.
scoped_ptr<Thread> thread(new Thread());
scoped_ptr<<API key>> runnable(new <API key>());
thread->Start(runnable.get());
EXPECT_TRUE(ss_->Wait(1500, true));
EXPECT_TRUE(ExpectSignal(SIGTERM));
EXPECT_EQ(Thread::Current(), signaled_thread_);
EXPECT_TRUE(ExpectNone());
}
#endif
} // namespace rtc |
<?php
namespace Symfony\Component\HttpFoundation\Session\Storage\Handler;
class <API key> implements \<API key>
{
/**
* @var \Memcached Memcached driver
*/
private $memcached;
/**
* @var int Time to live in seconds
*/
private $ttl;
/**
* @var string Key prefix for shared environments
*/
private $prefix;
/**
* Constructor.
*
* List of available options:
* * prefix: The prefix to use for the memcached keys in order to avoid collision
* * expiretime: The time to live in seconds
*
* @param \Memcached $memcached A \Memcached instance
* @param array $options An associative array of Memcached options
*
* @throws \<API key> When unsupported options are passed
*/
public function __construct(\Memcached $memcached, array $options = array())
{
$this->memcached = $memcached;
if ($diff = array_diff(array_keys($options), array('prefix', 'expiretime'))) {
throw new \<API key>(sprintf(
'The following options are not supported "%s"', implode(', ', $diff)
));
}
$this->ttl = isset($options['expiretime']) ? (int) $options['expiretime'] : 86400;
$this->prefix = isset($options['prefix']) ? $options['prefix'] : 'sf2s';
}
/**
* {@inheritdoc}
*/
public function open($savePath, $sessionName)
{
return true;
}
/**
* {@inheritdoc}
*/
public function close()
{
return true;
}
/**
* {@inheritdoc}
*/
public function read($sessionId)
{
return $this->memcached->get($this->prefix.$sessionId) ?: '';
}
/**
* {@inheritdoc}
*/
public function write($sessionId, $data)
{
return $this->memcached->set($this->prefix.$sessionId, $data, time() + $this->ttl);
}
/**
* {@inheritdoc}
*/
public function destroy($sessionId)
{
return $this->memcached->delete($this->prefix.$sessionId);
}
/**
* {@inheritdoc}
*/
public function gc($maxlifetime)
{
// not required here because memcached will auto expire the records anyhow.
return true;
}
/**
* Return a Memcached instance.
*
* @return \Memcached
*/
protected function getMemcached()
{
return $this->memcached;
}
} |
goog.provide('ng.material.components.icon');
goog.require('ng.material.core');
/**
* @ngdoc module
* @name material.components.icon
* @description
* Icon
*/
angular.module('material.components.icon', [
'material.core'
]);
angular
.module('material.components.icon')
.directive('mdIcon', ['$mdIcon', '$mdTheming', '$mdAria', mdIconDirective]);
function mdIconDirective($mdIcon, $mdTheming, $mdAria ) {
return {
scope: {
fontSet : '@mdFontSet',
fontIcon: '@mdFontIcon',
svgIcon : '@mdSvgIcon',
svgSrc : '@mdSvgSrc'
},
restrict: 'E',
link : postLink
};
/**
* Directive postLink
* Supports embedded SVGs, font-icons, & external SVGs
*/
function postLink(scope, element, attr) {
$mdTheming(element);
prepareForFontIcon();
// If using a font-icon, then the textual name of the icon itself
// provides the aria-label.
var label = attr.alt || scope.fontIcon || scope.svgIcon || element.text();
var attrName = attr.$normalize(attr.$attr.mdSvgIcon || attr.$attr.mdSvgSrc || '');
if ( !attr['aria-label'] ) {
if (label != '' && !parentsHaveText() ) {
$mdAria.expect(element, 'aria-label', label);
$mdAria.expect(element, 'role', 'img');
} else if ( !element.text() ) {
// If not a font-icon with ligature, then
// hide from the accessibility layer.
$mdAria.expect(element, 'aria-hidden', 'true');
}
}
if (attrName) {
// Use either pre-configured SVG or URL source, respectively.
attr.$observe(attrName, function(attrVal) {
element.empty();
if (attrVal) {
$mdIcon(attrVal).then(function(svg) {
element.append(svg);
});
}
});
}
function parentsHaveText() {
var parent = element.parent();
if (parent.attr('aria-label') || parent.text()) {
return true;
}
else if(parent.parent().attr('aria-label') || parent.parent().text()) {
return true;
}
return false;
}
function prepareForFontIcon () {
if (!scope.svgIcon && !scope.svgSrc) {
if (scope.fontIcon) {
element.addClass('md-font ' + scope.fontIcon);
}
if (scope.fontSet) {
element.addClass($mdIcon.fontSet(scope.fontSet));
}
if (<API key>()) {
element.addClass($mdIcon.fontSet());
}
}
function <API key>() {
return !scope.fontIcon && !scope.fontSet;
}
}
}
}
angular
.module('material.components.icon' )
.provider('$mdIcon', MdIconProvider);
/**
* @ngdoc service
* @name $mdIconProvider
* @module material.components.icon
*
* @description
* `$mdIconProvider` is used only to register icon IDs with URLs. These configuration features allow
* icons and icon sets to be pre-registered and associated with source URLs **before** the `<md-icon />`
* directives are compiled.
*
* If using font-icons, the developer is repsonsible for loading the fonts.
*
* If using SVGs, loading of the actual svg files are deferred to on-demand requests and are loaded
* internally by the `$mdIcon` service using the `$http` service. When an SVG is requested by name/ID,
* the `$mdIcon` service searches its registry for the associated source URL;
* that URL is used to on-demand load and parse the SVG dynamically.
*
* @usage
* <hljs lang="js">
* app.config(function($mdIconProvider) {
*
* // Configure URLs for icons specified by [set:]id.
*
* $mdIconProvider
* .defaultFontSet( 'fontawesome' )
* .defaultIconSet('my/app/icons.svg') // Register a default set of SVG icons
* .iconSet('social', 'my/app/social.svg') // Register a named icon set of SVGs
* .icon('android', 'my/app/android.svg') // Register a specific icon (by name)
* .icon('work:chair', 'my/app/chair.svg'); // Register icon in a specific set
* });
* </hljs>
*
* SVG icons and icon sets can be easily pre-loaded and cached using either (a) a build process or (b) a runtime
* **startup** process (shown below):
*
* <hljs lang="js">
* app.config(function($mdIconProvider) {
*
* // Register a default set of SVG icon definitions
* $mdIconProvider.defaultIconSet('my/app/icons.svg')
*
* })
* .run(function($http, $templateCache){
*
* // Pre-fetch icons sources by URL and cache in the $templateCache...
* // subsequent $http calls will look there first.
*
* var urls = [ 'imy/app/icons.svg', 'img/icons/android.svg'];
*
* angular.forEach(urls, function(url) {
* $http.get(url, {cache: $templateCache});
* });
*
* });
*
* </hljs>
*
* NOTE: the loaded SVG data is subsequently cached internally for future requests.
*
*/
/**
* @ngdoc method
* @name $mdIconProvider#icon
*
* @description
* Register a source URL for a specific icon name; the name may include optional 'icon set' name prefix.
* These icons will later be retrieved from the cache using `$mdIcon( <icon name> )`
*
* @param {string} id Icon name/id used to register the icon
* @param {string} url specifies the external location for the data file. Used internally by `$http` to load the
* data or as part of the lookup in `$templateCache` if pre-loading was configured.
* @param {number=} viewBoxSize Sets the width and height the icon's viewBox.
* It is ignored for icons with an existing viewBox. Default size is 24.
*
* @returns {obj} an `$mdIconProvider` reference; used to support method call chains for the API
*
* @usage
* <hljs lang="js">
* app.config(function($mdIconProvider) {
*
* // Configure URLs for icons specified by [set:]id.
*
* $mdIconProvider
* .icon('android', 'my/app/android.svg') // Register a specific icon (by name)
* .icon('work:chair', 'my/app/chair.svg'); // Register icon in a specific set
* });
* </hljs>
*
*/
/**
* @ngdoc method
* @name $mdIconProvider#iconSet
*
* @description
* Register a source URL for a 'named' set of icons; group of SVG definitions where each definition
* has an icon id. Individual icons can be subsequently retrieved from this cached set using
* `$mdIcon(<icon set name>:<icon name>)`
*
* @param {string} id Icon name/id used to register the iconset
* @param {string} url specifies the external location for the data file. Used internally by `$http` to load the
* data or as part of the lookup in `$templateCache` if pre-loading was configured.
* @param {number=} viewBoxSize Sets the width and height of the viewBox of all icons in the set.
* It is ignored for icons with an existing viewBox. All icons in the icon set should be the same size.
* Default value is 24.
*
* @returns {obj} an `$mdIconProvider` reference; used to support method call chains for the API
*
*
* @usage
* <hljs lang="js">
* app.config(function($mdIconProvider) {
*
* // Configure URLs for icons specified by [set:]id.
*
* $mdIconProvider
* .iconSet('social', 'my/app/social.svg') // Register a named icon set
* });
* </hljs>
*
*/
/**
* @ngdoc method
* @name $mdIconProvider#defaultIconSet
*
* @description
* Register a source URL for the default 'named' set of icons. Unless explicitly registered,
* subsequent lookups of icons will failover to search this 'default' icon set.
* Icon can be retrieved from this cached, default set using `$mdIcon(<name>)`
*
* @param {string} url specifies the external location for the data file. Used internally by `$http` to load the
* data or as part of the lookup in `$templateCache` if pre-loading was configured.
* @param {number=} viewBoxSize Sets the width and height of the viewBox of all icons in the set.
* It is ignored for icons with an existing viewBox. All icons in the icon set should be the same size.
* Default value is 24.
*
* @returns {obj} an `$mdIconProvider` reference; used to support method call chains for the API
*
* @usage
* <hljs lang="js">
* app.config(function($mdIconProvider) {
*
* // Configure URLs for icons specified by [set:]id.
*
* $mdIconProvider
* .defaultIconSet( 'my/app/social.svg' ) // Register a default icon set
* });
* </hljs>
*
*/
/**
* @ngdoc method
* @name $mdIconProvider#defaultFontSet
*
* @description
* When using Font-Icons, Angular Material assumes the the Material Design icons will be used and automatically
* configures the default font-set == 'material-icons'. Note that the font-set references the font-icon library
* class style that should be applied to the `<md-icon>`.
*
* Configuring the default means that the attributes
* `md-font-set="material-icons"` or `class="material-icons"` do not need to be explicitly declared on the
* `<md-icon>` markup. For example:
*
* `<md-icon> face </md-icon>`
* will render as
* `<span class="material-icons"> face </span>`, and
*
* `<md-icon md-font-set="fa"> face </md-icon>`
* will render as
* `<span class="fa"> face </span>`
*
* @param {string} name of the font-library style that should be applied to the md-icon DOM element
*
* @usage
* <hljs lang="js">
* app.config(function($mdIconProvider) {
* $mdIconProvider.defaultFontSet( 'fontawesome' );
* });
* </hljs>
*
*/
/**
* @ngdoc method
* @name $mdIconProvider#defaultViewBoxSize
*
* @description
* While `<md-icon />` markup can also be style with sizing CSS, this method configures
* the default width **and** height used for all icons; unless overridden by specific CSS.
* The default sizing is (24px, 24px).
* @param {number=} viewBoxSize Sets the width and height of the viewBox for an icon or an icon set.
* All icons in a set should be the same size. The default value is 24.
*
* @returns {obj} an `$mdIconProvider` reference; used to support method call chains for the API
*
* @usage
* <hljs lang="js">
* app.config(function($mdIconProvider) {
*
* // Configure URLs for icons specified by [set:]id.
*
* $mdIconProvider
* .defaultViewBoxSize(36) // Register a default icon size (width == height)
* });
* </hljs>
*
*/
var config = {
defaultViewBoxSize: 24,
defaultFontSet: 'material-icons',
fontSets : [ ]
};
function MdIconProvider() { }
MdIconProvider.prototype = {
icon : function (id, url, viewBoxSize) {
if ( id.indexOf(':') == -1 ) id = '$default:' + id;
config[id] = new ConfigurationItem(url, viewBoxSize );
return this;
},
iconSet : function (id, url, viewBoxSize) {
config[id] = new ConfigurationItem(url, viewBoxSize );
return this;
},
defaultIconSet : function (url, viewBoxSize) {
var setName = '$default';
if ( !config[setName] ) {
config[setName] = new ConfigurationItem(url, viewBoxSize );
}
config[setName].viewBoxSize = viewBoxSize || config.defaultViewBoxSize;
return this;
},
defaultViewBoxSize : function (viewBoxSize) {
config.defaultViewBoxSize = viewBoxSize;
return this;
},
/**
* Register an alias name associated with a font-icon library style ;
*/
fontSet : function fontSet(alias, className) {
config.fontSets.push({
alias : alias,
fontSet : className || alias
});
return this;
},
/**
* Specify a default style name associated with a font-icon library
* fallback to Material Icons.
*
*/
defaultFontSet : function defaultFontSet(className) {
config.defaultFontSet = !className ? '' : className;
return this;
},
defaultIconSize : function defaultIconSize(iconSize) {
config.defaultIconSize = iconSize;
return this;
},
preloadIcons: function ($templateCache) {
var iconProvider = this;
var svgRegistry = [
{
id : 'md-tabs-arrow',
url: 'md-tabs-arrow.svg',
svg: '<svg version="1.1" x="0px" y="0px" viewBox="0 0 24 24"><g><polygon points="15.4,7.4 14,6 8,12 14,18 15.4,16.6 10.8,12 "/></g></svg>'
},
{
id : 'md-close',
url: 'md-close.svg',
svg: '<svg version="1.1" x="0px" y="0px" viewBox="0 0 24 24"><g><path d="M19 6.41l-1.41-1.41-5.59 5.59-5.59-5.59-1.41 1.41 5.59 5.59-5.59 5.59 1.41 1.41 5.59-5.59 5.59 5.59 1.41-1.41-5.59-5.59z"/></g></svg>'
},
{
id: 'md-cancel',
url: 'md-cancel.svg',
svg: '<svg version="1.1" x="0px" y="0px" viewBox="0 0 24 24"><g><path d="M12 2c-5.53 0-10 4.47-10 10s4.47 10 10 10 10-4.47 10-10-4.47-10-10-10zm5 13.59l-1.41 1.41-3.59-3.59-3.59 3.59-1.41-1.41 3.59-3.59-3.59-3.59 1.41-1.41 3.59 3.59 3.59-3.59 1.41 1.41-3.59 3.59 3.59 3.59z"/></g></svg>'
},
{
id: 'md-menu',
url: 'md-menu.svg',
svg: '<svg version="1.1" x="0px" y="0px" viewBox="0 0 24 24"><path d="M3,6H21V8H3V6M3,11H21V13H3V11M3,16H21V18H3V16Z" /></svg>'
},
{
id: 'md-toggle-arrow',
url: 'md-toggle-arrow-svg',
svg: '<svg version="1.1" x="0px" y="0px" viewBox="0 0 48 48"><path d="M24 16l-12 12 2.83 2.83 9.17-9.17 9.17 9.17 2.83-2.83z"/><path d="M0 0h48v48h-48z" fill="none"/></svg>'
},
{
id: 'md-calendar',
url: 'md-calendar.svg',
svg: '<svg xmlns="http:
}
];
svgRegistry.forEach(function(asset){
iconProvider.icon(asset.id, asset.url);
$templateCache.put(asset.url, asset.svg);
});
},
$get : ['$http', '$q', '$log', '$templateCache', function($http, $q, $log, $templateCache) {
this.preloadIcons($templateCache);
return MdIconService(config, $http, $q, $log, $templateCache);
}]
};
/**
* Configuration item stored in the Icon registry; used for lookups
* to load if not already cached in the `loaded` cache
*/
function ConfigurationItem(url, viewBoxSize) {
this.url = url;
this.viewBoxSize = viewBoxSize || config.defaultViewBoxSize;
}
/**
* @ngdoc service
* @name $mdIcon
* @module material.components.icon
*
* @description
* The `$mdIcon` service is a function used to lookup SVG icons.
*
* @param {string} id Query value for a unique Id or URL. If the argument is a URL, then the service will retrieve the icon element
* from its internal cache or load the icon and cache it first. If the value is not a URL-type string, then an ID lookup is
* performed. The Id may be a unique icon ID or may include an iconSet ID prefix.
*
* For the **id** query to work properly, this means that all id-to-URL mappings must have been previously configured
* using the `$mdIconProvider`.
*
* @returns {obj} Clone of the initial SVG DOM element; which was created from the SVG markup in the SVG data file.
*
* @usage
* <hljs lang="js">
* function SomeDirective($mdIcon) {
*
* // See if the icon has already been loaded, if not
* // then lookup the icon from the registry cache, load and cache
* // it for future requests.
* // NOTE: ID queries require configuration with $mdIconProvider
*
* $mdIcon('android').then(function(iconEl) { element.append(iconEl); });
* $mdIcon('work:chair').then(function(iconEl) { element.append(iconEl); });
*
* // Load and cache the external SVG using a URL
*
* $mdIcon('img/icons/android.svg').then(function(iconEl) {
* element.append(iconEl);
* });
* };
* </hljs>
*
* NOTE: The `<md-icon /> ` directive internally uses the `$mdIcon` service to query, loaded, and instantiate
* SVG DOM elements.
*/
/* ngInject */
function MdIconService(config, $http, $q, $log, $templateCache) {
var iconCache = {};
var urlRegex = /[-a-zA-Z0-9@:%_\+.~#?&//=]{2,256}\.[a-z]{2,4}\b(\/[-a-zA-Z0-9@:%_\+.~#?&//=]*)?/i;
Icon.prototype = { clone : cloneSVG, prepare: prepareAndStyle };
getIcon.fontSet = <API key>;
// Publish service...
return getIcon;
/**
* Actual $mdIcon service is essentially a lookup function
*/
function getIcon(id) {
id = id || '';
// If already loaded and cached, use a clone of the cached icon.
// Otherwise either load by URL, or lookup in the registry and then load by URL, and cache.
if ( iconCache[id] ) return $q.when( iconCache[id].clone() );
if ( urlRegex.test(id) ) return loadByURL(id).then( cacheIcon(id) );
if ( id.indexOf(':') == -1 ) id = '$default:' + id;
var load = config[id] ? loadByID : loadFromIconSet;
return load(id)
.then( cacheIcon(id) );
}
/**
* Lookup registered fontSet style using its alias...
* If not found,
*/
function <API key>(alias) {
var useDefault = angular.isUndefined(alias) || !(alias && alias.length);
if ( useDefault ) return config.defaultFontSet;
var result = alias;
angular.forEach(config.fontSets, function(it){
if ( it.alias == alias ) result = it.fontSet || result;
});
return result;
}
/**
* Prepare and cache the loaded icon for the specified `id`
*/
function cacheIcon( id ) {
return function updateCache( icon ) {
iconCache[id] = isIcon(icon) ? icon : new Icon(icon, config[id]);
return iconCache[id].clone();
};
}
/**
* Lookup the configuration in the registry, if !registered throw an error
* otherwise load the icon [on-demand] using the registered URL.
*
*/
function loadByID(id) {
var iconConfig = config[id];
return loadByURL(iconConfig.url).then(function(icon) {
return new Icon(icon, iconConfig);
});
}
/**
* Loads the file as XML and uses querySelector( <id> ) to find
* the desired node...
*/
function loadFromIconSet(id) {
var setName = id.substring(0, id.lastIndexOf(':')) || '$default';
var iconSetConfig = config[setName];
return !iconSetConfig ? announceIdNotFound(id) : loadByURL(iconSetConfig.url).then(extractFromSet);
function extractFromSet(set) {
var iconName = id.slice(id.lastIndexOf(':') + 1);
var icon = set.querySelector('#' + iconName);
return !icon ? announceIdNotFound(id) : new Icon(icon, iconSetConfig);
}
function announceIdNotFound(id) {
var msg = 'icon ' + id + ' not found';
$log.warn(msg);
return $q.reject(msg || id);
}
}
/**
* Load the icon by URL (may use the $templateCache).
* Extract the data for later conversion to Icon
*/
function loadByURL(url) {
return $http
.get(url, { cache: $templateCache })
.then(function(response) {
return angular.element('<div>').append(response.data).find('svg')[0];
}).catch(announceNotFound);
}
/**
* Catch HTTP or generic errors not related to incorrect icon IDs.
*/
function announceNotFound(err) {
var msg = angular.isString(err) ? err : (err.message || err.data || err.statusText);
$log.warn(msg);
return $q.reject(msg);
}
/**
* Check target signature to see if it is an Icon instance.
*/
function isIcon(target) {
return angular.isDefined(target.element) && angular.isDefined(target.config);
}
/**
* Define the Icon class
*/
function Icon(el, config) {
if (el.tagName != 'svg') {
el = angular.element('<svg xmlns="http:
}
// Inject the namespace if not available...
if ( !el.getAttribute('xmlns') ) {
el.setAttribute('xmlns', "http:
}
this.element = el;
this.config = config;
this.prepare();
}
/**
* Prepare the DOM element that will be cached in the
* loaded iconCache store.
*/
function prepareAndStyle() {
var viewBoxSize = this.config ? this.config.viewBoxSize : config.defaultViewBoxSize;
angular.forEach({
'fit' : '',
'height': '100%',
'width' : '100%',
'preserveAspectRatio': 'xMidYMid meet',
'viewBox' : this.element.getAttribute('viewBox') || ('0 0 ' + viewBoxSize + ' ' + viewBoxSize)
}, function(val, attr) {
this.element.setAttribute(attr, val);
}, this);
angular.forEach({
'pointer-events' : 'none',
'display' : 'block'
}, function(val, style) {
this.element.style[style] = val;
}, this);
}
/**
* Clone the Icon DOM element.
*/
function cloneSVG(){
return this.element.cloneNode(true);
}
}
MdIconService.$inject = ["config", "$http", "$q", "$log", "$templateCache"];
ng.material.components.icon = angular.module("material.components.icon"); |
<reference path='refs.ts'/>
module TDev
{
export class DragHandler
extends ClickHandler
{
private offX = 0;
private offY = 0;
public lockX = false;
public lockY = false;
private isTap = true;
private lastX = 0;
private lastY = 0;
private beginTime = 0;
public moveElt = true;
private isIeTouch = false;
constructor(public helt:HTMLElement, public cb:(tag:string, x:number, y:number, x2:number, y2:number)=>void) {
super(helt, null)
this.helt.style.msTouchAction = "none";
this.helt.style.touchAction = "none";
}
public setupVersion() { }
public clickBegin(pos:any)
{
super.clickBegin(pos);
this.offX = this.helt.offsetLeft - this.begX;
this.offY = this.helt.offsetTop - this.begY;
this.beginTime = Util.now();
this.isTap = true;
this.lastX = this.begX;
this.lastY = this.begY;
this.cb("drag", 0, 0, this.begX, this.begY);
}
public onMove(pos:any)
{
this.lastX = pos.pageX;
this.lastY = pos.pageY;
if (this.lockX) this.lastX = this.begX;
if (this.lockY) this.lastY = this.begY;
if (this.moveElt) {
this.helt.style.left = this.offX + this.lastX + "px";
this.helt.style.top = this.offY + this.lastY + "px";
}
var dx = this.lastX - this.begX;
var dy = this.lastY - this.begY;
if (Math.abs(dx) > 10 || Math.abs(dy) > 10) this.isTap = false;
this.cb("move", dx, dy, undefined, undefined)
}
public fireClick(pos:any)
{
if (Util.now() - this.beginTime > 300) this.isTap = false;
this.clear();
this.cb("release", this.lastX - this.begX, this.lastY - this.begY, <any>this.isTap, undefined);
}
public prepareMouseOverlay()
{
if (this.isIeTouch)
this.mouseCaptureOverlay = this.helt;
else
this.mouseCaptureOverlay = document.body;
}
public hideMouseOverlay()
{
}
public handleEvent(e:MouseEvent) {
try {
if (this.skipIt(e)) return;
e.stopPropagation();
e.preventDefault();
this.isIeTouch = (<MSPointerEvent>e).pointerType == 2;
if ((<MSPointerEvent>e).preventMouseEvent) {
(<MSPointerEvent>e).preventMouseEvent();
// TDev.elt("leftPaneContent").style.overflowY = "hidden";
// TDev.elt("leftPaneContent").style.msContentZooming = "hidden";
//TDev.elt("leftPaneContent").style.msTouchAction = "none";
// helt.style.msTouchAction = "none";
}
if ((<MSPointerEvent>e).preventManipulation) {
(<MSPointerEvent>e).preventManipulation();
}
super.handleEvent(e);
} catch (err) {
Util.reportError("dragHandler", err);
}
}
}
} |
import {ABSTRACT, BaseException, CONST} from 'angular2/src/facade/lang';
import {ChangeDetectorRef} from '../change_detector_ref';
/**
* Indicates that the result of a {@link Pipe} transformation has changed even though the reference
* has not changed.
*
* The wrapped value will be unwrapped by change detection, and the unwrapped value will be stored.
*/
export class WrappedValue {
constructor(public wrapped: any) {}
static wrap(value: any): WrappedValue {
var w = _wrappedValues[_wrappedIndex++ % 5];
w.wrapped = value;
return w;
}
}
var _wrappedValues = [
new WrappedValue(null),
new WrappedValue(null),
new WrappedValue(null),
new WrappedValue(null),
new WrappedValue(null)
];
var _wrappedIndex = 0;
/**
* An interface which all pipes must implement.
*
* #Example
*
* ```
* class DoublePipe implements Pipe {
* supports(obj) {
* return true;
* }
*
* onDestroy() {}
*
* transform(value, args = []) {
* return `${value}${value}`;
* }
* }
* ```
*/
export interface Pipe {
/**
* Query if a pipe supports a particular object instance.
*/
supports(obj): boolean;
onDestroy(): void;
transform(value: any, args: List<any>): any;
}
/**
* Provides default implementation of `supports` and `onDestroy` method.
*
* #Example
*
* ```
* class DoublePipe extends BasePipe {
* transform(value) {
* return `${value}${value}`;
* }
* }
* ```
*/
@CONST()
export class BasePipe implements Pipe {
supports(obj: any): boolean { return true; }
onDestroy(): void {}
transform(value: any, args: List<any>): any { return _abstract(); }
}
export interface PipeFactory {
supports(obs): boolean;
create(cdRef: ChangeDetectorRef): Pipe;
}
function _abstract() {
throw new BaseException('This method is abstract');
} |
# <API key>: true
require "cases/helper"
require "models/topic"
require "models/reply"
require "models/post"
require "models/author"
class <API key> < ActiveRecord::TestCase
fixtures :topics, :authors, :author_addresses, :posts
def <API key>
<API key> aware_attributes: true, zone: "Pacific Time (US & Canada)" do
topic = Topic.new(written_on: DateTime.now)
<API key> { topic.to_yaml }
end
end
def test_roundtrip
topic = Topic.first
assert topic
t = YAML.load YAML.dump topic
assert_equal topic, t
end
def <API key>
topic = Topic.new(content: { omg: :lol })
assert_equal({ omg: :lol }, YAML.load(YAML.dump(topic)).content)
end
def <API key>
topic = Topic.first
assert topic
t = Psych.load Psych.dump topic
assert_equal topic, t
end
def <API key>
topic = Topic.new
assert topic
t = Psych.load Psych.dump topic
assert_equal topic.attributes, t.attributes
end
def <API key>
[Topic.all].to_yaml
end
def <API key>
topic = Topic.new(parent_id: "123")
assert_equal "123", topic.<API key>
assert_equal "123", YAML.load(YAML.dump(topic)).<API key>
end
def <API key>
topic = Topic.new(parent_id: "123")
assert_equal 123, topic.parent_id
assert_equal 123, YAML.load(YAML.dump(topic)).parent_id
end
def <API key>
topic = Topic.new
assert topic.new_record?, "Sanity check that new records are new"
assert YAML.load(YAML.dump(topic)).new_record?, "Record should be new after deserialization"
topic.save!
assert_not topic.new_record?, "Saved records are not new"
assert_not YAML.load(YAML.dump(topic)).new_record?, "Saved record should not be new after deserialization"
topic = Topic.select("title").last
assert_not topic.new_record?, "Loaded records without ID are not new"
assert_not YAML.load(YAML.dump(topic)).new_record?, "Record should not be new after deserialization"
end
def <API key>
author = Author.select("authors.*, count(posts.id) as posts_count")
.joins(:posts)
.group("authors.id")
.first
dumped = YAML.load(YAML.dump(author))
assert_equal 5, author.posts_count
assert_equal 5, dumped.posts_count
end
def <API key>
coder = {}
Topic.first.encode_with(coder)
assert coder["<API key>"]
end
def <API key>
topic = YAML.load(yaml_fixture("rails_v2"))
<API key> topic, :new_record?
assert_equal 1, topic.id
assert_equal "The First Topic", topic.title
assert_equal "Have a nice day", topic.content
end
def <API key>
topic = YAML.load(yaml_fixture("rails_v1_mysql"))
<API key> topic, :new_record?
assert_equal 1, topic.id
assert_equal "The First Topic", topic.title
assert_equal "Have a nice day", topic.content
end
def <API key>
topic = assert_deprecated do
YAML.load(yaml_fixture("rails_4_1"))
end
assert_predicate topic, :new_record?
assert_nil topic.id
assert_equal "The First Topic", topic.title
assert_equal({ omg: :lol }, topic.content)
end
def <API key>
topic = assert_deprecated do
YAML.load(yaml_fixture("rails_4_2_0"))
end
<API key> topic, :new_record?
assert_equal 1, topic.id
assert_equal "The First Topic", topic.title
assert_equal("Have a nice day", topic.content)
end
def <API key>
author = Author.first
author.name = "Sean"
dumped = YAML.load(YAML.dump(author))
assert_equal "Sean", dumped.name
assert_equal author.name_was, dumped.name_was
assert_equal author.changes, dumped.changes
end
def <API key>
topic = Topic.first
topic.approved = false
dumped = YAML.load(YAML.dump(topic))
assert_equal false, dumped.approved
end
private
def yaml_fixture(file_name)
path = File.expand_path(
"support/<API key>/#{file_name}.yml",
TEST_ROOT
)
File.read(path)
end
end |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Home - Documentation</title>
<script src="scripts/prettify/prettify.js"></script>
<script src="scripts/prettify/lang-css.js"></script>
<!--[if lt IE 9]>
<script src="//html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]
<link type="text/css" rel="stylesheet" href="https://code.ionicframework.com/ionicons/2.0.1/css/ionicons.min.css">
<link type="text/css" rel="stylesheet" href="styles/prettify.css">
<link type="text/css" rel="stylesheet" href="styles/jsdoc.css">
</head>
<body>
<input type="checkbox" id="nav-trigger" class="nav-trigger" />
<label for="nav-trigger" class="navicon-button x">
<div class="navicon"></div>
</label>
<label for="nav-trigger" class="overlay"></label>
<nav>
<h2><a href="index.html">Home</a></h2><h3>Classes</h3><ul><li><a href="GMaps.html">GMaps</a><ul class='methods'><li data-type='method'><a href="GMaps.html#addControl">addControl</a></li><li data-type='method'><a href="GMaps.html#fitLatLngBounds">fitLatLngBounds</a></li><li data-type='method'><a href="GMaps.html#fitZoom">fitZoom</a></li><li data-type='method'><a href="GMaps.html#getElement">getElement</a></li><li data-type='method'><a href="GMaps.html#hideContextMenu">hideContextMenu</a></li><li data-type='method'><a href="GMaps.html#refresh">refresh</a></li><li data-type='method'><a href="GMaps.html#removeControl">removeControl</a></li><li data-type='method'><a href="GMaps.html#setCenter">setCenter</a></li><li data-type='method'><a href="GMaps.html#setContextMenu">setContextMenu</a></li><li data-type='method'><a href="GMaps.html#zoomIn">zoomIn</a></li><li data-type='method'><a href="GMaps.html#zoomOut">zoomOut</a></li></ul></li></ul>
</nav>
<div id="main">
</div>
<br class="clear">
<footer>
Documentation generated by <a href="https://github.com/jsdoc3/jsdoc">JSDoc 3.4.0</a> on Sun Apr 03 2016 18:36:23 GMT-0400 (EDT) using the Minami theme.
</footer>
<script>prettyPrint();</script>
<script src="scripts/linenumber.js"></script>
</body>
</html> |
// CodeContracts
// File System.ServiceModel.Configuration.<API key>.cs
// Automatically generated contract file.
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Diagnostics.Contracts;
using System;
// Disable the "this variable is not used" warning as every field would imply it.
#pragma warning disable 0414
// Disable the "this variable is never assigned to".
#pragma warning disable 0067
// Disable the "this event is never assigned to".
#pragma warning disable 0649
// Disable the "this variable is never used".
#pragma warning disable 0169
// Disable the "new keyword not required" warning.
#pragma warning disable 0109
// Disable the "extern without DllImport" warning.
#pragma warning disable 0626
// Disable the "could hide other member" warning, can happen on certain properties.
#pragma warning disable 0108
namespace System.ServiceModel.Configuration
{
sealed public partial class <API key> : System.Configuration.<API key>
{
#region Methods and constructors
public void Copy(System.ServiceModel.Configuration.<API key> from)
{
}
public <API key>()
{
}
#endregion
#region Properties and indexers
public string FindValue
{
get
{
return default(string);
}
set
{
}
}
protected override System.Configuration.<API key> Properties
{
get
{
return default(System.Configuration.<API key>);
}
}
public System.Security.Cryptography.X509Certificates.StoreLocation StoreLocation
{
get
{
return default(System.Security.Cryptography.X509Certificates.StoreLocation);
}
set
{
}
}
public System.Security.Cryptography.X509Certificates.StoreName StoreName
{
get
{
return default(System.Security.Cryptography.X509Certificates.StoreName);
}
set
{
}
}
public System.Security.Cryptography.X509Certificates.X509FindType X509FindType
{
get
{
return default(System.Security.Cryptography.X509Certificates.X509FindType);
}
set
{
}
}
#endregion
}
} |
namespace Microsoft.Test.Taupo.OData.WCFService
{
using System;
using System.IO;
<summary>
Class for handling delete requests.
</summary>
public class DeleteHandler : RequestHandler
{
<summary>
Parses the request and removes the specified item from the data store.
</summary>
<returns>An empty stream if successful, otherwise an error.</returns>
public Stream <API key>()
{
try
{
var queryContext = this.<API key>();
var targetEntitySet = queryContext.ResolveEntitySet();
var keyValues = queryContext.ResolveKeyValues();
this.DataContext.DeleteItem(targetEntitySet, keyValues);
return new MemoryStream();
}
catch (Exception error)
{
return this.WriteErrorResponse(400, error);
}
}
}
} |
// CodeContracts
// File System.Configuration.<API key>.cs
// Automatically generated contract file.
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Diagnostics.Contracts;
using System;
// Disable the "this variable is not used" warning as every field would imply it.
#pragma warning disable 0414
// Disable the "this variable is never assigned to".
#pragma warning disable 0067
// Disable the "this event is never assigned to".
#pragma warning disable 0649
// Disable the "this variable is never used".
#pragma warning disable 0169
// Disable the "new keyword not required" warning.
#pragma warning disable 0109
// Disable the "extern without DllImport" warning.
#pragma warning disable 0626
// Disable the "could hide other member" warning, can happen on certain properties.
#pragma warning disable 0108
namespace System.Configuration
{
abstract public partial class <API key> : SettingsBase, System.ComponentModel.<API key>
{
#region Methods and constructors
protected <API key>(string settingsKey)
{
}
protected <API key>(System.ComponentModel.IComponent owner, string settingsKey)
{
}
protected <API key>()
{
}
protected <API key>(System.ComponentModel.IComponent owner)
{
}
public Object GetPreviousVersion(string propertyName)
{
Contract.Requires(this.Properties != null);
return default(Object);
}
protected virtual new void OnPropertyChanged(Object sender, System.ComponentModel.<API key> e)
{
}
protected virtual new void OnSettingChanging(Object sender, <API key> e)
{
}
protected virtual new void OnSettingsLoaded(Object sender, <API key> e)
{
}
protected virtual new void OnSettingsSaving(Object sender, System.ComponentModel.CancelEventArgs e)
{
}
public void Reload()
{
}
public void Reset()
{
}
public override void Save()
{
}
public virtual new void Upgrade()
{
}
#endregion
#region Properties and indexers
public override SettingsContext Context
{
get
{
return default(SettingsContext);
}
}
public override Object this [string propertyName]
{
get
{
return default(Object);
}
set
{
}
}
public override <API key> Properties
{
get
{
return default(<API key>);
}
}
public override <API key> PropertyValues
{
get
{
return default(<API key>);
}
}
public override <API key> Providers
{
get
{
return default(<API key>);
}
}
public string SettingsKey
{
get
{
return default(string);
}
set
{
}
}
#endregion
#region Events
public event System.ComponentModel.<API key> PropertyChanged
{
add
{
}
remove
{
}
}
public event <API key> SettingChanging
{
add
{
}
remove
{
}
}
public event <API key> SettingsLoaded
{
add
{
}
remove
{
}
}
public event <API key> SettingsSaving
{
add
{
}
remove
{
}
}
#endregion
}
} |
// CodeContracts
// File System.CodeDom.CodeTypeParameter.cs
// Automatically generated contract file.
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Diagnostics.Contracts;
using System;
// Disable the "this variable is not used" warning as every field would imply it.
#pragma warning disable 0414
// Disable the "this variable is never assigned to".
#pragma warning disable 0067
// Disable the "this event is never assigned to".
#pragma warning disable 0649
// Disable the "this variable is never used".
#pragma warning disable 0169
// Disable the "new keyword not required" warning.
#pragma warning disable 0109
// Disable the "extern without DllImport" warning.
#pragma warning disable 0626
// Disable the "could hide other member" warning, can happen on certain properties.
#pragma warning disable 0108
namespace System.CodeDom
{
public partial class CodeTypeParameter : CodeObject
{
#region Methods and constructors
public CodeTypeParameter(string name)
{
}
public CodeTypeParameter()
{
}
#endregion
#region Properties and indexers
public <API key> Constraints
{
get
{
Contract.Ensures(Contract.Result<System.CodeDom.<API key>>() != null);
return default(<API key>);
}
}
public <API key> CustomAttributes
{
get
{
Contract.Ensures(Contract.Result<System.CodeDom.<API key>>() != null);
return default(<API key>);
}
}
public bool <API key>
{
get
{
return default(bool);
}
set
{
}
}
public string Name
{
get
{
Contract.Ensures(Contract.Result<string>() != null);
return default(string);
}
set
{
}
}
#endregion
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.