code
stringlengths 3
1.01M
| repo_name
stringlengths 5
116
| path
stringlengths 3
311
| language
stringclasses 30
values | license
stringclasses 15
values | size
int64 3
1.01M
|
|---|---|---|---|---|---|
<?php
declare(strict_types=1);
namespace Edde\Common\Protocol\Request;
use Edde\Common\Protocol\Element;
class Response extends Element {
public function __construct(string $id = null) {
parent::__construct('response', $id);
}
}
|
edde-framework/edde-framework
|
src/Edde/Common/Protocol/Request/Response.php
|
PHP
|
apache-2.0
| 244
|
#!/usr/bin/python
# Copyright 2015 Comcast Cable Communications Management, LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# End Copyright
# Little external FS (fact service) example
# Wrap Yahoo stock quotes as an FS.
# Pattern must specify a single ticker symbol "symbol".
# Pattern must specify at least one additional property from the set
legalProperties = {"bid", "ask", "change", "percentChange", "lastTradeSize"}
# curl 'http://download.finance.yahoo.com/d/quotes.csv?s=CMCSA&f=abc1p2k3&e=.csv'
# http://www.canbike.ca/information-technology/yahoo-finance-url-download-to-a-csv-file.html
# A more principled approach would allow the pattern to specify only a
# single additional property, but that decision is a separate
# discussion.
# Usage:
#
# curl -d '{"symbol":"CMCSA","bid":"?bid","ask":"?ask"}' 'http://localhost:6666/facts/search'
#
from BaseHTTPServer import BaseHTTPRequestHandler,HTTPServer
import cgi # Better way now?
import json
import urllib2
import urllib
import re
PORT = 6666
def protest (response, message):
response.send_response(200)
response.send_header('Content-type','text/plain')
response.end_headers()
response.wfile.write(message) # Should probably be JSON
def getQuote (symbol):
uri = "http://download.finance.yahoo.com/d/quotes.csv?s=" + symbol + "&f=abc1p2k3&e=.csv"
print "uri ", uri
line = urllib2.urlopen(uri).read().strip()
print "got ", line, "\n"
line = re.sub(r'[%"\n]+', "", line)
print "clean ", line, "\n"
data = line.split(",")
ns = map(float, data)
q = {}
q["bid"] = ns[0]
q["ask"] = ns[1]
q["change"] = ns[2]
q["percentChange"] = ns[3]
q["lastTradeSize"] = ns[4]
return q
class handler(BaseHTTPRequestHandler):
def do_GET(self):
protest(self, "You should POST with json.\n")
return
def do_POST(self):
if not self.path == '/facts/search':
protest(self, "Only can do /facts/search.\n")
return
try:
content_length = int(self.headers['Content-Length'])
js = self.rfile.read(content_length)
m = json.loads(js)
if 'symbol' not in m:
protest(self, "Need symbol.\n")
return
symbol = m["symbol"]
del m["symbol"]
for p in m:
if p not in legalProperties:
protest(self, "Illegal property " + p + ".\n")
return
v = m[p]
if not v.startswith("?"):
protest(self, "Value " + v + " must be a variable.\n")
return
if len(v) < 2:
protest(self, "Need an named variable for " + v + ".\n")
return
q = getQuote(symbol)
print q, "\n"
bindings = {}
satisfied = True
for p in m:
print p, ": ", q[p], "\n"
if p in q:
bindings[m[p]] = q[p]
else:
satisfied = False
break
if satisfied:
js = json.dumps(bindings)
response = '{"Found":[{"Bindingss":[%s]}]}' % (js)
else:
response = '{"Found":[{"Bindingss":[]}]}'
self.send_response(200)
self.send_header('Content-type','application/json')
self.end_headers()
print 'response ', response
self.wfile.write(response)
except Exception as broke:
print broke, "\n"
protest(self, str(broke))
try:
server = HTTPServer(('', PORT), handler)
print 'Started weather FS on port ' , PORT
server.serve_forever()
except KeyboardInterrupt:
print '^C received, shutting down the weather FS on ', PORT
server.socket.close()
|
Comcast/rulio
|
examples/stockfs.py
|
Python
|
apache-2.0
| 4,418
|
import os
from torch.utils.ffi import create_extension
sources = ["src/lib_cffi.cpp"]
headers = ["src/lib_cffi.h"]
extra_objects = ["src/bn.o"]
with_cuda = True
this_file = os.path.dirname(os.path.realpath(__file__))
extra_objects = [os.path.join(this_file, fname) for fname in extra_objects]
ffi = create_extension(
"_ext",
headers=headers,
sources=sources,
relative_to=__file__,
with_cuda=with_cuda,
extra_objects=extra_objects,
extra_compile_args=["-std=c++11"],
)
if __name__ == "__main__":
ffi.build()
|
Diyago/Machine-Learning-scripts
|
DEEP LEARNING/segmentation/Kaggle TGS Salt Identification Challenge/v2/modules/build.py
|
Python
|
apache-2.0
| 544
|
<?php
/*
* $Id: OCI8ResultSet.php,v 1.1 2007/01/03 20:10:14 rpm Exp $
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* This software consists of voluntary contributions made by many individuals
* and is licensed under the LGPL. For more information please see
* <http://creole.phpdb.org>.
*/
require_once 'creole/ResultSet.php';
require_once 'creole/common/ResultSetCommon.php';
/**
* Oracle (OCI8) implementation of ResultSet class.
*
* @author David Giffin <david@giffin.org>
* @author Hans Lellelid <hans@xmpl.org>
* @version $Revision: 1.1 $
* @package creole.drivers.oracle
*/
class OCI8ResultSet extends ResultSetCommon implements ResultSet
{
/**
* @see ResultSet::seek()
*/
function seek($rownum)
{
if ( $rownum < $this->cursorPos )
{
// this will effectively disable previous(), first() and some calls to relative() or absolute()
throw new SQLException( 'Oracle ResultSet is FORWARD-ONLY' );
}
// Oracle has no seek function imulate it here
while ( $this->cursorPos < $rownum )
{
$this->next();
}
$this->cursorPos = $rownum;
return true;
}
/**
* @see ResultSet::next()
*/
function next()
{
// no specific result position available
// Returns an array, which corresponds to the next result row or FALSE
// in case of error or there is no more rows in the result.
$this->fields = oci_fetch_array( $this->result
, $this->fetchmode
+ OCI_RETURN_NULLS
+ OCI_RETURN_LOBS
);
if ( ! $this->fields )
{
// grab error via array
$error = oci_error( $this->result );
if ( ! $error )
{
// end of recordset
$this->afterLast();
return false;
}
else
{
throw new SQLException( 'Error fetching result'
, $error[ 'code' ] . ': ' . $error[ 'message' ]
);
}
}
// Oracle returns all field names in uppercase and associative indices
// in the result array will be uppercased too.
if ($this->fetchmode === ResultSet::FETCHMODE_ASSOC && $this->lowerAssocCase)
{
$this->fields = array_change_key_case($this->fields, CASE_LOWER);
}
// Advance cursor position
$this->cursorPos++;
return true;
}
/**
* @see ResultSet::getRecordCount()
*/
function getRecordCount()
{
$rows = oci_num_rows( $this->result );
if ( $rows === false )
{
throw new SQLException( 'Error fetching num rows'
, $this->conn->nativeError( $this->result )
);
}
return ( int ) $rows;
}
/**
* @see ResultSet::close()
*/
function close()
{
$this->fields = array();
@oci_free_statement( $this->result );
}
}
|
rodrigoprestesmachado/whiteboard
|
creole/drivers/oracle/OCI8ResultSet.php
|
PHP
|
apache-2.0
| 3,726
|
/**
* WTCoB WTCoB License
* This source code and all modifications done by WTCoB
* are licensed under the Apache Public License (version 2) and
* are Copyright (c) 2009-2014 by WTCoB, Inc.
*/
/*
* Copyright (C) 2006 Apple Computer, Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. 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 TiValueRef_h
#define TiValueRef_h
#include <JavaScriptCore/TiBase.h>
#include <JavaScriptCore/WebKitAvailability.h>
#ifndef __cplusplus
#include <stdbool.h>
#endif
/*!
@enum JSType
@abstract A constant identifying the type of a TiValue.
@constant kTITypeUndefined The unique undefined value.
@constant kTITypeNull The unique null value.
@constant kTITypeBoolean A primitive boolean value, one of true or false.
@constant kTITypeNumber A primitive number value.
@constant kTITypeString A primitive string value.
@constant kTITypeObject An object value (meaning that this TiValueRef is a TiObjectRef).
*/
typedef enum {
kTITypeUndefined,
kTITypeNull,
kTITypeBoolean,
kTITypeNumber,
kTITypeString,
kTITypeObject
} TiType;
#ifdef __cplusplus
extern "C" {
#endif
/*!
@function
@abstract Returns a JavaScript value's type.
@param ctx The execution context to use.
@param value The TiValue whose type you want to obtain.
@result A value of type JSType that identifies value's type.
*/
JS_EXPORT TiType TiValueGetType(TiContextRef ctx, TiValueRef);
/*!
@function
@abstract Tests whether a JavaScript value's type is the undefined type.
@param ctx The execution context to use.
@param value The TiValue to test.
@result true if value's type is the undefined type, otherwise false.
*/
JS_EXPORT bool TiValueIsUndefined(TiContextRef ctx, TiValueRef value);
/*!
@function
@abstract Tests whether a JavaScript value's type is the null type.
@param ctx The execution context to use.
@param value The TiValue to test.
@result true if value's type is the null type, otherwise false.
*/
JS_EXPORT bool TiValueIsNull(TiContextRef ctx, TiValueRef value);
/*!
@function
@abstract Tests whether a JavaScript value's type is the boolean type.
@param ctx The execution context to use.
@param value The TiValue to test.
@result true if value's type is the boolean type, otherwise false.
*/
JS_EXPORT bool TiValueIsBoolean(TiContextRef ctx, TiValueRef value);
/*!
@function
@abstract Tests whether a JavaScript value's type is the number type.
@param ctx The execution context to use.
@param value The TiValue to test.
@result true if value's type is the number type, otherwise false.
*/
JS_EXPORT bool TiValueIsNumber(TiContextRef ctx, TiValueRef value);
/*!
@function
@abstract Tests whether a JavaScript value's type is the string type.
@param ctx The execution context to use.
@param value The TiValue to test.
@result true if value's type is the string type, otherwise false.
*/
JS_EXPORT bool TiValueIsString(TiContextRef ctx, TiValueRef value);
/*!
@function
@abstract Tests whether a JavaScript value's type is the array type.
@param ctx The execution context to use.
@param value The TiValue to test.
@result true if value's type is the string type, otherwise false.
*/
JS_EXPORT bool TiValueIsArray(TiContextRef ctx, TiValueRef value);
/*!
@function
@abstract Tests whether a JavaScript value's type is the date type.
@param ctx The execution context to use.
@param value The TiValue to test.
@result true if value's type is the string type, otherwise false.
*/
JS_EXPORT bool TiValueIsDate(TiContextRef ctx, TiValueRef value);
/*!
@function
@abstract Tests whether a JavaScript value's type is the object type.
@param ctx The execution context to use.
@param value The TiValue to test.
@result true if value's type is the object type, otherwise false.
*/
JS_EXPORT bool TiValueIsObject(TiContextRef ctx, TiValueRef value);
/*!
@function
@abstract Tests whether a JavaScript value is an object with a given class in its class chain.
@param ctx The execution context to use.
@param value The TiValue to test.
@param jsClass The TiClass to test against.
@result true if value is an object and has jsClass in its class chain, otherwise false.
*/
JS_EXPORT bool TiValueIsObjectOfClass(TiContextRef ctx, TiValueRef value, TiClassRef jsClass);
/* Comparing values */
/*!
@function
@abstract Tests whether two JavaScript values are equal, as compared by the JS == operator.
@param ctx The execution context to use.
@param a The first value to test.
@param b The second value to test.
@param exception A pointer to a TiValueRef in which to store an exception, if any. Pass NULL if you do not care to store an exception.
@result true if the two values are equal, false if they are not equal or an exception is thrown.
*/
JS_EXPORT bool TiValueIsEqual(TiContextRef ctx, TiValueRef a, TiValueRef b, TiValueRef* exception);
/*!
@function
@abstract Tests whether two JavaScript values are strict equal, as compared by the JS === operator.
@param ctx The execution context to use.
@param a The first value to test.
@param b The second value to test.
@result true if the two values are strict equal, otherwise false.
*/
JS_EXPORT bool TiValueIsStrictEqual(TiContextRef ctx, TiValueRef a, TiValueRef b);
/*!
@function
@abstract Tests whether a JavaScript value is an object constructed by a given constructor, as compared by the JS instanceof operator.
@param ctx The execution context to use.
@param value The TiValue to test.
@param constructor The constructor to test against.
@param exception A pointer to a TiValueRef in which to store an exception, if any. Pass NULL if you do not care to store an exception.
@result true if value is an object constructed by constructor, as compared by the JS instanceof operator, otherwise false.
*/
JS_EXPORT bool TiValueIsInstanceOfConstructor(TiContextRef ctx, TiValueRef value, TiObjectRef constructor, TiValueRef* exception);
/* Creating values */
/*!
@function
@abstract Creates a JavaScript value of the undefined type.
@param ctx The execution context to use.
@result The unique undefined value.
*/
JS_EXPORT TiValueRef TiValueMakeUndefined(TiContextRef ctx);
/*!
@function
@abstract Creates a JavaScript value of the null type.
@param ctx The execution context to use.
@result The unique null value.
*/
JS_EXPORT TiValueRef TiValueMakeNull(TiContextRef ctx);
/*!
@function
@abstract Creates a JavaScript value of the boolean type.
@param ctx The execution context to use.
@param boolean The bool to assign to the newly created TiValue.
@result A TiValue of the boolean type, representing the value of boolean.
*/
JS_EXPORT TiValueRef TiValueMakeBoolean(TiContextRef ctx, bool boolean);
/*!
@function
@abstract Creates a JavaScript value of the number type.
@param ctx The execution context to use.
@param number The double to assign to the newly created TiValue.
@result A TiValue of the number type, representing the value of number.
*/
JS_EXPORT TiValueRef TiValueMakeNumber(TiContextRef ctx, double number);
/*!
@function
@abstract Creates a JavaScript value of the string type.
@param ctx The execution context to use.
@param string The JSString to assign to the newly created TiValue. The
newly created TiValue retains string, and releases it upon garbage collection.
@result A TiValue of the string type, representing the value of string.
*/
JS_EXPORT TiValueRef TiValueMakeString(TiContextRef ctx, TiStringRef string);
/* Converting to and from JSON formatted strings */
/*!
@function
@abstract Creates a JavaScript value from a JSON formatted string.
@param ctx The execution context to use.
@param string The JSString containing the JSON string to be parsed.
@result A TiValue containing the parsed value, or NULL if the input is invalid.
*/
JS_EXPORT TiValueRef TiValueMakeFromJSONString(TiContextRef ctx, TiStringRef string) CF_AVAILABLE(10_7, 7_0);
/*!
@function
@abstract Creates a JavaScript string containing the JSON serialized representation of a JS value.
@param ctx The execution context to use.
@param value The value to serialize.
@param indent The number of spaces to indent when nesting. If 0, the resulting JSON will not contains newlines. The size of the indent is clamped to 10 spaces.
@param exception A pointer to a TiValueRef in which to store an exception, if any. Pass NULL if you do not care to store an exception.
@result A JSString with the result of serialization, or NULL if an exception is thrown.
*/
JS_EXPORT TiStringRef TiValueCreateJSONString(TiContextRef ctx, TiValueRef value, unsigned indent, TiValueRef* exception) CF_AVAILABLE(10_7, 7_0);
/* Converting to primitive values */
/*!
@function
@abstract Converts a JavaScript value to boolean and returns the resulting boolean.
@param ctx The execution context to use.
@param value The TiValue to convert.
@result The boolean result of conversion.
*/
JS_EXPORT bool TiValueToBoolean(TiContextRef ctx, TiValueRef value);
/*!
@function
@abstract Converts a JavaScript value to number and returns the resulting number.
@param ctx The execution context to use.
@param value The TiValue to convert.
@param exception A pointer to a TiValueRef in which to store an exception, if any. Pass NULL if you do not care to store an exception.
@result The numeric result of conversion, or NaN if an exception is thrown.
*/
JS_EXPORT double TiValueToNumber(TiContextRef ctx, TiValueRef value, TiValueRef* exception);
/*!
@function
@abstract Converts a JavaScript value to string and copies the result into a JavaScript string.
@param ctx The execution context to use.
@param value The TiValue to convert.
@param exception A pointer to a TiValueRef in which to store an exception, if any. Pass NULL if you do not care to store an exception.
@result A JSString with the result of conversion, or NULL if an exception is thrown. Ownership follows the Create Rule.
*/
JS_EXPORT TiStringRef TiValueToStringCopy(TiContextRef ctx, TiValueRef value, TiValueRef* exception);
/*!
@function
@abstract Converts a JavaScript value to object and returns the resulting object.
@param ctx The execution context to use.
@param value The TiValue to convert.
@param exception A pointer to a TiValueRef in which to store an exception, if any. Pass NULL if you do not care to store an exception.
@result The JSObject result of conversion, or NULL if an exception is thrown.
*/
JS_EXPORT TiObjectRef TiValueToObject(TiContextRef ctx, TiValueRef value, TiValueRef* exception);
/* Garbage collection */
/*!
@function
@abstract Protects a JavaScript value from garbage collection.
@param ctx The execution context to use.
@param value The TiValue to protect.
@discussion Use this method when you want to store a TiValue in a global or on the heap, where the garbage collector will not be able to discover your reference to it.
A value may be protected multiple times and must be unprotected an equal number of times before becoming eligible for garbage collection.
*/
JS_EXPORT void TiValueProtect(TiContextRef ctx, TiValueRef value);
/*!
@function
@abstract Unprotects a JavaScript value from garbage collection.
@param ctx The execution context to use.
@param value The TiValue to unprotect.
@discussion A value may be protected multiple times and must be unprotected an
equal number of times before becoming eligible for garbage collection.
*/
JS_EXPORT void TiValueUnprotect(TiContextRef ctx, TiValueRef value);
#ifdef __cplusplus
}
#endif
#endif /* TiValueRef_h */
|
TeamAir4385/Production
|
build/iphone/headers/JavaScriptCore/TiValueRef.h
|
C
|
apache-2.0
| 13,039
|
---
title: All Ledgers
clientData:
laboratoryUrl: https://www.stellar.org/laboratory/#explorer?resource=ledgers&endpoint=all
---
This endpoint represents all [ledgers](./resources/ledger.md).
This endpoint can also be used in [streaming](../learn/responses.md#streaming) mode so it is possible to use it to get notifications as ledgers are closed by the Stellar network.
If called in streaming mode Horizon will start at the earliest known ledger unless a `cursor` is set. In that case it will start from the `cursor`. You can also set `cursor` value to `now` to only stream ledgers created since your request time.
## Request
```
GET /ledgers{?cursor,limit,order}
```
### Arguments
| name | notes | description | example |
| ---- | ----- | ----------- | ------- |
| `?cursor` | optional, any, default _null_ | A paging token, specifying where to start returning records from. When streaming this can be set to `now` to stream object created since your request time. | `12884905984` |
| `?order` | optional, string, default `asc` | The order in which to return rows, "asc" or "desc". | `asc` |
| `?limit` | optional, number, default: `10` | Maximum number of records to return. | `200` |
### curl Example Request
```sh
# Retrieve the 200 latest ledgers, ordered chronologically
curl "https://horizon-testnet.stellar.org/ledgers?limit=200&order=desc"
```
### JavaScript Example Request
```js
server.ledgers()
.call()
.then(function (ledgerResult) {
// page 1
console.log(ledgerResult.records)
return ledgerResult.next()
})
.then(function (ledgerResult) {
// page 2
console.log(ledgerResult.records)
})
.catch(function(err) {
console.log(err)
})
```
## Response
This endpoint responds with a list of ledgers. See [ledger resource](./resources/ledger.md) for reference.
### Example Response
```json
{
"_embedded": {
"records": [
{
"_links": {
"effects": {
"href": "/ledgers/1/effects/{?cursor,limit,order}",
"templated": true
},
"operations": {
"href": "/ledgers/1/operations/{?cursor,limit,order}",
"templated": true
},
"self": {
"href": "/ledgers/1"
},
"transactions": {
"href": "/ledgers/1/transactions/{?cursor,limit,order}",
"templated": true
}
},
"id": "e8e10918f9c000c73119abe54cf089f59f9015cc93c49ccf00b5e8b9afb6e6b1",
"paging_token": "4294967296",
"hash": "e8e10918f9c000c73119abe54cf089f59f9015cc93c49ccf00b5e8b9afb6e6b1",
"sequence": 1,
"transaction_count": 0,
"operation_count": 0,
"closed_at": "1970-01-01T00:00:00Z"
},
{
"_links": {
"effects": {
"href": "/ledgers/2/effects/{?cursor,limit,order}",
"templated": true
},
"operations": {
"href": "/ledgers/2/operations/{?cursor,limit,order}",
"templated": true
},
"self": {
"href": "/ledgers/2"
},
"transactions": {
"href": "/ledgers/2/transactions/{?cursor,limit,order}",
"templated": true
}
},
"id": "e12e5809ab8c59d8256e691cb48a024dd43960bc15902d9661cd627962b2bc71",
"paging_token": "8589934592",
"hash": "e12e5809ab8c59d8256e691cb48a024dd43960bc15902d9661cd627962b2bc71",
"prev_hash": "e8e10918f9c000c73119abe54cf089f59f9015cc93c49ccf00b5e8b9afb6e6b1",
"sequence": 2,
"transaction_count": 0,
"operation_count": 0,
"closed_at": "2015-07-16T23:49:00Z"
}
]
},
"_links": {
"next": {
"href": "/ledgers?order=asc&limit=2&cursor=8589934592"
},
"prev": {
"href": "/ledgers?order=desc&limit=2&cursor=4294967296"
},
"self": {
"href": "/ledgers?order=asc&limit=2&cursor="
}
}
}
```
### Example Streaming Event
```json
{
"_links": {
"effects": {
"href": "/ledgers/69859/effects/{?cursor,limit,order}",
"templated": true
},
"operations": {
"href": "/ledgers/69859/operations/{?cursor,limit,order}",
"templated": true
},
"self": {
"href": "/ledgers/69859"
},
"transactions": {
"href": "/ledgers/69859/transactions/{?cursor,limit,order}",
"templated": true
}
},
"id": "4db1e4f145e9ee75162040d26284795e0697e2e84084624e7c6c723ebbf80118",
"paging_token": "300042120331264",
"hash": "4db1e4f145e9ee75162040d26284795e0697e2e84084624e7c6c723ebbf80118",
"prev_hash": "4b0b8bace3b2438b2404776ce57643966855487ba6384724a3c664c7aa4cd9e4",
"sequence": 69859,
"transaction_count": 0,
"operation_count": 0,
"closed_at": "2015-07-20T15:51:52Z"
}
```
## Errors
- The [standard errors](../learn/errors.md#Standard_Errors).
|
irisli/horizon
|
docs/reference/ledgers-all.md
|
Markdown
|
apache-2.0
| 4,868
|
package com.sfl.pms.services.order.exception;
import com.sfl.pms.services.common.exception.EntityNotFoundForUuIdException;
import com.sfl.pms.services.order.model.Order;
/**
* User: Mher Sargsyan
* Company: SFL LLC
* Date: 1/29/15
* Time: 3:54 PM
*/
public class OrderNotFoundForUuIdException extends EntityNotFoundForUuIdException {
private static final long serialVersionUID = -1505298075428816221L;
public OrderNotFoundForUuIdException(final String uuId) {
super(uuId, Order.class);
}
}
|
sflpro/ms_payment
|
services/services_core/src/main/java/com/sfl/pms/services/order/exception/OrderNotFoundForUuIdException.java
|
Java
|
apache-2.0
| 519
|
<?php
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: google/ads/googleads/v10/enums/conversion_tracking_status_enum.proto
namespace Google\Ads\GoogleAds\V10\Enums;
if (false) {
/**
* This class is deprecated. Use Google\Ads\GoogleAds\V10\Enums\ConversionTrackingStatusEnum\ConversionTrackingStatus instead.
* @deprecated
*/
class ConversionTrackingStatusEnum_ConversionTrackingStatus {}
}
class_exists(ConversionTrackingStatusEnum\ConversionTrackingStatus::class);
@trigger_error('Google\Ads\GoogleAds\V10\Enums\ConversionTrackingStatusEnum_ConversionTrackingStatus is deprecated and will be removed in the next major release. Use Google\Ads\GoogleAds\V10\Enums\ConversionTrackingStatusEnum\ConversionTrackingStatus instead', E_USER_DEPRECATED);
|
googleads/google-ads-php
|
src/Google/Ads/GoogleAds/V10/Enums/ConversionTrackingStatusEnum_ConversionTrackingStatus.php
|
PHP
|
apache-2.0
| 794
|
/* Copyright 2018 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
=======================================================================*/
// This class has been generated, DO NOT EDIT!
package org.tensorflow.op.math;
import java.util.Arrays;
import org.tensorflow.GraphOperation;
import org.tensorflow.Operand;
import org.tensorflow.Operation;
import org.tensorflow.OperationBuilder;
import org.tensorflow.Output;
import org.tensorflow.op.RawOp;
import org.tensorflow.op.RawOpInputs;
import org.tensorflow.op.Scope;
import org.tensorflow.op.annotation.Endpoint;
import org.tensorflow.op.annotation.OpInputsMetadata;
import org.tensorflow.op.annotation.OpMetadata;
import org.tensorflow.op.annotation.Operator;
import org.tensorflow.proto.framework.DataType;
import org.tensorflow.types.family.TType;
/**
* Returns conj(x - y)(x - y) element-wise.
* <em>NOTE</em>: {@code math.SquaredDifference} supports broadcasting. More about broadcasting
* <a href="http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html">here</a>
*
* @param <T> data type for {@code z} output
*/
@OpMetadata(
opType = SquaredDifference.OP_NAME,
inputsClass = SquaredDifference.Inputs.class
)
@Operator(
group = "math"
)
public final class SquaredDifference<T extends TType> extends RawOp implements Operand<T> {
/**
* The name of this op, as known by TensorFlow core engine
*/
public static final String OP_NAME = "SquaredDifference";
private Output<T> z;
public SquaredDifference(Operation operation) {
super(operation, OP_NAME);
int outputIdx = 0;
z = operation.output(outputIdx++);
}
/**
* Factory method to create a class wrapping a new SquaredDifference operation.
*
* @param scope current scope
* @param x The x value
* @param y The y value
* @param <T> data type for {@code SquaredDifference} output and operands
* @return a new instance of SquaredDifference
*/
@Endpoint(
describeByClass = true
)
public static <T extends TType> SquaredDifference<T> create(Scope scope, Operand<T> x,
Operand<T> y) {
OperationBuilder opBuilder = scope.opBuilder(OP_NAME, "SquaredDifference");
opBuilder.addInput(x.asOutput());
opBuilder.addInput(y.asOutput());
return new SquaredDifference<>(opBuilder.build());
}
/**
* Gets z.
*
* @return z.
*/
public Output<T> z() {
return z;
}
@Override
public Output<T> asOutput() {
return z;
}
@OpInputsMetadata(
outputsClass = SquaredDifference.class
)
public static class Inputs<T extends TType> extends RawOpInputs<SquaredDifference<T>> {
/**
* The x input
*/
public final Operand<T> x;
/**
* The y input
*/
public final Operand<T> y;
/**
* The T attribute
*/
public final DataType T;
public Inputs(GraphOperation op) {
super(new SquaredDifference<>(op), op, Arrays.asList("T"));
int inputIndex = 0;
x = (Operand<T>) op.input(inputIndex++);
y = (Operand<T>) op.input(inputIndex++);
T = op.attributes().getAttrType("T");
}
}
}
|
tensorflow/java
|
tensorflow-core/tensorflow-core-api/src/gen/java/org/tensorflow/op/math/SquaredDifference.java
|
Java
|
apache-2.0
| 3,621
|
/*
* Licensed to ElasticSearch and Shay Banon under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. ElasticSearch licenses this
* file to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.action.admin.indices.stats;
import org.elasticsearch.action.support.broadcast.BroadcastOperationRequest;
import org.elasticsearch.common.io.stream.StreamInput;
import org.elasticsearch.common.io.stream.StreamOutput;
import java.io.IOException;
/**
* A request to get indices level stats. Allow to enable different stats to be returned.
* <p/>
* <p>By default, the {@link #docs(boolean)}, {@link #store(boolean)}, {@link #indexing(boolean)}
* are enabled. Other stats can be enabled as well.
* <p/>
* <p>All the stats to be returned can be cleared using {@link #clear()}, at which point, specific
* stats can be enabled.
*/
public class IndicesStatsRequest extends BroadcastOperationRequest {
private boolean docs = true;
private boolean store = true;
private boolean indexing = true;
private boolean get = true;
private boolean search = true;
private boolean merge = false;
private boolean refresh = false;
private boolean flush = false;
private boolean warmer = false;
private String[] types = null;
private String[] groups = null;
public IndicesStatsRequest indices(String... indices) {
this.indices = indices;
return this;
}
/**
* Sets all flags to return all stats.
*/
public IndicesStatsRequest all() {
docs = true;
store = true;
get = true;
indexing = true;
search = true;
merge = true;
refresh = true;
flush = true;
warmer = true;
types = null;
groups = null;
return this;
}
/**
* Clears all stats.
*/
public IndicesStatsRequest clear() {
docs = false;
store = false;
get = false;
indexing = false;
search = false;
merge = false;
refresh = false;
flush = false;
warmer = false;
types = null;
groups = null;
return this;
}
/**
* Document types to return stats for. Mainly affects {@link #indexing(boolean)} when
* enabled, returning specific indexing stats for those types.
*/
public IndicesStatsRequest types(String... types) {
this.types = types;
return this;
}
/**
* Document types to return stats for. Mainly affects {@link #indexing(boolean)} when
* enabled, returning specific indexing stats for those types.
*/
public String[] types() {
return this.types;
}
/**
* Sets specific search group stats to retrieve the stats for. Mainly affects search
* when enabled.
*/
public IndicesStatsRequest groups(String... groups) {
this.groups = groups;
return this;
}
public String[] groups() {
return this.groups;
}
public IndicesStatsRequest docs(boolean docs) {
this.docs = docs;
return this;
}
public boolean docs() {
return this.docs;
}
public IndicesStatsRequest store(boolean store) {
this.store = store;
return this;
}
public boolean store() {
return this.store;
}
public IndicesStatsRequest indexing(boolean indexing) {
this.indexing = indexing;
return this;
}
public boolean indexing() {
return this.indexing;
}
public IndicesStatsRequest get(boolean get) {
this.get = get;
return this;
}
public boolean get() {
return this.get;
}
public IndicesStatsRequest search(boolean search) {
this.search = search;
return this;
}
public boolean search() {
return this.search;
}
public IndicesStatsRequest merge(boolean merge) {
this.merge = merge;
return this;
}
public boolean merge() {
return this.merge;
}
public IndicesStatsRequest refresh(boolean refresh) {
this.refresh = refresh;
return this;
}
public boolean refresh() {
return this.refresh;
}
public IndicesStatsRequest flush(boolean flush) {
this.flush = flush;
return this;
}
public boolean flush() {
return this.flush;
}
public IndicesStatsRequest warmer(boolean warmer) {
this.warmer = warmer;
return this;
}
public boolean warmer() {
return this.warmer;
}
@Override
public void writeTo(StreamOutput out) throws IOException {
super.writeTo(out);
out.writeBoolean(docs);
out.writeBoolean(store);
out.writeBoolean(indexing);
out.writeBoolean(get);
out.writeBoolean(search);
out.writeBoolean(merge);
out.writeBoolean(flush);
out.writeBoolean(refresh);
out.writeBoolean(warmer);
if (types == null) {
out.writeVInt(0);
} else {
out.writeVInt(types.length);
for (String type : types) {
out.writeUTF(type);
}
}
if (groups == null) {
out.writeVInt(0);
} else {
out.writeVInt(groups.length);
for (String group : groups) {
out.writeUTF(group);
}
}
}
@Override
public void readFrom(StreamInput in) throws IOException {
super.readFrom(in);
docs = in.readBoolean();
store = in.readBoolean();
indexing = in.readBoolean();
get = in.readBoolean();
search = in.readBoolean();
merge = in.readBoolean();
flush = in.readBoolean();
refresh = in.readBoolean();
warmer = in.readBoolean();
int size = in.readVInt();
if (size > 0) {
types = new String[size];
for (int i = 0; i < size; i++) {
types[i] = in.readUTF();
}
}
size = in.readVInt();
if (size > 0) {
groups = new String[size];
for (int i = 0; i < size; i++) {
groups[i] = in.readUTF();
}
}
}
}
|
chanil1218/elasticsearch
|
src/main/java/org/elasticsearch/action/admin/indices/stats/IndicesStatsRequest.java
|
Java
|
apache-2.0
| 6,877
|
package o;
import java.util.HashSet;
public final class ч$if
{
public String ˊ;
public String ˋ;
public boolean ˎ;
public ч$if(String paramString1, String paramString2)
{
this.ˊ = paramString1;
this.ˋ = paramString2;
this.ˎ = ﺩ.ˋ(paramString1);
ч.ˋ().add(paramString1);
}
}
/* Location: /Users/vikas/Documents/Mhacks_Real_app/classes-dex2jar.jar
* Qualified Name: o.—á.if
* JD-Core Version: 0.6.2
*/
|
mmmsplay10/QuizUpWinner
|
quizup/o/—á$if.java
|
Java
|
apache-2.0
| 467
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
namespace PromosiMVC.Helpers
{
public static class TestHelpers
{
private static Random rnd = new Random();
public static string GenerateCode(int size)
{
// Random rnd = new Random();
string input = "abcdefghijklmnopqrstuvwxyz0123456789";
StringBuilder builder = new StringBuilder();
char ch;
for (int i = 0; i < size; i++)
{
ch = input[rnd.Next(0, input.Length)];
if (rnd.Next(0, 1) == 0)
Char.ToUpper(ch);
else
char.ToLower(ch);
builder.Append(ch);
}
return builder.ToString();
}
public static string GenerateText(int size)
{
//Random rnd = new Random();
string input = "abcdefghijklmnopqrstuvwxyz ";
StringBuilder builder = new StringBuilder();
char ch;
for (int i = 0; i < size; i++)
{
ch = input[rnd.Next(0, input.Length)];
if (i == 0)
Char.ToUpper(ch);
builder.Append(ch);
}
return builder.ToString();
}
}
}
|
RandomLyrics/aaabbbcdefgh
|
PromosiMVC/Helpers/TestHelpers.cs
|
C#
|
apache-2.0
| 1,405
|
package org.cucina.engine.client.service;
import org.cucina.conversation.EventHandler;
import org.cucina.conversation.events.CallbackEvent;
import org.cucina.conversation.events.ConversationEvent;
import org.cucina.engine.client.Check;
import org.cucina.engine.client.Operation;
import org.cucina.engine.server.definition.CheckDescriptorDto;
import org.cucina.engine.server.definition.OperationDescriptorDto;
import org.cucina.engine.server.definition.ProcessElementDto;
import org.cucina.engine.server.event.ActionResultEvent;
import org.cucina.engine.server.event.BooleanEvent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.convert.ConversionService;
import org.springframework.util.Assert;
import java.util.Map;
/**
* JAVADOC for Class Level
*
* @author $Author: $
* @version $Revision: $
*/
public class ProcessEventHandler implements EventHandler<ConversationEvent> {
private static final Logger LOG = LoggerFactory.getLogger(ProcessEventHandler.class);
private ConversionService conversionService;
private DomainFindingService domainFindingService;
/**
* Creates a new WorkflowEventHandler object.
*/
public ProcessEventHandler(DomainFindingService domainFindingService,
ConversionService conversionService) {
Assert.notNull(domainFindingService, "domainFindingService is null");
this.domainFindingService = domainFindingService;
Assert.notNull(conversionService, "conversionService is null");
this.conversionService = conversionService;
}
/**
* JAVADOC Method Level Comments
*
* @param event JAVADOC.
* @return JAVADOC.
*/
@Override
public ConversationEvent handleEvent(ConversationEvent event) {
if (LOG.isDebugEnabled()) {
LOG.debug("Handling event:" + event);
}
// TODO typecheck
ProcessElementDto source = (ProcessElementDto) event.getSource();
Map<String, Object> parameters = ((CallbackEvent) event).getParameters();
Assert.notNull(source, "no dto in event");
Object pe = loadDomainObject(source.getDomainType(), source.getDomainId());
if (LOG.isDebugEnabled()) {
LOG.debug("Loaded object " + pe);
}
if (source instanceof CheckDescriptorDto) {
boolean result = conversionService.convert(source, Check.class).test(pe,
parameters);
return new BooleanEvent(event, result);
} else if (source instanceof OperationDescriptorDto) {
conversionService.convert(source, Operation.class).execute(pe, parameters);
return new ActionResultEvent(parameters);
}
// TODO look at the usage
throw new IllegalArgumentException("Invalid event has been sent, rolling back");
}
private Object loadDomainObject(String type, Object id) {
return domainFindingService.find(type, id);
}
}
|
cucina/opencucina
|
engine-client/src/main/java/org/cucina/engine/client/service/ProcessEventHandler.java
|
Java
|
apache-2.0
| 2,730
|
Aeron Archive
===
[](http://www.javadoc.io/doc/io.aeron/aeron-all)
The aeron-archive is an module which enables Aeron data stream recording and replay from persistent storage.
Samples can be found [here](https://github.com/real-logic/aeron/blob/master/aeron-samples/scripts/archive/README.md) and
systems tests [here](https://github.com/real-logic/aeron/tree/master/aeron-system-tests/src/test/java/io/aeron/archive).
Features:
- **Record:** service can record a particular subscription, described by `<channel, streamId>`. Each resulting image
for the subscription will be recorded under a new `recordingId`. Local network publications are recorded using the spy
feature for efficiency. If no subscribers are active then the recording can advance the stream by setting the
`aeron.spies.simulate.connection` system property to true.
- **Extend:** service can extend an existing recording by appending.
- **Replay:** service can replay a recorded `recordingId` from a particular `position`, and for a particular `length`
which can be `Aeron.NULL_VALUE` for an open ended replay.
- **Query:** the catalog for existing recordings and the recorded position of an active recording.
- **Truncate:** allows a stopped recording to have its length truncated, and if truncated to the start position then it
is effectively deleted.
- **Replay Merge:** allows a late joining subscriber of a recorded stream to replay a recording and then merge with the
live stream for cut over if the consumer is fast enough to keep up.
Usage
=====
Protocol
=====
Messages are specified using SBE in [aeron-archive-codecs.xml](https://github.com/real-logic/aeron/blob/master/aeron-archive/src/main/resources/aeron-archive-codecs.xml).
The Archive communicates via the following interfaces:
- **Recording Events stream:** other parties can subscribe to events for the start,
stop, and progress of recordings. These are the recording events messages specified in the codec.
- **Control Request stream:** this allows clients to initiate replay or queries interactions with the archive.
Requests have a correlationId sent on the initiating request. The `correlationId` is expected to be managed by
the clients and is offered as a means for clients to track multiple concurrent requests. A request will typically
involve the archive sending data back on the reply channel specified by the client on the `ConnectRequest`.
A control session can be established with the Archive after a `ConnectRequest`. Operations happen within
the context of such a ControlSession which is allocated a `controlSessionId`.
Recording Events
----
Aeron clients wishing to observe the Archive recordings lifecycle can do so by subscribing to the recording events
channel. The messages are described in the codec. To fully capture the state of the Archive a client could subscribe
to these events as well as query for the full list of descriptors.
Persisted Format
=====
The Archive is backed by 2 file types, all of which are expected to reside in the `archiveDir`.
- **Catalog (one per archive):** The catalog contains fixed length (1k) records of recording
descriptors. The descriptors can be queried as described above. Each descriptor entry is 1k aligned,
and as the `recordingId` is a simple sequence, this means lookup is a dead reckoning operation.
Each entry has a header (32 bytes) followed by the RecordingDescriptor, the header contains the encoded
length of the RecordingDescriptor. See the codec schema for full descriptor details.
- **Recording Segment Data (many per recorded stream):** This is where the recorded data is kept.
Recording segments follow the naming convention of: `<recordingId>-<segmentIndex>.rec`
The Archive copies data as is from the recorded Image. As such the files follow the same convention
as Aeron data streams. Data starts at `startPosition`, which translates into the offset
`startPosition % termBufferLength` in the first segment file. From there one can read fragments
as described by the `DataHeaderFlyweight` up to the `stopPosition`. Segment length is a multiple of `termBufferLength`.
|
galderz/Aeron
|
aeron-archive/README.md
|
Markdown
|
apache-2.0
| 4,183
|
import * as React from "react";
import { LineContainerComponent } from '../../sharedComponents/lineContainerComponent';
import { IPropertyComponentProps } from './propertyComponentProps';
import { TextInputLineComponent } from '../../sharedComponents/textInputLineComponent';
import { TextLineComponent } from '../../sharedComponents/textLineComponent';
import { CheckBoxLineComponent } from '../../sharedComponents/checkBoxLineComponent';
import { FloatLineComponent } from '../../sharedComponents/floatLineComponent';
import { SliderLineComponent } from '../../sharedComponents/sliderLineComponent';
import { Vector2LineComponent } from '../../sharedComponents/vector2LineComponent';
import { OptionsLineComponent } from '../../sharedComponents/optionsLineComponent';
import { InputBlock } from 'babylonjs/Materials/Node/Blocks/Input/inputBlock';
import { PropertyTypeForEdition, IPropertyDescriptionForEdition, IEditablePropertyListOption } from 'babylonjs/Materials/Node/nodeMaterialDecorator';
export class GenericPropertyComponent extends React.Component<IPropertyComponentProps> {
constructor(props: IPropertyComponentProps) {
super(props);
}
render() {
return (
<>
<GeneralPropertyTabComponent globalState={this.props.globalState} block={this.props.block}/>
<GenericPropertyTabComponent globalState={this.props.globalState} block={this.props.block}/>
</>
);
}
}
export class GeneralPropertyTabComponent extends React.Component<IPropertyComponentProps> {
constructor(props: IPropertyComponentProps) {
super(props);
}
render() {
return (
<>
<LineContainerComponent title="GENERAL">
{
(!this.props.block.isInput || !(this.props.block as InputBlock).isAttribute) &&
<TextInputLineComponent globalState={this.props.globalState} label="Name" propertyName="name" target={this.props.block}
onChange={() => this.props.globalState.onUpdateRequiredObservable.notifyObservers()} />
}
<TextLineComponent label="Type" value={this.props.block.getClassName()} />
<TextInputLineComponent globalState={this.props.globalState} label="Comments" propertyName="comments" target={this.props.block}
onChange={() => this.props.globalState.onUpdateRequiredObservable.notifyObservers()} />
</LineContainerComponent>
</>
);
}
}
export class GenericPropertyTabComponent extends React.Component<IPropertyComponentProps> {
constructor(props: IPropertyComponentProps) {
super(props);
}
forceRebuild(notifiers?: { "rebuild"?: boolean; "update"?: boolean; }) {
if (!notifiers || notifiers.update) {
this.props.globalState.onUpdateRequiredObservable.notifyObservers();
}
if (!notifiers || notifiers.rebuild) {
this.props.globalState.onRebuildRequiredObservable.notifyObservers();
}
}
render() {
const block = this.props.block,
propStore: IPropertyDescriptionForEdition[] = (block as any)._propStore;
if (!propStore) {
return (
<>
</>
);
}
const componentList: { [groupName: string]: JSX.Element[]} = {},
groups: string[] = [];
for (const { propertyName, displayName, type, groupName, options } of propStore) {
let components = componentList[groupName];
if (!components) {
components = [];
componentList[groupName] = components;
groups.push(groupName);
}
switch (type) {
case PropertyTypeForEdition.Boolean: {
components.push(
<CheckBoxLineComponent label={displayName} target={this.props.block} propertyName={propertyName} onValueChanged={() => this.forceRebuild(options.notifiers)} />
);
break;
}
case PropertyTypeForEdition.Float: {
let cantDisplaySlider = (isNaN(options.min as number) || isNaN(options.max as number) || options.min === options.max);
if (cantDisplaySlider) {
components.push(
<FloatLineComponent globalState={this.props.globalState} label={displayName} propertyName={propertyName} target={this.props.block} onChange={() => this.forceRebuild(options.notifiers)} />
);
} else {
components.push(
<SliderLineComponent label={displayName} target={this.props.block} propertyName={propertyName} step={Math.abs((options.max as number) - (options.min as number)) / 100.0} minimum={Math.min(options.min as number, options.max as number)} maximum={options.max as number} onChange={() => this.forceRebuild(options.notifiers)}/>
);
}
break;
}
case PropertyTypeForEdition.Vector2: {
components.push(
<Vector2LineComponent globalState={this.props.globalState} label={displayName} propertyName={propertyName} target={this.props.block} onChange={() => this.forceRebuild(options.notifiers)} />
);
break;
}
case PropertyTypeForEdition.List: {
components.push(
<OptionsLineComponent label={displayName} options={options.options as IEditablePropertyListOption[]} target={this.props.block} propertyName={propertyName} onSelect={() => this.forceRebuild(options.notifiers)} />
);
break;
}
}
}
return (
<>
{
groups.map((group) =>
<LineContainerComponent title={group}>
{componentList[group]}
</LineContainerComponent>
)
}
</>
);
}
}
|
jbousquie/Babylon.js
|
nodeEditor/src/diagram/properties/genericNodePropertyComponent.tsx
|
TypeScript
|
apache-2.0
| 6,448
|
package com.koch.ambeth.query;
/*-
* #%L
* jambeth-test
* %%
* Copyright (C) 2017 Koch Softwaredevelopment
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
* #L%
*/
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import java.sql.Date;
import java.sql.Timestamp;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import javax.persistence.criteria.JoinType;
import org.junit.Assert;
import org.junit.Test;
import com.koch.ambeth.event.IEventDispatcher;
import com.koch.ambeth.filter.IPagingResponse;
import com.koch.ambeth.filter.PagingRequest;
import com.koch.ambeth.informationbus.persistence.setup.SQLData;
import com.koch.ambeth.informationbus.persistence.setup.SQLStructure;
import com.koch.ambeth.ioc.annotation.Autowired;
import com.koch.ambeth.ioc.exception.BeanAlreadyDisposedException;
import com.koch.ambeth.merge.IMergeProcess;
import com.koch.ambeth.merge.cache.ICache;
import com.koch.ambeth.merge.proxy.PersistenceContext;
import com.koch.ambeth.merge.proxy.PersistenceContextType;
import com.koch.ambeth.model.AbstractEntity;
import com.koch.ambeth.persistence.api.IDatabase;
import com.koch.ambeth.persistence.api.database.DatabaseCallback;
import com.koch.ambeth.persistence.filter.QueryConstants;
import com.koch.ambeth.query.config.QueryConfigurationConstants;
import com.koch.ambeth.query.filter.IPagingQuery;
import com.koch.ambeth.query.jdbc.sql.SqlColumnOperand;
import com.koch.ambeth.query.jdbc.sql.SqlJoinOperator;
import com.koch.ambeth.query.persistence.IDataCursor;
import com.koch.ambeth.query.persistence.IDataItem;
import com.koch.ambeth.query.persistence.IEntityCursor;
import com.koch.ambeth.query.persistence.IVersionCursor;
import com.koch.ambeth.query.persistence.IVersionItem;
import com.koch.ambeth.service.cache.ClearAllCachesEvent;
import com.koch.ambeth.service.config.ServiceConfigurationConstants;
import com.koch.ambeth.service.merge.model.IObjRef;
import com.koch.ambeth.testutil.AbstractInformationBusWithPersistenceTest;
import com.koch.ambeth.testutil.TestProperties;
import com.koch.ambeth.testutil.TestPropertiesList;
import com.koch.ambeth.util.collections.ArrayList;
import com.koch.ambeth.util.collections.HashMap;
import com.koch.ambeth.util.collections.ILinkedMap;
import com.koch.ambeth.util.collections.IList;
@TestPropertiesList({
@TestProperties(
name = "ambeth.log.level.com.koch.ambeth.persistence.jdbc.connection.LogPreparedStatementInterceptor",
value = "DEBUG"),
@TestProperties(name = ServiceConfigurationConstants.mappingFile,
value = "com/koch/ambeth/query/Query_orm.xml")})
@SQLStructure("Query_structure.sql")
@SQLData("Query_data.sql")
@PersistenceContext(PersistenceContextType.NOT_REQUIRED)
public class QueryTest extends AbstractInformationBusWithPersistenceTest {
protected static final String paramName1 = "param.1";
protected static final String paramName2 = "param.2";
protected static final String columnName1 = "ID";
protected static final String propertyName1 = "Id";
protected static final String columnName2 = "VERSION";
protected static final String propertyName2 = "Version";
protected static final String columnName3 = "FK";
protected static final String propertyName3 = "Fk";
protected static final String columnName4 = "CONTENT";
protected static final String propertyName4 = "Content";
protected static final String propertyName5 = "Name1";
@Autowired
protected ICache cache;
@Autowired
protected IMergeProcess mergeProcess;
protected IQueryBuilder<QueryEntity> qb;
protected HashMap<Object, Object> nameToValueMap = new HashMap<>();
@Override
public void afterPropertiesSet() throws Throwable {
super.afterPropertiesSet();
qb = queryBuilderFactory.create(QueryEntity.class);
nameToValueMap.clear();
}
@SuppressWarnings("deprecation")
@Test
public void testFinalize() throws Exception {
IOperand rootOperand = qb.let(qb.column(columnName1)).isEqualTo(qb.valueName(paramName1));
assertNotNull(qb.build(rootOperand));
}
@Test(expected = BeanAlreadyDisposedException.class)
public void testFinalize_alreadBuild1() throws Exception {
qb.build();
qb.dispose();
qb.build();
}
@SuppressWarnings("deprecation")
@Test(expected = BeanAlreadyDisposedException.class)
public void testFinalize_alreadyBuild2() throws Exception {
IOperand rootOperand = qb.let(qb.column(columnName1)).isEqualTo(qb.valueName(paramName1));
qb.build(rootOperand);
qb.dispose();
qb.build(rootOperand);
}
@SuppressWarnings("deprecation")
@Test(expected = BeanAlreadyDisposedException.class)
public void testFinalize_alreadyBuild3() throws Exception {
IOperand rootOperand = qb.let(qb.column(columnName1)).isEqualTo(qb.valueName(paramName1));
qb.build(rootOperand, new ISqlJoin[0]);
qb.dispose();
qb.build(rootOperand);
}
@SuppressWarnings("deprecation")
@Test(expected = IllegalStateException.class)
public void testRetrieveAsVersionCursorNoTransaction() throws Exception {
Object value1 = Integer.valueOf(3);
IOperand rootOperand = qb.let(qb.column(columnName1)).isEqualTo(qb.valueName(paramName1));
IQuery<QueryEntity> query = qb.build(rootOperand);
IVersionCursor actual = query.param(paramName1, value1).retrieveAsVersions();
assertNotNull(actual);
Iterator<IVersionItem> iterator = actual.iterator();
assertTrue(iterator.hasNext());
IVersionItem item = iterator.next();
assertNotNull(item);
assertEquals(value1, conversionHelper.convertValueToType(value1.getClass(), item.getId()));
}
@Test
public void testRetrieveAsVersionCursor() throws Exception {
transaction.processAndCommit(new DatabaseCallback() {
@Override
public void callback(ILinkedMap<Object, IDatabase> persistenceUnitToDatabaseMap)
throws Exception {
testRetrieveAsVersionCursorNoTransaction();
}
});
}
@SuppressWarnings("deprecation")
@Test
public void testRetrieveAsEntityCursor() throws Exception {
final Object value1 = Integer.valueOf(2);
IOperand rootOperand = qb.let(qb.column(columnName1)).isEqualTo(qb.valueName(paramName1));
final IQuery<QueryEntity> query = qb.build(rootOperand);
transaction.processAndCommit(new DatabaseCallback() {
@Override
public void callback(
com.koch.ambeth.util.collections.ILinkedMap<Object, IDatabase> persistenceUnitToDatabaseMap)
throws Exception {
IEntityCursor<QueryEntity> actual = query.param(paramName1, value1).retrieveAsCursor();
assertNotNull(actual);
Iterator<QueryEntity> iterator = actual.iterator();
assertTrue(iterator.hasNext());
QueryEntity item = iterator.next();
assertNotNull(item);
assertEquals(value1, item.getId());
}
});
}
@SuppressWarnings("deprecation")
@Test
public void testRetrieveAsList() throws Exception {
List<Integer> values = Arrays.asList(new Integer[] {2, 4});
IOperand operand1 = qb.let(qb.column(columnName1)).isEqualTo(qb.valueName(paramName1));
IOperand operand2 = qb.let(qb.column(columnName1)).isEqualTo(qb.valueName(paramName2));
IOperand rootOperand = qb.or(operand1, operand2);
IQuery<QueryEntity> query = qb.build(rootOperand);
nameToValueMap.put(paramName1, values.get(0));
nameToValueMap.put(paramName2, values.get(1));
List<QueryEntity> actual = query.retrieve(nameToValueMap);
assertSimilar(values, actual);
}
@SuppressWarnings("deprecation")
@Test
public void retrieveWhereNullByEqual() throws Exception {
List<Integer> expected = Arrays.asList(new Integer[] {2, 5});
IQuery<QueryEntity> query = qb
.build(qb.let(qb.property(propertyName3)).isEqualTo(qb.valueName(paramName1)));
nameToValueMap.put(paramName1, null);
List<QueryEntity> actual = query.retrieve(nameToValueMap);
assertSimilar(expected, actual);
}
@SuppressWarnings("deprecation")
@Test
public void retrieveWhereNotNullByEqual() throws Exception {
List<Integer> expected = Arrays.asList(new Integer[] {1, 3, 4, 6});
IQuery<QueryEntity> query = qb
.build(qb.let(qb.property(propertyName3)).isNotEqualTo(qb.valueName(paramName1)));
nameToValueMap.put(paramName1, null);
List<QueryEntity> actual = query.retrieve(nameToValueMap);
assertSimilar(expected, actual);
}
/**
* Greater-than with a null-value is always false - so no results.
*
* @throws Exception
*/
@SuppressWarnings("deprecation")
@Test
public void retrieveWhereGTNullByEqual() throws Exception {
IQuery<QueryEntity> query = qb
.build(qb.let(qb.property(propertyName3)).isGreaterThan(qb.valueName(paramName1)));
nameToValueMap.put(paramName1, null);
List<QueryEntity> actual = query.retrieve(nameToValueMap);
assertTrue(actual.isEmpty());
}
@Test
public void retrieveWhereNull() throws Exception {
List<Integer> expected = Arrays.asList(2, 5);
IQuery<QueryEntity> query = qb.build(qb.let(qb.property(propertyName3)).isNull());
List<QueryEntity> actual = query.param(paramName1, null).retrieve();
assertSimilar(expected, actual);
}
@Test
public void retrieveWhereNotNull() throws Exception {
List<Integer> expected = Arrays.asList(1, 3, 4, 6);
IQuery<QueryEntity> query = qb.build(qb.let(qb.property(propertyName3)).isNotNull());
List<QueryEntity> actual = query.param(paramName1, null).retrieve();
assertSimilar(expected, actual);
}
@Test
public void retrieveByDate_long() {
long updatedOn = updateQueryEntity1();
IQuery<QueryEntity> query = qb
.build(qb.let(qb.property("UpdatedOn")).isEqualTo(qb.value(updatedOn)));
IList<QueryEntity> res = query.retrieve();
Assert.assertNotNull(res);
Assert.assertEquals(1, res.size());
Assert.assertEquals(1, res.get(0).getId());
}
@Test
public void retrieveByDate_Date() {
long updatedOn = updateQueryEntity1();
java.util.Date updatedOnDate = new java.util.Date(updatedOn);
IQuery<QueryEntity> query = qb
.build(qb.let(qb.property("UpdatedOn")).isEqualTo(qb.value(updatedOnDate)));
IList<QueryEntity> res = query.retrieve();
Assert.assertNotNull(res);
Assert.assertEquals(1, res.size());
Assert.assertEquals(1, res.get(0).getId());
}
@Test
public void retrieveByDate_SqlDate() {
long updatedOn = updateQueryEntity1();
Date updatedOnDate = new Date(updatedOn);
IQuery<QueryEntity> query = qb
.build(qb.let(qb.property("UpdatedOn")).isEqualTo(qb.value(updatedOnDate)));
IList<QueryEntity> res = query.retrieve();
Assert.assertNotNull(res);
Assert.assertEquals(1, res.size());
Assert.assertEquals(1, res.get(0).getId());
}
@Test
public void retrieveByDate_Timestamp() {
long updatedOn = updateQueryEntity1();
Timestamp timestamp = new Timestamp(updatedOn);
IQuery<QueryEntity> query = qb
.build(qb.let(qb.property("UpdatedOn")).isEqualTo(qb.value(timestamp)));
IList<QueryEntity> res = query.retrieve();
Assert.assertNotNull(res);
Assert.assertEquals(1, res.size());
Assert.assertEquals(1, res.get(0).getId());
}
protected long updateQueryEntity1() {
QueryEntity queryEntity1 = cache.getObject(QueryEntity.class, 1);
queryEntity1.setContent(2.);
mergeProcess.process(queryEntity1);
long updatedOn = queryEntity1.getUpdatedOn();
return updatedOn;
}
@Test
public void retrieveAll() throws Exception {
List<Integer> expected = Arrays.asList(1, 2, 3, 4, 5, 6);
IQuery<QueryEntity> query = qb.build();
List<QueryEntity> actual = query.retrieve();
assertSimilar(expected, actual);
}
@Test
public void retrieveWithLimitAndOrder1() throws Exception {
IQuery<QueryEntity> query = qb.limit(qb.value(1))
.orderBy(qb.property("UpdatedOn"), OrderByType.DESC).build();
List<QueryEntity> actual = query.retrieve();
assertEquals(1, actual.size());
}
@Test
public void retrieveWithLimit1() throws Exception {
IQuery<QueryEntity> query = qb.limit(qb.value(1)).build();
List<QueryEntity> actual = query.retrieve();
assertEquals(1, actual.size());
}
@Test
public void retrieveSingleWithLimit1() throws Exception {
IQuery<QueryEntity> query = qb.limit(qb.value(1)).build();
QueryEntity actual = query.retrieveSingle();
assertNotNull(actual);
}
@Test
public void retrieveWithLimit100() throws Exception {
List<Integer> expected = Arrays.asList(1, 2, 3, 4, 5, 6);
IQuery<QueryEntity> query = qb.limit(qb.value(100)).build();
List<QueryEntity> actual = query.retrieve();
assertSimilar(expected, actual);
}
@Test
public void isEmptyWithLimit0() throws Exception {
// This test makes sure that limit 1 is stil used for isEmpty
IQuery<QueryEntity> query = qb.limit(qb.value(0)).build();
Assert.assertFalse(query.isEmpty());
}
@Test
public void retrieveAllAfterUpdate() throws Exception {
transaction.processAndCommit(new DatabaseCallback() {
@Override
public void callback(ILinkedMap<Object, IDatabase> persistenceUnitToDatabaseMap)
throws Exception {
String name1Value = "name1xx";
List<Integer> expectedBeforeUpdate = Arrays.asList(1, 2, 3, 4, 5, 6);
List<Integer> expectedAfterUpdate = Arrays.asList(1, 3, 4, 5, 6);
IQuery<QueryEntity> query = qb
.build(qb.let(qb.property(QueryEntity.Name1)).isNotEqualTo(qb.value(name1Value)));
List<QueryEntity> allBeforeUpdate = query.retrieve();
assertSimilar(expectedBeforeUpdate, allBeforeUpdate);
QueryEntity changedQueryEntity = beanContext.getService(ICache.class)
.getObject(QueryEntity.class, 2);
changedQueryEntity.setName1(name1Value);
beanContext.getService(IMergeProcess.class).process(changedQueryEntity);
List<QueryEntity> allAfterUpdate = query.retrieve();
assertSimilar(expectedAfterUpdate, allAfterUpdate);
}
});
}
@Test
@PersistenceContext
public void retrieveGroupByWithSum() throws Exception {
// Select col1, sum(col2) as col2 from table group by col1 where col2 = ?
// Select VERSION, sum(CONTENT) as CONTENT from QUERY_ENTITY group by VERSION
IOperand versionProperty = qb.property("Version");
int versionIndex = qb.select(versionProperty);
int contentIndex = qb.select(qb.function("SUM", qb.property("Content")));
IQuery<QueryEntity> query = qb.groupBy(versionProperty).build();
IDataCursor dataCursor = query.retrieveAsData();
try {
for (IDataItem dataItem : dataCursor) {
Object version = dataItem.getValue(versionIndex);
Object content = dataItem.getValue(contentIndex);
System.out.println(version + ": " + content);
}
}
finally {
dataCursor.dispose();
}
}
@Test
@PersistenceContext
public void retrieveGroupByWithCount() throws Exception {
// Select col1, sum(col2) as col2 from table group by col1 where col2 = ?
// Select VERSION, count(VERSION) as COUNT from QUERY_ENTITY group by VERSION where VERSION = 2
IOperand versionProperty = qb.property("Version");
int versionIndex = qb.select(versionProperty);
int countIndex = qb.select(qb.function("Count", versionProperty));
qb.groupBy(versionProperty);
IQuery<QueryEntity> query = qb.groupBy(versionProperty)
.build(qb.let(versionProperty).isEqualTo(qb.value(2)));
IDataCursor dataCursor = query.retrieveAsData();
try {
for (IDataItem dataItem : dataCursor) {
Object version = dataItem.getValue(versionIndex);
Object content = dataItem.getValue(countIndex);
System.out.println(version + ": " + content);
}
}
finally {
dataCursor.dispose();
}
}
@Test
@PersistenceContext
public void retrieveAllGroupByOrderBy() throws Exception {
IOperand versionOp = qb.property(AbstractEntity.Version);
IOperand maxName1 = qb.function("MAX", qb.property(QueryEntity.Name1));
int maxIndex = qb.select(maxName1);
int versionIndex = qb.select(versionOp);
IQuery<QueryEntity> query = qb.groupBy(versionOp).orderBy(versionOp, OrderByType.DESC).build(); // .build(qb.isNotEqualTo(maxName1,
// qb.value(0)));
Object[][] expected = {{2, "name2"}, {1, "name3"}};
IDataCursor dataCursor = query.retrieveAsData();
try {
int index = 0;
if (expected.length > 0) {
Assert.assertEquals(expected[0].length, dataCursor.getFieldCount());
}
for (IDataItem dataItem : dataCursor) {
Object version = dataItem.getValue(versionIndex);
Object max = dataItem.getValue(maxIndex);
Object[] expectedItem = expected[index];
Assert.assertEquals(expectedItem[0].toString(), version.toString());
Assert.assertEquals(expectedItem[1].toString(), max.toString());
index++;
}
Assert.assertEquals(expected.length, index);
}
finally {
dataCursor.dispose();
}
}
@Test
@TestProperties(name = QueryConfigurationConstants.PagingPrefetchBehavior, value = "true")
public void retrievePagingAfterUpdate() throws Exception {
transaction.processAndCommit(new DatabaseCallback() {
@Override
public void callback(ILinkedMap<Object, IDatabase> persistenceUnitToDatabaseMap)
throws Exception {
String name1Value = "name1xx";
List<Integer> expectedBeforeUpdate = Arrays.asList(new Integer[] {1, 2, 3, 4, 5, 6});
List<Integer> expectedAfterUpdate = Arrays.asList(new Integer[] {1, 3, 4, 5, 6});
PagingRequest pr = new PagingRequest().withNumber(1).withSize(expectedBeforeUpdate.size());
IPagingQuery<QueryEntity> query = qb
.buildPaging(
qb.let(qb.property(QueryEntity.Name1)).isNotEqualTo(qb.value(name1Value)));
IPagingResponse<QueryEntity> allBeforeUpdate = query.retrieve(pr);
assertSimilar(expectedBeforeUpdate, allBeforeUpdate.getResult());
QueryEntity changedQueryEntity = beanContext.getService(ICache.class)
.getObject(QueryEntity.class, 2);
changedQueryEntity.setName1(name1Value);
beanContext.getService(IMergeProcess.class).process(changedQueryEntity);
IPagingResponse<QueryEntity> allAfterUpdate = query.retrieve(pr);
assertSimilar(expectedAfterUpdate, allAfterUpdate.getResult());
}
});
}
@SuppressWarnings("deprecation")
@Test
public void fulltextSimple() throws Exception {
IOperand rootOperand = qb.fulltext(qb.valueName(paramName1));
qb.orderBy(qb.property("Id"), OrderByType.ASC);
IQuery<QueryEntity> query = qb.build(rootOperand);
HashMap<Object, Object> nameToValueMap = new HashMap<>();
nameToValueMap.put(paramName1, "me3");
List<QueryEntity> result = query.retrieve(nameToValueMap);
assertEquals(3, result.size());
assertEquals(1, result.get(0).getId());
assertEquals(3, result.get(1).getId());
assertEquals(4, result.get(2).getId());
}
@Test
public void retrieveAllOrdered() throws Exception {
List<Integer> expectedIds = Arrays.asList(new Integer[] {1, 2, 3, 4, 5, 6});
qb.orderBy(qb.property("Id"), OrderByType.ASC);
IQuery<QueryEntity> queryAsc = qb.build(qb.all());
qb = queryBuilderFactory.create(QueryEntity.class);
qb.orderBy(qb.property("Id"), OrderByType.DESC);
IQuery<QueryEntity> queryDesc = qb.build(qb.all());
List<QueryEntity> actualAsc = queryAsc.retrieve();
assertEquals(expectedIds.size(), actualAsc.size());
for (int i = actualAsc.size(); i-- > 0;) {
assertEquals((int) expectedIds.get(i), actualAsc.get(i).getId());
}
List<QueryEntity> actualDesc = queryDesc.retrieve();
int size = actualAsc.size();
assertEquals(size, actualDesc.size());
for (int i = size; i-- > 0;) {
assertEquals(actualAsc.get(i), actualDesc.get(size - i - 1));
}
}
@SuppressWarnings("deprecation")
@Test
public void retrievePagingSimple() throws Exception {
List<Integer> expected = Arrays.asList(new Integer[] {4, 3, 2});
qb.orderBy(qb.property("Id"), OrderByType.DESC);
qb.orderBy(qb.property("Version"), OrderByType.ASC);
IQuery<QueryEntity> query = qb.build(qb.all());
HashMap<Object, Object> currentNameToValueMap = new HashMap<>(nameToValueMap);
currentNameToValueMap.put(QueryConstants.PAGING_INDEX_OBJECT, 2);
currentNameToValueMap.put(QueryConstants.PAGING_SIZE_OBJECT, expected.size());
List<QueryEntity> actual = query.retrieve(currentNameToValueMap);
assertEquals(expected.size(), actual.size());
for (int i = expected.size(); i-- > 0;) {
assertEquals((int) expected.get(i), actual.get(i).getId());
}
}
/**
* The column of the alternate key is selected two times (once as AK and once for the 'orderBy').
*
* @throws Exception
*/
@Test
public void retrievePagingAllOrderedByAK() throws Exception {
List<Integer> expectedIds = Arrays.asList(2, 1, 5, 6, 3, 4);
qb.orderBy(qb.property("Name1"), OrderByType.ASC);
IPagingQuery<QueryEntity> pagingQuery = qb.buildPaging(qb.all());
PagingRequest pagingRequest = new PagingRequest();
pagingRequest.setNumber(1);
pagingRequest.setSize(expectedIds.size());
IPagingResponse<QueryEntity> pagingResponse = pagingQuery.retrieveRefs(pagingRequest);
assertEquals(pagingRequest.getSize(), pagingResponse.getSize());
List<IObjRef> refResult = pagingResponse.getRefResult();
assertEquals(pagingRequest.getSize(), refResult.size());
}
@PersistenceContext
@Test
public void retrieveAllOrderedByNotSelectedChildProp() throws Exception {
List<Integer> expectedIds = Arrays.asList(3, 6, 4, 1, 5, 2);
// Query used:
// SELECT DISTINCT S_A."ID",S_A."VERSION",S_A."NAME1",J_A."ID" FROM "JAMBETH"."QUERY_ENTITY" S_A
// LEFT OUTER JOIN "JAMBETH"."JOIN_QUERY_ENTITY" J_A ON (S_A."FK"=J_A."ID")
// ORDER BY J_A."ID" ASC
qb.orderBy(qb.property("Fk.Id"), OrderByType.ASC);
IQuery<QueryEntity> query = qb.build(qb.all());
IVersionCursor versionCursor = query.retrieveAsVersions(true);
try {
ArrayList<Integer> loadedIds = new ArrayList<>();
for (IVersionItem current : versionCursor) {
Integer currentId = conversionHelper.convertValueToType(Integer.class, current.getId());
loadedIds.add(currentId);
}
Object[] expectedArray = expectedIds.toArray();
Arrays.sort(expectedArray);
Object[] loadedArray = loadedIds.toArray();
Arrays.sort(loadedArray);
Assert.assertArrayEquals(expectedArray, loadedArray);
}
finally {
versionCursor.dispose();
}
}
@Test
public void testJoinQuery() throws Exception {
List<Integer> expectedIds = Arrays.asList(1, 4);
// Query used:
// SELECT DISTINCT S_A."ID",S_A."VERSION",S_A."NAME1" FROM "JAMBETH"."QUERY_ENTITY"
// S_A LEFT OUTER JOIN "JAMBETH"."JOIN_QUERY_ENTITY" J_A ON (S_A."FK"=J_A."ID")
// WHERE (J_A."VERSION"=?)
IQuery<QueryEntity> query = qb
.build(qb.let(qb.property("Fk.Version")).isEqualTo(qb.valueName(paramName1)));
List<QueryEntity> actual = query.param(paramName1, 3).retrieve();
assertSimilar(expectedIds, actual);
actual = query.param(paramName1, 2).retrieve();
assertNotNull(actual);
assertEquals(2, actual.size());
}
@SuppressWarnings("deprecation")
@Test
public void testJoinQueryWithOrderBy() throws Exception {
List<Integer> expectedIds = Arrays.asList(new Integer[] {1, 4});
// Query used:
// SELECT "QUERY_ENTITY"."ID","QUERY_ENTITY"."VERSION" FROM "QUERY_ENTITY"
// LEFT OUTER JOIN "JOIN_QUERY_ENTITY" ON ("QUERY_ENTITY"."FK"="JOIN_QUERY_ENTITY"."ID")
// WHERE ("JOIN_QUERY_ENTITY"."VERSION"=3)
IOperand fkA = qb.column(columnName3);
IOperand idB = qb.column(columnName1);
ISqlJoin joinClause = qb.join(JoinQueryEntity.class, fkA, idB, JoinType.LEFT);
IOperand verB = qb.column(columnName2, joinClause);
IOperand whereClause = qb.let(verB).isEqualTo(qb.valueName(paramName1));
qb.orderBy(qb.property(propertyName5), OrderByType.ASC);
IQuery<QueryEntity> query = qb.build(whereClause, joinClause);
nameToValueMap.put(paramName1, 3);
List<QueryEntity> actual = query.retrieve(nameToValueMap);
assertSimilar(expectedIds, actual);
nameToValueMap.clear();
nameToValueMap.put(paramName1, 2);
actual = query.retrieve(nameToValueMap);
assertNotNull(actual);
assertEquals(2, actual.size());
assertEquals(6, actual.get(0).getId());
}
@SuppressWarnings("deprecation")
@Test
public void testJoinToSelfQuery() throws Exception {
List<Integer> expectedIds = Arrays.asList(new Integer[] {1, 3, 5, 6});
// Query used:
// SELECT A."ID",A."VERSION" FROM "QUERY_ENTITY" A
// LEFT OUTER JOIN "QUERY_ENTITY" B ON ((A."VERSION"=B."VERSION") AND (A."ID"<>B."ID"))
// LEFT OUTER JOIN "JOIN_QUERY_ENTITY" C ON (B."FK"=C."ID")
// WHERE (C."VERSION"=2);
IOperand idQE1 = qb.column(columnName1);
IOperand idQE2 = qb.column(columnName1);
IOperand verQE1 = qb.column(columnName2);
IOperand verQE2 = qb.column(columnName2);
ISqlJoin joinClause1 = qb.join(QueryEntity.class,
qb.and(qb.let(verQE1).isEqualTo(verQE2), qb.let(idQE1).isNotEqualTo(idQE2)),
JoinType.LEFT);
((SqlColumnOperand) idQE2).setJoinClause((SqlJoinOperator) joinClause1);
((SqlColumnOperand) verQE2).setJoinClause((SqlJoinOperator) joinClause1);
IOperand fkQE = qb.column(columnName3, joinClause1);
IOperand idJQE = qb.column(columnName1);
ISqlJoin joinClause2 = qb.join(JoinQueryEntity.class, fkQE, idJQE, JoinType.LEFT);
IOperand verJQE = qb.column(columnName2, joinClause2);
IOperand whereClause = qb.let(verJQE).isEqualTo(qb.valueName(paramName1));
IQuery<QueryEntity> query = qb.build(whereClause, joinClause1, joinClause2);
nameToValueMap.put(paramName1, 2);
List<QueryEntity> actual = query.retrieve(nameToValueMap);
assertSimilar(expectedIds, actual);
}
@Test
public void testJoinToSelfQueryByProperty() throws Exception {
// SELECT DISTINCT S_A."ID",S_A."VERSION",S_A."NAME1" FROM "QUERY_ENTITY" S_A
// LEFT OUTER JOIN "JOIN_QUERY_ENTITY" J_A ON (S_A."FK"=J_A."ID")
// LEFT OUTER JOIN "JOIN_QUERY_ENTITY" J_B ON (J_A."PARENT"=J_B."ID")
// WHERE (J_B."ID"=?)
List<Integer> expectedIds = Arrays.asList(new Integer[] {3, 6});
IOperand whereClause = qb.let(qb.property("Fk.Parent.Id")).isEqualTo(qb.valueName(paramName1));
IQuery<QueryEntity> query = qb.build(whereClause);// whereClause, joinClause1, joinClause2);
List<QueryEntity> actual = query.param(paramName1, 2).retrieve();
assertSimilar(expectedIds, actual);
}
@SuppressWarnings("deprecation")
@Test
public void testIsInMoreThan1000() throws Exception {
int count = 2013;
IList<QueryEntity> entities = new ArrayList<>(count);
for (int a = count; a-- > 0;) {
QueryEntity queryEntity = entityFactory.createEntity(QueryEntity.class);
queryEntity.setName1("Name11_" + a);
queryEntity.setName2("Name22_" + a);
entities.add(queryEntity);
}
beanContext.getService(IMergeProcess.class).process(entities);
List<Object> values = new ArrayList<>(count);
for (int a = entities.size(); a-- > 0;) {
values.add(entities.get(a).getId());
}
IOperand rootOperand = qb.let(qb.column(columnName1)).isIn(qb.valueName(paramName1));
IQuery<QueryEntity> query = qb.build(rootOperand);
beanContext.getService(IEventDispatcher.class).dispatchEvent(ClearAllCachesEvent.getInstance());
entities = query.param(paramName1, values).retrieve();
assertNotNull(entities);
assertEquals(count, entities.size());
}
@Test
public void testQueryKeyUniqueness() throws Exception {
IQuery<QueryEntity> query = qb.build(qb.or(qb.let(qb.property("Id")).isEqualTo(qb.value(3)),
qb.let(qb.property("Fk.Version")).isEqualTo(qb.value(3))));
IQueryKey queryKey = query.getQueryKey(nameToValueMap);
qb = queryBuilderFactory.create(QueryEntity.class);
IQuery<QueryEntity> query2 =
qb.build(qb.or(qb.let(qb.property("Fk.Id")).isEqualTo(qb.value(3)),
qb.let(qb.property("Version")).isEqualTo(qb.value(3))));
IQueryKey queryKey2 = query2.getQueryKey(nameToValueMap);
assertFalse(queryKey.equals(queryKey2));
}
protected static void assertSimilar(List<Integer> expectedIds, List<QueryEntity> actual) {
assertNotNull(actual);
assertEquals(expectedIds.size(), actual.size());
for (int i = actual.size(); i-- > 0;) {
assertTrue(actual.get(i).getId() + " not expected",
expectedIds.contains(actual.get(i).getId()));
}
}
}
|
Dennis-Koch/ambeth
|
jambeth/jambeth-test/src/test/java/com/koch/ambeth/query/QueryTest.java
|
Java
|
apache-2.0
| 28,311
|
package com.guapiweather.android.service;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.IBinder;
import android.os.SystemClock;
import android.preference.PreferenceManager;
import com.guapiweather.android.gson.Weather;
import com.guapiweather.android.util.HttpUtil;
import com.guapiweather.android.util.Utility;
import java.io.IOException;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;
public class AutoUpdateService extends Service {
public AutoUpdateService() {
}
@Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
return null;
// throw new UnsupportedOperationException("Not yet implemented");
}
@Override
public int onStartCommand(Intent intent,int flags,int startId){
updateWeather();
updateBingPic();
AlarmManager manager=(AlarmManager)getSystemService(ALARM_SERVICE);
int anHour=8*60*60*1000;
long triggreAtTime= SystemClock.elapsedRealtime()+anHour;
Intent i=new Intent(this,AutoUpdateService.class);
PendingIntent pi=PendingIntent.getService(this,0,i,0);
manager.cancel(pi);
manager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP,triggreAtTime,pi);
return super.onStartCommand(intent,flags,startId);
}
/**
* 更新天气信息
*/
private void updateWeather(){
SharedPreferences prefs= PreferenceManager.getDefaultSharedPreferences(this);
String weatherString=prefs.getString("weather",null);
if(weatherString!=null){
//有缓存时直接解析天气数据
Weather weather= Utility.handleWeatherResponse(weatherString);
String weatherId=weather.basic.weatherId;
String weatherUrl="https://free-api.heweather.com/x3/weather?cityid="+weatherId+"&key=bb0ba703883b42a49292ed33bd7a7c7b";
HttpUtil.sendOkHttpRequest(weatherUrl, new Callback() {
@Override
public void onFailure(Call call, IOException e) {
e.printStackTrace();
}
@Override
public void onResponse(Call call, Response response) throws IOException {
String responseText=response.body().string();
Weather weather=Utility.handleWeatherResponse(responseText);
if(weather!=null&&"ok".equals(weather.status)) {
SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(AutoUpdateService.this).edit();
editor.putString("weather", responseText);
editor.apply();
}
}
});
}
}
/**
* 更新每日一图
*/
private void updateBingPic(){
String requestBingPic="http://guolin.tech/api/bing_pic";
HttpUtil.sendOkHttpRequest(requestBingPic, new Callback() {
@Override
public void onFailure(Call call, IOException e) {
e.printStackTrace();
}
@Override
public void onResponse(Call call, Response response) throws IOException {
String bingPic=response.body().string();
SharedPreferences.Editor editor=PreferenceManager.getDefaultSharedPreferences(AutoUpdateService.this).edit();
editor.putString("bing_pic",bingPic);
editor.apply();
}
});
}
}
|
LJiLong/guapiweather
|
app/src/main/java/com/guapiweather/android/service/AutoUpdateService.java
|
Java
|
apache-2.0
| 3,661
|
<?php
/**
* Copyright 2015 Tomas Halman
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
include_once "aducid/aducid.php";
include_once "config.php";
include_once "database.php";
/**
* hlavicka stranky
*/
function head() {
$html =
"<!DOCTYPE html>\n<html>\n".
"<head>\n".
" <meta charset=\"utf-8\">\n".
" <meta http-equiv=\"X-UA-Compatible\" content=\"IE=9\" />\n".
" <title>Demo Police-on-web</title>\n".
" <link rel=\"stylesheet\" href=\"css/bootstrap.min.css\">\n".
" <link rel=\"stylesheet\" href=\"app.css\">\n".
"</head>\n".
"<body>\n".
"<script src=\"js/jquery-1.10.1.min.js\"></script>\n".
"<script src=\"js/bootstrap.js\"></script>\n".
"<script src=\"app.js\"></script>\n".
"<!-- =================================== head end -->\n";
return $html;
}
/**
* paticka stranky
*/
function foot() {
return
"\n<!-- =================================== foot -->\n".
"</body>\n".
"</html>\n";
}
/**
* modalni dialog
*/
function popupMessageWithParams($image,$title,$text,$buttontext,$id = "popupModal") {
return
"\n<!-- =================================== popupMessage -->\n".
"<div id=\"". $id ."\" class=\"modal fade\">\n".
" <div class=\"modal-dialog\">\n".
" <div class=\"modal-content\">\n".
" <div class=\"modal-header\">\n".
" <button type=\"button\" class=\"close\" data-dismiss=\"modal\" aria-hidden=\"true\">×</button>\n".
" <h4 class=\"modal-title\">".
( ( $image != NULL ) ? "<img src=\"img/". $image ."\" width=\"30\"/> " : "" ) .
$title . "</h4>\n".
" </div>\n".
" <div class=\"modal-body\">\n".
" <p>" . $text . "</p>\n".
" </div>\n".
" <div class=\"modal-footer\">\n".
" <button type=\"button\" class=\"btn btn-default\" data-dismiss=\"modal\">".$buttontext."</button>\n".
" </div>\n".
" </div>\n".
" </div>\n".
"</div>\n";
}
/**
* JS pro vyvolani modalniho dialogu po nahrani stranky
*/
function onLoadJs($popup) {
return
"<script type=\"text/javascript\">\n".
" $(window).load(function(){\n".
" $('#" . $popup ."').modal('show');\n".
" });\n".
"</script>\n";
}
/**
* jedna polozka radio menu
*/
function radioItem($id, $selected, $label, $func="onRadioClick") {
$html = "<div class=\"radioitem\"><img id=\"radio" . $id . "\" src=\"app-radio" . ( $selected ? "-selected" : "" ) . ".png\"".
" onClick='".$func ."(".$id.")'>" .
" <label id=\"label" . $id . "\" for=\"radio" . $id . "\" onClick='".$func."(".$id.")'>" .
$label . " </label></div>" ;
return $html;
}
/**
* stranka neprihlaseneho uzivatele
*/
function loginBody() {
$html =
"<div class=\"container appcontainer\">\n" .
" <div class=\"row\">\n" .
" <img src=\"app-header.jpg\" width=\"100%\">\n".
" </div>\n".
" <div class=\"row\">\n" .
" <div class=\"apptext\">\n" .
" <p>Déposer une déclaration en ligne</p>\n".
" <p>Police-on-web vous permet de déposer plainte en ligne pour les délits repris dans la liste ci-dessous, de déposer un avis d'absence, et également de déclarer votre système d'alarme.</p>\n".
" <p>Attention ! Si une intervention urgente est requise, appelez le 101.</p>\n" .
" </div>\n" .
" <!-- div class=\"center-block eighty\"><img src=\"app-menu.jpg\" width=\"100%\"></div -->\n".
" </div>\n".
" <div class=\"row\">\n" .
" <div class=\"col-sm-1\">\n" .
" </div>\n".
" <div class=\"col-sm-5\">\n" .
" <div class=\"sectionheader\">Systèmes d'alarme:</div>\n" .
" " . radioItem(200, false, "Gestion des déclarations") . "\n" .
" <div><br/><br/></div>\n" .
" <div class=\"sectionheader\">Déclaration d'absence:</div>\n" .
" " . radioItem(300, false, "Demande de surveillance d'habitation") . "\n" .
" <br/>\n" .
" </div>\n".
" <div class=\"col-sm-5\">\n" .
" <div class=\"sectionheader\">Dépôt de plainte:</div>\n" .
" " . radioItem(400, false, "Vol de vélo") . "\n" .
" " . radioItem(401, false, "Vol de vélomoteur") . "\n" .
" " . radioItem(402, false, "Vol à l'étalage") . "\n" .
" " . radioItem(403, false, "Dégradations diverses") . "\n" .
" " . radioItem(404, false, "Graffiti") . "\n" .
" <br/>\n" .
" </div>\n".
" <div class=\"col-sm-1\">\n" .
" </div>\n".
" </div>\n".
" <div class=\"row\">\n" .
" <div class=\"col-sm-1\">\n" .
" </div>\n".
" <div class=\"col-sm-10\">\n" .
" <div class=\"sectionheader\">Méthode d'identification:</div>\n" .
" " . radioItem(100, false, "J'ai déjà une carte d'identité électronique, au moyen de laquelle je m'identifie","setLanguage") . "\n" .
" " . radioItem(101, false, "Je n'ai pas encore de carte d'identité électronique, par contre j'ai un token citoyen","setLanguage") . "\n" .
" " . radioItem(102, false, "Je n'ai ni carte d'identité électronique ni token; par contre j'ai un compte sur le portail fédéral","setLanguage") . "\n" .
" " . radioItem(103, false, "Jsem občan české republiky <img src=\"app-flag-cz.png\">","setLanguage") . "\n" .
" <p class=\"text-right\">\n" .
" <br/><br/><a id=\"loginbutton\" href=\"" . AducidClient::currentURL() . "?action=login\" class=\"btn loginbutton\" onclick='return checkAction()' >Suivant<img src=\"app-login-arrow.png\"></a>\n" .
" </p>\n".
" </div>\n".
" <div class=\"col-sm-1\">\n" .
" </div>\n".
" </div>\n".
"</div>\n";
return $html;
}
/**
* stranka prihlaseneho uzivatele
*/
function loggedInBody() {
$html =
"<div class=\"container appcontainer\">\n" .
" <div class=\"row\">\n" .
" <img src=\"app-header.jpg\" width=\"100%\">\n".
" </div>\n".
" <div class=\"row\">\n" .
" <div class=\"apptext\">\n" .
" <p>Dobrý den!</p>\n".
" <p> </p>\n" .
" <p>Přihlásil jste se jako</p>\n".
" <p class=\"appgradient\">" . $_SESSION["usercn"] . "</p>\n".
" <p> </p>\n" .
" <p> </p>\n" .
" <p> </p>\n" .
" <p> </p>\n" .
" <p> </p>\n" .
" <p> </p>\n" .
" <p> </p>\n" .
" </div>\n" .
" </div>\n".
" <div class=\"row\">\n" .
" <p class=\"text-right\">\n" .
" <a href=\"" . AducidClient::currentURL() . "?action=logout\" class=\"btn loginbutton\">Odhlásit se<img src=\"app-login-arrow.png\"></a>\n" .
" </p>\n".
" </div>\n".
"</div>\n";
return $html;
}
function body() {
if( isset($_SESSION["username"]) ) {
return loggedInBody();
} else {
return loginBody();
}
}
/**
* hlavni kod aplikace
*/
aducidRequire(3.002);
$action = isset($_REQUEST["action"]) ? $_REQUEST["action"] : "";
session_name("euapp");
session_start();
$errormsg = "";
echo head();
error_log("action is\"" . $action ."\"");
switch($action) {
case "login":
$a = new AducidSessionClient($GLOBALS["aim"]);
$a->open(AducidSessionClient::currentURL() . "?action=check");
$a->invokePeig();
break;
case "check":
$a = new AducidSessionClient($GLOBALS["aim"]);
$a->setFromRequest();
if( $a->verify() ) {
error_log("aducid ok");
$db = new DDSDatabase();
$username = $db->getUsernameByUdi( $a->getUserDatabaseIndex() );
if( $username == "" ) {
error_log("username error");
$errormsg = "User unknown";
} else {
error_log("username \"" . $username . "\"");
$_SESSION["username"] = $username;
$_SESSION["usercn"] = $db->getCN($username);
}
} else {
// failed
error_log("aducid error");
$errormsg = "Autentication failed!";
}
break;
case "logout":
session_unset();
break;
}
if( $errormsg != "" ) {
echo popupMessageWithParams("failed.png","Error",$errormsg,"Close");
echo onLoadJs("popupModal");
}
echo body();
echo foot();
?>
|
thalman/dds
|
src/app.php
|
PHP
|
apache-2.0
| 9,514
|
# Hantzschia weiprechtii Grunow SPECIES
#### Status
ACCEPTED
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null
|
mdoering/backbone
|
life/Plantae/Bacillariophyta/Bacillariophyceae/Bacillariales/Bacillariaceae/Hantzschia/Hantzschia weiprechtii/README.md
|
Markdown
|
apache-2.0
| 187
|
# Kuromatea glabra (Thunb.) Kudô SPECIES
#### Status
SYNONYM
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null
|
mdoering/backbone
|
life/Plantae/Magnoliophyta/Magnoliopsida/Fagales/Fagaceae/Lithocarpus/Lithocarpus glaber/ Syn. Kuromatea glabra/README.md
|
Markdown
|
apache-2.0
| 188
|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.accumulo.core.file.blockfile.cache.lru;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicLong;
import java.util.function.Supplier;
import org.apache.accumulo.core.file.blockfile.cache.CacheEntry.Weighbable;
import org.apache.accumulo.core.file.blockfile.cache.impl.ClassSize;
import org.apache.accumulo.core.file.blockfile.cache.impl.SizeConstants;
/**
* Represents an entry in the configurable block cache.
*
* <p>
* Makes the block memory-aware with {@link HeapSize} and Comparable to sort by access time for the LRU. It also takes care of priority by either instantiating
* as in-memory or handling the transition from single to multiple access.
*/
public class CachedBlock implements HeapSize, Comparable<CachedBlock> {
public final static long PER_BLOCK_OVERHEAD = ClassSize.align(ClassSize.OBJECT + (3 * ClassSize.REFERENCE) + (2 * SizeConstants.SIZEOF_LONG)
+ ClassSize.STRING + ClassSize.BYTE_BUFFER + ClassSize.REFERENCE);
public static enum BlockPriority {
/**
* Accessed a single time (used for scan-resistance)
*/
SINGLE,
/**
* Accessed multiple times
*/
MULTI,
/**
* Block from in-memory store
*/
MEMORY
}
private byte[] buffer;
private final String blockName;
private volatile long accessTime;
private volatile long recordedSize;
private BlockPriority priority;
private Weighbable index;
public CachedBlock(String blockName, byte buf[], long accessTime, boolean inMemory) {
this.buffer = buf;
this.blockName = blockName;
this.accessTime = accessTime;
if (inMemory) {
this.priority = BlockPriority.MEMORY;
} else {
this.priority = BlockPriority.SINGLE;
}
}
/**
* Block has been accessed. Update its local access time.
*/
public void access(long accessTime) {
this.accessTime = accessTime;
if (this.priority == BlockPriority.SINGLE) {
this.priority = BlockPriority.MULTI;
}
}
@Override
public long heapSize() {
if (recordedSize < 0) {
throw new IllegalStateException("Block was evicted");
}
return recordedSize;
}
@Override
public int hashCode() {
return Objects.hashCode(accessTime);
}
@Override
public boolean equals(Object obj) {
return this == obj || (obj != null && obj instanceof CachedBlock && 0 == compareTo((CachedBlock) obj));
}
@Override
public int compareTo(CachedBlock that) {
if (this.accessTime == that.accessTime)
return 0;
return this.accessTime < that.accessTime ? 1 : -1;
}
public String getName() {
return this.blockName;
}
public BlockPriority getPriority() {
return this.priority;
}
public byte[] getBuffer() {
return buffer;
}
@SuppressWarnings("unchecked")
public synchronized <T extends Weighbable> T getIndex(Supplier<T> supplier) {
if (index == null && recordedSize >= 0) {
index = supplier.get();
}
return (T) index;
}
public synchronized long recordSize(AtomicLong totalSize) {
if (recordedSize >= 0) {
long indexSize = (index == null) ? 0 : index.weight();
long newSize = ClassSize.align(blockName.length()) + ClassSize.align(buffer.length) + PER_BLOCK_OVERHEAD + indexSize;
long delta = newSize - recordedSize;
recordedSize = newSize;
return totalSize.addAndGet(delta);
}
throw new IllegalStateException("Block was evicted");
}
public synchronized long evicted(AtomicLong totalSize) {
if (recordedSize >= 0) {
totalSize.addAndGet(recordedSize * -1);
long tmp = recordedSize;
recordedSize = -1;
index = null;
return tmp;
}
throw new IllegalStateException("already evicted");
}
}
|
mikewalch/accumulo
|
core/src/main/java/org/apache/accumulo/core/file/blockfile/cache/lru/CachedBlock.java
|
Java
|
apache-2.0
| 4,543
|
/*
* Copyright 2017-2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
package com.amazonaws.services.costexplorer.model.transform;
import javax.annotation.Generated;
import com.amazonaws.SdkClientException;
import com.amazonaws.services.costexplorer.model.*;
import com.amazonaws.protocol.*;
import com.amazonaws.annotation.SdkInternalApi;
/**
* SavingsPlansPurchaseRecommendationMetadataMarshaller
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
@SdkInternalApi
public class SavingsPlansPurchaseRecommendationMetadataMarshaller {
private static final MarshallingInfo<String> RECOMMENDATIONID_BINDING = MarshallingInfo.builder(MarshallingType.STRING)
.marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("RecommendationId").build();
private static final MarshallingInfo<String> GENERATIONTIMESTAMP_BINDING = MarshallingInfo.builder(MarshallingType.STRING)
.marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("GenerationTimestamp").build();
private static final MarshallingInfo<String> ADDITIONALMETADATA_BINDING = MarshallingInfo.builder(MarshallingType.STRING)
.marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("AdditionalMetadata").build();
private static final SavingsPlansPurchaseRecommendationMetadataMarshaller instance = new SavingsPlansPurchaseRecommendationMetadataMarshaller();
public static SavingsPlansPurchaseRecommendationMetadataMarshaller getInstance() {
return instance;
}
/**
* Marshall the given parameter object.
*/
public void marshall(SavingsPlansPurchaseRecommendationMetadata savingsPlansPurchaseRecommendationMetadata, ProtocolMarshaller protocolMarshaller) {
if (savingsPlansPurchaseRecommendationMetadata == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(savingsPlansPurchaseRecommendationMetadata.getRecommendationId(), RECOMMENDATIONID_BINDING);
protocolMarshaller.marshall(savingsPlansPurchaseRecommendationMetadata.getGenerationTimestamp(), GENERATIONTIMESTAMP_BINDING);
protocolMarshaller.marshall(savingsPlansPurchaseRecommendationMetadata.getAdditionalMetadata(), ADDITIONALMETADATA_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
}
}
|
aws/aws-sdk-java
|
aws-java-sdk-costexplorer/src/main/java/com/amazonaws/services/costexplorer/model/transform/SavingsPlansPurchaseRecommendationMetadataMarshaller.java
|
Java
|
apache-2.0
| 2,983
|
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>列表</title>
<meta name="generator" content="Org mode" />
<meta name="author" content="Wu, Shanliang" />
<style type="text/css">
<!--/*--><![CDATA[/*><!--*/
.title { text-align: center;
margin-bottom: .2em; }
.subtitle { text-align: center;
font-size: medium;
font-weight: bold;
margin-top:0; }
.todo { font-family: monospace; color: red; }
.done { font-family: monospace; color: green; }
.priority { font-family: monospace; color: orange; }
.tag { background-color: #eee; font-family: monospace;
padding: 2px; font-size: 80%; font-weight: normal; }
.timestamp { color: #bebebe; }
.timestamp-kwd { color: #5f9ea0; }
.org-right { margin-left: auto; margin-right: 0px; text-align: right; }
.org-left { margin-left: 0px; margin-right: auto; text-align: left; }
.org-center { margin-left: auto; margin-right: auto; text-align: center; }
.underline { text-decoration: underline; }
#postamble p, #preamble p { font-size: 90%; margin: .2em; }
p.verse { margin-left: 3%; }
pre {
border: 1px solid #ccc;
box-shadow: 3px 3px 3px #eee;
padding: 8pt;
font-family: monospace;
overflow: auto;
margin: 1.2em;
}
pre.src {
position: relative;
overflow: visible;
padding-top: 1.2em;
}
pre.src:before {
display: none;
position: absolute;
background-color: white;
top: -10px;
right: 10px;
padding: 3px;
border: 1px solid black;
}
pre.src:hover:before { display: inline;}
/* Languages per Org manual */
pre.src-asymptote:before { content: 'Asymptote'; }
pre.src-awk:before { content: 'Awk'; }
pre.src-C:before { content: 'C'; }
/* pre.src-C++ doesn't work in CSS */
pre.src-clojure:before { content: 'Clojure'; }
pre.src-css:before { content: 'CSS'; }
pre.src-D:before { content: 'D'; }
pre.src-ditaa:before { content: 'ditaa'; }
pre.src-dot:before { content: 'Graphviz'; }
pre.src-calc:before { content: 'Emacs Calc'; }
pre.src-emacs-lisp:before { content: 'Emacs Lisp'; }
pre.src-fortran:before { content: 'Fortran'; }
pre.src-gnuplot:before { content: 'gnuplot'; }
pre.src-haskell:before { content: 'Haskell'; }
pre.src-hledger:before { content: 'hledger'; }
pre.src-java:before { content: 'Java'; }
pre.src-js:before { content: 'Javascript'; }
pre.src-latex:before { content: 'LaTeX'; }
pre.src-ledger:before { content: 'Ledger'; }
pre.src-lisp:before { content: 'Lisp'; }
pre.src-lilypond:before { content: 'Lilypond'; }
pre.src-lua:before { content: 'Lua'; }
pre.src-matlab:before { content: 'MATLAB'; }
pre.src-mscgen:before { content: 'Mscgen'; }
pre.src-ocaml:before { content: 'Objective Caml'; }
pre.src-octave:before { content: 'Octave'; }
pre.src-org:before { content: 'Org mode'; }
pre.src-oz:before { content: 'OZ'; }
pre.src-plantuml:before { content: 'Plantuml'; }
pre.src-processing:before { content: 'Processing.js'; }
pre.src-python:before { content: 'Python'; }
pre.src-R:before { content: 'R'; }
pre.src-ruby:before { content: 'Ruby'; }
pre.src-sass:before { content: 'Sass'; }
pre.src-scheme:before { content: 'Scheme'; }
pre.src-screen:before { content: 'Gnu Screen'; }
pre.src-sed:before { content: 'Sed'; }
pre.src-sh:before { content: 'shell'; }
pre.src-sql:before { content: 'SQL'; }
pre.src-sqlite:before { content: 'SQLite'; }
/* additional languages in org.el's org-babel-load-languages alist */
pre.src-forth:before { content: 'Forth'; }
pre.src-io:before { content: 'IO'; }
pre.src-J:before { content: 'J'; }
pre.src-makefile:before { content: 'Makefile'; }
pre.src-maxima:before { content: 'Maxima'; }
pre.src-perl:before { content: 'Perl'; }
pre.src-picolisp:before { content: 'Pico Lisp'; }
pre.src-scala:before { content: 'Scala'; }
pre.src-shell:before { content: 'Shell Script'; }
pre.src-ebnf2ps:before { content: 'ebfn2ps'; }
/* additional language identifiers per "defun org-babel-execute"
in ob-*.el */
pre.src-cpp:before { content: 'C++'; }
pre.src-abc:before { content: 'ABC'; }
pre.src-coq:before { content: 'Coq'; }
pre.src-groovy:before { content: 'Groovy'; }
/* additional language identifiers from org-babel-shell-names in
ob-shell.el: ob-shell is the only babel language using a lambda to put
the execution function name together. */
pre.src-bash:before { content: 'bash'; }
pre.src-csh:before { content: 'csh'; }
pre.src-ash:before { content: 'ash'; }
pre.src-dash:before { content: 'dash'; }
pre.src-ksh:before { content: 'ksh'; }
pre.src-mksh:before { content: 'mksh'; }
pre.src-posh:before { content: 'posh'; }
/* Additional Emacs modes also supported by the LaTeX listings package */
pre.src-ada:before { content: 'Ada'; }
pre.src-asm:before { content: 'Assembler'; }
pre.src-caml:before { content: 'Caml'; }
pre.src-delphi:before { content: 'Delphi'; }
pre.src-html:before { content: 'HTML'; }
pre.src-idl:before { content: 'IDL'; }
pre.src-mercury:before { content: 'Mercury'; }
pre.src-metapost:before { content: 'MetaPost'; }
pre.src-modula-2:before { content: 'Modula-2'; }
pre.src-pascal:before { content: 'Pascal'; }
pre.src-ps:before { content: 'PostScript'; }
pre.src-prolog:before { content: 'Prolog'; }
pre.src-simula:before { content: 'Simula'; }
pre.src-tcl:before { content: 'tcl'; }
pre.src-tex:before { content: 'TeX'; }
pre.src-plain-tex:before { content: 'Plain TeX'; }
pre.src-verilog:before { content: 'Verilog'; }
pre.src-vhdl:before { content: 'VHDL'; }
pre.src-xml:before { content: 'XML'; }
pre.src-nxml:before { content: 'XML'; }
/* add a generic configuration mode; LaTeX export needs an additional
(add-to-list 'org-latex-listings-langs '(conf " ")) in .emacs */
pre.src-conf:before { content: 'Configuration File'; }
table { border-collapse:collapse; }
caption.t-above { caption-side: top; }
caption.t-bottom { caption-side: bottom; }
td, th { vertical-align:top; }
th.org-right { text-align: center; }
th.org-left { text-align: center; }
th.org-center { text-align: center; }
td.org-right { text-align: right; }
td.org-left { text-align: left; }
td.org-center { text-align: center; }
dt { font-weight: bold; }
.footpara { display: inline; }
.footdef { margin-bottom: 1em; }
.figure { padding: 1em; }
.figure p { text-align: center; }
.equation-container {
display: table;
text-align: center;
width: 100%;
}
.equation {
vertical-align: middle;
}
.equation-label {
display: table-cell;
text-align: right;
vertical-align: middle;
}
.inlinetask {
padding: 10px;
border: 2px solid gray;
margin: 10px;
background: #ffffcc;
}
#org-div-home-and-up
{ text-align: right; font-size: 70%; white-space: nowrap; }
textarea { overflow-x: auto; }
.linenr { font-size: smaller }
.code-highlighted { background-color: #ffff00; }
.org-info-js_info-navigation { border-style: none; }
#org-info-js_console-label
{ font-size: 10px; font-weight: bold; white-space: nowrap; }
.org-info-js_search-highlight
{ background-color: #ffff00; color: #000000; font-weight: bold; }
.org-svg { width: 90%; }
/*]]>*/-->
</style>
<link rel="stylesheet" type="text/css" href="../css/main.css" />
<script type="text/javascript">
/*
@licstart The following is the entire license notice for the
JavaScript code in this tag.
Copyright (C) 2012-2020 Free Software Foundation, Inc.
The JavaScript code in this tag is free software: you can
redistribute it and/or modify it under the terms of the GNU
General Public License (GNU GPL) as published by the Free Software
Foundation, either version 3 of the License, or (at your option)
any later version. The code is distributed WITHOUT ANY WARRANTY;
without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the GNU GPL for more details.
As additional permission under GNU GPL version 3 section 7, you
may distribute non-source (e.g., minimized or compacted) forms of
that code without the copy of the GNU GPL normally required by
section 4, provided you include this license notice and a URL
through which recipients can access the Corresponding Source.
@licend The above is the entire license notice
for the JavaScript code in this tag.
*/
<!--/*--><![CDATA[/*><!--*/
function CodeHighlightOn(elem, id)
{
var target = document.getElementById(id);
if(null != target) {
elem.cacheClassElem = elem.className;
elem.cacheClassTarget = target.className;
target.className = "code-highlighted";
elem.className = "code-highlighted";
}
}
function CodeHighlightOff(elem, id)
{
var target = document.getElementById(id);
if(elem.cacheClassElem)
elem.className = elem.cacheClassElem;
if(elem.cacheClassTarget)
target.className = elem.cacheClassTarget;
}
/*]]>*///-->
</script>
</head>
<body>
<div id="org-div-home-and-up">
<a accesskey="h" href="atom.html"> UP </a>
|
<a accesskey="H" href="sequential.html"> HOME </a>
</div><div id="content">
<h1 class="title">列表</h1>
<div id="table-of-contents">
<h2>Table of Contents</h2>
<div id="text-table-of-contents">
<ul>
<li><a href="#org7b2acad">计算列表长度</a></li>
</ul>
</div>
</div>
<pre class="example">
虽然元组可以将数据组成一组,但是也需要表示数据列表
</pre>
<p>
Erlang 中的列表由 <span class="underline">方括号</span> 括起来表示。例如,世界上不同城市的温度列表就可以表示为:
</p>
<div class="org-src-container">
<pre class="src src-erlang">[{moscow, {c, -10}}, {cape_town, {f, 70}}, {stockholm, {c, -4}},
{paris, {f, 28}}, {london, {f, 36}}]
</pre>
</div>
<p>
请注意:这个列表太长而没有放在一行中,但是这并没有什么关系
</p>
<pre class="example">
Erlang 允许在 “合理的地方” 换行,但是并不允许在一些 “不合理的方”,比如原子类型、整数、或者其它数据类型的中间
</pre>
<p>
可以使用 <span class="underline">|</span> 查看部分列表:
</p>
<div class="org-src-container">
<pre class="src src-sh">11> [First |TheRest] = [1,2,3,4,5].
[First |TheRest] = [1,2,3,4,5].
[1,2,3,4,5]
12> First .
First .
1
13> TheRest .
TheRest .
[2,3,4,5]
</pre>
</div>
<p>
这里用 | 将列表中的第一个元素与列表中其它元素分离开
</p>
<pre class="example">
First 值为 1,TheRest 的值为 [2,3,4,5]
</pre>
<div class="org-src-container">
<pre class="src src-sh">20> [E1, E2 | R] = [1,2,3,4,5,6,7].
[1,2,3,4,5,6,7]
21> E1.
1
22> E2.
2
23> R.
[3,4,5,6,7]
</pre>
</div>
<pre class="example">
这个例子中,用 | 取得了列表中的前两个元素
</pre>
<p>
如果要 <b>取得的元素的数量超过了列表中元素的总数</b> ,将 <span class="underline">返回错误</span> 。请注意列表中特殊情况, <b>空列表</b> (没有元素),即 <span class="underline">[]</span> :
</p>
<div class="org-src-container">
<pre class="src src-sh">24> [A, B | C] = [1, 2].
[1,2]
25> A.
1
26> B.
2
27> C.
[]
</pre>
</div>
<pre class="example">
在前面的例子中,用的是新的变量名而没有重复使用已有的变量名: First,TheRest,E1,R,A,B 或者 C
这是因为:在同一上下文环境下一个变量只能被赋值一次
</pre>
<div id="outline-container-org7b2acad" class="outline-2">
<h2 id="org7b2acad">计算列表长度</h2>
<div class="outline-text-2" id="text-org7b2acad">
<p>
下面的例子中演示了如何获得一个列表的长度:
</p>
<div class="org-src-container">
<pre class="src src-erlang"><span style="color: #ffd700;">-module</span>(list).
<span style="color: #ffd700;">-export</span>([<span style="color: #98f5ff;">list_length/1</span>]).
<span style="color: #daa520; font-weight: bold;">list_length</span>([]) ->
0;
<span style="color: #daa520; font-weight: bold;">list_length</span>([<span style="color: #4eee94;">First</span> | <span style="color: #4eee94;">Rest</span>]) ->
1 + <span style="color: #98f5ff;">list_length</span>(<span style="color: #4eee94;">Rest</span>).
</pre>
</div>
<p>
测试:
</p>
<div class="org-src-container">
<pre class="src src-sh">15> list:list_length([1,2,3,4,5,6,7])<span style="color: #f08080;">.</span>
list:list_length([1,2,3,4,5,6,7])<span style="color: #f08080;">.</span>
</pre>
</div>
<p>
代码含义如下:
</p>
<div class="org-src-container">
<pre class="src src-erlang"><span style="color: #daa520; font-weight: bold;">list_length</span>([]) ->
0;
</pre>
</div>
<p>
空列表的长度显然为 0
</p>
<div class="org-src-container">
<pre class="src src-erlang"><span style="color: #daa520; font-weight: bold;">list_length</span>([<span style="color: #4eee94;">First</span> | <span style="color: #4eee94;">Rest</span>]) ->
1 + <span style="color: #98f5ff;">list_length</span>(<span style="color: #4eee94;">Rest</span>).
</pre>
</div>
<p>
一个列表中包含第一个元素 First 与剩余元素列表 Rest, 所以列表长度为 Rest 列表的长度加上 1
</p>
<pre class="example">
这并不是尾递归,还有更好地实现该函数的方法
</pre>
<p>
一般地,Erlang 中元组类型承担其它语言中记录或者结构体类型的功能。列表是一个可变长容器,与其它语言中的链表功能相同
</p>
<pre class="example">
Erlang 中没有字符串类型。因为,在 Erlang 中字符串可以用 Unicode 字符的列表表示
这也隐含地说明了列表 [97,98,99] 等价于字符串 “abc”
</pre>
<p>
<a href="map.html">Next:映射</a>
</p>
<p>
<a href="atom.html">Previous:原子类型</a>
</p>
<p>
<a href="sequential.html">Home:顺序编程</a>
</p>
</div>
</div>
</div>
<div id="postamble" class="status">
<br/>
<div class='ds-thread'></div>
<script>
var duoshuoQuery = {short_name:'klose911'};
(function() {
var dsThread = document.getElementsByClassName('ds-thread')[0];
dsThread.setAttribute('data-thread-key', document.title);
dsThread.setAttribute('data-title', document.title);
dsThread.setAttribute('data-url', window.location.href);
var ds = document.createElement('script');
ds.type = 'text/javascript';ds.async = true;
ds.src = (document.location.protocol == 'https:' ? 'https:' : 'http:') + '//static.duoshuo.com/embed.js';
ds.charset = 'UTF-8';
(document.getElementsByTagName('head')[0]
|| document.getElementsByTagName('body')[0]).appendChild(ds);
})();
</script>
<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','https://www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-90850421-1', 'auto');
ga('send', 'pageview');
</script>
</div>
</body>
</html>
|
klose911/klose911.github.io
|
html/erlang/tutorial/sequential/list.html
|
HTML
|
apache-2.0
| 15,489
|
/*******************************************************************************
* Copyright (c) 2015 www.DockerFoundry.cn
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Apache License,
* Version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Contributors:
* Xi Ning Wang
********************************************************************************/
package cn.dockerfoundry.ide.eclipse.explorer.ui.preferences;
/**
* Constant definitions for plug-in preferences
*/
public class PreferenceConstants {
public static final String P_SERVERADDRESS = "ServerAddress";
public static final String P_USERNAME = "Username";
public static final String P_PASSWORD = "Password";
public static final String P_EMAIL = "Email";
}
|
osswangxining/dockerfoundry
|
cn.dockerfoundry.ide.eclipse.explorer.ui/src/cn/dockerfoundry/ide/eclipse/explorer/ui/preferences/PreferenceConstants.java
|
Java
|
apache-2.0
| 1,277
|
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// This file is autogenerated by
// incubator-weex/weex_core/Source/android/jniprebuild/jni_generator.py
// For
// com/taobao/weex/bridge/WXParams
#ifndef com_taobao_weex_bridge_WXParams_JNI
#define com_taobao_weex_bridge_WXParams_JNI
#include <jni.h>
#include "base/android/jni/android_jni.h"
//#include "base/android/jni_int_wrapper.h"
// Step 1: forward declarations.
namespace {
const char kWXParamsClassPath[] = "com/taobao/weex/bridge/WXParams";
// Leaking this jclass as we cannot use LazyInstance from some threads.
jclass g_WXParams_clazz = NULL;
#define WXParams_clazz(env) g_WXParams_clazz
} // namespace
// Step 2: method stubs.
static intptr_t g_WXParams_getOptions = 0;
static base::android::ScopedLocalJavaRef<jobject>
Java_WXParams_getOptions(JNIEnv* env, jobject obj) {
/* Must call RegisterNativesImpl() */
//CHECK_CLAZZ(env, obj,
// WXParams_clazz(env), NULL);
jmethodID method_id =
base::android::GetMethod(
env, WXParams_clazz(env),
base::android::INSTANCE_METHOD,
"getOptions",
"("
")"
"Ljava/lang/Object;",
&g_WXParams_getOptions);
jobject ret =
env->CallObjectMethod(obj,
method_id);
base::android::CheckException(env);
return base::android::ScopedLocalJavaRef<jobject>(env, ret);
}
static intptr_t g_WXParams_getPlatform = 0;
static base::android::ScopedLocalJavaRef<jstring>
Java_WXParams_getPlatform(JNIEnv* env, jobject obj) {
/* Must call RegisterNativesImpl() */
//CHECK_CLAZZ(env, obj,
// WXParams_clazz(env), NULL);
jmethodID method_id =
base::android::GetMethod(
env, WXParams_clazz(env),
base::android::INSTANCE_METHOD,
"getPlatform",
"("
")"
"Ljava/lang/String;",
&g_WXParams_getPlatform);
jstring ret =
static_cast<jstring>(env->CallObjectMethod(obj,
method_id));
base::android::CheckException(env);
return base::android::ScopedLocalJavaRef<jstring>(env, ret);
}
static intptr_t g_WXParams_getCacheDir = 0;
static base::android::ScopedLocalJavaRef<jstring>
Java_WXParams_getCacheDir(JNIEnv* env, jobject obj) {
/* Must call RegisterNativesImpl() */
//CHECK_CLAZZ(env, obj,
// WXParams_clazz(env), NULL);
jmethodID method_id =
base::android::GetMethod(
env, WXParams_clazz(env),
base::android::INSTANCE_METHOD,
"getCacheDir",
"("
")"
"Ljava/lang/String;",
&g_WXParams_getCacheDir);
jstring ret =
static_cast<jstring>(env->CallObjectMethod(obj,
method_id));
base::android::CheckException(env);
return base::android::ScopedLocalJavaRef<jstring>(env, ret);
}
static intptr_t g_WXParams_getOsVersion = 0;
static base::android::ScopedLocalJavaRef<jstring>
Java_WXParams_getOsVersion(JNIEnv* env, jobject obj) {
/* Must call RegisterNativesImpl() */
//CHECK_CLAZZ(env, obj,
// WXParams_clazz(env), NULL);
jmethodID method_id =
base::android::GetMethod(
env, WXParams_clazz(env),
base::android::INSTANCE_METHOD,
"getOsVersion",
"("
")"
"Ljava/lang/String;",
&g_WXParams_getOsVersion);
jstring ret =
static_cast<jstring>(env->CallObjectMethod(obj,
method_id));
base::android::CheckException(env);
return base::android::ScopedLocalJavaRef<jstring>(env, ret);
}
static intptr_t g_WXParams_getAppVersion = 0;
static base::android::ScopedLocalJavaRef<jstring>
Java_WXParams_getAppVersion(JNIEnv* env, jobject obj) {
/* Must call RegisterNativesImpl() */
//CHECK_CLAZZ(env, obj,
// WXParams_clazz(env), NULL);
jmethodID method_id =
base::android::GetMethod(
env, WXParams_clazz(env),
base::android::INSTANCE_METHOD,
"getAppVersion",
"("
")"
"Ljava/lang/String;",
&g_WXParams_getAppVersion);
jstring ret =
static_cast<jstring>(env->CallObjectMethod(obj,
method_id));
base::android::CheckException(env);
return base::android::ScopedLocalJavaRef<jstring>(env, ret);
}
static intptr_t g_WXParams_getWeexVersion = 0;
static base::android::ScopedLocalJavaRef<jstring>
Java_WXParams_getWeexVersion(JNIEnv* env, jobject obj) {
/* Must call RegisterNativesImpl() */
//CHECK_CLAZZ(env, obj,
// WXParams_clazz(env), NULL);
jmethodID method_id =
base::android::GetMethod(
env, WXParams_clazz(env),
base::android::INSTANCE_METHOD,
"getWeexVersion",
"("
")"
"Ljava/lang/String;",
&g_WXParams_getWeexVersion);
jstring ret =
static_cast<jstring>(env->CallObjectMethod(obj,
method_id));
base::android::CheckException(env);
return base::android::ScopedLocalJavaRef<jstring>(env, ret);
}
static intptr_t g_WXParams_getDeviceModel = 0;
static base::android::ScopedLocalJavaRef<jstring>
Java_WXParams_getDeviceModel(JNIEnv* env, jobject obj) {
/* Must call RegisterNativesImpl() */
//CHECK_CLAZZ(env, obj,
// WXParams_clazz(env), NULL);
jmethodID method_id =
base::android::GetMethod(
env, WXParams_clazz(env),
base::android::INSTANCE_METHOD,
"getDeviceModel",
"("
")"
"Ljava/lang/String;",
&g_WXParams_getDeviceModel);
jstring ret =
static_cast<jstring>(env->CallObjectMethod(obj,
method_id));
base::android::CheckException(env);
return base::android::ScopedLocalJavaRef<jstring>(env, ret);
}
static intptr_t g_WXParams_getAppName = 0;
static base::android::ScopedLocalJavaRef<jstring>
Java_WXParams_getAppName(JNIEnv* env, jobject obj) {
/* Must call RegisterNativesImpl() */
//CHECK_CLAZZ(env, obj,
// WXParams_clazz(env), NULL);
jmethodID method_id =
base::android::GetMethod(
env, WXParams_clazz(env),
base::android::INSTANCE_METHOD,
"getAppName",
"("
")"
"Ljava/lang/String;",
&g_WXParams_getAppName);
jstring ret =
static_cast<jstring>(env->CallObjectMethod(obj,
method_id));
base::android::CheckException(env);
return base::android::ScopedLocalJavaRef<jstring>(env, ret);
}
static intptr_t g_WXParams_getDeviceWidth = 0;
static base::android::ScopedLocalJavaRef<jstring>
Java_WXParams_getDeviceWidth(JNIEnv* env, jobject obj) {
/* Must call RegisterNativesImpl() */
//CHECK_CLAZZ(env, obj,
// WXParams_clazz(env), NULL);
jmethodID method_id =
base::android::GetMethod(
env, WXParams_clazz(env),
base::android::INSTANCE_METHOD,
"getDeviceWidth",
"("
")"
"Ljava/lang/String;",
&g_WXParams_getDeviceWidth);
jstring ret =
static_cast<jstring>(env->CallObjectMethod(obj,
method_id));
base::android::CheckException(env);
return base::android::ScopedLocalJavaRef<jstring>(env, ret);
}
static intptr_t g_WXParams_getDeviceHeight = 0;
static base::android::ScopedLocalJavaRef<jstring>
Java_WXParams_getDeviceHeight(JNIEnv* env, jobject obj) {
/* Must call RegisterNativesImpl() */
//CHECK_CLAZZ(env, obj,
// WXParams_clazz(env), NULL);
jmethodID method_id =
base::android::GetMethod(
env, WXParams_clazz(env),
base::android::INSTANCE_METHOD,
"getDeviceHeight",
"("
")"
"Ljava/lang/String;",
&g_WXParams_getDeviceHeight);
jstring ret =
static_cast<jstring>(env->CallObjectMethod(obj,
method_id));
base::android::CheckException(env);
return base::android::ScopedLocalJavaRef<jstring>(env, ret);
}
static intptr_t g_WXParams_getUseSingleProcess = 0;
static base::android::ScopedLocalJavaRef<jstring>
Java_WXParams_getUseSingleProcess(JNIEnv* env, jobject obj) {
/* Must call RegisterNativesImpl() */
//CHECK_CLAZZ(env, obj,
// WXParams_clazz(env), NULL);
jmethodID method_id =
base::android::GetMethod(
env, WXParams_clazz(env),
base::android::INSTANCE_METHOD,
"getUseSingleProcess",
"("
")"
"Ljava/lang/String;",
&g_WXParams_getUseSingleProcess);
jstring ret =
static_cast<jstring>(env->CallObjectMethod(obj,
method_id));
base::android::CheckException(env);
return base::android::ScopedLocalJavaRef<jstring>(env, ret);
}
static intptr_t g_WXParams_getLibJssPath = 0;
static base::android::ScopedLocalJavaRef<jstring>
Java_WXParams_getLibJssPath(JNIEnv* env, jobject obj) {
/* Must call RegisterNativesImpl() */
//CHECK_CLAZZ(env, obj,
// WXParams_clazz(env), NULL);
jmethodID method_id =
base::android::GetMethod(
env, WXParams_clazz(env),
base::android::INSTANCE_METHOD,
"getLibJssPath",
"("
")"
"Ljava/lang/String;",
&g_WXParams_getLibJssPath);
jstring ret =
static_cast<jstring>(env->CallObjectMethod(obj,
method_id));
base::android::CheckException(env);
return base::android::ScopedLocalJavaRef<jstring>(env, ret);
}
static intptr_t g_WXParams_getLibIcuPath = 0;
static base::android::ScopedLocalJavaRef<jstring>
Java_WXParams_getLibIcuPath(JNIEnv* env, jobject obj) {
/* Must call RegisterNativesImpl() */
//CHECK_CLAZZ(env, obj,
// WXParams_clazz(env), NULL);
jmethodID method_id =
base::android::GetMethod(
env, WXParams_clazz(env),
base::android::INSTANCE_METHOD,
"getLibIcuPath",
"("
")"
"Ljava/lang/String;",
&g_WXParams_getLibIcuPath);
jstring ret =
static_cast<jstring>(env->CallObjectMethod(obj,
method_id));
base::android::CheckException(env);
return base::android::ScopedLocalJavaRef<jstring>(env, ret);
}
// Step 3: RegisterNatives.
static bool RegisterNativesImpl(JNIEnv* env) {
g_WXParams_clazz = reinterpret_cast<jclass>(env->NewGlobalRef(
base::android::GetClass(env, kWXParamsClassPath).Get()));
return true;
}
#endif // com_taobao_weex_bridge_WXParams_JNI
|
acton393/incubator-weex
|
weex_core/Source/base/android/jniprebuild/jniheader/WXParams_jni.h
|
C
|
apache-2.0
| 10,605
|
var config = {
defaultPort: process.env.WEB_PORT || 3000,
defaultLogLength: process.env.LOGLENGTH || 64,
defaultLogLines: process.env.LOGLINES || 10,
defaultSpacer: process.env.SPACER || ' | ',
defaultIdentifier: process.env.IDENTIFIER || '',
defaultLineCount: process.env.LINECOUNT || 1,
defaultLineDated: process.env.LINEDATED || 0,
defaultRepeatDelay: process.env.REPEATDELAY || 2
};
module.exports = config;
|
bryanlatten/docker-log-gen
|
lib/config.js
|
JavaScript
|
apache-2.0
| 430
|
//
// HotKey.h
//
// Created by chao on 7/12/16.
// Copyright © 2016 eschao. All rights reserved.
//
#import <Cocoa/Cocoa.h>
#import <Carbon/Carbon.h>
@interface HotKey : NSObject
@property (readonly) NSUInteger keyCode;
@property (readonly) NSUInteger keyMod;
@property (readonly) BOOL enabled;
- (instancetype)initWithKeyCode:(NSUInteger)keyCode
keyMod:(NSUInteger)keyMod
target:(id)target
action:(SEL)action;
- (instancetype)initWithHotKey:(NSString *)hotKey
target:(id)target
action:(SEL)action;
- (NSNumber *)getID;
- (BOOL)register;
- (BOOL)registerWith:(NSString *)hotKey;
- (BOOL)registerWith:(NSUInteger)keyCode
keyMod:(NSUInteger)keyMod;
- (BOOL)unregister;
- (BOOL)canRestoreWithDefaultHotKey;
- (BOOL)enable:(NSString *)hotKey;
- (BOOL)disable;
- (void)perform;
- (NSString *)hotKey2String;
+ (NSNumber *)getID:(NSUInteger)keyCode
keyMod:(NSUInteger)keyMod;
+ (NSString *)hotKey2String:(NSUInteger)keyCode
keyMod:(NSUInteger)keyMod;
@end
|
eschao/MyHotKey
|
src/MyHotKey/HotKey/HotKey.h
|
C
|
apache-2.0
| 1,130
|
# Porolithon castellum Dawson SPECIES
#### Status
ACCEPTED
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null
|
mdoering/backbone
|
life/Plantae/Rhodophyta/Florideophyceae/Corallinales/Corallinaceae/Porolithon/Porolithon castellum/README.md
|
Markdown
|
apache-2.0
| 185
|
<!DOCTYPE html>
<html>
<head>
<title>BÖLGELER</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="jquery.mobile-1.4.5.min.css" />
<script src="jquery-1.11.1.min.js"></script>
<script src="jquery.mobile-1.4.5.min.js"></script>
</head>
<body>
<div data-role="page" id="testpage">
<div data-role="header">
<h1>doğu anadolu bölgesi
</h1>
<a href="index.html" data-rel="back" class="ui-btn ui-corner-all ui-shadow ui-icon-back ui-btn-icon-left ui-btn-icon-notext">Geri</a>
</div><!-- /header -->
<div class="ui-content" role="main">
<center><img src="doguanadolu.jpg" width="50%"></center>
<ol>
<li><em>konum</em>.Türkiye'nin Doğusunda yer alır.</li>
<li><em>iklim</em>: Kışları soğuk ve karlı, yazları ise sıcak ve kuraktır. </li>
<li><em>bölgede yetiştirilen ürünler</em>:arpa,buğday,tütün,pamuk</li>
</ol>
</div>
<div data-role="footer">
<h4>doğu anadolu bölgesi</h4>
</div><!-- /footer -->
</div>
</body>
</html>
|
meltemdablan/meltemdablan01
|
doguanadolu.html
|
HTML
|
apache-2.0
| 1,154
|
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html lang="en">
<head>
<title>Source code</title>
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">
</head>
<body>
<div class="sourceContainer">
<pre><span class="sourceLineNo">001</span>package io.ebean.meta;<a name="line.1"></a>
<span class="sourceLineNo">002</span><a name="line.2"></a>
<span class="sourceLineNo">003</span>/**<a name="line.3"></a>
<span class="sourceLineNo">004</span> * Query execution metrics.<a name="line.4"></a>
<span class="sourceLineNo">005</span> */<a name="line.5"></a>
<span class="sourceLineNo">006</span>public interface MetaQueryMetric extends MetaTimedMetric {<a name="line.6"></a>
<span class="sourceLineNo">007</span><a name="line.7"></a>
<span class="sourceLineNo">008</span> /**<a name="line.8"></a>
<span class="sourceLineNo">009</span> * The type of entity or DTO bean.<a name="line.9"></a>
<span class="sourceLineNo">010</span> */<a name="line.10"></a>
<span class="sourceLineNo">011</span> Class<?> getType();<a name="line.11"></a>
<span class="sourceLineNo">012</span><a name="line.12"></a>
<span class="sourceLineNo">013</span> /**<a name="line.13"></a>
<span class="sourceLineNo">014</span> * The label for the query (can be null).<a name="line.14"></a>
<span class="sourceLineNo">015</span> */<a name="line.15"></a>
<span class="sourceLineNo">016</span> String getLabel();<a name="line.16"></a>
<span class="sourceLineNo">017</span><a name="line.17"></a>
<span class="sourceLineNo">018</span> /**<a name="line.18"></a>
<span class="sourceLineNo">019</span> * The actual SQL of the query.<a name="line.19"></a>
<span class="sourceLineNo">020</span> */<a name="line.20"></a>
<span class="sourceLineNo">021</span> String getSql();<a name="line.21"></a>
<span class="sourceLineNo">022</span><a name="line.22"></a>
<span class="sourceLineNo">023</span>}<a name="line.23"></a>
</pre>
</div>
</body>
</html>
|
ebean-orm/ebean-orm.github.io
|
apidoc/11/src-html/io/ebean/meta/MetaQueryMetric.html
|
HTML
|
apache-2.0
| 2,074
|
/**
*
*/
package com.spun.util.io;
public class StackElementLevelSelector implements StackElementSelector
{
private int ignoreLevels;
public StackElementLevelSelector(int ignoreLevels)
{
this.ignoreLevels = ignoreLevels;
}
public StackTraceElement selectElement(StackTraceElement[] trace)
{
return trace[ignoreLevels + 1];
}
@Override
public void increment()
{
ignoreLevels++;
}
}
|
approvals/ApprovalTests.Java
|
approvaltests-util/src/main/java/com/spun/util/io/StackElementLevelSelector.java
|
Java
|
apache-2.0
| 418
|
# The set of languages for which implicit dependencies are needed:
set(CMAKE_DEPENDS_LANGUAGES
"CXX"
)
# The set of files for implicit dependencies of each language:
set(CMAKE_DEPENDS_CHECK_CXX
"/home/xiaobai/Work/rust/qmlrs/ext/lib/api.cpp" "/home/xiaobai/Work/rust/qmlrs/ext/lib/build/CMakeFiles/librsqml.dir/api.cpp.o"
"/home/xiaobai/Work/rust/qmlrs/ext/lib/dynamicobject.cpp" "/home/xiaobai/Work/rust/qmlrs/ext/lib/build/CMakeFiles/librsqml.dir/dynamicobject.cpp.o"
"/home/xiaobai/Work/rust/qmlrs/ext/lib/engine.cpp" "/home/xiaobai/Work/rust/qmlrs/ext/lib/build/CMakeFiles/librsqml.dir/engine.cpp.o"
"/home/xiaobai/Work/rust/qmlrs/ext/lib/build/librsqml_automoc.cpp" "/home/xiaobai/Work/rust/qmlrs/ext/lib/build/CMakeFiles/librsqml.dir/librsqml_automoc.cpp.o"
)
set(CMAKE_CXX_COMPILER_ID "GNU")
# Preprocessor definitions for this target.
set(CMAKE_TARGET_DEFINITIONS
"QT_CORE_LIB"
"QT_GUI_LIB"
"QT_NETWORK_LIB"
"QT_NO_DEBUG"
"QT_QML_LIB"
"QT_QUICK_LIB"
)
# Targets to which this target links.
set(CMAKE_TARGET_LINKED_INFO_FILES
)
# The include file search paths:
set(CMAKE_C_TARGET_INCLUDE_PATH
"."
".."
"/usr/include/qt5"
"/usr/include/qt5/QtCore"
"/usr/lib64/qt5/mkspecs/linux-g++"
"/usr/include/qt5/QtQuick"
"/usr/include/qt5/QtQml"
"/usr/include/qt5/QtNetwork"
"/usr/include/qt5/QtGui"
)
set(CMAKE_CXX_TARGET_INCLUDE_PATH ${CMAKE_C_TARGET_INCLUDE_PATH})
set(CMAKE_Fortran_TARGET_INCLUDE_PATH ${CMAKE_C_TARGET_INCLUDE_PATH})
set(CMAKE_ASM_TARGET_INCLUDE_PATH ${CMAKE_C_TARGET_INCLUDE_PATH})
|
Jxspy/rust-qml
|
ext/lib/build/CMakeFiles/librsqml.dir/DependInfo.cmake
|
CMake
|
apache-2.0
| 1,552
|
///
/// Copyright (c) 2016 Dropbox, Inc. All rights reserved.
///
/// Auto-generated by Stone, do not modify.
///
#import <Foundation/Foundation.h>
#import "DBSerializableProtocol.h"
@class DBSHARINGJobError;
@class DBSHARINGJobStatus;
#pragma mark - API Object
///
/// The `JobStatus` union.
///
/// This class implements the `DBSerializable` protocol (serialize and
/// deserialize instance methods), which is required for all Obj-C SDK API route
/// objects.
///
@interface DBSHARINGJobStatus : NSObject <DBSerializable, NSCopying>
#pragma mark - Instance fields
/// The `DBSHARINGJobStatusTag` enum type represents the possible tag states
/// with which the `DBSHARINGJobStatus` union can exist.
typedef NS_ENUM(NSInteger, DBSHARINGJobStatusTag) {
/// The asynchronous job is still in progress.
DBSHARINGJobStatusInProgress,
/// The asynchronous job has finished.
DBSHARINGJobStatusComplete,
/// The asynchronous job returned an error.
DBSHARINGJobStatusFailed,
};
/// Represents the union's current tag state.
@property (nonatomic, readonly) DBSHARINGJobStatusTag tag;
/// The asynchronous job returned an error. @note Ensure the `isFailed` method
/// returns true before accessing, otherwise a runtime exception will be raised.
@property (nonatomic, readonly) DBSHARINGJobError * _Nonnull failed;
#pragma mark - Constructors
///
/// Initializes union class with tag state of "in_progress".
///
/// Description of the "in_progress" tag state: The asynchronous job is still in
/// progress.
///
/// @return An initialized instance.
///
- (nonnull instancetype)initWithInProgress;
///
/// Initializes union class with tag state of "complete".
///
/// Description of the "complete" tag state: The asynchronous job has finished.
///
/// @return An initialized instance.
///
- (nonnull instancetype)initWithComplete;
///
/// Initializes union class with tag state of "failed".
///
/// Description of the "failed" tag state: The asynchronous job returned an
/// error.
///
/// @param failed The asynchronous job returned an error.
///
/// @return An initialized instance.
///
- (nonnull instancetype)initWithFailed:(DBSHARINGJobError * _Nonnull)failed;
- (nonnull instancetype)init NS_UNAVAILABLE;
#pragma mark - Tag state methods
///
/// Retrieves whether the union's current tag state has value "in_progress".
///
/// @return Whether the union's current tag state has value "in_progress".
///
- (BOOL)isInProgress;
///
/// Retrieves whether the union's current tag state has value "complete".
///
/// @return Whether the union's current tag state has value "complete".
///
- (BOOL)isComplete;
///
/// Retrieves whether the union's current tag state has value "failed".
///
/// @note Call this method and ensure it returns true before accessing the
/// `failed` property, otherwise a runtime exception will be thrown.
///
/// @return Whether the union's current tag state has value "failed".
///
- (BOOL)isFailed;
///
/// Retrieves string value of union's current tag state.
///
/// @return A human-readable string representing the union's current tag state.
///
- (NSString * _Nonnull)tagName;
@end
#pragma mark - Serializer Object
///
/// The serialization class for the `DBSHARINGJobStatus` union.
///
@interface DBSHARINGJobStatusSerializer : NSObject
///
/// Serializes `DBSHARINGJobStatus` instances.
///
/// @param instance An instance of the `DBSHARINGJobStatus` API object.
///
/// @return A json-compatible dictionary representation of the
/// `DBSHARINGJobStatus` API object.
///
+ (NSDictionary * _Nonnull)serialize:(DBSHARINGJobStatus * _Nonnull)instance;
///
/// Deserializes `DBSHARINGJobStatus` instances.
///
/// @param dict A json-compatible dictionary representation of the
/// `DBSHARINGJobStatus` API object.
///
/// @return An instantiation of the `DBSHARINGJobStatus` object.
///
+ (DBSHARINGJobStatus * _Nonnull)deserialize:(NSDictionary * _Nonnull)dict;
@end
|
vntodorova/Notes
|
Notes/Pods/ObjectiveDropboxOfficial/Source/ObjectiveDropboxOfficial/Shared/Generated/ApiObjects/Sharing/Headers/DBSHARINGJobStatus.h
|
C
|
apache-2.0
| 3,924
|
# Copyright 2015 Palo Alto Networks, Inc
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from __future__ import absolute_import
import logging
import yaml
import netaddr
import os
import re
import collections
import itertools
import shutil
import gevent
import gevent.queue
import gevent.event
import pan.xapi
from . import base
from . import actorbase
from . import table
from .utils import utc_millisec
LOG = logging.getLogger(__name__)
SUBRE = re.compile("[^A-Za-z0-9_]")
class DevicePusher(gevent.Greenlet):
def __init__(self, device, prefix, watermark, attributes, persistent):
super(DevicePusher, self).__init__()
self.device = device
self.xapi = pan.xapi.PanXapi(
tag=self.device.get('tag', None),
api_username=self.device.get('api_username', None),
api_password=self.device.get('api_password', None),
api_key=self.device.get('api_key', None),
port=self.device.get('port', None),
hostname=self.device.get('hostname', None),
serial=self.device.get('serial', None)
)
self.prefix = prefix
self.attributes = attributes
self.watermark = watermark
self.persistent = persistent
self.q = gevent.queue.Queue()
def put(self, op, address, value):
LOG.debug('adding %s:%s to device queue', op, address)
self.q.put([op, address, value])
def _get_registered_ip_tags(self, ip):
self.xapi.op(
cmd='<show><object><registered-ip><ip>%s</ip></registered-ip></object></show>' % ip,
vsys=self.device.get('vsys', None),
cmd_xml=False
)
entries = self.xapi.element_root.findall('./result/entry')
if entries is None or len(entries) == 0:
LOG.warning('%s: ip %s has no tags', self.device.get('hostname', None), ip)
return None
tags = [member.text for member in entries[0].findall('./tag/member')
if member.text and member.text.startswith(self.prefix)]
return tags
def _get_all_registered_ips(self):
cmd = (
'<show><object><registered-ip><tag><entry name="%s%s"/></tag></registered-ip></object></show>' %
(self.prefix, self.watermark)
)
self.xapi.op(
cmd=cmd,
vsys=self.device.get('vsys', None),
cmd_xml=False
)
entries = self.xapi.element_root.findall('./result/entry')
if not entries:
return
for entry in entries:
ip = entry.get("ip")
yield ip, self._get_registered_ip_tags(ip)
def _dag_message(self, type_, addresses):
message = [
"<uid-message>",
"<version>1.0</version>",
"<type>update</type>",
"<payload>"
]
persistent = ''
if type_ == 'register':
persistent = ' persistent="%d"' % (1 if self.persistent else 0)
message.append('<%s>' % type_)
if addresses is not None and len(addresses) != 0:
akeys = sorted(addresses.keys())
for a in akeys:
message.append(
'<entry ip="%s"%s>' % (a, persistent)
)
tags = sorted(addresses[a])
if tags is not None:
message.append('<tag>')
for t in tags:
message.append('<member>%s</member>' % t)
message.append('</tag>')
message.append('</entry>')
message.append('</%s>' % type_)
message.append('</payload></uid-message>')
return ''.join(message)
def _user_id(self, cmd=None):
try:
self.xapi.user_id(cmd=cmd,
vsys=self.device.get('vsys', None))
except gevent.GreenletExit:
raise
except pan.xapi.PanXapiError as e:
LOG.debug('%s', e)
if 'already exists, ignore' in str(e):
pass
elif 'does not exist, ignore unreg' in str(e):
pass
elif 'Failed to register' in str(e):
pass
else:
LOG.exception('XAPI exception in pusher for device %s: %s',
self.device.get('hostname', None), str(e))
raise
def _tags_from_value(self, value):
result = []
def _tag(t, v):
if type(v) == unicode:
v = v.encode('ascii', 'replace')
else:
v = str(v)
v = SUBRE.sub('_', v)
tag = '%s%s_%s' % (self.prefix, t, v)
return tag
for t in self.attributes:
if t in value:
if t == 'confidence':
confidence = value[t]
if confidence < 50:
tag = '%s%s_low' % (self.prefix, t)
elif confidence < 75:
tag = '%s%s_medium' % (self.prefix, t)
else:
tag = '%s%s_high' % (self.prefix, t)
result.append(tag)
else:
LOG.debug('%s %s %s', t, value[t], type(value[t]))
if isinstance(value[t], list):
for v in value[t]:
LOG.debug('%s', v)
result.append(_tag(t, v))
else:
result.append(_tag(t, value[t]))
else:
# XXX noop for this case?
result.append('%s%s_unknown' % (self.prefix, t))
LOG.debug('%s', result)
return set(result) # XXX eliminate duplicates
def _push(self, op, address, value):
tags = []
tags.append('%s%s' % (self.prefix, self.watermark))
tags += self._tags_from_value(value)
if len(tags) == 0:
tags = None
msg = self._dag_message(op, {address: tags})
self._user_id(cmd=msg)
def _init_resync(self):
ctags = collections.defaultdict(set)
while True:
op, address, value = self.q.get()
if op == 'EOI':
break
if op != 'init':
raise RuntimeError(
'DevicePusher %s - wrong op %s received in init phase' %
(self.device.get('hostname', None), op)
)
ctags[address].add('%s%s' % (self.prefix, self.watermark))
for t in self._tags_from_value(value):
ctags[address].add(t)
LOG.debug('%s', ctags)
register = collections.defaultdict(list)
unregister = collections.defaultdict(list)
for a, atags in self._get_all_registered_ips():
regtags = set()
if atags is not None:
for t in atags:
regtags.add(t)
added = ctags[a] - regtags
removed = regtags - ctags[a]
for t in added:
register[a].append(t)
for t in removed:
unregister[a].append(t)
ctags.pop(a)
# ips not in firewall
for a, atags in ctags.iteritems():
register[a] = atags
LOG.debug('register %s', register)
LOG.debug('unregister %s', unregister)
# XXX use constant for chunk size
if len(register) != 0:
addrs = iter(register)
for i in xrange(0, len(register), 1000):
rmsg = self._dag_message(
'register',
{k: register[k] for k in itertools.islice(addrs, 1000)}
)
self._user_id(cmd=rmsg)
if len(unregister) != 0:
addrs = iter(unregister)
for i in xrange(0, len(unregister), 1000):
urmsg = self._dag_message(
'unregister',
{k: unregister[k] for k in itertools.islice(addrs, 1000)}
)
self._user_id(cmd=urmsg)
def _run(self):
self._init_resync()
while True:
try:
op, address, value = self.q.peek()
self._push(op, address, value)
self.q.get() # discard processed message
except gevent.GreenletExit:
break
except pan.xapi.PanXapiError as e:
LOG.exception('XAPI exception in pusher for device %s: %s',
self.device.get('hostname', None), str(e))
raise
class DagPusher(actorbase.ActorBaseFT):
def __init__(self, name, chassis, config):
self.devices = []
self.device_pushers = []
self.device_list_glet = None
self.device_list_mtime = None
self.ageout_glet = None
self.last_ageout_run = None
self.hup_event = gevent.event.Event()
super(DagPusher, self).__init__(name, chassis, config)
def configure(self):
super(DagPusher, self).configure()
self.device_list_path = self.config.get('device_list', None)
if self.device_list_path is None:
self.device_list_path = os.path.join(
os.environ['MM_CONFIG_DIR'],
'%s_device_list.yml' % self.name
)
self.age_out = self.config.get('age_out', 3600)
self.age_out_interval = self.config.get('age_out_interval', None)
self.tag_prefix = self.config.get('tag_prefix', 'mmld_')
self.tag_watermark = self.config.get('tag_watermark', 'pushed')
self.tag_attributes = self.config.get(
'tag_attributes',
['confidence', 'direction']
)
self.persistent_registered_ips = self.config.get(
'persistent_registered_ips',
True
)
def _initialize_table(self, truncate=False):
self.table = table.Table(self.name, truncate=truncate)
self.table.create_index('_age_out')
def initialize(self):
self._initialize_table()
def rebuild(self):
self.rebuild_flag = True
self._initialize_table(truncate=True)
def reset(self):
self._initialize_table(truncate=True)
def _validate_ip(self, indicator, value):
type_ = value.get('type', None)
if type_ not in ['IPv4', 'IPv6']:
LOG.error('%s - invalid indicator type, ignored: %s',
self.name, type_)
self.statistics['ignored'] += 1
return
if '-' in indicator:
i1, i2 = indicator.split('-', 1)
if i1 != i2:
LOG.error('%s - indicator range must be equal, ignored: %s',
self.name, indicator)
self.statistics['ignored'] += 1
return
indicator = i1
try:
address = netaddr.IPNetwork(indicator)
except netaddr.core.AddrFormatError as e:
LOG.error('%s - invalid IP address received, ignored: %s',
self.name, e)
self.statistics['ignored'] += 1
return
if address.size != 1:
LOG.error('%s - IP network received, ignored: %s',
self.name, address)
self.statistics['ignored'] += 1
return
if type_ == 'IPv4' and address.version != 4 or \
type_ == 'IPv6' and address.version != 6:
LOG.error('%s - IP version mismatch, ignored',
self.name)
self.statistics['ignored'] += 1
return
return address
@base._counting('update.processed')
def filtered_update(self, source=None, indicator=None, value=None):
address = self._validate_ip(indicator, value)
if address is None:
return
current_value = self.table.get(str(address))
now = utc_millisec()
age_out = now+self.age_out*1000
value['_age_out'] = age_out
self.statistics['added'] += 1
self.table.put(str(address), value)
LOG.debug('%s - #indicators: %d', self.name, self.length())
value.pop('_age_out')
uflag = False
if current_value is not None:
for t in self.tag_attributes:
cv = current_value.get(t, None)
nv = value.get(t, None)
if isinstance(cv, list) or isinstance(nv, list):
uflag |= set(cv) != set(nv)
else:
uflag |= cv != nv
LOG.debug('uflag %s current %s new %s', uflag, current_value, value)
for p in self.device_pushers:
if uflag:
p.put('unregister', str(address), current_value)
p.put('register', str(address), value)
@base._counting('withdraw.processed')
def filtered_withdraw(self, source=None, indicator=None, value=None):
address = self._validate_ip(indicator, value)
if address is None:
return
current_value = self.table.get(str(address))
if current_value is None:
LOG.warning('%s - unknown indicator received, ignored: %s',
self.name, address)
self.statistics['ignored'] += 1
return
current_value.pop('_age_out', None)
self.statistics['removed'] += 1
self.table.delete(str(address))
LOG.debug('%s - #indicators: %d', self.name, self.length())
for p in self.device_pushers:
p.put('unregister', str(address), current_value)
def _age_out_run(self):
while True:
try:
now = utc_millisec()
LOG.debug('now: %s', now)
for i, v in self.table.query(index='_age_out',
to_key=now-1,
include_value=True):
LOG.debug('%s - %s %s aged out', self.name, i, v)
for dp in self.device_pushers:
dp.put(
op='unregister',
address=i,
value=v
)
self.statistics['aged_out'] += 1
self.table.delete(i)
self.last_ageout_run = now
LOG.debug('%s - #indicators: %d', self.name, self.length())
except gevent.GreenletExit:
break
except Exception:
LOG.exception('Exception in _age_out_loop')
try:
gevent.sleep(self.age_out_interval)
except gevent.GreenletExit:
break
def _spawn_device_pusher(self, device):
dp = DevicePusher(
device,
self.tag_prefix,
self.tag_watermark,
self.tag_attributes,
self.persistent_registered_ips
)
dp.link_exception(self._device_pusher_died)
for i, v in self.table.query(include_value=True):
LOG.debug('%s - addding %s to init', self.name, i)
dp.put('init', i, v)
dp.put('EOI', None, None)
return dp
def _device_pusher_died(self, g):
try:
g.get()
except gevent.GreenletExit:
pass
except Exception:
LOG.exception('%s - exception in greenlet for %s, '
'respawning in 60 seconds',
self.name, g.device['hostname'])
for idx in range(len(self.device_pushers)):
if self.device_pushers[idx].device == g.device:
break
else:
LOG.info('%s - device pusher for %s removed,' +
' respawning aborted',
self.name, g.device['hostname'])
g = None
return
dp = self._spawn_device_pusher(g.device)
self.device_pushers[idx] = dp
dp.start_later(60)
def _load_device_list(self):
with open(self.device_list_path, 'r') as dlf:
dlist = yaml.safe_load(dlf)
added = [d for i, d in enumerate(dlist) if d not in self.devices]
removed = [i for i, d in enumerate(self.devices) if d not in dlist]
dpushers = []
for d in dlist:
if d in added:
dp = self._spawn_device_pusher(d)
dpushers.append(dp)
else:
idx = self.devices.index(d)
dpushers.append(self.device_pushers[idx])
for idx in removed:
self.device_pushers[idx].kill()
self.device_pushers = dpushers
self.devices = dlist
for g in self.device_pushers:
if g.value is None and not g.started:
g.start()
def _huppable_wait(self, wait_time):
hup_called = self.hup_event.wait(timeout=wait_time)
if hup_called:
LOG.debug('%s - clearing poll event', self.name)
self.hup_event.clear()
def _device_list_monitor(self):
if self.device_list_path is None:
LOG.warning('%s - no device_list path configured', self.name)
return
while True:
try:
mtime = os.stat(self.device_list_path).st_mtime
except OSError:
LOG.debug('%s - error checking mtime of %s',
self.name, self.device_list_path)
self._huppable_wait(5)
continue
if mtime != self.device_list_mtime:
self.device_list_mtime = mtime
try:
self._load_device_list()
LOG.info('%s - device list loaded', self.name)
except Exception:
LOG.exception('%s - exception loading device list',
self.name)
self._huppable_wait(5)
def mgmtbus_status(self):
result = super(DagPusher, self).mgmtbus_status()
result['devices'] = len(self.devices)
return result
def length(self, source=None):
return self.table.num_indicators
def start(self):
super(DagPusher, self).start()
if self.device_list_glet is not None:
return
self.device_list_glet = gevent.spawn_later(
2,
self._device_list_monitor
)
if self.age_out_interval is not None:
self.ageout_glet = gevent.spawn(self._age_out_run)
def stop(self):
super(DagPusher, self).stop()
if self.device_list_glet is None:
return
for g in self.device_pushers:
g.kill()
self.device_list_glet.kill()
if self.ageout_glet is not None:
self.ageout_glet.kill()
self.table.close()
def hup(self, source=None):
LOG.info('%s - hup received, reload device list', self.name)
self.hup_event.set()
@staticmethod
def gc(name, config=None):
actorbase.ActorBaseFT.gc(name, config=config)
shutil.rmtree(name, ignore_errors=True)
device_list_path = None
if config is not None:
device_list_path = config.get('device_list', None)
if device_list_path is None:
device_list_path = os.path.join(
os.environ['MM_CONFIG_DIR'],
'{}_device_list.yml'.format(name)
)
try:
os.remove(device_list_path)
except OSError:
pass
|
PaloAltoNetworks/minemeld-core
|
minemeld/ft/dag.py
|
Python
|
apache-2.0
| 20,185
|
/*-------------------------------------------------------------------------
*
* execBitmapHeapScan.c
* Support routines for scanning Heap tables using bitmaps.
*
* Portions Copyright (c) 2014-Present Pivotal Software, Inc.
* Portions Copyright (c) 1996-2008, PostgreSQL Global Development Group
* Portions Copyright (c) 1994, Regents of the University of California
*
*
* IDENTIFICATION
* src/backend/executor/execBitmapHeapScan.c
*
*-------------------------------------------------------------------------
*/
#include "postgres.h"
#include "executor/executor.h"
#include "nodes/execnodes.h"
#include "access/heapam.h"
#include "access/relscan.h"
#include "access/transam.h"
#include "executor/execdebug.h"
#include "executor/nodeBitmapHeapscan.h"
#include "pgstat.h"
#include "storage/bufmgr.h"
#include "utils/memutils.h"
#include "miscadmin.h"
#include "parser/parsetree.h"
#include "cdb/cdbvars.h" /* gp_select_invisible */
#include "nodes/tidbitmap.h"
/*
* Prepares for a new heap scan.
*/
void
BitmapHeapScanBegin(ScanState *scanState)
{
BitmapTableScanState *node = (BitmapTableScanState *)scanState;
Relation currentRelation = node->ss.ss_currentRelation;
EState *estate = node->ss.ps.state;
Assert(node->scanDesc == NULL);
/*
* Even though we aren't going to do a conventional seqscan, it is useful
* to create a HeapScanDesc --- most of the fields in it are usable.
*/
node->scanDesc = heap_beginscan_bm(currentRelation,
estate->es_snapshot,
0,
NULL);
/*
* Heap always needs rechecking each tuple because of potential
* visibility issue (we don't store MVCC info in the index).
*/
node->recheckTuples = true;
}
/*
* Cleans up after the scanning is done.
*/
void
BitmapHeapScanEnd(ScanState *scanState)
{
BitmapTableScanState *node = (BitmapTableScanState *)scanState;
/*
* We might call "End" method before even calling init method,
* in case we had an ERROR. Ignore scanDesc cleanup in such cases
*/
if (NULL != node->scanDesc)
{
heap_endscan((HeapScanDesc)node->scanDesc);
node->scanDesc = NULL;
}
if (NULL != node->iterator)
{
pfree(node->iterator);
node->iterator = NULL;
}
}
/*
* Returns the next matching tuple.
*/
TupleTableSlot *
BitmapHeapScanNext(ScanState *scanState)
{
BitmapTableScanState *node = (BitmapTableScanState *)scanState;
Assert((node->ss.scan_state & SCAN_SCAN) != 0);
/*
* extract necessary information from index scan node
*/
TupleTableSlot *slot = node->ss.ss_ScanTupleSlot;
HeapScanDesc scan = node->scanDesc;
TBMIterateResult *tbmres = (TBMIterateResult *)node->tbmres;
Assert(tbmres != NULL && tbmres->ntuples != 0);
Assert(node->needNewBitmapPage == false);
for (;;)
{
CHECK_FOR_INTERRUPTS();
if (node->iterator == NULL)
{
/*
* Fetch the current heap page and identify candidate tuples.
*/
bitgetpage(scan, tbmres);
/*
* Set rs_cindex to first slot to examine
*/
scan->rs_cindex = 0;
/*
* The nullity of the iterator is used to check if
* we need a new iterator to process a new bitmap page.
* Note: the bitmap page is provided by BitmapTableScan.
* This iterator is supposed to maintain the cursor position
* in the heap page that it is scanning. However, for heap
* tables we already have such cursor state as part of ScanState,
* and so, we just use a dummy allocation here to indicate
* ourselves that we have finished initialization for processing
* a new bitmap page.
*/
node->iterator = palloc(0);
}
else
{
/*
* Continuing in previously obtained page; advance rs_cindex
*/
scan->rs_cindex++;
}
/*
* If we reach the end of the relation or if we are out of range or
* nothing more to look at on this page, then request a new bitmap page.
*/
if (tbmres->blockno >= scan->rs_nblocks || scan->rs_cindex < 0 ||
scan->rs_cindex >= scan->rs_ntuples)
{
Assert(NULL != node->iterator);
pfree(node->iterator);
node->iterator = NULL;
node->needNewBitmapPage = true;
return ExecClearTuple(slot);
}
/*
* Okay to fetch the tuple
*/
OffsetNumber targoffset = scan->rs_vistuples[scan->rs_cindex];
Page dp = (Page) BufferGetPage(scan->rs_cbuf);
ItemId lp = PageGetItemId(dp, targoffset);
Assert(ItemIdIsUsed(lp));
scan->rs_ctup.t_data = (HeapTupleHeader) PageGetItem((Page) dp, lp);
scan->rs_ctup.t_len = ItemIdGetLength(lp);
ItemPointerSet(&scan->rs_ctup.t_self, tbmres->blockno, targoffset);
pgstat_count_heap_fetch(scan->rs_rd);
/*
* Set up the result slot to point to this tuple. Note that the slot
* acquires a pin on the buffer.
*/
ExecStoreHeapTuple(&scan->rs_ctup,
slot,
scan->rs_cbuf,
false);
if (!BitmapTableScanRecheckTuple(node, slot))
{
ExecClearTuple(slot);
continue;
}
return slot;
}
/*
* We should never reach here as the termination is handled
* from nodeBitmapTableScan.
*/
Assert(false);
return NULL;
}
/*
* Prepares for a re-scan.
*/
void
BitmapHeapScanReScan(ScanState *scanState)
{
BitmapTableScanState *node = (BitmapTableScanState *)scanState;
Assert(node->scanDesc != NULL);
/* rescan to release any page pin */
heap_rescan(node->scanDesc, NULL);
}
|
Chibin/gpdb
|
src/backend/executor/execBitmapHeapScan.c
|
C
|
apache-2.0
| 5,281
|
/*
* Project Scelight
*
* Copyright (c) 2013 Andras Belicza <iczaaa@gmail.com>
*
* This software is the property of Andras Belicza.
* Copying, modifying, distributing, refactoring without the author's permission
* is prohibited and protected by Law.
*/
package hu.scelight.sc2.rep.model.messageevents;
import hu.scelight.gui.icon.Icons;
import hu.scelightapi.sc2.rep.model.messageevents.IPingEvent;
import hu.sllauncher.gui.icon.LRIcon;
import java.util.Map;
/**
* Minimap ping message event.
*
* @author Andras Belicza
*/
public class PingEvent extends MsgEvent implements IPingEvent {
/** RIcon of the ping event. */
public static final LRIcon RICON = Icons.F_MAP_PIN;
/**
* Creates a new {@link PingEvent}.
*
* @param struct event data structure
* @param id id of the event
* @param name type name of the event
* @param loop game loop when the event occurred
* @param userId user id causing the event
*/
public PingEvent( final Map< String, Object > struct, final int id, final String name, final int loop, final int userId ) {
super( struct, id, name, loop, userId );
}
@Override
public Integer getX() {
return get( P_POINT_X );
}
@Override
public Float getXFloat() {
final Integer x = get( P_POINT_X );
return x == null ? null : x / 8192.0f;
}
@Override
public Integer getY() {
return get( P_POINT_Y );
}
@Override
public Float getYFloat() {
final Integer y = get( P_POINT_Y );
return y == null ? null : y / 8192.0f;
}
@Override
public LRIcon getRicon() {
return RICON;
}
}
|
icza/scelight
|
src-app/hu/scelight/sc2/rep/model/messageevents/PingEvent.java
|
Java
|
apache-2.0
| 1,637
|
package org.gradle.test.performance.mediummonolithicjavaproject.p13;
import org.junit.Test;
import static org.junit.Assert.*;
public class Test261 {
Production261 objectUnderTest = new Production261();
@Test
public void testProperty0() {
String value = "value";
objectUnderTest.setProperty0(value);
assertEquals(value, objectUnderTest.getProperty0());
}
@Test
public void testProperty1() {
String value = "value";
objectUnderTest.setProperty1(value);
assertEquals(value, objectUnderTest.getProperty1());
}
@Test
public void testProperty2() {
String value = "value";
objectUnderTest.setProperty2(value);
assertEquals(value, objectUnderTest.getProperty2());
}
@Test
public void testProperty3() {
String value = "value";
objectUnderTest.setProperty3(value);
assertEquals(value, objectUnderTest.getProperty3());
}
@Test
public void testProperty4() {
String value = "value";
objectUnderTest.setProperty4(value);
assertEquals(value, objectUnderTest.getProperty4());
}
@Test
public void testProperty5() {
String value = "value";
objectUnderTest.setProperty5(value);
assertEquals(value, objectUnderTest.getProperty5());
}
@Test
public void testProperty6() {
String value = "value";
objectUnderTest.setProperty6(value);
assertEquals(value, objectUnderTest.getProperty6());
}
@Test
public void testProperty7() {
String value = "value";
objectUnderTest.setProperty7(value);
assertEquals(value, objectUnderTest.getProperty7());
}
@Test
public void testProperty8() {
String value = "value";
objectUnderTest.setProperty8(value);
assertEquals(value, objectUnderTest.getProperty8());
}
@Test
public void testProperty9() {
String value = "value";
objectUnderTest.setProperty9(value);
assertEquals(value, objectUnderTest.getProperty9());
}
}
|
oehme/analysing-gradle-performance
|
commons/src/test/java/org/gradle/test/performance/mediummonolithicjavaproject/p13/Test261.java
|
Java
|
apache-2.0
| 2,107
|
var searchData=
[
['ratecomment',['rateComment',['../namespace_meanco_app_1_1views_1_1_api_comment.html#a3126e77b21099a4dd4dea0c7d5370b50',1,'MeancoApp::views::ApiComment']]],
['raterelation',['rateRelation',['../namespace_meanco_app_1_1views_1_1_api_relation.html#a024057c446726ba7e55cba45c6ce116c',1,'MeancoApp::views::ApiRelation']]],
['register',['register',['../namespace_meanco_app_1_1views_1_1_api_authentication.html#af77e576094ba5aac7cb8bb6ec321aecc',1,'MeancoApp::views::ApiAuthentication']]]
];
|
bounswe/bounswe2016group12
|
docs/html/search/functions_6.js
|
JavaScript
|
apache-2.0
| 512
|
package com.triangleleft.flashcards.rule;
import org.openqa.selenium.Capabilities;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.remote.DesiredCapabilities;
import java.io.File;
import java.net.URL;
import io.appium.java_client.android.AndroidDriver;
import io.appium.java_client.remote.AndroidMobileCapabilityType;
import io.appium.java_client.remote.MobileCapabilityType;
import io.appium.java_client.remote.MobilePlatform;
public class AppiumAndroidDriver extends AndroidDriver<WebElement> {
public static final String APK_PATH = "../app/build/outputs/apk/";
public static final String APK_NAME = "app-appium.apk";
public static final String PACKAGE_NAME = "com.triangleleft.flashcards";
public static final String ACTIVITY_NAME = ".ui.login.LoginActivity";
public static AppiumAndroidDriver create(URL remoteAddress, boolean fullReset) {
File classpathRoot = new File(System.getProperty("user.dir"));
File appDir = new File(classpathRoot, APK_PATH);
File appFile = new File(appDir, APK_NAME);
DesiredCapabilities capabilities = new DesiredCapabilities();
capabilities.setCapability(MobileCapabilityType.DEVICE_NAME, "emulator-5556");
capabilities.setCapability(MobileCapabilityType.PLATFORM_NAME, MobilePlatform.ANDROID);
if (fullReset) {
capabilities.setCapability(MobileCapabilityType.APP, appFile.getAbsolutePath());
capabilities.setCapability(MobileCapabilityType.NO_RESET, false);
} else {
capabilities.setCapability(MobileCapabilityType.NO_RESET, true);
}
capabilities.setCapability(AndroidMobileCapabilityType.APP_PACKAGE, PACKAGE_NAME);
capabilities.setCapability(AndroidMobileCapabilityType.APP_ACTIVITY, ACTIVITY_NAME);
return new AppiumAndroidDriver(remoteAddress, capabilities);
}
private AppiumAndroidDriver(URL remoteAddress, Capabilities desiredCapabilities) {
super(remoteAddress, desiredCapabilities);
}
}
|
TriangleLeft/Flashcards
|
appium/src/test/java/com/triangleleft/flashcards/rule/AppiumAndroidDriver.java
|
Java
|
apache-2.0
| 2,026
|
/*
* Copyright 2010 the original author or authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.springtestdbunit.dbunitrule.setup;
import javax.sql.DataSource;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.transaction.annotation.Transactional;
import com.github.springtestdbunit.DbUnitRule;
import com.github.springtestdbunit.annotation.DatabaseOperation;
import com.github.springtestdbunit.annotation.DatabaseSetup;
import com.github.springtestdbunit.entity.EntityAssert;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("/META-INF/dbunit-context.xml")
@Transactional
public class InsertSetupOnMethodTest {
@Rule
public DbUnitRule dbUnit = new DbUnitRule();
@Autowired
DataSource dataSource;
@Autowired
private EntityAssert entityAssert;
@Test
@DatabaseSetup(type = DatabaseOperation.INSERT, value = "/META-INF/db/insert.xml")
public void test() throws Exception {
this.entityAssert.assertValues("existing1", "existing2", "fromDbUnit");
}
}
|
ariestse/spring-test-hibernate-dbunit
|
spring-test-hibernate-dbunit/src/test/java/com/github/springtestdbunit/dbunitrule/setup/InsertSetupOnMethodTest.java
|
Java
|
apache-2.0
| 1,770
|
from django.contrib.staticfiles import storage
# Configure the permissions used by ./manage.py collectstatic
# See https://docs.djangoproject.com/en/1.10/ref/contrib/staticfiles/
class TTStaticFilesStorage(storage.StaticFilesStorage):
def __init__(self, *args, **kwargs):
kwargs['file_permissions_mode'] = 0o644
kwargs['directory_permissions_mode'] = 0o755
super(TTStaticFilesStorage, self).__init__(*args, **kwargs)
|
Goodly/TextThresher
|
thresher_backend/storage.py
|
Python
|
apache-2.0
| 446
|
package com.tweetqueue.core.services.user;
import com.tweetqueue.core.model.user.User;
import com.tweetqueue.core.model.user.UserFactory;
import com.tweetqueue.core.model.user.UserRepository;
public class CreateUserService {
private final UserRepository userRepository;
private final UserFactory userFactory;
private final UserResponseFactory userResponseFactory;
public CreateUserService(
UserRepository userRepository,
UserFactory userFactory,
UserResponseFactory userResponseFactory) {
this.userRepository = userRepository;
this.userFactory = userFactory;
this.userResponseFactory = userResponseFactory;
}
public UserResponse createUser(CreateUserRequest createUserRequest) {
User user = userRepository.save(userFactory.getUser(createUserRequest.getUsername()));
return userResponseFactory.getUserResponse(user);
}
}
|
tweetqueue/core
|
src/main/java/com/tweetqueue/core/services/user/CreateUserService.java
|
Java
|
apache-2.0
| 880
|
#! /bin/bash
set -e
set -x
if [ x"$TRAVIS" = xtrue ]; then
CPU_COUNT=2
else
CPU_COUNT=$(nproc)
fi
mv tcl/target/1986ве1т.cfg tcl/target/1986be1t.cfg
mv tcl/target/к1879xб1я.cfg tcl/target/k1879x61r.cfg
./bootstrap
mkdir build
cd build
../configure \
--prefix=$PREFIX \
--enable-static \
--disable-shared \
--enable-usb-blaster-2 \
--enable-usb_blaster_libftdi \
--enable-jtag_vpi \
--enable-remote-bitbang \
make -j$CPU_COUNT
make install
|
timvideos/conda-hdmi2usb-packages
|
prog/openocd/build.sh
|
Shell
|
apache-2.0
| 467
|
#!/bin/bash -eux
/sbin/chroot /mnt /bin/bash <<'EOF'
find /lib/modules/ -type f -name '*.ko' -exec gzip {} \;
depmod -a
EOF
|
robinwl/packer-templates
|
packer/scripts/slackware/kernel.sh
|
Shell
|
apache-2.0
| 124
|
package rsc.parallel;
import java.util.concurrent.atomic.AtomicIntegerFieldUpdater;
import java.util.concurrent.atomic.AtomicLongFieldUpdater;
import java.util.concurrent.atomic.AtomicReferenceFieldUpdater;
import org.reactivestreams.Subscriber;
import org.reactivestreams.Subscription;
import rsc.flow.Fuseable;
import rsc.publisher.GroupedPublisher;
import rsc.publisher.PublisherArray;
import rsc.publisher.Px;
import rsc.util.BackpressureHelper;
import rsc.subscriber.SubscriptionHelper;
/**
* Exposes the 'rails' as individual GroupedPublisher instances, keyed by the rail index (zero based).
* <p>
* Each group can be consumed only once; requests and cancellation compose through. Note
* that cancelling only one rail may result in undefined behavior.
*
* @param <T> the value type
*/
public final class ParallelGroup<T> extends Px<GroupedPublisher<Integer, T>> implements Fuseable {
final ParallelPublisher<? extends T> source;
public ParallelGroup(ParallelPublisher<? extends T> source) {
this.source = source;
}
@Override
public void subscribe(Subscriber<? super GroupedPublisher<Integer, T>> s) {
int n = source.parallelism();
@SuppressWarnings("unchecked")
ParallelInnerGroup<T>[] groups = new ParallelInnerGroup[n];
for (int i = 0; i < n; i++) {
groups[i] = new ParallelInnerGroup<>(i);
}
PublisherArray.subscribeWithArray(s, groups);
source.subscribe(groups);
}
static final class ParallelInnerGroup<T> extends GroupedPublisher<Integer, T>
implements Subscriber<T>, Subscription {
final int key;
volatile int once;
@SuppressWarnings("rawtypes")
static final AtomicIntegerFieldUpdater<ParallelInnerGroup> ONCE =
AtomicIntegerFieldUpdater.newUpdater(ParallelInnerGroup.class, "once");
volatile Subscription s;
@SuppressWarnings("rawtypes")
static final AtomicReferenceFieldUpdater<ParallelInnerGroup, Subscription> S =
AtomicReferenceFieldUpdater.newUpdater(ParallelInnerGroup.class, Subscription.class, "s");
volatile long requested;
@SuppressWarnings("rawtypes")
static final AtomicLongFieldUpdater<ParallelInnerGroup> REQUESTED =
AtomicLongFieldUpdater.newUpdater(ParallelInnerGroup.class, "requested");
Subscriber<? super T> actual;
public ParallelInnerGroup(int key) {
this.key = key;
}
@Override
public Integer key() {
return key;
}
@Override
public void subscribe(Subscriber<? super T> s) {
if (ONCE.compareAndSet(this, 0, 1)) {
this.actual = s;
s.onSubscribe(this);
} else {
SubscriptionHelper.error(s, new IllegalStateException("This ParallelGroup can be subscribed to at most once."));
}
}
@Override
public void onSubscribe(Subscription s) {
if (SubscriptionHelper.setOnce(S, this, s)) {
long r = REQUESTED.getAndSet(this, 0L);
if (r != 0L) {
s.request(r);
}
}
}
@Override
public void onNext(T t) {
actual.onNext(t);
}
@Override
public void onError(Throwable t) {
actual.onError(t);
}
@Override
public void onComplete() {
actual.onComplete();
}
@Override
public void request(long n) {
if (SubscriptionHelper.validate(n)) {
Subscription a = s;
if (a == null) {
BackpressureHelper.getAndAddCap(REQUESTED, this, n);
a = s;
if (a != null) {
long r = REQUESTED.getAndSet(this, 0L);
if (r != 0L) {
a.request(n);
}
}
} else {
a.request(n);
}
}
}
@Override
public void cancel() {
SubscriptionHelper.terminate(S, this);
}
}
}
|
reactor/reactive-streams-commons
|
src/main/java/rsc/parallel/ParallelGroup.java
|
Java
|
apache-2.0
| 4,430
|
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"
"http://www.w3.org/TR/REC-html40/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html">
<meta name="Template" content="C:\PROGRAM FILES\MICROSOFT
OFFICE\OFFICE\html.dot">
<title>FrequencyResolution</title>
</head>
<body text="#000000" bgcolor="#FDF5E6" link="#FF00FF" vlink="#800080"
alink="#FF0000">
<center>
<h1>FrequencyResolution</h1>
</center>
<center>
<LARGE><b>Author : Bernard Schutz</b>
<p>
<LARGE><b>Version : 1.0</b>
</p>
<p><b>Input Types : <a
href="../../../../help/JavaDoc/triana/types/Spectral.html">Spectral</a></b>
<br>
<b>Output Types : <a
href="../../../../help/JavaDoc/triana/types/Parameter.html">Parameter</a></b>
<br>
<b>Date : 26 Feb 2001 </b></LARGE>
</p>
</center>
<h2><a name="contents"></a>Contents</h2>
<ul>
<li><a href="#description">Description of FrequencyResolution</a></li>
<li><a href="#using">Using FrequencyResolution</a></li>
</ul>
<hr width="15%" size="4">
<h2><a name="description"></a>Description of FrequencyResolution</h2>
The unit called FrequencyResolution accepts any data type that implements the
Spectral interface as input and outputs a Parameter type that contains the
frequency resolution of the input data. This can be input to another unit as a
parameter. <br>
<br>
<h2><a name="using"></a>Using FrequencyResolution</h2>
FrequencyResolution has no parameter window.
<p></p>
<hr width="15%" size="4">
</body>
</html>
|
CSCSI/Triana
|
triana-toolboxes/signalproc/help/dataparam/FrequencyResolution.html
|
HTML
|
apache-2.0
| 1,638
|
// Code generated by msgraph.go/gen DO NOT EDIT.
package msgraph
import "context"
// ApplicationRequestBuilder is request builder for Application
type ApplicationRequestBuilder struct{ BaseRequestBuilder }
// Request returns ApplicationRequest
func (b *ApplicationRequestBuilder) Request() *ApplicationRequest {
return &ApplicationRequest{
BaseRequest: BaseRequest{baseURL: b.baseURL, client: b.client},
}
}
// ApplicationRequest is request for Application
type ApplicationRequest struct{ BaseRequest }
// Get performs GET request for Application
func (r *ApplicationRequest) Get(ctx context.Context) (resObj *Application, err error) {
var query string
if r.query != nil {
query = "?" + r.query.Encode()
}
err = r.JSONRequest(ctx, "GET", query, nil, &resObj)
return
}
// Update performs PATCH request for Application
func (r *ApplicationRequest) Update(ctx context.Context, reqObj *Application) error {
return r.JSONRequest(ctx, "PATCH", "", reqObj, nil)
}
// Delete performs DELETE request for Application
func (r *ApplicationRequest) Delete(ctx context.Context) error {
return r.JSONRequest(ctx, "DELETE", "", nil, nil)
}
// ApplicationSignInDetailedSummaryRequestBuilder is request builder for ApplicationSignInDetailedSummary
type ApplicationSignInDetailedSummaryRequestBuilder struct{ BaseRequestBuilder }
// Request returns ApplicationSignInDetailedSummaryRequest
func (b *ApplicationSignInDetailedSummaryRequestBuilder) Request() *ApplicationSignInDetailedSummaryRequest {
return &ApplicationSignInDetailedSummaryRequest{
BaseRequest: BaseRequest{baseURL: b.baseURL, client: b.client},
}
}
// ApplicationSignInDetailedSummaryRequest is request for ApplicationSignInDetailedSummary
type ApplicationSignInDetailedSummaryRequest struct{ BaseRequest }
// Get performs GET request for ApplicationSignInDetailedSummary
func (r *ApplicationSignInDetailedSummaryRequest) Get(ctx context.Context) (resObj *ApplicationSignInDetailedSummary, err error) {
var query string
if r.query != nil {
query = "?" + r.query.Encode()
}
err = r.JSONRequest(ctx, "GET", query, nil, &resObj)
return
}
// Update performs PATCH request for ApplicationSignInDetailedSummary
func (r *ApplicationSignInDetailedSummaryRequest) Update(ctx context.Context, reqObj *ApplicationSignInDetailedSummary) error {
return r.JSONRequest(ctx, "PATCH", "", reqObj, nil)
}
// Delete performs DELETE request for ApplicationSignInDetailedSummary
func (r *ApplicationSignInDetailedSummaryRequest) Delete(ctx context.Context) error {
return r.JSONRequest(ctx, "DELETE", "", nil, nil)
}
// ApplicationTemplateRequestBuilder is request builder for ApplicationTemplate
type ApplicationTemplateRequestBuilder struct{ BaseRequestBuilder }
// Request returns ApplicationTemplateRequest
func (b *ApplicationTemplateRequestBuilder) Request() *ApplicationTemplateRequest {
return &ApplicationTemplateRequest{
BaseRequest: BaseRequest{baseURL: b.baseURL, client: b.client},
}
}
// ApplicationTemplateRequest is request for ApplicationTemplate
type ApplicationTemplateRequest struct{ BaseRequest }
// Get performs GET request for ApplicationTemplate
func (r *ApplicationTemplateRequest) Get(ctx context.Context) (resObj *ApplicationTemplate, err error) {
var query string
if r.query != nil {
query = "?" + r.query.Encode()
}
err = r.JSONRequest(ctx, "GET", query, nil, &resObj)
return
}
// Update performs PATCH request for ApplicationTemplate
func (r *ApplicationTemplateRequest) Update(ctx context.Context, reqObj *ApplicationTemplate) error {
return r.JSONRequest(ctx, "PATCH", "", reqObj, nil)
}
// Delete performs DELETE request for ApplicationTemplate
func (r *ApplicationTemplateRequest) Delete(ctx context.Context) error {
return r.JSONRequest(ctx, "DELETE", "", nil, nil)
}
//
type ApplicationAddKeyRequestBuilder struct{ BaseRequestBuilder }
// AddKey action undocumented
func (b *ApplicationRequestBuilder) AddKey(reqObj *ApplicationAddKeyRequestParameter) *ApplicationAddKeyRequestBuilder {
bb := &ApplicationAddKeyRequestBuilder{BaseRequestBuilder: b.BaseRequestBuilder}
bb.BaseRequestBuilder.baseURL += "/addKey"
bb.BaseRequestBuilder.requestObject = reqObj
return bb
}
//
type ApplicationAddKeyRequest struct{ BaseRequest }
//
func (b *ApplicationAddKeyRequestBuilder) Request() *ApplicationAddKeyRequest {
return &ApplicationAddKeyRequest{
BaseRequest: BaseRequest{baseURL: b.baseURL, client: b.client, requestObject: b.requestObject},
}
}
//
func (r *ApplicationAddKeyRequest) Post(ctx context.Context) (resObj *KeyCredential, err error) {
err = r.JSONRequest(ctx, "POST", "", r.requestObject, &resObj)
return
}
//
type ApplicationAddPasswordRequestBuilder struct{ BaseRequestBuilder }
// AddPassword action undocumented
func (b *ApplicationRequestBuilder) AddPassword(reqObj *ApplicationAddPasswordRequestParameter) *ApplicationAddPasswordRequestBuilder {
bb := &ApplicationAddPasswordRequestBuilder{BaseRequestBuilder: b.BaseRequestBuilder}
bb.BaseRequestBuilder.baseURL += "/addPassword"
bb.BaseRequestBuilder.requestObject = reqObj
return bb
}
//
type ApplicationAddPasswordRequest struct{ BaseRequest }
//
func (b *ApplicationAddPasswordRequestBuilder) Request() *ApplicationAddPasswordRequest {
return &ApplicationAddPasswordRequest{
BaseRequest: BaseRequest{baseURL: b.baseURL, client: b.client, requestObject: b.requestObject},
}
}
//
func (r *ApplicationAddPasswordRequest) Post(ctx context.Context) (resObj *PasswordCredential, err error) {
err = r.JSONRequest(ctx, "POST", "", r.requestObject, &resObj)
return
}
//
type ApplicationRemoveKeyRequestBuilder struct{ BaseRequestBuilder }
// RemoveKey action undocumented
func (b *ApplicationRequestBuilder) RemoveKey(reqObj *ApplicationRemoveKeyRequestParameter) *ApplicationRemoveKeyRequestBuilder {
bb := &ApplicationRemoveKeyRequestBuilder{BaseRequestBuilder: b.BaseRequestBuilder}
bb.BaseRequestBuilder.baseURL += "/removeKey"
bb.BaseRequestBuilder.requestObject = reqObj
return bb
}
//
type ApplicationRemoveKeyRequest struct{ BaseRequest }
//
func (b *ApplicationRemoveKeyRequestBuilder) Request() *ApplicationRemoveKeyRequest {
return &ApplicationRemoveKeyRequest{
BaseRequest: BaseRequest{baseURL: b.baseURL, client: b.client, requestObject: b.requestObject},
}
}
//
func (r *ApplicationRemoveKeyRequest) Post(ctx context.Context) error {
return r.JSONRequest(ctx, "POST", "", r.requestObject, nil)
}
//
type ApplicationRemovePasswordRequestBuilder struct{ BaseRequestBuilder }
// RemovePassword action undocumented
func (b *ApplicationRequestBuilder) RemovePassword(reqObj *ApplicationRemovePasswordRequestParameter) *ApplicationRemovePasswordRequestBuilder {
bb := &ApplicationRemovePasswordRequestBuilder{BaseRequestBuilder: b.BaseRequestBuilder}
bb.BaseRequestBuilder.baseURL += "/removePassword"
bb.BaseRequestBuilder.requestObject = reqObj
return bb
}
//
type ApplicationRemovePasswordRequest struct{ BaseRequest }
//
func (b *ApplicationRemovePasswordRequestBuilder) Request() *ApplicationRemovePasswordRequest {
return &ApplicationRemovePasswordRequest{
BaseRequest: BaseRequest{baseURL: b.baseURL, client: b.client, requestObject: b.requestObject},
}
}
//
func (r *ApplicationRemovePasswordRequest) Post(ctx context.Context) error {
return r.JSONRequest(ctx, "POST", "", r.requestObject, nil)
}
//
type ApplicationTemplateInstantiateRequestBuilder struct{ BaseRequestBuilder }
// Instantiate action undocumented
func (b *ApplicationTemplateRequestBuilder) Instantiate(reqObj *ApplicationTemplateInstantiateRequestParameter) *ApplicationTemplateInstantiateRequestBuilder {
bb := &ApplicationTemplateInstantiateRequestBuilder{BaseRequestBuilder: b.BaseRequestBuilder}
bb.BaseRequestBuilder.baseURL += "/instantiate"
bb.BaseRequestBuilder.requestObject = reqObj
return bb
}
//
type ApplicationTemplateInstantiateRequest struct{ BaseRequest }
//
func (b *ApplicationTemplateInstantiateRequestBuilder) Request() *ApplicationTemplateInstantiateRequest {
return &ApplicationTemplateInstantiateRequest{
BaseRequest: BaseRequest{baseURL: b.baseURL, client: b.client, requestObject: b.requestObject},
}
}
//
func (r *ApplicationTemplateInstantiateRequest) Post(ctx context.Context) (resObj *ApplicationServicePrincipal, err error) {
err = r.JSONRequest(ctx, "POST", "", r.requestObject, &resObj)
return
}
|
42wim/matterbridge
|
vendor/github.com/yaegashi/msgraph.go/beta/RequestApplication.go
|
GO
|
apache-2.0
| 8,365
|
/**
* Copyright 2010 - 2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package jetbrains.exodus.entitystore.tables;
import jetbrains.exodus.entitystore.PersistentEntityStoreImpl;
import jetbrains.exodus.entitystore.PersistentStoreTransaction;
import jetbrains.exodus.env.Store;
import jetbrains.exodus.env.StoreConfig;
import org.jetbrains.annotations.NotNull;
public class SingleColumnTable extends Table {
@NotNull
private final Store database;
public SingleColumnTable(@NotNull final PersistentStoreTransaction txn,
@NotNull final String name,
@NotNull final StoreConfig config) {
final PersistentEntityStoreImpl store = txn.getStore();
database = store.getEnvironment().openStore(name, config, txn.getEnvironmentTransaction());
store.trackTableCreation(database, txn);
}
@NotNull
public Store getDatabase() {
return database;
}
@Override
public boolean canBeCached() {
return !database.getConfig().temporaryEmpty;
}
}
|
morj/xodus
|
entity-store/src/main/java/jetbrains/exodus/entitystore/tables/SingleColumnTable.java
|
Java
|
apache-2.0
| 1,599
|
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1" charset="UTF-8">
<title>alignWithin</title>
<link href="../../../images/logo-icon.svg" rel="icon" type="image/svg">
<script>var pathToRoot = "../../../";</script>
<script type="text/javascript" src="../../../scripts/sourceset_dependencies.js" async="async"></script>
<link href="../../../styles/style.css" rel="Stylesheet">
<link href="../../../styles/logo-styles.css" rel="Stylesheet">
<link href="../../../styles/jetbrains-mono.css" rel="Stylesheet">
<link href="../../../styles/main.css" rel="Stylesheet">
<script type="text/javascript" src="../../../scripts/clipboard.js" async="async"></script>
<script type="text/javascript" src="../../../scripts/navigation-loader.js" async="async"></script>
<script type="text/javascript" src="../../../scripts/platform-content-handler.js" async="async"></script>
<script type="text/javascript" src="../../../scripts/main.js" async="async"></script>
</head>
<body>
<div id="container">
<div id="leftColumn">
<div id="logo"></div>
<div id="paneSearch"></div>
<div id="sideMenu"></div>
</div>
<div id="main">
<div id="leftToggler"><span class="icon-toggler"></span></div>
<script type="text/javascript" src="../../../scripts/pages.js"></script>
<script type="text/javascript" src="../../../scripts/main.js"></script>
<div class="main-content" id="content" pageIds="org.hexworks.zircon.api.component/ComponentAlignment/alignWithin/#org.hexworks.zircon.api.data.Rect#org.hexworks.zircon.api.data.Size/PointingToDeclaration//-828656838">
<div class="navigation-wrapper" id="navigation-wrapper">
<div class="breadcrumbs"><a href="../../index.html">zircon.core</a>/<a href="../index.html">org.hexworks.zircon.api.component</a>/<a href="index.html">ComponentAlignment</a>/<a href="align-within.html">alignWithin</a></div>
<div class="pull-right d-flex">
<div class="filter-section" id="filter-section"><button class="platform-tag platform-selector common-like" data-active="" data-filter=":zircon.core:dokkaHtml/commonMain">common</button></div>
<div id="searchBar"></div>
</div>
</div>
<div class="cover ">
<h1 class="cover"><span>align</span><wbr></wbr><span>Within</span></h1>
</div>
<div class="divergent-group" data-filterable-current=":zircon.core:dokkaHtml/commonMain" data-filterable-set=":zircon.core:dokkaHtml/commonMain"><div class="with-platform-tags"><span class="pull-right"></span></div>
<div>
<div class="platform-hinted " data-platform-hinted="data-platform-hinted"><div class="content sourceset-depenent-content" data-active="" data-togglable=":zircon.core:dokkaHtml/commonMain"><div class="symbol monospace">fun <a href="align-within.html">alignWithin</a>(other: <a href="../../org.hexworks.zircon.api.data/-rect/index.html">Rect</a>, target: <a href="../../org.hexworks.zircon.api.data/-size/index.html">Size</a>): <a href="../../org.hexworks.zircon.api.data/-position/index.html">Position</a><span class="top-right-position"><span class="copy-icon"></span><div class="copy-popup-wrapper popup-to-left"><span class="copy-popup-icon"></span><span>Content copied to clipboard</span></div></span></div></div></div>
</div>
<p class="paragraph">Returns the <a href="../../org.hexworks.zircon.api.data/-position/index.html">Position</a> which can be used to properly align a boundable with <span data-unresolved-link="org.hexworks.zircon.api.component/ComponentAlignment/target/#/PointingToCallableParameters(-1)/">target</span> size within<span data-unresolved-link="org.hexworks.zircon.api.component/ComponentAlignment/other/#/PointingToCallableParameters(-1)/">other</span>.</p></div>
<h2 class="">Sources</h2>
<div class="table" data-togglable="Sources"><a data-name="%5Borg.hexworks.zircon.api.component%2FComponentAlignment%2FalignWithin%2F%23org.hexworks.zircon.api.data.Rect%23org.hexworks.zircon.api.data.Size%2FPointingToDeclaration%2F%5D%2FSource%2F-828656838" anchor-label="https://github.com/Hexworks/zircon/tree/master/zircon.core/src/commonMain/kotlin/org/hexworks/zircon/api/component/ComponentAlignment.kt#L71" id="%5Borg.hexworks.zircon.api.component%2FComponentAlignment%2FalignWithin%2F%23org.hexworks.zircon.api.data.Rect%23org.hexworks.zircon.api.data.Size%2FPointingToDeclaration%2F%5D%2FSource%2F-828656838" data-filterable-set=":zircon.core:dokkaHtml/commonMain"></a>
<div class="table-row" data-filterable-current=":zircon.core:dokkaHtml/commonMain" data-filterable-set=":zircon.core:dokkaHtml/commonMain">
<div class="main-subrow keyValue ">
<div class=""><span class="inline-flex"><a href="https://github.com/Hexworks/zircon/tree/master/zircon.core/src/commonMain/kotlin/org/hexworks/zircon/api/component/ComponentAlignment.kt#L71">(source)</a><span class="anchor-wrapper"><span class="anchor-icon" pointing-to="%5Borg.hexworks.zircon.api.component%2FComponentAlignment%2FalignWithin%2F%23org.hexworks.zircon.api.data.Rect%23org.hexworks.zircon.api.data.Size%2FPointingToDeclaration%2F%5D%2FSource%2F-828656838"></span>
<div class="copy-popup-wrapper "><span class="copy-popup-icon"></span><span>Link copied to clipboard</span></div>
</span></span></div>
<div></div>
</div>
</div>
</div>
</div>
<div class="footer"><span class="go-to-top-icon"><a href="#content"></a></span><span>© 2020 Copyright</span><span class="pull-right"><span>Sponsored and developed by dokka</span><a href="https://github.com/Kotlin/dokka"><span class="padded-icon"></span></a></span></div>
</div>
</div>
</body>
</html>
|
Hexworks/zircon
|
docs/2020.2.0-RELEASE-KOTLIN/zircon.core/zircon.core/org.hexworks.zircon.api.component/-component-alignment/align-within.html
|
HTML
|
apache-2.0
| 5,900
|
using Fidget.Validation.Addresses.Metadata;
using System.Collections.Generic;
using System.Linq;
using Xunit;
namespace Fidget.Validation.Addresses.Validation.Validators
{
public class CountryValidatorTests
{
IAddressValidator instance => new CountryValidator();
ValidationContext context = new ValidationContext();
IEnumerable<AddressValidationFailure> invoke() => instance.Validate( context );
[Fact]
public void IsRegistered()
{
var actual = DependencyInjection.Container.GetAllInstances<IAddressValidator>();
Assert.Contains( actual, _ => _ is CountryValidator );
}
/// <summary>
/// Cases where the country should be considered valid.
/// </summary>
public static IEnumerable<object[]> ValidCases()
{
// cases where the country is not specified in the address
// the country being unspecified is a different validator
var unspecified =
from value in new string[] { null, string.Empty, "\t" }
from country in new CountryMetadata[] { null, new CountryMetadata() }
select new object[] { value, country };
// cases where the country is specified and its metadata exists
var valid = new object[][]
{
new object[] { "ABC", new CountryMetadata() },
};
return valid.Union( unspecified );
}
[Theory]
[MemberData(nameof(ValidCases))]
public void Validate_whenValid_returnsSuccess( string country, CountryMetadata meta )
{
context.Address = new AddressData { Country = country };
context.CountryMetadata = meta;
var actual = invoke();
Assert.Empty( actual );
}
[Fact]
public void Validate_whenNotValid_returnsFailure()
{
// when the country is specified but has no metadata, a failure should be reported
context.Address = new AddressData { Country = "XW" };
context.CountryMetadata = null;
var expected = new AddressValidationFailure { Field = AddressField.Country, Error = AddressFieldError.UnkownValue };
var actual = invoke();
Assert.Equal( expected, actual.Single() );
}
}
}
|
seanterry42/Fidget.Validation.Addresses
|
test/Validation/Validators/CountryValidatorTests.cs
|
C#
|
apache-2.0
| 2,470
|
/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/usr/intr/intrrp.C $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* COPYRIGHT International Business Machines Corp. 2011,2014 */
/* */
/* Licensed under the Apache License, Version 2.0 (the "License"); */
/* you may not use this file except in compliance with the License. */
/* You may obtain a copy of the License at */
/* */
/* http://www.apache.org/licenses/LICENSE-2.0 */
/* */
/* Unless required by applicable law or agreed to in writing, software */
/* distributed under the License is distributed on an "AS IS" BASIS, */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */
/* implied. See the License for the specific language governing */
/* permissions and limitations under the License. */
/* */
/* IBM_PROLOG_END_TAG */
/**
* @file intrrp.C
* @brief Interrupt Resource Provider
*/
#include "intrrp.H"
#include <trace/interface.H>
#include <errno.h>
#include <initservice/taskargs.H>
#include <initservice/initserviceif.H>
#include <util/singleton.H>
#include <intr/intr_reasoncodes.H>
#include <sys/mmio.h>
#include <sys/mm.h>
#include <sys/misc.h>
#include <kernel/console.H>
#include <kernel/ipc.H>
#include <sys/task.h>
#include <vmmconst.h>
#include <targeting/common/targetservice.H>
#include <targeting/common/attributes.H>
#include <targeting/common/utilFilter.H>
#include <devicefw/userif.H>
#include <sys/time.h>
#include <sys/vfs.h>
#include <hwas/common/hwasCallout.H>
#include <fsi/fsiif.H>
#include <arch/ppc.H>
#define INTR_TRACE_NAME INTR_COMP_NAME
using namespace INTR;
using namespace TARGETING;
const uint32_t IntrRp::cv_PE_IRSN_COMP_SCOM_LIST[] =
{
PE0_IRSN_COMP_SCOM_ADDR,
PE1_IRSN_COMP_SCOM_ADDR,
PE2_IRSN_COMP_SCOM_ADDR
};
const uint32_t IntrRp::cv_PE_IRSN_MASK_SCOM_LIST[] =
{
PE0_IRSN_MASK_SCOM_ADDR,
PE1_IRSN_MASK_SCOM_ADDR,
PE2_IRSN_MASK_SCOM_ADDR
};
const uint32_t IntrRp::cv_PE_BAR_SCOM_LIST[] =
{
PE0_BAREN_SCOM_ADDR,
PE1_BAREN_SCOM_ADDR,
PE2_BAREN_SCOM_ADDR
};
trace_desc_t * g_trac_intr = NULL;
TRAC_INIT(&g_trac_intr, INTR_TRACE_NAME, 16*KILOBYTE, TRACE::BUFFER_SLOW);
/**
* setup _start and handle barrier
*/
TASK_ENTRY_MACRO( IntrRp::init );
/**
* @brief Utility function to get the list of enabled threads
* @return Bitstring of enabled threads
*/
uint64_t get_enabled_threads( void )
{
TARGETING::Target* sys = NULL;
TARGETING::targetService().getTopLevelTarget(sys);
assert( sys != NULL );
uint64_t en_threads = sys->getAttr<TARGETING::ATTR_ENABLED_THREADS>();
if( en_threads == 0 )
{
// Read the scratch reg that the SBE setup
// Enabled threads are listed as a bitstring in bits 16:23
// A value of zero means the SBE hasn't set them up yet
// Loop for 1 sec (1000 x 1 msec) for this value to be set
uint64_t loop_count = 0;
const uint64_t LOOP_MAX = 1000;
while( (en_threads == 0) && (loop_count < LOOP_MAX) )
{
en_threads = mmio_scratch_read(MMIO_SCRATCH_AVP_THREADS);
if( en_threads == 0 )
{
// Sleep if value has not been set
nanosleep(0,NS_PER_MSEC); // 1 msec
}
// Update the counter
loop_count++;
}
// If LOOP_MAX reached, CRIT_ASSERT
if ( unlikely(loop_count == LOOP_MAX) )
{
TRACFCOMP( g_trac_intr,"SBE Didn't Set Active Threads");
crit_assert(0);
}
else
{
en_threads = en_threads << 16; //left-justify the threads
TRACFCOMP( g_trac_intr,
"Enabled Threads = %.16X",
en_threads );
sys->setAttr<TARGETING::ATTR_ENABLED_THREADS>(en_threads);
}
}
TRACDCOMP( g_trac_intr, "en_threads=%.16X", en_threads );
return en_threads;
}
void IntrRp::init( errlHndl_t &io_errlHndl_t )
{
errlHndl_t err = NULL;
err = Singleton<IntrRp>::instance()._init();
// pass task error back to parent
io_errlHndl_t = err ;
}
// ICPBAR = INTP.ICP_BAR[0:25] in P8 = 0x3FFFF800 + (8*node) + procPos
// P8 Scom address = 0x020109c9
//
// BaseAddress P8:
// BA[14:43] = ICPBAR (30 bits)
// BA[45:48] = coreID (1-6,9-14) (12 cores)
// BA[49:51] = thread (0-7)
//
// BA+0 = XIRR (poll - Read/Write has no side effects))
// BA+4 = XIRR (Read locks HW, Write -> EOI to HW))
// BA+12 = MFRR (1 byte)
// BA+16 = LINKA (4 bytes)
// BA+20 = LINKB (4 bytes)
// BA+24 = LINKC (4 bytes)
errlHndl_t IntrRp::_init()
{
errlHndl_t err = NULL;
// get the PIR
// Which ever cpu core this is running on is the MASTER cpu
// Make master thread 0
uint32_t cpuid = task_getcpuid();
iv_masterCpu = cpuid;
iv_masterCpu.threadId = 0;
TRACFCOMP(g_trac_intr,"Master cpu node[%d], chip[%d], core[%d], thread[%d]",
iv_masterCpu.nodeId, iv_masterCpu.chipId, iv_masterCpu.coreId,
iv_masterCpu.threadId);
// The base realAddr is the base address for the whole system.
// Therefore the realAddr must be based on the processor
// that would have the lowest BAR value in the system,
// whether it exists or not. In this case n0p0
TARGETING::Target* procTarget = NULL;
TARGETING::targetService().masterProcChipTargetHandle( procTarget );
uint64_t barValue = 0;
barValue = procTarget->getAttr<TARGETING::ATTR_INTP_BASE_ADDR>();
// Mask off node & chip id to get base address
uint64_t realAddr = barValue & ICPBAR_BASE_ADDRESS_MASK;
TRACFCOMP(g_trac_intr,"INTR: realAddr = %lx",realAddr);
// VADDR_SIZE is 1MB per chip - max 32 -> 32MB
iv_baseAddr = reinterpret_cast<uint64_t>
(mmio_dev_map(reinterpret_cast<void*>(realAddr),THIRTYTWO_MB));
TRACFCOMP(g_trac_intr,"INTR: vAddr = %lx",iv_baseAddr);
// Set up the IPC message Data area
TARGETING::Target * sys = NULL;
TARGETING::targetService().getTopLevelTarget( sys );
assert(sys != NULL);
uint64_t hrmor_base =
sys->getAttr<TARGETING::ATTR_HB_HRMOR_NODAL_BASE>();
KernelIpc::ipc_data_area.pir = iv_masterCpu.word;
KernelIpc::ipc_data_area.hrmor_base = hrmor_base;
KernelIpc::ipc_data_area.msg_queue_id = IPC_DATA_AREA_CLEAR;
// Set the BAR scom reg
err = setBAR(procTarget,iv_masterCpu);
if(!err)
{
err = checkAddress(iv_baseAddr);
}
if(!err)
{
uint8_t is_mpipl = 0;
TARGETING::Target * sys = NULL;
TARGETING::targetService().getTopLevelTarget(sys);
if(sys &&
sys->tryGetAttr<TARGETING::ATTR_IS_MPIPL_HB>(is_mpipl) &&
is_mpipl)
{
TRACFCOMP(g_trac_intr,"Disable interupts for MPIPL");
err = hw_disableIntrMpIpl();
if(err)
{
errlCommit(err,INTR_COMP_ID);
err = NULL;
}
}
// Set up the interrupt provider registers
// NOTE: It's only possible to set up the master core at this point.
//
// Set up link registers to forward all intrpts to master cpu.
//
// There is one register set per cpu thread.
uint64_t max_threads = cpu_thread_count();
uint64_t en_threads = get_enabled_threads();
PIR_t pir = iv_masterCpu;
for(size_t thread = 0; thread < max_threads; ++thread)
{
// Skip threads that we shouldn't be starting
if( !(en_threads & (0x8000000000000000>>thread)) )
{
TRACDCOMP(g_trac_intr,
"IntrRp::_init: Skipping thread %d : en_threads=%X",
thread,en_threads);
continue;
}
pir.threadId = thread;
initInterruptPresenter(pir);
}
// Get the kernel msg queue for ext intr
// Create a task to handle the messages
iv_msgQ = msg_q_create();
msg_intr_q_register(iv_msgQ, realAddr);
task_create(IntrRp::msg_handler, NULL);
// Register event to be called on shutdown
INITSERVICE::registerShutdownEvent(iv_msgQ,
MSG_INTR_SHUTDOWN,
INITSERVICE::INTR_PRIORITY);
}
if(!err)
{
// Enable PSI to present interrupts
err = initIRSCReg(procTarget);
}
return err;
}
errlHndl_t IntrRp::enableInterrupts()
{
errlHndl_t err = NULL;
// Enable the interrupt on master processor core, thread 0
uint64_t baseAddr = iv_baseAddr + cpuOffsetAddr(iv_masterCpu);
err = checkAddress(baseAddr);
if(!err)
{
uint8_t * cppr = reinterpret_cast<uint8_t*>(baseAddr+CPPR_OFFSET);
*cppr = 0xff;
}
return err;
}
errlHndl_t IntrRp::disableInterrupts()
{
errlHndl_t err = NULL;
// Disable the interrupt on master processor core, thread 0
uint64_t baseAddr = iv_baseAddr + cpuOffsetAddr(iv_masterCpu);
err = checkAddress(baseAddr);
if(!err)
{
uint8_t * cppr = reinterpret_cast<uint8_t*>(baseAddr+CPPR_OFFSET);
*cppr = 0;
}
return err;
}
/**
* Helper function to start the messge handler
*/
void* IntrRp::msg_handler(void * unused)
{
Singleton<IntrRp>::instance().msgHandler();
return NULL;
}
void IntrRp::msgHandler()
{
while(1)
{
msg_t* msg = msg_wait(iv_msgQ); // wait for interrupt msg
switch(msg->type)
{
case MSG_INTR_EXTERN:
{
ext_intr_t type = NO_INTERRUPT;
// xirr was read by interrupt message handler.
// Passed in as upper word of data[0]
uint32_t xirr = static_cast<uint32_t>(msg->data[0]>>32);
// data[0] (lower word) has the PIR
uint64_t l_data0 = (msg->data[0] & 0xFFFFFFFF);
PIR_t pir = static_cast<PIR_t>(l_data0);
uint64_t baseAddr = iv_baseAddr + cpuOffsetAddr(pir);
uint32_t * xirrAddress =
reinterpret_cast<uint32_t*>(baseAddr + XIRR_OFFSET);
// type = XISR = XIRR[8:31]
// priority = XIRR[0:7]
// Use the XISR as the type (for now)
type = static_cast<ext_intr_t>(xirr & XISR_MASK);
TRACFCOMP(g_trac_intr,
"External Interrupt received. XIRR=%x, PIR=%x",
xirr,pir.word);
// Acknowlege msg
msg->data[1] = 0;
msg_respond(iv_msgQ, msg);
Registry_t::iterator r = iv_registry.find(type);
if(r != iv_registry.end() &&
type != INTERPROC_XISR) //handle IPI after EOI, not here
{
msg_q_t msgQ = r->second.msgQ;
msg_t * rmsg = msg_allocate();
rmsg->type = r->second.msgType;
rmsg->data[0] = type; // interrupt type
rmsg->data[1] = 0;
rmsg->extra_data = NULL;
int rc = msg_sendrecv(msgQ,rmsg);
if(rc)
{
TRACFCOMP(g_trac_intr,ERR_MRK
"External Interrupt received type = %d, "
"but could not send message to registered"
" handler. Ignoring it. rc = %d",
(uint32_t) type, rc);
}
msg_free(rmsg);
}
else if (type == INTERPROC_XISR)
{
// Ignore "spurious" IPIs (handled below).
// Note that we could get an INTERPROC interrupt
// and handle it through the above registration list
// as well. This is to catch the case where no one
// has registered for an IPI.
}
else // no queue registered for this interrupt type
{
// Throw it away for now.
TRACFCOMP(g_trac_intr,ERR_MRK
"External Interrupt received type = %d, but "
"nothing registered to handle it. "
"Ignoring it.",
(uint32_t)type);
}
// Handle IPIs special since they're used for waking up
// cores and have special clearing requirements.
if (type == INTERPROC_XISR)
{
// Clear IPI request.
volatile uint8_t * mfrr =
reinterpret_cast<uint8_t*>(baseAddr + MFRR_OFFSET);
TRACFCOMP( g_trac_intr,"mfrr = %x",*mfrr);
(*mfrr) = 0xff;
eieio(); // Force mfrr clear before xirr EIO.
// Deal with pending IPIs.
PIR_t core_pir = pir; core_pir.threadId = 0;
if (iv_ipisPending.count(core_pir))
{
TRACFCOMP(g_trac_intr,INFO_MRK
"IPI wakeup received for %d", pir.word);
IPI_Info_t& ipiInfo = iv_ipisPending[core_pir];
ipiInfo.first &=
~(0x8000000000000000 >> pir.threadId);
if (0 == ipiInfo.first)
{
msg_t* ipiMsg = ipiInfo.second;
iv_ipisPending.erase(core_pir);
ipiMsg->data[1] = 0;
msg_respond(iv_msgQ, ipiMsg);
}
else
{
TRACDCOMP(g_trac_intr,INFO_MRK
"IPI still pending for %x",
ipiInfo.first);
}
}
}
// Writing the XIRR with the same value read earlier
// tells the interrupt presenter hardware to signal an EOI.
xirr |= CPPR_MASK; //set all CPPR bits - allow any INTR
*xirrAddress = xirr;
TRACDCOMP(g_trac_intr,
"EOI issued. XIRR=%x, PIR=%x",
xirr,pir);
// Now handle any IPC messages
if (type == INTERPROC_XISR)
{
// If something is registered for IPIs and
// it has not already been handled then handle
if(r != iv_registry.end() &&
KernelIpc::ipc_data_area.msg_queue_id !=
IPC_DATA_AREA_READ)
{
msg_q_t msgQ = r->second.msgQ;
msg_t * rmsg = msg_allocate();
rmsg->type = r->second.msgType;
rmsg->data[0] = type; // interrupt type
rmsg->data[1] = 0;
rmsg->extra_data = NULL;
int rc = msg_sendrecv(msgQ,rmsg);
if(rc)
{
TRACFCOMP(g_trac_intr,ERR_MRK
"IPI Interrupt received, but could "
"not send message to the registered "
"handler. Ignoring it. rc = %d",
rc);
}
msg_free(rmsg);
}
if(KernelIpc::ipc_data_area.msg_queue_id ==
IPC_DATA_AREA_READ)
{
KernelIpc::ipc_data_area.msg_queue_id =
IPC_DATA_AREA_CLEAR;
}
}
}
break;
case MSG_INTR_REGISTER_MSGQ:
{
msg_q_t l_msgQ = reinterpret_cast<msg_q_t>(msg->data[0]);
uint64_t l_type = msg->data[1];
ISNvalue_t l_intr_type = static_cast<ISNvalue_t>
(l_type & 0xFFFF);
errlHndl_t err = registerInterruptISN(l_msgQ,l_type >> 32,
l_intr_type);
if(!err)
{
err = initXIVR(l_intr_type, true);
}
msg->data[1] = reinterpret_cast<uint64_t>(err);
msg_respond(iv_msgQ,msg);
}
break;
case MSG_INTR_UNREGISTER_MSGQ:
{
TRACFCOMP(g_trac_intr,
"INTR remove registration of interrupt type = 0x%lx",
msg->data[0]);
ISNvalue_t l_type = static_cast<ISNvalue_t>(msg->data[0]);
msg_q_t msgQ = unregisterInterruptISN(l_type);
if(msgQ)
{
//shouldn't get an error since we found a queue
//Just commit it
errlHndl_t err = initXIVR(l_type, false);
if(err)
{
errlCommit(err,INTR_COMP_ID);
}
}
msg->data[1] = reinterpret_cast<uint64_t>(msgQ);
TRACDCOMP(g_trac_intr,
"UNREG: msgQ = 0x%lx",
msg->data[1]);
msg_respond(iv_msgQ,msg);
}
break;
case MSG_INTR_ENABLE:
{
errlHndl_t err = enableInterrupts();
msg->data[1] = reinterpret_cast<uint64_t>(err);
msg_respond(iv_msgQ,msg);
}
break;
case MSG_INTR_DISABLE:
{
errlHndl_t err =disableInterrupts();
msg->data[1] = reinterpret_cast<uint64_t>(err);
msg_respond(iv_msgQ,msg);
}
break;
// Called when a new cpu becomes active other than the master
// Expect a call for each new core
case MSG_INTR_ADD_CPU:
{
PIR_t pir = msg->data[1];
pir.threadId = 0;
iv_cpuList.push_back(pir);
TRACFCOMP(g_trac_intr,"Add CPU node[%d], chip[%d],"
"core[%d], thread[%d]",
pir.nodeId, pir.chipId, pir.coreId,
pir.threadId);
size_t threads = cpu_thread_count();
uint64_t en_threads = get_enabled_threads();
iv_ipisPending[pir] = IPI_Info_t(en_threads, msg);
for(size_t thread = 0; thread < threads; ++thread)
{
// Skip threads that we shouldn't be starting
if( !(en_threads & (0x8000000000000000>>thread)) )
{
TRACDCOMP(g_trac_intr,"MSG_INTR_ADD_CPU: Skipping thread %d",thread);
continue;
}
pir.threadId = thread;
initInterruptPresenter(pir);
sendIPI(pir);
}
pir.threadId = 0;
task_create(handleCpuTimeout,
reinterpret_cast<void*>(pir.word));
}
break;
case MSG_INTR_ADD_CPU_TIMEOUT:
{
PIR_t pir = msg->data[0];
size_t count = msg->data[1];
if(iv_ipisPending.count(pir))
{
if (count < CPU_WAKEUP_INTERVAL_COUNT)
{
TRACDCOMP(g_trac_intr,
INFO_MRK "Cpu wakeup pending on %x",
pir.word);
// Tell child thread to retry.
msg->data[1] = EAGAIN;
}
else // Timed out.
{
TRACFCOMP(g_trac_intr,
ERR_MRK "Cpu wakeup timeout on %x",
pir.word);
// Tell child thread to exit.
msg->data[1] = 0;
// Get saved thread info.
IPI_Info_t& ipiInfo = iv_ipisPending[pir];
msg_t* ipiMsg = ipiInfo.second;
iv_ipisPending.erase(pir);
// Respond to waiting thread with ETIME.
ipiMsg->data[1] = -ETIME;
msg_respond(iv_msgQ, ipiMsg);
}
}
else // Ended successfully.
{
TRACDCOMP(g_trac_intr,
INFO_MRK "Cpu wakeup completed on %x",
pir.word);
// Tell child thread to exit.
msg->data[1] = 0;
}
msg_respond(iv_msgQ, msg);
}
break;
case MSG_INTR_ENABLE_PSI_INTR:
{
TARGETING::Target * target =
reinterpret_cast<TARGETING::Target *>(msg->data[0]);
errlHndl_t err = initIRSCReg(target);
msg->data[1] = reinterpret_cast<uint64_t>(err);
msg_respond(iv_msgQ,msg);
}
break;
case MSG_INTR_ISSUE_SBE_MBOX_WA:
{
//The SBE IPI injection on master winkle wakeup
//can clobber a pending mailbox interrupt in the ICP
//To workaround need to issue EOI on mailbox. If
//mbx intr is not hot this does nothing, if it is
//then the EOI will cause intr to be represented
//This is safe on FSPless since the PSI intr are
//always setup on master chip
uint64_t baseAddr = iv_baseAddr +
cpuOffsetAddr(iv_masterCpu);
uint32_t * xirrAddress =
reinterpret_cast<uint32_t*>(baseAddr + XIRR_OFFSET);
//Generate the mailbox IRSN for this node
uint32_t l_irsn = makeXISR(iv_masterCpu, ISN_FSI);
l_irsn |= CPPR_MASK; //set all CPPR bits - allow any INTR
TRACFCOMP(g_trac_intr,
"MBX SBE WA Issue EOI to %x",l_irsn);
*xirrAddress = l_irsn; //Issue EOI
// Acknowlege msg
msg->data[1] = 0;
msg_respond(iv_msgQ, msg);
}
break;
case MSG_INTR_SHUTDOWN:
{
TRACFCOMP(g_trac_intr,"Shutdown event received");
shutDown(msg->data[0]);
msg_respond(iv_msgQ, msg);
}
break;
case MSG_INTR_ADD_HBNODE: // node info for mpipl
{
errlHndl_t err = addHbNodeToMpiplSyncArea(msg->data[0]);
if(err)
{
errlCommit(err,INTR_COMP_ID);
}
msg_free(msg); // async message
}
break;
default:
msg->data[1] = -EINVAL;
msg_respond(iv_msgQ, msg);
}
}
}
errlHndl_t IntrRp::setBAR(TARGETING::Target * i_target,
const PIR_t i_pir)
{
errlHndl_t err = NULL;
uint64_t barValue = 0;
barValue = i_target->getAttr<TARGETING::ATTR_INTP_BASE_ADDR>();
barValue <<= 14;
barValue |= 1ULL << (63 - ICPBAR_EN);
TRACFCOMP(g_trac_intr,"INTR: Target %p. ICPBAR value: 0x%016lx",
i_target,barValue);
uint64_t size = sizeof(barValue);
err = deviceWrite(i_target,
&barValue,
size,
DEVICE_SCOM_ADDRESS(ICPBAR_SCOM_ADDR));
if(err)
{
TRACFCOMP(g_trac_intr,ERR_MRK"Unable to set IPCBAR");
}
return err;
}
errlHndl_t IntrRp::getPsiIRSN(TARGETING::Target * i_target,
uint32_t& o_irsn, uint32_t& o_num)
{
errlHndl_t err = NULL;
// Setup PHBISR
// EN.TPC.PSIHB.PSIHB_ISRN_REG set to 0x00030003FFFF0000
PSIHB_ISRN_REG_t reg;
size_t scom_len = sizeof(uint64_t);
o_num = ISN_HOST; //Hardcoded based on HB knowledge of HW
do{
err = deviceRead
( i_target,
®,
scom_len,
DEVICE_SCOM_ADDRESS(PSIHB_ISRN_REG_t::PSIHB_ISRN_REG));
if(err)
{
break;
}
//only calc IRSN if downstream interrupts are enabled
o_irsn = 0;
if(reg.die == 1) //downstream interrupt enable = 1
{
o_irsn = reg.irsn & reg.mask;
}
}while(0);
TRACFCOMP(g_trac_intr,"PSIHB_ISRN: 0x%x",o_irsn);
return err;
}
errlHndl_t IntrRp::getNxIRSN(TARGETING::Target * i_target,
uint32_t& o_irsn, uint32_t& o_num)
{
errlHndl_t err = NULL;
size_t scom_len = sizeof(uint64_t);
uint64_t reg = 0x0;
do{
err = deviceRead
( i_target,
®,
scom_len,
DEVICE_SCOM_ADDRESS(NX_BUID_SCOM_ADDR));
if(err)
{
break;
}
//only calc IRSN if downstream interrupts are enabled
o_irsn = 0;
if(reg &(1ull << (63-NX_BUID_ENABLE))) //reg has NX_BUID_ENABLE set
{
uint32_t l_mask = ((static_cast<uint32_t>(reg >> NX_IRSN_MASK_SHIFT)
& NX_IRSN_MASK_MASK) | NX_IRSN_UPPER_MASK);
o_irsn = ((static_cast<uint32_t>(reg >> NX_IRSN_COMP_SHIFT)
& IRSN_COMP_MASK) & l_mask);
//To get the number of interrupts, we need to "count" the 0 bits
//cheat by extending mask to FFF8 + mask, then invert and add 1
o_num = (~((~IRSN_COMP_MASK) | l_mask)) +1;
}
}while(0);
TRACFCOMP(g_trac_intr,"NX_ISRN: 0x%x, num: 0x%x",o_irsn, o_num);
return err;
}
errlHndl_t IntrRp::initIRSCReg(TARGETING::Target * i_target)
{
errlHndl_t err = NULL;
// Only do once for each proc chip
if(std::find(iv_chipList.begin(),iv_chipList.end(),i_target) ==
iv_chipList.end())
{
uint8_t chip = 0;
uint8_t node = 0;
node = i_target->getAttr<ATTR_FABRIC_NODE_ID>();
chip = i_target->getAttr<ATTR_FABRIC_CHIP_ID>();
size_t scom_len = sizeof(uint64_t);
// Mask off interrupts from isn's on this target
// This also sets the source isn and PIR destination
// such that if an interrupt is pending when when the ISRN
// is written, simics get the right destination for the
// interrupt. err is from deviceWrite(...)
err = maskXIVR(i_target);
if(!err)
{
// Setup PHBISR
// EN.TPC.PSIHB.PSIHB_ISRN_REG set to 0x00030003FFFF0000
PSIHB_ISRN_REG_t reg;
PIR_t pir(0);
pir.nodeId = node;
pir.chipId = chip;
// IRSN must be unique for each processor chip
reg.irsn = makeXISR(pir,0);
reg.die = PSIHB_ISRN_REG_t::ENABLE;
reg.uie = PSIHB_ISRN_REG_t::ENABLE;
reg.mask = PSIHB_ISRN_REG_t::IRSN_MASK;
TRACFCOMP(g_trac_intr,"PSIHB_ISRN_REG: 0x%016lx",reg.d64);
err = deviceWrite
( i_target,
®,
scom_len,
DEVICE_SCOM_ADDRESS(PSIHB_ISRN_REG_t::PSIHB_ISRN_REG));
}
if(!err)
{
iv_chipList.push_back(i_target);
}
}
return err;
}
errlHndl_t IntrRp::initXIVR(enum ISNvalue_t i_isn, bool i_enable)
{
errlHndl_t err = NULL;
size_t scom_len = sizeof(uint64_t);
uint64_t scom_addr = 0;
//Don't do any of this for ISN_INTERPROC
if(ISN_INTERPROC != i_isn)
{
//Setup the XIVR register
PsiHbXivr xivr;
PIR_t pir = intrDestCpuId();
xivr.pir = pir.word;
xivr.source = i_isn;
switch(i_isn)
{
case ISN_PSI:
xivr.priority = PsiHbXivr::PSI_PRIO;
scom_addr = PsiHbXivr::PSI_XIVR_ADRR;
break;
case ISN_OCC:
xivr.priority = PsiHbXivr::OCC_PRIO;
scom_addr = PsiHbXivr::OCC_XIVR_ADRR;
break;
case ISN_FSI: //FSP_MAILBOX
xivr.priority = PsiHbXivr::FSI_PRIO;
scom_addr = PsiHbXivr::FSI_XIVR_ADRR;
break;
case ISN_LPC:
xivr.priority = PsiHbXivr::LPC_PRIO;
scom_addr = PsiHbXivr::LPC_XIVR_ADRR;
break;
case ISN_LCL_ERR:
xivr.priority = PsiHbXivr::LCL_ERR_PRIO;
scom_addr = PsiHbXivr::LCL_ERR_XIVR_ADDR;
break;
case ISN_HOST:
xivr.priority = PsiHbXivr::HOST_PRIO;
scom_addr = PsiHbXivr::HOST_XIVR_ADRR;
break;
default: //Unsupported ISN
TRACFCOMP(g_trac_intr,"Unsupported ISN: 0x%02x",i_isn);
/*@ errorlog tag
* @errortype ERRL_SEV_INFORMATIONAL
* @moduleid INTR::MOD_INTR_INIT_XIVR
* @reasoncode INTR::RC_BAD_ISN
* @userdata1 Interrupt type to register
* @userdata2 0
*
* @devdesc Unsupported ISN Requested
*
*/
err = new ERRORLOG::ErrlEntry
(
ERRORLOG::ERRL_SEV_INFORMATIONAL, // severity
INTR::MOD_INTR_INIT_XIVR, // moduleid
INTR::RC_BAD_ISN, // reason code
static_cast<uint64_t>(i_isn),
0
);
}
// Init the XIVR on all chips we have setup
// Note that this doesn't handle chips getting added midstream,
// But the current use case only has FSIMbox (1 chip) and
// ATTN (all chips) at stable points in the IPL
if(!err)
{
if(i_enable)
{
iv_isnList.push_back(i_isn);
}
else
{
xivr.priority = PsiHbXivr::PRIO_DISABLED;
//Remove from isn list
ISNList_t::iterator itr = std::find(iv_isnList.begin(),
iv_isnList.end(),
i_isn);
if(itr != iv_isnList.end())
{
iv_isnList.erase(itr);
}
}
for(ChipList_t::iterator target_itr = iv_chipList.begin();
target_itr != iv_chipList.end(); ++target_itr)
{
err = deviceWrite
(*target_itr,
&xivr,
scom_len,
DEVICE_SCOM_ADDRESS(scom_addr));
if(err)
{
break;
}
}
}
}
return err;
}
//----------------------------------------------------------------------------
// Set priority highest (disabled) ,but with valid PIR
errlHndl_t IntrRp::maskXIVR(TARGETING::Target *i_target)
{
struct XIVR_INFO
{
ISNvalue_t isn:8;
uint32_t addr;
};
static const XIVR_INFO xivr_info[] =
{
{ISN_PSI, PsiHbXivr::PSI_XIVR_ADRR},
{ISN_OCC, PsiHbXivr::OCC_XIVR_ADRR},
{ISN_FSI, PsiHbXivr::FSI_XIVR_ADRR},
{ISN_LPC, PsiHbXivr::LPC_XIVR_ADRR},
{ISN_LCL_ERR, PsiHbXivr::LCL_ERR_XIVR_ADDR},
{ISN_HOST, PsiHbXivr::HOST_XIVR_ADRR}
};
errlHndl_t err = NULL;
size_t scom_len = sizeof(uint64_t);
PIR_t pir = intrDestCpuId();
PsiHbXivr xivr;
xivr.pir = pir.word;
xivr.priority = PsiHbXivr::PRIO_DISABLED;
for(size_t i = 0; i < sizeof(xivr_info)/sizeof(xivr_info[0]); ++i)
{
xivr.source = xivr_info[i].isn;
err = deviceWrite
(i_target,
&xivr,
scom_len,
DEVICE_SCOM_ADDRESS(xivr_info[i].addr));
if(err)
{
break;
}
}
return err;
}
//----------------------------------------------------------------------------
errlHndl_t IntrRp::registerInterruptISN(msg_q_t i_msgQ,
uint32_t i_msg_type,
ext_intr_t i_intr_type)
{
errlHndl_t err = NULL;
//INTERPROC is special -- same for all procs
if(i_intr_type == ISN_INTERPROC)
{
err = registerInterruptXISR(i_msgQ, i_msg_type,
INTERPROC_XISR);
}
else
{
//Register interrupt type on all present procs
for(ChipList_t::iterator target_itr = iv_chipList.begin();
target_itr != iv_chipList.end(); ++target_itr)
{
uint8_t chip = 0;
uint8_t node = 0;
node = (*target_itr)->getAttr<ATTR_FABRIC_NODE_ID>();
chip = (*target_itr)->getAttr<ATTR_FABRIC_CHIP_ID>();
PIR_t pir(0);
pir.nodeId = node;
pir.chipId = chip;
uint32_t l_irsn = makeXISR(pir, i_intr_type);
err = registerInterruptXISR(i_msgQ, i_msg_type, l_irsn);
if(err)
{
break;
}
}
}
return err;
}
errlHndl_t IntrRp::registerInterruptXISR(msg_q_t i_msgQ,
uint32_t i_msg_type,
ext_intr_t i_xisr)
{
errlHndl_t err = NULL;
Registry_t::iterator r = iv_registry.find(i_xisr);
if(r == iv_registry.end())
{
TRACFCOMP(g_trac_intr,"INTR::register intr type 0x%x", i_xisr);
iv_registry[i_xisr] = intr_response_t(i_msgQ,i_msg_type);
}
else
{
if(r->second.msgQ != i_msgQ)
{
/*@ errorlog tag
* @errortype ERRL_SEV_INFORMATIONAL
* @moduleid INTR::MOD_INTRRP_REGISTERINTERRUPT
* @reasoncode INTR::RC_ALREADY_REGISTERED
* @userdata1 XISR
* @userdata2 0
*
* @devdesc Interrupt type already registered
*
*/
err = new ERRORLOG::ErrlEntry
(
ERRORLOG::ERRL_SEV_INFORMATIONAL, // severity
INTR::MOD_INTRRP_REGISTERINTERRUPT, // moduleid
INTR::RC_ALREADY_REGISTERED, // reason code
i_xisr,
0
);
}
}
return err;
}
msg_q_t IntrRp::unregisterInterruptISN(ISNvalue_t i_intr_type)
{
msg_q_t msgQ = NULL;
//INTERPROC is special -- same for all procs
if(i_intr_type == ISN_INTERPROC)
{
msgQ = unregisterInterruptXISR(INTERPROC_XISR);
}
else
{
//Unregister interrupt type on all present procs
for(ChipList_t::iterator target_itr = iv_chipList.begin();
target_itr != iv_chipList.end(); ++target_itr)
{
uint8_t chip = 0;
uint8_t node = 0;
node = (*target_itr)->getAttr<ATTR_FABRIC_NODE_ID>();
chip = (*target_itr)->getAttr<ATTR_FABRIC_CHIP_ID>();
PIR_t pir(0);
pir.nodeId = node;
pir.chipId = chip;
uint32_t l_irsn = makeXISR(pir, i_intr_type);
msgQ = unregisterInterruptXISR(l_irsn);
}
}
return msgQ;
}
msg_q_t IntrRp::unregisterInterruptXISR(ext_intr_t i_xisr)
{
msg_q_t msgQ = NULL;
Registry_t::iterator r = iv_registry.find(i_xisr);
if(r != iv_registry.end())
{
msgQ = r->second.msgQ;
iv_registry.erase(r);
}
return msgQ;
}
void IntrRp::initInterruptPresenter(const PIR_t i_pir) const
{
uint64_t baseAddr = iv_baseAddr + cpuOffsetAddr(i_pir);
uint8_t * cppr =
reinterpret_cast<uint8_t*>(baseAddr + CPPR_OFFSET);
uint32_t * plinkReg =
reinterpret_cast<uint32_t *>(baseAddr + LINKA_OFFSET);
TRACDCOMP(g_trac_intr,"PIR 0x%x offset: 0x%lx",
i_pir.word,
cpuOffsetAddr(i_pir));
if(i_pir.word == iv_masterCpu.word)
{
*cppr = 0xff; // Allow all interrupts
}
else
{
// Allow Wake-up IPIs only
// link regs route non-IPIs to iv_masterCPU) anyway
// IPC IPIs are only directed at iv_masterCpu
*cppr = IPI_USR_PRIO + 1;
}
// Links are intended to be set up in rings. If an interrupt ends up
// where it started, it gets rejected by hardware.
//
// According to BOOK IV, The links regs are setup by firmware.
//
// Should be possible to link all interrupt forwarding directly to
// the master core and either make them direct (lspec = 0) or by setting
// the LOOPTRIP bit to stop the forwarding at the masterProc.
//
LinkReg_t linkReg;
linkReg.word = 0;
linkReg.loopTrip = 1; // needed?
linkReg.node = iv_masterCpu.nodeId;
linkReg.pchip= iv_masterCpu.chipId;
linkReg.pcore= iv_masterCpu.coreId;
linkReg.tspec= iv_masterCpu.threadId;
*(plinkReg) = linkReg.word;
*(plinkReg + 1) = linkReg.word;
linkReg.last = 1;
*(plinkReg + 2) = linkReg.word;
}
void IntrRp::disableInterruptPresenter(const PIR_t i_pir) const
{
uint64_t baseAddr = iv_baseAddr + cpuOffsetAddr(i_pir);
uint8_t * cppr =
reinterpret_cast<uint8_t*>(baseAddr + CPPR_OFFSET);
uint32_t * plinkReg =
reinterpret_cast<uint32_t *>(baseAddr + LINKA_OFFSET);
// non- side effect xirr register
uint32_t * xirrAddr =
reinterpret_cast<uint32_t *>(baseAddr + XIRR_RO_OFFSET);
uint32_t xirr = *xirrAddr & 0x00FFFFFF;
TRACDCOMP(g_trac_intr,"PIR 0x%x offset: 0x%lx",
i_pir.word,
cpuOffsetAddr(i_pir));
// Not sure if this will ever happen, but squawk alittle if it does
if(xirr)
{
TRACFCOMP(g_trac_intr,
ERR_MRK
"Pending interrupt found on shutdown. CpuId:0x%x XIRR:0x%x",
i_pir.word,
xirr);
}
*cppr = 0; // Set priority to most favored (off)
*plinkReg = 0; // Reset link registers - clear all forwarding
*(plinkReg + 1) = 0;
*(plinkReg + 2) = 0;
}
void IntrRp::sendIPI(const PIR_t i_pir) const
{
uint64_t baseAddr = iv_baseAddr + cpuOffsetAddr(i_pir);
volatile uint8_t * mfrr =
reinterpret_cast<uint8_t*>(baseAddr + MFRR_OFFSET);
eieio(); sync();
MAGIC_INSTRUCTION(MAGIC_SIMICS_CORESTATESAVE);
(*mfrr) = IPI_USR_PRIO;
}
errlHndl_t IntrRp::checkAddress(uint64_t i_addr)
{
errlHndl_t err = NULL;
if(i_addr < VMM_VADDR_DEVICE_SEGMENT_FIRST)
{
/*@ errorlog tag
* @errortype ERRL_SEV_INFORMATIONAL
* @moduleid INTR::MOD_INTRRP_CHECKADDRESS
* @reasoncode INTR::RC_BAD_VIRTUAL_IO_ADDRESS
* @userdata1 The bad virtual address
* @userdata2 0
*
* @devdesc The virtual address is not a valid IO address
*
*/
err = new ERRORLOG::ErrlEntry
(
ERRORLOG::ERRL_SEV_INFORMATIONAL,
INTR::MOD_INTRRP_CHECKADDRESS,
INTR::RC_BAD_VIRTUAL_IO_ADDRESS,
i_addr,
0
);
}
return err;
}
void IntrRp::shutDown(uint64_t i_status)
{
errlHndl_t err = NULL;
msg_t * rmsg = msg_allocate();
// Call everyone and say shutting down!
for(Registry_t::iterator r = iv_registry.begin();
r != iv_registry.end();
++r)
{
msg_q_t msgQ = r->second.msgQ;
rmsg->type = r->second.msgType;
rmsg->data[0] = SHUT_DOWN;
rmsg->data[1] = i_status;
rmsg->extra_data = NULL;
int rc = msg_sendrecv(msgQ,rmsg);
if(rc)
{
TRACFCOMP(g_trac_intr,ERR_MRK
"Could not send message to registered handler to Shut"
" down. Ignoring it. rc = %d",
rc);
}
}
msg_free(rmsg);
// Reset the PSI regs
// NOTE: there is nothing in the IRSN Proposal.odt document that
// specifies a procedure or order for disabling interrupts.
// @see RTC story 47105 discussion for Firmware & Hardware requirements
//
//Going to clear the XIVRs first
ISNList_t l_isnList = iv_isnList;
for(ISNList_t::iterator isnItr = l_isnList.begin();
isnItr != l_isnList.end();++isnItr)
{
//shouldn't get an error since we found a queue
//so just commit it
err = initXIVR((*isnItr), false);
if(err)
{
errlCommit(err,INTR_COMP_ID);
err = NULL;
}
}
PSIHB_ISRN_REG_t reg; //zeros self
size_t scom_len = sizeof(reg);
for(ChipList_t::iterator target_itr = iv_chipList.begin();
target_itr != iv_chipList.end(); ++target_itr)
{
err = deviceWrite
(*target_itr,
®,
scom_len,
DEVICE_SCOM_ADDRESS(PSIHB_ISRN_REG_t::PSIHB_ISRN_REG));
if(err)
{
errlCommit(err,INTR_COMP_ID);
err = NULL;
}
}
// Reset the IP hardware regiseters
iv_cpuList.push_back(iv_masterCpu);
size_t threads = cpu_thread_count();
uint64_t en_threads = get_enabled_threads();
for(CpuList_t::iterator pir_itr = iv_cpuList.begin();
pir_itr != iv_cpuList.end();
++pir_itr)
{
PIR_t pir = *pir_itr;
for(size_t thread = 0; thread < threads; ++thread)
{
// Skip threads that were never started
if( !(en_threads & (0x8000000000000000>>thread)) )
{
TRACDCOMP(g_trac_intr,"IntrRp::shutDown: Skipping thread %d",thread);
continue;
}
pir.threadId = thread;
disableInterruptPresenter(pir);
}
}
TRACFCOMP(g_trac_intr,INFO_MRK,"INTR is shutdown");
}
//----------------------------------------------------------------------------
errlHndl_t IntrRp::hw_disableRouting(TARGETING::Target * i_proc,
INTR_ROUTING_t i_rx_tx)
{
errlHndl_t err = NULL;
do
{
size_t scom_len = sizeof(uint64_t);
// PSI
PSIHB_ISRN_REG_t reg;
err = deviceRead
(
i_proc,
®,
scom_len,
DEVICE_SCOM_ADDRESS(PSIHB_ISRN_REG_t::PSIHB_ISRN_REG)
);
if(err)
{
break;
}
switch(i_rx_tx)
{
case INTR_UPSTREAM:
reg.uie = 0; //upstream interrupt enable = 0 (disable)
break;
case INTR_DOWNSTREAM:
reg.die = 0; //downstream interrupt enable = 0 (disable)
break;
}
scom_len = sizeof(uint64_t);
err = deviceWrite
(
i_proc,
®,
scom_len,
DEVICE_SCOM_ADDRESS(PSIHB_ISRN_REG_t::PSIHB_ISRN_REG)
);
if(err)
{
break;
}
for(size_t i = 0;
i < sizeof(cv_PE_BAR_SCOM_LIST)/sizeof(cv_PE_BAR_SCOM_LIST[0]);
++i)
{
uint64_t reg = 0;
scom_len = sizeof(uint64_t);
err = deviceRead
(
i_proc,
®,
scom_len,
DEVICE_SCOM_ADDRESS(cv_PE_BAR_SCOM_LIST[i])
);
if(err)
{
break;
}
switch(i_rx_tx)
{
case INTR_UPSTREAM:
// reset bit PE_IRSN_UPSTREAM
reg &= ~((1ull << (63-PE_IRSN_UPSTREAM)));
break;
case INTR_DOWNSTREAM:
// reset bit PE_IRSN_DOWNSTREAM
reg &= ~((1ull << (63-PE_IRSN_DOWNSTREAM)));
break;
}
scom_len = sizeof(uint64_t);
err = deviceWrite
(
i_proc,
®,
scom_len,
DEVICE_SCOM_ADDRESS(cv_PE_BAR_SCOM_LIST[i])
);
if(err)
{
break;
}
}
if(err)
{
break;
}
//NX has no up/down stream enable bit - just one enable bit.
//The NX should be cleared as part of an MPIPL so no
//interrupts should be pending from this unit, however
//we must allow EOIs to flow, so only disable when
//downstream is requested
if(i_rx_tx == INTR_DOWNSTREAM)
{
uint64_t reg = 0;
scom_len = sizeof(uint64_t);
err = deviceRead
(
i_proc,
®,
scom_len,
DEVICE_SCOM_ADDRESS(NX_BUID_SCOM_ADDR)
);
if(err)
{
break;
}
// reset bit NX_BUID_ENABLE
reg &= ~(1ull << (63-NX_BUID_ENABLE));
scom_len = sizeof(uint64_t);
err = deviceWrite
(
i_proc,
®,
scom_len,
DEVICE_SCOM_ADDRESS(NX_BUID_SCOM_ADDR)
);
if(err)
{
break;
}
}
} while(0);
return err;
}
//----------------------------------------------------------------------------
errlHndl_t IntrRp::hw_resetIRSNregs(TARGETING::Target * i_proc)
{
errlHndl_t err = NULL;
size_t scom_len = sizeof(uint64_t);
do
{
// PSI
PSIHB_ISRN_REG_t reg1; // zeros self
reg1.irsn -= 1; // default all '1's according to scom spec
// all other fields = 0
err = deviceWrite
(
i_proc,
®1,
scom_len,
DEVICE_SCOM_ADDRESS(PSIHB_ISRN_REG_t::PSIHB_ISRN_REG)
);
if(err)
{
break;
}
// PE
for(size_t i = 0;
i < sizeof(cv_PE_BAR_SCOM_LIST)/sizeof(cv_PE_BAR_SCOM_LIST[0]);
++i)
{
uint64_t reg = 0;
scom_len = sizeof(uint64_t);
// Note: no default value specified in scom spec - assume 0
err = deviceWrite
(
i_proc,
®,
scom_len,
DEVICE_SCOM_ADDRESS(cv_PE_IRSN_COMP_SCOM_LIST[i])
);
if(err)
{
break;
}
scom_len = sizeof(uint64_t);
// Note: no default value specified in scom spec - assume 0
err = deviceWrite
(
i_proc,
®,
scom_len,
DEVICE_SCOM_ADDRESS(cv_PE_IRSN_MASK_SCOM_LIST[i])
);
if(err)
{
break;
}
}
if(err)
{
break;
}
// NX [1:19] is BUID [20:32] mask
// No default value specified in scom spec. assume 0
uint64_t reg = 0;
scom_len = sizeof(uint64_t);
err = deviceWrite
(
i_proc,
®,
scom_len,
DEVICE_SCOM_ADDRESS(NX_BUID_SCOM_ADDR)
);
if(err)
{
break;
}
} while(0);
return err;
}
//----------------------------------------------------------------------------
errlHndl_t IntrRp::blindIssueEOIs(TARGETING::Target * i_proc)
{
errlHndl_t err = NULL;
TARGETING::TargetHandleList procCores;
getChildChiplets(procCores, i_proc, TYPE_CORE, false); //state can change
do
{
//Issue eio to IPIs first
for(TARGETING::TargetHandleList::iterator
core = procCores.begin();
core != procCores.end();
++core)
{
FABRIC_CHIP_ID_ATTR chip = i_proc->getAttr<ATTR_FABRIC_CHIP_ID>();
FABRIC_NODE_ID_ATTR node = i_proc->getAttr<ATTR_FABRIC_NODE_ID>();
CHIP_UNIT_ATTR coreId =
(*core)->getAttr<TARGETING::ATTR_CHIP_UNIT>();
PIR_t pir(0);
pir.nodeId = node;
pir.chipId = chip;
pir.coreId = coreId;
size_t threads = cpu_thread_count();
for(size_t thread = 0; thread < threads; ++thread)
{
pir.threadId = thread;
uint64_t xirrAddr = iv_baseAddr +
cpuOffsetAddr(pir);
uint32_t * xirrPtr =
reinterpret_cast<uint32_t*>(xirrAddr + XIRR_OFFSET);
uint8_t * mfrrPtr = reinterpret_cast<uint8_t*>(
xirrAddr + MFRR_OFFSET);
//need to set mfrr to 0xFF first
TRACDCOMP(g_trac_intr,"Clearing IPI to xirrPtr[%p]", xirrPtr);
*mfrrPtr = 0xFF;
*xirrPtr = 0xFF000002;
}
}
PIR_t pir(iv_masterCpu);
pir.threadId = 0;
//Can just write all EOIs to master core thread 0 XIRR
uint64_t xirrAddr = iv_baseAddr + cpuOffsetAddr(pir);
volatile uint32_t * xirrPtr =
reinterpret_cast<uint32_t*>(xirrAddr +XIRR_OFFSET);
//Issue eio to PSI logic
uint32_t l_psiBaseIsn;
uint32_t l_maxInt = 0;
err = getPsiIRSN(i_proc, l_psiBaseIsn, l_maxInt);
if(err)
{
break;
}
//Only issue if ISN is non zero (ie set)
if(l_psiBaseIsn)
{
l_psiBaseIsn |= 0xFF000000;
uint32_t l_psiMaxIsn = l_psiBaseIsn + l_maxInt;
TRACFCOMP(g_trac_intr,"Issuing EOI to PSIHB range %x - %x",
l_psiBaseIsn, l_psiMaxIsn);
for(uint32_t l_isn = l_psiBaseIsn; l_isn < l_psiMaxIsn; ++l_isn)
{
TRACDCOMP(g_trac_intr," xirrPtr[%p] xirr[%x]\n", xirrPtr, l_isn);
*xirrPtr = l_isn;
}
}
//Don't need to issue EOIs to PHBs
//since PHB ETU reset cleans them up
//Issue eio to NX logic
uint32_t l_nxBaseIsn;
err = getNxIRSN(i_proc, l_nxBaseIsn, l_maxInt);
if(err)
{
break;
}
//Only issue if ISN is non zero (ie set)
if(l_nxBaseIsn)
{
l_nxBaseIsn |= 0xFF000000;
uint32_t l_nxMaxIsn = l_nxBaseIsn + l_maxInt;
TRACFCOMP(g_trac_intr,"Issuing EOI to NX range %x - %x",
l_nxBaseIsn, l_nxMaxIsn);
for(uint32_t l_isn = l_nxBaseIsn; l_isn < l_nxMaxIsn; ++l_isn)
{
*xirrPtr = l_isn;
}
}
} while(0);
return err;
}
//----------------------------------------------------------------------------
errlHndl_t IntrRp::findProcs_Cores(TARGETING::TargetHandleList & o_procs,
TARGETING::TargetHandleList& o_cores)
{
errlHndl_t err = NULL;
do
{
//Build a list of "functional" processors. This needs to be
//done without targetting support (just blueprint) since
//on MPIPL the targeting information is obtained in
//discover_targets -- much later in the IPL.
//Since this is MPIPL we will rely on two things:
// 1) FSI will be active to present chips
// 2) The MPIPL HW bit in CFAM 2839 will be set
//force FSI to init so we can rely on slave data
err = FSI::initializeHardware();
if(err)
{
break;
}
TARGETING::TargetHandleList procChips;
TARGETING::PredicateCTM predProc( TARGETING::CLASS_CHIP,
TARGETING::TYPE_PROC );
TARGETING::TargetService& tS = TARGETING::targetService();
TARGETING::Target * sysTarget = NULL;
tS.getTopLevelTarget( sysTarget );
assert( sysTarget != NULL );
TARGETING::Target* masterProcTarget = NULL;
TARGETING::targetService().masterProcChipTargetHandle(
masterProcTarget );
tS.getAssociated( procChips,
sysTarget,
TARGETING::TargetService::CHILD,
TARGETING::TargetService::ALL,
&predProc );
for(TARGETING::TargetHandleList::iterator proc = procChips.begin();
proc != procChips.end();
++proc)
{
//if master proc -- just add it as we are running on it
if (*proc == masterProcTarget)
{
o_procs.push_back(*proc);
continue;
}
//First see if present
if(FSI::isSlavePresent(*proc))
{
TRACFCOMP(g_trac_intr,"Proc %x detected via FSI", TARGETING::get_huid(*proc));
//Second check to see if MPIPL bit is on cfam "2839" which
//Note 2839 is ecmd addressing, real address is 0x28E4 (byte)
uint64_t l_addr = 0x28E4;
uint32_t l_data = 0;
size_t l_size = sizeof(uint32_t);
err = deviceRead(*proc,
&l_data,
l_size,
DEVICE_FSI_ADDRESS(l_addr));
if (err)
{
TRACFCOMP(g_trac_intr,"Failed to read CFAM 2839 on %x",
TARGETING::get_huid(*proc));
break;
}
TRACFCOMP(g_trac_intr,"Proc %x 2839 val [%x]", TARGETING::get_huid(*proc),
l_data);
if(l_data & 0x80000000)
{
//Chip is present and functional -- add it to our list
o_procs.push_back(*proc);
//Also need to force it to use Xscom
//Note that it has to support (ie it is part of the SMP)
ScomSwitches l_switches =
(*proc)->getAttr<ATTR_SCOM_SWITCHES>();
l_switches.useFsiScom = 0;
l_switches.useXscom = 1;
(*proc)->setAttr<ATTR_SCOM_SWITCHES>(l_switches);
}
}
}
if (err)
{
break;
}
//Build up a list of all possible cores (don't care if func/present,
//just that they exist in the blueprint
TARGETING::TargetHandleList l_cores;
for(TARGETING::TargetHandleList::iterator proc = o_procs.begin();
proc != o_procs.end();
++proc)
{
l_cores.clear();
getChildChiplets(l_cores, *proc, TYPE_CORE, false);
for(TARGETING::TargetHandleList::iterator core = l_cores.begin();
core != l_cores.end();
++core)
{
o_cores.push_back(*core);
}
}
}while(0);
return err;
}
void IntrRp::allowAllInterrupts(TARGETING::Target* i_core)
{
const TARGETING::Target * proc = getParentChip(i_core);
FABRIC_CHIP_ID_ATTR chip = proc->getAttr<ATTR_FABRIC_CHIP_ID>();
FABRIC_NODE_ID_ATTR node = proc->getAttr<ATTR_FABRIC_NODE_ID>();
CHIP_UNIT_ATTR coreId = i_core->getAttr<TARGETING::ATTR_CHIP_UNIT>();
PIR_t pir(0);
pir.nodeId = node;
pir.chipId = chip;
pir.coreId = coreId;
size_t threads = cpu_thread_count();
for(size_t thread = 0; thread < threads; ++thread)
{
pir.threadId = thread;
uint64_t cpprAddr=cpuOffsetAddr(pir)+iv_baseAddr+CPPR_OFFSET;
uint8_t *cppr = reinterpret_cast<uint8_t*>(cpprAddr);
*cppr = 0xff; // allow all interrupts
}
}
void IntrRp::disableAllInterrupts(TARGETING::Target* i_core)
{
const TARGETING::Target * proc = getParentChip(i_core);
FABRIC_CHIP_ID_ATTR chip = proc->getAttr<ATTR_FABRIC_CHIP_ID>();
FABRIC_NODE_ID_ATTR node = proc->getAttr<ATTR_FABRIC_NODE_ID>();
CHIP_UNIT_ATTR coreId = i_core->getAttr<TARGETING::ATTR_CHIP_UNIT>();
PIR_t pir(0);
pir.nodeId = node;
pir.chipId = chip;
pir.coreId = coreId;
size_t threads = cpu_thread_count();
for(size_t thread = 0; thread < threads; ++thread)
{
pir.threadId = thread;
disableInterruptPresenter(pir);
}
}
void IntrRp::drainMpIplInterrupts(TARGETING::TargetHandleList & i_cores)
{
TRACFCOMP(g_trac_intr,"Drain pending interrupts");
bool interrupt_found = false;
size_t retryCount = 10;
do
{
interrupt_found = false;
nanosleep(0,1000000); // 1 ms
for(TARGETING::TargetHandleList::iterator
core = i_cores.begin();
core != i_cores.end();
++core)
{
const TARGETING::Target * proc = getParentChip(*core);
FABRIC_CHIP_ID_ATTR chip = proc->getAttr<ATTR_FABRIC_CHIP_ID>();
FABRIC_NODE_ID_ATTR node = proc->getAttr<ATTR_FABRIC_NODE_ID>();
CHIP_UNIT_ATTR coreId =
(*core)->getAttr<TARGETING::ATTR_CHIP_UNIT>();
PIR_t pir(0);
pir.nodeId = node;
pir.chipId = chip;
pir.coreId = coreId;
TRACFCOMP(g_trac_intr," n%d p%d c%d", node, chip, coreId);
size_t threads = cpu_thread_count();
for(size_t thread = 0; thread < threads; ++thread)
{
pir.threadId = thread;
uint64_t xirrAddr = iv_baseAddr +
cpuOffsetAddr(pir) + XIRR_RO_OFFSET;
volatile uint32_t * xirrPtr =
reinterpret_cast<uint32_t*>(xirrAddr);
uint32_t xirr = *xirrPtr & 0x00FFFFFF;
TRACDCOMP(g_trac_intr," xirrPtr[%p] xirr[%x]\n", xirrPtr, xirr);
if(xirr)
{
// Found pending interrupt!
interrupt_found = true;
TRACFCOMP(g_trac_intr,
ERR_MRK
"Pending interrupt found on MPIPL."
" CpuId:0x%x XIRR:0x%x",
pir.word,
xirr);
uint8_t * mfrrPtr =
reinterpret_cast<uint8_t*>(xirrAddr + MFRR_OFFSET);
// Signal EOI - read then write xirr value
++xirrPtr; // move to RW XIRR reg
volatile uint32_t xirr_rw = *xirrPtr;
//If IPI need to set mfrr to 0xFF
if(INTERPROC_XISR == xirr)
{
*mfrrPtr = 0xFF;
}
*xirrPtr = xirr_rw;
--xirrPtr; // back to RO XIRR reg
}
}
}
} while(interrupt_found == true && --retryCount != 0);
if(interrupt_found && (retryCount == 0))
{
// traces above should identify stuck interrupt
INITSERVICE::doShutdown(INTR::RC_PERSISTENT_INTERRUPTS);
}
}
errlHndl_t IntrRp::hw_disableIntrMpIpl()
{
errlHndl_t err = NULL;
TARGETING::TargetHandleList funcProc, procCores;
//Need to clear out all pending interrupts. This includes
//ones that PHYP already accepted and ones "hot" in the XIRR
//register. Must be done for all processors prior to opening
//up traffic for mailbox (since we switch the IRSN). PHYP
//can route PSI interrupts to any chip in the system so all
//must be cleaned up prior to switching
do
{
//extract the node layout for later
err = extractHbNodeInfo();
if(err)
{
break;
}
//Get the procs/cores
err = findProcs_Cores(funcProc, procCores);
if(err)
{
break;
}
//since HB will need to use PSI interrupt block, we need to
//perform the extra step of disabling FSP PSI interrupts at
//source(theoretically upstream disable should have handled,
//but it seesms to slip through somehow and doesn't get fully
//cleaned up cause we clear the XIVR
for(TARGETING::TargetHandleList::iterator proc = funcProc.begin();
(proc != funcProc.end()) && !err;
++proc)
{
uint64_t reg = PSI_FSP_INT_ENABLE;
size_t scom_len = sizeof(uint64_t);
err = deviceWrite
(
(*proc),
®,
scom_len,
DEVICE_SCOM_ADDRESS(PSI_HBCR_AND_SCOM_ADDR)
);
}
if(err)
{
break;
}
// Disable upstream intr routing on all processor chips
TRACFCOMP(g_trac_intr,"Disable upstream interrupt");
for(TARGETING::TargetHandleList::iterator proc = funcProc.begin();
(proc != funcProc.end()) && !err;
++proc)
{
// disable upstream intr routing
err = hw_disableRouting(*proc,INTR_UPSTREAM);
}
if(err)
{
break;
}
err = syncNodes(INTR_MPIPL_UPSTREAM_DISABLED);
if ( err )
{
break;
}
// Set interrupt presenter to allow all interrupts
TRACFCOMP(g_trac_intr,"Allow interrupts");
for(TARGETING::TargetHandleList::iterator
core = procCores.begin();
core != procCores.end();
++core)
{
allowAllInterrupts(*core);
}
// Now look for interrupts
drainMpIplInterrupts(procCores);
// Issue blind EOIs to all threads IPIs and to clean up stale XIRR
TRACFCOMP(g_trac_intr,"Issue blind EOIs to all ISRN and IPIs");
for(TARGETING::TargetHandleList::iterator proc = funcProc.begin();
(proc != funcProc.end()) && !err;
++proc)
{
err = blindIssueEOIs(*proc);
}
if(err)
{
break;
}
err = syncNodes(INTR_MPIPL_DRAINED);
if( err )
{
break;
}
// Disable all interrupt presenters
for(TARGETING::TargetHandleList::iterator core = procCores.begin();
core != procCores.end();
++core)
{
disableAllInterrupts(*core);
}
// disable downstream routing and clean up IRSN regs
for(TARGETING::TargetHandleList::iterator proc = funcProc.begin();
proc != funcProc.end();
++proc)
{
// disable downstream routing
err = hw_disableRouting(*proc,INTR_DOWNSTREAM);
if(err)
{
break;
}
// reset IRSN values
err = hw_resetIRSNregs(*proc);
if(err)
{
break;
}
//Now mask off all XIVRs under the PSI unit
//This prevents hot PSI mbox interrupts from flowing up to HB
//and allows PHYP to deal with them
err = maskXIVR(*proc);
if(err)
{
break;
}
}
if(err)
{
break;
}
} while(0);
return err;
}
errlHndl_t syncNodesError(void * i_p, uint64_t i_len)
{
TRACFCOMP(g_trac_intr,"Failure calling mm_block_map: phys_addr=%p",
i_p);
/*@
* @errortype ERRL_SEV_UNRECOVERABLE
* @moduleid INTR::MOD_INTR_SYNC_NODES
* @reasoncode INTR::RC_CANNOT_MAP_MEMORY
* @userdata1 physical address
* @userdata2 Block size requested
* @devdesc Error mapping in memory
*/
return new ERRORLOG::ErrlEntry
(
ERRORLOG::ERRL_SEV_UNRECOVERABLE,
INTR::MOD_INTR_SYNC_NODES,
INTR::RC_CANNOT_MAP_MEMORY,
reinterpret_cast<uint64_t>(i_p),
i_len,
true /*Add HB Software Callout*/);
}
errlHndl_t IntrRp::syncNodes(intr_mpipl_sync_t i_sync_type)
{
errlHndl_t err = NULL;
bool reported[MAX_NODES_PER_SYS] = { false,};
uint64_t hrmorBase = KernelIpc::ipc_data_area.hrmor_base;
void * node_info_ptr =
reinterpret_cast<void *>((iv_masterCpu.nodeId * hrmorBase) +
VMM_INTERNODE_PRESERVED_MEMORY_ADDR);
internode_info_t * this_node_info =
reinterpret_cast<internode_info_t *>
(mm_block_map(node_info_ptr,INTERNODE_INFO_SIZE));
do
{
if(this_node_info == NULL)
{
err = syncNodesError(this_node_info, INTERNODE_INFO_SIZE);
break;
}
if(this_node_info->eye_catcher != NODE_INFO_EYE_CATCHER)
{
TRACFCOMP(g_trac_intr, INFO_MRK
"MPIPL, but INTR node data sync area unintialized."
" Assuming single HB Intance system");
break;
}
// Map the internode data areas to a virtual address
internode_info_t * vaddr[MAX_NODES_PER_SYS];
for(uint64_t node = 0; node < MAX_NODES_PER_SYS; ++node)
{
if (node == iv_masterCpu.nodeId)
{
vaddr[node] = this_node_info;
}
else if(this_node_info->exist[node])
{
node_info_ptr =
reinterpret_cast<void *>
((node*hrmorBase)+VMM_INTERNODE_PRESERVED_MEMORY_ADDR);
internode_info_t * node_info =
reinterpret_cast<internode_info_t *>
(mm_block_map(node_info_ptr,
INTERNODE_INFO_SIZE));
if(node_info == NULL)
{
err = syncNodesError(node_info_ptr,
INTERNODE_INFO_SIZE);
break;
}
vaddr[node] = node_info;
reported[node] = false;
}
}
if (err)
{
break;
}
// This node has hit the sync point
this_node_info->mpipl_intr_sync = i_sync_type;
lwsync();
bool synched = false;
// Loop until all nodes have reached the sync point
while(synched == false)
{
synched = true;
for(uint64_t node = 0; node < MAX_NODES_PER_SYS; ++node)
{
if(this_node_info->exist[node])
{
intr_mpipl_sync_t sync_type =
vaddr[node]->mpipl_intr_sync;
if(sync_type < i_sync_type)
{
synched = false;
// Insure simics does a context switch
setThreadPriorityLow();
setThreadPriorityHigh();
}
else if(reported[node] == false)
{
reported[node] = true;
TRACFCOMP( g_trac_intr, INFO_MRK
"MPIPL node %ld reached syncpoint %d",
node, (uint32_t)i_sync_type);
}
}
}
}
isync();
for(uint64_t node = 0; node < MAX_NODES_PER_SYS; ++node)
{
if(this_node_info->exist[node])
{
// We are still using this_node_info area
// so unmap it later.
if(node != iv_masterCpu.nodeId)
{
mm_block_unmap(vaddr[node]);
}
}
}
mm_block_unmap(this_node_info);
} while(0);
return err;
}
errlHndl_t IntrRp::initializeMpiplSyncArea()
{
errlHndl_t err = NULL;
uint64_t hrmorBase = KernelIpc::ipc_data_area.hrmor_base;
void * node_info_ptr =
reinterpret_cast<void *>((iv_masterCpu.nodeId * hrmorBase) +
VMM_INTERNODE_PRESERVED_MEMORY_ADDR);
internode_info_t * this_node_info =
reinterpret_cast<internode_info_t *>
(mm_block_map(node_info_ptr,INTERNODE_INFO_SIZE));
if(this_node_info)
{
TRACFCOMP( g_trac_intr,
"MPIPL SYNC at phys %p virt %p value %lx\n",
node_info_ptr, this_node_info, NODE_INFO_EYE_CATCHER );
this_node_info->eye_catcher = NODE_INFO_EYE_CATCHER;
this_node_info->version = NODE_INFO_VERSION;
this_node_info->mpipl_intr_sync = INTR_MPIPL_SYNC_CLEAR;
for(uint64_t node = 0; node < MAX_NODES_PER_SYS; ++node)
{
if(iv_masterCpu.nodeId == node)
{
this_node_info->exist[node] = true;
}
else
{
this_node_info->exist[node] = false;
}
}
mm_block_unmap(this_node_info);
}
else
{
TRACFCOMP( g_trac_intr, "Failure calling mm_block_map : phys_addr=%p",
node_info_ptr);
/*@
* @errortype ERRL_SEV_UNRECOVERABLE
* @moduleid INTR::MOD_INTR_INIT_MPIPLAREA
* @reasoncode INTR::RC_CANNOT_MAP_MEMORY
* @userdata1 physical address
* @userdata2 Size
* @devdesc Error mapping in memory
*/
err = new ERRORLOG::ErrlEntry(
ERRORLOG::ERRL_SEV_UNRECOVERABLE,
INTR::MOD_INTR_INIT_MPIPLAREA,
INTR::RC_CANNOT_MAP_MEMORY,
reinterpret_cast<uint64_t>(node_info_ptr),
INTERNODE_INFO_SIZE,
true /*Add HB Software Callout*/);
}
return err;
}
errlHndl_t IntrRp::addHbNodeToMpiplSyncArea(uint64_t i_hbNode)
{
errlHndl_t err = NULL;
uint64_t hrmorBase = KernelIpc::ipc_data_area.hrmor_base;
void * node_info_ptr =
reinterpret_cast<void *>((iv_masterCpu.nodeId * hrmorBase) +
VMM_INTERNODE_PRESERVED_MEMORY_ADDR);
internode_info_t * this_node_info =
reinterpret_cast<internode_info_t *>
(mm_block_map(node_info_ptr,INTERNODE_INFO_SIZE));
if(this_node_info)
{
if(this_node_info->eye_catcher != NODE_INFO_EYE_CATCHER)
{
// Initialize the mutli-node area for this node.
err = initializeMpiplSyncArea();
}
this_node_info->exist[i_hbNode] = true;
this_node_info->mpipl_intr_sync = INTR_MPIPL_SYNC_CLEAR;
mm_block_unmap(this_node_info);
}
else
{
TRACFCOMP( g_trac_intr, "Failure calling mm_block_map : phys_addr=%p",
node_info_ptr);
/*@
* @errortype ERRL_SEV_UNRECOVERABLE
* @moduleid INTR::MOD_INTR_SYNC_ADDNODE
* @reasoncode INTR::RC_CANNOT_MAP_MEMORY
* @userdata1 physical address
* @userdata2 Size
* @devdesc Error mapping in memory
*/
err = new ERRORLOG::ErrlEntry(
ERRORLOG::ERRL_SEV_UNRECOVERABLE,
INTR::MOD_INTR_SYNC_ADDNODE,
INTR::RC_CANNOT_MAP_MEMORY,
reinterpret_cast<uint64_t>(node_info_ptr),
INTERNODE_INFO_SIZE,
true /*Add HB Software Callout*/);
}
return err;
}
errlHndl_t IntrRp::extractHbNodeInfo(void)
{
errlHndl_t err = NULL;
uint64_t hrmorBase = KernelIpc::ipc_data_area.hrmor_base;
TARGETING::ATTR_HB_EXISTING_IMAGE_type hb_existing_image = 0;
void * node_info_ptr =
reinterpret_cast<void *>((iv_masterCpu.nodeId * hrmorBase) +
VMM_INTERNODE_PRESERVED_MEMORY_ADDR);
internode_info_t * this_node_info =
reinterpret_cast<internode_info_t *>
(mm_block_map(node_info_ptr,INTERNODE_INFO_SIZE));
if(this_node_info)
{
if(this_node_info->eye_catcher != NODE_INFO_EYE_CATCHER)
{
TRACFCOMP(g_trac_intr, INFO_MRK
"MPIPL, but INTR node data sync area unintialized."
" Assuming single HB Intance system");
}
else //multinode
{
TARGETING::ATTR_HB_EXISTING_IMAGE_type mask = 0x1 <<
(MAX_NODES_PER_SYS -1);
for(uint64_t node = 0; node < MAX_NODES_PER_SYS; ++node)
{
//If comm area indicates node exists, add to map
if(this_node_info->exist[node])
{
hb_existing_image |= (mask >> node);
}
}
}
mm_block_unmap(this_node_info);
}
else
{
TRACFCOMP( g_trac_intr, "Failure calling mm_block_map : phys_addr=%p",
node_info_ptr);
/*@
* @errortype ERRL_SEV_UNRECOVERABLE
* @moduleid INTR::MOD_INTR_EXTRACTNODEINFO
* @reasoncode INTR::RC_CANNOT_MAP_MEMORY
* @userdata1 physical address
* @userdata2 Size
* @devdesc Error mapping in memory
*/
err = new ERRORLOG::ErrlEntry(
ERRORLOG::ERRL_SEV_UNRECOVERABLE,
INTR::MOD_INTR_EXTRACTNODEINFO,
INTR::RC_CANNOT_MAP_MEMORY,
reinterpret_cast<uint64_t>(node_info_ptr),
INTERNODE_INFO_SIZE,
true /*Add HB Software Callout*/);
}
TARGETING::Target * sys = NULL;
TARGETING::targetService().getTopLevelTarget(sys);
sys->setAttr<TARGETING::ATTR_HB_EXISTING_IMAGE>(hb_existing_image);
TRACFCOMP( g_trac_intr, "extractHbNodeInfo found map: %x", hb_existing_image);
return err;
}
//----------------------------------------------------------------------------
// External interfaces
//----------------------------------------------------------------------------
// Register a message queue with a particular intr type
errlHndl_t INTR::registerMsgQ(msg_q_t i_msgQ,
uint32_t i_msg_type,
ext_intr_t i_intr_type)
{
errlHndl_t err = NULL;
// Can't add while handling an interrupt, so
// send msg instead of direct call
msg_q_t intr_msgQ = msg_q_resolve(VFS_ROOT_MSG_INTR);
if(intr_msgQ)
{
msg_t * msg = msg_allocate();
msg->type = MSG_INTR_REGISTER_MSGQ;
msg->data[0] = reinterpret_cast<uint64_t>(i_msgQ);
msg->data[1] = static_cast<uint64_t>(i_intr_type);
msg->data[1] |= static_cast<uint64_t>(i_msg_type) << 32;
int rc = msg_sendrecv(intr_msgQ, msg);
if(!rc)
{
err = reinterpret_cast<errlHndl_t>(msg->data[1]);
}
else
{
TRACFCOMP(g_trac_intr,ERR_MRK
"INTR::registerMsgQ - msg_sendrecv failed. errno = %d",
rc);
}
msg_free(msg);
}
else
{
/*@ errorlog tag
* @errortype ERRL_SEV_INFORMATIONAL
* @moduleid INTR::MOD_INTR_REGISTER
* @reasoncode INTR::RC_REGISTRY_NOT_READY
* @userdata1 Interrupt type to register
* @userdata2 0
*
* @devdesc Interrupt resource provider not initialized yet.
*
*/
err = new ERRORLOG::ErrlEntry
(
ERRORLOG::ERRL_SEV_INFORMATIONAL, // severity
INTR::MOD_INTR_REGISTER, // moduleid
INTR::RC_REGISTRY_NOT_READY, // reason code
static_cast<uint64_t>(i_intr_type),
0
);
}
return err;
}
// Unregister message queue from interrupt handler
msg_q_t INTR::unRegisterMsgQ(ext_intr_t i_type)
{
msg_q_t msgQ = NULL;
msg_q_t intr_msgQ = msg_q_resolve(VFS_ROOT_MSG_INTR);
if(intr_msgQ)
{
msg_t * msg = msg_allocate();
msg->type = MSG_INTR_UNREGISTER_MSGQ;
msg->data[0] = static_cast<uint64_t>(i_type);
int rc = msg_sendrecv(intr_msgQ,msg);
if(!rc)
{
msgQ = reinterpret_cast<msg_q_t>(msg->data[1]);
}
else
{
TRACFCOMP(g_trac_intr,ERR_MRK
"INTR::unRegisterMsgQ - msg_sendrecv failed. errno = %d",
rc);
}
msg_free(msg);
}
return msgQ;
}
/*
* Enable hardware to report external interrupts
*/
errlHndl_t INTR::enableExternalInterrupts()
{
errlHndl_t err = NULL;
msg_q_t intr_msgQ = msg_q_resolve(VFS_ROOT_MSG_INTR);
if(intr_msgQ)
{
msg_t * msg = msg_allocate();
msg->type = MSG_INTR_ENABLE;
msg_sendrecv(intr_msgQ, msg);
err = reinterpret_cast<errlHndl_t>(msg->data[1]);
msg_free(msg);
}
else
{
/*@ errorlog tag
* @errortype ERRL_SEV_INFORMATIONAL
* @moduleid INTR::MOD_INTR_ENABLE
* @reasoncode INTR::RC_RP_NOT_INITIALIZED
* @userdata1 MSG_INTR_ENABLE
* @userdata2 0
*
* @devdesc Interrupt resource provider not initialized yet.
*
*/
err = new ERRORLOG::ErrlEntry
(
ERRORLOG::ERRL_SEV_INFORMATIONAL, // severity
INTR::MOD_INTR_ENABLE, // moduleid
INTR::RC_RP_NOT_INITIALIZED, // reason code
static_cast<uint64_t>(MSG_INTR_ENABLE),
0
);
}
return err;
}
/*
* Disable hardware from reporting external interrupts
*/
errlHndl_t INTR::disableExternalInterrupts()
{
errlHndl_t err = NULL;
// Can't disable while handling interrupt, so send msg to serialize
msg_q_t intr_msgQ = msg_q_resolve(VFS_ROOT_MSG_INTR);
if(intr_msgQ)
{
msg_t * msg = msg_allocate();
msg->type = MSG_INTR_DISABLE;
msg_sendrecv(intr_msgQ, msg);
err = reinterpret_cast<errlHndl_t>(msg->data[1]);
msg_free(msg);
}
else
{
/*@ errorlog tag
* @errortype ERRL_SEV_INFORMATIONAL
* @moduleid INTR::MOD_INTR_DISABLE
* @reasoncode INTR::RC_RP_NOT_INITIALIZED
* @userdata1 MSG_INTR_DISABLE
* @userdata2 0
*
* @devdesc Interrupt resource provider not initialized yet.
*
*/
err = new ERRORLOG::ErrlEntry
(
ERRORLOG::ERRL_SEV_INFORMATIONAL, // severity
INTR::MOD_INTR_DISABLE, // moduleid
INTR::RC_RP_NOT_INITIALIZED, // reason code
static_cast<uint64_t>(MSG_INTR_DISABLE),
0
);
}
return err;
}
errlHndl_t INTR::enablePsiIntr(TARGETING::Target * i_target)
{
errlHndl_t err = NULL;
msg_q_t intr_msgQ = msg_q_resolve(VFS_ROOT_MSG_INTR);
if(intr_msgQ)
{
msg_t * msg = msg_allocate();
msg->type = MSG_INTR_ENABLE_PSI_INTR;
msg->data[0] = reinterpret_cast<uint64_t>(i_target);
msg_sendrecv(intr_msgQ, msg);
err = reinterpret_cast<errlHndl_t>(msg->data[1]);
msg_free(msg);
}
else
{
/*@ errorlog tag
* @errortype ERRL_SEV_INFORMATIONAL
* @moduleid INTR::MOD_INTR_ENABLE_PSI_INTR
* @reasoncode INTR::RC_RP_NOT_INITIALIZED
* @userdata1 MSG_INTR_ENABLE_PSI_INTR
* @userdata2 0
*
* @devdesc Interrupt resource provider not initialized yet.
*
*/
err = new ERRORLOG::ErrlEntry
(
ERRORLOG::ERRL_SEV_INFORMATIONAL, // severity
INTR::MOD_INTR_ENABLE_PSI_INTR, // moduleid
INTR::RC_RP_NOT_INITIALIZED, // reason code
static_cast<uint64_t>(MSG_INTR_ENABLE_PSI_INTR),
0
);
}
return err;
}
uint64_t INTR::getIntpAddr(const TARGETING::Target * i_ex, uint8_t i_thread)
{
const TARGETING::Target * l_proc = getParentChip(i_ex);
uint64_t l_intB =l_proc->getAttr<TARGETING::ATTR_INTP_BASE_ADDR>();
PIR_t pir(0);
pir.nodeId = l_proc->getAttr<TARGETING::ATTR_FABRIC_NODE_ID>();
pir.chipId = l_proc->getAttr<TARGETING::ATTR_FABRIC_CHIP_ID>();
pir.coreId = i_ex->getAttr<TARGETING::ATTR_CHIP_UNIT>();
pir.threadId = i_thread;
return (l_intB+ InterruptMsgHdlr::mmio_offset(
pir.word & (InterruptMsgHdlr::P8_PIR_THREADID_MSK |
InterruptMsgHdlr::P8_PIR_COREID_MSK)));
}
void* INTR::IntrRp::handleCpuTimeout(void* _pir)
{
uint64_t pir = reinterpret_cast<uint64_t>(_pir);
task_detach();
int count = 0;
int rc = 0;
// Allocate a message to send to the RP thread.
msg_t* msg = msg_allocate();
msg->type = MSG_INTR_ADD_CPU_TIMEOUT;
msg->data[0] = pir;
msg_q_t intr_msgQ = msg_q_resolve(VFS_ROOT_MSG_INTR);
do
{
// Sleep for the right amount.
nanosleep(0, CPU_WAKEUP_INTERVAL_NS);
// Check the status with the RP thread.
msg->data[1] = count;
msg_sendrecv(intr_msgQ, msg);
// Get the status from the response message.
rc = msg->data[1];
count++;
} while(rc == EAGAIN);
msg_free(msg);
return NULL;
}
errlHndl_t INTR::addHbNode(uint64_t i_hbNode)
{
errlHndl_t err = NULL;
msg_q_t intr_msgQ = msg_q_resolve(VFS_ROOT_MSG_INTR);
TRACFCOMP( g_trac_intr,"Add node %d for MPIPL",i_hbNode);
if(intr_msgQ)
{
msg_t * msg = msg_allocate();
msg->data[0] = i_hbNode;
msg->type = MSG_INTR_ADD_HBNODE;
msg_send(intr_msgQ, msg);
}
else
{
/*@ errorlog tag
* @errortype ERRL_SEV_INFORMATIONAL
* @moduleid INTR::MOD_INTR_ADDHBNODE
* @reasoncode INTR::RC_RP_NOT_INITIALIZED
* @userdata1 MSG_INTR_ADD_HBNODE
* @userdata2 hbNode to add
*
* @devdesc Interrupt resource provider not initialized yet.
*
*/
err = new ERRORLOG::ErrlEntry
(
ERRORLOG::ERRL_SEV_INFORMATIONAL, // severity
INTR::MOD_INTR_ADDHBNODE, // moduleid
INTR::RC_RP_NOT_INITIALIZED, // reason code
static_cast<uint64_t>(MSG_INTR_ADD_HBNODE),
i_hbNode
);
}
return err;
}
|
shenki/hostboot
|
src/usr/intr/intrrp.C
|
C++
|
apache-2.0
| 86,116
|
//
// FNNewsKeyButton.h
// FourNews
//
// Created by xmg on 16/4/4.
// Copyright © 2016年 天涯海北. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface FNNewsKeyButton : UIButton
@end
|
ongnen/FourNews
|
FourNews/FourNews/Class/News/View/NewsRelative/FNNewsKeyButton.h
|
C
|
apache-2.0
| 204
|
package com.xiaogua.better.apache;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import org.apache.commons.beanutils.BasicDynaClass;
import org.apache.commons.beanutils.DynaBean;
import org.apache.commons.beanutils.DynaProperty;
import org.junit.Test;
public class TestApacheDynaBean {
@Test
public void testDynaBean() throws Exception {
DynaProperty[] props = new DynaProperty[] { new DynaProperty("address", java.util.Map.class),
new DynaProperty("firstName", String.class), new DynaProperty("lastName", String.class),
new DynaProperty("createDate", Date.class) };
BasicDynaClass dynaClass = new BasicDynaClass("employee", null, props);
DynaBean employee = dynaClass.newInstance();
employee.set("address", new HashMap<String, String>());
employee.set("firstName", "hello");
employee.set("lastName", "Flintstone");
employee.set("createDate", new Date());
System.out.println(employee.get("firstName") + "---=" + employee.get("createDate"));
DynaProperty[] propArr = employee.getDynaClass().getDynaProperties();
System.out.println(Arrays.toString(propArr));
}
}
|
oyxiaogua/JavaBasicCode
|
src/test/java/com/xiaogua/better/apache/TestApacheDynaBean.java
|
Java
|
apache-2.0
| 1,153
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.apache.skywalking.apm.plugin.spring.mvc.v4.define;
import org.apache.skywalking.apm.agent.core.plugin.interceptor.enhance.ClassInstanceMethodsEnhancePluginDefine;
public abstract class AbstractSpring4Instrumentation extends ClassInstanceMethodsEnhancePluginDefine {
public static final String WITHNESS_CLASSES = "org.springframework.web.servlet.tags.ArgumentTag";
@Override
protected final String[] witnessClasses() {
return new String[] {WITHNESS_CLASSES};
}
}
|
hanahmily/sky-walking
|
apm-sniffer/apm-sdk-plugin/spring-plugins/mvc-annotation-4.x-plugin/src/main/java/org/apache/skywalking/apm/plugin/spring/mvc/v4/define/AbstractSpring4Instrumentation.java
|
Java
|
apache-2.0
| 1,308
|
# -*- coding: utf-8 -*-
# Generated by Django 1.9 on 2015-12-12 16:07
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('tocayoapp', '0007_gender_description'),
]
operations = [
migrations.AlterField(
model_name='gender',
name='description',
field=models.CharField(max_length=15),
),
]
|
philpot/tocayo
|
tocayoproj/tocayoapp/migrations/0008_auto_20151212_1607.py
|
Python
|
apache-2.0
| 455
|
/*
* Copyright (C) 2012-2021 DuyHai DOAN
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package info.archinnov.achilles.async;
import static org.slf4j.LoggerFactory.getLogger;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;
import org.slf4j.Logger;
/**
* Default factory for executor thread
*/
public class DefaultExecutorThreadFactory implements ThreadFactory {
private static final Logger LOGGER = getLogger("achilles-default-executor");
private final AtomicInteger threadNumber = new AtomicInteger(0);
private Thread.UncaughtExceptionHandler uncaughtExceptionHandler = (t, e) ->
LOGGER.error("Uncaught asynchronous exception : " + e.getMessage(), e);
@Override
public Thread newThread(Runnable r) {
Thread thread = new Thread(r);
thread.setName("achilles-default-executor-" + threadNumber.incrementAndGet());
thread.setDaemon(true);
thread.setUncaughtExceptionHandler(uncaughtExceptionHandler);
return thread;
}
}
|
doanduyhai/Achilles
|
achilles-core/src/main/java/info/archinnov/achilles/async/DefaultExecutorThreadFactory.java
|
Java
|
apache-2.0
| 1,560
|
# Tibouchina fulvipilis var. scrobiculata Cogn. VARIETY
#### Status
SYNONYM
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null
|
mdoering/backbone
|
life/Plantae/Magnoliophyta/Magnoliopsida/Myrtales/Melastomataceae/Tibouchina/Tibouchina fulvipilis/ Syn. Tibouchina fulvipilis scrobiculata/README.md
|
Markdown
|
apache-2.0
| 202
|
@(user: Option[com.mohiva.play.silhouette.impl.User] = None,
twitterHandleForm: Form[forms.TwitterTimeLineForm.Data],
neo4jURI: String)(implicit request: RequestHeader, messages: Messages)
@import b3.inline.fieldConstructor
@main(Messages("timeLine.title"), user, neo4jURI) {
<div class="col-md-6 col-md-offset-3">
<legend>@Messages("timeLine.input.legend")</legend>
@helper.form(action = routes.TimeLineController.submit(), 'id -> "twitter-time-line-form") {
@helper.CSRF.formField
<label>@Messages("timeLine.input.nodeLabel.label")</label>
@b3.text(
twitterHandleForm("nodeLabel"),
'id -> "twitter-node-label-input",
'_hiddenLabel -> Messages("timeLine.input.nodeLabel.placeholder"),
'placeholder -> Messages("timeLine.input.nodeLabel.placeholder"),
'class -> "form-control input-lg"
)
<label>@Messages("timeLine.input.twitterHandles.label")</label>
@bootstrap3.helper.twitterHandles(
twitterHandleForm("twitterHandles"),
'id -> "twitter-handles-input",
'_hiddenLabel -> Messages("timeLine.input.twitterHandles.placeholder"),
'placeholder -> Messages("timeLine.input.twitterHandles.placeholder"),
'class -> "form-control input-lg"
)
@b3.checkbox(
twitterHandleForm("withRetweeters"),
'id -> "twitter-with-retweeters-input",
'_text -> Messages("timeLine.input.withRetweeters.label")
)
@b3.checkbox(
twitterHandleForm("withHashTagSearch"),
'id -> "twitter-with-hashtag-search-input",
'_text -> Messages("timeLine.input.withHashTagSearch.label")
)
@b3.submit('class -> "btn btn-lg btn-primary btn-block") {
@Messages("timeLine.input.submit")
}
}
</div>
}
|
Queendimimi/twitter_extractor
|
app/views/twitterTimeLineForm.scala.html
|
HTML
|
apache-2.0
| 2,040
|
package com.vmware.vim25;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for ArrayOfVirtualDeviceConfigSpec complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="ArrayOfVirtualDeviceConfigSpec">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="VirtualDeviceConfigSpec" type="{urn:vim25}VirtualDeviceConfigSpec" maxOccurs="unbounded" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "ArrayOfVirtualDeviceConfigSpec", propOrder = {
"virtualDeviceConfigSpec"
})
public class ArrayOfVirtualDeviceConfigSpec {
@XmlElement(name = "VirtualDeviceConfigSpec")
protected List<VirtualDeviceConfigSpec> virtualDeviceConfigSpec;
/**
* Gets the value of the virtualDeviceConfigSpec property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the virtualDeviceConfigSpec property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getVirtualDeviceConfigSpec().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link VirtualDeviceConfigSpec }
*
*
*/
public List<VirtualDeviceConfigSpec> getVirtualDeviceConfigSpec() {
if (virtualDeviceConfigSpec == null) {
virtualDeviceConfigSpec = new ArrayList<VirtualDeviceConfigSpec>();
}
return this.virtualDeviceConfigSpec;
}
}
|
jdgwartney/vsphere-ws
|
java/JAXWS/samples/com/vmware/vim25/ArrayOfVirtualDeviceConfigSpec.java
|
Java
|
apache-2.0
| 2,205
|
package com.vmware.vim25;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for ArrayOfDVSHealthCheckConfig complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="ArrayOfDVSHealthCheckConfig">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="DVSHealthCheckConfig" type="{urn:vim25}DVSHealthCheckConfig" maxOccurs="unbounded" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "ArrayOfDVSHealthCheckConfig", propOrder = {
"dvsHealthCheckConfig"
})
public class ArrayOfDVSHealthCheckConfig {
@XmlElement(name = "DVSHealthCheckConfig")
protected List<DVSHealthCheckConfig> dvsHealthCheckConfig;
/**
* Gets the value of the dvsHealthCheckConfig property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the dvsHealthCheckConfig property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getDVSHealthCheckConfig().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link DVSHealthCheckConfig }
*
*
*/
public List<DVSHealthCheckConfig> getDVSHealthCheckConfig() {
if (dvsHealthCheckConfig == null) {
dvsHealthCheckConfig = new ArrayList<DVSHealthCheckConfig>();
}
return this.dvsHealthCheckConfig;
}
}
|
jdgwartney/vsphere-ws
|
java/JAXWS/samples/com/vmware/vim25/ArrayOfDVSHealthCheckConfig.java
|
Java
|
apache-2.0
| 2,145
|
/*
* Copyright 2008 The Closure Compiler Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.javascript.jscomp;
import static com.google.common.truth.Truth.assertThat;
import com.google.common.collect.Multimap;
import com.google.javascript.rhino.Node;
import com.google.javascript.rhino.jstype.JSTypeNative;
import com.google.javascript.rhino.jstype.JSTypeRegistry;
import com.google.javascript.rhino.testing.BaseJSTypeTestCase;
import com.google.javascript.rhino.testing.TestErrorReporter;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.TreeSet;
/**
* Unit test for the Compiler DisambiguateProperties pass.
*
*/
public final class DisambiguatePropertiesTest extends CompilerTestCase {
private DisambiguateProperties lastPass;
private static String renameFunctionDefinition =
"/** @const */ var goog = {};\n"
+ "/** @const */ goog.reflect = {};\n"
+ "/** @return {string} */ goog.reflect.objectProperty = function(prop, obj) {};\n";
public DisambiguatePropertiesTest() {
parseTypeInfo = true;
}
@Override
protected void setUp() throws Exception {
super.setUp();
super.enableNormalize();
super.enableTypeCheck();
}
@Override
public CompilerPass getProcessor(final Compiler compiler) {
return new CompilerPass() {
@Override
public void process(Node externs, Node root) {
Map<String, CheckLevel> propertiesToErrorFor = new HashMap<>();
propertiesToErrorFor.put("foobar", CheckLevel.ERROR);
// This must be created after type checking is run as it depends on
// any mismatches found during checking.
lastPass = new DisambiguateProperties(compiler, propertiesToErrorFor);
lastPass.process(externs, root);
}
};
}
@Override
protected int getNumRepetitions() {
return 1;
}
public void testOneType1() {
String js = ""
+ "/** @constructor */ function Foo() {}\n"
+ "Foo.prototype.a = 0;\n"
+ "/** @type {Foo} */\n"
+ "var F = new Foo;\n"
+ "F.a = 0;";
testSets(js, js, "{a=[[Foo.prototype]]}");
js =
renameFunctionDefinition
+ "/** @constructor */ function Foo() {}\n"
+ "Foo.prototype.a = 0;\n"
+ "/** @type {Foo} */\n"
+ "var F = new Foo;\n"
+ "F[goog.reflect.objectProperty('a', F)] = 0;";
testSets(js, js, "{a=[[Foo.prototype]]}");
}
public void testOneType2() {
String js = ""
+ "/** @constructor */ function Foo() {}\n"
+ "Foo.prototype = {a: 0};\n"
+ "/** @type {Foo} */\n"
+ "var F = new Foo;\n"
+ "F.a = 0;";
String expected = "{a=[[Foo.prototype]]}";
testSets(js, js, expected);
js =
renameFunctionDefinition
+ "/** @constructor */ function Foo() {}\n"
+ "Foo.prototype = {a: 0};\n"
+ "/** @type {Foo} */\n"
+ "var F = new Foo;\n"
+ "F[goog.reflect.objectProperty('a', F)] = 0;";
testSets(js, js, expected);
}
public void testOneType3() {
String js = ""
+ "/** @constructor */ function Foo() {}\n"
+ "Foo.prototype = { get a() {return 0},"
+ " set a(b) {} };\n"
+ "/** @type {Foo} */\n"
+ "var F = new Foo;\n"
+ "F.a = 0;";
String expected = "{a=[[Foo.prototype]]}";
testSets(js, js, expected);
js =
renameFunctionDefinition
+ "/** @constructor */ function Foo() {}\n"
+ "Foo.prototype = { get a() {return 0},"
+ " set a(b) {} };\n"
+ "/** @type {Foo} */\n"
+ "var F = new Foo;\n"
+ "F[goog.reflect.objectProperty('a', F)] = 0;";
testSets(js, js, expected);
}
public void testOneType4() {
String js = ""
+ "/** @constructor */ function Foo() {}\n"
+ "Foo.prototype = {'a': 0};\n"
+ "/** @type {Foo} */\n"
+ "var F = new Foo;\n"
+ "F['a'] = 0;";
String expected = "{}";
testSets(js, js, expected);
}
public void testPrototypeAndInstance1() {
String js = ""
+ "/** @constructor */ function Foo() {}\n"
+ "Foo.prototype.a = 0;\n"
+ "/** @type {Foo} */\n"
+ "var F = new Foo;\n"
+ "F.a = 0;";
testSets(js, js, "{a=[[Foo.prototype]]}");
js =
""
+ "/** @constructor */ function Foo() {}\n"
+ "Foo.prototype.a = 0;\n"
+ "/** @type {Foo} */\n"
+ "var F = new Foo;\n"
+ "F.a = 0;";
testSets(js, js, "{a=[[Foo.prototype]]}");
}
public void testPrototypeAndInstance2() {
String js = ""
+ "/** @constructor @template T */ "
+ "function Foo() {"
+ " this.a = 0;"
+ "}\n"
+ "/** @type {Foo.<string>} */\n"
+ "var f1 = new Foo;\n"
+ "f1.a = 0;"
+ "/** @type {Foo.<string>} */\n"
+ "var f2 = new Foo;\n"
+ "f2.a = 0;";
testSets(js, js, "{a=[[Foo]]}");
}
public void testPrototypeAndInstance3() {
String js = ""
+ "/** @constructor */ function Foo() {}\n"
+ "Foo.prototype.a = 0;\n"
+ "new Foo().a = 0;";
testSets(js, js, "{a=[[Foo.prototype]]}");
}
public void testPrototypeAndInstance4() {
String js = ""
+ "/** @constructor @template T */ "
+ "function Foo() {}\n"
+ "Foo.prototype.a = 0;\n"
+ "/** @type {Foo.<string>} */\n"
+ "var f = new Foo;\n"
+ "f.a = 0;";
testSets(js, js, "{a=[[Foo.prototype]]}");
}
public void testTwoTypes1() {
String js = ""
+ "/** @constructor */ function Foo() {}\n"
+ "Foo.prototype.a = 0;"
+ "/** @type {Foo} */\n"
+ "var F = new Foo;\n"
+ "F.a = 0;"
+ "/** @constructor */ function Bar() {}\n"
+ "Bar.prototype.a = 0;"
+ "/** @type {Bar} */\n"
+ "var B = new Bar;\n"
+ "B.a = 0;";
String output = ""
+ "/** @constructor */function Foo(){}"
+ "Foo.prototype.Foo_prototype$a=0;"
+ "/** @type {Foo} */"
+ "var F=new Foo;"
+ "F.Foo_prototype$a=0;"
+ "/** @constructor */ function Bar(){}"
+ "Bar.prototype.Bar_prototype$a=0;"
+ "/** @type {Bar} */"
+ "var B=new Bar;"
+ "B.Bar_prototype$a=0";
testSets(js, output, "{a=[[Bar.prototype], [Foo.prototype]]}");
}
public void testTwoTypes2() {
String js = ""
+ "/** @constructor */ function Foo() {}\n"
+ "Foo.prototype = {a: 0};"
+ "/** @type {Foo} */\n"
+ "var F = new Foo;\n"
+ "F.a = 0;"
+ "/** @constructor */ function Bar() {}\n"
+ "Bar.prototype = {a: 0};"
+ "/** @type {Bar} */\n"
+ "var B = new Bar;\n"
+ "B.a = 0;";
String output = ""
+ "/** @constructor */ function Foo(){}"
+ "Foo.prototype = {Foo_prototype$a: 0};"
+ "/** @type {Foo} */"
+ "var F=new Foo;"
+ "F.Foo_prototype$a=0;"
+ "/** @constructor */ function Bar(){}"
+ "Bar.prototype = {Bar_prototype$a: 0};"
+ "/** @type {Bar} */"
+ "var B=new Bar;"
+ "B.Bar_prototype$a=0";
testSets(js, output, "{a=[[Bar.prototype], [Foo.prototype]]}");
}
public void testTwoTypes3() {
String js = ""
+ "/** @constructor */ function Foo() {}\n"
+ "Foo.prototype = { get a() {return 0},"
+ " set a(b) {} };\n"
+ "/** @type {Foo} */\n"
+ "var F = new Foo;\n"
+ "F.a = 0;"
+ "/** @constructor */ function Bar() {}\n"
+ "Bar.prototype = { get a() {return 0},"
+ " set a(b) {} };\n"
+ "/** @type {Bar} */\n"
+ "var B = new Bar;\n"
+ "B.a = 0;";
String output = ""
+ "/** @constructor */ function Foo(){}"
+ "Foo.prototype = { get Foo_prototype$a() {return 0},"
+ " set Foo_prototype$a(b) {} };\n"
+ "/** @type {Foo} */\n"
+ "var F=new Foo;"
+ "F.Foo_prototype$a=0;"
+ "/** @constructor */ function Bar(){}"
+ "Bar.prototype = { get Bar_prototype$a() {return 0},"
+ " set Bar_prototype$a(b) {} };\n"
+ "/** @type {Bar} */\n"
+ "var B=new Bar;"
+ "B.Bar_prototype$a=0";
testSets(js, output, "{a=[[Bar.prototype], [Foo.prototype]]}");
}
public void testTwoTypes4() {
String js = ""
+ "/** @constructor */ function Foo() {}\n"
+ "Foo.prototype = {a: 0};"
+ "/** @type {Foo} */\n"
+ "var F = new Foo;\n"
+ "F.a = 0;"
+ "/** @constructor */ function Bar() {}\n"
+ "Bar.prototype = {'a': 0};"
+ "/** @type {Bar} */\n"
+ "var B = new Bar;\n"
+ "B['a'] = 0;";
String output = ""
+ "/** @constructor */ function Foo(){}"
+ "Foo.prototype = {a: 0};"
+ "/** @type {Foo} */ var F=new Foo;"
+ "F.a=0;"
+ "/** @constructor */ function Bar(){}"
+ "Bar.prototype = {'a': 0};"
+ "/** @type {Bar} */ var B=new Bar;"
+ "B['a']=0";
testSets(js, output, "{a=[[Foo.prototype]]}");
}
public void testTwoTypes5() {
String js = ""
+ "/** @constructor @template T */ function Foo() { this.a = 0; }\n"
+ "/** @type {Foo<string>} */\n"
+ "var F = new Foo;\n"
+ "F.a = 0;"
+ "/** @constructor @template T */ function Bar() { this.a = 0; }\n"
+ "/** @type {Bar<string>} */\n"
+ "var B = new Bar;\n"
+ "B.a = 0;";
String output = ""
+ "/** @constructor @template T */ function Foo(){ this.Foo$a = 0; }"
+ "/** @type {Foo<string>} */"
+ "var F=new Foo;"
+ "F.Foo$a=0;"
+ "/** @constructor @template T */ function Bar(){ this.Bar$a = 0; }"
+ "/** @type {Bar<string>} */ var B=new Bar;"
+ "B.Bar$a=0";
testSets(js, output, "{a=[[Bar], [Foo]]}");
}
public void testTwoFields() {
String js = ""
+ "/** @constructor */ function Foo() {}\n"
+ "Foo.prototype.a = 0;"
+ "Foo.prototype.b = 0;"
+ "/** @type {Foo} */\n"
+ "var F = new Foo;\n"
+ "F.a = 0;"
+ "F.b = 0;";
String output = ""
+ "/** @constructor */\n"
+ "function Foo() {}\n"
+ "Foo.prototype.a=0;\n"
+ "Foo.prototype.b=0;"
+ "/** @type {Foo} */\n"
+ "var F = new Foo;\n"
+ "F.a = 0;\n"
+ "F.b = 0";
testSets(js, output, "{a=[[Foo.prototype]], b=[[Foo.prototype]]}");
}
public void testTwoSeparateFieldsTwoTypes() {
String js = ""
+ "/** @constructor */ function Foo() {}\n"
+ "Foo.prototype.a = 0;"
+ "Foo.prototype.b = 0;"
+ "/** @type {Foo} */\n"
+ "var F = new Foo;\n"
+ "F.a = 0;"
+ "F.b = 0;"
+ "/** @constructor */ function Bar() {}\n"
+ "Bar.prototype.a = 0;"
+ "Bar.prototype.b = 0;"
+ "/** @type {Bar} */\n"
+ "var B = new Bar;\n"
+ "B.a = 0;"
+ "B.b = 0;";
String output = ""
+ "/** @constructor */ function Foo(){}"
+ "Foo.prototype.Foo_prototype$a=0;"
+ "Foo.prototype.Foo_prototype$b=0;"
+ "/** @type {Foo} */ var F=new Foo;"
+ "F.Foo_prototype$a=0;"
+ "F.Foo_prototype$b=0;"
+ "/** @constructor */ function Bar(){}"
+ "Bar.prototype.Bar_prototype$a=0;"
+ "Bar.prototype.Bar_prototype$b=0;"
+ "/** @type {Bar} */ var B=new Bar;"
+ "B.Bar_prototype$a=0;"
+ "B.Bar_prototype$b=0";
testSets(js, output, "{a=[[Bar.prototype], [Foo.prototype]],"
+ " b=[[Bar.prototype], [Foo.prototype]]}");
}
public void testUnionType() {
String js = ""
+ "/** @constructor */ function Foo() {}\n"
+ "Foo.prototype.a = 0;"
+ "/** @constructor */ function Bar() {}\n"
+ "Bar.prototype.a = 0;"
+ "/** @type {Bar|Foo} */\n"
+ "var B = new Bar;\n"
+ "B.a = 0;\n"
+ "B = new Foo;\n"
+ "B.a = 0;\n"
+ "/** @constructor */ function Baz() {}\n"
+ "Baz.prototype.a = 0;\n";
testSets(js, "{a=[[Bar.prototype, Foo.prototype], [Baz.prototype]]}");
}
public void testIgnoreUnknownType() {
String js = ""
+ "/** @constructor */\n"
+ "function Foo() {}\n"
+ "Foo.prototype.blah = 3;\n"
+ "/** @type {Foo} */\n"
+ "var F = new Foo;\n"
+ "F.blah = 0;\n"
+ "var U = function() { return {} };\n"
+ "U().blah();";
String expected = ""
+ "/** @constructor */ function Foo(){}"
+ "Foo.prototype.blah=3;"
+ "/** @type {Foo} */"
+ "var F = new Foo;F.blah=0;"
+ "var U=function(){return{}};U().blah()";
testSets(js, expected, "{}");
}
public void testIgnoreUnknownType1() {
String js = ""
+ "/** @constructor */\n"
+ "function Foo() {}\n"
+ "Foo.prototype.blah = 3;\n"
+ "/** @type {Foo} */\n"
+ "var F = new Foo;\n"
+ "F.blah = 0;\n"
+ "/** @return {Object} */\n"
+ "var U = function() { return {} };\n"
+ "U().blah();";
String expected = ""
+ "/** @constructor */ function Foo(){}"
+ "Foo.prototype.blah=3;"
+ "/** @type {Foo} */ var F = new Foo;"
+ "F.blah=0;"
+ "/** @return {Object} */"
+ "var U=function(){return{}};"
+ "U().blah()";
testSets(js, expected, "{blah=[[Foo.prototype]]}");
}
public void testIgnoreUnknownType2() {
String js = ""
+ "/** @constructor */\n"
+ "function Foo() {}\n"
+ "Foo.prototype.blah = 3;\n"
+ "/** @type {Foo} */\n"
+ "var F = new Foo;\n"
+ "F.blah = 0;\n"
+ "/** @constructor */\n"
+ "function Bar() {}\n"
+ "Bar.prototype.blah = 3;\n"
+ "/** @return {Object} */\n"
+ "var U = function() { return {} };\n"
+ "U().blah();";
String expected = ""
+ "/** @constructor */ function Foo(){}"
+ "Foo.prototype.blah=3;"
+ "/** @type {Foo} */"
+ "var F = new Foo;"
+ "F.blah=0;"
+ "/** @constructor */ function Bar(){}"
+ "Bar.prototype.blah=3;"
+ "/** @return {Object} */"
+ "var U=function(){return{}};U().blah()";
testSets(js, expected, "{}");
}
public void testUnionTypeTwoFields() {
String js = ""
+ "/** @constructor */ function Foo() {}\n"
+ "Foo.prototype.a = 0;\n"
+ "Foo.prototype.b = 0;\n"
+ "/** @constructor */ function Bar() {}\n"
+ "Bar.prototype.a = 0;\n"
+ "Bar.prototype.b = 0;\n"
+ "/** @type {Foo|Bar} */\n"
+ "var B = new Bar;\n"
+ "B.a = 0;\n"
+ "B.b = 0;\n"
+ "B = new Foo;\n"
+ "/** @constructor */ function Baz() {}\n"
+ "Baz.prototype.a = 0;\n"
+ "Baz.prototype.b = 0;\n";
testSets(js, "{a=[[Bar.prototype, Foo.prototype], [Baz.prototype]],"
+ " b=[[Bar.prototype, Foo.prototype], [Baz.prototype]]}");
}
public void testCast() {
String js = ""
+ "/** @constructor */ function Foo() {}\n"
+ "Foo.prototype.a = 0;"
+ "/** @constructor */ function Bar() {}\n"
+ "Bar.prototype.a = 0;"
+ "/** @type {Foo|Bar} */\n"
+ "var F = new Foo;\n"
+ "(/** @type {Bar} */(F)).a = 0;";
String output = ""
+ "/** @constructor */ function Foo(){}\n"
+ "Foo.prototype.Foo_prototype$a=0;\n"
+ "/** @constructor */ function Bar(){}\n"
+ "Bar.prototype.Bar_prototype$a=0;\n"
+ "/** @type {Foo|Bar} */\n"
+ "var F=new Foo;\n"
+ "/** @type {Bar} */ (F).Bar_prototype$a=0;";
testSets(js, output, "{a=[[Bar.prototype], [Foo.prototype]]}");
}
public void testConstructorFields() {
String js = ""
+ "/** @constructor */\n"
+ "var Foo = function() { this.a = 0; };\n"
+ "/** @constructor */ function Bar() {}\n"
+ "Bar.prototype.a = 0;"
+ "new Foo";
String output = ""
+ "/** @constructor */ var Foo=function(){this.Foo$a=0};"
+ "/** @constructor */ function Bar(){}"
+ "Bar.prototype.Bar_prototype$a=0;"
+ "new Foo";
testSets(js, output, "{a=[[Bar.prototype], [Foo]]}");
}
public void testStaticProperty() {
String js = ""
+ "/** @constructor */ function Foo() {} \n"
+ "/** @constructor */ function Bar() {}\n"
+ "Foo.a = 0;"
+ "Bar.a = 0;";
String output = ""
+ "/** @constructor */ function Foo(){}"
+ "/** @constructor */ function Bar(){}"
+ "Foo.function__new_Foo___undefined$a = 0;"
+ "Bar.function__new_Bar___undefined$a = 0;";
testSets(js, output, "{a=[[function (new:Bar): undefined]," +
" [function (new:Foo): undefined]]}");
}
public void testSupertypeWithSameField() {
String js = ""
+ "/** @constructor */ function Foo() {}\n"
+ "Foo.prototype.a = 0;\n"
+ "/** @constructor\n* @extends {Foo} */ function Bar() {}\n"
+ "/** @override */\n"
+ "Bar.prototype.a = 0;\n"
+ "/** @type {Bar} */\n"
+ "var B = new Bar;\n"
+ "B.a = 0;"
+ "/** @constructor */ function Baz() {}\n"
+ "Baz.prototype.a = function(){};\n";
String output = ""
+ "/** @constructor */ function Foo(){}"
+ "Foo.prototype.Foo_prototype$a=0;"
+ "/** @constructor @extends {Foo} */ function Bar(){}"
+ "/** @override */"
+ "Bar.prototype.Foo_prototype$a=0;"
+ "/** @type {Bar} */"
+ "var B = new Bar;"
+ "B.Foo_prototype$a=0;"
+ "/** @constructor */ function Baz(){}Baz.prototype.Baz_prototype$a=function(){};";
testSets(js, output, "{a=[[Baz.prototype], [Foo.prototype]]}");
}
public void testScopedType() {
String js = ""
+ "var g = {};\n"
+ "/** @constructor */ g.Foo = function() {}\n"
+ "g.Foo.prototype.a = 0;"
+ "/** @constructor */ g.Bar = function() {}\n"
+ "g.Bar.prototype.a = 0;";
String output = ""
+ "var g={};"
+ "/** @constructor */ g.Foo=function(){};"
+ "g.Foo.prototype.g_Foo_prototype$a=0;"
+ "/** @constructor */ g.Bar=function(){};"
+ "g.Bar.prototype.g_Bar_prototype$a=0;";
testSets(js, output, "{a=[[g.Bar.prototype], [g.Foo.prototype]]}");
}
public void testUnresolvedType() {
// NOTE(nicksantos): This behavior seems very wrong to me.
String js = ""
+ "var g = {};"
+ "/** @constructor \n @extends {?} */ "
+ "var Foo = function() {};\n"
+ "Foo.prototype.a = 0;"
+ "/** @constructor */ var Bar = function() {};\n"
+ "Bar.prototype.a = 0;";
String output = ""
+ "var g={};"
+ "/** @constructor @extends {?} */ var Foo=function(){};"
+ "Foo.prototype.Foo_prototype$a=0;"
+ "/** @constructor */ var Bar=function(){};"
+ "Bar.prototype.Bar_prototype$a=0;";
setExpectParseWarningsThisTest();
testSets(BaseJSTypeTestCase.ALL_NATIVE_EXTERN_TYPES, js,
output, "{a=[[Bar.prototype], [Foo.prototype]]}");
}
public void testNamedType() {
String js = ""
+ "var g = {};"
+ "/** @constructor \n @extends {g.Late} */ var Foo = function() {}\n"
+ "Foo.prototype.a = 0;"
+ "/** @constructor */ var Bar = function() {}\n"
+ "Bar.prototype.a = 0;"
+ "/** @constructor */ g.Late = function() {}";
String output = ""
+ "var g={};"
+ "/** @constructor @extends {g.Late} */ var Foo=function(){};"
+ "Foo.prototype.Foo_prototype$a=0;"
+ "/** @constructor */ var Bar=function(){};"
+ "Bar.prototype.Bar_prototype$a=0;"
+ "/** @constructor */ g.Late = function(){}";
testSets(js, output, "{a=[[Bar.prototype], [Foo.prototype]]}");
}
public void testUnknownType() {
String js = ""
+ "/** @constructor */ var Foo = function() {};\n"
+ "/** @constructor */ var Bar = function() {};\n"
+ "/** @return {?} */ function fun() {}\n"
+ "Foo.prototype.a = fun();\n"
+ "fun().a;\n"
+ "Bar.prototype.a = 0;";
testSets(js, js, "{}");
}
// When objects flow to untyped code, it is the programmer's responsibility to
// use them in a type-safe way, otherwise disambiguation will be wrong.
public void testUntypedCodeWrongDisambiguation1() {
String js = ""
+ "/** @constructor */\n"
+ "function Foo() { this.p1 = 0; }\n"
+ "/** @constructor */\n"
+ "function Bar() { this.p1 = 1; }\n"
+ "var arr = [new Foo, new Bar];\n"
+ "var /** !Foo */ z = arr[1];\n"
+ "z.p1;\n";
String output = ""
+ "/** @constructor */ function Foo() { this.Foo$p1 = 0; }\n"
+ "/** @constructor */ function Bar() { this.Bar$p1 = 1; }\n"
+ "var arr = [new Foo, new Bar];\n"
+ "var /** !Foo */z = arr[1];\n"
+ "z.Foo$p1;\n";
testSets(js, output, "{p1=[[Bar], [Foo]]}");
}
// When objects flow to untyped code, it is the programmer's responsibility to
// use them in a type-safe way, otherwise disambiguation will be wrong.
public void testUntypedCodeWrongDisambiguation2() {
String js = ""
+ "/** @constructor */\n"
+ "function Foo() { this.p1 = 0; }\n"
+ "/** @constructor */\n"
+ "function Bar() { this.p1 = 1; }\n"
+ "function select(cond, x, y) { return cond ? x : y; }\n"
+ "/**\n"
+ " * @param {!Foo} x\n"
+ " * @param {!Bar} y\n"
+ " * @return {!Foo}\n"
+ " */\n"
+ "function f(x, y) {\n"
+ " var /** !Foo */ z = select(false, x, y);\n"
+ " return z;\n"
+ "}\n"
+ "f(new Foo, new Bar).p1;\n";
String output = ""
+ "/** @constructor */ function Foo() { this.Foo$p1 = 0; }\n"
+ "/** @constructor */ function Bar() { this.Bar$p1 = 1; }\n"
+ "function select(cond, x, y) { return cond ? x : y; }\n"
+ "/**\n"
+ " * @param {!Foo} x\n"
+ " * @param {!Bar} y\n"
+ " * @return {!Foo}\n"
+ " */\n"
+ "function f(x, y) {\n"
+ " var /** !Foo */ z = select(false, x, y);\n"
+ " return z;\n"
+ "}\n"
+ "f(new Foo, new Bar).Foo$p1;\n";
testSets(js, output, "{p1=[[Bar], [Foo]]}");
}
public void testEnum() {
String js = ""
+ "/** @enum {string} */ var En = {\n"
+ " A: 'first',\n"
+ " B: 'second'\n"
+ "};\n"
+ "var EA = En.A;\n"
+ "var EB = En.B;\n"
+ "/** @constructor */ function Foo(){};\n"
+ "Foo.prototype.A = 0;\n"
+ "Foo.prototype.B = 0;\n";
String output = ""
+ "/** @enum {string} */ var En={A:'first',B:'second'};"
+ "var EA=En.A;"
+ "var EB=En.B;"
+ "/** @constructor */ function Foo(){};"
+ "Foo.prototype.Foo_prototype$A=0;"
+ "Foo.prototype.Foo_prototype$B=0";
testSets(js, output, "{A=[[Foo.prototype]], B=[[Foo.prototype]]}");
}
public void testEnumOfObjects() {
String js = ""
+ "/** @constructor */ function Formatter() {}"
+ "Formatter.prototype.format = function() {};"
+ "/** @constructor */ function Unrelated() {}"
+ "Unrelated.prototype.format = function() {};"
+ "/** @enum {!Formatter} */ var Enum = {\n"
+ " A: new Formatter()\n"
+ "};\n"
+ "Enum.A.format();\n";
String output = ""
+ "/** @constructor */ function Formatter() {}"
+ "Formatter.prototype.Formatter_prototype$format = function() {};"
+ "/** @constructor */ function Unrelated() {}"
+ "Unrelated.prototype.Unrelated_prototype$format = function() {};"
+ "/** @enum {!Formatter} */ var Enum = {\n"
+ " A: new Formatter()\n"
+ "};\n"
+ "Enum.A.Formatter_prototype$format();\n";
testSets(js, output, "{format=[[Formatter.prototype], [Unrelated.prototype]]}");
}
public void testEnumOfObjects2() {
String js = ""
+ "/** @constructor */ function Formatter() {}"
+ "Formatter.prototype.format = function() {};"
+ "/** @constructor */ function Unrelated() {}"
+ "Unrelated.prototype.format = function() {};"
+ "/** @enum {?Formatter} */ var Enum = {\n"
+ " A: new Formatter(),\n"
+ " B: new Formatter()\n"
+ "};\n"
+ "function f() {\n"
+ " var formatter = window.toString() ? Enum.A : Enum.B;\n"
+ " formatter.format();\n"
+ "}";
String output = ""
+ "/** @constructor */ function Formatter() {}"
+ "Formatter.prototype.format = function() {};"
+ "/** @constructor */ function Unrelated() {}"
+ "Unrelated.prototype.format = function() {};"
+ "/** @enum {?Formatter} */ var Enum = {\n"
+ " A: new Formatter(),\n"
+ " B: new Formatter()\n"
+ "};\n"
+ "function f() {\n"
+ " var formatter = window.toString() ? Enum.A : Enum.B;\n"
+ " formatter.format();\n"
+ "}";
testSets(js, output, "{}");
}
public void testEnumOfObjects3() {
String js = ""
+ "/** @constructor */ function Formatter() {}"
+ "Formatter.prototype.format = function() {};"
+ "/** @constructor */ function Unrelated() {}"
+ "Unrelated.prototype.format = function() {};"
+ "/** @enum {!Formatter} */ var Enum = {\n"
+ " A: new Formatter(),\n"
+ " B: new Formatter()\n"
+ "};\n"
+ "/** @enum {!Enum} */ var SubEnum = {\n"
+ " C: Enum.A\n"
+ "};\n"
+ "function f() {\n"
+ " var formatter = SubEnum.C\n"
+ " formatter.format();\n"
+ "}";
String output = ""
+ "/** @constructor */ function Formatter() {}"
+ "Formatter.prototype.Formatter_prototype$format = function() {};"
+ "/** @constructor */ function Unrelated() {}"
+ "Unrelated.prototype.Unrelated_prototype$format = function() {};"
+ "/** @enum {!Formatter} */ var Enum = {\n"
+ " A: new Formatter(),\n"
+ " B: new Formatter()\n"
+ "};\n"
+ "/** @enum {!Enum} */ var SubEnum = {\n"
+ " C: Enum.A\n"
+ "};\n"
+ "function f() {\n"
+ " var formatter = SubEnum.C\n"
+ " formatter.Formatter_prototype$format();\n"
+ "}";
testSets(js, output, "{format=[[Formatter.prototype], [Unrelated.prototype]]}");
}
public void testUntypedExterns() {
String externs =
BaseJSTypeTestCase.ALL_NATIVE_EXTERN_TYPES
+ "var window;"
+ "window.alert = function() {x};";
String js = ""
+ "/** @constructor */ function Foo() {}\n"
+ "Foo.prototype.a = 0;\n"
+ "Foo.prototype.alert = 0;\n"
+ "Foo.prototype.window = 0;\n"
+ "/** @constructor */ function Bar() {}\n"
+ "Bar.prototype.a = 0;\n"
+ "Bar.prototype.alert = 0;\n"
+ "Bar.prototype.window = 0;\n"
+ "window.alert();";
String output = ""
+ "/** @constructor */ function Foo(){}"
+ "Foo.prototype.Foo_prototype$a=0;"
+ "Foo.prototype.alert=0;"
+ "Foo.prototype.Foo_prototype$window=0;"
+ "/** @constructor */ function Bar(){}"
+ "Bar.prototype.Bar_prototype$a=0;"
+ "Bar.prototype.alert=0;"
+ "Bar.prototype.Bar_prototype$window=0;"
+ "window.alert();";
testSets(externs, js, output, "{a=[[Bar.prototype], [Foo.prototype]]"
+ ", window=[[Bar.prototype], [Foo.prototype]]}");
}
public void testUnionTypeInvalidation() {
String externs = ""
+ "/** @constructor */ function Baz() {}"
+ "Baz.prototype.a";
String js = ""
+ "/** @constructor */ function Ind() {this.a=0}\n"
+ "/** @constructor */ function Foo() {}\n"
+ "Foo.prototype.a = 0;\n"
+ "/** @constructor */ function Bar() {}\n"
+ "Bar.prototype.a = 0;\n"
+ "/** @type {Foo|Bar} */\n"
+ "var F = new Foo;\n"
+ "F.a = 1;\n"
+ "F = new Bar;\n"
+ "/** @type {Baz} */\n"
+ "var Z = new Baz;\n"
+ "Z.a = 1;\n"
+ "/** @type {Bar|Baz} */\n"
+ "var B = new Baz;\n"
+ "B.a = 1;\n"
+ "B = new Bar;\n";
// Only the constructor field a of Ind is renamed, as Foo is related to Baz
// through Bar in the unions Bar|Baz and Foo|Bar.
String output = ""
+ "/** @constructor */ function Ind() { this.Ind$a = 0; }\n"
+ "/** @constructor */ function Foo() {}\n"
+ "Foo.prototype.a = 0;\n"
+ "/** @constructor */ function Bar() {}\n"
+ "Bar.prototype.a = 0;\n"
+ "/** @type {Foo|Bar} */\n"
+ "var F = new Foo;\n"
+ "F.a = 1;\n"
+ "F = new Bar;\n"
+ "/** @type {Baz} */\n"
+ "var Z = new Baz;\n"
+ "Z.a = 1;\n"
+ "/** @type {Bar|Baz} */"
+ "var B = new Baz;"
+ "B.a = 1;"
+ "B = new Bar;";
testSets(externs, js, output, "{a=[[Ind]]}");
}
public void testUnionAndExternTypes() {
String externs = ""
+ "/** @constructor */ function Foo() { }"
+ "Foo.prototype.a = 4;\n";
String js = ""
+ "/** @constructor */ function Bar() { this.a = 2; }\n"
+ "/** @constructor */ function Baz() { this.a = 3; }\n"
+ "/** @constructor */ function Buz() { this.a = 4; }\n"
+ "/** @constructor */ function T1() { this.a = 3; }\n"
+ "/** @constructor */ function T2() { this.a = 3; }\n"
+ "/** @type {Bar|Baz} */ var b;\n"
+ "/** @type {Baz|Buz} */ var c;\n"
+ "/** @type {Buz|Foo} */ var d;\n"
+ "b.a = 5; c.a = 6; d.a = 7;";
String output = ""
+ "/** @constructor */ function Bar() { this.a = 2; }\n"
+ "/** @constructor */ function Baz() { this.a = 3; }\n"
+ "/** @constructor */ function Buz() { this.a = 4; }\n"
+ "/** @constructor */ function T1() { this.T1$a = 3; }\n"
+ "/** @constructor */ function T2() { this.T2$a = 3; }\n"
+ "/** @type {Bar|Baz} */ var b;\n"
+ "/** @type {Baz|Buz} */ var c;\n"
+ "/** @type {Buz|Foo} */ var d;\n"
+ "b.a = 5; c.a = 6; d.a = 7;";
// We are testing the skipping of multiple types caused by unionizing with
// extern types.
testSets(externs, js, output, "{a=[[T1], [T2]]}");
}
public void testTypedExterns() {
String externs = ""
+ "/** @constructor */ function Window() {};\n"
+ "Window.prototype.alert;"
+ "/** @type {Window} */"
+ "var window;";
String js = ""
+ "/** @constructor */ function Foo() {}\n"
+ "Foo.prototype.alert = 0;\n"
+ "window.alert('blarg');";
String output = ""
+ "/** @constructor */ function Foo(){}"
+ "Foo.prototype.Foo_prototype$alert=0;"
+ "window.alert('blarg');";
testSets(externs, js, output, "{alert=[[Foo.prototype]]}");
}
public void testSubtypesWithSameField() {
String js = ""
+ "/** @constructor */ function Top() {}\n"
+ "/** @constructor \n@extends Top*/ function Foo() {}\n"
+ "Foo.prototype.a;\n"
+ "/** @constructor \n@extends Top*/ function Bar() {}\n"
+ "Bar.prototype.a;\n"
+ "/** @param {Top} top */"
+ "function foo(top) {\n"
+ " var x = top.a;\n"
+ "}\n"
+ "foo(new Foo);\n"
+ "foo(new Bar);\n";
testSets(js, "{}");
}
public void testSupertypeReferenceOfSubtypeProperty() {
String externs = ""
+ "/** @constructor */ function Ext() {}"
+ "Ext.prototype.a;";
String js = ""
+ "/** @constructor */ function Foo() {}\n"
+ "/** @constructor @extends {Foo} */ function Bar() {}\n"
+ "Bar.prototype.a;\n"
+ "/** @param {Foo} foo */"
+ "function foo(foo) {\n"
+ " var x = foo.a;\n"
+ "}\n";
String result = ""
+ "/** @constructor */ function Foo() {}\n"
+ "/** @constructor @extends {Foo} */ function Bar() {}\n"
+ "Bar.prototype.Bar_prototype$a;\n"
+ "/** @param {Foo} foo */\n"
+ "function foo(foo$$1) {\n"
+ " var x = foo$$1.Bar_prototype$a;\n"
+ "}\n";
testSets(externs, js, result, "{a=[[Bar.prototype]]}");
}
public void testObjectLiteralNotRenamed() {
String js = ""
+ "var F = {a:'a', b:'b'};"
+ "F.a = 'z';";
testSets(js, js, "{}");
}
public void testObjectLiteralReflected() {
String js = ""
+ "var goog = {};"
+ "goog.reflect = {};"
+ "goog.reflect.object = function(x, y) { return y; };"
+ "/** @constructor */ function F() {}"
+ "/** @type {number} */ F.prototype.foo = 3;"
+ "/** @constructor */ function G() {}"
+ "/** @type {number} */ G.prototype.foo = 3;"
+ "goog.reflect.object(F, {foo: 5});";
String result = ""
+ "var goog = {};"
+ "goog.reflect = {};"
+ "goog.reflect.object = function(x, y) { return y; };"
+ "/** @constructor */ function F() {}"
+ "/** @type {number} */ F.prototype.F_prototype$foo = 3;"
+ "/** @constructor */ function G() {}"
+ "/** @type {number} */ G.prototype.G_prototype$foo = 3;"
+ "goog.reflect.object(F, {F_prototype$foo: 5});";
testSets(js, result, "{foo=[[F.prototype], [G.prototype]]}");
}
public void testObjectLiteralDefineProperties() {
String externs =
LINE_JOINER.join(
"/** @const */ var Object = {};",
"Object.defineProperties = function(typeRef, definitions) {}",
"/** @constructor */ function FooBar() {}",
"/** @type {string} */ FooBar.prototype.bar_;",
"/** @type {string} */ FooBar.prototype.bar;");
String js =
LINE_JOINER.join(
"/** @struct @constructor */ var Foo = function() {",
" this.bar_ = 'bar';",
"};",
"/** @type {?} */ Foo.prototype.bar;",
"Object.defineProperties(Foo.prototype, {",
" bar: {",
" configurable: true,",
" enumerable: true,",
" /** @this {Foo} */ get: function() { return this.bar_;},",
" /** @this {Foo} */ set: function(value) { this.bar_ = value; }",
" }",
"});");
String result =
LINE_JOINER.join(
"/** @struct @constructor */ var Foo = function() {",
" this.Foo$bar_ = 'bar';",
"};",
"/** @type {?} */ Foo.prototype.Foo_prototype$bar;",
"Object.defineProperties(Foo.prototype, {",
" Foo_prototype$bar: {",
" configurable: true,",
" enumerable: true,",
" /** @this {Foo} */ get: function() { return this.Foo$bar_;},",
" /** @this {Foo} */ set: function(value) { this.Foo$bar_ = value; }",
" }",
"});");
testSets(externs, js, result, "{bar=[[Foo.prototype]], bar_=[[Foo]]}");
}
public void testObjectLiteralDefinePropertiesQuoted() {
String externs =
LINE_JOINER.join(
"/** @const */ var Object = {};",
"Object.defineProperties = function(typeRef, definitions) {}",
"/** @constructor */ function FooBar() {}",
"/** @type {string} */ FooBar.prototype.bar_;",
"/** @type {string} */ FooBar.prototype.bar;");
String js =
LINE_JOINER.join(
"/** @struct @constructor */ var Foo = function() {",
" this.bar_ = 'bar';",
"};",
"/** @type {?} */ Foo.prototype['bar'];",
"Object.defineProperties(Foo.prototype, {",
" 'bar': {",
" configurable: true,",
" enumerable: true,",
" /** @this {Foo} */ get: function() { return this.bar_;},",
" /** @this {Foo} */ set: function(value) { this.bar_ = value; }",
" }",
"});");
String result =
LINE_JOINER.join(
"/** @struct @constructor */ var Foo = function() {",
" this.Foo$bar_ = 'bar';",
"};",
"/** @type {?} */ Foo.prototype['bar'];",
"Object.defineProperties(Foo.prototype, {",
" 'bar': {",
" configurable: true,",
" enumerable: true,",
" /** @this {Foo} */ get: function() { return this.Foo$bar_;},",
" /** @this {Foo} */ set: function(value) { this.Foo$bar_ = value; }",
" }",
"});");
testSets(externs, js, result, "{bar_=[[Foo]]}");
}
public void testObjectLiteralLends() {
String js = ""
+ "var mixin = function(x) { return x; };"
+ "/** @constructor */ function F() {}"
+ "/** @type {number} */ F.prototype.foo = 3;"
+ "/** @constructor */ function G() {}"
+ "/** @type {number} */ G.prototype.foo = 3;"
+ "mixin(/** @lends {F.prototype} */ ({foo: 5}));";
String result = ""
+ "var mixin = function(x) { return x; };"
+ "/** @constructor */ function F() {}"
+ "/** @type {number} */ F.prototype.F_prototype$foo = 3;"
+ "/** @constructor */ function G() {}"
+ "/** @type {number} */ G.prototype.G_prototype$foo = 3;"
+ "mixin(/** @lends {F.prototype} */ ({F_prototype$foo: 5}));";
testSets(js, result, "{foo=[[F.prototype], [G.prototype]]}");
}
public void testClosureInherits() {
String js = ""
+ "var goog = {};"
+ "/** @param {Function} childCtor Child class.\n"
+ " * @param {Function} parentCtor Parent class. */\n"
+ "goog.inherits = function(childCtor, parentCtor) {\n"
+ " /** @constructor */\n"
+ " function tempCtor() {};\n"
+ " tempCtor.prototype = parentCtor.prototype;\n"
+ " childCtor.superClass_ = parentCtor.prototype;\n"
+ " childCtor.prototype = new tempCtor();\n"
+ " childCtor.prototype.constructor = childCtor;\n"
+ "};"
+ "/** @constructor */ function Top() {}\n"
+ "Top.prototype.f = function() {};"
+ "/** @constructor \n@extends Top*/ function Foo() {}\n"
+ "goog.inherits(Foo, Top);\n"
+ "/** @override */\n"
+ "Foo.prototype.f = function() {"
+ " Foo.superClass_.f();"
+ "};\n"
+ "/** @constructor \n* @extends Foo */ function Bar() {}\n"
+ "goog.inherits(Bar, Foo);\n"
+ "/** @override */\n"
+ "Bar.prototype.f = function() {"
+ " Bar.superClass_.f();"
+ "};\n"
+ "(new Bar).f();\n";
testSets(js, "{f=[[Top.prototype]]}");
}
public void testSkipNativeFunctionMethod() {
String externs = ""
+ "/** @constructor \n @param {*} var_args */"
+ "function Function(var_args) {}"
+ "Function.prototype.call = function() {};";
String js = ""
+ "/** @constructor */ function Foo(){};"
+ "/** @constructor\n @extends Foo */"
+ "function Bar() { Foo.call(this); };"; // call should not be renamed
testSame(externs, js, null);
}
public void testSkipNativeObjectMethod() {
String externs = ""
+ "/**"
+ " * @constructor\n"
+ " * @param {*} opt_v\n"
+ " * @return {!Object}\n"
+ " */\n"
+ "function Object(opt_v) {}"
+ "Object.prototype.hasOwnProperty;";
String js = ""
+ "/** @constructor */ function Foo(){};"
+ "(new Foo).hasOwnProperty('x');";
testSets(externs, js, js, "{}");
}
public void testExtendNativeType() {
String externs = ""
+ "/** @constructor \n @return {string} */"
+ "function Date(opt_1, opt_2, opt_3, opt_4, opt_5, opt_6, opt_7) {}"
+ "/** @override */ Date.prototype.toString = function() {}";
String js = ""
+ "/** @constructor\n @extends {Date} */ function SuperDate() {};\n"
+ "(new SuperDate).toString();";
testSets(externs, js, js, "{}");
}
public void testStringFunction() {
// Extern functions are not renamed, but user functions on a native
// prototype object are.
String externs = "/**@constructor\n@param {*} opt_str \n @return {string}*/"
+ "function String(opt_str) {};\n"
+ "/** @override \n @return {string} */\n"
+ "String.prototype.toString = function() { };\n";
String js = ""
+ "/** @constructor */ function Foo() {};\n"
+ "Foo.prototype.foo = function() {};\n"
+ "String.prototype.foo = function() {};\n"
+ "var a = 'str'.toString().foo();\n";
String output = ""
+ "/** @constructor */ function Foo() {};\n"
+ "Foo.prototype.Foo_prototype$foo = function() {};\n"
+ "String.prototype.String_prototype$foo = function() {};\n"
+ "var a = 'str'.toString().String_prototype$foo();\n";
testSets(externs, js, output, "{foo=[[Foo.prototype], [String.prototype]]}");
}
public void testUnusedTypeInExterns() {
String externs = ""
+ "/** @constructor */ function Foo() {};\n"
+ "Foo.prototype.a";
String js = ""
+ "/** @constructor */ function Bar() {};\n"
+ "Bar.prototype.a;"
+ "/** @constructor */ function Baz() {};\n"
+ "Baz.prototype.a;";
String output = ""
+ "/** @constructor */ function Bar() {};\n"
+ "Bar.prototype.Bar_prototype$a;"
+ "/** @constructor */ function Baz() {};\n"
+ "Baz.prototype.Baz_prototype$a";
testSets(externs, js, output, "{a=[[Bar.prototype], [Baz.prototype]]}");
}
public void testInterface() {
String js = ""
+ "/** @interface */ function I() {};\n"
+ "I.prototype.a;\n"
+ "/** @constructor \n @implements {I} */ function Foo() {};\n"
+ "Foo.prototype.a;\n"
+ "/** @type {I} */\n"
+ "var F = new Foo;"
+ "var x = F.a;";
testSets(js, "{a=[[Foo.prototype, I.prototype]]}");
}
public void testInterfaceOfSuperclass() {
String js = ""
+ "/** @interface */ function I() {};\n"
+ "I.prototype.a;\n"
+ "/** @constructor \n @implements {I} */ function Foo() {};\n"
+ "Foo.prototype.a;\n"
+ "/** @constructor \n @extends Foo */ function Bar() {};\n"
+ "Bar.prototype.a;\n"
+ "/** @type {Bar} */\n"
+ "var B = new Bar;"
+ "B.a = 0";
testSets(js, "{a=[[Foo.prototype, I.prototype]]}");
}
public void testInterfaceOfSuperclass2() {
String js = LINE_JOINER.join(
"/** @const */ var goog = {};",
"goog.abstractMethod = function(var_args) {};",
"/** @interface */ function I() {}",
"I.prototype.a = function(x) {};",
"/** @constructor @implements {I} */ function Foo() {}",
"/** @override */ Foo.prototype.a = goog.abstractMethod;",
"/** @constructor @extends Foo */ function Bar() {}",
"/** @override */ Bar.prototype.a = function(x) {};");
testSets(js, "{a=[[Foo.prototype, I.prototype]]}");
}
public void testTwoInterfacesWithSomeInheritance() {
String js = ""
+ "/** @interface */ function I() {};\n"
+ "I.prototype.a;\n"
+ "/** @interface */ function I2() {};\n"
+ "I2.prototype.a;\n"
+ "/** @constructor \n @implements {I} */ function Foo() {};\n"
+ "Foo.prototype.a;\n"
+ "/** @constructor \n @extends {Foo} \n @implements {I2}*/\n"
+ "function Bar() {};\n"
+ "Bar.prototype.a;\n"
+ "/** @type {Bar} */\n"
+ "var B = new Bar;"
+ "B.a = 0";
testSets(js, "{a=[[Foo.prototype, I.prototype, I2.prototype]]}");
}
public void testInvalidatingInterface() {
String js = ""
+ "/** @interface */ function I2() {};\n"
+ "I2.prototype.a;\n"
+ "/** @constructor */ function Bar() {}\n"
+ "/** @type {I} */\n"
+ "var i = new Bar;\n" // Make I invalidating
+ "/** @constructor \n @implements {I} \n @implements {I2} */"
+ "function Foo() {};\n"
+ "/** @override */\n"
+ "Foo.prototype.a = 0;\n"
+ "(new Foo).a = 0;"
+ "/** @interface */ function I() {};\n"
+ "I.prototype.a;\n";
testSets(js, "{}", TypeValidator.TYPE_MISMATCH_WARNING);
}
public void testMultipleInterfaces() {
String js = ""
+ "/** @interface */ function I() {};\n"
+ "/** @interface */ function I2() {};\n"
+ "I2.prototype.a;\n"
+ "/** @constructor \n @implements {I} \n @implements {I2} */"
+ "function Foo() {};\n"
+ "/** @override */"
+ "Foo.prototype.a = 0;\n"
+ "(new Foo).a = 0";
testSets(js, "{a=[[Foo.prototype, I2.prototype]]}");
}
public void testInterfaceWithSupertypeImplementor() {
String js = ""
+ "/** @interface */ function C() {}\n"
+ "C.prototype.foo = function() {};\n"
+ "/** @constructor */ function A (){}\n"
+ "A.prototype.foo = function() {};\n"
+ "/** @constructor \n @implements {C} \n @extends {A} */\n"
+ "function B() {}\n"
+ "/** @type {C} */ var b = new B();\n"
+ "b.foo();\n";
testSets(js, "{foo=[[A.prototype, C.prototype]]}");
}
public void testSuperInterface() {
String js = ""
+ "/** @interface */ function I() {};\n"
+ "I.prototype.a;\n"
+ "/** @interface \n @extends I */ function I2() {};\n"
+ "/** @constructor \n @implements {I2} */"
+ "function Foo() {};\n"
+ "/** @override */\n"
+ "Foo.prototype.a = 0;\n"
+ "(new Foo).a = 0";
testSets(js, "{a=[[Foo.prototype, I.prototype]]}");
}
public void testInterfaceUnionWithCtor() {
String js = ""
+ "/** @interface */ function I() {};\n"
+ "/** @type {!Function} */ I.prototype.addEventListener;\n"
+ "/** @constructor \n * @implements {I} */ function Impl() {};\n"
+ "/** @type {!Function} */ Impl.prototype.addEventListener;"
+ "/** @constructor */ function C() {};\n"
+ "/** @type {!Function} */ C.prototype.addEventListener;"
+ "/** @param {C|I} x */"
+ "function f(x) { x.addEventListener(); };\n"
+ "f(new C()); f(new Impl());";
testSets(js, js, "{addEventListener=[[C.prototype, I.prototype, Impl.prototype]]}");
}
public void testExternInterfaceUnionWithCtor() {
String externs = ""
+ "/** @interface */ function I() {};\n"
+ "/** @type {!Function} */ I.prototype.addEventListener;\n"
+ "/** @constructor \n * @implements {I} */ function Impl() {};\n"
+ "/** @type {!Function} */ Impl.prototype.addEventListener;";
String js = ""
+ "/** @constructor */ function C() {};\n"
+ "/** @type {!Function} */ C.prototype.addEventListener;"
+ "/** @param {C|I} x */"
+ "function f(x) { x.addEventListener(); };\n"
+ "f(new C()); f(new Impl());";
testSets(externs, js, js, "{}");
}
public void testAliasedTypeIsNotDisambiguated() {
String js = LINE_JOINER.join(
"/** @return {SecondAlias} */",
"function f() {}",
"function g() { f().blah; }",
"",
"/** @constructor */",
"function Second() {",
" /** @type {number} */",
" this.blah = 5;",
"};",
"var /** @const */ SecondAlias = Second;");
testSets(js, js, "{blah=[[Second]]}");
}
public void testConstructorsWithTypeErrorsAreNotDisambiguated() {
String js = LINE_JOINER.join(
"/** @constructor */",
"function Foo(){}",
"Foo.prototype.alias = function() {};",
"",
"/** @constructor */",
"function Bar(){};",
"/** @return {void} */",
"Bar.prototype.alias;",
"",
"Bar = Foo;",
"",
"(new Bar()).alias();");
testSets("", js, js, "{}", TypeValidator.TYPE_MISMATCH_WARNING, "assignment\n"
+ "found : function (new:Foo): undefined\n"
+ "required: function (new:Bar): undefined");
}
public void testStructuralTypingWithDisambiguatePropertyRenaming1() {
String js = LINE_JOINER.join(
"/** @record */",
"function I(){}",
"/** @type {number} */",
"I.prototype.x;",
"",
"/** @constructor @implements {I} */",
"function Foo(){}",
"/** @type {number} */",
"Foo.prototype.x;",
"",
"/** @constructor */",
"function Bar(){}",
"/** @type {number} */",
"Bar.prototype.x;",
"",
"function f(/** I */ i) { return i.x; }");
// In this case, I.prototype.x and Bar.prototype.x could be the
// same property since Bar <: I (under structural interface matching).
// If there is no code that uses a Bar as an I, however, then we
// will consider the two types distinct and disambiguate the properties
// with different names.
String output = LINE_JOINER.join(
"/** @record */",
"function I(){}/** @type {number} */I.prototype.Foo_prototype$x;",
"/** @constructor @implements {I} */",
"function Foo(){}/** @type {number} */Foo.prototype.Foo_prototype$x;",
"/** @constructor */",
"function Bar(){}/** @type {number} */Bar.prototype.Bar_prototype$x;",
"function f(/** I */ i){return i.Foo_prototype$x}");
testSets(js, output, "{x=[[Bar.prototype], [Foo.prototype, I.prototype]]}");
}
public void testStructuralTypingWithDisambiguatePropertyRenaming1_1() {
String js = LINE_JOINER.join(
"/** @record */",
"function I(){}",
"/** @type {number} */",
"I.prototype.x;",
"",
"/** @constructor @implements {I} */",
"function Foo(){}",
"/** @type {number} */",
"Foo.prototype.x;",
"",
"/** @constructor */",
"function Bar(){}",
"/** @type {number} */",
"Bar.prototype.x;",
"",
"function f(/** I */ i) { return i.x; }",
"f(new Bar());");
testSets(js, js, "{}");
}
public void testStructuralTypingWithDisambiguatePropertyRenaming1_2() {
String js = LINE_JOINER.join(
"/** @record */",
"function I(){}",
"/** @type {number} */",
"I.prototype.x;",
"",
"/** @constructor @implements {I} */",
"function Foo(){}",
"/** @type {number} */",
"Foo.prototype.x;",
"",
"function f(/** I */ i) { return i.x; }",
"f({x:5});");
testSets(js, js, "{}");
}
public void testStructuralTypingWithDisambiguatePropertyRenaming1_3() {
String js = LINE_JOINER.join(
"/** @record */",
"function I(){}",
"/** @type {number} */",
"I.prototype.x;",
"",
"/** @constructor @implements {I} */",
"function Foo(){}",
"/** @type {number} */",
"Foo.prototype.x;",
"",
"/** @constructor */",
"function Bar(){}",
"/** @type {number} */",
"Bar.prototype.x;",
"",
"function f(/** I */ i) { return i.x; }",
"function g(/** {x:number} */ i) { return f(i); }",
"g(new Bar());");
testSets(js, js, "{}");
}
public void testStructuralTypingWithDisambiguatePropertyRenaming1_4() {
String js = LINE_JOINER.join(
"/** @record */",
"function I(){}",
"/** @type {number} */",
"I.prototype.x;",
"",
"/** @constructor @implements {I} */",
"function Foo(){}",
"/** @type {number} */",
"Foo.prototype.x;",
"",
"/** @constructor */",
"function Bar(){}",
"/** @type {number} */",
"Bar.prototype.x;",
"",
"function f(/** I */ i) { return i.x; }",
"function g(/** {x:number} */ i) { return f(i); }",
"g(new Bar());");
testSets(js, js, "{}");
}
public void testStructuralTypingWithDisambiguatePropertyRenaming1_5() {
String js = LINE_JOINER.join(
"/** @record */",
"function I(){}",
"/** @type {number} */",
"I.prototype.x;",
"",
"/** @constructor @implements {I} */",
"function Foo(){}",
"/** @type {number} */",
"Foo.prototype.x;",
"",
"/** @constructor */",
"function Bar(){}",
"/** @type {number} */",
"Bar.prototype.x;",
"",
"function g(/** I */ i) { return f.x; }",
"var /** I */ i = new Bar();",
"g(i);");
testSets(js, js, "{}");
}
/**
* a test case where registerMismatch registers a strict mismatch
* but not a regular mismatch.
*/
public void testStructuralTypingWithDisambiguatePropertyRenaming1_6() throws Exception {
String js = LINE_JOINER.join(
"/** @record */ function I() {}",
"/** @type {!Function} */ I.prototype.addEventListener;",
"/** @constructor */ function C() {}",
"/** @type {!Function} */ C.prototype.addEventListener;",
"/** @param {I} x */",
"function f(x) { x.addEventListener(); }",
"f(new C());");
testSets(js, js, "{}");
}
/**
* a test case where registerMismatch registers a strict mismatch
* but not a regular mismatch.
*/
public void testStructuralTypingWithDisambiguatePropertyRenaming1_7() throws Exception {
String js = LINE_JOINER.join(
"/** @record */ function I() {}",
"/** @type {!Function} */ I.prototype.addEventListener;",
"/** @constructor */ function C() {}",
"/** @type {!Function} */ C.prototype.addEventListener;",
"/** @type {I} */ var x",
"x = new C()");
testSets(js, js, "{}");
}
public void testStructuralTypingWithDisambiguatePropertyRenaming2() {
String js = LINE_JOINER.join(
"/** @record */",
"function I(){}",
"/** @type {number} */",
"I.prototype.x;",
"",
"/** @constructor @implements {I} */",
"function Foo(){}",
"/** @type {number} */",
"Foo.prototype.x;",
"",
"/** @constructor */",
"function Bar(){}",
"/** @type {number} */",
"Bar.prototype.x;",
"",
"/** @param {Foo|Bar} i */",
"function f(i) { return i.x; }");
testSets(js, js, "{x=[[Bar.prototype, Foo.prototype, I.prototype]]}");
}
public void testStructuralTypingWithDisambiguatePropertyRenaming3() {
String js = LINE_JOINER.join(
"/** @record */",
"function I(){}",
"/** @type {number} */",
"I.prototype.x;",
"",
"/** @constructor */",
"function Bar(){}",
"/** @type {number} */",
"Bar.prototype.x;",
"",
"/** @param {I} i */",
"function f(i) { return i.x; }",
"f(new Bar());");
testSets(js, js, "{}");
}
public void testStructuralTypingWithDisambiguatePropertyRenaming3_1() {
String js = LINE_JOINER.join(
"/** @record */",
"function I(){}",
"/** @type {number} */",
"I.prototype.x;",
"",
"/** @constructor @implements {I} */\n" +
"function Foo(){}\n" +
"/** @type {number} */\n" +
"Foo.prototype.x;",
"",
"/** @constructor */",
"function Bar(){}",
"/** @type {number} */",
"Bar.prototype.x;",
"",
"/** @param {(I|Bar)} i */",
"function f(i) { return i.x; }",
"f(new Bar());");
testSets(js, js, "{x=[[Bar.prototype, Foo.prototype, I.prototype]]}");
}
public void testStructuralTypingWithDisambiguatePropertyRenaming4() {
String js = LINE_JOINER.join(
"/** @record */",
"function I(){}",
"/** @type {number} */",
"I.prototype.x;",
"",
"/** @constructor @implements {I} */",
"function Foo(){}",
"/** @type {number} */",
"Foo.prototype.x;",
"",
"/** @constructor */",
"function Bar(){}",
"/** @type {number} */",
"Bar.prototype.x;",
"",
"/** @param {Foo|I} i */",
"function f(i) { return i.x; }");
String output = LINE_JOINER.join(
"/** @record */",
"function I(){}/** @type {number} */I.prototype.Foo_prototype$x;",
"/** @constructor @implements {I} */",
"function Foo(){}/** @type {number} */Foo.prototype.Foo_prototype$x;",
"/** @constructor */",
"function Bar(){}/** @type {number} */Bar.prototype.Bar_prototype$x;",
"/** @param {Foo|I} i */",
"function f(i){return i.Foo_prototype$x}");
testSets(js, output, "{x=[[Bar.prototype], [Foo.prototype, I.prototype]]}");
}
public void testStructuralTypingWithDisambiguatePropertyRenaming5() {
String js = LINE_JOINER.join(
"/** @record */",
"function I(){}",
"/** @type {number} */",
"I.prototype.x;",
"",
"/** @constructor @implements {I} */",
"function Foo(){}",
"/** @type {number} */",
"Foo.prototype.x;",
"",
"/** @constructor */",
"function Bar(){}",
"/** @type {number} */",
"Bar.prototype.x;",
"",
"function f(/** Bar */ i) { return i.x; }");
String output = LINE_JOINER.join(
"/** @record */",
"function I(){}",
"/** @type {number} */",
"I.prototype.Foo_prototype$x;",
"/** @constructor @implements {I} */",
"function Foo(){}",
"/** @type {number} */",
"Foo.prototype.Foo_prototype$x;",
"/** @constructor */",
"function Bar(){}",
"/** @type {number} */",
"Bar.prototype.Bar_prototype$x;",
"function f(/** Bar */ i){return i.Bar_prototype$x}");
testSets(js, output, "{x=[[Bar.prototype], [Foo.prototype, I.prototype]]}");
}
/**
* Tests that the type based version skips renaming on types that have a
* mismatch, and the type tightened version continues to work as normal.
*/
public void testMismatchInvalidation() {
String js = ""
+ "/** @constructor */ function Foo() {}\n"
+ "Foo.prototype.a = 0;\n"
+ "/** @constructor */ function Bar() {}\n"
+ "Bar.prototype.a = 0;\n"
+ "/** @type {Foo} */\n"
+ "var F = new Bar;\n"
+ "F.a = 0;";
testSets("", js, js, "{}", TypeValidator.TYPE_MISMATCH_WARNING,
"initializing variable\n"
+ "found : Bar\n"
+ "required: (Foo|null)");
}
public void testBadCast() {
String js = "/** @constructor */ function Foo() {};\n"
+ "Foo.prototype.a = 0;\n"
+ "/** @constructor */ function Bar() {};\n"
+ "Bar.prototype.a = 0;\n"
+ "var a = /** @type {!Foo} */ (new Bar);\n"
+ "a.a = 4;";
testSets("", js, js, "{}", TypeValidator.INVALID_CAST,
"invalid cast - must be a subtype or supertype\n"
+ "from: Bar\n"
+ "to : Foo");
}
public void testDeterministicNaming() {
String js =
"/** @constructor */function A() {}\n"
+ "/** @return {string} */A.prototype.f = function() {return 'a';};\n"
+ "/** @constructor */function B() {}\n"
+ "/** @return {string} */B.prototype.f = function() {return 'b';};\n"
+ "/** @constructor */function C() {}\n"
+ "/** @return {string} */C.prototype.f = function() {return 'c';};\n"
+ "/** @type {A|B} */var ab = 1 ? new B : new A;\n"
+ "/** @type {string} */var n = ab.f();\n";
String output =
"/** @constructor */ function A() {}\n"
+ "/** @return {string} */ A.prototype.A_prototype$f = function() { return'a'; };\n"
+ "/** @constructor */ function B() {}\n"
+ "/** @return {string} */ B.prototype.A_prototype$f = function() { return'b'; };\n"
+ "/** @constructor */ function C() {}\n"
+ "/** @return {string} */ C.prototype.C_prototype$f = function() { return'c'; };\n"
+ "/** @type {A|B} */ var ab = 1 ? new B : new A;\n"
+ "/** @type {string} */ var n = ab.A_prototype$f();\n";
for (int i = 0; i < 5; i++) {
testSets(js, output, "{f=[[A.prototype, B.prototype], [C.prototype]]}");
}
}
public void testObjectLiteral() {
String js = "/** @constructor */ function Foo() {}\n"
+ "Foo.prototype.a;\n"
+ "/** @constructor */ function Bar() {}\n"
+ "Bar.prototype.a;\n"
+ "var F = /** @type {Foo} */({ a: 'a' });\n";
String output = "/** @constructor */ function Foo() {}\n"
+ "Foo.prototype.Foo_prototype$a;\n"
+ "/** @constructor */ function Bar() {}\n"
+ "Bar.prototype.Bar_prototype$a;\n"
+ "var F = /** @type {Foo} */ ({ Foo_prototype$a: 'a' });";
testSets(js, output, "{a=[[Bar.prototype], [Foo.prototype]]}");
}
public void testCustomInherits() {
String js = "Object.prototype.inheritsFrom = function(shuper) {\n" +
" /** @constructor */\n" +
" function Inheriter() { }\n" +
" Inheriter.prototype = shuper.prototype;\n" +
" this.prototype = new Inheriter();\n" +
" this.superConstructor = shuper;\n" +
"};\n" +
"function Foo(var1, var2, strength) {\n" +
" Foo.superConstructor.call(this, strength);\n" +
"}" +
"Foo.inheritsFrom(Object);";
String externs =
"function Function(var_args) {}"
+ "/** @return {*} */Function.prototype.call = function(var_args) {};";
testSets(externs, js, js, "{}");
}
public void testSkipNativeFunctionStaticProperty() {
String js = ""
+ "/** @param {!Function} ctor */\n"
+ "function addSingletonGetter(ctor) { ctor.a; }\n"
+ "/** @constructor */ function Foo() {}\n"
+ "Foo.a = 0;"
+ "/** @constructor */ function Bar() {}\n"
+ "Bar.a = 0;";
String output = ""
+ "/** @param {!Function} ctor */"
+ "function addSingletonGetter(ctor){ctor.a}"
+ "/** @constructor */ function Foo(){}"
+ "Foo.a=0;"
+ "/** @constructor */ function Bar(){}"
+ "Bar.a=0";
testSets(js, output, "{}");
}
public void testStructuralInterfacesInExterns() {
String externs =
LINE_JOINER.join(
"/** @record */",
"var I = function() {};",
"/** @return {string} */",
"I.prototype.baz = function() {};");
String js =
LINE_JOINER.join(
"/** @constructor */",
"function Bar() {}",
"Bar.prototype.baz = function() { return ''; };",
"",
"/** @constructor */",
"function Foo() {}",
"Foo.prototype.baz = function() { return ''; };");
testSets(externs, js, js, "{}");
}
public void testPropInParentInterface1() {
String js = LINE_JOINER.join(
"/** @interface */",
"function MyIterable() {}",
"MyIterable.prototype.iterator = function() {};",
"/**",
" * @interface",
" * @extends {MyIterable}",
" * @template T",
" */",
"function MyCollection() {}",
"/**",
" * @constructor",
" * @implements {MyCollection<?>}",
" */",
"function MyAbstractCollection() {}",
"/** @override */",
"MyAbstractCollection.prototype.iterator = function() {};");
testSets(js, "{iterator=[[MyAbstractCollection.prototype, MyIterable.prototype]]}");
}
public void testPropInParentInterface2() {
String js = LINE_JOINER.join(
"/** @interface */",
"function MyIterable() {}",
"MyIterable.prototype.iterator = function() {};",
"/**",
" * @interface",
" * @extends {MyIterable}",
" */",
"function MyCollection() {}",
"/**",
" * @constructor",
" * @implements {MyCollection<?>}",
" */",
"function MyAbstractCollection() {}",
"/** @override */",
"MyAbstractCollection.prototype.iterator = function() {};");
testSets(js, "{iterator=[[MyAbstractCollection.prototype, MyIterable.prototype]]}");
}
public void testPropInParentInterface3() {
String js = LINE_JOINER.join(
"/** @interface */",
"function MyIterable() {}",
"MyIterable.prototype.iterator = function() {};",
"/**",
" * @interface",
" * @extends {MyIterable}",
" */",
"function MyCollection() {}",
"/**",
" * @constructor",
" * @implements {MyCollection}",
" */",
"function MyAbstractCollection() {}",
"/** @override */",
"MyAbstractCollection.prototype.iterator = function() {};");
testSets(js, js, "{iterator=[[MyAbstractCollection.prototype, MyIterable.prototype]]}");
}
public void testErrorOnProtectedProperty() {
testError("function addSingletonGetter(foo) { foo.foobar = 'a'; };",
DisambiguateProperties.Warnings.INVALIDATION);
assertThat(getLastCompiler().getErrors()[0].toString()).contains("foobar");
}
public void testMismatchForbiddenInvalidation() {
testError(
"/** @constructor */ function F() {}"
+ "/** @type {number} */ F.prototype.foobar = 3;"
+ "/** @return {number} */ function g() { return new F(); }",
DisambiguateProperties.Warnings.INVALIDATION);
assertThat(getLastCompiler().getErrors()[0].toString()).contains("Consider fixing errors");
}
public void testUnionTypeInvalidationError() {
String externs = ""
+ "/** @constructor */ function Baz() {}"
+ "Baz.prototype.foobar";
String js = ""
+ "/** @constructor */ function Ind() {this.foobar=0}\n"
+ "/** @constructor */ function Foo() {}\n"
+ "Foo.prototype.foobar = 0;\n"
+ "/** @constructor */ function Bar() {}\n"
+ "Bar.prototype.foobar = 0;\n"
+ "/** @type {Foo|Bar} */\n"
+ "var F = new Foo;\n"
+ "F.foobar = 1\n;"
+ "F = new Bar;\n"
+ "/** @type {Baz} */\n"
+ "var Z = new Baz;\n"
+ "Z.foobar = 1\n;";
test(
externs, js, (String) null,
DisambiguateProperties.Warnings.INVALIDATION_ON_TYPE, null);
assertThat(getLastCompiler().getErrors()[0].toString()).contains("foobar");
}
public void runFindHighestTypeInChain() {
// Check that this doesn't go into an infinite loop.
new DisambiguateProperties(new Compiler(), new HashMap<String, CheckLevel>())
.getTypeWithProperty("no",
new JSTypeRegistry(new TestErrorReporter(null, null))
.getNativeType(JSTypeNative.OBJECT_PROTOTYPE));
}
private void testSets(String js, String expected, String fieldTypes) {
test(js, expected);
assertEquals(
fieldTypes, mapToString(lastPass.getRenamedTypesForTesting()));
}
private void testSets(String externs, String js, String expected,
String fieldTypes) {
testSets(externs, js, expected, fieldTypes, null, null);
}
private void testSets(String externs, String js, String expected,
String fieldTypes, DiagnosticType warning, String description) {
test(externs, js, expected, null, warning, description);
assertEquals(
fieldTypes, mapToString(lastPass.getRenamedTypesForTesting()));
}
/**
* Compiles the code and checks that the set of types for each field matches
* the expected value.
*
* <p>The format for the set of types for fields is:
* {field=[[Type1, Type2]]}
*/
private void testSets(String js, String fieldTypes) {
test(js, null, null, null);
assertEquals(fieldTypes, mapToString(lastPass.getRenamedTypesForTesting()));
}
/**
* Compiles the code and checks that the set of types for each field matches
* the expected value.
*
* <p>The format for the set of types for fields is:
* {field=[[Type1, Type2]]}
*/
private void testSets(String js, String fieldTypes, DiagnosticType warning) {
testWarning(js, warning);
assertEquals(fieldTypes, mapToString(lastPass.getRenamedTypesForTesting()));
}
/** Sorts the map and converts to a string for comparison purposes. */
private <T> String mapToString(Multimap<String, Collection<T>> map) {
TreeMap<String, String> retMap = new TreeMap<>();
for (String key : map.keySet()) {
TreeSet<String> treeSet = new TreeSet<>();
for (Collection<T> collection : map.get(key)) {
Set<String> subSet = new TreeSet<>();
for (T type : collection) {
subSet.add(type.toString());
}
treeSet.add(subSet.toString());
}
retMap.put(key, treeSet.toString());
}
return retMap.toString();
}
}
|
LorenzoDV/closure-compiler
|
test/com/google/javascript/jscomp/DisambiguatePropertiesTest.java
|
Java
|
apache-2.0
| 69,850
|
package org.gradle.test.performance.mediummonolithicjavaproject.p474;
public class Production9487 {
private String property0;
public String getProperty0() {
return property0;
}
public void setProperty0(String value) {
property0 = value;
}
private String property1;
public String getProperty1() {
return property1;
}
public void setProperty1(String value) {
property1 = value;
}
private String property2;
public String getProperty2() {
return property2;
}
public void setProperty2(String value) {
property2 = value;
}
private String property3;
public String getProperty3() {
return property3;
}
public void setProperty3(String value) {
property3 = value;
}
private String property4;
public String getProperty4() {
return property4;
}
public void setProperty4(String value) {
property4 = value;
}
private String property5;
public String getProperty5() {
return property5;
}
public void setProperty5(String value) {
property5 = value;
}
private String property6;
public String getProperty6() {
return property6;
}
public void setProperty6(String value) {
property6 = value;
}
private String property7;
public String getProperty7() {
return property7;
}
public void setProperty7(String value) {
property7 = value;
}
private String property8;
public String getProperty8() {
return property8;
}
public void setProperty8(String value) {
property8 = value;
}
private String property9;
public String getProperty9() {
return property9;
}
public void setProperty9(String value) {
property9 = value;
}
}
|
oehme/analysing-gradle-performance
|
my-app/src/main/java/org/gradle/test/performance/mediummonolithicjavaproject/p474/Production9487.java
|
Java
|
apache-2.0
| 1,891
|
import logging
import os
import os.path
import shutil
import subprocess
import tempfile
import time
from six.moves import urllib
import uuid
from six.moves.urllib.parse import urlparse # pylint: disable=E0611,F0401
from test.service import ExternalService, SpawnedService
from test.testutil import get_open_port
log = logging.getLogger(__name__)
class Fixture(object):
kafka_version = os.environ.get('KAFKA_VERSION', '0.8.0')
scala_version = os.environ.get("SCALA_VERSION", '2.8.0')
project_root = os.environ.get('PROJECT_ROOT', os.path.abspath(os.path.join(os.path.dirname(__file__), "..")))
kafka_root = os.environ.get("KAFKA_ROOT", os.path.join(project_root, 'servers', kafka_version, "kafka-bin"))
ivy_root = os.environ.get('IVY_ROOT', os.path.expanduser("~/.ivy2/cache"))
@classmethod
def download_official_distribution(cls,
kafka_version=None,
scala_version=None,
output_dir=None):
if not kafka_version:
kafka_version = cls.kafka_version
if not scala_version:
scala_version = cls.scala_version
if not output_dir:
output_dir = os.path.join(cls.project_root, 'servers', 'dist')
distfile = 'kafka_%s-%s' % (scala_version, kafka_version,)
url_base = 'https://archive.apache.org/dist/kafka/%s/' % (kafka_version,)
output_file = os.path.join(output_dir, distfile + '.tgz')
if os.path.isfile(output_file):
log.info("Found file already on disk: %s", output_file)
return output_file
# New tarballs are .tgz, older ones are sometimes .tar.gz
try:
url = url_base + distfile + '.tgz'
log.info("Attempting to download %s", url)
response = urllib.request.urlopen(url)
except urllib.error.HTTPError:
log.exception("HTTP Error")
url = url_base + distfile + '.tar.gz'
log.info("Attempting to download %s", url)
response = urllib.request.urlopen(url)
log.info("Saving distribution file to %s", output_file)
with open(output_file, 'w') as output_file_fd:
output_file_fd.write(response.read())
return output_file
@classmethod
def test_resource(cls, filename):
return os.path.join(cls.project_root, "servers", cls.kafka_version, "resources", filename)
@classmethod
def kafka_run_class_args(cls, *args):
result = [os.path.join(cls.kafka_root, 'bin', 'kafka-run-class.sh')]
result.extend(args)
return result
@classmethod
def kafka_run_class_env(cls):
env = os.environ.copy()
env['KAFKA_LOG4J_OPTS'] = "-Dlog4j.configuration=file:%s" % cls.test_resource("log4j.properties")
return env
@classmethod
def render_template(cls, source_file, target_file, binding):
with open(source_file, "r") as handle:
template = handle.read()
with open(target_file, "w") as handle:
handle.write(template.format(**binding))
class ZookeeperFixture(Fixture):
@classmethod
def instance(cls):
if "ZOOKEEPER_URI" in os.environ:
parse = urlparse(os.environ["ZOOKEEPER_URI"])
(host, port) = (parse.hostname, parse.port)
fixture = ExternalService(host, port)
else:
(host, port) = ("127.0.0.1", get_open_port())
fixture = cls(host, port)
fixture.open()
return fixture
def __init__(self, host, port):
self.host = host
self.port = port
self.tmp_dir = None
self.child = None
def out(self, message):
log.info("*** Zookeeper [%s:%d]: %s", self.host, self.port, message)
def open(self):
self.tmp_dir = tempfile.mkdtemp()
self.out("Running local instance...")
log.info(" host = %s", self.host)
log.info(" port = %s", self.port)
log.info(" tmp_dir = %s", self.tmp_dir)
# Generate configs
template = self.test_resource("zookeeper.properties")
properties = os.path.join(self.tmp_dir, "zookeeper.properties")
self.render_template(template, properties, vars(self))
# Configure Zookeeper child process
args = self.kafka_run_class_args("org.apache.zookeeper.server.quorum.QuorumPeerMain", properties)
env = self.kafka_run_class_env()
# Party!
self.out("Starting...")
timeout = 5
max_timeout = 30
backoff = 1
while True:
self.child = SpawnedService(args, env)
self.child.start()
timeout = min(timeout, max_timeout)
if self.child.wait_for(r"binding to port", timeout=timeout):
break
self.child.stop()
timeout *= 2
time.sleep(backoff)
self.out("Done!")
def close(self):
self.out("Stopping...")
self.child.stop()
self.child = None
self.out("Done!")
shutil.rmtree(self.tmp_dir)
class KafkaFixture(Fixture):
@classmethod
def instance(cls, broker_id, zk_host, zk_port, zk_chroot=None, replicas=1, partitions=2):
if zk_chroot is None:
zk_chroot = "kafka-python_" + str(uuid.uuid4()).replace("-", "_")
if "KAFKA_URI" in os.environ:
parse = urlparse(os.environ["KAFKA_URI"])
(host, port) = (parse.hostname, parse.port)
fixture = ExternalService(host, port)
else:
(host, port) = ("127.0.0.1", get_open_port())
fixture = KafkaFixture(host, port, broker_id, zk_host, zk_port, zk_chroot, replicas, partitions)
fixture.open()
return fixture
def __init__(self, host, port, broker_id, zk_host, zk_port, zk_chroot, replicas=1, partitions=2):
self.host = host
self.port = port
self.broker_id = broker_id
self.zk_host = zk_host
self.zk_port = zk_port
self.zk_chroot = zk_chroot
self.replicas = replicas
self.partitions = partitions
self.tmp_dir = None
self.child = None
self.running = False
def out(self, message):
log.info("*** Kafka [%s:%d]: %s", self.host, self.port, message)
def open(self):
if self.running:
self.out("Instance already running")
return
self.tmp_dir = tempfile.mkdtemp()
self.out("Running local instance...")
log.info(" host = %s", self.host)
log.info(" port = %s", self.port)
log.info(" broker_id = %s", self.broker_id)
log.info(" zk_host = %s", self.zk_host)
log.info(" zk_port = %s", self.zk_port)
log.info(" zk_chroot = %s", self.zk_chroot)
log.info(" replicas = %s", self.replicas)
log.info(" partitions = %s", self.partitions)
log.info(" tmp_dir = %s", self.tmp_dir)
# Create directories
os.mkdir(os.path.join(self.tmp_dir, "logs"))
os.mkdir(os.path.join(self.tmp_dir, "data"))
# Generate configs
template = self.test_resource("kafka.properties")
properties = os.path.join(self.tmp_dir, "kafka.properties")
self.render_template(template, properties, vars(self))
# Party!
self.out("Creating Zookeeper chroot node...")
args = self.kafka_run_class_args("org.apache.zookeeper.ZooKeeperMain",
"-server", "%s:%d" % (self.zk_host, self.zk_port),
"create",
"/%s" % self.zk_chroot,
"kafka-python")
env = self.kafka_run_class_env()
proc = subprocess.Popen(args, env=env, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
if proc.wait() != 0:
self.out("Failed to create Zookeeper chroot node")
self.out(proc.stdout.read())
self.out(proc.stderr.read())
raise RuntimeError("Failed to create Zookeeper chroot node")
self.out("Done!")
self.out("Starting...")
# Configure Kafka child process
args = self.kafka_run_class_args("kafka.Kafka", properties)
env = self.kafka_run_class_env()
timeout = 5
max_timeout = 30
backoff = 1
while True:
self.child = SpawnedService(args, env)
self.child.start()
timeout = min(timeout, max_timeout)
if self.child.wait_for(r"\[Kafka Server %d\], Started" %
self.broker_id, timeout=timeout):
break
self.child.stop()
timeout *= 2
time.sleep(backoff)
self.out("Done!")
self.running = True
def close(self):
if not self.running:
self.out("Instance already stopped")
return
self.out("Stopping...")
self.child.stop()
self.child = None
self.out("Done!")
shutil.rmtree(self.tmp_dir)
self.running = False
|
gamechanger/kafka-python
|
test/fixtures.py
|
Python
|
apache-2.0
| 9,197
|
package org.eufraten.trelloreporter.ordemDeServico;
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import org.apache.commons.lang3.builder.CompareToBuilder;
import org.eufraten.trelloreporter.trello.TrelloBoard;
import com.julienvey.trello.domain.Action;
import com.julienvey.trello.domain.Argument;
import com.julienvey.trello.domain.Card;
import com.julienvey.trello.domain.CheckItem;
import com.julienvey.trello.domain.CheckList;
import com.julienvey.trello.domain.Label;
public class OrdemDeServico {
private String id;
private String cardId;
private String solicitante;
private Date dataAbertura;
private String epv;
private String prioridade;
private String descricao;
private List<Item> itens = new ArrayList<>();
private String titulo;
private Date dataFechamento;
public OrdemDeServico(String id, Card card, TrelloBoard trelloBoard) {
this(card, trelloBoard);
this.id = id;
}
OrdemDeServico(String id, String solicitante, Date dataAbertura, String epv, String prioridade, String descricao) {
this.id = id;
this.solicitante = solicitante;
this.dataAbertura = dataAbertura;
this.epv = epv;
this.prioridade = prioridade;
this.descricao = descricao;
this.cardId = "mockCardId";
}
OrdemDeServico(Card card, TrelloBoard trelloBoard) {
this.cardId = card.getId();
this.descricao = card.getName();
this.descricao += "\n";
this.descricao += card.getDesc();
this.titulo = card.getName();
List<Action> actions = card.getActions(new Argument("filter", "createCard"),
new Argument("memberCreator_fields", "fullName"));
if (actions != null && !actions.isEmpty()) {
Action creationAction = actions.get(0);
this.dataAbertura = creationAction.getDate();
this.solicitante = creationAction.getMemberCreator().getFullName();
}
if (card.getLabels() != null) {
for (Label label : card.getLabels()) {
if (label.getName().startsWith("EPV")) {
this.epv = label.getName();
} else if (label.getName().startsWith("P")) {
this.prioridade = label.getName();
}
}
}
List<CheckList> checkLists = trelloBoard.checkListsPorCard(card);
for (CheckList checkList : checkLists) {
for (CheckItem checkItem : checkList.getCheckItems()) {
this.itens.add(new Item(checkItem, checkList));
}
}
Collections.sort(this.itens);
}
void addItem(Item item) {
this.itens.add(item);
}
@Override
public String toString() {
return "OrdemDeServico [id=" + id + ", solicitante=" + solicitante + ", dataAbertura=" + dataAbertura + ", epv="
+ epv + ", prioridade=" + prioridade + ", descricao=" + descricao + ", itens=" + itens + "]";
}
public String getId() {
return id;
}
public String getCardId() {
return cardId;
}
public String getSolicitante() {
return solicitante;
}
public Date getDataAbertura() {
return dataAbertura;
}
public String getEpv() {
return epv;
}
public String getPrioridade() {
return prioridade;
}
public String getDescricao() {
return descricao;
}
public String getTitulo() {
return titulo;
}
public List<Item> getItens() {
return itens;
}
public Date getDataFechamento() {
return dataFechamento;
}
void setDataFechamento(Date dataFechamento) {
this.dataFechamento = dataFechamento;
}
public long calcularLeadTime() {
LocalDate inicio = LocalDateTime
.ofInstant(Instant.ofEpochMilli(this.dataAbertura.getTime()), ZoneId.systemDefault())
.toLocalDate();
LocalDate fim;
if (this.dataFechamento == null) {
fim = LocalDate.now(ZoneId.systemDefault());
} else {
fim = LocalDateTime
.ofInstant(Instant.ofEpochMilli(this.dataFechamento.getTime()), ZoneId.systemDefault())
.toLocalDate();
}
return ChronoUnit.DAYS.between(inicio, fim);
}
// Se precisar ignorar fim de semana
// static long daysBetween(LocalDate start, LocalDate end, List<DayOfWeek> ignore) {
// return Stream.iterate(start, d->d.plusDays(1))
// .limit(start.until(end, ChronoUnit.DAYS))
// .filter(d->!ignore.contains(d.getDayOfWeek()))
// .count();
// }
public static class Item implements Comparable<Item> {
private String tipo;
private String nome;
private boolean marcado;
Item(CheckItem checkItem, CheckList checkList) {
this.tipo = checkList.getName();
this.nome = checkItem.getName();
this.marcado = "complete".equals(checkItem.getState());
}
Item(String tipo, String nome, boolean marcado) {
this.tipo = tipo;
this.nome = nome;
this.marcado = marcado;
}
@Override
public String toString() {
return "Item [tipo=" + tipo + ", nome=" + nome + ", marcado=" + marcado + "]";
}
@Override
public int compareTo(Item other) {
return new CompareToBuilder().append(this.tipo, other.tipo)
.append(this.marcado, other.marcado)
.append(this.nome, other.nome)
.toComparison();
}
public String getTipo() {
return tipo;
}
public String getNome() {
return nome;
}
public boolean isMarcado() {
return marcado;
}
}
}
|
gusehr/eufraten-trello-reporter
|
src/main/java/org/eufraten/trelloreporter/ordemDeServico/OrdemDeServico.java
|
Java
|
apache-2.0
| 5,183
|
</div><form action="search.asp" name="form1" id="form1">
<table border="1" id="table1" style="border-collapse: collapse">
<tr>
<td height="25" align="center"><span style="font-size: 16px">唐</span></td>
<td height="25" align="center"><span style="font-size: 16px">公元860年</span></td>
<td height="25" align="center"><span style="font-size: 16px">庚辰</span></td>
<td height="25px" align="center"><span style="font-size: 16px">大中十四年 咸通元年</span></td>
</tr>
<tr>
<td colspan="4">
<table border="0" width="100%">
<tr>
<td valign="top">
<b>历史纪事</b> </td>
<td>
<div>改元咸通
大中十四年(八六0)十一月二日,懿宗于圜丘祭天,赦天下,改元咸通。
南诏攻陷交趾
咸通元年(八六0)十二月三日,安南土蛮引南诏兵共三万人乘虚攻陷交趾(今越南河内)。安南都护李鄠与监军逃奔武州(今广西南宁附近)。</div></td>
</tr>
</table>
</td>
</tr>
<tr>
<td colspan="4">
<table border="0" width="100%">
<tr>
<td valign="top">
<b>文化纪事</b> </td>
<td>
<div>李群玉卒
咸通元年(八六0),李群玉约卒于本年。群玉,字文山,澧州(今湖南澧县)人,善吹笙,工书法,举进士不第。大中八年(八五四),以布衣游长安,向宣宗献诗三百篇,授宏文馆校书郎。不久去职。其诗善写羁旅之情。有《李群玉诗集》传世。</div></td>
</tr>
</table>
</td>
</tr>
<tr>
<td colspan="4">
<table border="0" width="100%">
<tr>
<td valign="top">
<b>杂谭逸事</b> </td>
<td>
<div>敕复李德裕官爵
咸通元年(八六0)九月,右拾遗刘邺上奏,以为李德裕父子为相,有功于国。自贬逐以来,亲属几尽,生涯已空,宜赠一官。十月十一日,敕复李德裕太子少保、卫国公,赠左仆射。</div></td>
</tr>
</table>
</td>
</tr>
<tr>
<td colspan="4">
<table border="0" width="100%">
<tr>
<td valign="top">
<b>注释</b></td>
<td>
<div>唐懿宗李凗 咸通元年</div></td>
</tr>
</table>
</td>
</tr>
<tr>
</tr></table>
|
ilearninging/xxhis
|
all/1787.html
|
HTML
|
apache-2.0
| 2,172
|
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <math.h>
#define DATASETSIZE 10
void heap_sort(double* srcdata, int len);
void main(void){
double srcdata[DATASETSIZE];
int idx, jdx;
srand(time(NULL));
for( idx=0; idx<DATASETSIZE; idx++ ){
srcdata[idx] = rand()*1.0/RAND_MAX;
}
for( idx=0; idx<DATASETSIZE; idx++ ){
if(idx%10 == 0) printf("\n\n");
printf(" %f, ",srcdata[idx]);
}
printf("\n");
heap_sort(srcdata,DATASETSIZE);
for( idx=0; idx<DATASETSIZE; idx++ ){
if(idx%10 == 0) printf("\n\n");
printf(" %f, ",srcdata[idx]);
}
printf("\n");
}
void swap(double* srcdata,int i,int j){
double temp;
temp = srcdata[i];
srcdata[i] = srcdata[j];
srcdata[j] = temp;
}
int left(int i){
return 2*i;
}
int right(int i){
return 2*i+1;
}
void max_heapify(double* srcdata,int len,int i){
int l = left(i);
int r = right(i);
int largest = 0;
if( l<len && srcdata[l]>srcdata[i] ){
largest = l;
}else largest = i;
if( r<len && srcdata[largest]<srcdata[r] ){
largest = r;
}
if( largest!=i ){
swap(srcdata,largest,i);
max_heapify(srcdata,len,largest);
}
}
void build_max_heap(double* srcdata,int len){
int idx=0;
for(idx=(int)(floor(len/2));idx>=0;idx--){
max_heapify(srcdata,len,idx);
}
}
void heap_sort(double* srcdata,int len){
int idx=0;
build_max_heap(srcdata,len);
for(idx=len-1;idx>0;idx--){
swap(srcdata,0,idx);
len--;
max_heapify(srcdata,len,0);
}
}
|
batermj/algorithm-challenger
|
books/cs/general-purpose-algorithms/introduction-to-algorithms/3rd-edition/chapter6/C/heap_sort.c
|
C
|
apache-2.0
| 1,748
|
/**
* angularjs-jspm-seed
* Created by kdavin on 19/11/2015.
*/
import {Service, Module} from '../../decorators';
@Module({
name : "app.common.services"
})
@Service("CustomLogService")
class CustomLogService {
constructor ($log) {
"ngInject";
this.$log = $log;
}
print(message = "Hello World !!") {
this.$log.info(message);
}
}
export default CustomLogService;
|
davinkevin/angularjs-jspm-seed
|
public/app/common/service/customLogService.js
|
JavaScript
|
apache-2.0
| 390
|
// Copyright 2017 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package codeu.chat;
import org.junit.runner.JUnitCore;
import org.junit.runner.Result;
import org.junit.runner.notification.Failure;
public final class TestRunner {
public static void main(String[] args) {
final Result result =
JUnitCore.runClasses(
codeu.chat.common.SecretTest.class,
codeu.chat.relay.ServerTest.class,
codeu.chat.server.BasicControllerTest.class,
codeu.chat.server.RawControllerTest.class,
codeu.chat.server.PersistenceTest.class,
codeu.chat.util.TimeTest.class,
codeu.chat.util.UuidTest.class,
codeu.chat.util.store.StoreTest.class
);
for (final Failure failure : result.getFailures()) {
System.out.println(failure.toString());
}
System.out.println(result.wasSuccessful());
}
}
|
oldmud0/codeu17-group18
|
test/codeu/chat/TestRunner.java
|
Java
|
apache-2.0
| 1,447
|
/*
* Perfclispe
*
*
* Copyright (c) 2013 Jakub Knetl
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.perfclipse.core.commands;
import org.eclipse.gef.commands.Command;
import org.perfclipse.core.model.DestinationModel;
/**
* @author Jakub Knetl
*
*/
public class EditDestinationEnabledCommand extends Command {
private DestinationModel destination;
private boolean oldValue;
private boolean newValue;
public EditDestinationEnabledCommand(DestinationModel destination, boolean newValue) {
super("Edit reporter enabled flag");
this.destination = destination;
this.newValue = newValue;
this.oldValue = destination.getDestination().isEnabled();
}
@Override
public void execute() {
destination.setEnabled(newValue);
}
@Override
public void undo() {
destination.setEnabled(oldValue);
}
}
|
PerfCake/PerfClipse
|
org.perfclipse.core/src/org/perfclipse/core/commands/EditDestinationEnabledCommand.java
|
Java
|
apache-2.0
| 1,347
|
// Copyright 2007 Xito.org
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package org.xito.boot;
import java.io.*;
import java.net.*;
import java.util.*;
import java.util.jar.*;
import java.util.zip.*;
import java.util.logging.*;
import java.security.*;
/**
* Describes a specific entry for a ClassPath. ClassPath entries can be Jar files Zip files or
* a URL to a Folder. They can be configured to be downloaded eagerly or lazily, and set to
* be cached or not cached.
*
* @author Deane Richan
*/
public class ClassPathEntry implements Serializable {
private static Logger logger = Logger.getLogger(ClassPathEntry.class.getName());
public static final int EAGER = 0;
public static final int LAZY = 1;
private int downloadType = EAGER;
private String partName = null;
private CachePolicy cachePolicy = CachePolicy.ALWAYS;
private boolean mainJar;
private URL resourceURL = null;
private String os = null;
transient protected boolean downloaded_flag = false;
transient private boolean initialized_flag = false;
transient private JarFile jarFile;
transient private Hashtable<String, JarEntry> jarEntryNames = new Hashtable<String, JarEntry>();
transient private Manifest manifest;
transient private String defaultSpecTitle;
transient private String defaultSpecVersion;
transient private String defaultSpecVendor;
transient private String defaultImplTitle;
transient private String defaultImplVersion;
transient private String defaultImplVendor;
transient private boolean defaultSealed;
/**
* Create a ClassPath Entry
*/
public ClassPathEntry(String os, URL url) {
this.os = os;
setResourceURL(url);
}
/**
* Create a ClassPath Entry
*/
public ClassPathEntry(URL url) {
setResourceURL(url);
}
/**
* Make a Copy of this ClassPath Entry
*/
public ClassPathEntry copy() {
ClassPathEntry c = new ClassPathEntry(resourceURL);
c.downloadType = this.downloadType;
c.cachePolicy = this.cachePolicy;
c.partName = this.partName;
c.mainJar = this.mainJar;
return c;
}
/**
* Return true if the resource has been downloaded
*/
public boolean isDownloaded() {
return downloaded_flag;
}
/**
* return true if resource URL points to jar file
*/
public boolean isJar() {
if(resourceURL.toString().endsWith(".jar")){
return true;
}
else {
return false;
}
}
/**
* return true if resource URL points to zip file
*/
public boolean isZip() {
if(resourceURL.toString().endsWith(".zip")){
return true;
}
else {
return false;
}
}
/**
* Attempt to close any resources that are open
*/
public synchronized void close() {
downloaded_flag = false;
initialized_flag = false;
if(jarEntryNames != null) {
jarEntryNames.clear();
}
if(jarFile != null) {
try {
jarFile.close();
}
catch(IOException ioExp) {
//ignore this I don't care
logger.log(Level.WARNING, ioExp.getMessage(), ioExp);
}
}
manifest = null;
jarFile = null;
}
/**
* Download the resource and then Initialize it
*/
protected void downloadResource() {
if(downloaded_flag) return;
//if the resource is not a Jar or Zip then just return
//we can't download it
if(!isJar() && !isZip()) {
return;
}
CacheManager cm = Boot.getCacheManager();
try {
cm.downloadResource(null, resourceURL, cm.getDefaultListener(), cachePolicy);
downloaded_flag = true;
initializeJar();
}
catch(Exception exp) {
logger.log(Level.SEVERE, exp.getMessage(), exp);
}
}
protected synchronized boolean isInitialized() {
return initialized_flag;
}
/**
* Initialize the Jar Archive
* The resource is assumed to already be downloaded and in the cache before this is called
*/
protected synchronized void initializeJar() {
//Check to see if we are already initialized
if(isInitialized()) return;
//we can't initialize non-jar non-zip resources
if(!isJar() && !isZip()) {
initialized_flag = true;
return;
}
try {
File f = null;
if(resourceURL.getProtocol().equals("file")){
f = new File(resourceURL.getFile());
}
else {
f = Boot.getCacheManager().getCachedFileForURL(resourceURL);
}
if(!f.exists()) {
logger.log(Level.WARNING, "*** Resource file:"+f.toString()+" was not found!");
return;
}
jarFile = new JarFile(f);
jarEntryNames.clear();
Enumeration<JarEntry> entries = jarFile.entries();
while(entries.hasMoreElements()) {
JarEntry entry = entries.nextElement();
jarEntryNames.put(entry.getName(), entry);
}
manifest = jarFile.getManifest();
if(manifest != null) {
Attributes mainAttrs = manifest.getMainAttributes();
if(mainAttrs != null) {
defaultSpecTitle = mainAttrs.getValue("Specification-Title");
defaultSpecVersion = mainAttrs.getValue("Specification-Version");
defaultSpecVendor = mainAttrs.getValue("Specification-Vendor");
defaultImplTitle = mainAttrs.getValue("Implementation-Title");
defaultImplVersion = mainAttrs.getValue("Implementation-Version");
defaultImplVendor = mainAttrs.getValue("Implementation-Vendor");
defaultSealed = Boolean.valueOf(mainAttrs.getValue("Sealed")).booleanValue();
}
}
}
catch(Exception ioExp) {
logger.log(Level.SEVERE, ioExp.getMessage(), ioExp);
}
finally {
initialized_flag = true;
}
}
/**
* process information from the Manifest
*/
protected void definePackage(String name, CacheClassLoader loader) {
if(name == null) return;
//Get attributes for this package
if(manifest != null) {
Attributes attrs = manifest.getAttributes(name.replace('.', '/')+'/');
if(attrs != null) {
String specTitle = defaultSpecTitle != null ? defaultSpecTitle : attrs.getValue("Specification-Title");
String specVersion = defaultSpecVersion != null ? defaultSpecVersion : attrs.getValue("Specification-Version");
String specVendor = defaultSpecVendor != null ? defaultSpecVendor : attrs.getValue("Specification-Vendor");
String implTitle = defaultImplTitle != null ? defaultImplTitle : attrs.getValue("Implementation-Title");
String implVersion = defaultImplVersion != null ? defaultImplVersion : attrs.getValue("Implementation-Version");
String implVendor = defaultImplVendor != null ? defaultImplVendor : attrs.getValue("Implementation-Vendor");
String sealedStr = attrs.getValue("Sealed");
boolean sealed = defaultSealed;
if(sealedStr != null) {
sealed = Boolean.valueOf(attrs.getValue("Sealed")).booleanValue();
}
loader.definePackage(name, specTitle, specVersion, specVendor, implTitle, implVersion, implVendor, (sealed)?resourceURL:null);
return;
}
}
//Just use default settings
loader.definePackage(name, defaultSpecTitle, defaultSpecVersion, defaultSpecVendor, defaultImplTitle, defaultImplVersion, defaultImplVendor, (defaultSealed)?resourceURL:null);
}
/**
* Get the OS this ClassPathEntry should be used for
* @return
*/
public String getOs() {
return os;
}
/**
* Set the OS this ClassPathEntry should be used for
* @param os
*/
public void setOs(String os) {
this.os = os;
}
/**
* Set the Resource URL for this ClassPath Entry
*/
public void setResourceURL(URL url) {
resourceURL = url;
}
/**
* Get the URL of the Resource
*/
public URL getResourceURL() {
return resourceURL;
}
/**
* Set Part Name
*/
public void setPart(String part) {
partName = part;
}
/**
* Get the Part Name
*/
public String getPart() {
return partName;
}
/**
* Set the Cache Policy of this Resource. Defaults to ALWAYS if policy is null
*/
public void setCachePolicy(CachePolicy policy) {
if(policy == null) {
cachePolicy = CachePolicy.ALWAYS;
return;
}
cachePolicy = policy;
}
/**
* Get the Cache Policy of this Resource
*/
public CachePolicy getCachePolicy() {
return cachePolicy;
}
/**
* Set Main Jar Flag
*/
public void setMainJar(boolean b) {
mainJar = b;
}
/**
* Return true if this resource is flagged as a Main jar
*/
public boolean isMainJar() {
return mainJar;
}
/**
* Get the Main Class from this Resource Manifest
*/
public String getMainClassName() {
downloadResource();
initializeJar();
if(manifest == null) return null;
Attributes attrs = manifest.getMainAttributes();
if(attrs == null) return null;
return attrs.getValue("Main-Class");
}
/**
* Set the Download Type either EAGER or LAZY
*/
public void setDownloadType(int type) {
if(downloadType == LAZY) {
downloadType = LAZY;
}
else {
downloadType = EAGER;
}
}
/**
* Get the Download Type either EAGER or LAZY
*/
public int getDownloadType() {
return downloadType;
}
/**
* Find a Class in this ClassPath Entry
*/
protected Class findClass(String name, CacheClassLoader loader) throws ClassNotFoundException {
if(!isInitialized()) {
initializeJar();
}
//If this resource is not a jar or zip then attempt to just download the file
if(!isJar() && !isZip()) {
initialized_flag = true;
return findClassFromURL(name, loader);
}
//Check to see if this Jar has this class
String classFileName = CacheClassLoader.getClassFileName(name);
if(!jarEntryNames.containsKey(classFileName)) {
throw new ClassNotFoundException(name);
}
synchronized (this) {
JarEntry entry = jarFile.getJarEntry(classFileName);
//If no entry in jar for this name then throw exception
if(entry == null) {
throw new ClassNotFoundException(name);
}
//Extract the Class Data from the Jar
InputStream in = null;
try {
ByteArrayOutputStream out = new ByteArrayOutputStream();
in = jarFile.getInputStream(entry);
byte buf[] = new byte[1024];
int c = in.read(buf);
while(c != -1) {
out.write(buf, 0, c);
c = in.read(buf);
}
byte data[] = out.toByteArray();
URL u = resourceURL;
if(u != null && !u.getProtocol().equals("file")) {
u = Boot.getCacheManager().convertToCachedURL(u);
}
CodeSource cs = new CodeSource(u, entry.getCertificates());
return loader.defineClassInternal(name, data, 0, data.length, cs);
}
catch(IOException ioExp) {
logger.log(Level.SEVERE, ioExp.getMessage(), ioExp);
throw new ClassNotFoundException(name);
}
finally {
if(in != null) {
try {in.close();}catch(IOException ioExp){ioExp.printStackTrace();}
}
}
}
}
/**
* Find a class using the URL the URL is assumed to be a base
* URL. The class name is appended to it to download the file
*/
protected Class findClassFromURL(String name, CacheClassLoader loader) throws ClassNotFoundException {
URL url = null;
InputStream in = null;
try {
if(resourceURL.toString().endsWith("/")) {
url = new URL(resourceURL.toString() + CacheClassLoader.getClassFileName(name));
}
else {
url = new URL(resourceURL.toString() + "/" + CacheClassLoader.getClassFileName(name));
}
//Now download the URL
Boot.getCacheManager().downloadResource(null, url, null, cachePolicy);
File f = Boot.getCacheManager().getCachedFileForURL(url);
ByteArrayOutputStream out = new ByteArrayOutputStream();
in = new FileInputStream(f);
byte buf[] = new byte[1024];
int c = in.read(buf);
while(c != -1) {
out.write(buf, 0, c);
c = in.read(buf);
}
byte data[] = out.toByteArray();
URL u = resourceURL;
if(u != null && !u.getProtocol().equals("file")) {
u = Boot.getCacheManager().convertToCachedURL(u);
}
CodeSource cs = new CodeSource(u, (java.security.cert.Certificate[])null);
Class cls = loader.defineClassInternal(name, data, 0, data.length, cs);
return cls;
}
catch(Exception exp) {
logger.log(Level.SEVERE, exp.getMessage(), exp);
throw new ClassNotFoundException(name);
}
finally {
if(in != null) {
try {in.close();}catch(IOException ioExp){ioExp.printStackTrace();}
}
}
}
/**
* Find a Resource in this ClassPath Entry
*/
protected URL findResource(String name) {
//First initialize jar
if(!isInitialized()) {
initializeJar();
}
//If this resource is not a jar or zip then attempt to find the Resource from a URL
if(!isJar() && !isZip()) {
initialized_flag = true;
return findResourceFromURL(name);
}
//Check to see if this Jar has this resource
synchronized (this) {
JarEntry entry = jarFile.getJarEntry(name);
//If no entry in jar for this name then return null
if(entry == null) {
return null;
}
//Return a URL to this Resource
File f = null;
try {
if(resourceURL.getProtocol().equals("file")){
f = new File(resourceURL.getFile());
}
else {
f = Boot.getCacheManager().getCachedFileForURL(resourceURL);
}
URL url = new URL("jar:"+f.toURL()+"!/"+name);
return url;
}
catch(Exception badURL) {
logger.log(Level.SEVERE, badURL.getMessage(), badURL);
}
return null;
}
}
/**
* Find a resource using the URL the URL is assumed to be a base
* URL. The resource name is appended to it to download the file
*/
protected URL findResourceFromURL(String name) {
URL url = null;
try {
if(resourceURL.toString().endsWith("/")) {
url = new URL(resourceURL.toString() + name);
}
else {
url = new URL(resourceURL.toString() + "/" + name);
}
//Now download the URL
Boot.getCacheManager().downloadResource(null, url, null, cachePolicy);
File f = Boot.getCacheManager().getCachedFileForURL(url);
return f.toURL();
}
catch(Exception exp) {
logger.log(Level.SEVERE, exp.getMessage(), exp);
}
return null;
}
}
|
drichan/xito
|
modules/bootstrap/src/main/java/org/xito/boot/ClassPathEntry.java
|
Java
|
apache-2.0
| 16,187
|
# Randia longiflora var. ovoidea VARIETY
#### Status
SYNONYM
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null
|
mdoering/backbone
|
life/Plantae/Magnoliophyta/Magnoliopsida/Gentianales/Rubiaceae/Oxyceros/Oxyceros longiflorus/ Syn. Randia longiflora ovoidea/README.md
|
Markdown
|
apache-2.0
| 187
|
# Brodiaea lactea var. major VARIETY
#### Status
SYNONYM
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null
|
mdoering/backbone
|
life/Plantae/Magnoliophyta/Liliopsida/Asparagales/Asparagaceae/Triteleia/Triteleia hyacinthina/ Syn. Brodiaea lactea major/README.md
|
Markdown
|
apache-2.0
| 183
|
# Wildemania amethystea (Kützing) De Toni SPECIES
#### Status
ACCEPTED
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null
|
mdoering/backbone
|
life/Plantae/Rhodophyta/Bangiophyceae/Bangiales/Bangiaceae/Wildemania/Wildemania amethystea/README.md
|
Markdown
|
apache-2.0
| 198
|
# Pleurotus applicatus var. calopogon Pat. & Demange VARIETY
#### Status
ACCEPTED
#### According to
Index Fungorum
#### Published in
null
#### Original name
Pleurotus applicatus var. calopogon Pat. & Demange
### Remarks
null
|
mdoering/backbone
|
life/Fungi/Basidiomycota/Agaricomycetes/Agaricales/Tricholomataceae/Resupinatus/Resupinatus applicatus/Pleurotus applicatus calopogon/README.md
|
Markdown
|
apache-2.0
| 229
|
# Platanthera helferi (Rchb.f.) Kraenzl. SPECIES
#### Status
SYNONYM
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null
|
mdoering/backbone
|
life/Plantae/Magnoliophyta/Liliopsida/Asparagales/Orchidaceae/Brachycorythis/Brachycorythis helferi/ Syn. Platanthera helferi/README.md
|
Markdown
|
apache-2.0
| 195
|
# Cenolophon macrostephanum (Baker) Holttum SPECIES
#### Status
SYNONYM
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null
|
mdoering/backbone
|
life/Plantae/Magnoliophyta/Liliopsida/Zingiberales/Zingiberaceae/Alpinia/Alpinia macrostephana/ Syn. Cenolophon macrostephanum/README.md
|
Markdown
|
apache-2.0
| 198
|
# Commiphora montana Engl. SPECIES
#### Status
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null
|
mdoering/backbone
|
life/Plantae/Magnoliophyta/Magnoliopsida/Sapindales/Burseraceae/Commiphora/Commiphora montana/README.md
|
Markdown
|
apache-2.0
| 174
|
# Microagglomeratus Awramik in Allison & Awramik, 1989 GENUS
#### Status
ACCEPTED
#### According to
Interim Register of Marine and Nonmarine Genera
#### Published in
null
#### Original name
null
### Remarks
null
|
mdoering/backbone
|
life/Protozoa/Acritarcha/Microagglomeratus/README.md
|
Markdown
|
apache-2.0
| 216
|
# Angelica montana Brot. SPECIES
#### Status
ACCEPTED
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null
|
mdoering/backbone
|
life/Plantae/Magnoliophyta/Magnoliopsida/Apiales/Apiaceae/Angelica/Angelica montana/README.md
|
Markdown
|
apache-2.0
| 180
|
# Huperzia selago subsp. arctica (Grossh.) Á. Löve & D. Löve SUBSPECIES
#### Status
SYNONYM
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null
|
mdoering/backbone
|
life/Plantae/Lycopodiophyta/Lycopodiopsida/Lycopodiales/Lycopodiaceae/Huperzia/Huperzia selago/ Syn. Huperzia selago arctica/README.md
|
Markdown
|
apache-2.0
| 221
|
package PSLHAR;//edu.umd.cs.example;
import java.util.ArrayList;
import edu.umd.cs.psl.database.ReadOnlyDatabase;
import edu.umd.cs.psl.model.argument.ArgumentType;
import edu.umd.cs.psl.model.argument.GroundTerm;
import edu.umd.cs.psl.model.argument.IntegerAttribute;
import edu.umd.cs.psl.model.function.ExternalFunction;
class FromSamePlaneToOnTopFunction implements ExternalFunction {
private ArgumentType[] argTypes = new ArgumentType[]{ArgumentType.UniqueID, ArgumentType.UniqueID, ArgumentType.UniqueID, ArgumentType.UniqueID, ArgumentType.UniqueID, ArgumentType.UniqueID};
private int maxIncrement;
private static final ArrayList<Integer> timestamps = new ArrayList<Integer>();
public FromSamePlaneToOnTopFunction(int maxIncrement) {
this.maxIncrement = maxIncrement;
}
@Override
public double getValue(ReadOnlyDatabase db, GroundTerm... args) {
boolean passedToBeOnTop = false; // argTypes = new ArgumentType[args.length];
/* Get args */
try{
timestamps.clear();
for (int j = 0; j < args.length; j = j+3) {
String x = args[j].toString();
String y = args[j+1].toString();
String z = args[j+2].toString();
if (! x.equals(""))
Xpos.add(Integer.parseInt(x));
if(!y.equals("")
Ypos.add(Integer.parseInt(y));
if(!z.equals("")
Zpos.add(Integer.parseInt(z));
}
if(Xpos.size()<2){
System.err.println("Error in function: missing extra input variable ");
System.exit(-1);
}
else{
if(objectsOnTopOfEachOther(pos1, pos2) && objectsInStackedPosition.size()>1){ // SEARCHING MIN 3 OBJECTS OF SAME TYPE ARE DETECTED WITH "STACKED" POSITIONS
//System.out.println("__StackingMov__ detected in activ "+activityToMatch);
Dictionary o2 = new Hashtable();
o2.put("object", object2);
o2.put("pos", new float[]{pos2[0], pos2[1], pos2[2]});
o2.put("objectID", object2ID);
objectsInStackedPosition.add(o2);
if(activityToMatch.equals(STACKING))
return true;
}
else{ // CHECKING FOR UNSTACKED OBJECTS
if(objectsOnSameSurface(pos1, pos2) && objectsInUnstackedPosition.size()<1){//state.equals("stacked")){ //
Dictionary o1 = new Hashtable();
o1.put("object", object1);
o1.put("pos", new float[]{pos1[0], pos1[1], pos1[2]});
o1.put("objectID", object1ID);
objectsInUnstackedPosition.add(o1); // if different type than the previous object?
Dictionary o2 = new Hashtable();
o2.put("object", object2);
o2.put("pos", new float[]{pos2[0], pos2[1], pos2[2]});
o2.put("objectID", object2ID);
objectsInUnstackedPosition.add(o2);
}
else{ // TODO: IS CONSIDERING STATES OF GROUPS OF 3 OBJECTS OF SAME TYPE NEEDED?
if(objectsOnSameSurface(pos1, pos2) && objectsInUnstackedPosition.size()>1)
}
}
catch(Exception e){//Catch exception if any
System.err.println("Error in FollowsFunction: " + e.getMessage());
}
return follows ? 1.0 : 0.0; // 0 is False; 1 is True
}
@Override
public int getArity() {
return argTypes.length;
}
@Override
public ArgumentType[] getArgumentTypes() {
return argTypes;
}
}
|
NataliaDiaz/ActivityRecognitionPSL
|
src/main/java/PSLHAR/FromSamePlaneToOnTopFunction.java
|
Java
|
apache-2.0
| 3,534
|
$packageName = 'firefox-nightly'
$softwareVersion = '55.0.1.2017031021-alpha' -Replace "^(\d+)\.(\d+)\.(\d+)[^-]+-([a-z]).*",'$1.$2$4$3'
$softwareName = "Nightly $softwareVersion*"
$installerType = 'exe'
$silentArgs = '/VERYSILENT /SUPPRESSMSGBOXES /NORESTART /SP-'
$validExitCodes = @(0)
[array]$key = Get-UninstallRegistryKey -SoftwareName $softwareName
$key | ForEach-Object {
Uninstall-ChocolateyPackage -PackageName $packageName `
-FileType $installerType `
-SilentArgs $($silentArgs) `
-File $($_.UninstallString.Replace('"','')) `
-ValidExitCodes $validExitCodes
}
|
dtgm/chocolatey-packages
|
automatic/_output/firefox-nightly/55.0.1.2017031021/tools/chocolateyUninstall.ps1
|
PowerShell
|
apache-2.0
| 820
|
#pragma once
#include "message.hh"
#include <string>
namespace eclipse {
namespace messages {
struct OffsetKeyValue: public Message {
OffsetKeyValue () = default;
OffsetKeyValue (uint32_t, std::string, std::string, uint32_t, uint32_t);
std::string get_type() const override;
uint32_t key;
std::string name, value;
uint32_t pos, len;
};
}
}
|
DICL/VeloxMR
|
src/messages/offsetkv.hh
|
C++
|
apache-2.0
| 357
|
/* Copyright 2020 Telstra Open Source
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.openkilda.wfm.topology.flowhs.fsm.delete.actions;
import static java.lang.String.format;
import org.openkilda.messaging.Message;
import org.openkilda.messaging.error.ErrorType;
import org.openkilda.model.Flow;
import org.openkilda.model.FlowStatus;
import org.openkilda.persistence.PersistenceManager;
import org.openkilda.persistence.repositories.FeatureTogglesRepository;
import org.openkilda.persistence.repositories.RepositoryFactory;
import org.openkilda.wfm.share.history.model.FlowEventData;
import org.openkilda.wfm.share.logger.FlowOperationsDashboardLogger;
import org.openkilda.wfm.topology.flowhs.exception.FlowProcessingException;
import org.openkilda.wfm.topology.flowhs.fsm.common.actions.NbTrackableAction;
import org.openkilda.wfm.topology.flowhs.fsm.delete.FlowDeleteContext;
import org.openkilda.wfm.topology.flowhs.fsm.delete.FlowDeleteFsm;
import org.openkilda.wfm.topology.flowhs.fsm.delete.FlowDeleteFsm.Event;
import org.openkilda.wfm.topology.flowhs.fsm.delete.FlowDeleteFsm.State;
import lombok.extern.slf4j.Slf4j;
import java.util.Optional;
@Slf4j
public class ValidateFlowAction extends NbTrackableAction<FlowDeleteFsm, State, Event, FlowDeleteContext> {
private final FeatureTogglesRepository featureTogglesRepository;
private final FlowOperationsDashboardLogger dashboardLogger;
public ValidateFlowAction(PersistenceManager persistenceManager, FlowOperationsDashboardLogger dashboardLogger) {
super(persistenceManager);
RepositoryFactory repositoryFactory = persistenceManager.getRepositoryFactory();
featureTogglesRepository = repositoryFactory.createFeatureTogglesRepository();
this.dashboardLogger = dashboardLogger;
}
@Override
protected Optional<Message> performWithResponse(State from, State to, Event event, FlowDeleteContext context,
FlowDeleteFsm stateMachine) {
String flowId = stateMachine.getFlowId();
dashboardLogger.onFlowDelete(flowId);
boolean isOperationAllowed = featureTogglesRepository.getOrDefault().getDeleteFlowEnabled();
if (!isOperationAllowed) {
throw new FlowProcessingException(ErrorType.NOT_PERMITTED, "Flow delete feature is disabled");
}
Flow resultFlow = transactionManager.doInTransaction(() -> {
Flow flow = getFlow(flowId);
if (flow.getStatus() == FlowStatus.IN_PROGRESS) {
throw new FlowProcessingException(ErrorType.REQUEST_INVALID,
format("Flow %s is in progress now", flowId));
}
// Keep it, just in case we have to revert it.
stateMachine.setOriginalFlowStatus(flow.getStatus());
flow.setStatus(FlowStatus.IN_PROGRESS);
return flow;
});
stateMachine.setDstSwitchId(resultFlow.getDestSwitchId());
stateMachine.setSrcSwitchId(resultFlow.getSrcSwitchId());
stateMachine.saveNewEventToHistory("Flow was validated successfully", FlowEventData.Event.DELETE);
return Optional.of(buildResponseMessage(resultFlow, stateMachine.getCommandContext()));
}
@Override
protected String getGenericErrorMessage() {
return "Could not delete flow";
}
}
|
jonvestal/open-kilda
|
src-java/flowhs-topology/flowhs-storm-topology/src/main/java/org/openkilda/wfm/topology/flowhs/fsm/delete/actions/ValidateFlowAction.java
|
Java
|
apache-2.0
| 3,905
|
# Copyright (c) 2012 NetApp, Inc. All rights reserved.
# Copyright (c) 2014 Ben Swartzlander. All rights reserved.
# Copyright (c) 2014 Navneet Singh. All rights reserved.
# Copyright (c) 2014 Clinton Knight. All rights reserved.
# Copyright (c) 2014 Alex Meade. All rights reserved.
# Copyright (c) 2014 Andrew Kerr. All rights reserved.
# Copyright (c) 2014 Jeff Applewhite. All rights reserved.
# Copyright (c) 2015 Tom Barron. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
"""
Volume driver library for NetApp 7/C-mode block storage systems.
"""
import math
import sys
import uuid
from oslo_log import log as logging
from oslo_utils import excutils
from oslo_utils import units
import six
from cinder import exception
from cinder.i18n import _, _LE, _LI, _LW
from cinder.volume.drivers.netapp.dataontap.client import api as na_api
from cinder.volume.drivers.netapp import options as na_opts
from cinder.volume.drivers.netapp import utils as na_utils
from cinder.volume import utils as volume_utils
from cinder.zonemanager import utils as fczm_utils
LOG = logging.getLogger(__name__)
class NetAppLun(object):
"""Represents a LUN on NetApp storage."""
def __init__(self, handle, name, size, metadata_dict):
self.handle = handle
self.name = name
self.size = size
self.metadata = metadata_dict or {}
def get_metadata_property(self, prop):
"""Get the metadata property of a LUN."""
if prop in self.metadata:
return self.metadata[prop]
name = self.name
LOG.debug("No metadata property %(prop)s defined for the LUN %(name)s",
{'prop': prop, 'name': name})
def __str__(self, *args, **kwargs):
return 'NetApp LUN [handle:%s, name:%s, size:%s, metadata:%s]' % (
self.handle, self.name, self.size, self.metadata)
class NetAppBlockStorageLibrary(object):
"""NetApp block storage library for Data ONTAP."""
# do not increment this as it may be used in volume type definitions
VERSION = "1.0.0"
REQUIRED_FLAGS = ['netapp_login', 'netapp_password',
'netapp_server_hostname']
ALLOWED_LUN_OS_TYPES = ['linux', 'aix', 'hpux', 'image', 'windows',
'windows_2008', 'windows_gpt', 'solaris',
'solaris_efi', 'netware', 'openvms', 'hyper_v']
ALLOWED_IGROUP_HOST_TYPES = ['linux', 'aix', 'hpux', 'windows', 'solaris',
'netware', 'default', 'vmware', 'openvms',
'xen', 'hyper_v']
DEFAULT_LUN_OS = 'linux'
DEFAULT_HOST_TYPE = 'linux'
def __init__(self, driver_name, driver_protocol, **kwargs):
na_utils.validate_instantiation(**kwargs)
self.driver_name = driver_name
self.driver_protocol = driver_protocol
self.zapi_client = None
self._stats = {}
self.lun_table = {}
self.lun_ostype = None
self.host_type = None
self.lookup_service = fczm_utils.create_lookup_service()
self.app_version = kwargs.get("app_version", "unknown")
self.configuration = kwargs['configuration']
self.configuration.append_config_values(na_opts.netapp_connection_opts)
self.configuration.append_config_values(na_opts.netapp_basicauth_opts)
self.configuration.append_config_values(na_opts.netapp_transport_opts)
self.configuration.append_config_values(
na_opts.netapp_provisioning_opts)
self.configuration.append_config_values(na_opts.netapp_san_opts)
def do_setup(self, context):
na_utils.check_flags(self.REQUIRED_FLAGS, self.configuration)
self.lun_ostype = (self.configuration.netapp_lun_ostype
or self.DEFAULT_LUN_OS)
self.host_type = (self.configuration.netapp_host_type
or self.DEFAULT_HOST_TYPE)
def check_for_setup_error(self):
"""Check that the driver is working and can communicate.
Discovers the LUNs on the NetApp server.
"""
if self.lun_ostype not in self.ALLOWED_LUN_OS_TYPES:
msg = _("Invalid value for NetApp configuration"
" option netapp_lun_ostype.")
LOG.error(msg)
raise exception.NetAppDriverException(msg)
if self.host_type not in self.ALLOWED_IGROUP_HOST_TYPES:
msg = _("Invalid value for NetApp configuration"
" option netapp_host_type.")
LOG.error(msg)
raise exception.NetAppDriverException(msg)
lun_list = self.zapi_client.get_lun_list()
self._extract_and_populate_luns(lun_list)
LOG.debug("Success getting list of LUNs from server.")
def get_pool(self, volume):
"""Return pool name where volume resides.
:param volume: The volume hosted by the driver.
:return: Name of the pool where given volume is hosted.
"""
name = volume['name']
metadata = self._get_lun_attr(name, 'metadata') or dict()
return metadata.get('Volume', None)
def create_volume(self, volume):
"""Driver entry point for creating a new volume (Data ONTAP LUN)."""
LOG.debug('create_volume on %s', volume['host'])
# get Data ONTAP volume name as pool name
pool_name = volume_utils.extract_host(volume['host'], level='pool')
if pool_name is None:
msg = _("Pool is not available in the volume host field.")
raise exception.InvalidHost(reason=msg)
extra_specs = na_utils.get_volume_extra_specs(volume)
lun_name = volume['name']
size = int(volume['size']) * units.Gi
metadata = {'OsType': self.lun_ostype,
'SpaceReserved': 'true',
'Path': '/vol/%s/%s' % (pool_name, lun_name)}
qos_policy_group_info = self._setup_qos_for_volume(volume, extra_specs)
qos_policy_group_name = (
na_utils.get_qos_policy_group_name_from_info(
qos_policy_group_info))
try:
self._create_lun(pool_name, lun_name, size, metadata,
qos_policy_group_name)
except Exception:
LOG.exception(_LE("Exception creating LUN %(name)s in pool "
"%(pool)s."),
{'name': lun_name, 'pool': pool_name})
self._mark_qos_policy_group_for_deletion(qos_policy_group_info)
msg = _("Volume %s could not be created.")
raise exception.VolumeBackendAPIException(data=msg % (
volume['name']))
LOG.debug('Created LUN with name %(name)s and QoS info %(qos)s',
{'name': lun_name, 'qos': qos_policy_group_info})
metadata['Path'] = '/vol/%s/%s' % (pool_name, lun_name)
metadata['Volume'] = pool_name
metadata['Qtree'] = None
handle = self._create_lun_handle(metadata)
self._add_lun_to_table(NetAppLun(handle, lun_name, size, metadata))
def _setup_qos_for_volume(self, volume, extra_specs):
return None
def _mark_qos_policy_group_for_deletion(self, qos_policy_group_info):
return
def delete_volume(self, volume):
"""Driver entry point for destroying existing volumes."""
name = volume['name']
metadata = self._get_lun_attr(name, 'metadata')
if not metadata:
LOG.warning(_LW("No entry in LUN table for volume/snapshot"
" %(name)s."), {'name': name})
return
self.zapi_client.destroy_lun(metadata['Path'])
self.lun_table.pop(name)
def ensure_export(self, context, volume):
"""Driver entry point to get the export info for an existing volume."""
handle = self._get_lun_attr(volume['name'], 'handle')
return {'provider_location': handle}
def create_export(self, context, volume):
"""Driver entry point to get the export info for a new volume."""
handle = self._get_lun_attr(volume['name'], 'handle')
return {'provider_location': handle}
def remove_export(self, context, volume):
"""Driver entry point to remove an export for a volume.
Since exporting is idempotent in this driver, we have nothing
to do for unexporting.
"""
pass
def create_snapshot(self, snapshot):
"""Driver entry point for creating a snapshot.
This driver implements snapshots by using efficient single-file
(LUN) cloning.
"""
vol_name = snapshot['volume_name']
snapshot_name = snapshot['name']
lun = self._get_lun_from_table(vol_name)
self._clone_lun(lun.name, snapshot_name, space_reserved='false')
def delete_snapshot(self, snapshot):
"""Driver entry point for deleting a snapshot."""
self.delete_volume(snapshot)
LOG.debug("Snapshot %s deletion successful", snapshot['name'])
def create_volume_from_snapshot(self, volume, snapshot):
source = {'name': snapshot['name'], 'size': snapshot['volume_size']}
return self._clone_source_to_destination(source, volume)
def create_cloned_volume(self, volume, src_vref):
src_lun = self._get_lun_from_table(src_vref['name'])
source = {'name': src_lun.name, 'size': src_vref['size']}
return self._clone_source_to_destination(source, volume)
def _clone_source_to_destination(self, source, destination_volume):
source_size = source['size']
destination_size = destination_volume['size']
source_name = source['name']
destination_name = destination_volume['name']
extra_specs = na_utils.get_volume_extra_specs(destination_volume)
qos_policy_group_info = self._setup_qos_for_volume(
destination_volume, extra_specs)
qos_policy_group_name = (
na_utils.get_qos_policy_group_name_from_info(
qos_policy_group_info))
try:
self._clone_lun(source_name, destination_name,
space_reserved='true',
qos_policy_group_name=qos_policy_group_name)
if destination_size != source_size:
try:
self.extend_volume(
destination_volume, destination_size,
qos_policy_group_name=qos_policy_group_name)
except Exception:
with excutils.save_and_reraise_exception():
LOG.error(
_LE("Resizing %s failed. Cleaning volume."),
destination_volume['id'])
self.delete_volume(destination_volume)
except Exception:
LOG.exception(_LE("Exception cloning volume %(name)s from source "
"volume %(source)s."),
{'name': destination_name, 'source': source_name})
self._mark_qos_policy_group_for_deletion(qos_policy_group_info)
msg = _("Volume %s could not be created from source volume.")
raise exception.VolumeBackendAPIException(
data=msg % destination_name)
def _create_lun(self, volume_name, lun_name, size,
metadata, qos_policy_group_name=None):
"""Creates a LUN, handling Data ONTAP differences as needed."""
raise NotImplementedError()
def _create_lun_handle(self, metadata):
"""Returns LUN handle based on filer type."""
raise NotImplementedError()
def _extract_lun_info(self, lun):
"""Extracts the LUNs from API and populates the LUN table."""
meta_dict = self._create_lun_meta(lun)
path = lun.get_child_content('path')
(_rest, _splitter, name) = path.rpartition('/')
handle = self._create_lun_handle(meta_dict)
size = lun.get_child_content('size')
return NetAppLun(handle, name, size, meta_dict)
def _extract_and_populate_luns(self, api_luns):
"""Extracts the LUNs from API and populates the LUN table."""
for lun in api_luns:
discovered_lun = self._extract_lun_info(lun)
self._add_lun_to_table(discovered_lun)
def _map_lun(self, name, initiator_list, initiator_type, lun_id=None):
"""Maps LUN to the initiator(s) and returns LUN ID assigned."""
metadata = self._get_lun_attr(name, 'metadata')
path = metadata['Path']
igroup_name, ig_host_os, ig_type = self._get_or_create_igroup(
initiator_list, initiator_type, self.host_type)
if ig_host_os != self.host_type:
LOG.warning(_LW("LUN misalignment may occur for current"
" initiator group %(ig_nm)s) with host OS type"
" %(ig_os)s. Please configure initiator group"
" manually according to the type of the"
" host OS."),
{'ig_nm': igroup_name, 'ig_os': ig_host_os})
try:
return self.zapi_client.map_lun(path, igroup_name, lun_id=lun_id)
except na_api.NaApiError:
exc_info = sys.exc_info()
(_igroup, lun_id) = self._find_mapped_lun_igroup(path,
initiator_list)
if lun_id is not None:
return lun_id
else:
raise exc_info[0], exc_info[1], exc_info[2]
def _unmap_lun(self, path, initiator_list):
"""Unmaps a LUN from given initiator."""
(igroup_name, _lun_id) = self._find_mapped_lun_igroup(path,
initiator_list)
self.zapi_client.unmap_lun(path, igroup_name)
def _find_mapped_lun_igroup(self, path, initiator_list):
"""Find an igroup for a LUN mapped to the given initiator(s)."""
raise NotImplementedError()
def _has_luns_mapped_to_initiators(self, initiator_list):
"""Checks whether any LUNs are mapped to the given initiator(s)."""
return self.zapi_client.has_luns_mapped_to_initiators(initiator_list)
def _get_or_create_igroup(self, initiator_list, initiator_group_type,
host_os_type):
"""Checks for an igroup for a set of one or more initiators.
Creates igroup if not already present with given host os type,
igroup type and adds initiators.
"""
igroups = self.zapi_client.get_igroup_by_initiators(initiator_list)
igroup_name = None
if igroups:
igroup = igroups[0]
igroup_name = igroup['initiator-group-name']
host_os_type = igroup['initiator-group-os-type']
initiator_group_type = igroup['initiator-group-type']
if not igroup_name:
igroup_name = self._create_igroup_add_initiators(
initiator_group_type, host_os_type, initiator_list)
return igroup_name, host_os_type, initiator_group_type
def _create_igroup_add_initiators(self, initiator_group_type,
host_os_type, initiator_list):
"""Creates igroup and adds initiators."""
igroup_name = na_utils.OPENSTACK_PREFIX + six.text_type(uuid.uuid4())
self.zapi_client.create_igroup(igroup_name, initiator_group_type,
host_os_type)
for initiator in initiator_list:
self.zapi_client.add_igroup_initiator(igroup_name, initiator)
return igroup_name
def _add_lun_to_table(self, lun):
"""Adds LUN to cache table."""
if not isinstance(lun, NetAppLun):
msg = _("Object is not a NetApp LUN.")
raise exception.VolumeBackendAPIException(data=msg)
self.lun_table[lun.name] = lun
def _get_lun_from_table(self, name):
"""Gets LUN from cache table.
Refreshes cache if LUN not found in cache.
"""
lun = self.lun_table.get(name)
if lun is None:
lun_list = self.zapi_client.get_lun_list()
self._extract_and_populate_luns(lun_list)
lun = self.lun_table.get(name)
if lun is None:
raise exception.VolumeNotFound(volume_id=name)
return lun
def _clone_lun(self, name, new_name, space_reserved='true',
qos_policy_group_name=None, src_block=0, dest_block=0,
block_count=0):
"""Clone LUN with the given name to the new name."""
raise NotImplementedError()
def _get_lun_attr(self, name, attr):
"""Get the LUN attribute if found else None."""
try:
attr = getattr(self._get_lun_from_table(name), attr)
return attr
except exception.VolumeNotFound as e:
LOG.error(_LE("Message: %s"), e.msg)
except Exception as e:
LOG.error(_LE("Error getting LUN attribute. Exception: %s"), e)
return None
def _create_lun_meta(self, lun):
raise NotImplementedError()
def _get_fc_target_wwpns(self, include_partner=True):
raise NotImplementedError()
def get_volume_stats(self, refresh=False):
"""Get volume stats.
If 'refresh' is True, run update the stats first.
"""
if refresh:
self._update_volume_stats()
return self._stats
def _update_volume_stats(self):
raise NotImplementedError()
def extend_volume(self, volume, new_size, qos_policy_group_name=None):
"""Extend an existing volume to the new size."""
name = volume['name']
lun = self._get_lun_from_table(name)
path = lun.metadata['Path']
curr_size_bytes = six.text_type(lun.size)
new_size_bytes = six.text_type(int(new_size) * units.Gi)
# Reused by clone scenarios.
# Hence comparing the stored size.
if curr_size_bytes != new_size_bytes:
lun_geometry = self.zapi_client.get_lun_geometry(path)
if (lun_geometry and lun_geometry.get("max_resize")
and int(lun_geometry.get("max_resize")) >=
int(new_size_bytes)):
self.zapi_client.do_direct_resize(path, new_size_bytes)
else:
self._do_sub_clone_resize(
path, new_size_bytes,
qos_policy_group_name=qos_policy_group_name)
self.lun_table[name].size = new_size_bytes
else:
LOG.info(_LI("No need to extend volume %s"
" as it is already the requested new size."), name)
def _get_vol_option(self, volume_name, option_name):
"""Get the value for the volume option."""
value = None
options = self.zapi_client.get_volume_options(volume_name)
for opt in options:
if opt.get_child_content('name') == option_name:
value = opt.get_child_content('value')
break
return value
def _do_sub_clone_resize(self, path, new_size_bytes,
qos_policy_group_name=None):
"""Does sub LUN clone after verification.
Clones the block ranges and swaps
the LUNs also deletes older LUN
after a successful clone.
"""
seg = path.split("/")
LOG.info(_LI("Resizing LUN %s to new size using clone operation."),
seg[-1])
name = seg[-1]
vol_name = seg[2]
lun = self._get_lun_from_table(name)
metadata = lun.metadata
compression = self._get_vol_option(vol_name, 'compression')
if compression == "on":
msg = _('%s cannot be resized using clone operation'
' as it is hosted on compressed volume')
raise exception.VolumeBackendAPIException(data=msg % name)
else:
block_count = self._get_lun_block_count(path)
if block_count == 0:
msg = _('%s cannot be resized using clone operation'
' as it contains no blocks.')
raise exception.VolumeBackendAPIException(data=msg % name)
new_lun = 'new-%s' % name
self.zapi_client.create_lun(
vol_name, new_lun, new_size_bytes, metadata,
qos_policy_group_name=qos_policy_group_name)
try:
self._clone_lun(name, new_lun, block_count=block_count,
qos_policy_group_name=qos_policy_group_name)
self._post_sub_clone_resize(path)
except Exception:
with excutils.save_and_reraise_exception():
new_path = '/vol/%s/%s' % (vol_name, new_lun)
self.zapi_client.destroy_lun(new_path)
def _post_sub_clone_resize(self, path):
"""Try post sub clone resize in a transactional manner."""
st_tm_mv, st_nw_mv, st_del_old = None, None, None
seg = path.split("/")
LOG.info(_LI("Post clone resize LUN %s"), seg[-1])
new_lun = 'new-%s' % (seg[-1])
tmp_lun = 'tmp-%s' % (seg[-1])
tmp_path = "/vol/%s/%s" % (seg[2], tmp_lun)
new_path = "/vol/%s/%s" % (seg[2], new_lun)
try:
st_tm_mv = self.zapi_client.move_lun(path, tmp_path)
st_nw_mv = self.zapi_client.move_lun(new_path, path)
st_del_old = self.zapi_client.destroy_lun(tmp_path)
except Exception as e:
if st_tm_mv is None:
msg = _("Failure staging LUN %s to tmp.")
raise exception.VolumeBackendAPIException(data=msg % (seg[-1]))
else:
if st_nw_mv is None:
self.zapi_client.move_lun(tmp_path, path)
msg = _("Failure moving new cloned LUN to %s.")
raise exception.VolumeBackendAPIException(
data=msg % (seg[-1]))
elif st_del_old is None:
LOG.error(_LE("Failure deleting staged tmp LUN %s."),
tmp_lun)
else:
LOG.error(_LE("Unknown exception in"
" post clone resize LUN %s."), seg[-1])
LOG.error(_LE("Exception details: %s"), e)
def _get_lun_block_count(self, path):
"""Gets block counts for the LUN."""
LOG.debug("Getting LUN block count.")
lun_infos = self.zapi_client.get_lun_by_args(path=path)
if not lun_infos:
seg = path.split('/')
msg = _('Failure getting LUN info for %s.')
raise exception.VolumeBackendAPIException(data=msg % seg[-1])
lun_info = lun_infos[-1]
bs = int(lun_info.get_child_content('block-size'))
ls = int(lun_info.get_child_content('size'))
block_count = ls / bs
return block_count
def _check_volume_type_for_lun(self, volume, lun, existing_ref,
extra_specs):
"""Checks if lun satifies the volume type."""
raise NotImplementedError()
def manage_existing(self, volume, existing_ref):
"""Brings an existing storage object under Cinder management.
existing_ref can contain source-id or source-name or both.
source-id: lun uuid.
source-name: complete lun path eg. /vol/vol0/lun.
"""
lun = self._get_existing_vol_with_manage_ref(existing_ref)
extra_specs = na_utils.get_volume_extra_specs(volume)
self._check_volume_type_for_lun(volume, lun, existing_ref, extra_specs)
qos_policy_group_info = self._setup_qos_for_volume(volume, extra_specs)
qos_policy_group_name = (
na_utils.get_qos_policy_group_name_from_info(
qos_policy_group_info))
path = lun.get_metadata_property('Path')
if lun.name == volume['name']:
new_path = path
LOG.info(_LI("LUN with given ref %s need not be renamed "
"during manage operation."), existing_ref)
else:
(rest, splitter, name) = path.rpartition('/')
new_path = '%s/%s' % (rest, volume['name'])
self.zapi_client.move_lun(path, new_path)
lun = self._get_existing_vol_with_manage_ref(
{'source-name': new_path})
if qos_policy_group_name is not None:
self.zapi_client.set_lun_qos_policy_group(new_path,
qos_policy_group_name)
self._add_lun_to_table(lun)
LOG.info(_LI("Manage operation completed for LUN with new path"
" %(path)s and uuid %(uuid)s."),
{'path': lun.get_metadata_property('Path'),
'uuid': lun.get_metadata_property('UUID')})
def manage_existing_get_size(self, volume, existing_ref):
"""Return size of volume to be managed by manage_existing.
When calculating the size, round up to the next GB.
"""
lun = self._get_existing_vol_with_manage_ref(existing_ref)
return int(math.ceil(float(lun.size) / units.Gi))
def _get_existing_vol_with_manage_ref(self, existing_ref):
"""Get the corresponding LUN from the storage server."""
uuid = existing_ref.get('source-id')
path = existing_ref.get('source-name')
if not (uuid or path):
reason = _('Reference must contain either source-id'
' or source-name element.')
raise exception.ManageExistingInvalidReference(
existing_ref=existing_ref, reason=reason)
lun_info = {}
lun_info.setdefault('path', path if path else None)
if hasattr(self, 'vserver') and uuid:
lun_info['uuid'] = uuid
luns = self.zapi_client.get_lun_by_args(**lun_info)
if luns:
for lun in luns:
netapp_lun = self._extract_lun_info(lun)
storage_valid = self._is_lun_valid_on_storage(netapp_lun)
uuid_valid = True
if uuid:
if netapp_lun.get_metadata_property('UUID') == uuid:
uuid_valid = True
else:
uuid_valid = False
if storage_valid and uuid_valid:
return netapp_lun
raise exception.ManageExistingInvalidReference(
existing_ref=existing_ref,
reason=(_('LUN not found with given ref %s.') % existing_ref))
def _is_lun_valid_on_storage(self, lun):
"""Validate lun specific to storage system."""
return True
def unmanage(self, volume):
"""Removes the specified volume from Cinder management.
Does not delete the underlying backend storage object.
"""
managed_lun = self._get_lun_from_table(volume['name'])
LOG.info(_LI("Unmanaged LUN with current path %(path)s and uuid "
"%(uuid)s."),
{'path': managed_lun.get_metadata_property('Path'),
'uuid': managed_lun.get_metadata_property('UUID')
or 'unknown'})
def initialize_connection_iscsi(self, volume, connector):
"""Driver entry point to attach a volume to an instance.
Do the LUN masking on the storage system so the initiator can access
the LUN on the target. Also return the iSCSI properties so the
initiator can find the LUN. This implementation does not call
_get_iscsi_properties() to get the properties because cannot store the
LUN number in the database. We only find out what the LUN number will
be during this method call so we construct the properties dictionary
ourselves.
"""
initiator_name = connector['initiator']
name = volume['name']
lun_id = self._map_lun(name, [initiator_name], 'iscsi', None)
LOG.debug("Mapped LUN %(name)s to the initiator %(initiator_name)s",
{'name': name, 'initiator_name': initiator_name})
target_list = self.zapi_client.get_iscsi_target_details()
if not target_list:
raise exception.VolumeBackendAPIException(
data=_('Failed to get LUN target list for the LUN %s') % name)
LOG.debug("Successfully fetched target list for LUN %(name)s and "
"initiator %(initiator_name)s",
{'name': name, 'initiator_name': initiator_name})
preferred_target = self._get_preferred_target_from_list(
target_list)
if preferred_target is None:
msg = _('Failed to get target portal for the LUN %s')
raise exception.VolumeBackendAPIException(data=msg % name)
(address, port) = (preferred_target['address'],
preferred_target['port'])
iqn = self.zapi_client.get_iscsi_service_details()
if not iqn:
msg = _('Failed to get target IQN for the LUN %s')
raise exception.VolumeBackendAPIException(data=msg % name)
properties = na_utils.get_iscsi_connection_properties(lun_id, volume,
iqn, address,
port)
return properties
def _get_preferred_target_from_list(self, target_details_list,
filter=None):
preferred_target = None
for target in target_details_list:
if filter and target['address'] not in filter:
continue
if target.get('interface-enabled', 'true') == 'true':
preferred_target = target
break
if preferred_target is None and len(target_details_list) > 0:
preferred_target = target_details_list[0]
return preferred_target
def terminate_connection_iscsi(self, volume, connector, **kwargs):
"""Driver entry point to unattach a volume from an instance.
Unmask the LUN on the storage system so the given initiator can no
longer access it.
"""
initiator_name = connector['initiator']
name = volume['name']
metadata = self._get_lun_attr(name, 'metadata')
path = metadata['Path']
self._unmap_lun(path, [initiator_name])
LOG.debug("Unmapped LUN %(name)s from the initiator "
"%(initiator_name)s",
{'name': name, 'initiator_name': initiator_name})
def initialize_connection_fc(self, volume, connector):
"""Initializes the connection and returns connection info.
Assign any created volume to a compute node/host so that it can be
used from that host.
The driver returns a driver_volume_type of 'fibre_channel'.
The target_wwn can be a single entry or a list of wwns that
correspond to the list of remote wwn(s) that will export the volume.
Example return values:
{
'driver_volume_type': 'fibre_channel'
'data': {
'target_discovered': True,
'target_lun': 1,
'target_wwn': '500a098280feeba5',
'access_mode': 'rw',
'initiator_target_map': {
'21000024ff406cc3': ['500a098280feeba5'],
'21000024ff406cc2': ['500a098280feeba5']
}
}
}
or
{
'driver_volume_type': 'fibre_channel'
'data': {
'target_discovered': True,
'target_lun': 1,
'target_wwn': ['500a098280feeba5', '500a098290feeba5',
'500a098190feeba5', '500a098180feeba5'],
'access_mode': 'rw',
'initiator_target_map': {
'21000024ff406cc3': ['500a098280feeba5',
'500a098290feeba5'],
'21000024ff406cc2': ['500a098190feeba5',
'500a098180feeba5']
}
}
}
"""
initiators = [fczm_utils.get_formatted_wwn(wwpn)
for wwpn in connector['wwpns']]
volume_name = volume['name']
lun_id = self._map_lun(volume_name, initiators, 'fcp', None)
LOG.debug("Mapped LUN %(name)s to the initiator(s) %(initiators)s",
{'name': volume_name, 'initiators': initiators})
target_wwpns, initiator_target_map, num_paths = (
self._build_initiator_target_map(connector))
if target_wwpns:
LOG.debug("Successfully fetched target details for LUN %(name)s "
"and initiator(s) %(initiators)s",
{'name': volume_name, 'initiators': initiators})
else:
raise exception.VolumeBackendAPIException(
data=_('Failed to get LUN target details for '
'the LUN %s') % volume_name)
target_info = {'driver_volume_type': 'fibre_channel',
'data': {'target_discovered': True,
'target_lun': int(lun_id),
'target_wwn': target_wwpns,
'access_mode': 'rw',
'initiator_target_map': initiator_target_map}}
return target_info
def terminate_connection_fc(self, volume, connector, **kwargs):
"""Disallow connection from connector.
Return empty data if other volumes are in the same zone.
The FibreChannel ZoneManager doesn't remove zones
if there isn't an initiator_target_map in the
return of terminate_connection.
:returns: data - the target_wwns and initiator_target_map if the
zone is to be removed, otherwise the same map with
an empty dict for the 'data' key
"""
initiators = [fczm_utils.get_formatted_wwn(wwpn)
for wwpn in connector['wwpns']]
name = volume['name']
metadata = self._get_lun_attr(name, 'metadata')
path = metadata['Path']
self._unmap_lun(path, initiators)
LOG.debug("Unmapped LUN %(name)s from the initiator %(initiators)s",
{'name': name, 'initiators': initiators})
info = {'driver_volume_type': 'fibre_channel',
'data': {}}
if not self._has_luns_mapped_to_initiators(initiators):
# No more exports for this host, so tear down zone.
LOG.info(_LI("Need to remove FC Zone, building initiator "
"target map"))
target_wwpns, initiator_target_map, num_paths = (
self._build_initiator_target_map(connector))
info['data'] = {'target_wwn': target_wwpns,
'initiator_target_map': initiator_target_map}
return info
def _build_initiator_target_map(self, connector):
"""Build the target_wwns and the initiator target map."""
# get WWPNs from controller and strip colons
all_target_wwpns = self._get_fc_target_wwpns()
all_target_wwpns = [six.text_type(wwpn).replace(':', '')
for wwpn in all_target_wwpns]
target_wwpns = []
init_targ_map = {}
num_paths = 0
if self.lookup_service is not None:
# Use FC SAN lookup to determine which ports are visible.
dev_map = self.lookup_service.get_device_mapping_from_network(
connector['wwpns'],
all_target_wwpns)
for fabric_name in dev_map:
fabric = dev_map[fabric_name]
target_wwpns += fabric['target_port_wwn_list']
for initiator in fabric['initiator_port_wwn_list']:
if initiator not in init_targ_map:
init_targ_map[initiator] = []
init_targ_map[initiator] += fabric['target_port_wwn_list']
init_targ_map[initiator] = list(set(
init_targ_map[initiator]))
for target in init_targ_map[initiator]:
num_paths += 1
target_wwpns = list(set(target_wwpns))
else:
initiator_wwns = connector['wwpns']
target_wwpns = all_target_wwpns
for initiator in initiator_wwns:
init_targ_map[initiator] = target_wwpns
return target_wwpns, init_targ_map, num_paths
|
julianwang/cinder
|
cinder/volume/drivers/netapp/dataontap/block_base.py
|
Python
|
apache-2.0
| 37,442
|
/*
* Copyright 2016-2021 52°North Spatial Information Research GmbH
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.n52.javaps.rest.model;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.JsonNode;
import org.springframework.validation.annotation.Validated;
import javax.validation.constraints.NotNull;
import java.util.Objects;
/**
* Input
*/
@Validated
public class Input {
@JsonProperty("id")
private String id;
@JsonProperty("input")
private JsonNode input;
public Input id(String id) {
this.id = id;
return this;
}
/**
* Get id
*
* @return id
**/
@NotNull
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public Input input(JsonNode input) {
this.input = input;
return this;
}
/**
* Get input
*
* @return input
**/
@NotNull
public JsonNode getInput() {
return input;
}
public void setInput(JsonNode input) {
this.input = input;
}
@Override
public boolean equals(java.lang.Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Input other = (Input) o;
return Objects.equals(this.id, other.id) && Objects.equals(this.input, other.input);
}
@Override
public int hashCode() {
return Objects.hash(id, input);
}
@Override
public String toString() {
return String.format("class Input {id: %s, input: %s}", id, input);
}
}
|
52North/javaPS
|
rest/src/main/java/org/n52/javaps/rest/model/Input.java
|
Java
|
apache-2.0
| 2,201
|
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<title>Uses of Class org.deidentifier.arx.ARXResult (ARX API Documentation)</title>
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">
</head>
<body>
<script type="text/javascript"><!--
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Uses of Class org.deidentifier.arx.ARXResult (ARX API Documentation)";
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar_top">
<!-- -->
</a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../org/deidentifier/arx/ARXResult.html" title="class in org.deidentifier.arx">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../package-tree.html">Tree</a></li>
<li><a href="../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../index-files/index-1.html">Index</a></li>
<li><a href="../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../index.html?org/deidentifier/arx/class-use/ARXResult.html" target="_top">Frames</a></li>
<li><a href="ARXResult.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip-navbar_top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<div class="header">
<h2 title="Uses of Class org.deidentifier.arx.ARXResult" class="title">Uses of Class<br>org.deidentifier.arx.ARXResult</h2>
</div>
<div class="classUseContainer">
<ul class="blockList">
<li class="blockList">
<table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing packages, and an explanation">
<caption><span>Packages that use <a href="../../../../org/deidentifier/arx/ARXResult.html" title="class in org.deidentifier.arx">ARXResult</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Package</th>
<th class="colLast" scope="col">Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><a href="#org.deidentifier.arx">org.deidentifier.arx</a></td>
<td class="colLast">
<div class="block">This package provides the public API for the ARX anonymization framework.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="#org.deidentifier.arx.certificate">org.deidentifier.arx.certificate</a></td>
<td class="colLast"> </td>
</tr>
</tbody>
</table>
</li>
<li class="blockList">
<ul class="blockList">
<li class="blockList"><a name="org.deidentifier.arx">
<!-- -->
</a>
<h3>Uses of <a href="../../../../org/deidentifier/arx/ARXResult.html" title="class in org.deidentifier.arx">ARXResult</a> in <a href="../../../../org/deidentifier/arx/package-summary.html">org.deidentifier.arx</a></h3>
<table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation">
<caption><span>Methods in <a href="../../../../org/deidentifier/arx/package-summary.html">org.deidentifier.arx</a> that return <a href="../../../../org/deidentifier/arx/ARXResult.html" title="class in org.deidentifier.arx">ARXResult</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><code><a href="../../../../org/deidentifier/arx/ARXResult.html" title="class in org.deidentifier.arx">ARXResult</a></code></td>
<td class="colLast"><span class="strong">ARXAnonymizer.</span><code><strong><a href="../../../../org/deidentifier/arx/ARXAnonymizer.html#anonymize(org.deidentifier.arx.Data,%20org.deidentifier.arx.ARXConfiguration)">anonymize</a></strong>(<a href="../../../../org/deidentifier/arx/Data.html" title="class in org.deidentifier.arx">Data</a> data,
<a href="../../../../org/deidentifier/arx/ARXConfiguration.html" title="class in org.deidentifier.arx">ARXConfiguration</a> config)</code>
<div class="block">Performs data anonymization.</div>
</td>
</tr>
</tbody>
</table>
</li>
<li class="blockList"><a name="org.deidentifier.arx.certificate">
<!-- -->
</a>
<h3>Uses of <a href="../../../../org/deidentifier/arx/ARXResult.html" title="class in org.deidentifier.arx">ARXResult</a> in <a href="../../../../org/deidentifier/arx/certificate/package-summary.html">org.deidentifier.arx.certificate</a></h3>
<table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation">
<caption><span>Methods in <a href="../../../../org/deidentifier/arx/certificate/package-summary.html">org.deidentifier.arx.certificate</a> with parameters of type <a href="../../../../org/deidentifier/arx/ARXResult.html" title="class in org.deidentifier.arx">ARXResult</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><code>static <a href="../../../../org/deidentifier/arx/certificate/ARXCertificate.html" title="class in org.deidentifier.arx.certificate">ARXCertificate</a></code></td>
<td class="colLast"><span class="strong">ARXCertificate.</span><code><strong><a href="../../../../org/deidentifier/arx/certificate/ARXCertificate.html#create(org.deidentifier.arx.DataHandle,%20org.deidentifier.arx.DataDefinition,%20org.deidentifier.arx.ARXConfiguration,%20org.deidentifier.arx.ARXResult,%20org.deidentifier.arx.ARXLattice.ARXNode,%20org.deidentifier.arx.DataHandle)">create</a></strong>(<a href="../../../../org/deidentifier/arx/DataHandle.html" title="class in org.deidentifier.arx">DataHandle</a> input,
<a href="../../../../org/deidentifier/arx/DataDefinition.html" title="class in org.deidentifier.arx">DataDefinition</a> definition,
<a href="../../../../org/deidentifier/arx/ARXConfiguration.html" title="class in org.deidentifier.arx">ARXConfiguration</a> config,
<a href="../../../../org/deidentifier/arx/ARXResult.html" title="class in org.deidentifier.arx">ARXResult</a> result,
<a href="../../../../org/deidentifier/arx/ARXLattice.ARXNode.html" title="class in org.deidentifier.arx">ARXLattice.ARXNode</a> transformation,
<a href="../../../../org/deidentifier/arx/DataHandle.html" title="class in org.deidentifier.arx">DataHandle</a> output)</code>
<div class="block">Creates a new instance</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>static <a href="../../../../org/deidentifier/arx/certificate/ARXCertificate.html" title="class in org.deidentifier.arx.certificate">ARXCertificate</a></code></td>
<td class="colLast"><span class="strong">ARXCertificate.</span><code><strong><a href="../../../../org/deidentifier/arx/certificate/ARXCertificate.html#create(org.deidentifier.arx.DataHandle,%20org.deidentifier.arx.DataDefinition,%20org.deidentifier.arx.ARXConfiguration,%20org.deidentifier.arx.ARXResult,%20org.deidentifier.arx.ARXLattice.ARXNode,%20org.deidentifier.arx.DataHandle,%20org.deidentifier.arx.io.CSVSyntax)">create</a></strong>(<a href="../../../../org/deidentifier/arx/DataHandle.html" title="class in org.deidentifier.arx">DataHandle</a> input,
<a href="../../../../org/deidentifier/arx/DataDefinition.html" title="class in org.deidentifier.arx">DataDefinition</a> definition,
<a href="../../../../org/deidentifier/arx/ARXConfiguration.html" title="class in org.deidentifier.arx">ARXConfiguration</a> config,
<a href="../../../../org/deidentifier/arx/ARXResult.html" title="class in org.deidentifier.arx">ARXResult</a> result,
<a href="../../../../org/deidentifier/arx/ARXLattice.ARXNode.html" title="class in org.deidentifier.arx">ARXLattice.ARXNode</a> transformation,
<a href="../../../../org/deidentifier/arx/DataHandle.html" title="class in org.deidentifier.arx">DataHandle</a> output,
<a href="../../../../org/deidentifier/arx/io/CSVSyntax.html" title="class in org.deidentifier.arx.io">CSVSyntax</a> syntax)</code>
<div class="block">Renders the document into the given output stream.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>static <a href="../../../../org/deidentifier/arx/certificate/ARXCertificate.html" title="class in org.deidentifier.arx.certificate">ARXCertificate</a></code></td>
<td class="colLast"><span class="strong">ARXCertificate.</span><code><strong><a href="../../../../org/deidentifier/arx/certificate/ARXCertificate.html#create(org.deidentifier.arx.DataHandle,%20org.deidentifier.arx.DataDefinition,%20org.deidentifier.arx.ARXConfiguration,%20org.deidentifier.arx.ARXResult,%20org.deidentifier.arx.ARXLattice.ARXNode,%20org.deidentifier.arx.DataHandle,%20org.deidentifier.arx.io.CSVSyntax,%20org.deidentifier.arx.certificate.elements.ElementData)">create</a></strong>(<a href="../../../../org/deidentifier/arx/DataHandle.html" title="class in org.deidentifier.arx">DataHandle</a> input,
<a href="../../../../org/deidentifier/arx/DataDefinition.html" title="class in org.deidentifier.arx">DataDefinition</a> definition,
<a href="../../../../org/deidentifier/arx/ARXConfiguration.html" title="class in org.deidentifier.arx">ARXConfiguration</a> config,
<a href="../../../../org/deidentifier/arx/ARXResult.html" title="class in org.deidentifier.arx">ARXResult</a> result,
<a href="../../../../org/deidentifier/arx/ARXLattice.ARXNode.html" title="class in org.deidentifier.arx">ARXLattice.ARXNode</a> transformation,
<a href="../../../../org/deidentifier/arx/DataHandle.html" title="class in org.deidentifier.arx">DataHandle</a> output,
<a href="../../../../org/deidentifier/arx/io/CSVSyntax.html" title="class in org.deidentifier.arx.io">CSVSyntax</a> syntax,
<a href="../../../../org/deidentifier/arx/certificate/elements/ElementData.html" title="class in org.deidentifier.arx.certificate.elements">ElementData</a> metadata)</code>
<div class="block">Renders the document into the given output stream.</div>
</td>
</tr>
</tbody>
</table>
</li>
</ul>
</li>
</ul>
</div>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar_bottom">
<!-- -->
</a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../org/deidentifier/arx/ARXResult.html" title="class in org.deidentifier.arx">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../package-tree.html">Tree</a></li>
<li><a href="../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../index-files/index-1.html">Index</a></li>
<li><a href="../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../index.html?org/deidentifier/arx/class-use/ARXResult.html" target="_top">Frames</a></li>
<li><a href="ARXResult.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip-navbar_bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
</body>
</html>
|
kbabioch/arx
|
doc/api/org/deidentifier/arx/class-use/ARXResult.html
|
HTML
|
apache-2.0
| 12,529
|
/** @file
* Copyright (c) 2018, Arm Limited or its affiliates. All rights reserved.
* SPDX-License-Identifier : Apache-2.0
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
#include <Library/ShellCEntryLib.h>
#include <Library/UefiBootServicesTableLib.h>
#include <Library/UefiLib.h>
#include <Library/ShellLib.h>
#include <Library/PrintLib.h>
#include "include/pal_uefi.h"
UINT8 *gSharedMemory;
UINT8 **gSharedMemCpyBuf;
UINT64 **gSharedLatencyBuf;
/**
* @brief Provides a single point of abstraction to read from all
* Memory Mapped IO address
*
* @param addr 64-bit address
*
* @return 32-bit data read from the input address
*/
UINT32
pal_mmio_read(UINT64 addr)
{
UINT32 data;
if (addr & 0x3) {
acs_print(ACS_PRINT_WARN, L"\n Error-Input address is not aligned. Masking the last 2 bits \n");
addr = addr & ~(0x3); //make sure addr is aligned to 4 bytes
}
data = (*(volatile UINT32 *)addr);
acs_print(ACS_PRINT_INFO, L" pal_mmio_read Address = %8x Data = %x \n", addr, data);
return data;
}
/**
* @brief Provides a single point of abstraction to write to all
* Memory Mapped IO address
*
* @param addr 64-bit address
* @param data 32-bit data to write to address
*
* @return None
*/
VOID
pal_mmio_write(UINT64 addr, UINT32 data)
{
acs_print(ACS_PRINT_INFO, L" pal_mmio_write Address = %8x Data = %x \n", addr, data);
*(volatile UINT32 *)addr = data;
}
/**
* @brief Sends a formatted string to the output console
*
* @param string An ASCII string
* @param data data for the formatted output
*
* @return None
*/
VOID
pal_print(CHAR8 *string, UINT64 data)
{
if (g_acs_log_file_handle) {
CHAR8 Buffer[1024];
UINTN BufferSize = 1;
EFI_STATUS Status = 0;
BufferSize = AsciiSPrint(Buffer, 1024, string, data);
AsciiPrint(Buffer);
Status = ShellWriteFile(g_acs_log_file_handle, &BufferSize, (VOID*)Buffer);
if (EFI_ERROR(Status)) {
acs_print(ACS_PRINT_ERR, L"Error in writing to log file\n");
}
} else {
AsciiPrint(string, data);
}
}
/**
* @brief Sends a string to the output console without using UEFI print function
* This function will get COMM port address and directly writes to the addr char-by-char
*
* @param string An ASCII string
* @param data data for the formatted output
*
* @return None
*/
VOID
pal_print_raw(UINT64 addr, CHAR8 *string, UINT64 data)
{
UINT8 j, buffer[16];
INT8 i=0;
for ( ; *string!='\0'; ++string) {
if (*string == '%') {
++string;
if (*string == 'd') {
while (data != 0) {
j = data%10;
data = data/10;
buffer[i]= j + 48 ;
i = i+1;
}
} else if (*string == 'x' || *string == 'X') {
while (data != 0) {
j = data & 0xf;
data = data >> 4;
buffer[i]= j + ((j > 9) ? 55 : 48) ;
i = i+1;
}
}
if (i > 0) {
while (i >= 0)
*(volatile UINT8 *)addr = buffer[--i];
} else
*(volatile UINT8 *)addr = 48;
} else
*(volatile UINT8 *)addr = *string;
}
}
/**
* @brief Free the memory allocated by UEFI Framework APIs
*
* @param Buffer the base address of the memory range to be freed
*
* @return None
*/
VOID
pal_mem_free(VOID *Buffer)
{
gBS->FreePool (Buffer);
}
/**
* @brief Allocate memory which is to be used to share data across PEs
*
* @param num_pe Number of PEs in the system
* @param sizeofentry Size of memory region allocated to each PE
*
* @return None
*/
VOID
pal_mem_allocate_shared(UINT32 num_pe, UINT32 sizeofentry)
{
EFI_STATUS Status;
gSharedMemory = 0;
Status = gBS->AllocatePool ( EfiBootServicesData,
(num_pe * sizeofentry),
(VOID **) &gSharedMemory );
acs_print(ACS_PRINT_INFO, L"Shared memory is %llx \n", gSharedMemory);
if (EFI_ERROR(Status)) {
acs_print(ACS_PRINT_ERR, L"Allocate Pool shared memory failed %x \n", Status);
}
pal_pe_data_cache_ops_by_va((UINT64)&gSharedMemory, CLEAN_AND_INVALIDATE);
return;
}
/**
* @brief Return the base address of the shared memory region to the VAL layer
*
* @param None
*
* @return shared memory region address
*/
UINT64
pal_mem_get_shared_addr()
{
/* Shared memory is always less than 4GB for now */
return (UINT64) (gSharedMemory);
}
/**
* @brief Free the shared memory region allocated above
*
* @param None
*
* @return None
*/
VOID
pal_mem_free_shared()
{
gBS->FreePool ((VOID *)gSharedMemory);
}
/**
* @brief Allocate large memory from specific memory node to share across PEs
*
* @param MemBase base address of the memory node
* @param MemSize size of the memory node
* @param BufSize size of each shared buffer
* @param PeCnt number of pes to create shared buffers
*
* @return Status 1 for success, 0 for failure
*/
UINT8
pal_mem_allocate_shared_memcpybuf (
UINT64 MemBase,
UINT64 MemSize,
UINT64 BufSize,
UINT32 PeCnt
)
{
EFI_STATUS Status;
VOID *Buffer;
UINT32 PeIndex;
Buffer = NULL;
gSharedMemCpyBuf = NULL;
Status = gBS->AllocatePool ( EfiBootServicesData,
(PeCnt * sizeof(UINT64)),
(VOID **) &Buffer );
if (EFI_ERROR(Status)) {
acs_print(ACS_PRINT_ERR, L"Allocate Pool for shared memcpy buf failed %x \n", Status);
return 0;
}
gSharedMemCpyBuf = (UINT8 **)Buffer;
for (PeIndex = 0; PeIndex < PeCnt; PeIndex++) {
gSharedMemCpyBuf[PeIndex] = (uint8_t *) pal_mem_allocate_address (
MemBase + PeIndex*BufSize,
MemSize,
BufSize
);
if (gSharedMemCpyBuf[PeIndex] == NULL) {
acs_print(ACS_PRINT_ERR, L"Allocate address for shared memcpy buf failed %x \n", PeIndex);
pal_mem_free_shared_memcpybuf(PeIndex, BufSize);
return 0;
}
}
pal_pe_data_cache_ops_by_va((UINT64)&gSharedMemCpyBuf, CLEAN_AND_INVALIDATE);
return 1;
}
/**
* @brief Return the base address of the shared buffer to the VAL layer
*
* @param None
*
* @return shared buffer start address
*/
UINT64
pal_mem_get_shared_memcpybuf_addr()
{
return (UINT64) (gSharedMemCpyBuf);
}
/**
* @brief Free the shared mem copy buffers allocated for all pe
*
* @param PeCnt number of pes holding memcopy buffers
* @param BufSize size of shared buffer each pe holding
*
* @return None
*/
VOID
pal_mem_free_shared_memcpybuf (
UINT32 PeCnt,
UINT64 BufSize
)
{
UINT32 PeIndex;
for (PeIndex = 0; PeIndex < PeCnt; PeIndex++) {
pal_mem_free_buf((VOID *)(UINT64)gSharedMemCpyBuf[PeIndex], (UINTN)BufSize);
}
gBS->FreePool ((VOID *)gSharedMemCpyBuf);
}
/**
* @brief Allocate memory which is to be used to share large memories across PEs
*
* @param node_cnt Number of MPAM supported memory nodes in the system
* @param sizeofentry Size of memory region allocated to each memory node
*
* @return None
*/
VOID
pal_mem_allocate_shared_latencybuf (
UINT32 NodeCnt,
UINT32 ScenarioCnt
)
{
EFI_STATUS Status;
VOID *Buffer;
UINT32 NodeIndex;
Buffer = NULL;
gSharedLatencyBuf = NULL;
Status = gBS->AllocatePool ( EfiBootServicesData,
(NodeCnt * sizeof(UINT64)),
(VOID **) &Buffer );
if (EFI_ERROR(Status)) {
acs_print(ACS_PRINT_ERR, L"Allocate Pool shared latency buf failed %x \n", Status);
}
gSharedLatencyBuf = (UINT64 **)Buffer;
for (NodeIndex = 0; NodeIndex < NodeCnt; NodeIndex++) {
Buffer = NULL;
gSharedLatencyBuf[NodeIndex] = NULL;
Status = gBS->AllocatePool ( EfiBootServicesData,
(ScenarioCnt * sizeof(UINT64)),
(VOID **) &Buffer );
if (EFI_ERROR(Status)) {
acs_print(ACS_PRINT_ERR, L"Allocate Pool shared latency buf failed %x \n", Status);
}
gSharedLatencyBuf[NodeIndex] = (UINT64 *)Buffer;
}
pal_pe_data_cache_ops_by_va((UINT64)&gSharedLatencyBuf, CLEAN_AND_INVALIDATE);
return;
}
/**
* @brief Return the base address of the shared latency buffer to the VAL layer
*
* @param None
*
* @return shared latency buffer start address
*/
UINT64
pal_mem_get_shared_latencybuf_addr()
{
return (UINT64) (gSharedLatencyBuf);
}
/**
* @brief Free the shared latency buffers allocated for all pe
*
* @param PeCnt number of pes holding latency buffers
*
* @return None
*/
VOID
pal_mem_free_shared_latencybuf (
UINT32 NodeCnt
)
{
UINT32 NodeIndex;
for (NodeIndex = 0; NodeIndex < NodeCnt; NodeIndex++) {
gBS->FreePool ((VOID *)(UINT64)gSharedLatencyBuf[NodeIndex]);
}
gBS->FreePool ((VOID *)gSharedLatencyBuf);
}
/**
* @brief Allocates requested buffer size @bytes in a contiguous memory
* and returns the base address of the range
*
* @param Size allocation size in bytes
* @retval if SUCCESS pointer to allocated memory
* @retval if FAILURE NULL
*/
VOID *
pal_mem_allocate_buf (
UINTN Size
)
{
EFI_STATUS Status;
EFI_PHYSICAL_ADDRESS BaseAddr;
VOID *Buffer;
Buffer = NULL;
Status = gBS->AllocatePages (
AllocateAnyPages,
EfiBootServicesData,
EFI_SIZE_TO_PAGES (Size),
&BaseAddr
);
if (EFI_ERROR(Status)) {
acs_print(ACS_PRINT_ERR, L"AllocatePages failed %x \n", Status);
} else {
Buffer = (VOID *) (UINTN) BaseAddr;
}
return Buffer;
}
/**
* @brief Allocates requested buffer size @bytes in a contiguous memory
* and returns the base address of the range at the specified base
*
* @param MemNodeBase base address of the memory node
* @param MemNodeBase
* @param Size allocation size in bytes
* @retval if SUCCESS pointer to allocated memory
* @retval if FAILURE NULL
*/
VOID *
pal_mem_allocate_address (
UINT64 MemBase,
UINT64 MemSize,
UINTN BufSize
)
{
EFI_STATUS Status;
EFI_PHYSICAL_ADDRESS BaseAddr;
VOID *Buffer;
Buffer = NULL;
while (MemSize) {
BaseAddr = (EFI_PHYSICAL_ADDRESS)MemBase;
Status = gBS->AllocatePages (
AllocateAddress,
EfiBootServicesData,
EFI_SIZE_TO_PAGES (BufSize),
&BaseAddr
);
MemSize -= BufSize;
MemBase += BufSize;
if (!EFI_ERROR(Status) || (MemSize < BufSize)) {
break;
}
}
if (EFI_ERROR(Status)) {
acs_print(ACS_PRINT_ERR, L"AllocatePages failed %x \n", Status);
} else {
Buffer = (VOID *) (UINTN) BaseAddr;
}
return Buffer;
}
VOID
pal_mem_copy (
VOID *SourceAddr,
VOID *DestinationAddr,
UINTN Length
)
{
gBS->CopyMem (SourceAddr, DestinationAddr, Length);
}
VOID
pal_mem_free_buf (
VOID *Buffer,
UINTN Size
)
{
gBS->FreePages ((EFI_PHYSICAL_ADDRESS)(UINTN)Buffer, EFI_SIZE_TO_PAGES (Size));
}
|
ARM-software/arm-enterprise-acs
|
mpam/platform/pal_uefi_acpi_override/src/pal_misc.c
|
C
|
apache-2.0
| 12,248
|
---
layout: post
title: "Adder block is finished"
---
Finished soldering and testing of ALU adder block. While replacing bad relay found another one with corrupted contacts. I probably need to make quality inspection before attaching relays to the board and soldering them.
|
Dovgalyuk/Relay
|
docs/_posts/2013-03-17-Adder-block-is-finished.md
|
Markdown
|
apache-2.0
| 276
|
<!DOCTYPE html>
<html>
<head>
<meta charset='utf-8'>
<meta http-equiv="X-UA-Compatible" content="chrome=1">
<meta name="viewport" content="width=640">
<link rel="stylesheet" href="stylesheets/core.css" media="screen">
<link rel="stylesheet" href="stylesheets/mobile.css" media="handheld, only screen and (max-device-width:640px)">
<link rel="stylesheet" href="stylesheets/pygment_trac.css">
<script type="text/javascript" src="javascripts/modernizr.js"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript" src="javascripts/headsmart.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$('#main_content').headsmart()
})
</script>
<title>HR Health Index by jfs2j</title>
</head>
<body>
<a id="forkme_banner" href="https://github.com/jfs2j/HR-Health-Index">View on GitHub</a>
<div class="shell">
<header>
<span class="ribbon-outer">
<span class="ribbon-inner">
<h1>HR Health Index</h1>
<h2>Tracking Health Indicators in Hampton Roads.</h2>
</span>
<span class="left-tail"></span>
<span class="right-tail"></span>
</span>
</header>
<section id="downloads">
<span class="inner">
<a href="https://github.com/jfs2j/HR-Health-Index/zipball/master" class="zip"><em>download</em> .ZIP</a><a href="https://github.com/jfs2j/HR-Health-Index/tarball/master" class="tgz"><em>download</em> .TGZ</a>
</span>
</section>
<span class="banner-fix"></span>
<section id="main_content">
<h3>
<a id="welcome-to-github-pages" class="anchor" href="#welcome-to-github-pages" aria-hidden="true"><span class="octicon octicon-link"></span></a>Welcome to GitHub Pages.</h3>
<p>This is the homepage of the new and upcoming Hampton Roads Health Index.</p>
<pre><code>$ cd your_repo_root/repo_name
$ git fetch origin
$ git checkout gh-pages
</code></pre>
<p>If you're using the GitHub for Mac, simply sync your repository and you'll see the new branch.</p>
<h3>
<a id="authors-and-contributors" class="anchor" href="#authors-and-contributors" aria-hidden="true"><span class="octicon octicon-link"></span></a>Authors and Contributors</h3>
<p>You can <a href="https://github.com/blog/821" class="user-mention">@mention</a> a GitHub username to generate a link to their profile. The resulting <code><a></code> element will link to the contributor's GitHub Profile. For example: In 2007, Chris Wanstrath (<a href="https://github.com/defunkt" class="user-mention">@defunkt</a>), PJ Hyett (<a href="https://github.com/pjhyett" class="user-mention">@pjhyett</a>), and Tom Preston-Werner (<a href="https://github.com/mojombo" class="user-mention">@mojombo</a>) founded GitHub.</p>
<h3>
<a id="support-or-contact" class="anchor" href="#support-or-contact" aria-hidden="true"><span class="octicon octicon-link"></span></a>Support or Contact</h3>
<p>Having trouble with Pages? Check out the documentation at <a href="https://help.github.com/pages">https://help.github.com/pages</a> or contact <a href="mailto:support@github.com">support@github.com</a> and we’ll help you sort it out.</p>
</section>
<footer>
<span class="ribbon-outer">
<span class="ribbon-inner">
<p>this project by <a href="https://github.com/jfs2j">jfs2j</a> can be found on <a href="https://github.com/jfs2j/HR-Health-Index">GitHub</a></p>
</span>
<span class="left-tail"></span>
<span class="right-tail"></span>
</span>
<p>Generated with <a href="https://pages.github.com">GitHub Pages</a> using Merlot</p>
<span class="octocat"></span>
</footer>
</div>
</body>
</html>
|
jfs2j/HR-Health-Index
|
index.html
|
HTML
|
apache-2.0
| 3,897
|
# Generated by the protocol buffer compiler. DO NOT EDIT!
# Source: google/ads/googleads/v10/services/feed_item_set_service.proto for package 'Google.Ads.GoogleAds.V10.Services'
# Original file comments:
# Copyright 2022 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
require 'grpc'
require 'google/ads/google_ads/v10/services/feed_item_set_service_pb'
module Google
module Ads
module GoogleAds
module V10
module Services
module FeedItemSetService
# Proto file describing the FeedItemSet service.
#
# Service to manage feed Item Set
class Service
include ::GRPC::GenericService
self.marshal_class_method = :encode
self.unmarshal_class_method = :decode
self.service_name = 'google.ads.googleads.v10.services.FeedItemSetService'
# Creates, updates or removes feed item sets. Operation statuses are
# returned.
#
# List of thrown errors:
# [AuthenticationError]()
# [AuthorizationError]()
# [HeaderError]()
# [InternalError]()
# [MutateError]()
# [QuotaError]()
# [RequestError]()
rpc :MutateFeedItemSets, ::Google::Ads::GoogleAds::V10::Services::MutateFeedItemSetsRequest, ::Google::Ads::GoogleAds::V10::Services::MutateFeedItemSetsResponse
end
Stub = Service.rpc_stub_class
end
end
end
end
end
end
|
googleads/google-ads-ruby
|
lib/google/ads/google_ads/v10/services/feed_item_set_service_services_pb.rb
|
Ruby
|
apache-2.0
| 2,086
|
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<title>VirtualBox Main API: IGuest Interface 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.7.1 -->
<div class="navigation" id="top">
<div class="tabs">
<ul class="tablist">
<li><a href="index.html"><span>Main Page</span></a></li>
<li><a href="pages.html"><span>Related Pages</span></a></li>
<li><a href="modules.html"><span>Modules</span></a></li>
<li class="current"><a href="annotated.html"><span>Classes</span></a></li>
<li><a href="files.html"><span>Files</span></a></li>
</ul>
</div>
<div class="tabs2">
<ul class="tablist">
<li><a href="annotated.html"><span>Class List</span></a></li>
<li><a href="hierarchy.html"><span>Class Hierarchy</span></a></li>
<li><a href="functions.html"><span>Class Members</span></a></li>
</ul>
</div>
</div>
<div class="header">
<div class="summary">
<a href="#pub-methods">Public Member Functions</a> |
<a href="#pub-attribs">Public Attributes</a> </div>
<div class="headertitle">
<h1>IGuest Interface Reference</h1> </div>
</div>
<div class="contents">
<!-- doxytag: class="IGuest" -->
<p>The <a class="el" href="interface_i_guest.html" title="The IGuest interface represents information about the operating system running inside the virtual mac...">IGuest</a> interface represents information about the operating system running inside the virtual machine.
<a href="#_details">More...</a></p>
<p><a href="interface_i_guest-members.html">List of all members.</a></p>
<table class="memberdecls">
<tr><td colspan="2"><h2><a name="pub-methods"></a>
Public Member Functions</h2></td></tr>
<tr><td class="memItemLeft" align="right" valign="top">void </td><td class="memItemRight" valign="bottom"><a class="el" href="interface_i_guest.html#a71c66f08f94b27598b9ce931f38559fd">internalGetStatistics</a> (out unsigned long cpuUser, out unsigned long cpuKernel, out unsigned long cpuIdle, out unsigned long memTotal, out unsigned long memFree, out unsigned long memBalloon, out unsigned long memShared, out unsigned long memCache, out unsigned long pagedTotal, out unsigned long memAllocTotal, out unsigned long memFreeTotal, out unsigned long memBalloonTotal, out unsigned long memSharedTotal)</td></tr>
<tr><td class="mdescLeft"> </td><td class="mdescRight">Internal method; do not use as it might change at any time. <a href="#a71c66f08f94b27598b9ce931f38559fd"></a><br/></td></tr>
<tr><td class="memItemLeft" align="right" valign="top">void </td><td class="memItemRight" valign="bottom"><a class="el" href="interface_i_guest.html#aedd461f8255b9c4401564f45c081dd87">getFacilityStatus</a> (in <a class="el" href="_virtual_box_8idl.html#ae0ae133b7ff9bcca841ce04ac7c6586c">AdditionsFacilityType</a> facility, out long long timestamp,[retval] out <a class="el" href="_virtual_box_8idl.html#a3e8e780837b1fc51d47fcc81dc8fa048">AdditionsFacilityStatus</a> status)</td></tr>
<tr><td class="mdescLeft"> </td><td class="mdescRight">Get the current status of a Guest Additions facility. <a href="#aedd461f8255b9c4401564f45c081dd87"></a><br/></td></tr>
<tr><td class="memItemLeft" align="right" valign="top">void </td><td class="memItemRight" valign="bottom"><a class="el" href="interface_i_guest.html#a2722150225086f00e7cb4f1954306876">getAdditionsStatus</a> (in <a class="el" href="_virtual_box_8idl.html#a9e25175525bb1814c91c2df863d33d2d">AdditionsRunLevelType</a> level,[retval] out boolean active)</td></tr>
<tr><td class="mdescLeft"> </td><td class="mdescRight">Retrieve the current status of a certain Guest Additions run level. <a href="#a2722150225086f00e7cb4f1954306876"></a><br/></td></tr>
<tr><td class="memItemLeft" align="right" valign="top">void </td><td class="memItemRight" valign="bottom"><a class="el" href="interface_i_guest.html#a6efd39bc02a3c069a0f99eebb6440d32">setCredentials</a> (in wstring userName, in wstring password, in wstring domain, in boolean allowInteractiveLogon)</td></tr>
<tr><td class="mdescLeft"> </td><td class="mdescRight">Store login credentials that can be queried by guest operating systems with Additions installed. <a href="#a6efd39bc02a3c069a0f99eebb6440d32"></a><br/></td></tr>
<tr><td class="memItemLeft" align="right" valign="top">void </td><td class="memItemRight" valign="bottom"><a class="el" href="interface_i_guest.html#a75daa4e184503b6ce93d3cb83f0d5e11">dragHGEnter</a> (in unsigned long screenId, in unsigned long y, in unsigned long x, in <a class="el" href="_virtual_box_8idl.html#ac79c7829d9ea78dbf5ef65e88bab2d76">DragAndDropAction</a> defaultAction, in <a class="el" href="_virtual_box_8idl.html#ac79c7829d9ea78dbf5ef65e88bab2d76">DragAndDropAction</a>[] allowedActions, in wstring[] formats,[retval] out <a class="el" href="_virtual_box_8idl.html#ac79c7829d9ea78dbf5ef65e88bab2d76">DragAndDropAction</a> resultAction)</td></tr>
<tr><td class="mdescLeft"> </td><td class="mdescRight">Informs the guest about a Drag and Drop enter event. <a href="#a75daa4e184503b6ce93d3cb83f0d5e11"></a><br/></td></tr>
<tr><td class="memItemLeft" align="right" valign="top">void </td><td class="memItemRight" valign="bottom"><a class="el" href="interface_i_guest.html#a11fb414f5025859025c6769bdf5bd0d3">dragHGMove</a> (in unsigned long screenId, in unsigned long x, in unsigned long y, in <a class="el" href="_virtual_box_8idl.html#ac79c7829d9ea78dbf5ef65e88bab2d76">DragAndDropAction</a> defaultAction, in <a class="el" href="_virtual_box_8idl.html#ac79c7829d9ea78dbf5ef65e88bab2d76">DragAndDropAction</a>[] allowedActions, in wstring[] formats,[retval] out <a class="el" href="_virtual_box_8idl.html#ac79c7829d9ea78dbf5ef65e88bab2d76">DragAndDropAction</a> resultAction)</td></tr>
<tr><td class="mdescLeft"> </td><td class="mdescRight">Informs the guest about a Drag and Drop move event. <a href="#a11fb414f5025859025c6769bdf5bd0d3"></a><br/></td></tr>
<tr><td class="memItemLeft" align="right" valign="top">void </td><td class="memItemRight" valign="bottom"><a class="el" href="interface_i_guest.html#a2e3bb638a83ff2fdab685de0d3935381">dragHGLeave</a> (in unsigned long screenId)</td></tr>
<tr><td class="mdescLeft"> </td><td class="mdescRight">Informs the guest about a Drag and Drop leave event. <a href="#a2e3bb638a83ff2fdab685de0d3935381"></a><br/></td></tr>
<tr><td class="memItemLeft" align="right" valign="top">void </td><td class="memItemRight" valign="bottom"><a class="el" href="interface_i_guest.html#abab02db491b3ace56ff05744d0f8a3fe">dragHGDrop</a> (in unsigned long screenId, in unsigned long x, in unsigned long y, in <a class="el" href="_virtual_box_8idl.html#ac79c7829d9ea78dbf5ef65e88bab2d76">DragAndDropAction</a> defaultAction, in <a class="el" href="_virtual_box_8idl.html#ac79c7829d9ea78dbf5ef65e88bab2d76">DragAndDropAction</a>[] allowedActions, in wstring[] formats, out wstring format,[retval] out <a class="el" href="_virtual_box_8idl.html#ac79c7829d9ea78dbf5ef65e88bab2d76">DragAndDropAction</a> resultAction)</td></tr>
<tr><td class="mdescLeft"> </td><td class="mdescRight">Informs the guest about a drop event. <a href="#abab02db491b3ace56ff05744d0f8a3fe"></a><br/></td></tr>
<tr><td class="memItemLeft" align="right" valign="top">void </td><td class="memItemRight" valign="bottom"><a class="el" href="interface_i_guest.html#a9caee6441b77e91cd3c0a5428d0e9119">dragHGPutData</a> (in unsigned long screenId, in wstring format, in octet[] data,[retval] out <a class="el" href="interface_i_progress.html">IProgress</a> progress)</td></tr>
<tr><td class="mdescLeft"> </td><td class="mdescRight">Informs the guest about a drop data event. <a href="#a9caee6441b77e91cd3c0a5428d0e9119"></a><br/></td></tr>
<tr><td class="memItemLeft" align="right" valign="top">void </td><td class="memItemRight" valign="bottom"><a class="el" href="interface_i_guest.html#a3666b0f18a0ae66c6ae4aaaa393b9077">dragGHPending</a> (in unsigned long screenId, out wstring[] formats, out <a class="el" href="_virtual_box_8idl.html#ac79c7829d9ea78dbf5ef65e88bab2d76">DragAndDropAction</a>[] allowedActions,[retval] out <a class="el" href="_virtual_box_8idl.html#ac79c7829d9ea78dbf5ef65e88bab2d76">DragAndDropAction</a> defaultAction)</td></tr>
<tr><td class="mdescLeft"> </td><td class="mdescRight">Ask the guest if there is any Drag and Drop operation pending in the guest. <a href="#a3666b0f18a0ae66c6ae4aaaa393b9077"></a><br/></td></tr>
<tr><td class="memItemLeft" align="right" valign="top">void </td><td class="memItemRight" valign="bottom"><a class="el" href="interface_i_guest.html#af13bf28038f31a7f656a531a333ee3f1">dragGHDropped</a> (in wstring format, in <a class="el" href="_virtual_box_8idl.html#ac79c7829d9ea78dbf5ef65e88bab2d76">DragAndDropAction</a> action,[retval] out <a class="el" href="interface_i_progress.html">IProgress</a> progress)</td></tr>
<tr><td class="mdescLeft"> </td><td class="mdescRight">Informs the guest that a drop event occurred for a pending Drag and Drop event. <a href="#af13bf28038f31a7f656a531a333ee3f1"></a><br/></td></tr>
<tr><td class="memItemLeft" align="right" valign="top">void </td><td class="memItemRight" valign="bottom"><a class="el" href="interface_i_guest.html#a7b62f32bb502183bad4066de068b3d96">dragGHGetData</a> ([retval] out octet[] data)</td></tr>
<tr><td class="mdescLeft"> </td><td class="mdescRight">Fetch the data of a previously Drag and Drop event from the guest. <a href="#a7b62f32bb502183bad4066de068b3d96"></a><br/></td></tr>
<tr><td class="memItemLeft" align="right" valign="top">void </td><td class="memItemRight" valign="bottom"><a class="el" href="interface_i_guest.html#ad01dc4d81f1f0be4b9097977ddf2dc19">createSession</a> (in wstring user, in wstring password, in wstring domain, in wstring sessionName,[retval] out <a class="el" href="interface_i_guest_session.html">IGuestSession</a> guestSession)</td></tr>
<tr><td class="mdescLeft"> </td><td class="mdescRight">Creates a new guest session for controlling the guest. <a href="#ad01dc4d81f1f0be4b9097977ddf2dc19"></a><br/></td></tr>
<tr><td class="memItemLeft" align="right" valign="top">void </td><td class="memItemRight" valign="bottom"><a class="el" href="interface_i_guest.html#a63b81a8caf1fce8be910830eafbcc837">findSession</a> (in wstring sessionName,[retval] out <a class="el" href="interface_i_guest_session.html">IGuestSession</a>[] <a class="el" href="interface_i_guest.html#ace5635124343b6345a905297f727bbb9">sessions</a>)</td></tr>
<tr><td class="mdescLeft"> </td><td class="mdescRight">Finds guest sessions by their friendly name and returns an interface array with all found guest sessions. <a href="#a63b81a8caf1fce8be910830eafbcc837"></a><br/></td></tr>
<tr><td class="memItemLeft" align="right" valign="top">void </td><td class="memItemRight" valign="bottom"><a class="el" href="interface_i_guest.html#adaf65b47e8cfd88edf511c099dbd452b">updateGuestAdditions</a> (in wstring source, in wstring[] arguments, in <a class="el" href="_virtual_box_8idl.html#a3f2b787d08708d68640a33680f12db85">AdditionsUpdateFlag</a>[] flags,[retval] out <a class="el" href="interface_i_progress.html">IProgress</a> progress)</td></tr>
<tr><td class="mdescLeft"> </td><td class="mdescRight">Automatically updates already installed Guest Additions in a VM. <a href="#adaf65b47e8cfd88edf511c099dbd452b"></a><br/></td></tr>
<tr><td colspan="2"><h2><a name="pub-attribs"></a>
Public Attributes</h2></td></tr>
<tr><td class="memItemLeft" align="right" valign="top">readonly attribute wstring </td><td class="memItemRight" valign="bottom"><a class="el" href="interface_i_guest.html#a1836d4706baed01b5de022ac2ca25ab6">OSTypeId</a></td></tr>
<tr><td class="mdescLeft"> </td><td class="mdescRight">Identifier of the Guest OS type as reported by the Guest Additions. <a href="#a1836d4706baed01b5de022ac2ca25ab6"></a><br/></td></tr>
<tr><td class="memItemLeft" align="right" valign="top">readonly attribute <br class="typebreak"/>
<a class="el" href="_virtual_box_8idl.html#a9e25175525bb1814c91c2df863d33d2d">AdditionsRunLevelType</a> </td><td class="memItemRight" valign="bottom"><a class="el" href="interface_i_guest.html#aa948ff08dfedcfd29fd0d10d68eeda6d">additionsRunLevel</a></td></tr>
<tr><td class="mdescLeft"> </td><td class="mdescRight">Current run level of the Guest Additions. <a href="#aa948ff08dfedcfd29fd0d10d68eeda6d"></a><br/></td></tr>
<tr><td class="memItemLeft" align="right" valign="top">readonly attribute wstring </td><td class="memItemRight" valign="bottom"><a class="el" href="interface_i_guest.html#a1ccd19a6e704c8ef1b369961d3f47b43">additionsVersion</a></td></tr>
<tr><td class="mdescLeft"> </td><td class="mdescRight">Version of the Guest Additions in the same format as <a class="el" href="interface_i_virtual_box.html#aa39d78ffaa90c1abe9d340a1a0738ed9">IVirtualBox::version</a><b></b>. <a href="#a1ccd19a6e704c8ef1b369961d3f47b43"></a><br/></td></tr>
<tr><td class="memItemLeft" align="right" valign="top">readonly attribute unsigned long </td><td class="memItemRight" valign="bottom"><a class="el" href="interface_i_guest.html#a58206da74b7e15fbdb6d9863da5c49ee">additionsRevision</a></td></tr>
<tr><td class="mdescLeft"> </td><td class="mdescRight">The internal build revision number of the additions. <a href="#a58206da74b7e15fbdb6d9863da5c49ee"></a><br/></td></tr>
<tr><td class="memItemLeft" align="right" valign="top">readonly attribute <a class="el" href="interface_i_event_source.html">IEventSource</a> </td><td class="memItemRight" valign="bottom"><a class="el" href="interface_i_guest.html#a6369c01ace2aa597191daec48ba72ec8">eventSource</a></td></tr>
<tr><td class="mdescLeft"> </td><td class="mdescRight">Event source for guest events. <a href="#a6369c01ace2aa597191daec48ba72ec8"></a><br/></td></tr>
<tr><td class="memItemLeft" align="right" valign="top">readonly attribute <br class="typebreak"/>
<a class="el" href="interface_i_additions_facility.html">IAdditionsFacility</a>[] </td><td class="memItemRight" valign="bottom"><a class="el" href="interface_i_guest.html#a1bd283f572c6b7540f7209dd0e4a2d31">facilities</a></td></tr>
<tr><td class="mdescLeft"> </td><td class="mdescRight">Array of current known facilities. <a href="#a1bd283f572c6b7540f7209dd0e4a2d31"></a><br/></td></tr>
<tr><td class="memItemLeft" align="right" valign="top">readonly attribute <a class="el" href="interface_i_guest_session.html">IGuestSession</a>[] </td><td class="memItemRight" valign="bottom"><a class="el" href="interface_i_guest.html#ace5635124343b6345a905297f727bbb9">sessions</a></td></tr>
<tr><td class="mdescLeft"> </td><td class="mdescRight">Returns a collection of all opened guest sessions. <a href="#ace5635124343b6345a905297f727bbb9"></a><br/></td></tr>
<tr><td class="memItemLeft" align="right" valign="top">attribute unsigned long </td><td class="memItemRight" valign="bottom"><a class="el" href="interface_i_guest.html#a2616a76e5a8466929e60017cf17960af">memoryBalloonSize</a></td></tr>
<tr><td class="mdescLeft"> </td><td class="mdescRight">Guest system memory balloon size in megabytes (transient property). <a href="#a2616a76e5a8466929e60017cf17960af"></a><br/></td></tr>
<tr><td class="memItemLeft" align="right" valign="top">attribute unsigned long </td><td class="memItemRight" valign="bottom"><a class="el" href="interface_i_guest.html#aa1b7827f9228e604ed5112495e967f7f">statisticsUpdateInterval</a></td></tr>
<tr><td class="mdescLeft"> </td><td class="mdescRight">Interval to update guest statistics in seconds. <a href="#aa1b7827f9228e604ed5112495e967f7f"></a><br/></td></tr>
</table>
<hr/><a name="_details"></a><h2>Detailed Description</h2>
<p>The <a class="el" href="interface_i_guest.html" title="The IGuest interface represents information about the operating system running inside the virtual mac...">IGuest</a> interface represents information about the operating system running inside the virtual machine. </p>
<p>Used in <a class="el" href="interface_i_console.html#a6c6d64908daef7fd950a27276be2126a">IConsole::guest</a><b></b>.</p>
<p><a class="el" href="interface_i_guest.html" title="The IGuest interface represents information about the operating system running inside the virtual mac...">IGuest</a> provides information about the guest operating system, whether Guest Additions are installed and other OS-specific virtual machine properties.</p>
<dl class="user"><dt><b>Interface ID:</b></dt><dd><code>{8011A1B1-6ADB-4FFB-A37E-20ABDAEE4650}</code> </dd></dl>
<hr/><h2>Member Function Documentation</h2>
<a class="anchor" id="a71c66f08f94b27598b9ce931f38559fd"></a><!-- doxytag: member="IGuest::internalGetStatistics" ref="a71c66f08f94b27598b9ce931f38559fd" args="(out unsigned long cpuUser, out unsigned long cpuKernel, out unsigned long cpuIdle, out unsigned long memTotal, out unsigned long memFree, out unsigned long memBalloon, out unsigned long memShared, out unsigned long memCache, out unsigned long pagedTotal, out unsigned long memAllocTotal, out unsigned long memFreeTotal, out unsigned long memBalloonTotal, out unsigned long memSharedTotal)" -->
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">void IGuest::internalGetStatistics </td>
<td>(</td>
<td class="paramtype">out unsigned long </td>
<td class="paramname"> <em>cpuUser</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype">out unsigned long </td>
<td class="paramname"> <em>cpuKernel</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype">out unsigned long </td>
<td class="paramname"> <em>cpuIdle</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype">out unsigned long </td>
<td class="paramname"> <em>memTotal</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype">out unsigned long </td>
<td class="paramname"> <em>memFree</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype">out unsigned long </td>
<td class="paramname"> <em>memBalloon</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype">out unsigned long </td>
<td class="paramname"> <em>memShared</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype">out unsigned long </td>
<td class="paramname"> <em>memCache</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype">out unsigned long </td>
<td class="paramname"> <em>pagedTotal</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype">out unsigned long </td>
<td class="paramname"> <em>memAllocTotal</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype">out unsigned long </td>
<td class="paramname"> <em>memFreeTotal</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype">out unsigned long </td>
<td class="paramname"> <em>memBalloonTotal</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype">out unsigned long </td>
<td class="paramname"> <em>memSharedTotal</em></td><td> </td>
</tr>
<tr>
<td></td>
<td>)</td>
<td></td><td></td><td></td>
</tr>
</table>
</div>
<div class="memdoc">
<p>Internal method; do not use as it might change at any time. </p>
<dl><dt><b>Parameters:</b></dt><dd>
<table border="0" cellspacing="2" cellpadding="0">
<tr><td valign="top"></td><td valign="top"><em>cpuUser</em> </td><td>Percentage of processor time spent in user mode as seen by the guest.</td></tr>
<tr><td valign="top"></td><td valign="top"><em>cpuKernel</em> </td><td>Percentage of processor time spent in kernel mode as seen by the guest.</td></tr>
<tr><td valign="top"></td><td valign="top"><em>cpuIdle</em> </td><td>Percentage of processor time spent idling as seen by the guest.</td></tr>
<tr><td valign="top"></td><td valign="top"><em>memTotal</em> </td><td>Total amount of physical guest RAM.</td></tr>
<tr><td valign="top"></td><td valign="top"><em>memFree</em> </td><td>Free amount of physical guest RAM.</td></tr>
<tr><td valign="top"></td><td valign="top"><em>memBalloon</em> </td><td>Amount of ballooned physical guest RAM.</td></tr>
<tr><td valign="top"></td><td valign="top"><em>memShared</em> </td><td>Amount of shared physical guest RAM.</td></tr>
<tr><td valign="top"></td><td valign="top"><em>memCache</em> </td><td>Total amount of guest (disk) cache memory.</td></tr>
<tr><td valign="top"></td><td valign="top"><em>pagedTotal</em> </td><td>Total amount of space in the page file.</td></tr>
<tr><td valign="top"></td><td valign="top"><em>memAllocTotal</em> </td><td>Total amount of memory allocated by the hypervisor.</td></tr>
<tr><td valign="top"></td><td valign="top"><em>memFreeTotal</em> </td><td>Total amount of free memory available in the hypervisor.</td></tr>
<tr><td valign="top"></td><td valign="top"><em>memBalloonTotal</em> </td><td>Total amount of memory ballooned by the hypervisor.</td></tr>
<tr><td valign="top"></td><td valign="top"><em>memSharedTotal</em> </td><td>Total amount of shared memory in the hypervisor. </td></tr>
</table>
</dd>
</dl>
</div>
</div>
<a class="anchor" id="aedd461f8255b9c4401564f45c081dd87"></a><!-- doxytag: member="IGuest::getFacilityStatus" ref="aedd461f8255b9c4401564f45c081dd87" args="(in AdditionsFacilityType facility, out long long timestamp,[retval] out AdditionsFacilityStatus status)" -->
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">void IGuest::getFacilityStatus </td>
<td>(</td>
<td class="paramtype">in <a class="el" href="_virtual_box_8idl.html#ae0ae133b7ff9bcca841ce04ac7c6586c">AdditionsFacilityType</a> </td>
<td class="paramname"> <em>facility</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype">out long long </td>
<td class="paramname"> <em>timestamp</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype">[retval] out <a class="el" href="_virtual_box_8idl.html#a3e8e780837b1fc51d47fcc81dc8fa048">AdditionsFacilityStatus</a> </td>
<td class="paramname"> <em>status</em></td><td> </td>
</tr>
<tr>
<td></td>
<td>)</td>
<td></td><td></td><td></td>
</tr>
</table>
</div>
<div class="memdoc">
<p>Get the current status of a Guest Additions facility. </p>
<dl><dt><b>Parameters:</b></dt><dd>
<table border="0" cellspacing="2" cellpadding="0">
<tr><td valign="top"></td><td valign="top"><em>facility</em> </td><td>Facility to check status for.</td></tr>
<tr><td valign="top"></td><td valign="top"><em>timestamp</em> </td><td>Timestamp (in ms) of last status update seen by the host.</td></tr>
<tr><td valign="top"></td><td valign="top"><em>status</em> </td><td>The current (latest) facility status. </td></tr>
</table>
</dd>
</dl>
</div>
</div>
<a class="anchor" id="a2722150225086f00e7cb4f1954306876"></a><!-- doxytag: member="IGuest::getAdditionsStatus" ref="a2722150225086f00e7cb4f1954306876" args="(in AdditionsRunLevelType level,[retval] out boolean active)" -->
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">void IGuest::getAdditionsStatus </td>
<td>(</td>
<td class="paramtype">in <a class="el" href="_virtual_box_8idl.html#a9e25175525bb1814c91c2df863d33d2d">AdditionsRunLevelType</a> </td>
<td class="paramname"> <em>level</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype">[retval] out boolean </td>
<td class="paramname"> <em>active</em></td><td> </td>
</tr>
<tr>
<td></td>
<td>)</td>
<td></td><td></td><td></td>
</tr>
</table>
</div>
<div class="memdoc">
<p>Retrieve the current status of a certain Guest Additions run level. </p>
<dl><dt><b>Parameters:</b></dt><dd>
<table border="0" cellspacing="2" cellpadding="0">
<tr><td valign="top"></td><td valign="top"><em>level</em> </td><td>Status level to check</td></tr>
<tr><td valign="top"></td><td valign="top"><em>active</em> </td><td>Flag whether the status level has been reached or not</td></tr>
</table>
</dd>
</dl>
<dl class="user"><dt><b>Expected result codes:</b></dt><dd><table class="doxtable">
<tr>
<td><a class="el" href="group___virtual_box___c_o_m__result__codes.html#gaa4ba5e3fab3fe318c790d9d0b500c102">VBOX_E_NOT_SUPPORTED </a> </td><td>Wrong status level specified. </td></tr>
</table>
</dd></dl>
</div>
</div>
<a class="anchor" id="a6efd39bc02a3c069a0f99eebb6440d32"></a><!-- doxytag: member="IGuest::setCredentials" ref="a6efd39bc02a3c069a0f99eebb6440d32" args="(in wstring userName, in wstring password, in wstring domain, in boolean allowInteractiveLogon)" -->
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">void IGuest::setCredentials </td>
<td>(</td>
<td class="paramtype">in wstring </td>
<td class="paramname"> <em>userName</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype">in wstring </td>
<td class="paramname"> <em>password</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype">in wstring </td>
<td class="paramname"> <em>domain</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype">in boolean </td>
<td class="paramname"> <em>allowInteractiveLogon</em></td><td> </td>
</tr>
<tr>
<td></td>
<td>)</td>
<td></td><td></td><td></td>
</tr>
</table>
</div>
<div class="memdoc">
<p>Store login credentials that can be queried by guest operating systems with Additions installed. </p>
<p>The credentials are transient to the session and the guest may also choose to erase them. Note that the caller cannot determine whether the guest operating system has queried or made use of the credentials.</p>
<dl><dt><b>Parameters:</b></dt><dd>
<table border="0" cellspacing="2" cellpadding="0">
<tr><td valign="top"></td><td valign="top"><em>userName</em> </td><td>User name string, can be empty</td></tr>
<tr><td valign="top"></td><td valign="top"><em>password</em> </td><td>Password string, can be empty</td></tr>
<tr><td valign="top"></td><td valign="top"><em>domain</em> </td><td>Domain name (guest logon scheme specific), can be empty</td></tr>
<tr><td valign="top"></td><td valign="top"><em>allowInteractiveLogon</em> </td><td>Flag whether the guest should alternatively allow the user to interactively specify different credentials. This flag might not be supported by all versions of the Additions.</td></tr>
</table>
</dd>
</dl>
<dl class="user"><dt><b>Expected result codes:</b></dt><dd><table class="doxtable">
<tr>
<td><a class="el" href="group___virtual_box___c_o_m__result__codes.html#ga20b372463e8e5a2b0474fbb0e2d70c4e">VBOX_E_VM_ERROR </a> </td><td>VMM device is not available. </td></tr>
</table>
</dd></dl>
</div>
</div>
<a class="anchor" id="a75daa4e184503b6ce93d3cb83f0d5e11"></a><!-- doxytag: member="IGuest::dragHGEnter" ref="a75daa4e184503b6ce93d3cb83f0d5e11" args="(in unsigned long screenId, in unsigned long y, in unsigned long x, in DragAndDropAction defaultAction, in DragAndDropAction[] allowedActions, in wstring[] formats,[retval] out DragAndDropAction resultAction)" -->
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">void IGuest::dragHGEnter </td>
<td>(</td>
<td class="paramtype">in unsigned long </td>
<td class="paramname"> <em>screenId</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype">in unsigned long </td>
<td class="paramname"> <em>y</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype">in unsigned long </td>
<td class="paramname"> <em>x</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype">in <a class="el" href="_virtual_box_8idl.html#ac79c7829d9ea78dbf5ef65e88bab2d76">DragAndDropAction</a> </td>
<td class="paramname"> <em>defaultAction</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype">in <a class="el" href="_virtual_box_8idl.html#ac79c7829d9ea78dbf5ef65e88bab2d76">DragAndDropAction</a>[] </td>
<td class="paramname"> <em>allowedActions</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype">in wstring[] </td>
<td class="paramname"> <em>formats</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype">[retval] out <a class="el" href="_virtual_box_8idl.html#ac79c7829d9ea78dbf5ef65e88bab2d76">DragAndDropAction</a> </td>
<td class="paramname"> <em>resultAction</em></td><td> </td>
</tr>
<tr>
<td></td>
<td>)</td>
<td></td><td></td><td></td>
</tr>
</table>
</div>
<div class="memdoc">
<p>Informs the guest about a Drag and Drop enter event. </p>
<p>This is used in Host - Guest direction.</p>
<dl><dt><b>Parameters:</b></dt><dd>
<table border="0" cellspacing="2" cellpadding="0">
<tr><td valign="top"></td><td valign="top"><em>screenId</em> </td><td>The screen id where the Drag and Drop event occurred.</td></tr>
<tr><td valign="top"></td><td valign="top"><em>y</em> </td><td>y-position of the event.</td></tr>
<tr><td valign="top"></td><td valign="top"><em>x</em> </td><td>x-position of the event.</td></tr>
<tr><td valign="top"></td><td valign="top"><em>defaultAction</em> </td><td>The default action to use.</td></tr>
<tr><td valign="top"></td><td valign="top"><em>allowedActions</em> </td><td>The actions which are allowed.</td></tr>
<tr><td valign="top"></td><td valign="top"><em>formats</em> </td><td>The supported mime types.</td></tr>
<tr><td valign="top"></td><td valign="top"><em>resultAction</em> </td><td>The resulting action of this event.</td></tr>
</table>
</dd>
</dl>
<dl class="user"><dt><b>Expected result codes:</b></dt><dd><table class="doxtable">
<tr>
<td><a class="el" href="group___virtual_box___c_o_m__result__codes.html#ga20b372463e8e5a2b0474fbb0e2d70c4e">VBOX_E_VM_ERROR </a> </td><td>VMM device is not available. </td></tr>
</table>
</dd></dl>
</div>
</div>
<a class="anchor" id="a11fb414f5025859025c6769bdf5bd0d3"></a><!-- doxytag: member="IGuest::dragHGMove" ref="a11fb414f5025859025c6769bdf5bd0d3" args="(in unsigned long screenId, in unsigned long x, in unsigned long y, in DragAndDropAction defaultAction, in DragAndDropAction[] allowedActions, in wstring[] formats,[retval] out DragAndDropAction resultAction)" -->
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">void IGuest::dragHGMove </td>
<td>(</td>
<td class="paramtype">in unsigned long </td>
<td class="paramname"> <em>screenId</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype">in unsigned long </td>
<td class="paramname"> <em>x</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype">in unsigned long </td>
<td class="paramname"> <em>y</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype">in <a class="el" href="_virtual_box_8idl.html#ac79c7829d9ea78dbf5ef65e88bab2d76">DragAndDropAction</a> </td>
<td class="paramname"> <em>defaultAction</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype">in <a class="el" href="_virtual_box_8idl.html#ac79c7829d9ea78dbf5ef65e88bab2d76">DragAndDropAction</a>[] </td>
<td class="paramname"> <em>allowedActions</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype">in wstring[] </td>
<td class="paramname"> <em>formats</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype">[retval] out <a class="el" href="_virtual_box_8idl.html#ac79c7829d9ea78dbf5ef65e88bab2d76">DragAndDropAction</a> </td>
<td class="paramname"> <em>resultAction</em></td><td> </td>
</tr>
<tr>
<td></td>
<td>)</td>
<td></td><td></td><td></td>
</tr>
</table>
</div>
<div class="memdoc">
<p>Informs the guest about a Drag and Drop move event. </p>
<p>This is used in Host - Guest direction.</p>
<dl><dt><b>Parameters:</b></dt><dd>
<table border="0" cellspacing="2" cellpadding="0">
<tr><td valign="top"></td><td valign="top"><em>screenId</em> </td><td>The screen id where the Drag and Drop event occurred.</td></tr>
<tr><td valign="top"></td><td valign="top"><em>x</em> </td><td>x-position of the event.</td></tr>
<tr><td valign="top"></td><td valign="top"><em>y</em> </td><td>y-position of the event.</td></tr>
<tr><td valign="top"></td><td valign="top"><em>defaultAction</em> </td><td>The default action to use.</td></tr>
<tr><td valign="top"></td><td valign="top"><em>allowedActions</em> </td><td>The actions which are allowed.</td></tr>
<tr><td valign="top"></td><td valign="top"><em>formats</em> </td><td>The supported mime types.</td></tr>
<tr><td valign="top"></td><td valign="top"><em>resultAction</em> </td><td>The resulting action of this event.</td></tr>
</table>
</dd>
</dl>
<dl class="user"><dt><b>Expected result codes:</b></dt><dd><table class="doxtable">
<tr>
<td><a class="el" href="group___virtual_box___c_o_m__result__codes.html#ga20b372463e8e5a2b0474fbb0e2d70c4e">VBOX_E_VM_ERROR </a> </td><td>VMM device is not available. </td></tr>
</table>
</dd></dl>
</div>
</div>
<a class="anchor" id="a2e3bb638a83ff2fdab685de0d3935381"></a><!-- doxytag: member="IGuest::dragHGLeave" ref="a2e3bb638a83ff2fdab685de0d3935381" args="(in unsigned long screenId)" -->
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">void IGuest::dragHGLeave </td>
<td>(</td>
<td class="paramtype">in unsigned long </td>
<td class="paramname"> <em>screenId</em></td>
<td> ) </td>
<td></td>
</tr>
</table>
</div>
<div class="memdoc">
<p>Informs the guest about a Drag and Drop leave event. </p>
<p>This is used in Host - Guest direction.</p>
<dl><dt><b>Parameters:</b></dt><dd>
<table border="0" cellspacing="2" cellpadding="0">
<tr><td valign="top"></td><td valign="top"><em>screenId</em> </td><td>The screen id where the Drag and Drop event occurred.</td></tr>
</table>
</dd>
</dl>
<dl class="user"><dt><b>Expected result codes:</b></dt><dd><table class="doxtable">
<tr>
<td><a class="el" href="group___virtual_box___c_o_m__result__codes.html#ga20b372463e8e5a2b0474fbb0e2d70c4e">VBOX_E_VM_ERROR </a> </td><td>VMM device is not available. </td></tr>
</table>
</dd></dl>
</div>
</div>
<a class="anchor" id="abab02db491b3ace56ff05744d0f8a3fe"></a><!-- doxytag: member="IGuest::dragHGDrop" ref="abab02db491b3ace56ff05744d0f8a3fe" args="(in unsigned long screenId, in unsigned long x, in unsigned long y, in DragAndDropAction defaultAction, in DragAndDropAction[] allowedActions, in wstring[] formats, out wstring format,[retval] out DragAndDropAction resultAction)" -->
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">void IGuest::dragHGDrop </td>
<td>(</td>
<td class="paramtype">in unsigned long </td>
<td class="paramname"> <em>screenId</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype">in unsigned long </td>
<td class="paramname"> <em>x</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype">in unsigned long </td>
<td class="paramname"> <em>y</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype">in <a class="el" href="_virtual_box_8idl.html#ac79c7829d9ea78dbf5ef65e88bab2d76">DragAndDropAction</a> </td>
<td class="paramname"> <em>defaultAction</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype">in <a class="el" href="_virtual_box_8idl.html#ac79c7829d9ea78dbf5ef65e88bab2d76">DragAndDropAction</a>[] </td>
<td class="paramname"> <em>allowedActions</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype">in wstring[] </td>
<td class="paramname"> <em>formats</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype">out wstring </td>
<td class="paramname"> <em>format</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype">[retval] out <a class="el" href="_virtual_box_8idl.html#ac79c7829d9ea78dbf5ef65e88bab2d76">DragAndDropAction</a> </td>
<td class="paramname"> <em>resultAction</em></td><td> </td>
</tr>
<tr>
<td></td>
<td>)</td>
<td></td><td></td><td></td>
</tr>
</table>
</div>
<div class="memdoc">
<p>Informs the guest about a drop event. </p>
<p>This is used in Host - Guest direction.</p>
<dl><dt><b>Parameters:</b></dt><dd>
<table border="0" cellspacing="2" cellpadding="0">
<tr><td valign="top"></td><td valign="top"><em>screenId</em> </td><td>The screen id where the Drag and Drop event occurred.</td></tr>
<tr><td valign="top"></td><td valign="top"><em>x</em> </td><td>x-position of the event.</td></tr>
<tr><td valign="top"></td><td valign="top"><em>y</em> </td><td>y-position of the event.</td></tr>
<tr><td valign="top"></td><td valign="top"><em>defaultAction</em> </td><td>The default action to use.</td></tr>
<tr><td valign="top"></td><td valign="top"><em>allowedActions</em> </td><td>The actions which are allowed.</td></tr>
<tr><td valign="top"></td><td valign="top"><em>formats</em> </td><td>The supported mime types.</td></tr>
<tr><td valign="top"></td><td valign="top"><em>format</em> </td><td>The resulting format of this event.</td></tr>
<tr><td valign="top"></td><td valign="top"><em>resultAction</em> </td><td>The resulting action of this event.</td></tr>
</table>
</dd>
</dl>
<dl class="user"><dt><b>Expected result codes:</b></dt><dd><table class="doxtable">
<tr>
<td><a class="el" href="group___virtual_box___c_o_m__result__codes.html#ga20b372463e8e5a2b0474fbb0e2d70c4e">VBOX_E_VM_ERROR </a> </td><td>VMM device is not available. </td></tr>
</table>
</dd></dl>
</div>
</div>
<a class="anchor" id="a9caee6441b77e91cd3c0a5428d0e9119"></a><!-- doxytag: member="IGuest::dragHGPutData" ref="a9caee6441b77e91cd3c0a5428d0e9119" args="(in unsigned long screenId, in wstring format, in octet[] data,[retval] out IProgress progress)" -->
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">void IGuest::dragHGPutData </td>
<td>(</td>
<td class="paramtype">in unsigned long </td>
<td class="paramname"> <em>screenId</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype">in wstring </td>
<td class="paramname"> <em>format</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype">in octet[] </td>
<td class="paramname"> <em>data</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype">[retval] out <a class="el" href="interface_i_progress.html">IProgress</a> </td>
<td class="paramname"> <em>progress</em></td><td> </td>
</tr>
<tr>
<td></td>
<td>)</td>
<td></td><td></td><td></td>
</tr>
</table>
</div>
<div class="memdoc">
<p>Informs the guest about a drop data event. </p>
<p>This is used in Host - Guest direction.</p>
<dl><dt><b>Parameters:</b></dt><dd>
<table border="0" cellspacing="2" cellpadding="0">
<tr><td valign="top"></td><td valign="top"><em>screenId</em> </td><td>The screen id where the Drag and Drop event occurred.</td></tr>
<tr><td valign="top"></td><td valign="top"><em>format</em> </td><td>The mime type the data is in.</td></tr>
<tr><td valign="top"></td><td valign="top"><em>data</em> </td><td>The actual data.</td></tr>
<tr><td valign="top"></td><td valign="top"><em>progress</em> </td><td>Progress object to track the operation completion.</td></tr>
</table>
</dd>
</dl>
<dl class="user"><dt><b>Expected result codes:</b></dt><dd><table class="doxtable">
<tr>
<td><a class="el" href="group___virtual_box___c_o_m__result__codes.html#ga20b372463e8e5a2b0474fbb0e2d70c4e">VBOX_E_VM_ERROR </a> </td><td>VMM device is not available. </td></tr>
</table>
</dd></dl>
</div>
</div>
<a class="anchor" id="a3666b0f18a0ae66c6ae4aaaa393b9077"></a><!-- doxytag: member="IGuest::dragGHPending" ref="a3666b0f18a0ae66c6ae4aaaa393b9077" args="(in unsigned long screenId, out wstring[] formats, out DragAndDropAction[] allowedActions,[retval] out DragAndDropAction defaultAction)" -->
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">void IGuest::dragGHPending </td>
<td>(</td>
<td class="paramtype">in unsigned long </td>
<td class="paramname"> <em>screenId</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype">out wstring[] </td>
<td class="paramname"> <em>formats</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype">out <a class="el" href="_virtual_box_8idl.html#ac79c7829d9ea78dbf5ef65e88bab2d76">DragAndDropAction</a>[] </td>
<td class="paramname"> <em>allowedActions</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype">[retval] out <a class="el" href="_virtual_box_8idl.html#ac79c7829d9ea78dbf5ef65e88bab2d76">DragAndDropAction</a> </td>
<td class="paramname"> <em>defaultAction</em></td><td> </td>
</tr>
<tr>
<td></td>
<td>)</td>
<td></td><td></td><td></td>
</tr>
</table>
</div>
<div class="memdoc">
<p>Ask the guest if there is any Drag and Drop operation pending in the guest. </p>
<p>If no Drag and Drop operation is pending currently, Ignore is returned.</p>
<p>This is used in Guest - Host direction.</p>
<dl><dt><b>Parameters:</b></dt><dd>
<table border="0" cellspacing="2" cellpadding="0">
<tr><td valign="top"></td><td valign="top"><em>screenId</em> </td><td>The screen id where the Drag and Drop event occurred.</td></tr>
<tr><td valign="top"></td><td valign="top"><em>formats</em> </td><td>On return the supported mime types.</td></tr>
<tr><td valign="top"></td><td valign="top"><em>allowedActions</em> </td><td>On return the actions which are allowed.</td></tr>
<tr><td valign="top"></td><td valign="top"><em>defaultAction</em> </td><td>On return the default action to use.</td></tr>
</table>
</dd>
</dl>
<dl class="user"><dt><b>Expected result codes:</b></dt><dd><table class="doxtable">
<tr>
<td><a class="el" href="group___virtual_box___c_o_m__result__codes.html#ga20b372463e8e5a2b0474fbb0e2d70c4e">VBOX_E_VM_ERROR </a> </td><td>VMM device is not available. </td></tr>
</table>
</dd></dl>
</div>
</div>
<a class="anchor" id="af13bf28038f31a7f656a531a333ee3f1"></a><!-- doxytag: member="IGuest::dragGHDropped" ref="af13bf28038f31a7f656a531a333ee3f1" args="(in wstring format, in DragAndDropAction action,[retval] out IProgress progress)" -->
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">void IGuest::dragGHDropped </td>
<td>(</td>
<td class="paramtype">in wstring </td>
<td class="paramname"> <em>format</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype">in <a class="el" href="_virtual_box_8idl.html#ac79c7829d9ea78dbf5ef65e88bab2d76">DragAndDropAction</a> </td>
<td class="paramname"> <em>action</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype">[retval] out <a class="el" href="interface_i_progress.html">IProgress</a> </td>
<td class="paramname"> <em>progress</em></td><td> </td>
</tr>
<tr>
<td></td>
<td>)</td>
<td></td><td></td><td></td>
</tr>
</table>
</div>
<div class="memdoc">
<p>Informs the guest that a drop event occurred for a pending Drag and Drop event. </p>
<p>This is used in Guest - Host direction.</p>
<dl><dt><b>Parameters:</b></dt><dd>
<table border="0" cellspacing="2" cellpadding="0">
<tr><td valign="top"></td><td valign="top"><em>format</em> </td><td>The mime type the data must be in.</td></tr>
<tr><td valign="top"></td><td valign="top"><em>action</em> </td><td>The action to use.</td></tr>
<tr><td valign="top"></td><td valign="top"><em>progress</em> </td><td>Progress object to track the operation completion.</td></tr>
</table>
</dd>
</dl>
<dl class="user"><dt><b>Expected result codes:</b></dt><dd><table class="doxtable">
<tr>
<td><a class="el" href="group___virtual_box___c_o_m__result__codes.html#ga20b372463e8e5a2b0474fbb0e2d70c4e">VBOX_E_VM_ERROR </a> </td><td>VMM device is not available. </td></tr>
</table>
</dd></dl>
</div>
</div>
<a class="anchor" id="a7b62f32bb502183bad4066de068b3d96"></a><!-- doxytag: member="IGuest::dragGHGetData" ref="a7b62f32bb502183bad4066de068b3d96" args="([retval] out octet[] data)" -->
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">void IGuest::dragGHGetData </td>
<td>(</td>
<td class="paramtype">[retval] out octet[] </td>
<td class="paramname"> <em>data</em></td>
<td> ) </td>
<td></td>
</tr>
</table>
</div>
<div class="memdoc">
<p>Fetch the data of a previously Drag and Drop event from the guest. </p>
<p>This is used in Guest - Host direction.</p>
<dl><dt><b>Parameters:</b></dt><dd>
<table border="0" cellspacing="2" cellpadding="0">
<tr><td valign="top"></td><td valign="top"><em>data</em> </td><td>The actual data.</td></tr>
</table>
</dd>
</dl>
<dl class="user"><dt><b>Expected result codes:</b></dt><dd><table class="doxtable">
<tr>
<td><a class="el" href="group___virtual_box___c_o_m__result__codes.html#ga20b372463e8e5a2b0474fbb0e2d70c4e">VBOX_E_VM_ERROR </a> </td><td>VMM device is not available. </td></tr>
</table>
</dd></dl>
</div>
</div>
<a class="anchor" id="ad01dc4d81f1f0be4b9097977ddf2dc19"></a><!-- doxytag: member="IGuest::createSession" ref="ad01dc4d81f1f0be4b9097977ddf2dc19" args="(in wstring user, in wstring password, in wstring domain, in wstring sessionName,[retval] out IGuestSession guestSession)" -->
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">void IGuest::createSession </td>
<td>(</td>
<td class="paramtype">in wstring </td>
<td class="paramname"> <em>user</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype">in wstring </td>
<td class="paramname"> <em>password</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype">in wstring </td>
<td class="paramname"> <em>domain</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype">in wstring </td>
<td class="paramname"> <em>sessionName</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype">[retval] out <a class="el" href="interface_i_guest_session.html">IGuestSession</a> </td>
<td class="paramname"> <em>guestSession</em></td><td> </td>
</tr>
<tr>
<td></td>
<td>)</td>
<td></td><td></td><td></td>
</tr>
</table>
</div>
<div class="memdoc">
<p>Creates a new guest session for controlling the guest. </p>
<p>The new session will be started asynchronously, meaning on return of this function it is not guaranteed that the guest session is in a started and/or usable state. To wait for successful startup, use the <a class="el" href="interface_i_guest_session.html#a911191c8c9be777bbc342ae4c5fd790f">IGuestSession::waitFor</a><b></b> call.</p>
<p>A guest session represents one impersonated user account on the guest, so every operation will use the same credentials specified when creating the session object via <a class="el" href="interface_i_guest.html#ad01dc4d81f1f0be4b9097977ddf2dc19">IGuest::createSession</a><b></b>. Anonymous sessions, that is, sessions without specifying a valid user account on the guest are not allowed due to security reasons.</p>
<p>There can be a maximum of 32 sessions at once per VM. Each session keeps track of its started guest processes, opened guest files or guest directories. To work on guest files or directories a guest session offers methods to open or create such objects (see <a class="el" href="interface_i_guest_session.html#a857cb54981aea302ae1ee3197904ac0f">IGuestSession::fileOpen</a><b></b> or <a class="el" href="interface_i_guest_session.html#a9a9f95fd8c3bf69c02b1d5393f8500e8">IGuestSession::directoryOpen</a><b></b> for example).</p>
<p>There can be up to 2048 objects (guest processes, files or directories) a time per guest session. Exceeding the limit will result in an appropriate error message.</p>
<p>When done with either of these objects, including the guest session itself, use the appropriate close() method to let the object do its cleanup work.</p>
<p>Every guest session has its own environment variable block which gets automatically applied when starting a new guest process via <a class="el" href="interface_i_guest_session.html#abe43b79ce8bd8d02454c60456c2a44a9">IGuestSession::processCreate</a><b></b> or <a class="el" href="interface_i_guest_session.html#a1353ebd47bb078594127a491d3af9797">IGuestSession::processCreateEx</a><b></b>. To override (or unset) certain environment variables already set by the guest session, one can specify a per-process environment block when using one of the both above mentioned process creation calls.</p>
<p>Closing a session via <a class="el" href="interface_i_guest_session.html#a931fd027935b8381f241c50818d41d0c">IGuestSession::close</a><b></b> will try to close all the mentioned objects above unless these objects are still used by a client.</p>
<dl><dt><b>Parameters:</b></dt><dd>
<table border="0" cellspacing="2" cellpadding="0">
<tr><td valign="top"></td><td valign="top"><em>user</em> </td><td>User name this session will be using to control the guest; has to exist and have the appropriate rights to execute programs in the VM. Must not be empty.</td></tr>
<tr><td valign="top"></td><td valign="top"><em>password</em> </td><td>Password of the user account to be used. Empty passwords are allowed.</td></tr>
<tr><td valign="top"></td><td valign="top"><em>domain</em> </td><td>Domain name of the user account to be used if the guest is part of a domain. Optional. This feature is not implemented yet.</td></tr>
<tr><td valign="top"></td><td valign="top"><em>sessionName</em> </td><td>The session's friendly name. Optional, can be empty.</td></tr>
<tr><td valign="top"></td><td valign="top"><em>guestSession</em> </td><td>The newly created session object. </td></tr>
</table>
</dd>
</dl>
</div>
</div>
<a class="anchor" id="a63b81a8caf1fce8be910830eafbcc837"></a><!-- doxytag: member="IGuest::findSession" ref="a63b81a8caf1fce8be910830eafbcc837" args="(in wstring sessionName,[retval] out IGuestSession[] sessions)" -->
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">void IGuest::findSession </td>
<td>(</td>
<td class="paramtype">in wstring </td>
<td class="paramname"> <em>sessionName</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype">[retval] out <a class="el" href="interface_i_guest_session.html">IGuestSession</a>[] </td>
<td class="paramname"> <em>sessions</em></td><td> </td>
</tr>
<tr>
<td></td>
<td>)</td>
<td></td><td></td><td></td>
</tr>
</table>
</div>
<div class="memdoc">
<p>Finds guest sessions by their friendly name and returns an interface array with all found guest sessions. </p>
<dl><dt><b>Parameters:</b></dt><dd>
<table border="0" cellspacing="2" cellpadding="0">
<tr><td valign="top"></td><td valign="top"><em>sessionName</em> </td><td>The session's friendly name to find. Wildcards like ? and * are allowed.</td></tr>
<tr><td valign="top"></td><td valign="top"><em>sessions</em> </td><td>Array with all guest sessions found matching the name specified. </td></tr>
</table>
</dd>
</dl>
</div>
</div>
<a class="anchor" id="adaf65b47e8cfd88edf511c099dbd452b"></a><!-- doxytag: member="IGuest::updateGuestAdditions" ref="adaf65b47e8cfd88edf511c099dbd452b" args="(in wstring source, in wstring[] arguments, in AdditionsUpdateFlag[] flags,[retval] out IProgress progress)" -->
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">void IGuest::updateGuestAdditions </td>
<td>(</td>
<td class="paramtype">in wstring </td>
<td class="paramname"> <em>source</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype">in wstring[] </td>
<td class="paramname"> <em>arguments</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype">in <a class="el" href="_virtual_box_8idl.html#a3f2b787d08708d68640a33680f12db85">AdditionsUpdateFlag</a>[] </td>
<td class="paramname"> <em>flags</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype">[retval] out <a class="el" href="interface_i_progress.html">IProgress</a> </td>
<td class="paramname"> <em>progress</em></td><td> </td>
</tr>
<tr>
<td></td>
<td>)</td>
<td></td><td></td><td></td>
</tr>
</table>
</div>
<div class="memdoc">
<p>Automatically updates already installed Guest Additions in a VM. </p>
<p>At the moment only Windows guests are supported.</p>
<p>Because the VirtualBox Guest Additions drivers are not WHQL-certified yet there might be warning dialogs during the actual Guest Additions update. These need to be confirmed manually in order to continue the installation process. This applies to Windows 2000 and Windows XP guests and therefore these guests can't be updated in a fully automated fashion without user interaction. However, to start a Guest Additions update for the mentioned Windows versions anyway, the flag AdditionsUpdateFlag_WaitForUpdateStartOnly can be specified. See <a class="el" href="_virtual_box_8idl.html#a3f2b787d08708d68640a33680f12db85">AdditionsUpdateFlag</a><b></b> for more information.</p>
<dl><dt><b>Parameters:</b></dt><dd>
<table border="0" cellspacing="2" cellpadding="0">
<tr><td valign="top"></td><td valign="top"><em>source</em> </td><td>Path to the Guest Additions .ISO file to use for the update.</td></tr>
<tr><td valign="top"></td><td valign="top"><em>arguments</em> </td><td>Optional command line arguments to use for the Guest Additions installer. Useful for retrofitting features which weren't installed before on the guest.</td></tr>
<tr><td valign="top"></td><td valign="top"><em>flags</em> </td><td><a class="el" href="_virtual_box_8idl.html#a3f2b787d08708d68640a33680f12db85">AdditionsUpdateFlag</a><b></b> flags.</td></tr>
<tr><td valign="top"></td><td valign="top"><em>progress</em> </td><td>Progress object to track the operation completion.</td></tr>
</table>
</dd>
</dl>
<dl class="user"><dt><b>Expected result codes:</b></dt><dd><table class="doxtable">
<tr>
<td><a class="el" href="group___virtual_box___c_o_m__result__codes.html#gaa4ba5e3fab3fe318c790d9d0b500c102">VBOX_E_NOT_SUPPORTED </a> </td><td>Guest OS is not supported for automated Guest Additions updates or the already installed Guest Additions are not ready yet. </td></tr>
<tr>
<td><a class="el" href="group___virtual_box___c_o_m__result__codes.html#ga95e965b219ae7d16a8dee5eca6267ce5">VBOX_E_IPRT_ERROR </a> </td><td>Error while updating. </td></tr>
</table>
</dd></dl>
</div>
</div>
<hr/><h2>Member Data Documentation</h2>
<a class="anchor" id="a1836d4706baed01b5de022ac2ca25ab6"></a><!-- doxytag: member="IGuest::OSTypeId" ref="a1836d4706baed01b5de022ac2ca25ab6" args="" -->
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">readonly attribute wstring <a class="el" href="interface_i_guest.html#a1836d4706baed01b5de022ac2ca25ab6">IGuest::OSTypeId</a></td>
</tr>
</table>
</div>
<div class="memdoc">
<p>Identifier of the Guest OS type as reported by the Guest Additions. </p>
<p>You may use <a class="el" href="interface_i_virtual_box.html#a59008a50b8352e70b968450a4748ec39">IVirtualBox::getGuestOSType</a><b></b> to obtain an <a class="el" href="interface_i_guest_o_s_type.html">IGuestOSType</a> object representing details about the given Guest OS type.</p>
<dl class="note"><dt><b>Note:</b></dt><dd>If Guest Additions are not installed, this value will be the same as <a class="el" href="interface_i_machine.html#a8b78acadfe037c9153080fb055f46a7d">IMachine::OSTypeId</a><b></b>. </dd></dl>
</div>
</div>
<a class="anchor" id="aa948ff08dfedcfd29fd0d10d68eeda6d"></a><!-- doxytag: member="IGuest::additionsRunLevel" ref="aa948ff08dfedcfd29fd0d10d68eeda6d" args="" -->
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">readonly attribute <a class="el" href="_virtual_box_8idl.html#a9e25175525bb1814c91c2df863d33d2d">AdditionsRunLevelType</a> <a class="el" href="interface_i_guest.html#aa948ff08dfedcfd29fd0d10d68eeda6d">IGuest::additionsRunLevel</a></td>
</tr>
</table>
</div>
<div class="memdoc">
<p>Current run level of the Guest Additions. </p>
</div>
</div>
<a class="anchor" id="a1ccd19a6e704c8ef1b369961d3f47b43"></a><!-- doxytag: member="IGuest::additionsVersion" ref="a1ccd19a6e704c8ef1b369961d3f47b43" args="" -->
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">readonly attribute wstring <a class="el" href="interface_i_guest.html#a1ccd19a6e704c8ef1b369961d3f47b43">IGuest::additionsVersion</a></td>
</tr>
</table>
</div>
<div class="memdoc">
<p>Version of the Guest Additions in the same format as <a class="el" href="interface_i_virtual_box.html#aa39d78ffaa90c1abe9d340a1a0738ed9">IVirtualBox::version</a><b></b>. </p>
</div>
</div>
<a class="anchor" id="a58206da74b7e15fbdb6d9863da5c49ee"></a><!-- doxytag: member="IGuest::additionsRevision" ref="a58206da74b7e15fbdb6d9863da5c49ee" args="" -->
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">readonly attribute unsigned long <a class="el" href="interface_i_guest.html#a58206da74b7e15fbdb6d9863da5c49ee">IGuest::additionsRevision</a></td>
</tr>
</table>
</div>
<div class="memdoc">
<p>The internal build revision number of the additions. </p>
<p>See also <a class="el" href="interface_i_virtual_box.html#a2d802ce16005dca1202dfc067f39c699">IVirtualBox::revision</a><b></b>. </p>
</div>
</div>
<a class="anchor" id="a6369c01ace2aa597191daec48ba72ec8"></a><!-- doxytag: member="IGuest::eventSource" ref="a6369c01ace2aa597191daec48ba72ec8" args="" -->
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">readonly attribute <a class="el" href="interface_i_event_source.html">IEventSource</a> <a class="el" href="interface_i_guest.html#a6369c01ace2aa597191daec48ba72ec8">IGuest::eventSource</a></td>
</tr>
</table>
</div>
<div class="memdoc">
<p>Event source for guest events. </p>
</div>
</div>
<a class="anchor" id="a1bd283f572c6b7540f7209dd0e4a2d31"></a><!-- doxytag: member="IGuest::facilities" ref="a1bd283f572c6b7540f7209dd0e4a2d31" args="" -->
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">readonly attribute <a class="el" href="interface_i_additions_facility.html">IAdditionsFacility</a> [] <a class="el" href="interface_i_guest.html#a1bd283f572c6b7540f7209dd0e4a2d31">IGuest::facilities</a></td>
</tr>
</table>
</div>
<div class="memdoc">
<p>Array of current known facilities. </p>
<p>Only returns facilities where a status is known, e.g. facilities with an unknown status will not be returned. </p>
</div>
</div>
<a class="anchor" id="ace5635124343b6345a905297f727bbb9"></a><!-- doxytag: member="IGuest::sessions" ref="ace5635124343b6345a905297f727bbb9" args="" -->
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">readonly attribute <a class="el" href="interface_i_guest_session.html">IGuestSession</a> [] <a class="el" href="interface_i_guest.html#ace5635124343b6345a905297f727bbb9">IGuest::sessions</a></td>
</tr>
</table>
</div>
<div class="memdoc">
<p>Returns a collection of all opened guest sessions. </p>
</div>
</div>
<a class="anchor" id="a2616a76e5a8466929e60017cf17960af"></a><!-- doxytag: member="IGuest::memoryBalloonSize" ref="a2616a76e5a8466929e60017cf17960af" args="" -->
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">attribute unsigned long <a class="el" href="interface_i_guest.html#a2616a76e5a8466929e60017cf17960af">IGuest::memoryBalloonSize</a></td>
</tr>
</table>
</div>
<div class="memdoc">
<p>Guest system memory balloon size in megabytes (transient property). </p>
</div>
</div>
<a class="anchor" id="aa1b7827f9228e604ed5112495e967f7f"></a><!-- doxytag: member="IGuest::statisticsUpdateInterval" ref="aa1b7827f9228e604ed5112495e967f7f" args="" -->
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">attribute unsigned long <a class="el" href="interface_i_guest.html#aa1b7827f9228e604ed5112495e967f7f">IGuest::statisticsUpdateInterval</a></td>
</tr>
</table>
</div>
<div class="memdoc">
<p>Interval to update guest statistics in seconds. </p>
</div>
</div>
</div>
<hr class="footer"/><address class="footer"><small>Generated on Wed Dec 18 2013 16:36:51 for VirtualBox Main API by
<a href="http://www.doxygen.org/index.html">
<img class="footer" src="doxygen.png" alt="doxygen"/></a> 1.7.1 </small></address>
</body>
</html>
|
dgomez10/xanon
|
SDK/docs/html/interface_i_guest.html
|
HTML
|
apache-2.0
| 66,710
|
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (1.8.0_232) on Tue Sep 15 08:53:07 UTC 2020 -->
<title>Uses of Class org.springframework.web.util.UriTemplate (Spring Framework 5.1.18.RELEASE API)</title>
<meta name="date" content="2020-09-15">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">
<script type="text/javascript" src="../../../../../script.js"></script>
</head>
<body>
<script type="text/javascript"><!--
try {
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Uses of Class org.springframework.web.util.UriTemplate (Spring Framework 5.1.18.RELEASE API)";
}
}
catch(err) {
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar.top">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.top.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../../org/springframework/web/util/UriTemplate.html" title="class in org.springframework.web.util">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../../../../../overview-tree.html">Tree</a></li>
<li><a href="../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../index-files/index-1.html">Index</a></li>
<li><a href="../../../../../help-doc.html">Help</a></li>
</ul>
<div class="aboutLanguage">Spring Framework</div>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../index.html?org/springframework/web/util/class-use/UriTemplate.html" target="_top">Frames</a></li>
<li><a href="UriTemplate.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip.navbar.top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<div class="header">
<h2 title="Uses of Class org.springframework.web.util.UriTemplate" class="title">Uses of Class<br>org.springframework.web.util.UriTemplate</h2>
</div>
<div class="classUseContainer">No usage of org.springframework.web.util.UriTemplate</div>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar.bottom">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.bottom.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../../org/springframework/web/util/UriTemplate.html" title="class in org.springframework.web.util">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../../../../../overview-tree.html">Tree</a></li>
<li><a href="../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../index-files/index-1.html">Index</a></li>
<li><a href="../../../../../help-doc.html">Help</a></li>
</ul>
<div class="aboutLanguage">Spring Framework</div>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../index.html?org/springframework/web/util/class-use/UriTemplate.html" target="_top">Frames</a></li>
<li><a href="UriTemplate.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip.navbar.bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
</body>
</html>
|
akhr/java
|
Spring/jars/spring-framework-5.1.18.RELEASE/docs/javadoc-api/org/springframework/web/util/class-use/UriTemplate.html
|
HTML
|
apache-2.0
| 4,623
|
/**
* @license Apache-2.0
*
* Copyright (c) 2020 The Stdlib Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
'use strict';
// MODULES //
var tape = require( 'tape' );
var objectKeys = require( '@stdlib/utils/keys' );
var isPlainObject = require( '@stdlib/assert/is-plain-object' );
var table = require( './../' ).EMOJI_CODE_PICTO;
// TESTS //
tape( 'main export is a function', function test( t ) {
t.ok( true, __filename );
t.equal( typeof table, 'function', 'main export is a function' );
t.end();
});
tape( 'the function returns an object', function test( t ) {
var tbl = table();
t.equal( isPlainObject( tbl ), true, 'returns an object' );
t.end();
});
tape( 'the returned object has keys', function test( t ) {
var tbl = table();
t.equal( objectKeys( tbl ).length > 0, true, 'has keys' );
t.end();
});
tape( 'the returned object maps emoji codes to pictographs', function test( t ) {
var tbl = table();
t.equal( tbl[ ':smile:' ], '😄', 'returns expected value' );
t.equal( tbl[ ':unicorn:' ], '🦄', 'returns expected value' );
t.end();
});
|
stdlib-js/stdlib
|
dist/datasets-emoji/test/test.emoji_code_picto.js
|
JavaScript
|
apache-2.0
| 1,579
|
// dominators
// another problem with gcc
void cprop_test6(int *data) {
int j = 5;
if (data[0])
data[1] = 10*j;
else
data[2] = 15*j;
data[3] = 21*j;
}
|
regehr/optimizer-eval
|
handwritten/constant-propagation/cprop6test.c
|
C
|
apache-2.0
| 168
|
<?php
/**
* PHPExcel
*
* Copyright (c) 2006 - 2013 PHPExcel
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
* @category PHPExcel
* @package PHPExcel_Writer_Excel2007
* @copyright Copyright (c) 2006 - 2013 PHPExcel (http://www.codeplex.com/PHPExcel)
* @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
* @version 1.7.9, 2013-06-02
*/
/**
* PHPExcel_Writer_Excel2007_WriterPart
*
* @category PHPExcel
* @package PHPExcel_Writer_Excel2007
* @copyright Copyright (c) 2006 - 2013 PHPExcel (http://www.codeplex.com/PHPExcel)
*/
abstract class PHPExcel_Writer_Excel2007_WriterPart
{
/**
* Parent IWriter object
*
* @var PHPExcel_Writer_IWriter
*/
private $_parentWriter;
/**
* Set parent IWriter object
*
* @param PHPExcel_Writer_IWriter $pWriter
* @throws PHPExcel_Writer_Exception
*/
public function setParentWriter(PHPExcel_Writer_IWriter $pWriter = null)
{
$this->_parentWriter = $pWriter;
}
/**
* Get parent IWriter object
*
* @return PHPExcel_Writer_IWriter
* @throws PHPExcel_Writer_Exception
*/
public function getParentWriter()
{
if (!is_null($this->_parentWriter)) {
return $this->_parentWriter;
} else {
throw new PHPExcel_Writer_Exception("No parent PHPExcel_Writer_IWriter assigned.");
}
}
/**
* Set parent IWriter object
*
* @param PHPExcel_Writer_IWriter $pWriter
* @throws PHPExcel_Writer_Exception
*/
public function __construct(PHPExcel_Writer_IWriter $pWriter = null)
{
if (!is_null($pWriter)) {
$this->_parentWriter = $pWriter;
}
}
}
|
kristhianfigueroa/retos
|
protected/messages/PHPExcel/Classes/PHPExcel/Writer/Excel2007/WriterPart.php
|
PHP
|
apache-2.0
| 2,438
|
function MouseTimer(){
timers = {};
listenersWait = {};
function init(){
setMouseMoveHandler();
}
function setMouseMoveHandler(){
$(document).mousemove(function(event) {
for (var time in timers){
var timer = timers[time];
clearTimeout(timer);
delete timers[time];
addTimer(time);
}
});
}
function addTimer(time){
if (!timers[time]) {
timers[time] = setTimeout(function(){
for (var i in listenersWait[time]){
var handler = listenersWait[time][i];
handler();
}
}, time);
}
}
function mousewait(time, handler){
if (!listenersWait[time]){
listenersWait[time] = [];
}
listenersWait[time].push(handler);
addTimer(time);
}
this.on = function(event, time, handler){
if (event.toLowerCase() == "mousewait"){
mousewait(time, handler);
}
};
this.off = function(event, time, handler){
if (event.toLowerCase() == "mousewait"){
if (!listenersWait[time]) return;
var pos = listenersWait[time].indexOf(handler);
if (pos >= 0){
listenersWait[time].splice(pos, 1);
}
}
};
init();
}
var MouseTimer = new MouseTimer();
|
werneckpaiva/retrato-js
|
src/mouse-timer.js
|
JavaScript
|
apache-2.0
| 1,444
|
# AUTOGENERATED FILE
FROM balenalib/surface-go-debian:buster-run
RUN apt-get update \
&& apt-get install -y --no-install-recommends \
ca-certificates \
curl \
\
# .NET Core dependencies
libc6 \
libgcc1 \
libgssapi-krb5-2 \
libicu63 \
libssl1.1 \
libstdc++6 \
zlib1g \
&& rm -rf /var/lib/apt/lists/*
# Configure web servers to bind to port 80 when present
ENV ASPNETCORE_URLS=http://+:80 \
# Enable detection of running in a container
DOTNET_RUNNING_IN_CONTAINER=true
# Install .NET Core SDK
ENV DOTNET_SDK_VERSION 5.0.403
RUN curl -SL --output dotnet.tar.gz "https://dotnetcli.blob.core.windows.net/dotnet/Sdk/$DOTNET_SDK_VERSION/dotnet-sdk-$DOTNET_SDK_VERSION-linux-x64.tar.gz" \
&& dotnet_sha512='7ba5f7f898dba64ea7027dc66184d60ac5ac35fabe750bd509711628442e098413878789fad5766be163fd2867cf22ef482a951e187cf629bbc6f54dd9293a4a' \
&& echo "$dotnet_sha512 dotnet.tar.gz" | sha512sum -c - \
&& mkdir -p /usr/share/dotnet \
&& tar -zxf dotnet.tar.gz -C /usr/share/dotnet \
&& rm dotnet.tar.gz \
&& ln -s /usr/share/dotnet/dotnet /usr/bin/dotnet
# Enable correct mode for dotnet watch (only mode supported in a container)
ENV DOTNET_USE_POLLING_FILE_WATCHER=true \
# Skip extraction of XML docs - generally not useful within an image/container - helps performance
NUGET_XMLDOC_MODE=skip \
DOTNET_NOLOGO=true
# Trigger first run experience by running arbitrary cmd to populate local package cache
RUN dotnet help
CMD ["echo","'No CMD command was set in Dockerfile! Details about CMD command could be found in Dockerfile Guide section in our Docs. Here's the link: https://balena.io/docs"]
RUN curl -SLO "https://raw.githubusercontent.com/balena-io-library/base-images/44e597e40f2010cdde15b3ba1e397aea3a5c5271/scripts/assets/tests/test-stack@dotnet.sh" \
&& echo "Running test-stack@dotnet" \
&& chmod +x test-stack@dotnet.sh \
&& bash test-stack@dotnet.sh \
&& rm -rf test-stack@dotnet.sh
RUN [ ! -d /.balena/messages ] && mkdir -p /.balena/messages; echo 'Here are a few details about this Docker image (For more information please visit https://www.balena.io/docs/reference/base-images/base-images/): \nArchitecture: Intel 64-bit (x86-64) \nOS: Debian Buster \nVariant: run variant \nDefault variable(s): UDEV=off \nThe following software stack is preinstalled: \ndotnet 5.0-sdk \nExtra features: \n- Easy way to install packages with `install_packages <package-name>` command \n- Run anywhere with cross-build feature (for ARM only) \n- Keep the container idling with `balena-idle` command \n- Show base image details with `balena-info` command' > /.balena/messages/image-info
RUN echo '#!/bin/sh.real\nbalena-info\nrm -f /bin/sh\ncp /bin/sh.real /bin/sh\n/bin/sh "$@"' > /bin/sh-shim \
&& chmod +x /bin/sh-shim \
&& cp /bin/sh /bin/sh.real \
&& mv /bin/sh-shim /bin/sh
|
resin-io-library/base-images
|
balena-base-images/dotnet/surface-go/debian/buster/5.0-sdk/run/Dockerfile
|
Dockerfile
|
apache-2.0
| 2,924
|
/*
* Copyright 2017 Red Hat, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jboss.migration.wfly11.task.subsystem.elytron;
import org.jboss.as.controller.PathAddress;
import org.jboss.as.controller.operations.common.Util;
import org.jboss.dmr.ModelNode;
import java.util.ArrayList;
import java.util.List;
/**
* @author emmartins
*/
public class ConstantPermissionMapperAddOperation {
private final PathAddress subsystemPathAddress;
private final String contanstPermissionMapper;
private List<Permission> permissions;
public ConstantPermissionMapperAddOperation(PathAddress subsystemPathAddress, String contanstPermissionMapper) {
this.subsystemPathAddress = subsystemPathAddress;
this.contanstPermissionMapper = contanstPermissionMapper;
this.permissions = new ArrayList<>();
}
public ConstantPermissionMapperAddOperation addPermission(Permission permission) {
this.permissions.add(permission);
return this;
}
public ModelNode toModelNode() {
/*
"permissions" => [
{"class-name" => "org.wildfly.security.auth.permission.LoginPermission"},
{
"class-name" => "org.wildfly.extension.batch.jberet.deployment.BatchPermission",
"module" => "org.wildfly.extension.batch.jberet",
"target-name" => "*"
},
{
"class-name" => "org.wildfly.transaction.client.RemoteTransactionPermission",
"module" => "org.wildfly.transaction.client"
},
{
"class-name" => "org.jboss.ejb.client.RemoteEJBPermission",
"module" => "org.jboss.ejb-client"
}
],
"operation" => "add",
"address" => [
("subsystem" => "elytron"),
("constant-permission-mapper" => "constant-permission-mapper")
]
*/
final PathAddress pathAddress = subsystemPathAddress.append("constant-permission-mapper", contanstPermissionMapper);
final ModelNode operation = Util.createAddOperation(pathAddress);
if (permissions != null && !permissions.isEmpty()) {
final ModelNode permissionsNode = operation.get("permissions").setEmptyList();
for (Permission permission : permissions) {
permissionsNode.add(permission.toModelNode());
}
}
return operation;
}
}
|
emmartins/wildfly-server-migration
|
servers/wildfly11.0/src/main/java/org/jboss/migration/wfly11/task/subsystem/elytron/ConstantPermissionMapperAddOperation.java
|
Java
|
apache-2.0
| 3,062
|
/*
* Copyright 1999-2011 Alibaba Group.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.dubbo.remoting.transport.netty;
import java.net.InetSocketAddress;
import java.util.Collection;
import java.util.HashSet;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import org.jboss.netty.bootstrap.ServerBootstrap;
import org.jboss.netty.channel.ChannelFactory;
import org.jboss.netty.channel.ChannelPipeline;
import org.jboss.netty.channel.ChannelPipelineFactory;
import org.jboss.netty.channel.Channels;
import org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory;
import com.alibaba.dubbo.common.Constants;
import com.alibaba.dubbo.common.URL;
import com.alibaba.dubbo.common.logger.Logger;
import com.alibaba.dubbo.common.logger.LoggerFactory;
import com.alibaba.dubbo.common.utils.ExecutorUtil;
import com.alibaba.dubbo.common.utils.NamedThreadFactory;
import com.alibaba.dubbo.common.utils.NetUtils;
import com.alibaba.dubbo.remoting.Channel;
import com.alibaba.dubbo.remoting.ChannelHandler;
import com.alibaba.dubbo.remoting.RemotingException;
import com.alibaba.dubbo.remoting.Server;
import com.alibaba.dubbo.remoting.transport.AbstractServer;
import com.alibaba.dubbo.remoting.transport.dispatcher.ChannelHandlers;
import org.jboss.netty.logging.InternalLogger;
import org.jboss.netty.logging.InternalLoggerFactory;
/**
* NettyServer
*
* @author qian.lei
* @author chao.liuc
*/
public class NettyServer extends AbstractServer implements Server {
private static final InternalLogger logger = InternalLoggerFactory.getInstance(NettyClient.class);
private Map<String, Channel> channels; // <ip:port, channel>
private ServerBootstrap bootstrap;
private org.jboss.netty.channel.Channel channel;
public NettyServer(URL url, ChannelHandler handler) throws RemotingException {
super(url, ChannelHandlers.wrap(handler, ExecutorUtil.setThreadName(url, SERVER_THREAD_POOL_NAME)));
}
@Override
protected void doOpen() throws Throwable {
logger.debug("开始打开 NettyServer 监听..........." + this.getClass());
ExecutorService boss = Executors.newCachedThreadPool(new NamedThreadFactory("NettyServerBoss", true));
ExecutorService worker = Executors.newCachedThreadPool(new NamedThreadFactory("NettyServerWorker", true));
ChannelFactory channelFactory = new NioServerSocketChannelFactory(boss, worker, getUrl().getPositiveParameter(Constants.IO_THREADS_KEY, Constants.DEFAULT_IO_THREADS));
bootstrap = new ServerBootstrap(channelFactory);
final NettyHandler nettyHandler = new NettyHandler(getUrl(), this);
channels = nettyHandler.getChannels();
// https://issues.jboss.org/browse/NETTY-365
// https://issues.jboss.org/browse/NETTY-379
// final Timer timer = new HashedWheelTimer(new NamedThreadFactory("NettyIdleTimer", true));
bootstrap.setPipelineFactory(new ChannelPipelineFactory() {
public ChannelPipeline getPipeline() {
NettyCodecAdapter adapter = new NettyCodecAdapter(getCodec(), getUrl(), NettyServer.this);
ChannelPipeline pipeline = Channels.pipeline();
/*int idleTimeout = getIdleTimeout();
if (idleTimeout > 10000) {
pipeline.addLast("timer", new IdleStateHandler(timer, idleTimeout / 1000, 0, 0));
}*/
pipeline.addLast("decoder", adapter.getDecoder());
pipeline.addLast("encoder", adapter.getEncoder());
pipeline.addLast("handler", nettyHandler);
return pipeline;
}
});
// bind
channel = bootstrap.bind(getBindAddress());
logger.debug("NettyServer 监听 启动完成..........." + this.getClass());
}
@Override
protected void doClose() throws Throwable {
try {
if (channel != null) {
// unbind.
channel.close();
}
} catch (Throwable e) {
logger.warn(e.getMessage(), e);
}
try {
Collection<com.alibaba.dubbo.remoting.Channel> channels = getChannels();
if (channels != null && channels.size() > 0) {
for (com.alibaba.dubbo.remoting.Channel channel : channels) {
try {
channel.close();
} catch (Throwable e) {
logger.warn(e.getMessage(), e);
}
}
}
} catch (Throwable e) {
logger.warn(e.getMessage(), e);
}
try {
if (bootstrap != null) {
// release external resource.
bootstrap.releaseExternalResources();
}
} catch (Throwable e) {
logger.warn(e.getMessage(), e);
}
try {
if (channels != null) {
channels.clear();
}
} catch (Throwable e) {
logger.warn(e.getMessage(), e);
}
}
public Collection<Channel> getChannels() {
Collection<Channel> chs = new HashSet<Channel>();
for (Channel channel : this.channels.values()) {
if (channel.isConnected()) {
chs.add(channel);
} else {
channels.remove(NetUtils.toAddressString(channel.getRemoteAddress()));
}
}
return chs;
}
public Channel getChannel(InetSocketAddress remoteAddress) {
return channels.get(NetUtils.toAddressString(remoteAddress));
}
public boolean isBound() {
return channel.isBound();
}
}
|
LubinXuan/dubbox
|
dubbo-remoting/dubbo-remoting-netty/src/main/java/com/alibaba/dubbo/remoting/transport/netty/NettyServer.java
|
Java
|
apache-2.0
| 6,262
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.