code stringlengths 3 1.05M | repo_name stringlengths 4 116 | path stringlengths 4 991 | language stringclasses 9 values | license stringclasses 15 values | size int32 3 1.05M |
|---|---|---|---|---|---|
import Ember from 'ember';
const DELAY = 100;
export default Ember.Component.extend({
classNameBindings : ['inlineBlock:inline-block','clip:clip'],
tooltipService : Ember.inject.service('tooltip'),
inlineBlock : true,
clip : false,
model : null,
size : 'default',
ariaRole : ['tooltip'],
textChangedEvent : null,
showTimer : null,
textChanged: Ember.observer('textChangedEvent', function() {
this.show(this.get('textChangedEvent'));
}),
mouseEnter(evt) {
if ( !this.get('tooltipService.requireClick') )
{
let tgt = Ember.$(evt.currentTarget);
if (this.get('tooltipService.tooltipOpts')) {
this.set('tooltipService.tooltipOpts', null);
}
// Wait for a little bit of time so that the mouse can pass through
// another tooltip-element on the way to the dropdown trigger of a
// tooltip-action-menu without changing the tooltip.
this.set('showTimer', Ember.run.later(() => {
this.show(tgt);
}, DELAY));
}
},
show(node) {
if ( this._state === 'destroying' )
{
return;
}
let svc = this.get('tooltipService');
this.set('showTimer', null);
svc.cancelTimer();
let out = {
type : this.get('type'),
baseClass : this.get('baseClass'),
eventPosition : node.offset(),
originalNode : node,
model : this.get('model'),
template : this.get('tooltipTemplate'),
};
if ( this.get('isCopyTo') ) {
out.isCopyTo = true;
}
svc.set('tooltipOpts', out);
},
mouseLeave: function() {
if (!this.get('tooltipService.openedViaContextClick')) {
if ( this.get('showTimer') ) {
Ember.run.cancel(this.get('showTimer'));
}
else {
this.get('tooltipService').leave();
}
}
},
modelObserver: Ember.observer('model', 'textChangedEvent', function() {
let opts = this.get('tooltipService.tooltipOpts');
if (opts) {
this.set('tooltipService.tooltipOpts.model', this.get('model'));
}
})
});
| nrvale0/ui | app/components/tooltip-element/component.js | JavaScript | apache-2.0 | 2,144 |
package com.altas.preferencevobjectfile.model;
import java.io.Serializable;
/**
* @author Altas
* @email Altas.TuTu@gmail.com
* @date 2014年9月27日
*/
public class UserInfo implements Serializable {
/**
*
*/
private static final long serialVersionUID = 8558071977129572083L;
public int id;
public String token;
public String userName;
public String headImg;
public String phoneNum;
public double balance;
public int integral;
public UserInfo(){}
public UserInfo(int i,String t,String un,String hi,String pn,double b,int point){
id=i;
token=t;
userName = un;
headImg = hi;
phoneNum = pn;
balance = b;
integral = point;
}
}
| mdreza/PreferenceVObjectFile | PreferenceVObjectFile/src/com/altas/preferencevobjectfile/model/UserInfo.java | Java | apache-2.0 | 663 |
# -*- encoding: utf-8 -*-
#
# 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.
import pyparsing as pp
uninary_operators = ("not", )
binary_operator = (u">=", u"<=", u"!=", u">", u"<", u"=", u"==", u"eq", u"ne",
u"lt", u"gt", u"ge", u"le", u"in", u"like", u"≠", u"≥",
u"≤", u"like" "in")
multiple_operators = (u"and", u"or", u"∧", u"∨")
operator = pp.Regex(u"|".join(binary_operator))
null = pp.Regex("None|none|null").setParseAction(pp.replaceWith(None))
boolean = "False|True|false|true"
boolean = pp.Regex(boolean).setParseAction(lambda t: t[0].lower() == "true")
hex_string = lambda n: pp.Word(pp.hexnums, exact=n)
uuid = pp.Combine(hex_string(8) + ("-" + hex_string(4)) * 3 +
"-" + hex_string(12))
number = r"[+-]?\d+(:?\.\d*)?(:?[eE][+-]?\d+)?"
number = pp.Regex(number).setParseAction(lambda t: float(t[0]))
identifier = pp.Word(pp.alphas, pp.alphanums + "_")
quoted_string = pp.QuotedString('"') | pp.QuotedString("'")
comparison_term = pp.Forward()
in_list = pp.Group(pp.Suppress('[') +
pp.Optional(pp.delimitedList(comparison_term)) +
pp.Suppress(']'))("list")
comparison_term << (null | boolean | uuid | identifier | number |
quoted_string | in_list)
condition = pp.Group(comparison_term + operator + comparison_term)
expr = pp.operatorPrecedence(condition, [
("not", 1, pp.opAssoc.RIGHT, ),
("and", 2, pp.opAssoc.LEFT, ),
("∧", 2, pp.opAssoc.LEFT, ),
("or", 2, pp.opAssoc.LEFT, ),
("∨", 2, pp.opAssoc.LEFT, ),
])
def _parsed_query2dict(parsed_query):
result = None
while parsed_query:
part = parsed_query.pop()
if part in binary_operator:
result = {part: {parsed_query.pop(): result}}
elif part in multiple_operators:
if result.get(part):
result[part].append(
_parsed_query2dict(parsed_query.pop()))
else:
result = {part: [result]}
elif part in uninary_operators:
result = {part: result}
elif isinstance(part, pp.ParseResults):
kind = part.getName()
if kind == "list":
res = part.asList()
else:
res = _parsed_query2dict(part)
if result is None:
result = res
elif isinstance(result, dict):
list(result.values())[0].append(res)
else:
result = part
return result
def search_query_builder(query):
parsed_query = expr.parseString(query)[0]
return _parsed_query2dict(parsed_query)
def list2cols(cols, objs):
return cols, [tuple([o[k] for k in cols])
for o in objs]
def format_string_list(objs, field):
objs[field] = ", ".join(objs[field])
def format_dict_list(objs, field):
objs[field] = "\n".join(
"- " + ", ".join("%s: %s" % (k, v)
for k, v in elem.items())
for elem in objs[field])
def format_move_dict_to_root(obj, field):
for attr in obj[field]:
obj["%s/%s" % (field, attr)] = obj[field][attr]
del obj[field]
def format_archive_policy(ap):
format_dict_list(ap, "definition")
format_string_list(ap, "aggregation_methods")
def dict_from_parsed_args(parsed_args, attrs):
d = {}
for attr in attrs:
value = getattr(parsed_args, attr)
if value is not None:
d[attr] = value
return d
def dict_to_querystring(objs):
return "&".join(["%s=%s" % (k, v)
for k, v in objs.items()
if v is not None])
| chungg/python-aodhclient | aodhclient/utils.py | Python | apache-2.0 | 4,174 |
/* Copyright 2017 Braden Farmer
*
* 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.farmerbb.secondscreen.service;
import android.app.KeyguardManager;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.admin.DevicePolicyManager;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.inputmethodservice.InputMethodService;
import android.os.Build;
import androidx.core.app.NotificationCompat;
import android.text.InputType;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import com.farmerbb.secondscreen.R;
import com.farmerbb.secondscreen.receiver.KeyboardChangeReceiver;
import com.farmerbb.secondscreen.util.U;
import java.util.Random;
public class DisableKeyboardService extends InputMethodService {
Integer notificationId;
@Override
public boolean onShowInputRequested(int flags, boolean configChange) {
return false;
}
@Override
public void onStartInput(EditorInfo attribute, boolean restarting) {
boolean isEditingText = attribute.inputType != InputType.TYPE_NULL;
boolean hasHardwareKeyboard = getResources().getConfiguration().keyboard != Configuration.KEYBOARD_NOKEYS;
if(notificationId == null && isEditingText && !hasHardwareKeyboard) {
Intent keyboardChangeIntent = new Intent(this, KeyboardChangeReceiver.class);
PendingIntent keyboardChangePendingIntent = PendingIntent.getBroadcast(this, 0, keyboardChangeIntent, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder notification = new NotificationCompat.Builder(this)
.setContentIntent(keyboardChangePendingIntent)
.setSmallIcon(android.R.drawable.stat_sys_warning)
.setContentTitle(getString(R.string.disabling_soft_keyboard))
.setContentText(getString(R.string.tap_to_change_keyboards))
.setOngoing(true)
.setShowWhen(false);
// Respect setting to hide notification
SharedPreferences prefMain = U.getPrefMain(this);
if(prefMain.getBoolean("hide_notification", false))
notification.setPriority(Notification.PRIORITY_MIN);
notificationId = new Random().nextInt();
NotificationManager nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
nm.notify(notificationId, notification.build());
boolean autoShowInputMethodPicker = false;
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
DevicePolicyManager devicePolicyManager = (DevicePolicyManager) getSystemService(DEVICE_POLICY_SERVICE);
switch(devicePolicyManager.getStorageEncryptionStatus()) {
case DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE:
case DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE_PER_USER:
break;
default:
autoShowInputMethodPicker = true;
break;
}
}
KeyguardManager keyguardManager = (KeyguardManager) getSystemService(KEYGUARD_SERVICE);
if(keyguardManager.inKeyguardRestrictedInputMode() && autoShowInputMethodPicker) {
InputMethodManager manager = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
manager.showInputMethodPicker();
}
} else if(notificationId != null && !isEditingText) {
NotificationManager nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
nm.cancel(notificationId);
notificationId = null;
}
}
@Override
public void onDestroy() {
if(notificationId != null) {
NotificationManager nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
nm.cancel(notificationId);
notificationId = null;
}
super.onDestroy();
}
}
| farmerbb/SecondScreen | app/src/main/java/com/farmerbb/secondscreen/service/DisableKeyboardService.java | Java | apache-2.0 | 4,734 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Http;
using AutoMapper;
using Art.Domain;
namespace Art.Rest.v1
{
// Generated 07/20/2013 16:40:13
// Change code for each method
public class UsersController : BaseApiController
{
// GET Collection
[HttpGet]
public IEnumerable<ApiUser> Get(string expand = "")
{
return new List<ApiUser>();
}
// GET Single
[HttpGet]
public ApiUser Get(int? id, string expand = "")
{
return new ApiUser();
}
// POST = Insert
[HttpPost]
public ApiUser Post([FromBody] ApiUser apiuser)
{
return apiuser;
}
// PUT = Update
[HttpPut]
public ApiUser Put(int? id, [FromBody] ApiUser apiuser)
{
return apiuser;
}
// DELETE
[HttpDelete]
public ApiUser Delete(int? id)
{
return new ApiUser();
}
}
}
| Kiandr/MS | NetPatternDesign/Spark/Art.Rest.v1/Controllers/UsersController.cs | C# | apache-2.0 | 1,090 |
# Copyright 2013 - 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.
from solum import objects
from solum.objects import extension as abstract_extension
from solum.objects import operation as abstract_operation
from solum.objects import plan as abstract_plan
from solum.objects import sensor as abstract_sensor
from solum.objects import service as abstract_srvc
from solum.objects.sqlalchemy import extension
from solum.objects.sqlalchemy import operation
from solum.objects.sqlalchemy import plan
from solum.objects.sqlalchemy import sensor
from solum.objects.sqlalchemy import service
def load():
"""Activate the sqlalchemy backend."""
objects.registry.add(abstract_plan.Plan, plan.Plan)
objects.registry.add(abstract_plan.PlanList, plan.PlanList)
objects.registry.add(abstract_srvc.Service, service.Service)
objects.registry.add(abstract_srvc.ServiceList, service.ServiceList)
objects.registry.add(abstract_operation.Operation, operation.Operation)
objects.registry.add(abstract_operation.OperationList,
operation.OperationList)
objects.registry.add(abstract_sensor.Sensor, sensor.Sensor)
objects.registry.add(abstract_sensor.SensorList, sensor.SensorList)
objects.registry.add(abstract_extension.Extension, extension.Extension)
objects.registry.add(abstract_extension.ExtensionList,
extension.ExtensionList)
| shakamunyi/solum | solum/objects/sqlalchemy/__init__.py | Python | apache-2.0 | 1,920 |
/**
* @license Apache-2.0
*
* Copyright (c) 2018 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 Readable = require( 'readable-stream' ).Readable;
var isPositiveNumber = require( '@stdlib/assert/is-positive-number' ).isPrimitive;
var isProbability = require( '@stdlib/assert/is-probability' ).isPrimitive;
var isError = require( '@stdlib/assert/is-error' );
var copy = require( '@stdlib/utils/copy' );
var inherit = require( '@stdlib/utils/inherit' );
var setNonEnumerable = require( '@stdlib/utils/define-nonenumerable-property' );
var setNonEnumerableReadOnly = require( '@stdlib/utils/define-nonenumerable-read-only-property' );
var setReadOnlyAccessor = require( '@stdlib/utils/define-read-only-accessor' );
var setReadWriteAccessor = require( '@stdlib/utils/define-read-write-accessor' );
var rnbinom = require( '@stdlib/random/base/negative-binomial' ).factory;
var string2buffer = require( '@stdlib/buffer/from-string' );
var nextTick = require( '@stdlib/utils/next-tick' );
var DEFAULTS = require( './defaults.json' );
var validate = require( './validate.js' );
var debug = require( './debug.js' );
// FUNCTIONS //
/**
* Returns the PRNG seed.
*
* @private
* @returns {(PRNGSeedMT19937|null)} seed
*/
function getSeed() {
return this._prng.seed; // eslint-disable-line no-invalid-this
}
/**
* Returns the PRNG seed length.
*
* @private
* @returns {(PositiveInteger|null)} seed length
*/
function getSeedLength() {
return this._prng.seedLength; // eslint-disable-line no-invalid-this
}
/**
* Returns the PRNG state length.
*
* @private
* @returns {(PositiveInteger|null)} state length
*/
function getStateLength() {
return this._prng.stateLength; // eslint-disable-line no-invalid-this
}
/**
* Returns the PRNG state size (in bytes).
*
* @private
* @returns {(PositiveInteger|null)} state size (in bytes)
*/
function getStateSize() {
return this._prng.byteLength; // eslint-disable-line no-invalid-this
}
/**
* Returns the current PRNG state.
*
* @private
* @returns {(PRNGStateMT19937|null)} current state
*/
function getState() {
return this._prng.state; // eslint-disable-line no-invalid-this
}
/**
* Sets the PRNG state.
*
* @private
* @param {PRNGStateMT19937} s - generator state
* @throws {Error} must provide a valid state
*/
function setState( s ) {
this._prng.state = s; // eslint-disable-line no-invalid-this
}
/**
* Implements the `_read` method.
*
* @private
* @param {number} size - number (of bytes) to read
* @returns {void}
*/
function read() {
/* eslint-disable no-invalid-this */
var FLG;
var r;
if ( this._destroyed ) {
return;
}
FLG = true;
while ( FLG ) {
this._i += 1;
if ( this._i > this._iter ) {
debug( 'Finished generating pseudorandom numbers.' );
return this.push( null );
}
r = this._prng();
debug( 'Generated a new pseudorandom number. Value: %d. Iter: %d.', r, this._i );
if ( this._objectMode === false ) {
r = r.toString();
if ( this._i === 1 ) {
r = string2buffer( r );
} else {
r = string2buffer( this._sep+r );
}
}
FLG = this.push( r );
if ( this._i%this._siter === 0 ) {
this.emit( 'state', this.state );
}
}
/* eslint-enable no-invalid-this */
}
/**
* Gracefully destroys a stream, providing backward compatibility.
*
* @private
* @param {(string|Object|Error)} [error] - error
* @returns {RandomStream} Stream instance
*/
function destroy( error ) {
/* eslint-disable no-invalid-this */
var self;
if ( this._destroyed ) {
debug( 'Attempted to destroy an already destroyed stream.' );
return this;
}
self = this;
this._destroyed = true;
nextTick( close );
return this;
/**
* Closes a stream.
*
* @private
*/
function close() {
if ( error ) {
debug( 'Stream was destroyed due to an error. Error: %s.', ( isError( error ) ) ? error.message : JSON.stringify( error ) );
self.emit( 'error', error );
}
debug( 'Closing the stream...' );
self.emit( 'close' );
}
/* eslint-enable no-invalid-this */
}
// MAIN //
/**
* Stream constructor for generating a stream of pseudorandom numbers drawn from a binomial distribution.
*
* @constructor
* @param {PositiveNumber} r - number of successes until experiment is stopped
* @param {Probability} p - success probability
* @param {Options} [options] - stream options
* @param {boolean} [options.objectMode=false] - specifies whether the stream should operate in object mode
* @param {(string|null)} [options.encoding=null] - specifies how `Buffer` objects should be decoded to strings
* @param {NonNegativeNumber} [options.highWaterMark] - specifies the maximum number of bytes to store in an internal buffer before ceasing to generate additional pseudorandom numbers
* @param {string} [options.sep='\n'] - separator used to join streamed data
* @param {NonNegativeInteger} [options.iter] - number of iterations
* @param {PRNG} [options.prng] - pseudorandom number generator which generates uniformly distributed pseudorandom numbers
* @param {PRNGSeedMT19937} [options.seed] - pseudorandom number generator seed
* @param {PRNGStateMT19937} [options.state] - pseudorandom number generator state
* @param {boolean} [options.copy=true] - boolean indicating whether to copy a provided pseudorandom number generator state
* @param {PositiveInteger} [options.siter] - number of iterations after which to emit the PRNG state
* @throws {TypeError} `r` must be a positive number
* @throws {TypeError} `p` must be a probability
* @throws {TypeError} options argument must be an object
* @throws {TypeError} must provide valid options
* @throws {Error} must provide a valid state
* @returns {RandomStream} Stream instance
*
* @example
* var inspectStream = require( '@stdlib/streams/node/inspect-sink' );
*
* function log( chunk ) {
* console.log( chunk.toString() );
* }
*
* var opts = {
* 'iter': 10
* };
*
* var stream = new RandomStream( 20.0, 0.2, opts );
*
* stream.pipe( inspectStream( log ) );
*/
function RandomStream( r, p, options ) {
var opts;
var err;
if ( !( this instanceof RandomStream ) ) {
if ( arguments.length > 2 ) {
return new RandomStream( r, p, options );
}
return new RandomStream( r, p );
}
if ( !isPositiveNumber( r ) ) {
throw new TypeError( 'invalid argument. First argument must be a positive number. Value: `'+r+'`.' );
}
if ( !isProbability( p ) ) {
throw new TypeError( 'invalid argument. Second argument must be a probability. Value: `'+p+'`.' );
}
opts = copy( DEFAULTS );
if ( arguments.length > 2 ) {
err = validate( opts, options );
if ( err ) {
throw err;
}
}
// Make the stream a readable stream:
debug( 'Creating a readable stream configured with the following options: %s.', JSON.stringify( opts ) );
Readable.call( this, opts );
// Destruction state:
setNonEnumerable( this, '_destroyed', false );
// Cache whether the stream is operating in object mode:
setNonEnumerableReadOnly( this, '_objectMode', opts.objectMode );
// Cache the separator:
setNonEnumerableReadOnly( this, '_sep', opts.sep );
// Cache the total number of iterations:
setNonEnumerableReadOnly( this, '_iter', opts.iter );
// Cache the number of iterations after which to emit the underlying PRNG state:
setNonEnumerableReadOnly( this, '_siter', opts.siter );
// Initialize an iteration counter:
setNonEnumerable( this, '_i', 0 );
// Create the underlying PRNG:
setNonEnumerableReadOnly( this, '_prng', rnbinom( r, p, opts ) );
setNonEnumerableReadOnly( this, 'PRNG', this._prng.PRNG );
return this;
}
/*
* Inherit from the `Readable` prototype.
*/
inherit( RandomStream, Readable );
/**
* PRNG seed.
*
* @name seed
* @memberof RandomStream.prototype
* @type {(PRNGSeedMT19937|null)}
*/
setReadOnlyAccessor( RandomStream.prototype, 'seed', getSeed );
/**
* PRNG seed length.
*
* @name seedLength
* @memberof RandomStream.prototype
* @type {(PositiveInteger|null)}
*/
setReadOnlyAccessor( RandomStream.prototype, 'seedLength', getSeedLength );
/**
* PRNG state getter/setter.
*
* @name state
* @memberof RandomStream.prototype
* @type {(PRNGStateMT19937|null)}
* @throws {Error} must provide a valid state
*/
setReadWriteAccessor( RandomStream.prototype, 'state', getState, setState );
/**
* PRNG state length.
*
* @name stateLength
* @memberof RandomStream.prototype
* @type {(PositiveInteger|null)}
*/
setReadOnlyAccessor( RandomStream.prototype, 'stateLength', getStateLength );
/**
* PRNG state size (in bytes).
*
* @name byteLength
* @memberof RandomStream.prototype
* @type {(PositiveInteger|null)}
*/
setReadOnlyAccessor( RandomStream.prototype, 'byteLength', getStateSize );
/**
* Implements the `_read` method.
*
* @private
* @name _read
* @memberof RandomStream.prototype
* @type {Function}
* @param {number} size - number (of bytes) to read
* @returns {void}
*/
setNonEnumerableReadOnly( RandomStream.prototype, '_read', read );
/**
* Gracefully destroys a stream, providing backward compatibility.
*
* @name destroy
* @memberof RandomStream.prototype
* @type {Function}
* @param {(string|Object|Error)} [error] - error
* @returns {RandomStream} Stream instance
*/
setNonEnumerableReadOnly( RandomStream.prototype, 'destroy', destroy );
// EXPORTS //
module.exports = RandomStream;
| stdlib-js/stdlib | lib/node_modules/@stdlib/random/streams/negative-binomial/lib/main.js | JavaScript | apache-2.0 | 9,730 |
/**
* Copyright (c) 2005-2012 https://github.com/zhuruiboqq
*
* Licensed under the Apache License, Version 2.0 (the "License");
*/
package com.sishuok.es.common.entity.search.filter;
import com.sishuok.es.common.entity.search.SearchOperator;
import com.sishuok.es.common.entity.search.exception.InvlidSearchOperatorException;
import com.sishuok.es.common.entity.search.exception.SearchException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.Assert;
import java.util.List;
/**
* <p>查询过滤条件</p>
* <p>User: Zhang Kaitao
* <p>Date: 13-1-15 上午7:12
* <p>Version: 1.0
*/
public final class Condition implements SearchFilter {
//查询参数分隔符
public static final String separator = "_";
private String key;
private String searchProperty;
private SearchOperator operator;
private Object value;
/**
* 根据查询key和值生成Condition
*
* @param key 如 name_like
* @param value
* @return
*/
static Condition newCondition(final String key, final Object value) throws SearchException {
Assert.notNull(key, "Condition key must not null");
String[] searchs = StringUtils.split(key, separator);
if (searchs.length == 0) {
throw new SearchException("Condition key format must be : property or property_op");
}
String searchProperty = searchs[0];
SearchOperator operator = null;
if (searchs.length == 1) {
operator = SearchOperator.custom;
} else {
try {
operator = SearchOperator.valueOf(searchs[1]);
} catch (IllegalArgumentException e) {
throw new InvlidSearchOperatorException(searchProperty, searchs[1]);
}
}
boolean allowBlankValue = SearchOperator.isAllowBlankValue(operator);
boolean isValueBlank = (value == null);
isValueBlank = isValueBlank || (value instanceof String && StringUtils.isBlank((String) value));
isValueBlank = isValueBlank || (value instanceof List && ((List) value).size() == 0);
//过滤掉空值,即不参与查询
if (!allowBlankValue && isValueBlank) {
return null;
}
Condition searchFilter = newCondition(searchProperty, operator, value);
return searchFilter;
}
/**
* 根据查询属性、操作符和值生成Condition
*
* @param searchProperty
* @param operator
* @param value
* @return
*/
static Condition newCondition(final String searchProperty, final SearchOperator operator, final Object value) {
return new Condition(searchProperty, operator, value);
}
/**
* @param searchProperty 属性名
* @param operator 操作
* @param value 值
*/
private Condition(final String searchProperty, final SearchOperator operator, final Object value) {
this.searchProperty = searchProperty;
this.operator = operator;
this.value = value;
this.key = this.searchProperty + separator + this.operator;
}
public String getKey() {
return key;
}
public String getSearchProperty() {
return searchProperty;
}
/**
* 获取 操作符
*
* @return
*/
public SearchOperator getOperator() throws InvlidSearchOperatorException {
return operator;
}
/**
* 获取自定义查询使用的操作符
* 1、首先获取前台传的
* 2、返回空
*
* @return
*/
public String getOperatorStr() {
if (operator != null) {
return operator.getSymbol();
}
return "";
}
public Object getValue() {
return value;
}
public void setValue(final Object value) {
this.value = value;
}
public void setOperator(final SearchOperator operator) {
this.operator = operator;
}
public void setSearchProperty(final String searchProperty) {
this.searchProperty = searchProperty;
}
/**
* 得到实体属性名
*
* @return
*/
public String getEntityProperty() {
return searchProperty;
}
/**
* 是否是一元过滤 如is null is not null
*
* @return
*/
public boolean isUnaryFilter() {
String operatorStr = getOperator().getSymbol();
return StringUtils.isNotEmpty(operatorStr) && operatorStr.startsWith("is");
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Condition that = (Condition) o;
if (key != null ? !key.equals(that.key) : that.key != null) return false;
return true;
}
@Override
public int hashCode() {
return key != null ? key.hashCode() : 0;
}
@Override
public String toString() {
return "Condition{" +
"searchProperty='" + searchProperty + '\'' +
", operator=" + operator +
", value=" + value +
'}';
}
}
| zhuruiboqq/romantic-factor_baseOnES | common/src/main/java/com/sishuok/es/common/entity/search/filter/Condition.java | Java | apache-2.0 | 5,176 |
<?php
if (!defined('ACTIVE')) die(__FILE__);
$oldname = isset($_REQUEST['oldname'])? $_REQUEST['oldname'] : '';
$oldname = substr($oldname,1);
$newname = isset($_REQUEST['filename'])? $_REQUEST['filename'] : '';
if ($oldname=='') setErrorCode(4);
if (!file_exists($path.'/'.$oldname)) setErrorCode(1);
if ($newname=='') setErrorCode(4);
if (file_exists($path.'/'.$newname)) setErrorCode(2);
if ($errCode==0) @rename($path.'/'.$oldname,$path.'/'.$newname);
$params = array(
'cmd' => 'list',
'sort' => $sort,
'path' => urlencode($path)
);
if ($errCode!=0) $params['error'] = $errCode;
$LOCATION = 'index.php?'.buildQuery($params);
?> | sundoctor/phpcommander | fm/rename.cmd.php | PHP | apache-2.0 | 651 |
package com.hzh.corejava.proxy;
public class SpeakerExample {
public static void main(String[] args) {
AiSpeaker speaker = (AiSpeaker) AuthenticationProxy.newInstance(new XiaoaiAiSpeeker());
speaker.greeting();
}
}
| huangzehai/core-java | src/main/java/com/hzh/corejava/proxy/SpeakerExample.java | Java | apache-2.0 | 240 |
package io.skysail.server.queryfilter.nodes.test;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import org.junit.Ignore;
import org.junit.Test;
import io.skysail.domain.Entity;
import io.skysail.server.domain.jvm.FieldFacet;
import io.skysail.server.domain.jvm.facets.NumberFacet;
import io.skysail.server.domain.jvm.facets.YearFacet;
import io.skysail.server.filter.ExprNode;
import io.skysail.server.filter.FilterVisitor;
import io.skysail.server.filter.Operation;
import io.skysail.server.filter.PreparedStatement;
import io.skysail.server.filter.SqlFilterVisitor;
import io.skysail.server.queryfilter.nodes.LessNode;
import lombok.Data;
public class LessNodeTest {
@Data
public class SomeEntity implements Entity {
private String id, A, B;
}
@Test
public void defaultConstructor_creates_node_with_AND_operation_and_zero_children() {
LessNode lessNode = new LessNode("A", 0);
assertThat(lessNode.getOperation(),is(Operation.LESS));
assertThat(lessNode.isLeaf(),is(true));
}
@Test
public void listConstructor_creates_node_with_AND_operation_and_assigns_the_children_parameter() {
LessNode lessNode = new LessNode("A", 0);
assertThat(lessNode.getOperation(),is(Operation.LESS));
}
@Test
public void lessNode_with_one_children_gets_rendered() {
LessNode lessNode = new LessNode("A", 0);
assertThat(lessNode.asLdapString(),is("(A<0)"));
}
@Test
public void nodes_toString_method_provides_representation() {
LessNode lessNode = new LessNode("A", 0);
assertThat(lessNode.toString(),is("(A<0)"));
}
@Test
public void reduce_removes_the_matching_child() {
LessNode lessNode = new LessNode("A", 0);
Map<String, String> config = new HashMap<>();
config.put("BORDERS", "1");
assertThat(lessNode.reduce("(A<0)", new NumberFacet("A",config), null).asLdapString(),is(""));
}
@Test
public void reduce_does_not_remove_non_matching_child() {
LessNode lessNode = new LessNode("A", 0);
assertThat(lessNode.reduce("b",null, null).asLdapString(),is("(A<0)"));
}
@Test
public void creates_a_simple_preparedStatement() {
LessNode lessNode = new LessNode("A", 0);
Map<String, FieldFacet> facets = new HashMap<>();
PreparedStatement createPreparedStatement = (PreparedStatement) lessNode.accept(new SqlFilterVisitor(facets));
assertThat(createPreparedStatement.getParams().get("A"),is("0"));
assertThat(createPreparedStatement.getSql(), is("A<:A"));
}
@Test
public void creates_a_preparedStatement_with_year_facet() {
LessNode lessNode = new LessNode("A", 0);
Map<String, FieldFacet> facets = new HashMap<>();
Map<String, String> config = new HashMap<>();
facets.put("A", new YearFacet("A", config));
PreparedStatement createPreparedStatement = (PreparedStatement) lessNode.accept(new SqlFilterVisitor(facets));
assertThat(createPreparedStatement.getParams().get("A"),is("0"));
assertThat(createPreparedStatement.getSql(), is("A.format('YYYY')<:A"));
}
// @Test
// public void evaluateEntity() {
// LessNode lessNode = new LessNode("A", 0);
// Map<String, FieldFacet> facets = new HashMap<>();
// Map<String, String> config = new HashMap<>();
// facets.put("A", new YearFacet("A", config));
//
// SomeEntity someEntity = new SomeEntity();
// someEntity.setA(0);
// someEntity.setB("b");
//
// EntityEvaluationFilterVisitor entityEvaluationVisitor = new EntityEvaluationFilterVisitor(someEntity, facets);
// boolean evaluateEntity = lessNode.evaluateEntity(entityEvaluationVisitor);
//
// assertThat(evaluateEntity,is(false));
// }
@Test
@Ignore
public void getSelected() {
LessNode lessNode = new LessNode("A", 0);
FieldFacet facet = new YearFacet("id", Collections.emptyMap());
Iterator<String> iterator = lessNode.getSelected(facet,Collections.emptyMap()).iterator();
assertThat(iterator.next(),is("0"));
}
@Test
public void getKeys() {
LessNode lessNode = new LessNode("A", 0);
assertThat(lessNode.getKeys().size(),is(1));
Iterator<String> iterator = lessNode.getKeys().iterator();
assertThat(iterator.next(),is("A"));
}
@Test
public void accept() {
LessNode lessNode = new LessNode("A", 0);
assertThat(lessNode.accept(new FilterVisitor() {
@Override
public String visit(ExprNode node) {
return ".";
}
}),is("."));
}
}
| evandor/skysail | skysail.server.queryfilter/test/io/skysail/server/queryfilter/nodes/test/LessNodeTest.java | Java | apache-2.0 | 4,873 |
import ch.usi.overseer.OverAgent;
import ch.usi.overseer.OverHpc;
/**
* Overseer.OverAgent sample application.
* This example shows a basic usage of the OverAgent java agent to keep track of all the threads created
* by the JVM. Threads include garbage collectors, finalizers, etc. In order to use OverAgent, make sure to
* append this option to your command-line:
*
* -agentpath:/usr/local/lib/liboverAgent.so
*
* @author Achille Peternier (C) 2011 USI
*/
public class java_agent
{
static public void main(String argv[])
{
// Credits:
System.out.println("Overseer Java Agent test, A. Peternier (C) USI 2011\n");
// Check that -agentpath is working:
if (OverAgent.isRunning())
System.out.println(" OverAgent is running");
else
{
System.out.println(" OverAgent is not running (check your JVM settings)");
return;
}
// Get some info:
System.out.println(" Threads running: " + OverAgent.getNumberOfThreads());
System.out.println();
OverAgent.initEventCallback(new OverAgent.Callback()
{
// Callback invoked at thread creation:
public int onThreadCreation(int pid, String name)
{
System.out.println("[new] " + name + " (" + pid + ")");
return 0;
}
// Callback invoked at thread termination:
public int onThreadTermination(int pid, String name)
{
System.out.println("[delete] " + name + " (" + pid + ")");
return 0;
}});
OverHpc oHpc = OverHpc.getInstance();
int pid = oHpc.getThreadId();
OverAgent.updateStats();
// Waste some time:
double r = 0.0;
for (int d=0; d<10; d++)
{
if (true)
{
for (long c=0; c<100000000; c++)
{
r += r * Math.sqrt(r) * Math.pow(r, 40.0);
}
}
else
{
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
OverAgent.updateStats();
System.out.println(" Thread " + pid + " abs: " + OverAgent.getThreadCpuUsage(pid) + "%, rel: " + OverAgent.getThreadCpuUsageRelative(pid) + "%");
}
// Done:
System.out.println("Application terminated");
}
}
| IvanMamontov/overseer | examples/java_agent.java | Java | apache-2.0 | 2,131 |
package mat.model;
import com.google.gwt.user.client.rpc.IsSerializable;
/**
* The Class SecurityRole.
*/
public class SecurityRole implements IsSerializable {
/** The Constant serialVersionUID. */
private static final long serialVersionUID = 1L;
/** The Constant ADMIN_ROLE. */
public static final String ADMIN_ROLE = "Administrator";
/** The Constant USER_ROLE. */
public static final String USER_ROLE = "User";
/** The Constant SUPER_USER_ROLE. */
public static final String SUPER_USER_ROLE = "Super user";
/** The Constant ADMIN_ROLE_ID. */
public static final String ADMIN_ROLE_ID = "1";
/** The Constant USER_ROLE_ID. */
public static final String USER_ROLE_ID = "2";
/** The Constant SUPER_USER_ROLE_ID. */
public static final String SUPER_USER_ROLE_ID = "3";
/** The id. */
private String id;
/** The description. */
private String description;
/**
* Gets the id.
*
* @return the id
*/
public String getId() {
return id;
}
/**
* Sets the id.
*
* @param id
* the new id
*/
public void setId(String id) {
this.id = id;
}
/**
* Gets the description.
*
* @return the description
*/
public String getDescription() {
return description;
}
/**
* Sets the description.
*
* @param description
* the new description
*/
public void setDescription(String description) {
this.description = description;
}
}
| JaLandry/MeasureAuthoringTool_LatestSprint | mat/src/mat/model/SecurityRole.java | Java | apache-2.0 | 1,430 |
package com.gaojun.appmarket.ui.view;
import android.content.Context;
import android.content.res.TypedArray;
import android.util.AttributeSet;
import android.widget.FrameLayout;
import com.gaojun.appmarket.R;
/**
* Created by Administrator on 2016/6/29.
*/
public class RationLayout extends FrameLayout {
private float ratio;
public RationLayout(Context context) {
super(context);
initView();
}
public RationLayout(Context context, AttributeSet attrs) {
super(context, attrs);
initView();
TypedArray array = context.obtainStyledAttributes(attrs, R.styleable.RationLayout);
int n = array.length();
for (int i = 0; i < n; i++) {
switch (i){
case R.styleable.RationLayout_ratio:
ratio = array.getFloat(R.styleable.RationLayout_ratio,-1);
break;
}
}
array.recycle();
}
public RationLayout(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
initView();
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int width = MeasureSpec.getSize(widthMeasureSpec);
int widthMode = MeasureSpec.getMode(widthMeasureSpec);
int height = MeasureSpec.getSize(heightMeasureSpec);
int heightMode = MeasureSpec.getMode(heightMeasureSpec);
if (widthMode == MeasureSpec.EXACTLY && heightMode != MeasureSpec.EXACTLY &&
ratio>0){
int imageWidth = width - getPaddingLeft() - getPaddingRight();
int imageHeight = (int) (imageWidth/ratio);
height = imageHeight + getPaddingTop() + getPaddingBottom();
heightMeasureSpec = MeasureSpec.makeMeasureSpec(height,MeasureSpec.EXACTLY);
}
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
private void initView() {
}
}
| GaoJunLoveHL/AppMaker | market/src/main/java/com/gaojun/appmarket/ui/view/RationLayout.java | Java | apache-2.0 | 1,962 |
/*
* 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.lightsail.model;
import java.io.Serializable;
import javax.annotation.Generated;
import com.amazonaws.protocol.StructuredPojo;
import com.amazonaws.protocol.ProtocolMarshaller;
/**
* <p>
* Describes a block storage disk mapping.
* </p>
*
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/DiskMap" target="_top">AWS API
* Documentation</a>
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class DiskMap implements Serializable, Cloneable, StructuredPojo {
/**
* <p>
* The original disk path exposed to the instance (for example, <code>/dev/sdh</code>).
* </p>
*/
private String originalDiskPath;
/**
* <p>
* The new disk name (e.g., <code>my-new-disk</code>).
* </p>
*/
private String newDiskName;
/**
* <p>
* The original disk path exposed to the instance (for example, <code>/dev/sdh</code>).
* </p>
*
* @param originalDiskPath
* The original disk path exposed to the instance (for example, <code>/dev/sdh</code>).
*/
public void setOriginalDiskPath(String originalDiskPath) {
this.originalDiskPath = originalDiskPath;
}
/**
* <p>
* The original disk path exposed to the instance (for example, <code>/dev/sdh</code>).
* </p>
*
* @return The original disk path exposed to the instance (for example, <code>/dev/sdh</code>).
*/
public String getOriginalDiskPath() {
return this.originalDiskPath;
}
/**
* <p>
* The original disk path exposed to the instance (for example, <code>/dev/sdh</code>).
* </p>
*
* @param originalDiskPath
* The original disk path exposed to the instance (for example, <code>/dev/sdh</code>).
* @return Returns a reference to this object so that method calls can be chained together.
*/
public DiskMap withOriginalDiskPath(String originalDiskPath) {
setOriginalDiskPath(originalDiskPath);
return this;
}
/**
* <p>
* The new disk name (e.g., <code>my-new-disk</code>).
* </p>
*
* @param newDiskName
* The new disk name (e.g., <code>my-new-disk</code>).
*/
public void setNewDiskName(String newDiskName) {
this.newDiskName = newDiskName;
}
/**
* <p>
* The new disk name (e.g., <code>my-new-disk</code>).
* </p>
*
* @return The new disk name (e.g., <code>my-new-disk</code>).
*/
public String getNewDiskName() {
return this.newDiskName;
}
/**
* <p>
* The new disk name (e.g., <code>my-new-disk</code>).
* </p>
*
* @param newDiskName
* The new disk name (e.g., <code>my-new-disk</code>).
* @return Returns a reference to this object so that method calls can be chained together.
*/
public DiskMap withNewDiskName(String newDiskName) {
setNewDiskName(newDiskName);
return this;
}
/**
* Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
* redacted from this string using a placeholder value.
*
* @return A string representation of this object.
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{");
if (getOriginalDiskPath() != null)
sb.append("OriginalDiskPath: ").append(getOriginalDiskPath()).append(",");
if (getNewDiskName() != null)
sb.append("NewDiskName: ").append(getNewDiskName());
sb.append("}");
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (obj instanceof DiskMap == false)
return false;
DiskMap other = (DiskMap) obj;
if (other.getOriginalDiskPath() == null ^ this.getOriginalDiskPath() == null)
return false;
if (other.getOriginalDiskPath() != null && other.getOriginalDiskPath().equals(this.getOriginalDiskPath()) == false)
return false;
if (other.getNewDiskName() == null ^ this.getNewDiskName() == null)
return false;
if (other.getNewDiskName() != null && other.getNewDiskName().equals(this.getNewDiskName()) == false)
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
hashCode = prime * hashCode + ((getOriginalDiskPath() == null) ? 0 : getOriginalDiskPath().hashCode());
hashCode = prime * hashCode + ((getNewDiskName() == null) ? 0 : getNewDiskName().hashCode());
return hashCode;
}
@Override
public DiskMap clone() {
try {
return (DiskMap) super.clone();
} catch (CloneNotSupportedException e) {
throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e);
}
}
@com.amazonaws.annotation.SdkInternalApi
@Override
public void marshall(ProtocolMarshaller protocolMarshaller) {
com.amazonaws.services.lightsail.model.transform.DiskMapMarshaller.getInstance().marshall(this, protocolMarshaller);
}
}
| aws/aws-sdk-java | aws-java-sdk-lightsail/src/main/java/com/amazonaws/services/lightsail/model/DiskMap.java | Java | apache-2.0 | 6,034 |
namespace v_4_1.Protocol
{
public static class Asci
{
public const byte CR = 13;
public const byte LF = 10;
public const byte T = 84;
public const byte R = 82;
public const byte D = 68;
public const byte H = 72;
public const byte a = 97;
public const byte o = 111;
public const byte L = 76;
public const byte P = 80;
public const byte U = 85;
public const byte S = 83;
}
}
| TeoVincent/TEO-KONKURS | Parser_v_4_1/Protocol/Asci.cs | C# | apache-2.0 | 484 |
/*
* Copyright 2011-2014 Zhaotian Wang <zhaotianzju@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package flex.android.magiccube;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.FloatBuffer;
import java.util.Vector;
import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.opengles.GL10;
import flex.android.magiccube.R;
import flex.android.magiccube.bluetooth.MessageSender;
import flex.android.magiccube.interfaces.OnStateListener;
import flex.android.magiccube.interfaces.OnStepListener;
import flex.android.magiccube.solver.MagicCubeSolver;
import flex.android.magiccube.solver.SolverFactory;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.opengl.GLSurfaceView;
import android.opengl.GLU;
import android.opengl.GLUtils;
import android.opengl.Matrix;
public class MagicCubeRender implements GLSurfaceView.Renderer {
protected Context context;
private int width;
private int height;
//eye-coordinate
private float eyex;
private float eyey;
protected float eyez;
private float angle = 65.f;
protected float ratio = 0.6f;
protected float zfar = 25.5f;
private float bgdist = 25.f;
//background texture
private int[] BgTextureID = new int[1];
private Bitmap[] bitmap = new Bitmap[1];
private FloatBuffer bgtexBuffer; // Texture Coords Buffer for background
private FloatBuffer bgvertexBuffer; // Vertex Buffer for background
protected final int nStep = 9;//nstep for one rotate
protected int volume;
private boolean solved = false; //indicate if the cube has been solved
//background position
//...
//rotation variable
public float rx, ry;
protected Vector<Command> commands;
private Vector<Command> commandsBack; //backward command
private Vector<Command> commandsForward; //forward command
private Vector<Command> commandsAuto; //forward command
protected int[] command;
protected boolean HasCommand;
protected int CommandLoop;
private String CmdStrBefore = "";
private String CmdStrAfter = "";
public static final boolean ROTATE = true;
public static final boolean MOVE = false;
//matrix
public float[] pro_matrix = new float[16];
public int [] view_matrix = new int[4];
public float[] mod_matrix = new float[16];
//minimal valid move distance
private float MinMovedist;
//the cubes!
protected Magiccube magiccube;
private boolean DrawCube;
private boolean Finished = false;
private boolean Resetting = false;
protected OnStateListener stateListener = null;
private MessageSender messageSender = null;
private OnStepListener stepListener = null;
public MagicCubeRender(Context context, int w, int h) {
this.context = context;
this.width = w;
this.height = h;
this.eyex = 0.f;
this.eyey = 0.f;
this.eyez = 20.f;
this.rx = 22.f;
this.ry = -34.f;
this.HasCommand = false;
this.commands = new Vector<Command>(1,1);
this.commandsBack = new Vector<Command>(100, 10);
this.commandsForward = new Vector<Command>(100, 10);
this.commandsAuto = new Vector<Command>(40,5);
//this.Command = new int[3];
magiccube = new Magiccube();
DrawCube = true;
solved = false;
volume = MagiccubePreference.GetPreference(MagiccubePreference.MoveVolume, context);
//SetCommands("L- R2 F- D+ L+ U2 L2 D2 R+ D2 L+ F- D+ L2 D2 R2 B+ L+ U2 R2 U2 F2 R+ D2 U+");
//SetCommands("F- U+ F- D- L- D- F- U- L2 D-");
// SetCommands("U+");
// mediaPlayer = MediaPlayer.create(context, R.raw.move2);
}
public void SetDrawCube(boolean DrawCube)
{
this.DrawCube = DrawCube;
}
private void LoadBgTexture(GL10 gl)
{
//Load texture bitmap
bitmap[0] = BitmapFactory.decodeStream(
context.getResources().openRawResource(R.drawable.mainbg2));
gl.glGenTextures(1, BgTextureID, 0); // Generate texture-ID array for 6 IDs
//Set texture uv
float[] texCoords = {
0.0f, 1.0f, // A. left-bottom
1.0f, 1.0f, // B. right-bottom
0.0f, 0.0f, // C. left-top
1.0f, 0.0f // D. right-top
};
ByteBuffer tbb = ByteBuffer.allocateDirect(texCoords.length * 4 );
tbb.order(ByteOrder.nativeOrder());
bgtexBuffer = tbb.asFloatBuffer();
bgtexBuffer.put(texCoords);
bgtexBuffer.position(0); // Rewind
// Generate OpenGL texture images
gl.glBindTexture(GL10.GL_TEXTURE_2D, BgTextureID[0]);
gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MIN_FILTER,GL10.GL_LINEAR);
gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MAG_FILTER, GL10.GL_LINEAR);
// Build Texture from loaded bitmap for the currently-bind texture ID
GLUtils.texImage2D(GL10.GL_TEXTURE_2D, 0, bitmap[0], 0);
bitmap[0].recycle();
}
protected void DrawBg(GL10 gl)
{
gl.glEnableClientState(GL10.GL_VERTEX_ARRAY);
gl.glEnableClientState(GL10.GL_TEXTURE_COORD_ARRAY);
gl.glVertexPointer(3, GL10.GL_FLOAT, 0, bgvertexBuffer);
gl.glTexCoordPointer(2, GL10.GL_FLOAT, 0, bgtexBuffer);
gl.glEnable(GL10.GL_TEXTURE_2D); // Enable texture (NEW)
gl.glPushMatrix();
gl.glBindTexture(GL10.GL_TEXTURE_2D, this.BgTextureID[0]);
gl.glDrawArrays(GL10.GL_TRIANGLE_STRIP, 0, 4);
gl.glPopMatrix();
gl.glDisableClientState(GL10.GL_VERTEX_ARRAY);
gl.glDisableClientState(GL10.GL_TEXTURE_COORD_ARRAY);
}
@Override
public void onDrawFrame(GL10 gl) {
// Clear color and depth buffers using clear-value set earlier
gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT);
// You OpenGL|ES rendering code here
gl.glLoadIdentity();
GLU.gluLookAt(gl, eyex, eyey, eyez, 0.f, 0.f, 0.f, 0.f, 1.f, 0.f);
Matrix.setIdentityM(mod_matrix, 0);
Matrix.setLookAtM(mod_matrix, 0, eyex, eyey, eyez, 0.f, 0.f, 0.f, 0.f, 1.f, 0.f);
DrawScene(gl);
}
private void SetBackgroundPosition()
{
float halfheight = (float)Math.tan(angle/2.0/180.0*Math.PI)*bgdist*1.f;
float halfwidth = halfheight/this.height*this.width;
float[] vertices = {
-halfwidth, -halfheight, eyez-bgdist, // 0. left-bottom-front
halfwidth, -halfheight, eyez-bgdist, // 1. right-bottom-front
-halfwidth, halfheight,eyez-bgdist, // 2. left-top-front
halfwidth, halfheight, eyez-bgdist, // 3. right-top-front
};
ByteBuffer vbb = ByteBuffer.allocateDirect(12 * 4);
vbb.order(ByteOrder.nativeOrder());
bgvertexBuffer = vbb.asFloatBuffer();
bgvertexBuffer.put(vertices); // Populate
bgvertexBuffer.position(0); // Rewind
}
@Override
public void onSurfaceChanged(GL10 gl, int w, int h) {
//reset the width and the height;
//Log.e("screen", w+" "+h);
if (h == 0) h = 1; // To prevent divide by zero
this.width = w;
this.height = h;
float aspect = (float)w / h;
// Set the viewport (display area) to cover the entire window
gl.glViewport(0, 0, w, h);
this.view_matrix[0] = 0;
this.view_matrix[1] = 0;
this.view_matrix[2] = w;
this.view_matrix[3] = h;
// Setup perspective projection, with aspect ratio matches viewport
gl.glMatrixMode(GL10.GL_PROJECTION); // Select projection matrix
gl.glLoadIdentity(); // Reset projection matrix
// Use perspective projection
angle = 60;
//calculate the angle to adjust the screen resolution
//float idealwidth = Cube.CubeSize*3.f/(Math.abs(this.eyez-Cube.CubeSize*1.5f))*zfar/ratio;
float idealwidth = Cube.CubeSize*3.f/(Math.abs(this.eyez-Cube.CubeSize*1.5f))*zfar/ratio;
float idealheight = idealwidth/(float)w*(float)h;
angle = (float)(Math.atan2(idealheight/2.f, Math.abs(zfar))*2.f*180.f/Math.PI);
SetBackgroundPosition();
GLU.gluPerspective(gl, angle, aspect, 0.1f, zfar);
MinMovedist = w*ratio/3.f*0.15f;
float r = (float)w/(float)h;
float size = (float)(0.1*Math.tan(angle/2.0/180.0*Math.PI));
Matrix.setIdentityM(pro_matrix, 0);
Matrix.frustumM(pro_matrix, 0, -size*r, size*r, -size , size, 0.1f, zfar);
gl.glMatrixMode(GL10.GL_MODELVIEW); // Select model-view matrix
gl.glLoadIdentity(); // Reset
/* // You OpenGL|ES display re-sizing code here
gl.glBlendFunc(GL10.GL_SRC_ALPHA, GL10.GL_ONE);
//float []lightparam = {0.6f, 0.2f, 0.2f, 0.6f, 0.2f, 0.2f, 0, 0, 10};
float []lightparam = {1f, 1f, 1f, 3f, 1f, 1f, 0, 0, 5};
gl.glEnable(GL10.GL_LIGHTING);
// ���û�����
gl.glLightfv(GL10.GL_LIGHT0, GL10.GL_AMBIENT, lightparam, 0);
// ���������
gl.glLightfv(GL10.GL_LIGHT0, GL10.GL_DIFFUSE, lightparam, 3);
// ���þ��淴��
gl.glLightfv(GL10.GL_LIGHT0, GL10.GL_SPECULAR, lightparam, 3);
// ���ù�Դλ��
gl.glLightfv(GL10.GL_LIGHT0, GL10.GL_POSITION, lightparam, 6);
// ������Դ
gl.glEnable(GL10.GL_LIGHT0);
*/
// �������
//gl.glEnable(GL10.GL_BLEND);
if( this.stateListener != null )
{
stateListener.OnStateChanged(OnStateListener.LOADED);
}
}
@Override
public void onSurfaceCreated(GL10 gl, EGLConfig arg1) {
gl.glClearColor(0.0f, 0.0f, 0.0f, 1.0f); // Set color's clear-value to black
gl.glClearDepthf(1.0f); // Set depth's clear-value to farthest
gl.glEnable(GL10.GL_DEPTH_TEST); // Enables depth-buffer for hidden surface removal
gl.glDepthFunc(GL10.GL_LEQUAL); // The type of depth testing to do
gl.glHint(GL10.GL_PERSPECTIVE_CORRECTION_HINT, GL10.GL_NICEST); // nice perspective view
gl.glShadeModel(GL10.GL_SMOOTH); // Enable smooth shading of color
gl.glDisable(GL10.GL_DITHER); // Disable dithering for better performance
// You OpenGL|ES initialization code here
//Initial the cubes
magiccube.LoadTexture(gl, context);
//this.MessUp(50);
LoadBgTexture(gl);
}
public void SetMessageSender(MessageSender messageSender)
{
this.messageSender = messageSender;
}
protected void DrawScene(GL10 gl)
{
this.DrawBg(gl);
if( !DrawCube)
{
return;
}
if(Resetting)
{
//Resetting = false;
//reset();
}
if(HasCommand)
{
Command command = commands.firstElement();
if( CommandLoop == 0 && messageSender != null)
{
messageSender.SendMessage(command.toString());
}
int nsteps = command.N*this.nStep; //rotate nsteps
if(CommandLoop%nStep == 0 && CommandLoop != nsteps)
{
MusicPlayThread musicPlayThread = new MusicPlayThread(context, R.raw.move2, volume);
musicPlayThread.start();
}
if(command.Type == Command.ROTATE_ROW)
{
magiccube.RotateRow(command.RowID, command.Direction, 90.f/nStep,CommandLoop%nStep==nStep-1);
}
else if(command.Type == Command.ROTATE_COL)
{
magiccube.RotateCol(command.RowID, command.Direction, 90.f/nStep,CommandLoop%nStep==nStep-1);
}
else
{
magiccube.RotateFace(command.RowID, command.Direction, 90.f/nStep,CommandLoop%nStep==nStep-1);
}
CommandLoop++;
if(CommandLoop==nsteps)
{
CommandLoop = 0;
if(commands.size() > 1)
{
//Log.e("full", "full"+commands.size());
}
this.CmdStrAfter += command.toString() + " ";
commands.removeElementAt(0);
//Log.e("e", commands.size()+"");
if( commands.size() <= 0)
{
HasCommand = false;
}
if( stepListener != null)
{
stepListener.AddStep();
}
//this.ReportFaces();
//Log.e("state", this.GetState());
if(Finished && !this.IsComplete())
{
Finished = false;
if(this.stateListener != null)
{
stateListener.OnStateNotify(OnStateListener.CANAUTOSOLVE);
}
}
}
if(this.stateListener != null && this.IsComplete())
{
if( !Finished )
{
Finished = true;
stateListener.OnStateChanged(OnStateListener.FINISH);
stateListener.OnStateNotify(OnStateListener.CANNOTAUTOSOLVE);
}
}
}
DrawCubes(gl);
}
protected void DrawCubes(GL10 gl)
{
gl.glPushMatrix();
gl.glRotatef(rx, 1, 0, 0); //rotate
gl.glRotatef(ry, 0, 1, 0);
// Log.e("rxry", rx + " " + ry);
if(this.HasCommand)
{
magiccube.Draw(gl);
}
else
{
magiccube.DrawSimple(gl);
}
gl.glPopMatrix();
}
public void SetOnStateListener(OnStateListener stateListener)
{
this.stateListener = stateListener;
}
public void SetOnStepListnener(OnStepListener stepListener)
{
this.stepListener = stepListener;
}
public boolean GetPos(float[] point, int[] Pos)
{
//deal with the touch-point is out of the cube
if( true)
{
//return false;
}
if( rx > 0 && rx < 90.f)
{
}
return ROTATE;
}
public String SetCommand(Command command)
{
HasCommand = true;
this.commands.add(command);
this.commandsForward.clear();
this.commandsBack.add(command.Reverse());
if(this.stateListener != null)
{
stateListener.OnStateNotify(OnStateListener.CANMOVEBACK);
stateListener.OnStateNotify(OnStateListener.CANNOTMOVEFORWARD);
}
return command.CmdToCmdStr();
}
public void SetForwardCommand(String CmdStr)
{
//Log.e("cmdstr", CmdStr);
this.commandsForward = Reverse(Command.CmdStrsToCmd(CmdStr));
}
public String SetCommand(int ColOrRowOrFace, int ID, int Direction)
{
solved = false;
return SetCommand(new Command(ColOrRowOrFace, ID, Direction));
}
public boolean IsSolved()
{
return solved;
}
public String MoveBack()
{
if( this.commandsBack.size() <= 0)
{
return null;
}
Command command = commandsBack.lastElement();
HasCommand = true;
this.commands.add(command);
this.commandsBack.remove(this.commandsBack.size()-1);
if(this.commandsBack.size() <= 0 && stateListener != null)
{
stateListener.OnStateNotify(OnStateListener.CANNOTMOVEBACK);
}
if( solved)
{
this.commandsAuto.add(command.Reverse());
}
else
{
this.commandsForward.add(command.Reverse());
if(stateListener != null)
{
stateListener.OnStateNotify(OnStateListener.CANMOVEFORWARD);
}
}
return command.CmdToCmdStr();
}
public String MoveForward()
{
if( this.commandsForward.size() <= 0)
{
return null;
}
Command command = commandsForward.lastElement();
HasCommand = true;
this.commands.add(command);
this.commandsBack.add(command.Reverse());
this.commandsForward.remove(commandsForward.size()-1);
if( this.commandsForward.size() <= 0 && stateListener != null)
{
this.stateListener.OnStateNotify(OnStateListener.CANNOTMOVEFORWARD);
}
if( this.stateListener != null)
{
this.stateListener.OnStateNotify(OnStateListener.CANMOVEBACK);
}
return command.CmdToCmdStr();
}
public int MoveForward2()
{
if( this.commandsForward.size() <= 0)
{
return 0;
}
int n = commandsForward.size();
HasCommand = true;
this.commands.addAll(Reverse(commandsForward));
for( int i=commandsForward.size()-1; i>=0; i--)
{
this.commandsBack.add(commandsForward.get(i).Reverse());
}
this.commandsForward.clear();
if( this.commandsForward.size() <= 0 && stateListener != null)
{
this.stateListener.OnStateNotify(OnStateListener.CANNOTMOVEFORWARD);
}
if( this.stateListener != null)
{
this.stateListener.OnStateNotify(OnStateListener.CANMOVEBACK);
}
return n;
}
public int IsInCubeArea(float []Win)
{
int[] HitedFaceIndice = new int[6];
int HitNumber = 0;
for(int i=0; i<6; i++)
{
if(IsInQuad3D(magiccube.faces[i], Win))
{
HitedFaceIndice[HitNumber] = i;
HitNumber++;
}
}
if( HitNumber <=0)
{
return -1;
}
else
{
if( HitNumber == 1)
{
return HitedFaceIndice[0];
}
else //if more than one hitted, then choose the max z-value face as the hitted one
{
float maxzvalue = -1000.f;
int maxzindex = -1;
for( int i = 0; i< HitNumber; i++)
{
float thisz = this.GetCenterZ(magiccube.faces[HitedFaceIndice[i]]);
if( thisz > maxzvalue)
{
maxzvalue = thisz;
maxzindex = HitedFaceIndice[i];
}
}
return maxzindex;
}
}
}
private float GetLength2D(float []P1, float []P2)
{
float dx = P1[0]-P2[0];
float dy = P1[1]-P2[1];
return (float)Math.sqrt(dx*dx + dy*dy);
}
private boolean IsInQuad3D(Face f, float []Win)
{
return IsInQuad3D(f.P1, f.P2, f.P3, f.P4, Win);
}
private boolean IsInQuad3D(float []Point1, float []Point2, float []Point3, float Point4[], float []Win)
{
float[] Win1 = new float[2];
float[] Win2 = new float[2];
float[] Win3 = new float[2];
float[] Win4 = new float[2];
Project(Point1, Win1);
Project(Point2, Win2);
Project(Point3, Win3);
Project(Point4, Win4);
/* Log.e("P1", Win1[0] + " " + Win1[1]);
Log.e("P2", Win2[0] + " " + Win2[1]);
Log.e("P3", Win3[0] + " " + Win3[1]);
Log.e("P4", Win4[0] + " " + Win4[1]);*/
float []WinXY = new float[2];
WinXY[0] = Win[0];
WinXY[1] = this.view_matrix[3] - Win[1];
//Log.e("WinXY", WinXY[0] + " " + WinXY[1]);
return IsInQuad2D(Win1, Win2, Win3, Win4, WinXY);
}
private boolean IsInQuad2D(float []Point1, float []Point2, float []Point3, float Point4[], float []Win)
{
float angle = 0.f;
final float ZERO = 0.0001f;
angle += GetAngle(Win, Point1, Point2);
//Log.e("angle" , angle + " ");
angle += GetAngle(Win, Point2, Point3);
//Log.e("angle" , angle + " ");
angle += GetAngle(Win, Point3, Point4);
//Log.e("angle" , angle + " ");
angle += GetAngle(Win, Point4, Point1);
//Log.e("angle" , angle + " ");
if( Math.abs(angle-Math.PI*2.f) <= ZERO )
{
return true;
}
return false;
}
public String CalcCommand(float [] From, float [] To, int faceindex)
{
float [] from = new float[2];
float [] to = new float[2];
float angle, angleVertical, angleHorizon;
from[0] = From[0];
from[1] = this.view_matrix[3] - From[1];
to[0] = To[0];
to[1] = this.view_matrix[3] - To[1];
angle = GetAngle(from, to);//(float)Math.atan((to[1]-from[1])/(to[0]-from[0]))/(float)Math.PI*180.f;
//calc horizon angle
float ObjFrom[] = new float[3];
float ObjTo[] = new float[3];
float WinFrom[] = new float[2];
float WinTo[] = new float[2];
for(int i=0; i<3; i++)
{
ObjFrom[i] = (magiccube.faces[faceindex].P1[i] + magiccube.faces[faceindex].P4[i])/2.f;
ObjTo[i] = (magiccube.faces[faceindex].P2[i] + magiccube.faces[faceindex].P3[i])/2.f;
}
//Log.e("obj", ObjFrom[0]+" "+ObjFrom[1]+" "+ObjFrom[2]);
this.Project(ObjFrom, WinFrom);
this.Project(ObjTo, WinTo);
angleHorizon = GetAngle(WinFrom, WinTo);//(float)Math.atan((WinTo[1]-WinFrom[1])/(WinTo[0]-WinFrom[0]))/(float)Math.PI*180.f;
//calc vertical angle
for(int i=0; i<3; i++)
{
ObjFrom[i] = (magiccube.faces[faceindex].P1[i] + magiccube.faces[faceindex].P2[i])/2.f;
ObjTo[i] = (magiccube.faces[faceindex].P3[i] + magiccube.faces[faceindex].P4[i])/2.f;
}
this.Project(ObjFrom, WinFrom);
this.Project(ObjTo, WinTo);
angleVertical = GetAngle(WinFrom, WinTo);//(float)Math.atan((WinTo[1]-WinFrom[1])/(WinTo[0]-WinFrom[0]))/(float)Math.PI*180.f;
//Log.e("angle", angle +" " + angleHorizon + " " + angleVertical);
float dangle = DeltaAngle(angleHorizon, angleVertical);
float threshold = Math.min(dangle/2.f, 90.f-dangle/2.f)*0.75f; //this...........
if( DeltaAngle(angle, angleHorizon) < threshold || DeltaAngle(angle, (angleHorizon+180.f)%360.f) < threshold) //the direction
{
if(this.IsInQuad3D(magiccube.faces[faceindex].GetHorizonSubFace(0), From))
{
if( faceindex == Face.FRONT)
{
if(DeltaAngle(angle, angleHorizon) < threshold)
{
return this.SetCommand(Command.ROTATE_ROW, 0, Cube.ClockWise);
}
else
{
return this.SetCommand(Command.ROTATE_ROW, 0, Cube.CounterClockWise);
}
}
else if(faceindex == Face.BACK)
{
if(DeltaAngle(angle, angleHorizon) < threshold)
{
return this.SetCommand(Command.ROTATE_ROW, 0, Cube.ClockWise);
}
else
{
return this.SetCommand(Command.ROTATE_ROW, 0, Cube.CounterClockWise);
}
}
else if(faceindex == Face.LEFT)
{
if(DeltaAngle(angle, angleHorizon) < threshold)
{
return this.SetCommand(Command.ROTATE_ROW, 0, Cube.ClockWise);
}
else
{
return this.SetCommand(Command.ROTATE_ROW, 0, Cube.CounterClockWise);
}
}
else if(faceindex == Face.RIGHT)
{
if(DeltaAngle(angle, angleHorizon) < threshold)
{
return this.SetCommand(Command.ROTATE_ROW, 0, Cube.ClockWise);
}
else
{
return this.SetCommand(Command.ROTATE_ROW, 0, Cube.CounterClockWise);
}
}
else if(faceindex == Face.TOP)
{
if(DeltaAngle(angle, angleHorizon) < threshold)
{
return this.SetCommand(Command.ROTATE_FACE, 2, Cube.CounterClockWise);
}
else
{
return this.SetCommand(Command.ROTATE_FACE, 2, Cube.ClockWise);
}
}
else if(faceindex == Face.BOTTOM)
{
if(DeltaAngle(angle, angleHorizon) < threshold)
{
return this.SetCommand(Command.ROTATE_FACE, 0, Cube.ClockWise);
}
else
{
return this.SetCommand(Command.ROTATE_FACE, 0, Cube.CounterClockWise);
}
}
}
else if(this.IsInQuad3D(magiccube.faces[faceindex].GetHorizonSubFace(1), From))
{
if( faceindex == Face.FRONT)
{
if(DeltaAngle(angle, angleHorizon) < threshold)
{
return this.SetCommand(Command.ROTATE_ROW, 1, Cube.ClockWise);
}
else
{
return this.SetCommand(Command.ROTATE_ROW, 1, Cube.CounterClockWise);
}
}
else if( faceindex == Face.BACK)
{
if(DeltaAngle(angle, angleHorizon) < threshold)
{
return this.SetCommand(Command.ROTATE_ROW, 1, Cube.ClockWise);
}
else
{
return this.SetCommand(Command.ROTATE_ROW, 1, Cube.CounterClockWise);
}
}
else if(faceindex == Face.LEFT)
{
if(DeltaAngle(angle, angleHorizon) < threshold)
{
return this.SetCommand(Command.ROTATE_ROW, 1, Cube.ClockWise);
}
else
{
return this.SetCommand(Command.ROTATE_ROW, 1, Cube.CounterClockWise);
}
}
else if(faceindex == Face.RIGHT)
{
if(DeltaAngle(angle, angleHorizon) < threshold)
{
return this.SetCommand(Command.ROTATE_ROW, 1, Cube.ClockWise);
}
else
{
return this.SetCommand(Command.ROTATE_ROW, 1, Cube.CounterClockWise);
}
}
else if(faceindex == Face.TOP)
{
if(DeltaAngle(angle, angleHorizon) < threshold)
{
return this.SetCommand(Command.ROTATE_FACE, 1, Cube.CounterClockWise);
}
else
{
return this.SetCommand(Command.ROTATE_FACE, 1, Cube.ClockWise);
}
}
else if(faceindex == Face.BOTTOM)
{
if(DeltaAngle(angle, angleHorizon) < threshold)
{
return this.SetCommand(Command.ROTATE_FACE, 1, Cube.ClockWise);
}
else
{
return this.SetCommand(Command.ROTATE_FACE, 1, Cube.CounterClockWise);
}
}
}
else if(this.IsInQuad3D(magiccube.faces[faceindex].GetHorizonSubFace(2), From))
{
if( faceindex == Face.FRONT)
{
if(DeltaAngle(angle, angleHorizon) < threshold)
{
return this.SetCommand(Command.ROTATE_ROW, 2, Cube.ClockWise);
}
else
{
return this.SetCommand(Command.ROTATE_ROW, 2, Cube.CounterClockWise);
}
}
else if( faceindex == Face.BACK)
{
if(DeltaAngle(angle, angleHorizon) < threshold)
{
return this.SetCommand(Command.ROTATE_ROW, 2, Cube.ClockWise);
}
else
{
return this.SetCommand(Command.ROTATE_ROW, 2, Cube.CounterClockWise);
}
}
else if(faceindex == Face.LEFT)
{
if(DeltaAngle(angle, angleHorizon) < threshold)
{
return this.SetCommand(Command.ROTATE_ROW, 2, Cube.ClockWise);
}
else
{
return this.SetCommand(Command.ROTATE_ROW, 2, Cube.CounterClockWise);
}
}
else if(faceindex == Face.RIGHT)
{
if(DeltaAngle(angle, angleHorizon) < threshold)
{
return this.SetCommand(Command.ROTATE_ROW, 2, Cube.ClockWise);
}
else
{
return this.SetCommand(Command.ROTATE_ROW, 2, Cube.CounterClockWise);
}
}
else if(faceindex == Face.TOP)
{
if(DeltaAngle(angle, angleHorizon) < threshold)
{
return this.SetCommand(Command.ROTATE_FACE, 0, Cube.CounterClockWise);
}
else
{
return this.SetCommand(Command.ROTATE_FACE, 0, Cube.ClockWise);
}
}
else if(faceindex == Face.BOTTOM)
{
if(DeltaAngle(angle, angleHorizon) < threshold)
{
return this.SetCommand(Command.ROTATE_FACE, 2, Cube.ClockWise);
}
else
{
return this.SetCommand(Command.ROTATE_FACE, 2, Cube.CounterClockWise);
}
}
}
}
else if( DeltaAngle(angle, angleVertical) < threshold || DeltaAngle(angle, (angleVertical+180.f)%360.f) < threshold)
{
if(this.IsInQuad3D(magiccube.faces[faceindex].GetVerticalSubFace(0), From))
{
if( faceindex == Face.FRONT)
{
if(DeltaAngle(angle, angleVertical) < threshold)
{
return this.SetCommand(Command.ROTATE_COL, 0, Cube.CounterClockWise);
}
else
{
return this.SetCommand(Command.ROTATE_COL, 0, Cube.ClockWise);
}
}
else if(faceindex == Face.BACK)
{
if(DeltaAngle(angle, angleVertical) < threshold)
{
return this.SetCommand(Command.ROTATE_COL, 2, Cube.ClockWise);
}
else
{
return this.SetCommand(Command.ROTATE_COL, 2, Cube.CounterClockWise);
}
}
else if(faceindex == Face.LEFT)
{
if(DeltaAngle(angle, angleVertical) < threshold)
{
return this.SetCommand(Command.ROTATE_FACE, 2, Cube.CounterClockWise);
}
else
{
return this.SetCommand(Command.ROTATE_FACE, 2, Cube.ClockWise);
}
}
else if(faceindex == Face.RIGHT)
{
if(DeltaAngle(angle, angleVertical) < threshold)
{
return this.SetCommand(Command.ROTATE_FACE, 0, Cube.ClockWise);
}
else
{
return this.SetCommand(Command.ROTATE_FACE, 0, Cube.CounterClockWise);
}
}
else if(faceindex == Face.TOP)
{
if(DeltaAngle(angle, angleVertical) < threshold)
{
return this.SetCommand(Command.ROTATE_COL, 0, Cube.CounterClockWise);
}
else
{
return this.SetCommand(Command.ROTATE_COL, 0, Cube.ClockWise);
}
}
else if(faceindex == Face.BOTTOM)
{
if(DeltaAngle(angle, angleVertical) < threshold)
{
return this.SetCommand(Command.ROTATE_COL, 0, Cube.CounterClockWise);
}
else
{
return this.SetCommand(Command.ROTATE_COL, 0, Cube.ClockWise);
}
}
}
else if(this.IsInQuad3D(magiccube.faces[faceindex].GetVerticalSubFace(1), From))
{
if( faceindex == Face.FRONT)
{
if(DeltaAngle(angle, angleVertical) < threshold)
{
return this.SetCommand(Command.ROTATE_COL, 1, Cube.CounterClockWise);
}
else
{
return this.SetCommand(Command.ROTATE_COL, 1, Cube.ClockWise);
}
}
else if(faceindex == Face.BACK)
{
if(DeltaAngle(angle, angleVertical) < threshold)
{
return this.SetCommand(Command.ROTATE_COL, 1, Cube.ClockWise);
}
else
{
return this.SetCommand(Command.ROTATE_COL, 1, Cube.CounterClockWise);
}
}
else if(faceindex == Face.LEFT)
{
if(DeltaAngle(angle, angleVertical) < threshold)
{
return this.SetCommand(Command.ROTATE_FACE, 1, Cube.CounterClockWise);
}
else
{
return this.SetCommand(Command.ROTATE_FACE, 1, Cube.ClockWise);
}
}
else if(faceindex == Face.RIGHT)
{
if(DeltaAngle(angle, angleVertical) < threshold)
{
return this.SetCommand(Command.ROTATE_FACE, 1, Cube.ClockWise);
}
else
{
return this.SetCommand(Command.ROTATE_FACE, 1, Cube.CounterClockWise);
}
}
else if(faceindex == Face.TOP)
{
if(DeltaAngle(angle, angleVertical) < threshold)
{
return this.SetCommand(Command.ROTATE_COL, 1, Cube.CounterClockWise);
}
else
{
return this.SetCommand(Command.ROTATE_COL, 1, Cube.ClockWise);
}
}
else if(faceindex == Face.BOTTOM)
{
if(DeltaAngle(angle, angleVertical) < threshold)
{
return this.SetCommand(Command.ROTATE_COL, 1, Cube.CounterClockWise);
}
else
{
return this.SetCommand(Command.ROTATE_COL, 1, Cube.ClockWise);
}
}
}
else if(this.IsInQuad3D(magiccube.faces[faceindex].GetVerticalSubFace(2), From))
{
if( faceindex == Face.FRONT)
{
if(DeltaAngle(angle, angleVertical) < threshold)
{
return this.SetCommand(Command.ROTATE_COL, 2, Cube.CounterClockWise);
}
else
{
return this.SetCommand(Command.ROTATE_COL, 2, Cube.ClockWise);
}
}
else if(faceindex == Face.BACK)
{
if(DeltaAngle(angle, angleVertical) < threshold)
{
return this.SetCommand(Command.ROTATE_COL, 0, Cube.ClockWise);
}
else
{
return this.SetCommand(Command.ROTATE_COL, 0, Cube.CounterClockWise);
}
}
else if(faceindex == Face.LEFT)
{
if(DeltaAngle(angle, angleVertical) < threshold)
{
return this.SetCommand(Command.ROTATE_FACE, 0, Cube.CounterClockWise);
}
else
{
return this.SetCommand(Command.ROTATE_FACE, 0, Cube.ClockWise);
}
}
else if(faceindex == Face.RIGHT)
{
if(DeltaAngle(angle, angleVertical) < threshold)
{
return this.SetCommand(Command.ROTATE_FACE, 2, Cube.ClockWise);
}
else
{
return this.SetCommand(Command.ROTATE_FACE, 2, Cube.CounterClockWise);
}
}
else if(faceindex == Face.TOP)
{
if(DeltaAngle(angle, angleVertical) < threshold)
{
return this.SetCommand(Command.ROTATE_COL, 2, Cube.CounterClockWise);
}
else
{
return this.SetCommand(Command.ROTATE_COL, 2, Cube.ClockWise);
}
}
else if(faceindex == Face.BOTTOM)
{
if(DeltaAngle(angle, angleVertical) < threshold)
{
return this.SetCommand(Command.ROTATE_COL, 2, Cube.CounterClockWise);
}
else
{
return this.SetCommand(Command.ROTATE_COL, 2, Cube.ClockWise);
}
}
}
}
return null;
}
private float GetAngle(float[] From, float[] To)
{
float angle = (float)Math.atan((To[1]-From[1])/(To[0]-From[0]))/(float)Math.PI*180.f;
float dy = To[1]-From[1];
float dx = To[0]-From[0];
if( dy >= 0.f && dx > 0.f)
{
angle = (float)Math.atan(dy/dx)/(float)Math.PI*180.f;
}
else if( dx == 0.f)
{
if( dy > 0.f)
{
angle = 90.f;
}
else
{
angle = 270.f;
}
}
else if( dy >= 0.f && dx < 0.f)
{
angle = 180.f + (float)Math.atan(dy/dx)/(float)Math.PI*180.f;
}
else if( dy < 0.f && dx < 0.f)
{
angle = 180.f + (float)Math.atan(dy/dx)/(float)Math.PI*180.f;
}
else if(dy <0.f && dx > 0.f)
{
angle = 360.f + (float)Math.atan(dy/dx)/(float)Math.PI*180.f;
}
return angle;
}
private float DeltaAngle(float angle1, float angle2)
{
float a1 = Math.max(angle1, angle2);
float a2 = Math.min(angle1, angle2);
float delta = a1 - a2;
if( delta >= 180.f )
{
delta = 360.f - delta;
}
return delta;
}
private float GetCenterZ(Face f)
{
float zvalue = 0.f;
float [] matrix1 = new float[16];
float [] matrix2 = new float[16];
float [] matrix = new float[16];
Matrix.setIdentityM(matrix1, 0);
Matrix.setIdentityM(matrix2, 0);
Matrix.setIdentityM(matrix, 0);
Matrix.rotateM(matrix1, 0, rx, 1, 0, 0);
Matrix.rotateM(matrix2, 0, ry, 0, 1, 0);
Matrix.multiplyMM(matrix, 0, matrix1, 0, matrix2, 0);
float xyz[] = new float[3];
xyz[0] = f.P1[0];
xyz[1] = f.P1[1];
xyz[2] = f.P1[2];
Transform(matrix, xyz);
zvalue += xyz[2];
xyz[0] = f.P2[0];
xyz[1] = f.P2[1];
xyz[2] = f.P2[2];
Transform(matrix, xyz);
zvalue += xyz[2];
xyz[0] = f.P3[0];
xyz[1] = f.P3[1];
xyz[2] = f.P3[2];
Transform(matrix, xyz);
zvalue += xyz[2];
xyz[0] = f.P4[0];
xyz[1] = f.P4[1];
xyz[2] = f.P4[2];
Transform(matrix, xyz);
zvalue += xyz[2];
return zvalue/4.f;
}
private float GetAngle(float []Point0, float []Point1, float[]Point2)
{
float cos_value = (Point2[0]-Point0[0])*(Point1[0]-Point0[0]) + (Point1[1]-Point0[1])*(Point2[1]-Point0[1]);
cos_value /= Math.sqrt((Point2[0]-Point0[0])*(Point2[0]-Point0[0]) + (Point2[1]-Point0[1])*(Point2[1]-Point0[1]))
* Math.sqrt((Point1[0]-Point0[0])*(Point1[0]-Point0[0]) + (Point1[1]-Point0[1])*(Point1[1]-Point0[1]));
return (float)Math.acos(cos_value);
}
private void Project(float[] ObjXYZ, float [] WinXY)
{
float [] matrix1 = new float[16];
float [] matrix2 = new float[16];
float [] matrix = new float[16];
Matrix.setIdentityM(matrix1, 0);
Matrix.setIdentityM(matrix2, 0);
Matrix.setIdentityM(matrix, 0);
Matrix.rotateM(matrix1, 0, rx, 1, 0, 0);
Matrix.rotateM(matrix2, 0, ry, 0, 1, 0);
Matrix.multiplyMM(matrix, 0, matrix1, 0, matrix2, 0);
float xyz[] = new float[3];
xyz[0] = ObjXYZ[0];
xyz[1] = ObjXYZ[1];
xyz[2] = ObjXYZ[2];
Transform(matrix, xyz);
//Log.e("xyz", xyz[0] + " " + xyz[1] + " " + xyz[2]);
float []Win = new float[3];
GLU.gluProject(xyz[0], xyz[1], xyz[2], mod_matrix, 0, pro_matrix, 0, view_matrix, 0, Win, 0);
WinXY[0] = Win[0];
WinXY[1] = Win[1];
}
private void Transform(float[]matrix, float[]Point)
{
float w = 1.f;
float x, y, z, ww;
x = matrix[0]*Point[0] + matrix[4]*Point[1] + matrix[8]*Point[2] + matrix[12]*w;
y = matrix[1]*Point[0] + matrix[5]*Point[1] + matrix[9]*Point[2] + matrix[13]*w;
z = matrix[2]*Point[0] + matrix[6]*Point[1] + matrix[10]*Point[2] + matrix[14]*w;
ww = matrix[3]*Point[0] + matrix[7]*Point[1] + matrix[11]*Point[2] + matrix[15]*w;
Point[0] = x/ww;
Point[1] = y/ww;
Point[2] = z/ww;
}
public boolean IsComplete()
{
boolean r = true;
for( int i=0; i<6; i++)
{
r = r&&magiccube.faces[i].IsSameColor();
}
return magiccube.IsComplete();
}
public String MessUp(int nStep)
{
this.solved = false;
this.Finished = false;
if( this.stateListener != null)
{
stateListener.OnStateNotify(OnStateListener.CANAUTOSOLVE);
}
return magiccube.MessUp(nStep);
}
public void MessUp(String cmdstr)
{
this.solved = false;
magiccube.MessUp(cmdstr);
this.Finished = false;
if( this.stateListener != null)
{
stateListener.OnStateNotify(OnStateListener.CANAUTOSOLVE);
}
}
public boolean IsMoveValid(float[]From, float []To)
{
return this.GetLength2D(From, To) > this.MinMovedist;
}
public void SetCommands(String cmdStr)
{
this.commands = Command.CmdStrsToCmd(cmdStr);
this.HasCommand = true;
}
public String SetCommand(String cmdStr)
{
return SetCommand(Command.CmdStrToCmd(cmdStr));
}
public void AutoSolve(String SolverName)
{
if( !solved)
{
MagicCubeSolver solver = SolverFactory.CreateSolver(SolverName);
if(solver == null)
{
return;
}
//Log.e("state", this.GetState());
String SolveCmd = solver.AutoSolve(magiccube.GetState());
//Log.e("solve", SolveCmd);
this.commands.clear();
this.commandsBack.clear();
this.commandsForward.clear();
if( this.stateListener != null)
{
this.stateListener.OnStateNotify(OnStateListener.CANNOTMOVEBACK);
this.stateListener.OnStateNotify(OnStateListener.CANNOTMOVEFORWARD);
}
this.commandsAuto = Reverse(Command.CmdStrsToCmd(SolveCmd));
this.solved = true;
}
else if(commandsAuto.size() > 0)
{
Command command = commandsAuto.lastElement();
HasCommand = true;
this.commands.add(command);
this.commandsBack.add(command.Reverse());
this.commandsAuto.remove(commandsAuto.size()-1);
if( this.stateListener != null)
{
this.stateListener.OnStateNotify(OnStateListener.CANMOVEBACK);
}
}
}
public void AutoSolve2(String SolverName)
{
if( !solved)
{
MagicCubeSolver solver = SolverFactory.CreateSolver(SolverName);
if(solver == null)
{
return;
}
//Log.e("state", this.GetState());
String SolveCmd = solver.AutoSolve(magiccube.GetState());
//Log.e("solve", SolveCmd);
this.commands.clear();
this.commandsBack.clear();
this.commandsForward.clear();
this.commands = Command.CmdStrsToCmd(SolveCmd);
for( int i=0; i<commands.size(); i++)
{
commandsBack.add(commands.get(i).Reverse());
}
this.HasCommand = true;
this.solved = true;
}
else
{
commands.addAll(Reverse(commandsAuto));
for( int i=commandsAuto.size()-1; i>=0; i--)
{
commandsBack.add(commandsAuto.get(i).Reverse());
}
commandsAuto.clear();
HasCommand = true;
}
}
public void AutoSolve3(String SolverName)
{
if( !solved)
{
MagicCubeSolver solver = SolverFactory.CreateSolver(SolverName);
if(solver == null)
{
return;
}
//Log.e("state", this.GetState());
String SolveCmd = solver.AutoSolve(magiccube.GetState());
//Log.e("solve", SolveCmd);
this.commands.clear();
this.commandsBack.clear();
this.commandsForward.clear();
this.commands = Command.CmdStrsToCmd(SolveCmd);
commands.remove(commands.size()-1);
commands.remove(commands.size()-1);
for( int i=0; i<commands.size(); i++)
{
commandsBack.add(commands.get(i).Reverse());
}
this.HasCommand = true;
this.solved = true;
}
else
{
commands.addAll(Reverse(commandsAuto));
for( int i=commandsAuto.size()-1; i>=0; i--)
{
commandsBack.add(commandsAuto.get(i).Reverse());
}
commandsAuto.clear();
HasCommand = true;
}
}
private Vector<Command> Reverse(Vector<Command> v)
{
Vector<Command> v2 = new Vector<Command>(v.size());
for(int i=v.size()-1; i>=0; i--)
{
v2.add(v.elementAt(i));
}
return v2;
}
public void Reset()
{
Resetting = true;
reset();
}
private void reset()
{
this.rx = 22.f;
this.ry = -34.f;
this.HasCommand = false;
Finished = false;
this.CommandLoop = 0;
this.commands.clear();
this.commandsBack.clear();
this.commandsForward.clear();
this.CmdStrAfter = "";
this.CmdStrBefore = "";
magiccube.Reset();
if( this.stateListener != null)
{
this.stateListener.OnStateNotify(OnStateListener.CANNOTMOVEBACK);
this.stateListener.OnStateNotify(OnStateListener.CANNOTMOVEFORWARD);
this.stateListener.OnStateNotify(OnStateListener.CANNOTAUTOSOLVE);
}
}
public String GetCmdStrBefore()
{
return this.CmdStrBefore;
}
public void SetCmdStrBefore(String CmdStrBefore)
{
this.CmdStrBefore = CmdStrBefore;
}
public void SetCmdStrAfter(String CmdStrAfter)
{
this.CmdStrAfter = CmdStrAfter;
}
public String GetCmdStrAfter()
{
return this.CmdStrAfter;
}
public void setVolume(int volume) {
this.volume = volume;
}
}
| flexwang/HappyRubik | src/flex/android/magiccube/MagicCubeRender.java | Java | apache-2.0 | 40,437 |
<?php namespace Way\Generators\Syntax;
class CreateTable extends Table {
/**
* Build string for creating a
* table and columns
*
* @param $migrationData
* @param $fields
* @return mixed
*/
public function create($migrationData, $fields)
{
$migrationData = ['method' => 'create', 'table' => $migrationData['table']];
// All new tables should have an identifier
// Let's add that for the user automatically
$primaryKey['id'] = ['type' => 'increments'];
$fields = $primaryKey + $fields;
// We'll also add timestamps to new tables for convenience
$fields[''] = ['type' => 'timestamps'];
return (new AddToTable($this->file, $this->compiler))->add($migrationData, $fields);
}
} | pup-progguild/InformHerAPI | vendor/way/generators/src/Way/Generators/Syntax/CreateTable.php | PHP | apache-2.0 | 793 |
package sagex.phoenix.remote.services;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
import javax.script.Invocable;
import javax.script.ScriptException;
import sagex.phoenix.util.PhoenixScriptEngine;
public class JSMethodInvocationHandler implements InvocationHandler {
private PhoenixScriptEngine eng;
private Map<String, String> methodMap = new HashMap<String, String>();
public JSMethodInvocationHandler(PhoenixScriptEngine eng, String interfaceMethod, String jsMethod) {
this.eng = eng;
methodMap.put(interfaceMethod, jsMethod);
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
if (Object.class == method.getDeclaringClass()) {
String name = method.getName();
if ("equals".equals(name)) {
return proxy == args[0];
} else if ("hashCode".equals(name)) {
return System.identityHashCode(proxy);
} else if ("toString".equals(name)) {
return proxy.getClass().getName() + "@" + Integer.toHexString(System.identityHashCode(proxy))
+ ", with InvocationHandler " + this;
} else {
throw new IllegalStateException(String.valueOf(method));
}
}
String jsMethod = methodMap.get(method.getName());
if (jsMethod == null) {
throw new NoSuchMethodException("No Javascript Method for " + method.getName());
}
Invocable inv = (Invocable) eng.getEngine();
try {
return inv.invokeFunction(jsMethod, args);
} catch (NoSuchMethodException e) {
throw new NoSuchMethodException("The Java Method: " + method.getName() + " maps to a Javascript Method " + jsMethod
+ " that does not exist.");
} catch (ScriptException e) {
throw e;
}
}
}
| stuckless/sagetv-phoenix-core | src/main/java/sagex/phoenix/remote/services/JSMethodInvocationHandler.java | Java | apache-2.0 | 1,998 |
// Copyright 2015 Google Inc. 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.
package node
import (
"reflect"
"testing"
"github.com/kubernetes/dashboard/src/app/backend/resource/common"
"github.com/kubernetes/dashboard/src/app/backend/resource/dataselect"
"github.com/kubernetes/dashboard/src/app/backend/resource/metric"
metaV1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/kubernetes/fake"
api "k8s.io/client-go/pkg/api/v1"
)
func TestGetNodeList(t *testing.T) {
cases := []struct {
node *api.Node
expected *NodeList
}{
{
&api.Node{
ObjectMeta: metaV1.ObjectMeta{Name: "test-node"},
Spec: api.NodeSpec{
Unschedulable: true,
},
},
&NodeList{
ListMeta: common.ListMeta{
TotalItems: 1,
},
CumulativeMetrics: make([]metric.Metric, 0),
Nodes: []Node{{
ObjectMeta: common.ObjectMeta{Name: "test-node"},
TypeMeta: common.TypeMeta{Kind: common.ResourceKindNode},
Ready: "Unknown",
AllocatedResources: NodeAllocatedResources{
CPURequests: 0,
CPURequestsFraction: 0,
CPULimits: 0,
CPULimitsFraction: 0,
CPUCapacity: 0,
MemoryRequests: 0,
MemoryRequestsFraction: 0,
MemoryLimits: 0,
MemoryLimitsFraction: 0,
MemoryCapacity: 0,
AllocatedPods: 0,
PodCapacity: 0,
},
},
},
},
},
}
for _, c := range cases {
fakeClient := fake.NewSimpleClientset(c.node)
fakeHeapsterClient := FakeHeapsterClient{client: *fake.NewSimpleClientset()}
actual, _ := GetNodeList(fakeClient, dataselect.NoDataSelect, fakeHeapsterClient)
if !reflect.DeepEqual(actual, c.expected) {
t.Errorf("GetNodeList() == \ngot: %#v, \nexpected %#v", actual, c.expected)
}
}
}
| danielromlein/dashboard | src/app/backend/resource/node/list_test.go | GO | apache-2.0 | 2,364 |
package com.nagopy.android.disablemanager2;
import android.os.Build;
import com.android.uiautomator.core.UiSelector;
@SuppressWarnings("unused")
public class UiSelectorBuilder {
private UiSelector uiSelector;
public UiSelector build() {
return uiSelector;
}
/**
* @since API Level 16
*/
public UiSelectorBuilder() {
uiSelector = new UiSelector();
}
/**
* @since API Level 16
*/
public UiSelectorBuilder text(String text) {
uiSelector = uiSelector.text(text);
return this;
}
/**
* @since API Level 17
*/
public UiSelectorBuilder textMatches(String regex) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
uiSelector = uiSelector.textMatches(regex);
}
return this;
}
/**
* @since API Level 16
*/
public UiSelectorBuilder textStartsWith(String text) {
uiSelector = uiSelector.textStartsWith(text);
return this;
}
/**
* @since API Level 16
*/
public UiSelectorBuilder textContains(String text) {
uiSelector = uiSelector.textContains(text);
return this;
}
/**
* @since API Level 16
*/
public UiSelectorBuilder className(String className) {
uiSelector = uiSelector.className(className);
return this;
}
/**
* @since API Level 17
*/
public UiSelectorBuilder classNameMatches(String regex) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
uiSelector = uiSelector.classNameMatches(regex);
}
return this;
}
/**
* @since API Level 17
*/
public UiSelectorBuilder className(Class<?> type) {
uiSelector = uiSelector.className(type.getName());
return this;
}
/**
* @since API Level 16
*/
public UiSelectorBuilder description(String desc) {
uiSelector = uiSelector.description(desc);
return this;
}
/**
* @since API Level 17
*/
public UiSelectorBuilder descriptionMatches(String regex) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
uiSelector = uiSelector.descriptionMatches(regex);
}
return this;
}
/**
* @since API Level 16
*/
public UiSelectorBuilder descriptionStartsWith(String desc) {
uiSelector = uiSelector.descriptionStartsWith(desc);
return this;
}
/**
* @since API Level 16
*/
public UiSelectorBuilder descriptionContains(String desc) {
uiSelector = uiSelector.descriptionContains(desc);
return this;
}
/**
* @since API Level 18
*/
public UiSelectorBuilder resourceId(String id) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
uiSelector = uiSelector.resourceId(id);
}
return this;
}
/**
* @since API Level 18
*/
public UiSelectorBuilder resourceIdMatches(String regex) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
uiSelector = uiSelector.resourceIdMatches(regex);
}
return this;
}
/**
* @since API Level 16
*/
public UiSelectorBuilder index(final int index) {
uiSelector = uiSelector.index(index);
return this;
}
/**
* @since API Level 16
*/
public UiSelectorBuilder instance(final int instance) {
uiSelector = uiSelector.instance(instance);
return this;
}
/**
* @since API Level 16
*/
public UiSelectorBuilder enabled(boolean val) {
uiSelector = uiSelector.enabled(val);
return this;
}
/**
* @since API Level 16
*/
public UiSelectorBuilder focused(boolean val) {
uiSelector = uiSelector.focused(val);
return this;
}
/**
* @since API Level 16
*/
public UiSelectorBuilder focusable(boolean val) {
uiSelector = uiSelector.focusable(val);
return this;
}
/**
* @since API Level 16
*/
public UiSelectorBuilder scrollable(boolean val) {
uiSelector = uiSelector.scrollable(val);
return this;
}
/**
* @since API Level 16
*/
public UiSelectorBuilder selected(boolean val) {
uiSelector = uiSelector.selected(val);
return this;
}
/**
* @since API Level 16
*/
public UiSelectorBuilder checked(boolean val) {
uiSelector = uiSelector.checked(val);
return this;
}
/**
* @since API Level 16
*/
public UiSelectorBuilder clickable(boolean val) {
uiSelector = uiSelector.clickable(val);
return this;
}
/**
* @since API Level 18
*/
public UiSelectorBuilder checkable(boolean val) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
uiSelector = uiSelector.checkable(val);
}
return this;
}
/**
* @since API Level 17
*/
public UiSelectorBuilder longClickable(boolean val) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
uiSelector = uiSelector.longClickable(val);
}
return this;
}
/**
* @since API Level 16
*/
public UiSelectorBuilder childSelector(UiSelector selector) {
uiSelector = uiSelector.childSelector(selector);
return this;
}
/**
* @since API Level 16
*/
public UiSelectorBuilder fromParent(UiSelector selector) {
uiSelector = uiSelector.fromParent(selector);
return this;
}
/**
* @since API Level 16
*/
public UiSelectorBuilder packageName(String name) {
uiSelector = uiSelector.packageName(name);
return this;
}
/**
* @since API Level 17
*/
public UiSelectorBuilder packageNameMatches(String regex) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
uiSelector = uiSelector.packageNameMatches(regex);
}
return this;
}
}
| 75py/DisableManager | uiautomator/src/main/java/com/nagopy/android/disablemanager2/UiSelectorBuilder.java | Java | apache-2.0 | 6,177 |
package com.salesmanager.shop.model.entity;
import java.io.Serializable;
public abstract class ReadableList implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
private int totalPages;//totalPages
private int number;//number of record in current page
private long recordsTotal;//total number of records in db
private int recordsFiltered;
public int getTotalPages() {
return totalPages;
}
public void setTotalPages(int totalCount) {
this.totalPages = totalCount;
}
public long getRecordsTotal() {
return recordsTotal;
}
public void setRecordsTotal(long recordsTotal) {
this.recordsTotal = recordsTotal;
}
public int getRecordsFiltered() {
return recordsFiltered;
}
public void setRecordsFiltered(int recordsFiltered) {
this.recordsFiltered = recordsFiltered;
}
public int getNumber() {
return number;
}
public void setNumber(int number) {
this.number = number;
}
} | shopizer-ecommerce/shopizer | sm-shop-model/src/main/java/com/salesmanager/shop/model/entity/ReadableList.java | Java | apache-2.0 | 950 |
/*
* @(#)file SASLOutputStream.java
* @(#)author Sun Microsystems, Inc.
* @(#)version 1.10
* @(#)lastedit 07/03/08
* @(#)build @BUILD_TAG_PLACEHOLDER@
*
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright (c) 2007 Sun Microsystems, Inc. All Rights Reserved.
*
* The contents of this file are subject to the terms of either the GNU General
* Public License Version 2 only ("GPL") or the Common Development and
* Distribution License("CDDL")(collectively, the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy of the
* License at http://opendmk.dev.java.net/legal_notices/licenses.txt or in the
* LEGAL_NOTICES folder that accompanied this code. See the License for the
* specific language governing permissions and limitations under the License.
*
* When distributing the software, include this License Header Notice in each
* file and include the License file found at
* http://opendmk.dev.java.net/legal_notices/licenses.txt
* or in the LEGAL_NOTICES folder that accompanied this code.
* Sun designates this particular file as subject to the "Classpath" exception
* as provided by Sun in the GPL Version 2 section of the License file that
* accompanied this code.
*
* If applicable, add the following below the License Header, with the fields
* enclosed by brackets [] replaced by your own identifying information:
*
* "Portions Copyrighted [year] [name of copyright owner]"
*
* Contributor(s):
*
* If you wish your version of this file to be governed by only the CDDL or
* only the GPL Version 2, indicate your decision by adding
*
* "[Contributor] elects to include this software in this distribution
* under the [CDDL or GPL Version 2] license."
*
* If you don't indicate a single choice of license, a recipient has the option
* to distribute your version of this file under either the CDDL or the GPL
* Version 2, or to extend the choice of license to its licensees as provided
* above. However, if you add GPL Version 2 code and therefore, elected the
* GPL Version 2 license, then the option applies only if the new code is made
* subject to such option by the copyright holder.
*
*/
package com.sun.jmx.remote.opt.security;
import javax.security.sasl.Sasl;
import javax.security.sasl.SaslClient;
import javax.security.sasl.SaslServer;
import java.io.IOException;
import java.io.OutputStream;
import com.sun.jmx.remote.opt.util.ClassLogger;
public class SASLOutputStream extends OutputStream {
private int rawSendSize = 65536;
private byte[] lenBuf = new byte[4]; // buffer for storing length
private OutputStream out; // underlying output stream
private SaslClient sc;
private SaslServer ss;
public SASLOutputStream(SaslClient sc, OutputStream out)
throws IOException {
super();
this.out = out;
this.sc = sc;
this.ss = null;
String str = (String) sc.getNegotiatedProperty(Sasl.RAW_SEND_SIZE);
if (str != null) {
try {
rawSendSize = Integer.parseInt(str);
} catch (NumberFormatException e) {
throw new IOException(Sasl.RAW_SEND_SIZE +
" property must be numeric string: " + str);
}
}
}
public SASLOutputStream(SaslServer ss, OutputStream out)
throws IOException {
super();
this.out = out;
this.ss = ss;
this.sc = null;
String str = (String) ss.getNegotiatedProperty(Sasl.RAW_SEND_SIZE);
if (str != null) {
try {
rawSendSize = Integer.parseInt(str);
} catch (NumberFormatException e) {
throw new IOException(Sasl.RAW_SEND_SIZE +
" property must be numeric string: " + str);
}
}
}
public void write(int b) throws IOException {
byte[] buffer = new byte[1];
buffer[0] = (byte)b;
write(buffer, 0, 1);
}
public void write(byte[] buffer, int offset, int total) throws IOException {
int count;
byte[] wrappedToken, saslBuffer;
// "Packetize" buffer to be within rawSendSize
if (logger.traceOn()) {
logger.trace("write", "Total size: " + total);
}
for (int i = 0; i < total; i += rawSendSize) {
// Calculate length of current "packet"
count = (total - i) < rawSendSize ? (total - i) : rawSendSize;
// Generate wrapped token
if (sc != null)
wrappedToken = sc.wrap(buffer, offset+i, count);
else
wrappedToken = ss.wrap(buffer, offset+i, count);
// Write out length
intToNetworkByteOrder(wrappedToken.length, lenBuf, 0, 4);
if (logger.traceOn()) {
logger.trace("write", "sending size: " + wrappedToken.length);
}
out.write(lenBuf, 0, 4);
// Write out wrapped token
out.write(wrappedToken, 0, wrappedToken.length);
}
}
public void close() throws IOException {
if (sc != null)
sc.dispose();
else
ss.dispose();
out.close();
}
/**
* Encodes an integer into 4 bytes in network byte order in the buffer
* supplied.
*/
private void intToNetworkByteOrder(int num, byte[] buf,
int start, int count) {
if (count > 4) {
throw new IllegalArgumentException("Cannot handle more " +
"than 4 bytes");
}
for (int i = count-1; i >= 0; i--) {
buf[start+i] = (byte)(num & 0xff);
num >>>= 8;
}
}
private static final ClassLogger logger =
new ClassLogger("javax.management.remote.misc", "SASLOutputStream");
}
| nickman/heliosutils | src/main/java/com/sun/jmx/remote/opt/security/SASLOutputStream.java | Java | apache-2.0 | 5,384 |
# -*- coding:utf-8 -*-
#
# Copyright (c) 2017 mooncake. All Rights Reserved
####
# @brief
# @author Eric Yue ( hi.moonlight@gmail.com )
# @version 0.0.1
from distutils.core import setup
V = "0.7"
setup(
name = 'mooncake_utils',
packages = ['mooncake_utils'],
version = V,
description = 'just a useful utils for mooncake personal project.',
author = 'mooncake',
author_email = 'hi.moonlight@gmail.com',
url = 'https://github.com/ericyue/mooncake_utils',
download_url = 'https://github.com/ericyue/mooncake_utils/archive/%s.zip' % V,
keywords = ['utils','data','machine-learning'], # arbitrary keywords
classifiers = [],
)
| ericyue/mooncake_utils | setup.py | Python | apache-2.0 | 646 |
function f1(a) {
try {
throw "x";
} catch (arguments) {
console.log(arguments);
}
}
f1(3);
| csgordon/SJS | jscomp/tests/scope7.js | JavaScript | apache-2.0 | 123 |
<?php
namespace CultuurNet\UDB3\EventSourcing\DBAL;
class NonCompatibleUuid
{
/**
* @var string
*/
private $uuid;
/**
* DummyUuid constructor.
* @param string $uuid
*/
public function __construct($uuid)
{
$this->uuid = $uuid;
}
}
| cultuurnet/udb3-php | test/EventSourcing/DBAL/NonCompatibleUuid.php | PHP | apache-2.0 | 290 |
// JavaScript Document
var flag1=true;
var flag2=true;
$(function () {
/*********************/
$.ajax({
type : 'POST',
dataType : 'json',
url : 'baseNeiName.do',
async : true,
cache : false,
error : function(request) {
bootbox.alert({
message : "请求异常",
size : 'small'
});
},
success : function(data) {
var i = 0;
for ( var item in data) {
$("#baselistid").after(
"<option value="+data[i].id+">"
+ data[i].name + "</option>");
i++;
}
}
});
/**************************/
/*########*/
$(document).on("click", "#Submit", function() {
var projectname=$("#projectname").val();
var name=$("#name").val();
var address=$("#address").val();
var budget=$("#budget").val();
budget=budget.trim();
var baselist=$("#baselist").val();
var reason=$("#reason").val();
var strmoney=/^[0-9]*$/.test(budget);
var money=budget.substring(1,0);
if(projectname==""){
bootbox.alert({
message : "请填写项目名称",
size : 'small'
});
return 0;
}
else if(name==""){
bootbox.alert({
message : "请填写报修人",
size : 'small'
});
return 0;
}
else if(address==""){
bootbox.alert({
message : "请填写具体位置",
size : 'small'
});
return 0;
}
else if(budget==""){
bootbox.alert({
message : "请填写预算金额",
size : 'small'
});
return 0;
}
else if(strmoney==false){
bootbox.alert({
message : "预算金额只能为数字",
size : 'small'
});
return 0;
}
else if(budget.length>1&&money==0){
bootbox.alert({
message : "请填写正确的预算金额格式,第一个数字不能为零",
size : 'small'
});
return 0;
}
else if(baselist=="请选择"){
bootbox.alert({
message : "请选择基地",
size : 'small'
});
return 0;
}
else if(reason==""){
bootbox.alert({
message : "请填写原因",
size : 'small'
});
return 0;
}
if (!flag1) {
bootbox.alert({
message: "上传资料仅限于rar,zip压缩包格式",
size: 'small'
});
$("#applyfile").val('');
return;
}
if (!flag2) {
bootbox.alert({
message: "上传资料大小不能大于10M",
size: 'small'
});
$("#applyfile").val('');
return;
}
/*************/
$("#applyform").submit();
/*************/
})
$('#applyfile').change(function() {
var filepath = $(this).val();
var file_size = this.files[0].size;
var size = file_size / 1024;
var extStart = filepath.lastIndexOf(".");
var ext = filepath.substring(extStart, filepath.length).toUpperCase();
if (ext != ".RAR" && ext != ".ZIP") {
bootbox.alert({
message: "上传资料仅限于rar,zip压缩包格式",
size: 'small'
});
$("#applyfile").val('');
flag1=false;
return;
}
if (size > 1024 * 10) {
bootbox.alert({
message: "上传资料大小不能大于10M",
size: 'small'
});
$("#applyfile").val('');
flag2=false;
return;
}
flag1=true;
flag2=true;
});
/*########*/
}); | pange123/PB_Management | 后台页面/WebRoot/js/myNeed/Repairpply.js | JavaScript | apache-2.0 | 3,500 |
/*
* Copyright 2019 The Project Oak 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';
const showGreenIconForExtensionPages = {
conditions: [
new chrome.declarativeContent.PageStateMatcher({
pageUrl: {
hostEquals: chrome.runtime.id,
schemes: ['chrome-extension'],
pathEquals: '/index.html',
},
}),
],
actions: [new chrome.declarativeContent.SetIcon({ path: 'icon-green.png' })],
};
chrome.runtime.onInstalled.addListener(function () {
chrome.declarativeContent.onPageChanged.removeRules(undefined, function () {
chrome.declarativeContent.onPageChanged.addRules([
showGreenIconForExtensionPages,
]);
});
});
async function loadPageInASecureSandbox({ id: tabId }) {
const src = (
await new Promise((resolve) =>
chrome.tabs.executeScript(tabId, { file: 'getInnerHtml.js' }, resolve)
)
)?.[0];
// It's possible that the chrome extension cannot read the source code, either
// because it is served via a non-permitted scheme (eg `chrome-extension://`),
// or bc the user/adminstrator has denied this extension access to the page.
if (!src) {
chrome.notifications.create(undefined, {
type: 'basic',
title: 'Could not sandbox this page',
message: 'The extension does not have permission to modify this page.',
iconUrl: 'icon-red.png',
isClickable: false,
eventTime: Date.now(),
});
return;
}
const searchParams = new URLSearchParams({ src });
const url = `index.html?${searchParams.toString()}`;
chrome.tabs.update({ url });
}
chrome.browserAction.onClicked.addListener(loadPageInASecureSandbox);
| project-oak/oak | chrome_extension/background.js | JavaScript | apache-2.0 | 2,181 |
/*******************************************************************************
* Copyright © 2012-2015 eBay Software Foundation
* This program is dual licensed under the MIT and Apache 2.0 licenses.
* Please see LICENSE for more information.
*******************************************************************************/
package com.ebay.pulsar.analytics.metricstore.druid.query.sql;
/**
*
* @author mingmwang
*
*/
public class HllConstants {
public static final String HLLPREFIX = "hllhaving_";
}
| pulsarIO/pulsar-reporting-api | pulsarquery-druid/src/main/java/com/ebay/pulsar/analytics/metricstore/druid/query/sql/HllConstants.java | Java | apache-2.0 | 514 |
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
// Copyright 2014 Thomas Barnekow (cloning, Flat OPC (with Eric White))
using System;
using System.Diagnostics;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.Text;
using System.IO;
using System.IO.Packaging;
using System.Globalization;
using DocumentFormat.OpenXml;
using System.Linq;
using System.Xml;
using System.Xml.Linq;
#if FEATURE_SERIALIZATION
using System.Runtime.Serialization;
#endif
using static System.ReflectionExtensions;
namespace DocumentFormat.OpenXml.Packaging
{
internal struct RelationshipProperty
{
internal string Id;
internal string RelationshipType;
internal TargetMode TargetMode;
internal Uri TargetUri;
};
/// <summary>
/// Defines the base class for PackageRelationshipPropertyCollection and PackagePartRelationshipPropertyCollection objects.
/// </summary>
abstract internal class RelationshipCollection : List<RelationshipProperty>
{
protected PackageRelationshipCollection BasePackageRelationshipCollection { get; set; }
internal bool StrictTranslation { get; set; }
/// <summary>
/// This method fills the collection with PackageRels from the PackageRelationshipCollection that is given in the sub class.
/// </summary>
protected void Build()
{
foreach (PackageRelationship relationship in this.BasePackageRelationshipCollection)
{
bool found;
string transitionalNamespace;
RelationshipProperty relationshipProperty;
relationshipProperty.TargetUri = relationship.TargetUri;
relationshipProperty.TargetMode = relationship.TargetMode;
relationshipProperty.Id = relationship.Id;
relationshipProperty.RelationshipType = relationship.RelationshipType;
// If packageRel.RelationshipType is something for Strict, it tries to get the equivalent in Transitional.
found = NamespaceIdMap.TryGetTransitionalRelationship(relationshipProperty.RelationshipType, out transitionalNamespace);
if (found)
{
relationshipProperty.RelationshipType = transitionalNamespace;
this.StrictTranslation = true;
}
this.Add(relationshipProperty);
}
}
internal void UpdateRelationshipTypesInPackage()
{
// Update the relationshipTypes when editable.
if (this.GetPackage().FileOpenAccess != FileAccess.Read)
{
for (int index = 0; index < this.Count; index++)
{
RelationshipProperty relationshipProperty = this[index];
this.ReplaceRelationship(relationshipProperty.TargetUri, relationshipProperty.TargetMode, relationshipProperty.RelationshipType, relationshipProperty.Id);
}
}
}
abstract internal void ReplaceRelationship(Uri targetUri, TargetMode targetMode, string strRelationshipType, string strId);
abstract internal Package GetPackage();
}
/// <summary>
/// Represents a collection of relationships that are obtained from the package.
/// </summary>
internal class PackageRelationshipPropertyCollection : RelationshipCollection
{
public Package BasePackage { get; set; }
public PackageRelationshipPropertyCollection(Package package)
{
this.BasePackage = package;
if (this.BasePackage == null)
{
throw new ArgumentNullException(nameof(BasePackage));
}
this.BasePackageRelationshipCollection = this.BasePackage.GetRelationships();
this.Build();
}
internal override void ReplaceRelationship(Uri targetUri, TargetMode targetMode, string strRelationshipType, string strId)
{
this.BasePackage.DeleteRelationship(strId);
this.BasePackage.CreateRelationship(targetUri, targetMode, strRelationshipType, strId);
}
internal override Package GetPackage()
{
return this.BasePackage;
}
}
/// <summary>
/// Represents a collection of relationships that are obtained from the package part.
/// </summary>
internal class PackagePartRelationshipPropertyCollection : RelationshipCollection
{
public PackagePart BasePackagePart { get; set; }
public PackagePartRelationshipPropertyCollection(PackagePart packagePart)
{
this.BasePackagePart = packagePart;
if (this.BasePackagePart == null)
{
throw new ArgumentNullException(nameof(BasePackagePart));
}
this.BasePackageRelationshipCollection = this.BasePackagePart.GetRelationships();
this.Build();
}
internal override void ReplaceRelationship(Uri targetUri, TargetMode targetMode, string strRelationshipType, string strId)
{
this.BasePackagePart.DeleteRelationship(strId);
this.BasePackagePart.CreateRelationship(targetUri, targetMode, strRelationshipType, strId);
}
internal override Package GetPackage()
{
return this.BasePackagePart.Package;
}
}
/// <summary>
/// Represents a base class for strong typed Open XML document classes.
/// </summary>
public abstract class OpenXmlPackage : OpenXmlPartContainer, IDisposable
{
#region private data members
//internal object _lock = new object( );
private bool _disposed;
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
private Package _metroPackage;
private FileAccess _accessMode;
private string _mainPartContentType;
// compression level for content that is stored in a PackagePart.
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
private CompressionOption _compressionOption = CompressionOption.Normal;
private PartUriHelper _partUriHelper = new PartUriHelper();
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
private PartExtensionProvider _partExtensionProvider = new PartExtensionProvider();
private LinkedList<DataPart> _dataPartList = new LinkedList<DataPart>();
#endregion
internal OpenSettings OpenSettings { get; set; }
private bool _strictTranslation = false;
internal bool StrictTranslation
{
get
{
return this._strictTranslation;
}
set
{
this._strictTranslation = value;
}
}
#region internal constructors
/// <summary>
/// Initializes a new instance of the OpenXmlPackage class.
/// </summary>
protected OpenXmlPackage()
: base()
{
}
/// <summary>
/// Initializes a new instance of the OpenXmlPackage class using the supplied Open XML package.
/// </summary>
/// <param name="package">The target package for the OpenXmlPackage class.</param>
/// <exception cref="ArgumentNullException">Thrown when package is a null reference.</exception>
/// <exception cref="IOException">Thrown when package is not opened with read access.</exception>
/// <exception cref="OpenXmlPackageException">Thrown when the package is not a valid Open XML document.</exception>
internal void OpenCore(Package package)
{
if (package == null)
{
throw new ArgumentNullException(nameof(package));
}
if (package.FileOpenAccess == FileAccess.Write)
{
// TODO: move this line to derived class
throw new IOException(ExceptionMessages.PackageMustCanBeRead);
}
this._accessMode = package.FileOpenAccess;
this._metroPackage = package;
this.Load();
}
/// <summary>
/// Initializes a new instance of the OpenXmlPackage class with access to a specified Open XML package.
/// </summary>
/// <param name="package">The target package for the OpenXmlPackage class.</param>
/// <exception cref="ArgumentNullException">Thrown when package is a null reference.</exception>
/// <exception cref="IOException">Thrown when package is not opened with write access.</exception>
/// <exception cref="OpenXmlPackageException">Thrown when the package is not a valid Open XML document.</exception>
internal void CreateCore(Package package)
{
if (package == null)
{
throw new ArgumentNullException(nameof(package));
}
//if (package.FileOpenAccess != FileAccess.Write)
//{
// // TODO: move this line to derived class
// throw new IOException(ExceptionMessages.PackageAccessModeShouldBeWrite);
//}
this._accessMode = package.FileOpenAccess;
this._metroPackage = package;
}
/// <summary>
/// Initializes a new instance of the OpenXmlPackage class using the supplied I/O stream class.
/// </summary>
/// <param name="stream">The I/O stream on which to open the package.</param>
/// <param name="readWriteMode">Indicates whether or not the package is in read/write mode. False indicates read-only mode.</param>
/// <exception cref="IOException">Thrown when the specified stream is write-only. The package to open requires read or read/write permission.</exception>
internal void OpenCore(Stream stream, bool readWriteMode)
{
if (stream == null)
{
throw new ArgumentNullException(nameof(stream));
}
if (readWriteMode)
{
this._accessMode = FileAccess.ReadWrite;
}
else
{
this._accessMode = FileAccess.Read;
}
this._metroPackage = Package.Open(stream, (this._accessMode == FileAccess.Read) ? FileMode.Open : FileMode.OpenOrCreate, this._accessMode);
this.Load();
}
/// <summary>
/// Initializes a new instance of the OpenXmlPackage class using the supplied I/O stream class.
/// </summary>
/// <param name="stream">The I/O stream on which to open the package.</param>
/// <exception cref="IOException">Thrown when the specified stream is read-only. The package to open requires write or read/write permission. </exception>
internal void CreateCore(Stream stream)
{
if (stream == null)
{
throw new ArgumentNullException(nameof(stream));
}
if (!stream.CanWrite)
{
throw new OpenXmlPackageException(ExceptionMessages.StreamAccessModeShouldBeWrite);
}
this._accessMode = FileAccess.ReadWrite;
//this._accessMode = FileAccess.Write;
// below line will exception by Package. Packaging API bug?
// this._metroPackage = Package.Open(stream, FileMode.Create, packageAccess);
this._metroPackage = Package.Open(stream, FileMode.Create, FileAccess.ReadWrite);
}
/// <summary>
/// Initializes a new instance of the OpenXmlPackage class using the specified file.
/// </summary>
/// <param name="path">The path and file name of the target package for the OpenXmlPackage.</param>
/// <param name="readWriteMode">Indicates whether or not the package is in read/write mode. False for read only mode.</param>
internal void OpenCore(string path, bool readWriteMode)
{
if (path == null)
{
throw new ArgumentNullException(nameof(path));
}
if (readWriteMode)
{
this._accessMode = FileAccess.ReadWrite;
}
else
{
this._accessMode = FileAccess.Read;
}
this._metroPackage = Package.Open(path, (this._accessMode == FileAccess.Read) ? FileMode.Open : FileMode.OpenOrCreate, this._accessMode, (this._accessMode == FileAccess.Read) ? FileShare.Read : FileShare.None);
this.Load();
}
/// <summary>
/// Initializes a new instance of the OpenXmlPackage class using the supplied file.
/// </summary>
/// <param name="path">The path and file name of the target package for the OpenXmlPackage.</param>
internal void CreateCore(string path)
{
if (path == null)
{
throw new ArgumentNullException(nameof(path));
}
this._accessMode = FileAccess.ReadWrite;
//this._accessMode = FileAccess.Write;
// below line will exception by Package. Packaging API bug?
// this._metroPackage = Package.Open(path, FileMode.Create, packageAccess, FileShare.None);
this._metroPackage = Package.Open(path, FileMode.Create, FileAccess.ReadWrite, FileShare.None);
}
/// <summary>
/// Loads the package. This method must be called in the constructor of a derived class.
/// </summary>
private void Load()
{
Profiler.CommentMarkProfile(Profiler.MarkId.OpenXmlPackage_Load_In);
try
{
Dictionary<Uri, OpenXmlPart> loadedParts = new Dictionary<Uri, OpenXmlPart>();
bool hasMainPart = false;
RelationshipCollection relationshipCollection = new PackageRelationshipPropertyCollection(this._metroPackage);
// relationCollection.StrictTranslation is true when this collection contains Transitional relationships converted from Strict.
this.StrictTranslation = relationshipCollection.StrictTranslation;
// AutoSave must be false when opening ISO Strict doc as editable.
// (Attention: #2545529. Now we disable this code until we finally decide to go with this. Instead, we take an alternative approach that is added in the SavePartContents() method
// which we ignore AutoSave when this.StrictTranslation is true to keep consistency in the document.)
//if (this.StrictTranslation && (this._accessMode == FileAccess.ReadWrite || this._accessMode == FileAccess.Write) && !this.AutoSave)
//{
// OpenXmlPackageException exception = new OpenXmlPackageException(ExceptionMessages.StrictEditNeedsAutoSave);
// throw exception;
//}
// auto detect document type (main part type for Transitional)
foreach (RelationshipProperty relationship in relationshipCollection)
{
if (relationship.RelationshipType == this.MainPartRelationshipType)
{
hasMainPart = true;
Uri uriTarget = PackUriHelper.ResolvePartUri(new Uri("/", UriKind.Relative), relationship.TargetUri);
PackagePart metroPart = this.Package.GetPart(uriTarget);
if (!this.IsValidMainPartContentType(metroPart.ContentType))
{
OpenXmlPackageException exception = new OpenXmlPackageException(ExceptionMessages.InvalidPackageType);
throw exception;
}
this.MainPartContentType = metroPart.ContentType;
break;
}
}
if (!hasMainPart)
{
// throw exception is the package do not have the main part (MainDocument / Workbook / Presentation part)
OpenXmlPackageException exception = new OpenXmlPackageException(ExceptionMessages.NoMainPart);
throw exception;
}
this.LoadReferencedPartsAndRelationships(this, null, relationshipCollection, loadedParts);
}
catch (OpenXmlPackageException)
{
// invalid part ( content type is not expected )
this.Close();
throw;
}
catch (System.UriFormatException)
{
// UriFormatException is replaced here with OpenXmlPackageException. <O15:#322821>
OpenXmlPackageException exception = new OpenXmlPackageException(ExceptionMessages.InvalidUriFormat);
this.Close();
throw exception;
}
catch (Exception)
{
this.Close();
throw;
}
Profiler.CommentMarkProfile(Profiler.MarkId.OpenXmlPackage_Load_Out);
}
#endregion
#region public properties
/// <summary>
/// Gets the package of the document.
/// </summary>
public Package Package
{
get
{
this.ThrowIfObjectDisposed();
return _metroPackage;
}
}
/// <summary>
/// Gets the FileAccess setting for the document.
/// The current I/O access settings are: Read, Write, or ReadWrite.
/// </summary>
public FileAccess FileOpenAccess
{
get { return this._metroPackage.FileOpenAccess; }
}
/// <summary>
/// Gets or sets the compression level for the content of the new part.
/// </summary>
public CompressionOption CompressionOption
{
get { return this._compressionOption; }
set { this._compressionOption = value; }
}
/// <summary>
/// Gets the core package properties of the Open XML document.
/// </summary>
public PackageProperties PackageProperties
{
get
{
this.ThrowIfObjectDisposed();
return this.Package.PackageProperties;
}
}
/// <summary>
/// Gets a PartExtensionProvider part which provides a mapping from ContentType to part extension.
/// </summary>
public PartExtensionProvider PartExtensionProvider
{
get
{
this.ThrowIfObjectDisposed();
return this._partExtensionProvider;
}
}
/// <summary>
/// Gets or sets a value that indicates the maximum allowable number of characters in an Open XML part. A zero (0) value indicates that there are no limits on the size of the part. A non-zero value specifies the maximum size, in characters.
/// </summary>
/// <remarks>
/// This property allows you to mitigate denial of service attacks where the attacker submits a package with an extremely large Open XML part. By limiting the size of a part, you can detect the attack and recover reliably.
/// </remarks>
public long MaxCharactersInPart
{
get;
internal set;
}
/// <summary>
/// Enumerates all the <see cref="DataPart"/> parts in the document package.
/// </summary>
public IEnumerable<DataPart> DataParts
{
get
{
return this._dataPartList;
}
}
#endregion
#region public methods
/// <summary>
/// Adds the specified part to the document.
/// Use the returned part to operate on the part added to the document.
/// </summary>
/// <typeparam name="T">A class that is derived from the OpenXmlPart class.</typeparam>
/// <param name="part">The part to add to the document.</param>
/// <returns>The added part in the document. Differs from the part that was passed as an argument.</returns>
/// <exception cref="ArgumentOutOfRangeException">Thrown when the part is not allowed to be added.</exception>
/// <exception cref="OpenXmlPackageException">Thrown when the part type already exists and multiple instances of the part type is not allowed.</exception>
public override T AddPart<T>(T part)
{
this.ThrowIfObjectDisposed();
if (part == null)
{
throw new ArgumentNullException(nameof(part));
}
if (part.RelationshipType == this.MainPartRelationshipType &&
part.ContentType != this.MainPartContentType)
{
throw new ArgumentOutOfRangeException(ExceptionMessages.MainPartIsDifferent);
}
return (T)AddPartFrom(part, null);
}
/// <summary>
/// Deletes all the parts with the specified part type from the package recursively.
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1004:GenericMethodsShouldProvideTypeParameter")]
public void DeletePartsRecursivelyOfType<T>() where T : OpenXmlPart
{
this.ThrowIfObjectDisposed();
DeletePartsRecursivelyOfTypeBase<T>();
}
// Remove this method due to bug #18394
// User can call doc.Package.Flush( ) as a workaround.
///// <summary>
///// Saves the contents of all parts and relationships that are contained in the OpenXml package.
///// </summary>
//public void Save()
//{
// this.ThrowIfObjectDisposed();
// this.Package.Flush();
//}
/// <summary>
/// Saves and closes the OpenXml package and all underlying part streams.
/// </summary>
public void Close()
{
this.ThrowIfObjectDisposed();
Dispose();
}
#region methods to operate DataPart
/// <summary>
/// Creates a new <see cref="MediaDataPart"/> part in the document package.
/// </summary>
/// <param name="contentType">The content type of the new <see cref="MediaDataPart"/> part.</param>
/// <returns>The added <see cref="MediaDataPart"/> part.</returns>
/// <exception cref="ArgumentNullException">Thrown when <paramref name="contentType"/> is a null reference.</exception>
public MediaDataPart CreateMediaDataPart(string contentType)
{
ThrowIfObjectDisposed();
if (contentType == null)
{
throw new ArgumentNullException(nameof(contentType));
}
MediaDataPart mediaDataPart = new MediaDataPart();
mediaDataPart.CreateInternal(this.InternalOpenXmlPackage, contentType, null);
this._dataPartList.AddLast(mediaDataPart);
return mediaDataPart;
}
/// <summary>
/// Creates a new <see cref="MediaDataPart"/> part in the document package.
/// </summary>
/// <param name="contentType">The content type of the new <see cref="MediaDataPart"/> part.</param>
/// <param name="extension">The part name extension (.dat, etc.) of the new <see cref="MediaDataPart"/> part.</param>
/// <returns>The added <see cref="MediaDataPart"/> part.</returns>
/// <exception cref="ArgumentNullException">Thrown when <paramref name="contentType"/> is a null reference.</exception>
/// <exception cref="ArgumentNullException">Thrown when <paramref name="extension"/> is a null reference.</exception>
public MediaDataPart CreateMediaDataPart(string contentType, string extension)
{
ThrowIfObjectDisposed();
if (contentType == null)
{
throw new ArgumentNullException(nameof(contentType));
}
if (extension == null)
{
throw new ArgumentNullException(nameof(extension));
}
MediaDataPart mediaDataPart = new MediaDataPart();
mediaDataPart.CreateInternal(this.InternalOpenXmlPackage, contentType, extension);
this._dataPartList.AddLast(mediaDataPart);
return mediaDataPart;
}
/// <summary>
/// Creates a new <see cref="MediaDataPart"/> part in the document package.
/// </summary>
/// <param name="mediaDataPartType">The content type of the new <see cref="MediaDataPart"/> part.</param>
/// <returns>The added <see cref="MediaDataPart"/> part.</returns>
public MediaDataPart CreateMediaDataPart(MediaDataPartType mediaDataPartType)
{
ThrowIfObjectDisposed();
MediaDataPart mediaDataPart = new MediaDataPart();
mediaDataPart.CreateInternal(this.InternalOpenXmlPackage, mediaDataPartType);
this._dataPartList.AddLast(mediaDataPart);
return mediaDataPart;
}
/// <summary>
/// Deletes the specified <see cref="DataPart"/> from the document package.
/// </summary>
/// <param name="dataPart">The <see cref="DataPart"/> to be deleted.</param>
/// <returns>Returns true if the part is successfully removed; otherwise returns false. This method also returns false if the part was not found or the parameter is null.</returns>
/// <exception cref="InvalidOperationException">Thrown when <paramref name="dataPart"/> is referenced by another part in the document package.</exception>
public bool DeletePart(DataPart dataPart)
{
ThrowIfObjectDisposed();
if (dataPart == null)
{
throw new ArgumentNullException(nameof(dataPart));
}
if (dataPart.OpenXmlPackage != this)
{
throw new InvalidOperationException(ExceptionMessages.ForeignDataPart);
}
if (IsOrphanDataPart(dataPart))
{
// delete the part from the package
dataPart.Destroy();
return this._dataPartList.Remove(dataPart);
}
else
{
throw new InvalidOperationException(ExceptionMessages.DataPartIsInUse);
}
}
#endregion
#endregion
#region public virtual methods
/// <summary>
/// Validates the package. This method does not validate the XML content in each part.
/// </summary>
/// <param name="validationSettings">The OpenXmlPackageValidationSettings for validation events.</param>
/// <remarks>If validationSettings is null or no EventHandler is set, the default behavior is to throw an OpenXmlPackageException on the validation error. </remarks>
[Obsolete(ObsoleteAttributeMessages.ObsoleteV1ValidationFunctionality, false)]
public void Validate(OpenXmlPackageValidationSettings validationSettings)
{
this.ThrowIfObjectDisposed();
OpenXmlPackageValidationSettings actualValidationSettings;
if (validationSettings != null && validationSettings.GetEventHandler() != null)
{
actualValidationSettings = validationSettings;
}
else
{
// use default DefaultValidationEventHandler( ) which throw an exception
actualValidationSettings = new OpenXmlPackageValidationSettings();
actualValidationSettings.EventHandler += new EventHandler<OpenXmlPackageValidationEventArgs>(DefaultValidationEventHandler);
}
// TODO: what's expected behavior?
actualValidationSettings.FileFormat = FileFormatVersions.Office2007;
// for cycle defense
Dictionary<OpenXmlPart, bool> processedParts = new Dictionary<OpenXmlPart, bool>();
ValidateInternal(actualValidationSettings, processedParts);
}
#pragma warning disable 0618 // CS0618: A class member was marked with the Obsolete attribute, such that a warning will be issued when the class member is referenced.
/// <summary>
/// Validates the package. This method does not validate the XML content in each part.
/// </summary>
/// <param name="validationSettings">The OpenXmlPackageValidationSettings for validation events.</param>
/// <param name="fileFormatVersion">The target file format version.</param>
/// <remarks>If validationSettings is null or no EventHandler is set, the default behavior is to throw an OpenXmlPackageException on the validation error. </remarks>
internal void Validate(OpenXmlPackageValidationSettings validationSettings, FileFormatVersions fileFormatVersion)
{
this.ThrowIfObjectDisposed();
Debug.Assert(validationSettings != null);
Debug.Assert(fileFormatVersion == FileFormatVersions.Office2007 || fileFormatVersion == FileFormatVersions.Office2010 || fileFormatVersion == FileFormatVersions.Office2013);
validationSettings.FileFormat = fileFormatVersion;
// for cycle defense
Dictionary<OpenXmlPart, bool> processedParts = new Dictionary<OpenXmlPart, bool>();
ValidateInternal(validationSettings, processedParts);
}
#endregion
#region virtual methods / properties
#endregion
#region internal methods
/// <summary>
/// Reserves the URI of the loaded part.
/// </summary>
/// <param name="contentType"></param>
/// <param name="partUri"></param>
internal void ReserveUri(string contentType, Uri partUri)
{
this.ThrowIfObjectDisposed();
this._partUriHelper.ReserveUri(contentType, partUri);
}
/// <summary>
/// Gets a unique part URI for the newly created part.
/// </summary>
/// <param name="contentType">The content type of the part.</param>
/// <param name="parentUri">The URI of the parent part.</param>
/// <param name="targetPath"></param>
/// <param name="targetName"></param>
/// <param name="targetExt"></param>
/// <returns></returns>
internal Uri GetUniquePartUri(string contentType, Uri parentUri, string targetPath, string targetName, string targetExt)
{
this.ThrowIfObjectDisposed();
Uri partUri = null;
// fix bug #241492
// check to avoid name conflict with orphan parts in the packages.
do
{
partUri = this._partUriHelper.GetUniquePartUri(contentType, parentUri, targetPath, targetName, targetExt);
} while (this._metroPackage.PartExists(partUri));
return partUri;
}
/// <summary>
/// Gets a unique part URI for the newly created part.
/// </summary>
/// <param name="contentType">The content type of the part.</param>
/// <param name="parentUri">The URI of the parent part.</param>
/// <param name="targetUri"></param>
/// <returns></returns>
internal Uri GetUniquePartUri(string contentType, Uri parentUri, Uri targetUri)
{
this.ThrowIfObjectDisposed();
Uri partUri = null;
// fix bug #241492
// check to avoid name conflict with orphan parts in the packages.
do
{
partUri = this._partUriHelper.GetUniquePartUri(contentType, parentUri, targetUri);
} while (this._metroPackage.PartExists(partUri));
return partUri;
}
#endregion
#region dispose related methods
/// <summary>
/// Thrown if an object is disposed.
/// </summary>
protected override void ThrowIfObjectDisposed()
{
if (this._disposed)
{
throw new ObjectDisposedException(base.GetType().Name);
}
}
/// <summary>
/// Flushes and saves the content, closes the document, and releases all resources.
/// </summary>
/// <param name="disposing">Specify true to release both managed and unmanaged resources; false to release only unmanaged resources.</param>
protected virtual void Dispose(bool disposing)
{
if (!this._disposed)
{
if (disposing)
{
// Try to save contents of every part in the package
SavePartContents();
DeleteUnusedDataPartOnClose();
// TODO: Close resources
this._metroPackage.Close();
this._metroPackage = null;
this.PartDictionary = null;
this.ReferenceRelationshipList.Clear();
this._partUriHelper = null;
}
this._disposed = true;
}
}
#endregion
#region IDisposable Members
/// <summary>
/// Flushes and saves the content, closes the document, and releases all resources.
/// </summary>
public void Dispose()
{
this.Dispose(true);
GC.SuppressFinalize(this);
}
#endregion
#region MC Staffs
/// <summary>
/// Gets the markup compatibility settings applied at loading time.
/// </summary>
public MarkupCompatibilityProcessSettings MarkupCompatibilityProcessSettings
{
get
{
if (OpenSettings.MarkupCompatibilityProcessSettings == null)
return new MarkupCompatibilityProcessSettings(MarkupCompatibilityProcessMode.NoProcess, FileFormatVersions.Office2007);
else
return OpenSettings.MarkupCompatibilityProcessSettings;
}
}
//internal FileFormatVersions MCTargetFormat
//{
// get
// {
// if (MarkupCompatibilityProcessSettings.ProcessMode == MarkupCompatibilityProcessMode.NoProcess)
// return (FileFormatVersions.Office2007 | FileFormatVersions.Office2010);
// else
// {
// return MarkupCompatibilityProcessSettings.TargetFileFormatVersions;
// }
// }
//}
//internal bool ProcessMCInWholePackage
//{
// get
// {
// return MarkupCompatibilityProcessSettings.ProcessMode == MarkupCompatibilityProcessMode.ProcessAllParts;
// }
//}
#endregion
#region Auto-Save functions
/// <summary>
/// Gets a flag that indicates whether the parts should be saved when disposed.
/// </summary>
public bool AutoSave
{
get
{
return OpenSettings.AutoSave;
}
}
private void SavePartContents()
{
OpenXmlPackagePartIterator iterator;
bool isAnyPartChanged;
if (this.FileOpenAccess == FileAccess.Read)
{
return; // do nothing if the package is open in read-only mode.
}
// When this.StrictTranslation is true, we ignore AutoSave to do the translation if isAnyPartChanged is true. That's the way to keep consistency.
if (!this.AutoSave && !this.StrictTranslation)
{
return; // do nothing if AutoSave is false.
}
// Traversal the whole package and save changed contents.
iterator = new OpenXmlPackagePartIterator(this);
isAnyPartChanged = false;
// If a part is in the state of 'loaded', something in the part should've been changed.
// When all the part is not loaded yet, we can skip saving all parts' contents and updating Package relationship types.
foreach (var part in iterator)
{
if (part.IsRootElementLoaded)
{
isAnyPartChanged = true;
break;
}
}
// We update parts and relationship types only when any one of the parts was changed (i.e. loaded).
if (isAnyPartChanged)
{
foreach (var part in iterator)
{
TrySavePartContent(part);
}
if (this.StrictTranslation)
{
RelationshipCollection relationshipCollection;
// For Package: Invoking UpdateRelationshipTypesInPackage() changes the relationship types in the package.
// We need to new PackageRelationshipPropertyCollection to read through the package contents right here
// because some operation may have updated the package before we get here.
relationshipCollection = new PackageRelationshipPropertyCollection(this._metroPackage);
relationshipCollection.UpdateRelationshipTypesInPackage();
}
}
}
// Check if the part content changed and save it if yes.
private static void TrySavePartContent(OpenXmlPart part)
{
Debug.Assert(part != null);
Debug.Assert(part.OpenXmlPackage != null);
// If StrictTranslation is true, we need to update the part anyway.
if (part.OpenXmlPackage.StrictTranslation)
{
RelationshipCollection relationshipCollection;
// For PackagePart: Invoking UpdateRelationshipTypesInPackage() changes the relationship types in the package part.
// We need to new PackageRelationshipPropertyCollection to read through the package part contents right here
// because some operation may have updated the package part before we get here.
relationshipCollection = new PackagePartRelationshipPropertyCollection(part.PackagePart);
relationshipCollection.UpdateRelationshipTypesInPackage();
// For ISO Strict documents, we read and save the part anyway to translate the contents. The contents are translated when PartRootElement is being loaded.
if (part.PartRootElement != null)
{
SavePartContent(part);
}
}
else
{
// For Transitional documents, we only save the 'changed' part.
if (IsPartContentChanged(part))
{
SavePartContent(part);
}
}
}
// Check if the content of a part is changed.
private static bool IsPartContentChanged(OpenXmlPart part)
{
Debug.Assert(part != null);
// If the root element of the part is loaded,
// consider the part changed and should be saved.
Debug.Assert(part.OpenXmlPackage != null);
if (!part.IsRootElementLoaded &&
part.OpenXmlPackage.MarkupCompatibilityProcessSettings.ProcessMode == MarkupCompatibilityProcessMode.ProcessAllParts)
{
if (part.PartRootElement != null)
{
return true;
}
}
return part.IsRootElementLoaded;
}
// Save the content of a part to its stream.
private static void SavePartContent(OpenXmlPart part)
{
Debug.Assert(part != null);
Debug.Assert(part.IsRootElementLoaded);
// Save PartRootElement to the part stream.
part.PartRootElement.Save();
}
#endregion
#region internal methods related main part
/// <summary>
/// Gets the relationship type of the main part.
/// </summary>
internal abstract string MainPartRelationshipType { get; }
/// <summary>
/// Gets or sets the content type of the main part of the package.
/// </summary>
internal string MainPartContentType
{
get
{
return _mainPartContentType;
}
set
{
if (this.IsValidMainPartContentType(value))
{
this._mainPartContentType = value;
}
else
{
throw new ArgumentOutOfRangeException(ExceptionMessages.InvalidMainPartContentType);
}
}
}
/// <summary>
/// Gets the list of valid content types for the main part.
/// </summary>
internal abstract ICollection<string> ValidMainPartContentTypes { get; }
/// <summary>
/// Determines whether the content type is valid for the main part of the package.
/// </summary>
/// <param name="contentType">The content type.</param>
/// <returns>Returns true if the content type is valid.</returns>
internal bool IsValidMainPartContentType(string contentType)
{
return ValidMainPartContentTypes.Contains(contentType);
}
/// <summary>
/// Changes the type of the document.
/// </summary>
/// <typeparam name="T">The type of the document's main part.</typeparam>
/// <remarks>The MainDocumentPart will be changed.</remarks>
internal void ChangeDocumentTypeInternal<T>() where T : OpenXmlPart
{
ThrowIfObjectDisposed();
T mainPart = this.GetSubPartOfType<T>();
MemoryStream memoryStream = null;
ExtendedPart tempPart = null;
Dictionary<string, OpenXmlPart> childParts = new Dictionary<string, OpenXmlPart>();
ReferenceRelationship[] referenceRelationships;
try
{
// read the content to local string
using (Stream mainPartStream = mainPart.GetStream())
{
if (mainPartStream.Length > Int32.MaxValue)
{
throw new OpenXmlPackageException(ExceptionMessages.DocumentTooBig);
}
memoryStream = new MemoryStream(Convert.ToInt32(mainPartStream.Length));
OpenXmlPart.CopyStream(mainPartStream, memoryStream);
}
//
tempPart = this.AddExtendedPart(@"http://temp", this.MainPartContentType, @".xml");
foreach (KeyValuePair<string, OpenXmlPart> idPartPair in mainPart.ChildrenParts)
{
childParts.Add(idPartPair.Key, idPartPair.Value);
}
referenceRelationships = mainPart.ReferenceRelationshipList.ToArray();
}
catch (OpenXmlPackageException e)
{
throw new OpenXmlPackageException(ExceptionMessages.CannotChangeDocumentType, e);
}
#if FEATURE_SYSTEMEXCEPTION
catch (SystemException e)
{
throw new OpenXmlPackageException(ExceptionMessages.CannotChangeDocumentType, e);
}
#endif
try
{
Uri uri = mainPart.Uri;
string id = this.GetIdOfPart(mainPart);
// remove the old part
this.ChildrenParts.Remove(id);
this.DeleteRelationship(id);
mainPart.Destroy();
// create new part
T newMainPart = CreateInstance<T>();
// do not call this.InitPart( ). copy the code here
newMainPart.CreateInternal2(this, null, this.MainPartContentType, uri);
// add it and get the id
string relationshipId = this.AttachChild(newMainPart, id);
this.ChildrenParts.Add(relationshipId, newMainPart);
// copy the stream back
memoryStream.Position = 0;
newMainPart.FeedData(memoryStream);
// add back all relationships
foreach (KeyValuePair<string, OpenXmlPart> idPartPair in childParts)
{
// just call AttachChild( ) is OK. No need to call AddPart( ... )
newMainPart.AttachChild(idPartPair.Value, idPartPair.Key);
newMainPart.ChildrenParts.Add(idPartPair);
}
foreach (ExternalRelationship externalRel in referenceRelationships.OfType<ExternalRelationship>())
{
newMainPart.AddExternalRelationship(externalRel.RelationshipType, externalRel.Uri, externalRel.Id);
}
foreach (HyperlinkRelationship hyperlinkRel in referenceRelationships.OfType<HyperlinkRelationship>())
{
newMainPart.AddHyperlinkRelationship(hyperlinkRel.Uri, hyperlinkRel.IsExternal, hyperlinkRel.Id);
}
foreach (DataPartReferenceRelationship dataPartReference in referenceRelationships.OfType<DataPartReferenceRelationship>())
{
newMainPart.AddDataPartReferenceRelationship(dataPartReference);
}
// delete the temp part
id = this.GetIdOfPart(tempPart);
this.ChildrenParts.Remove(id);
this.DeleteRelationship(id);
tempPart.Destroy();
}
catch (OpenXmlPackageException e)
{
throw new OpenXmlPackageException(ExceptionMessages.CannotChangeDocumentType, e);
}
#if FEATURE_SYSTEMEXCEPTION
catch (SystemException e)
{
throw new OpenXmlPackageException(ExceptionMessages.CannotChangeDocumentTypeSerious, e);
}
#endif
}
#endregion
#region internal methods
// internal abstract IExtensionPartFactory ExtensionPartFactory { get; }
// cannot use generic, at it will emit error
// Compiler Error CS0310
// The type 'typename' must have a public parameter less constructor in order to use it as parameter 'parameter' in the generic type or method 'generic'
internal sealed override OpenXmlPart NewPart(string relationshipType, string contentType)
{
ThrowIfObjectDisposed();
if (contentType == null)
{
throw new ArgumentNullException(nameof(contentType));
}
PartConstraintRule partConstraintRule;
if (GetPartConstraint().TryGetValue(relationshipType, out partConstraintRule))
{
if (!partConstraintRule.MaxOccursGreatThanOne)
{
if (this.GetSubPart(relationshipType) != null)
{
// already have one, cannot add new one.
throw new InvalidOperationException();
}
}
OpenXmlPart child = CreateOpenXmlPart(relationshipType);
child.CreateInternal(this, null, contentType, null);
// add it and get the id
string relationshipId = this.AttachChild(child);
this.ChildrenParts.Add(relationshipId, child);
return child;
}
throw new ArgumentOutOfRangeException(nameof(relationshipType));
}
internal sealed override OpenXmlPackage InternalOpenXmlPackage
{
get { return this; }
}
internal sealed override OpenXmlPart ThisOpenXmlPart
{
get { return null; }
}
// find all reachable parts from the package root, the dictionary also used for cycle reference defense
internal sealed override void FindAllReachableParts(IDictionary<OpenXmlPart, bool> reachableParts)
{
ThrowIfObjectDisposed();
if (reachableParts == null)
{
throw new ArgumentNullException(nameof(reachableParts));
}
foreach (OpenXmlPart part in this.ChildrenParts.Values)
{
if (!reachableParts.ContainsKey(part))
{
part.FindAllReachableParts(reachableParts);
}
}
}
internal sealed override void DeleteRelationship(string id)
{
ThrowIfObjectDisposed();
this.Package.DeleteRelationship(id);
}
internal sealed override PackageRelationship CreateRelationship(Uri targetUri, TargetMode targetMode, string relationshipType)
{
ThrowIfObjectDisposed();
return this.Package.CreateRelationship(targetUri, targetMode, relationshipType);
}
internal sealed override PackageRelationship CreateRelationship(Uri targetUri, TargetMode targetMode, string relationshipType, string id)
{
ThrowIfObjectDisposed();
return this.Package.CreateRelationship(targetUri, targetMode, relationshipType, id);
}
// create the metro part in the package with the CompressionOption
internal PackagePart CreateMetroPart(Uri partUri, string contentType)
{
return this.Package.CreatePart(partUri, contentType, this.CompressionOption);
}
// default package validation event handler
static void DefaultValidationEventHandler(Object sender, OpenXmlPackageValidationEventArgs e)
{
OpenXmlPackageException exception = new OpenXmlPackageException(ExceptionMessages.ValidationException);
exception.Data.Add("OpenXmlPackageValidationEventArgs", e);
throw exception;
}
#endregion
#region methods on DataPart
private static bool IsOrphanDataPart(DataPart dataPart)
{
return !dataPart.GetDataPartReferenceRelationships().Any();
}
/// <summary>
/// Deletes all DataParts that are not referenced by any media, audio, or video reference relationships.
/// </summary>
private void DeleteUnusedDataPartOnClose()
{
if (this._dataPartList.Count > 0)
{
HashSet<DataPart> dataPartSet = new HashSet<DataPart>();
foreach (var dataPart in this.DataParts)
{
dataPartSet.Add(dataPart);
}
// first, see if there are any reference in package level.
foreach (var dataPartReferenceRelationship in this.DataPartReferenceRelationships)
{
dataPartSet.Remove(dataPartReferenceRelationship.DataPart);
if (dataPartSet.Count == 0)
{
// No more DataPart in the set. All DataParts are referenced somewhere.
return;
}
}
// for each part in the package, check the DataPartReferenceRelationships.
OpenXmlPackagePartIterator partIterator = new OpenXmlPackagePartIterator(this);
foreach (var openXmlPart in partIterator)
{
foreach (var dataPartReferenceRelationship in openXmlPart.DataPartReferenceRelationships)
{
dataPartSet.Remove(dataPartReferenceRelationship.DataPart);
if (dataPartSet.Count == 0)
{
// No more DataPart in the set. All DataParts are referenced somethwherr.
return;
}
}
}
//
foreach (var dataPart in dataPartSet)
{
// delete the part from the package
dataPart.Destroy();
this._dataPartList.Remove(dataPart);
}
}
}
/// <summary>
/// Finds the DataPart that has the specified part URI.
/// </summary>
/// <param name="partUri">The part URI.</param>
/// <returns>Returns null if there is no DataPart with the specified URI.</returns>
internal DataPart FindDataPart(Uri partUri)
{
foreach (var dataPart in this.DataParts)
{
if (dataPart.Uri == partUri)
{
return dataPart;
}
}
return null;
}
internal DataPart AddDataPartToList(DataPart dataPart)
{
this._dataPartList.AddLast(dataPart);
return dataPart;
}
#endregion
internal class PartUriHelper
{
private Dictionary<string, int> _sequenceNumbers = new Dictionary<string, int>(20);
private Dictionary<string, int> _reservedUri = new Dictionary<string, int>();
public PartUriHelper()
{
}
private bool IsReservedUri(Uri uri)
{
string uriString = uri.OriginalString.ToUpperInvariant();
return this._reservedUri.ContainsKey(uriString);
}
internal void AddToReserveUri(Uri partUri)
{
string uriString = partUri.OriginalString.ToUpperInvariant();
this._reservedUri.Add(uriString, 0);
}
internal void ReserveUri(string contentType, Uri partUri)
{
GetNextSequenceNumber(contentType);
this.AddToReserveUri(PackUriHelper.GetNormalizedPartUri(partUri));
}
internal Uri GetUniquePartUri(string contentType, Uri parentUri, string targetPath, string targetName, string targetExt)
{
Uri partUri;
do
{
string sequenceNumber = this.GetNextSequenceNumber(contentType);
string path = Path.Combine(targetPath, targetName + sequenceNumber + targetExt);
Uri uri = new Uri(path, UriKind.RelativeOrAbsolute);
partUri = PackUriHelper.ResolvePartUri(parentUri, uri);
// partUri = PackUriHelper.GetNormalizedPartUri(PackUriHelper.CreatePartUri(uri));
} while (this.IsReservedUri(partUri));
this.AddToReserveUri(partUri);
// do not need to add to the _existedNames
return partUri;
}
internal Uri GetUniquePartUri(string contentType, Uri parentUri, Uri targetUri)
{
Uri partUri;
partUri = PackUriHelper.ResolvePartUri(parentUri, targetUri);
if (this.IsReservedUri(partUri))
{
// already have one, create new
string targetPath = ".";
string targetName = Path.GetFileNameWithoutExtension(targetUri.OriginalString);
string targetExt = Path.GetExtension(targetUri.OriginalString);
partUri = GetUniquePartUri(contentType, partUri, targetPath, targetName, targetExt);
}
else
{
// not used, can use it.
this.AddToReserveUri(partUri);
}
return partUri;
}
private string GetNextSequenceNumber(string contentType)
{
if (this._sequenceNumbers.ContainsKey(contentType))
{
this._sequenceNumbers[contentType] += 1;
// use the default read-only NumberFormatInfo that is culture-independent (invariant).
// return this._sequenceNumbers[contentType].ToString(NumberFormatInfo.InvariantInfo);
// Let's use the number string in hex
return Convert.ToString(this._sequenceNumbers[contentType], 16);
}
else
{
this._sequenceNumbers.Add(contentType, 1);
return "";
}
}
}
#region saving and cloning
#region saving
private readonly object _saveAndCloneLock = new object();
/// <summary>
/// Saves the contents of all parts and relationships that are contained
/// in the OpenXml package, if FileOpenAccess is ReadWrite.
/// </summary>
public void Save()
{
ThrowIfObjectDisposed();
if (FileOpenAccess == FileAccess.ReadWrite)
{
lock (_saveAndCloneLock)
{
SavePartContents();
// TODO: Revisit.
// Package.Flush();
}
}
}
/// <summary>
/// Saves the contents of all parts and relationships that are contained
/// in the OpenXml package to the specified file. Opens the saved document
/// using the same settings that were used to open this OpenXml package.
/// </summary>
/// <remarks>
/// Calling SaveAs(string) is exactly equivalent to calling Clone(string).
/// This method is essentially provided for convenience.
/// </remarks>
/// <param name="path">The path and file name of the target document.</param>
/// <returns>The cloned OpenXml package</returns>
public OpenXmlPackage SaveAs(string path)
{
return Clone(path);
}
#endregion saving
#region Default clone method
/// <summary>
/// Creates an editable clone of this OpenXml package, opened on a
/// <see cref="MemoryStream"/> with expandable capacity and using
/// default OpenSettings.
/// </summary>
/// <returns>The cloned OpenXml package.</returns>
public OpenXmlPackage Clone()
{
return Clone(new MemoryStream(), true, new OpenSettings());
}
#endregion Default clone method
#region Stream-based cloning
/// <summary>
/// Creates a clone of this OpenXml package, opened on the given stream.
/// The cloned OpenXml package is opened with the same settings, i.e.,
/// FileOpenAccess and OpenSettings, as this OpenXml package.
/// </summary>
/// <param name="stream">The IO stream on which to open the OpenXml package.</param>
/// <returns>The cloned OpenXml package.</returns>
public OpenXmlPackage Clone(Stream stream)
{
return Clone(stream, FileOpenAccess == FileAccess.ReadWrite, OpenSettings);
}
/// <summary>
/// Creates a clone of this OpenXml package, opened on the given stream.
/// The cloned OpenXml package is opened with the same OpenSettings as
/// this OpenXml package.
/// </summary>
/// <param name="stream">The IO stream on which to open the OpenXml package.</param>
/// <param name="isEditable">In ReadWrite mode. False for Read only mode.</param>
/// <returns>The cloned OpenXml package.</returns>
public OpenXmlPackage Clone(Stream stream, bool isEditable)
{
return Clone(stream, isEditable, OpenSettings);
}
/// <summary>
/// Creates a clone of this OpenXml package, opened on the given stream.
/// </summary>
/// <param name="stream">The IO stream on which to open the OpenXml package.</param>
/// <param name="isEditable">In ReadWrite mode. False for Read only mode.</param>
/// <param name="openSettings">The advanced settings for opening a document.</param>
/// <returns>The cloned OpenXml package.</returns>
public OpenXmlPackage Clone(Stream stream, bool isEditable, OpenSettings openSettings)
{
if (stream == null)
throw new ArgumentNullException(nameof(stream));
// Use this OpenXml package's OpenSettings if none are provided.
// This is more in line with cloning than providing the default
// OpenSettings, i.e., unless the caller explicitly specifies
// something, we'll later open the clone with this OpenXml
// package's OpenSettings.
if (openSettings == null)
openSettings = OpenSettings;
lock (_saveAndCloneLock)
{
// Save the contents of all parts and relationships that are contained
// in the OpenXml package to make sure we clone a consistent state.
// This will also invoke ThrowIfObjectDisposed(), so we don't need
// to call it here.
Save();
// Create new OpenXmlPackage backed by stream. Next, copy all document
// parts (AddPart will copy the parts and their children in a recursive
// fashion) and close/dispose the document (by leaving the scope of the
// using statement). Finally, reopen the clone from the MemoryStream.
// This way, writing the stream to a file, for example, directly after
// returning from this method will not lead to issues with corrupt files
// and a FileFormatException ("Compressed part has inconsistent data length")
// thrown within OpenXmlPackage.OpenCore(string, bool) by the
// this._metroPackage = Package.Open(path, ...);
// assignment.
using (OpenXmlPackage clone = CreateClone(stream))
{
foreach (var part in this.Parts)
clone.AddPart(part.OpenXmlPart, part.RelationshipId);
}
return OpenClone(stream, isEditable, openSettings);
}
}
/// <summary>
/// Creates a new OpenXmlPackage on the given stream.
/// </summary>
/// <param name="stream">The stream on which the concrete OpenXml package will be created.</param>
/// <returns>A new instance of OpenXmlPackage.</returns>
protected abstract OpenXmlPackage CreateClone(Stream stream);
/// <summary>
/// Opens the cloned OpenXml package on the given stream.
/// </summary>
/// <param name="stream">The stream on which the cloned OpenXml package will be opened.</param>
/// <param name="isEditable">In ReadWrite mode. False for Read only mode.</param>
/// <param name="openSettings">The advanced settings for opening a document.</param>
/// <returns>A new instance of OpenXmlPackage.</returns>
protected abstract OpenXmlPackage OpenClone(Stream stream, bool isEditable, OpenSettings openSettings);
#endregion Stream-based cloning
#region File-based cloning
/// <summary>
/// Creates a clone of this OpenXml package opened from the given file
/// (which will be created by cloning this OpenXml package).
/// The cloned OpenXml package is opened with the same settings, i.e.,
/// FileOpenAccess and OpenSettings, as this OpenXml package.
/// </summary>
/// <param name="path">The path and file name of the target document.</param>
/// <returns>The cloned document.</returns>
public OpenXmlPackage Clone(string path)
{
return Clone(path, FileOpenAccess == FileAccess.ReadWrite, OpenSettings);
}
/// <summary>
/// Creates a clone of this OpenXml package opened from the given file
/// (which will be created by cloning this OpenXml package).
/// The cloned OpenXml package is opened with the same OpenSettings as
/// this OpenXml package.
/// </summary>
/// <param name="path">The path and file name of the target document.</param>
/// <param name="isEditable">In ReadWrite mode. False for Read only mode.</param>
/// <returns>The cloned document.</returns>
public OpenXmlPackage Clone(string path, bool isEditable)
{
return Clone(path, isEditable, OpenSettings);
}
/// <summary>
/// Creates a clone of this OpenXml package opened from the given file (which
/// will be created by cloning this OpenXml package).
/// </summary>
/// <param name="path">The path and file name of the target document.</param>
/// <param name="isEditable">In ReadWrite mode. False for Read only mode.</param>
/// <param name="openSettings">The advanced settings for opening a document.</param>
/// <returns>The cloned document.</returns>
public OpenXmlPackage Clone(string path, bool isEditable, OpenSettings openSettings)
{
if (path == null)
throw new ArgumentNullException(nameof(path));
// Use this OpenXml package's OpenSettings if none are provided.
// This is more in line with cloning than providing the default
// OpenSettings, i.e., unless the caller explicitly specifies
// something, we'll later open the clone with this OpenXml
// package's OpenSettings.
if (openSettings == null)
openSettings = OpenSettings;
lock (_saveAndCloneLock)
{
// Save the contents of all parts and relationships that are contained
// in the OpenXml package to make sure we clone a consistent state.
// This will also invoke ThrowIfObjectDisposed(), so we don't need
// to call it here.
Save();
// Use the same approach as for the streams-based cloning, i.e., close
// and reopen the document.
using (OpenXmlPackage clone = CreateClone(path))
{
foreach (var part in this.Parts)
clone.AddPart(part.OpenXmlPart, part.RelationshipId);
}
return OpenClone(path, isEditable, openSettings);
}
}
/// <summary>
/// Creates a new OpenXml package on the given file.
/// </summary>
/// <param name="path">The path and file name of the target OpenXml package.</param>
/// <returns>A new instance of OpenXmlPackage.</returns>
protected abstract OpenXmlPackage CreateClone(string path);
/// <summary>
/// Opens the cloned OpenXml package on the given file.
/// </summary>
/// <param name="path">The path and file name of the target OpenXml package.</param>
/// <param name="isEditable">In ReadWrite mode. False for Read only mode.</param>
/// <param name="openSettings">The advanced settings for opening a document.</param>
/// <returns>A new instance of OpenXmlPackage.</returns>
protected abstract OpenXmlPackage OpenClone(string path, bool isEditable, OpenSettings openSettings);
#endregion File-based cloning
#region Package-based cloning
/// <summary>
/// Creates a clone of this OpenXml package, opened on the specified instance
/// of Package. The clone will be opened with the same OpenSettings as this
/// OpenXml package.
/// </summary>
/// <param name="package">The specified instance of Package.</param>
/// <returns>The cloned OpenXml package.</returns>
public OpenXmlPackage Clone(Package package)
{
return Clone(package, OpenSettings);
}
/// <summary>
/// Creates a clone of this OpenXml package, opened on the specified instance
/// of Package.
/// </summary>
/// <param name="package">The specified instance of Package.</param>
/// <param name="openSettings">The advanced settings for opening a document.</param>
/// <returns>The cloned OpenXml package.</returns>
public OpenXmlPackage Clone(Package package, OpenSettings openSettings)
{
if (package == null)
throw new ArgumentNullException(nameof(package));
// Use this OpenXml package's OpenSettings if none are provided.
// This is more in line with cloning than providing the default
// OpenSettings, i.e., unless the caller explicitly specifies
// something, we'll later open the clone with this OpenXml
// package's OpenSettings.
if (openSettings == null)
openSettings = OpenSettings;
lock (_saveAndCloneLock)
{
// Save the contents of all parts and relationships that are contained
// in the OpenXml package to make sure we clone a consistent state.
// This will also invoke ThrowIfObjectDisposed(), so we don't need
// to call it here.
Save();
// Create a new OpenXml package, copy this package's parts, and flush.
// This is different from the stream and file-based cloning, because
// we don't close the package here (whereas it will be closed in
// stream and file-based cloning to make sure the underlying stream
// or file can be read without any corruption issues directly after
// having cloned the OpenXml package).
OpenXmlPackage clone = CreateClone(package);
foreach (var part in this.Parts)
{
clone.AddPart(part.OpenXmlPart, part.RelationshipId);
}
// TODO: Revisit.
// package.Flush();
// Configure OpenSettings.
clone.OpenSettings.AutoSave = openSettings.AutoSave;
clone.OpenSettings.MarkupCompatibilityProcessSettings.ProcessMode = openSettings.MarkupCompatibilityProcessSettings.ProcessMode;
clone.OpenSettings.MarkupCompatibilityProcessSettings.TargetFileFormatVersions = openSettings.MarkupCompatibilityProcessSettings.TargetFileFormatVersions;
clone.MaxCharactersInPart = openSettings.MaxCharactersInPart;
return clone;
}
}
/// <summary>
/// Creates a new instance of OpenXmlPackage on the specified instance
/// of Package.
/// </summary>
/// <param name="package">The specified instance of Package.</param>
/// <returns>A new instance of OpenXmlPackage.</returns>
protected abstract OpenXmlPackage CreateClone(Package package);
#endregion Package-based cloning
#endregion saving and cloning
#region Flat OPC
private static readonly XNamespace pkg = "http://schemas.microsoft.com/office/2006/xmlPackage";
private static readonly XNamespace rel = "http://schemas.openxmlformats.org/package/2006/relationships";
/// <summary>
/// Converts an OpenXml package in OPC format to string in Flat OPC format.
/// </summary>
/// <returns>The OpenXml package in Flat OPC format.</returns>
public string ToFlatOpcString()
{
return ToFlatOpcDocument().ToString();
}
/// <summary>
/// Converts an OpenXml package in OPC format to an <see cref="XDocument"/>
/// in Flat OPC format.
/// </summary>
/// <returns>The OpenXml package in Flat OPC format.</returns>
public abstract XDocument ToFlatOpcDocument();
/// <summary>
/// Converts an OpenXml package in OPC format to an <see cref="XDocument"/>
/// in Flat OPC format.
/// </summary>
/// <param name="instruction">The processing instruction.</param>
/// <returns>The OpenXml package in Flat OPC format.</returns>
protected XDocument ToFlatOpcDocument(XProcessingInstruction instruction)
{
// Save the contents of all parts and relationships that are contained
// in the OpenXml package to make sure we convert a consistent state.
// This will also invoke ThrowIfObjectDisposed(), so we don't need
// to call it here.
Save();
// Create an XML document with a standalone declaration, processing
// instruction (if not null), and a package root element with a
// namespace declaration and one child element for each part.
return new XDocument(
new XDeclaration("1.0", "UTF-8", "yes"),
instruction,
new XElement(
pkg + "package",
new XAttribute(XNamespace.Xmlns + "pkg", pkg.ToString()),
Package.GetParts().Select(part => GetContentsAsXml(part))));
}
/// <summary>
/// Gets the <see cref="PackagePart"/>'s contents as an <see cref="XElement"/>.
/// </summary>
/// <param name="part">The package part.</param>
/// <returns>The corresponding <see cref="XElement"/>.</returns>
private static XElement GetContentsAsXml(PackagePart part)
{
if (part.ContentType.EndsWith("xml"))
{
using (Stream stream = part.GetStream())
using (StreamReader streamReader = new StreamReader(stream))
using (XmlReader xmlReader = XmlReader.Create(streamReader))
return new XElement(pkg + "part",
new XAttribute(pkg + "name", part.Uri),
new XAttribute(pkg + "contentType", part.ContentType),
new XElement(pkg + "xmlData", XElement.Load(xmlReader)));
}
else
{
using (Stream stream = part.GetStream())
using (BinaryReader binaryReader = new BinaryReader(stream))
{
int len = (int)binaryReader.BaseStream.Length;
byte[] byteArray = binaryReader.ReadBytes(len);
// The following expression creates the base64String, then chunks
// it to lines of 76 characters long.
string base64String = System.Convert.ToBase64String(byteArray)
.Select((c, i) => new { Character = c, Chunk = i / 76 })
.GroupBy(c => c.Chunk)
.Aggregate(
new StringBuilder(),
(s, i) =>
s.Append(
i.Aggregate(
new StringBuilder(),
(seed, it) => seed.Append(it.Character),
sb => sb.ToString())).Append(Environment.NewLine),
s => s.ToString());
return new XElement(pkg + "part",
new XAttribute(pkg + "name", part.Uri),
new XAttribute(pkg + "contentType", part.ContentType),
new XAttribute(pkg + "compression", "store"),
new XElement(pkg + "binaryData", base64String));
}
}
}
/// <summary>
/// Converts an <see cref="XDocument"/> in Flat OPC format to an OpenXml package
/// stored on a <see cref="Stream"/>.
/// </summary>
/// <param name="document">The document in Flat OPC format.</param>
/// <param name="stream">The <see cref="Stream"/> on which to store the OpenXml package.</param>
/// <returns>The <see cref="Stream"/> containing the OpenXml package.</returns>
protected static Stream FromFlatOpcDocumentCore(XDocument document, Stream stream)
{
using (Package package = Package.Open(stream, FileMode.Create, FileAccess.ReadWrite))
{
FromFlatOpcDocumentCore(document, package);
}
return stream;
}
/// <summary>
/// Converts an <see cref="XDocument"/> in Flat OPC format to an OpenXml package
/// stored in a file.
/// </summary>
/// <param name="document">The document in Flat OPC format.</param>
/// <param name="path">The path and file name of the file in which to store the OpenXml package.</param>
/// <returns>The path and file name of the file containing the OpenXml package.</returns>
protected static string FromFlatOpcDocumentCore(XDocument document, string path)
{
using (Package package = Package.Open(path, FileMode.Create, FileAccess.ReadWrite, FileShare.None))
{
FromFlatOpcDocumentCore(document, package);
}
return path;
}
/// <summary>
/// Converts an <see cref="XDocument"/> in Flat OPC format to an OpenXml package
/// stored in a <see cref="Package"/>.
/// </summary>
/// <param name="document">The document in Flat OPC format.</param>
/// <param name="package">The <see cref="Package"/> in which to store the OpenXml package.</param>
/// <returns>The <see cref="Package"/> containing the OpenXml package.</returns>
protected static Package FromFlatOpcDocumentCore(XDocument document, Package package)
{
// Add all parts (but not relationships).
foreach (var xmlPart in document.Root
.Elements()
.Where(p =>
(string)p.Attribute(pkg + "contentType") !=
"application/vnd.openxmlformats-package.relationships+xml"))
{
string name = (string)xmlPart.Attribute(pkg + "name");
string contentType = (string)xmlPart.Attribute(pkg + "contentType");
if (contentType.EndsWith("xml"))
{
Uri uri = new Uri(name, UriKind.Relative);
PackagePart part = package.CreatePart(uri, contentType, CompressionOption.SuperFast);
using (Stream stream = part.GetStream(FileMode.Create))
using (XmlWriter xmlWriter = XmlWriter.Create(stream))
xmlPart.Element(pkg + "xmlData")
.Elements()
.First()
.WriteTo(xmlWriter);
}
else
{
Uri uri = new Uri(name, UriKind.Relative);
PackagePart part = package.CreatePart(uri, contentType, CompressionOption.SuperFast);
using (Stream stream = part.GetStream(FileMode.Create))
using (BinaryWriter binaryWriter = new BinaryWriter(stream))
{
string base64StringInChunks = (string)xmlPart.Element(pkg + "binaryData");
char[] base64CharArray = base64StringInChunks
.Where(c => c != '\r' && c != '\n').ToArray();
byte[] byteArray =
System.Convert.FromBase64CharArray(
base64CharArray, 0, base64CharArray.Length);
binaryWriter.Write(byteArray);
}
}
}
foreach (var xmlPart in document.Root.Elements())
{
string name = (string)xmlPart.Attribute(pkg + "name");
string contentType = (string)xmlPart.Attribute(pkg + "contentType");
if (contentType == "application/vnd.openxmlformats-package.relationships+xml")
{
if (name == "/_rels/.rels")
{
// Add the package level relationships.
foreach (XElement xmlRel in xmlPart.Descendants(rel + "Relationship"))
{
string id = (string)xmlRel.Attribute("Id");
string type = (string)xmlRel.Attribute("Type");
string target = (string)xmlRel.Attribute("Target");
string targetMode = (string)xmlRel.Attribute("TargetMode");
if (targetMode == "External")
package.CreateRelationship(
new Uri(target, UriKind.Absolute),
TargetMode.External, type, id);
else
package.CreateRelationship(
new Uri(target, UriKind.Relative),
TargetMode.Internal, type, id);
}
}
else
{
// Add part level relationships.
string directory = name.Substring(0, name.IndexOf("/_rels"));
string relsFilename = name.Substring(name.LastIndexOf('/'));
string filename = relsFilename.Substring(0, relsFilename.IndexOf(".rels"));
PackagePart fromPart = package.GetPart(new Uri(directory + filename, UriKind.Relative));
foreach (XElement xmlRel in xmlPart.Descendants(rel + "Relationship"))
{
string id = (string)xmlRel.Attribute("Id");
string type = (string)xmlRel.Attribute("Type");
string target = (string)xmlRel.Attribute("Target");
string targetMode = (string)xmlRel.Attribute("TargetMode");
if (targetMode == "External")
fromPart.CreateRelationship(
new Uri(target, UriKind.Absolute),
TargetMode.External, type, id);
else
fromPart.CreateRelationship(
new Uri(target, UriKind.Relative),
TargetMode.Internal, type, id);
}
}
}
}
// Save contents of all parts and relationships contained in package.
package.Flush();
return package;
}
#endregion Flat OPC
}
/// <summary>
/// Specifies event handlers that will handle OpenXmlPackage validation events and the OpenXmlPackageValidationEventArgs.
/// </summary>
// Building on Travis CI failed, saying that ObsoleteAttributeMessages does not contain a definition
// for 'ObsoleteV1ValidationFunctionality'. Thus, we've replaced the member with its value.
[Obsolete("This functionality is obsolete and will be removed from future version release. Please see OpenXmlValidator class for supported validation functionality.", false)]
public class OpenXmlPackageValidationSettings
{
private EventHandler<OpenXmlPackageValidationEventArgs> valEventHandler;
/// <summary>
/// Gets the event handler.
/// </summary>
/// <returns></returns>
internal EventHandler<OpenXmlPackageValidationEventArgs> GetEventHandler()
{
return this.valEventHandler;
}
/// <summary>
/// Represents the callback method that will handle OpenXmlPackage validation events and the OpenXmlPackageValidationEventArgs.
/// </summary>
public event EventHandler<OpenXmlPackageValidationEventArgs> EventHandler
{
add
{
this.valEventHandler = (EventHandler<OpenXmlPackageValidationEventArgs>)Delegate.Combine(this.valEventHandler, value);
}
remove
{
this.valEventHandler = (EventHandler<OpenXmlPackageValidationEventArgs>)Delegate.Remove(this.valEventHandler, value);
}
}
/// <summary>
/// Gets or sets the file format version that the validation is targeting.
/// </summary>
internal FileFormatVersions FileFormat
{
get;
set;
}
}
/// <summary>
/// Represents the Open XML package validation events.
/// </summary>
[SerializableAttribute]
[Obsolete(ObsoleteAttributeMessages.ObsoleteV1ValidationFunctionality, false)]
public sealed class OpenXmlPackageValidationEventArgs : EventArgs
{
private string _message;
private string _partClassName;
[NonSerializedAttribute]
private OpenXmlPart _childPart;
[NonSerializedAttribute]
private OpenXmlPart _parentPart;
internal OpenXmlPackageValidationEventArgs()
{
}
/// <summary>
/// Gets the message string of the event.
/// </summary>
public string Message
{
get
{
if (this._message == null && this.MessageId != null)
{
return ExceptionMessages.ResourceManager.GetString(this.MessageId);
}
else
{
return this._message;
}
}
set
{
this._message = value;
}
}
/// <summary>
/// Gets the class name of the part.
/// </summary>
public string PartClassName
{
get { return _partClassName; }
internal set { _partClassName = value; }
}
/// <summary>
/// Gets the part that caused the event.
/// </summary>
public OpenXmlPart SubPart
{
get { return _childPart; }
internal set { _childPart = value; }
}
/// <summary>
/// Gets the part in which to process the validation.
/// </summary>
public OpenXmlPart Part
{
get { return _parentPart; }
internal set { _parentPart = value; }
}
internal string MessageId
{
get;
set;
}
/// <summary>
/// The DataPartReferenceRelationship that caused the event.
/// </summary>
internal DataPartReferenceRelationship DataPartReferenceRelationship
{
get;
set;
}
}
/// <summary>
/// Represents an Open XML package exception class for errors.
/// </summary>
[SerializableAttribute]
public sealed class OpenXmlPackageException : Exception
{
/// <summary>
/// Initializes a new instance of the OpenXmlPackageException class.
/// </summary>
public OpenXmlPackageException()
: base()
{
}
/// <summary>
/// Initializes a new instance of the OpenXmlPackageException class using the supplied error message.
/// </summary>
/// <param name="message">The message that describes the error. </param>
public OpenXmlPackageException(string message)
: base(message)
{
}
#if FEATURE_SERIALIZATION
/// <summary>
/// Initializes a new instance of the OpenXmlPackageException class using the supplied serialized data.
/// </summary>
/// <param name="info">The serialized object data about the exception being thrown.</param>
/// <param name="context">The contextual information about the source or destination.</param>
private OpenXmlPackageException(SerializationInfo info, StreamingContext context)
: base(info, context)
{
}
#endif
/// <summary>
/// Initializes a new instance of the OpenXmlPackageException class using the supplied error message and a reference to the inner exception that caused the current exception.
/// </summary>
/// <param name="message">The error message that indicates the reason for the exception.</param>
/// <param name="innerException">The exception that is the cause of the current exception, or a null reference (Nothing in Visual Basic) if no inner exception is specified.</param>
public OpenXmlPackageException(string message, Exception innerException)
: base(message, innerException)
{
}
}
/// <summary>
/// Represents the settings when opening a document.
/// </summary>
public class OpenSettings
{
bool? autoSave;
MarkupCompatibilityProcessSettings _mcSettings;
/// <summary>
/// Gets or sets a value that indicates whether or not to auto save document modifications.
/// The default value is true.
/// </summary>
public bool AutoSave
{
get
{
if (autoSave == null)
{
return true;
}
return (bool)autoSave;
}
set
{
autoSave = value;
}
}
/// <summary>
/// Gets or sets the value of the markup compatibility processing mode.
/// </summary>
public MarkupCompatibilityProcessSettings MarkupCompatibilityProcessSettings
{
get
{
if (_mcSettings == null)
_mcSettings = new MarkupCompatibilityProcessSettings(MarkupCompatibilityProcessMode.NoProcess, FileFormatVersions.Office2007);
return _mcSettings;
}
set
{
_mcSettings = value;
}
}
/// <summary>
/// Gets or sets a value that indicates the maximum number of allowable characters in an Open XML part. A zero (0) value indicates that there are no limits on the size of the part. A non-zero value specifies the maximum size, in characters.
/// </summary>
/// <remarks>
/// This property allows you to mitigate denial of service attacks where the attacker submits a package with an extremely large Open XML part. By limiting the size of the part, you can detect the attack and recover reliably.
/// </remarks>
public long MaxCharactersInPart { get; set; }
}
/// <summary>
/// Represents markup compatibility processing settings.
/// </summary>
public class MarkupCompatibilityProcessSettings
{
/// <summary>
/// Gets the markup compatibility process mode.
/// </summary>
public MarkupCompatibilityProcessMode ProcessMode { get; internal set; }
/// <summary>
/// Gets the target file format versions.
/// </summary>
public FileFormatVersions TargetFileFormatVersions { get; internal set; }
/// <summary>
/// Creates a MarkupCompatibilityProcessSettings object using the supplied process mode and file format versions.
/// </summary>
/// <param name="processMode">The process mode.</param>
/// <param name="targetFileFormatVersions">The file format versions. This parameter is ignored if the value is NoProcess.</param>
public MarkupCompatibilityProcessSettings(MarkupCompatibilityProcessMode processMode, FileFormatVersions targetFileFormatVersions)
{
ProcessMode = processMode;
TargetFileFormatVersions = targetFileFormatVersions;
}
private MarkupCompatibilityProcessSettings()
{
ProcessMode = MarkupCompatibilityProcessMode.NoProcess;
TargetFileFormatVersions = FileFormatVersions.Office2007;
}
}
/// <summary>
/// Specifies the mode in which to process the markup compatibility tags in the document.
/// </summary>
public enum MarkupCompatibilityProcessMode
{
/// <summary>
/// Do not process MarkupCompatibility tags.
/// </summary>
NoProcess = 0,
/// <summary>
/// Process the loaded parts.
/// </summary>
ProcessLoadedPartsOnly,
/// <summary>
/// Process all the parts in the package.
/// </summary>
ProcessAllParts,
}
/// <summary>
/// Traversal parts in the <see cref="OpenXmlPackage"/> by breadth-first.
/// </summary>
internal class OpenXmlPackagePartIterator : IEnumerable<OpenXmlPart>
{
private OpenXmlPackage _package;
#region Constructor
/// <summary>
/// Initializes a new instance of the OpenXmlPackagePartIterator class using the supplied OpenXmlPackage class.
/// </summary>
/// <param name="package">The OpenXmlPackage to use to enumerate parts.</param>
public OpenXmlPackagePartIterator(OpenXmlPackage package)
{
Debug.Assert(package != null);
this._package = package;
}
#endregion
#region IEnumerable<OpenXmlPart> Members
/// <summary>
/// Gets an enumerator for parts in the whole package.
/// </summary>
/// <returns></returns>
public IEnumerator<OpenXmlPart> GetEnumerator()
{
return GetPartsByBreadthFirstTraversal();
}
// Traverses the parts graph by breath-first
private IEnumerator<OpenXmlPart> GetPartsByBreadthFirstTraversal()
{
Debug.Assert(_package != null);
var returnedParts = new List<OpenXmlPart>();
Queue<OpenXmlPart> tmpQueue = new Queue<OpenXmlPart>();
// Enqueue child parts of the package.
foreach (var idPartPair in _package.Parts)
{
tmpQueue.Enqueue(idPartPair.OpenXmlPart);
}
while (tmpQueue.Count > 0)
{
var part = tmpQueue.Dequeue();
returnedParts.Add(part);
foreach (var subIdPartPair in part.Parts)
{
if (!tmpQueue.Contains(subIdPartPair.OpenXmlPart)
&& !returnedParts.Contains(subIdPartPair.OpenXmlPart))
{
tmpQueue.Enqueue(subIdPartPair.OpenXmlPart);
}
}
}
return returnedParts.GetEnumerator();
}
#endregion
#region IEnumerable Members
/// <summary>
/// Gets an enumerator for parts in the whole package.
/// </summary>
/// <returns></returns>
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
#endregion
}
}
| tarunchopra/Open-XML-SDK | DocumentFormat.OpenXml/src/Framework/OpenXmlPackage.cs | C# | apache-2.0 | 95,907 |
/**************************************************************************
* Mask.java is part of Touch4j 4.0. Copyright 2012 Emitrom 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.
**************************************************************************/
package com.emitrom.touch4j.client.ui;
import com.emitrom.touch4j.client.core.Component;
import com.emitrom.touch4j.client.core.config.Attribute;
import com.emitrom.touch4j.client.core.config.Event;
import com.emitrom.touch4j.client.core.config.XType;
import com.emitrom.touch4j.client.core.handlers.CallbackRegistration;
import com.emitrom.touch4j.client.core.handlers.mask.MaskTapHandler;
import com.google.gwt.core.client.JavaScriptObject;
/**
* A simple class used to mask any Container. This should rarely be used
* directly, instead look at the Container.mask configuration.
*
* @see <a href=http://docs.sencha.com/touch/2-0/#!/api/Ext.Mask>Ext.Mask</a>
*/
public class Mask extends Component {
@Override
protected native void init()/*-{
var c = new $wnd.Ext.Mask();
this.@com.emitrom.touch4j.client.core.Component::configPrototype = c.initialConfig;
}-*/;
@Override
public String getXType() {
return XType.MASK.getValue();
}
@Override
protected native JavaScriptObject create(JavaScriptObject config) /*-{
return new $wnd.Ext.Mask(config);
}-*/;
public Mask() {
}
protected Mask(JavaScriptObject jso) {
super(jso);
}
/**
* True to make this mask transparent.
*
* Defaults to: false
*
* @param value
*/
public void setTransparent(String value) {
setAttribute(Attribute.TRANSPARENT.getValue(), value, true);
}
/**
* A tap event fired when a user taps on this mask
*
* @param handler
*/
public CallbackRegistration addTapHandler(MaskTapHandler handler) {
return this.addWidgetListener(Event.TAP.getValue(), handler.getJsoPeer());
}
}
| paulvi/touch4j | src/com/emitrom/touch4j/client/ui/Mask.java | Java | apache-2.0 | 2,495 |
// lightbox_plus.js
// == written by Takuya Otani <takuya.otani@gmail.com> ===
// == Copyright (C) 2006 SimpleBoxes/SerendipityNZ Ltd. ==
/*
Copyright (C) 2006 Takuya Otani/SimpleBoxes - http://serennz.cool.ne.jp/sb/
Copyright (C) 2006 SerendipityNZ - http://serennz.cool.ne.jp/snz/
This script is licensed under the Creative Commons Attribution 2.5 License
http://creativecommons.org/licenses/by/2.5/
basically, do anything you want, just leave my name and link.
*/
/*
Original script : Lightbox JS : Fullsize Image Overlays
Copyright (C) 2005 Lokesh Dhakar - http://www.huddletogether.com
For more information on this script, visit:
http://huddletogether.com/projects/lightbox/
*/
// ver. 20061027 - fixed a bug ( not work at xhml documents on Netscape7 )
// ver. 20061026 - fixed bugs
// ver. 20061010 - implemented image set feature
// ver. 20060921 - fixed a bug / added overall view
// ver. 20060920 - added flag to prevent mouse wheel event
// ver. 20060919 - fixed a bug
// ver. 20060918 - implemented functionality of wheel zoom & drag'n drop
// ver. 20060131 - fixed a bug to work correctly on Internet Explorer for Windows
// ver. 20060128 - implemented functionality of echoic word
// ver. 20060120 - implemented functionality of caption and close button
function WindowSize()
{ // window size object
this.w = 0;
this.h = 0;
return this.update();
}
WindowSize.prototype.update = function()
{
var d = document;
this.w =
(window.innerWidth) ? window.innerWidth
: (d.documentElement && d.documentElement.clientWidth) ? d.documentElement.clientWidth
: d.body.clientWidth;
this.h =
(window.innerHeight) ? window.innerHeight
: (d.documentElement && d.documentElement.clientHeight) ? d.documentElement.clientHeight
: d.body.clientHeight;
return this;
};
function PageSize()
{ // page size object
this.win = new WindowSize();
this.w = 0;
this.h = 0;
return this.update();
}
PageSize.prototype.update = function()
{
var d = document;
this.w =
(window.innerWidth && window.scrollMaxX) ? window.innerWidth + window.scrollMaxX
: (d.body.scrollWidth > d.body.offsetWidth) ? d.body.scrollWidth
: d.body.offsetWidt;
this.h =
(window.innerHeight && window.scrollMaxY) ? window.innerHeight + window.scrollMaxY
: (d.body.scrollHeight > d.body.offsetHeight) ? d.body.scrollHeight
: d.body.offsetHeight;
this.win.update();
if (this.w < this.win.w) this.w = this.win.w;
if (this.h < this.win.h) this.h = this.win.h;
return this;
};
function PagePos()
{ // page position object
this.x = 0;
this.y = 0;
return this.update();
}
PagePos.prototype.update = function()
{
var d = document;
this.x =
(window.pageXOffset) ? window.pageXOffset
: (d.documentElement && d.documentElement.scrollLeft) ? d.documentElement.scrollLeft
: (d.body) ? d.body.scrollLeft
: 0;
this.y =
(window.pageYOffset) ? window.pageYOffset
: (d.documentElement && d.documentElement.scrollTop) ? d.documentElement.scrollTop
: (d.body) ? d.body.scrollTop
: 0;
return this;
};
function LightBox(option)
{
var self = this;
self._imgs = [];
self._sets = [];
self._wrap = null;
self._box = null;
self._img = null;
self._open = -1;
self._page = new PageSize();
self._pos = new PagePos();
self._zoomimg = null;
self._expandable = false;
self._expanded = false;
self._funcs = {'move':null,'up':null,'drag':null,'wheel':null,'dbl':null};
self._level = 1;
self._curpos = {x:0,y:0};
self._imgpos = {x:0,y:0};
self._minpos = {x:0,y:0};
self._expand = option.expandimg;
self._shrink = option.shrinkimg;
self._resizable = option.resizable;
self._timer = null;
self._indicator = null;
self._overall = null;
self._openedset = null;
self._prev = null;
self._next = null;
self._hiding = [];
self._first = false;
return self._init(option);
}
LightBox.prototype = {
_init : function(option)
{
var self = this;
var d = document;
if (!d.getElementsByTagName) return;
if (Browser.isMacIE) return self;
var links = d.getElementsByTagName("a");
for (var i = 0; i < links.length; i++)
{
var anchor = links[i];
var num = self._imgs.length;
var rel = String(anchor.getAttribute("rel")).toLowerCase();
if (!anchor.getAttribute("href") || !rel.match('lightbox')) continue;
// initialize item
self._imgs[num] = {
src:anchor.getAttribute("href"),
w:-1,
h:-1,
title:'',
cls:anchor.className,
set:rel
};
if (anchor.getAttribute("title"))
self._imgs[num].title = anchor.getAttribute("title");
else if (anchor.firstChild
&& anchor.firstChild.getAttribute
&& anchor.firstChild.getAttribute("title"))
self._imgs[num].title = anchor.firstChild.getAttribute("title");
anchor.onclick = self._genOpener(num);
// set closure to onclick event
if (rel != 'lightbox')
{
if (!self._sets[rel]) self._sets[rel] = [];
self._sets[rel].push(num);
}
}
var body = d.getElementsByTagName("body")[0];
self._wrap = self._createWrapOn(body, option.loadingimg);
self._box = self._createBoxOn(body, option);
self._img = self._box.firstChild;
self._zoomimg = d.getElementById('actionImage');
return self;
},
_genOpener : function(num)
{
var self = this;
return function() {
self._show(num);
return false;
}
},
_createWrapOn : function(obj, imagePath)
{
var self = this;
if (!obj) return null;
// create wrapper object, translucent background
var wrap = document.createElement('div');
obj.appendChild(wrap);
wrap.id = 'overlay';
wrap.style.display = 'none';
wrap.style.position = 'fixed';
wrap.style.top = '0px';
wrap.style.left = '0px';
wrap.style.zIndex = '50';
wrap.style.width = '100%';
wrap.style.height = '100%';
if (Browser.isWinIE) wrap.style.position = 'absolute';
Event.register(wrap, "click", function(evt) {
self._close(evt);
});
// create loading image, animated image
var imag = new Image;
imag.onload = function() {
var spin = document.createElement('img');
wrap.appendChild(spin);
spin.id = 'loadingImage';
spin.src = imag.src;
spin.style.position = 'relative';
self._set_cursor(spin);
Event.register(spin, 'click', function(evt) {
self._close(evt);
});
imag.onload = function() {
};
};
if (imagePath != '') imag.src = imagePath;
return wrap;
},
_createBoxOn : function(obj, option)
{
var self = this;
if (!obj) return null;
// create lightbox object, frame rectangle
var box = document.createElement('div');
obj.appendChild(box);
box.id = 'lightbox';
box.style.display = 'none';
box.style.position = 'absolute';
box.style.zIndex = '60';
// create image object to display a target image
var img = document.createElement('img');
box.appendChild(img);
img.id = 'lightboxImage';
self._set_cursor(img);
Event.register(img, 'mouseover', function() {
self._show_action();
});
Event.register(img, 'mouseout', function() {
self._hide_action();
});
Event.register(img, 'click', function(evt) {
self._close(evt);
});
// create hover navi - prev
if (option.previmg)
{
var prevLink = document.createElement('img');
box.appendChild(prevLink);
prevLink.id = 'prevLink';
prevLink.style.display = 'none';
prevLink.style.position = 'absolute';
prevLink.style.left = '9px';
prevLink.style.zIndex = '70';
prevLink.src = option.previmg;
self._prev = prevLink;
Event.register(prevLink, 'mouseover', function() {
self._show_action();
});
Event.register(prevLink, 'click', function() {
self._show_next(-1);
});
}
// create hover navi - next
if (option.nextimg)
{
var nextLink = document.createElement('img');
box.appendChild(nextLink);
nextLink.id = 'nextLink';
nextLink.style.display = 'none';
nextLink.style.position = 'absolute';
nextLink.style.right = '9px';
nextLink.style.zIndex = '70';
nextLink.src = option.nextimg;
self._next = nextLink;
Event.register(nextLink, 'mouseover', function() {
self._show_action();
});
Event.register(nextLink, 'click', function() {
self._show_next(+1);
});
}
// create zoom indicator
var zoom = document.createElement('img');
box.appendChild(zoom);
zoom.id = 'actionImage';
zoom.style.display = 'none';
zoom.style.position = 'absolute';
zoom.style.top = '15px';
zoom.style.left = '15px';
zoom.style.zIndex = '70';
self._set_cursor(zoom);
zoom.src = self._expand;
Event.register(zoom, 'mouseover', function() {
self._show_action();
});
Event.register(zoom, 'click', function() {
self._zoom();
});
Event.register(window, 'resize', function() {
self._set_size(true);
});
// create close button
if (option.closeimg)
{
var btn = document.createElement('img');
box.appendChild(btn);
btn.id = 'closeButton';
btn.style.display = 'inline';
btn.style.position = 'absolute';
btn.style.right = '9px';
btn.style.top = '10px';
btn.style.zIndex = '80';
btn.src = option.closeimg;
self._set_cursor(btn);
Event.register(btn, 'click', function(evt) {
self._close(evt);
});
}
// caption text
var caption = document.createElement('span');
box.appendChild(caption);
caption.id = 'lightboxCaption';
caption.style.display = 'none';
caption.style.position = 'absolute';
caption.style.zIndex = '80';
// create effect image
/* if (!option.effectpos)
option.effectpos = {x:0,y:0};
else
{
if (option.effectpos.x == '') option.effectpos.x = 0;
if (option.effectpos.y == '') option.effectpos.y = 0;
}
var effect = new Image;
effect.onload = function()
{
var effectImg = document.createElement('img');
box.appendChild(effectImg);
effectImg.id = 'effectImage';
effectImg.src = effect.src;
if (option.effectclass) effectImg.className = option.effectclass;
effectImg.style.position = 'absolute';
effectImg.style.display = 'none';
effectImg.style.left = [option.effectpos.x,'px'].join('');;
effectImg.style.top = [option.effectpos.y,'px'].join('');
effectImg.style.zIndex = '90';
self._set_cursor(effectImg);
Event.register(effectImg,'click',function() { effectImg.style.display = 'none'; });
};
if (option.effectimg != '') effect.src = option.effectimg;*/
if (self._resizable)
{
var overall = document.createElement('div');
obj.appendChild(overall);
overall.id = 'lightboxOverallView';
overall.style.display = 'none';
overall.style.position = 'absolute';
overall.style.zIndex = '70';
self._overall = overall;
var indicator = document.createElement('div');
obj.appendChild(indicator);
indicator.id = 'lightboxIndicator';
indicator.style.display = 'none';
indicator.style.position = 'absolute';
indicator.style.zIndex = '80';
self._indicator = indicator;
}
return box;
},
_set_photo_size : function()
{
var self = this;
if (self._open == -1) return;
var targ = { w:self._page.win.w - 30, h:self._page.win.h - 30 };
var zoom = { x:15, y:15 };
var navi = { p:9, n:9, y:0 };
if (!self._expanded)
{ // shrink image with the same aspect
var orig = { w:self._imgs[self._open].w, h:self._imgs[self._open].h };
var ratio = 1.0;
if ((orig.w >= targ.w || orig.h >= targ.h) && orig.h && orig.w)
ratio = ((targ.w / orig.w) < (targ.h / orig.h)) ? targ.w / orig.w : targ.h / orig.h;
self._img.width = Math.floor(orig.w * ratio);
self._img.height = Math.floor(orig.h * ratio);
self._expandable = (ratio < 1.0) ? true : false;
if (self._resizable) self._expandable = true;
if (Browser.isWinIE) self._box.style.display = "block";
self._imgpos.x = self._pos.x + (targ.w - self._img.width) / 2;
self._imgpos.y = self._pos.y + (targ.h - self._img.height) / 2;
navi.y = Math.floor(self._img.height / 2) - 10;
self._show_caption(true);
self._show_overall(false);
}
else
{ // zoomed or actual sized image
var width = parseInt(self._imgs[self._open].w * self._level);
var height = parseInt(self._imgs[self._open].h * self._level);
self._minpos.x = self._pos.x + targ.w - width;
self._minpos.y = self._pos.y + targ.h - height;
if (width <= targ.w)
self._imgpos.x = self._pos.x + (targ.w - width) / 2;
else
{
if (self._imgpos.x > self._pos.x) self._imgpos.x = self._pos.x;
else if (self._imgpos.x < self._minpos.x) self._imgpos.x = self._minpos.x;
zoom.x = 15 + self._pos.x - self._imgpos.x;
navi.p = self._pos.x - self._imgpos.x - 5;
navi.n = width - self._page.win.w + self._imgpos.x + 25;
if (Browser.isWinIE) navi.n -= 10;
}
if (height <= targ.h)
{
self._imgpos.y = self._pos.y + (targ.h - height) / 2;
navi.y = Math.floor(self._img.height / 2) - 10;
}
else
{
if (self._imgpos.y > self._pos.y) self._imgpos.y = self._pos.y;
else if (self._imgpos.y < self._minpos.y) self._imgpos.y = self._minpos.y;
zoom.y = 15 + self._pos.y - self._imgpos.y;
navi.y = Math.floor(targ.h / 2) - 10 + self._pos.y - self._imgpos.y;
}
self._img.width = width;
self._img.height = height;
self._show_caption(false);
self._show_overall(true);
}
self._box.style.left = [self._imgpos.x,'px'].join('');
self._box.style.top = [self._imgpos.y,'px'].join('');
self._zoomimg.style.left = [zoom.x,'px'].join('');
self._zoomimg.style.top = [zoom.y,'px'].join('');
self._wrap.style.left = self._pos.x;
if (self._prev && self._next)
{
self._prev.style.left = [navi.p,'px'].join('');
self._next.style.right = [navi.n,'px'].join('');
self._prev.style.top = self._next.style.top = [navi.y,'px'].join('');
}
},
_show_overall : function(visible)
{
var self = this;
if (self._overall == null) return;
if (visible)
{
if (self._open == -1) return;
var base = 100;
var outer = { w:0, h:0, x:0, y:0 };
var inner = { w:0, h:0, x:0, y:0 };
var orig = { w:self._img.width , h:self._img.height };
var targ = { w:self._page.win.w - 30, h:self._page.win.h - 30 };
var max = orig.w;
if (max < orig.h) max = orig.h;
if (max < targ.w) max = targ.w;
if (max < targ.h) max = targ.h;
if (max < 1) return;
outer.w = parseInt(orig.w / max * base);
outer.h = parseInt(orig.h / max * base);
inner.w = parseInt(targ.w / max * base);
inner.h = parseInt(targ.h / max * base);
outer.x = self._pos.x + targ.w - base - 20;
outer.y = self._pos.y + targ.h - base - 20;
inner.x = outer.x - parseInt((self._imgpos.x - self._pos.x) / max * base);
inner.y = outer.y - parseInt((self._imgpos.y - self._pos.y) / max * base);
self._overall.style.left = [outer.x,'px'].join('');
self._overall.style.top = [outer.y,'px'].join('');
self._overall.style.width = [outer.w,'px'].join('');
self._overall.style.height = [outer.h,'px'].join('');
self._indicator.style.left = [inner.x,'px'].join('');
self._indicator.style.top = [inner.y,'px'].join('');
self._indicator.style.width = [inner.w,'px'].join('');
self._indicator.style.height = [inner.h,'px'].join('');
self._overall.style.display = 'block'
self._indicator.style.display = 'block';
}
else
{
self._overall.style.display = 'none';
self._indicator.style.display = 'none';
}
},
_set_size : function(onResize)
{
var self = this;
if (self._open == -1) return;
self._page.update();
self._pos.update();
var spin = self._wrap.firstChild;
if (spin)
{
var top = (self._page.win.h - spin.height) / 2;
if (self._wrap.style.position == 'absolute') top += self._pos.y;
spin.style.top = [top,'px'].join('');
spin.style.left = [(self._page.win.w - spin.width - 30) / 2,'px'].join('');
}
if (Browser.isWinIE)
{
self._wrap.style.width = [self._page.win.w,'px'].join('');
self._wrap.style.height = [self._page.win.h,'px'].join('');
self._wrap.style.top = [self._pos.y,'px'].join('');
}
if (onResize) self._set_photo_size();
},
_set_cursor : function(obj)
{
var self = this;
if (Browser.isWinIE && !Browser.isNewIE) return;
obj.style.cursor = 'pointer';
},
_current_setindex : function()
{
var self = this;
if (!self._openedset) return -1;
var list = self._sets[self._openedset];
for (var i = 0,n = list.length; i < n; i++)
{
if (list[i] == self._open) return i;
}
return -1;
},
_get_setlength : function()
{
var self = this;
if (!self._openedset) return -1;
return self._sets[self._openedset].length;
},
_show_action : function()
{
var self = this;
if (self._open == -1 || !self._expandable) return;
if (!self._zoomimg) return;
self._zoomimg.src = (self._expanded) ? self._shrink : self._expand;
self._zoomimg.style.display = 'inline';
var check = self._current_setindex();
if (check > -1)
{
if (check > 0) self._prev.style.display = 'inline';
if (check < self._get_setlength() - 1) self._next.style.display = 'inline';
}
},
_hide_action : function()
{
var self = this;
if (self._zoomimg) self._zoomimg.style.display = 'none';
if (self._open > -1 && self._expanded) self._dragstop(null);
if (self._prev) self._prev.style.display = 'none';
if (self._next) self._next.style.display = 'none';
},
_zoom : function()
{
var self = this;
var closeBtn = document.getElementById('closeButton');
if (self._expanded)
{
self._reset_func();
self._expanded = false;
if (closeBtn) closeBtn.style.display = 'inline';
}
else if (self._open > -1)
{
self._level = 1;
self._imgpos.x = self._pos.x;
self._imgpos.y = self._pos.y;
self._expanded = true;
self._funcs.drag = function(evt) {
self._dragstart(evt)
};
self._funcs.dbl = function(evt) {
self._close(null)
};
if (self._resizable)
{
self._funcs.wheel = function(evt) {
self._onwheel(evt)
};
Event.register(self._box, 'mousewheel', self._funcs.wheel);
}
Event.register(self._img, 'mousedown', self._funcs.drag);
Event.register(self._img, 'dblclick', self._funcs.dbl);
if (closeBtn) closeBtn.style.display = 'none';
}
self._set_photo_size();
self._show_action();
},
_reset_func : function()
{
var self = this;
if (self._funcs.wheel != null) Event.deregister(self._box, 'mousewheel', self._funcs.wheel);
if (self._funcs.move != null) Event.deregister(self._img, 'mousemove', self._funcs.move);
if (self._funcs.up != null) Event.deregister(self._img, 'mouseup', self._funcs.up);
if (self._funcs.drag != null) Event.deregister(self._img, 'mousedown', self._funcs.drag);
if (self._funcs.dbl != null) Event.deregister(self._img, 'dblclick', self._funcs.dbl);
self._funcs = {'move':null,'up':null,'drag':null,'wheel':null,'dbl':null};
},
_onwheel : function(evt)
{
var self = this;
var delta = 0;
evt = Event.getEvent(evt);
if (evt.wheelDelta) delta = event.wheelDelta / -120;
else if (evt.detail) delta = evt.detail / 3;
if (Browser.isOpera) delta = - delta;
var step =
(self._level < 1) ? 0.1
: (self._level < 2) ? 0.25
: (self._level < 4) ? 0.5
: 1;
self._level = (delta > 0) ? self._level + step : self._level - step;
if (self._level > 8) self._level = 8;
else if (self._level < 0.5) self._level = 0.5;
self._set_photo_size();
return Event.stop(evt);
},
_dragstart : function(evt)
{
var self = this;
evt = Event.getEvent(evt);
self._curpos.x = evt.screenX;
self._curpos.y = evt.screenY;
self._funcs.move = function(evnt) {
self._dragging(evnt);
};
self._funcs.up = function(evnt) {
self._dragstop(evnt);
};
Event.register(self._img, 'mousemove', self._funcs.move);
Event.register(self._img, 'mouseup', self._funcs.up);
return Event.stop(evt);
},
_dragging : function(evt)
{
var self = this;
evt = Event.getEvent(evt);
self._imgpos.x += evt.screenX - self._curpos.x;
self._imgpos.y += evt.screenY - self._curpos.y;
self._curpos.x = evt.screenX;
self._curpos.y = evt.screenY;
self._set_photo_size();
return Event.stop(evt);
},
_dragstop : function(evt)
{
var self = this;
evt = Event.getEvent(evt);
if (self._funcs.move != null) Event.deregister(self._img, 'mousemove', self._funcs.move);
if (self._funcs.up != null) Event.deregister(self._img, 'mouseup', self._funcs.up);
self._funcs.move = null;
self._funcs.up = null;
self._set_photo_size();
return (evt) ? Event.stop(evt) : false;
},
_show_caption : function(enable)
{
var self = this;
var caption = document.getElementById('lightboxCaption');
if (!caption) return;
if (caption.innerHTML.length == 0 || !enable)
{
caption.style.display = 'none';
}
else
{ // now display caption
caption.style.top = [self._img.height + 10,'px'].join('');
// 10 is top margin of lightbox
caption.style.left = '0px';
caption.style.width = [self._img.width + 20,'px'].join('');
// 20 is total side margin of lightbox
caption.style.display = 'block';
}
},
_toggle_wrap : function(flag)
{
var self = this;
self._wrap.style.display = flag ? "block" : "none";
if (self._hiding.length == 0 && !self._first)
{ // some objects may overlap on overlay, so we hide them temporarily.
var tags = ['select','embed','object'];
for (var i = 0,n = tags.length; i < n; i++)
{
var elem = document.getElementsByTagName(tags[i]);
for (var j = 0,m = elem.length; j < m; j++)
{ // check the original value at first. when alredy hidden, dont touch them
var check = elem[j].style.visibility;
if (!check)
{
if (elem[j].currentStyle)
check = elem[j].currentStyle['visibility'];
else if (document.defaultView)
check = document.defaultView.getComputedStyle(elem[j], '').getPropertyValue('visibility');
}
if (check == 'hidden') continue;
self._hiding.push(elem[j]);
}
}
self._first = true;
}
for (var i = 0,n = self._hiding.length; i < n; i++)
self._hiding[i].style.visibility = flag ? "hidden" : "visible";
},
_show : function(num)
{
var self = this;
var imag = new Image;
if (num < 0 || num >= self._imgs.length) return;
var loading = document.getElementById('loadingImage');
var caption = document.getElementById('lightboxCaption');
// var effect = document.getElementById('effectImage');
self._open = num;
// set opened image number
self._set_size(false);
// calc and set wrapper size
self._toggle_wrap(true);
if (loading) loading.style.display = 'inline';
imag.onload = function() {
if (self._imgs[self._open].w == -1)
{ // store original image width and height
self._imgs[self._open].w = imag.width;
self._imgs[self._open].h = imag.height;
}
/* if (effect)
{
effect.style.display = (!effect.className || self._imgs[self._open].cls == effect.className)
? 'block' : 'none';
}*/
if (caption)
try {
caption.innerHTML = self._imgs[self._open].title;
} catch(e) {
}
self._set_photo_size();
// calc and set lightbox size
self._hide_action();
self._box.style.display = "block";
self._img.src = imag.src;
self._img.setAttribute('title', self._imgs[self._open].title);
self._timer = window.setInterval(function() {
self._set_size(true)
}, 100);
if (loading) loading.style.display = 'none';
if (self._imgs[self._open].set != 'lightbox')
{
var set = self._imgs[self._open].set;
if (self._sets[set].length > 1) self._openedset = set;
if (!self._prev || !self._next) self._openedset = null;
}
};
self._expandable = false;
self._expanded = false;
imag.src = self._imgs[self._open].src;
},
_close_box : function()
{
var self = this;
self._open = -1;
self._openedset = null;
self._hide_action();
self._hide_action();
self._reset_func();
self._show_overall(false);
self._box.style.display = "none";
if (self._timer != null)
{
window.clearInterval(self._timer);
self._timer = null;
}
},
_show_next : function(direction)
{
var self = this;
if (!self._openedset) return self._close(null);
var index = self._current_setindex() + direction;
var targ = self._sets[self._openedset][index];
self._close_box();
self._show(targ);
},
_close : function(evt)
{
var self = this;
if (evt != null)
{
evt = Event.getEvent(evt);
var targ = evt.target || evt.srcElement;
if (targ && targ.getAttribute('id') == 'lightboxImage' && self._expanded) return;
}
self._close_box();
self._toggle_wrap(false);
}
};
Event.register(window, "load", function() {
var lightbox = new LightBox({
loadingimg:'lightbox/loading.gif',
expandimg:'lightbox/expand.gif',
shrinkimg:'lightbox/shrink.gif',
previmg:'lightbox/prev.gif',
nextimg:'lightbox/next.gif',
/* effectpos:{x:-40,y:-20},
effectclass:'effectable',*/
closeimg:'lightbox/close.gif',
resizable:true
});
});
| yusuke/samurai | site/lightbox/lightbox_plus.js | JavaScript | apache-2.0 | 29,978 |
/*
* Copyright 2017-present Facebook, 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 com.facebook.buck.util.trace.uploader.launcher;
import com.facebook.buck.core.model.BuildId;
import com.facebook.buck.log.Logger;
import com.facebook.buck.util.env.BuckClasspath;
import com.facebook.buck.util.trace.uploader.types.CompressionType;
import com.google.common.base.Strings;
import java.io.IOException;
import java.net.URI;
import java.nio.file.Path;
/** Utility to upload chrome trace in background. */
public class UploaderLauncher {
private static final Logger LOG = Logger.get(UploaderLauncher.class);
/** Upload chrome trace in background process which runs even after current process dies. */
public static void uploadInBackground(
BuildId buildId,
Path traceFilePath,
String traceFileKind,
URI traceUploadUri,
Path logFile,
CompressionType compressionType) {
LOG.debug("Uploading build trace in the background. Upload will log to %s", logFile);
String buckClasspath = BuckClasspath.getBuckClasspathFromEnvVarOrNull();
if (Strings.isNullOrEmpty(buckClasspath)) {
LOG.error(
BuckClasspath.ENV_VAR_NAME + " env var is not set. Will not upload the trace file.");
return;
}
try {
String[] args = {
"java",
"-cp",
buckClasspath,
"com.facebook.buck.util.trace.uploader.Main",
"--buildId",
buildId.toString(),
"--traceFilePath",
traceFilePath.toString(),
"--traceFileKind",
traceFileKind,
"--baseUrl",
traceUploadUri.toString(),
"--log",
logFile.toString(),
"--compressionType",
compressionType.name(),
};
Runtime.getRuntime().exec(args);
} catch (IOException e) {
LOG.error(e, e.getMessage());
}
}
}
| LegNeato/buck | src/com/facebook/buck/util/trace/uploader/launcher/UploaderLauncher.java | Java | apache-2.0 | 2,379 |
/*
* Copyright 2013, Google 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:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.jf.dexlib2.builder;
import org.jf.dexlib2.*;
import org.jf.dexlib2.builder.instruction.*;
import org.jf.dexlib2.iface.instruction.*;
import java.util.*;
import javax.annotation.*;
public abstract class BuilderSwitchPayload extends BuilderInstruction implements SwitchPayload {
@Nullable
MethodLocation referrer;
protected BuilderSwitchPayload(@Nonnull Opcode opcode) {
super(opcode);
}
@Nonnull
public MethodLocation getReferrer() {
if (referrer == null) {
throw new IllegalStateException("The referrer has not been set yet");
}
return referrer;
}
@Nonnull
@Override
public abstract List<? extends BuilderSwitchElement> getSwitchElements();
}
| nao20010128nao/show-java | app/src/main/java/org/jf/dexlib2/builder/BuilderSwitchPayload.java | Java | apache-2.0 | 2,310 |
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""Tests for the Google Chrome Cache files event formatter."""
import unittest
from plaso.formatters import chrome_cache
from tests.formatters import test_lib
class ChromeCacheEntryEventFormatterTest(test_lib.EventFormatterTestCase):
"""Tests for the Chrome Cache entry event formatter."""
def testInitialization(self):
"""Tests the initialization."""
event_formatter = chrome_cache.ChromeCacheEntryEventFormatter()
self.assertIsNotNone(event_formatter)
def testGetFormatStringAttributeNames(self):
"""Tests the GetFormatStringAttributeNames function."""
event_formatter = chrome_cache.ChromeCacheEntryEventFormatter()
expected_attribute_names = [u'original_url']
self._TestGetFormatStringAttributeNames(
event_formatter, expected_attribute_names)
# TODO: add test for GetMessages.
if __name__ == '__main__':
unittest.main()
| dc3-plaso/plaso | tests/formatters/chrome_cache.py | Python | apache-2.0 | 925 |
package nodeAST.relational;
import java.util.Map;
import nodeAST.BinaryExpr;
import nodeAST.Expression;
import nodeAST.Ident;
import nodeAST.literals.Literal;
import types.BoolType;
import types.Type;
import visitor.ASTVisitor;
import visitor.IdentifiersTypeMatcher;
public class NEq extends BinaryExpr {
public NEq(Expression leftHandOperand, Expression rightHandOperand) {
super(leftHandOperand,rightHandOperand);
}
@Override
public void accept(ASTVisitor visitor) {
visitor.visit(this, this.leftHandOperand, this.rightHandOperand);
}
@Override
public String toString() {
return this.leftHandOperand.toString() + "!=" + this.rightHandOperand.toString();
}
@Override
public Type getType(IdentifiersTypeMatcher typeMatcher) {
return new BoolType();
}
@Override
public boolean areOperandsTypeValid(IdentifiersTypeMatcher typeMatcher) {
Type t1=this.leftHandOperand.getType(typeMatcher);
Type t2=this.rightHandOperand.getType(typeMatcher);
return t1.isCompatibleWith(t2) &&
(t1.isArithmetic() || t1.isBoolean() || t1.isRelational() || t1.isString() );
}
@Override
public Literal compute(Map<Ident, Expression> identifiers) {
return this.leftHandOperand.compute(identifiers).neq(
this.rightHandOperand.compute(identifiers)
);
}
}
| software-engineering-amsterdam/poly-ql | GeorgePachitariu/ANTLR-First/src/nodeAST/relational/NEq.java | Java | apache-2.0 | 1,336 |
package edu.ptu.javatest._60_dsa;
import org.junit.Test;
import java.util.TreeMap;
import static edu.ptu.javatest._20_ooad._50_dynamic._00_ReflectionTest.getRefFieldBool;
import static edu.ptu.javatest._20_ooad._50_dynamic._00_ReflectionTest.getRefFieldObj;
public class _35_TreeMapTest {
@Test
public void testPrintTreeMap() {
TreeMap hashMapTest = new TreeMap<>();
for (int i = 0; i < 6; i++) {
hashMapTest.put(new TMHashObj(1,i*2 ), i*2 );
}
Object table = getRefFieldObj(hashMapTest, hashMapTest.getClass(), "root");
printTreeMapNode(table);
hashMapTest.put(new TMHashObj(1,9), 9);
printTreeMapNode(table);
System.out.println();
}
public static int getTreeDepth(Object rootNode) {
if (rootNode == null || !rootNode.getClass().toString().equals("class java.util.TreeMap$Entry"))
return 0;
return rootNode == null ? 0 : (1 + Math.max(getTreeDepth(getRefFieldObj(rootNode, rootNode.getClass(), "left")), getTreeDepth(getRefFieldObj(rootNode, rootNode.getClass(), "right"))));
}
public static void printTreeMapNode(Object rootNode) {//转化为堆
if (rootNode == null || !rootNode.getClass().toString().equals("class java.util.TreeMap$Entry"))
return;
int treeDepth = getTreeDepth(rootNode);
Object[] objects = new Object[(int) (Math.pow(2, treeDepth) - 1)];
objects[0] = rootNode;
// objects[0]=rootNode;
// objects[1]=getRefFieldObj(objects,objects.getClass(),"left");
// objects[2]=getRefFieldObj(objects,objects.getClass(),"right");
//
// objects[3]=getRefFieldObj(objects[1],objects[1].getClass(),"left");
// objects[4]=getRefFieldObj(objects[1],objects[1].getClass(),"right");
// objects[5]=getRefFieldObj(objects[2],objects[3].getClass(),"left");
// objects[6]=getRefFieldObj(objects[2],objects[4].getClass(),"right");
for (int i = 1; i < objects.length; i++) {//数组打印
int index = (i - 1) / 2;//parent
if (objects[index] != null) {
if (i % 2 == 1)
objects[i] = getRefFieldObj(objects[index], objects[index].getClass(), "left");
else
objects[i] = getRefFieldObj(objects[index], objects[index].getClass(), "right");
}
}
StringBuilder sb = new StringBuilder();
StringBuilder outSb = new StringBuilder();
String space = " ";
for (int i = 0; i < treeDepth + 1; i++) {
sb.append(space);
}
int nextlineIndex = 0;
for (int i = 0; i < objects.length; i++) {//new line: 0,1 ,3,7
//print space
//print value
if (nextlineIndex == i) {
outSb.append("\n\n");
if (sb.length() >= space.length()) {
sb.delete(0, space.length());
}
nextlineIndex = i * 2 + 1;
}
outSb.append(sb.toString());
if (objects[i] != null) {
Object value = getRefFieldObj(objects[i], objects[i].getClass(), "value");
boolean red = !getRefFieldBool(objects[i], objects[i].getClass(), "color");// BLACK = true;
String result = "" + value + "(" + (red ? "r" : "b") + ")";
outSb.append(result);
} else {
outSb.append("nil");
}
}
System.out.println(outSb.toString());
}
public static class TMHashObj implements Comparable{
int hash;
int value;
TMHashObj(int hash, int value) {
this.hash = hash;
this.value = value;
}
@Override
public int hashCode() {
return hash;
}
@Override
public int compareTo(Object o) {
if (o instanceof TMHashObj){
return this.value-((TMHashObj) o).value;
}
return value-o.hashCode();
}
}
}
| rickgit/Test | JavaTest/src/main/java/edu/ptu/javatest/_60_dsa/_35_TreeMapTest.java | Java | apache-2.0 | 4,084 |
using System;
using System.Html;
using System.Runtime.CompilerServices;
namespace jQueryApi.UI.Widgets {
[Imported]
[IgnoreNamespace]
[Serializable]
public sealed class DialogResizeStartEvent {
public object OriginalPosition {
get; set;
}
public object OriginalSize {
get; set;
}
public object Position {
get; set;
}
public object Size {
get; set;
}
}
}
| Saltarelle/SaltarelleJQueryUI | jQuery.UI/Generated/Widgets/Dialog/DialogResizeStartEvent.cs | C# | apache-2.0 | 492 |
package com.cisco.axl.api._8;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for LPhoneSecurityProfile complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="LPhoneSecurityProfile">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence minOccurs="0">
* <element name="phoneType" type="{http://www.cisco.com/AXL/API/8.0}XModel" minOccurs="0"/>
* <element name="protocol" type="{http://www.cisco.com/AXL/API/8.0}XDeviceProtocol" minOccurs="0"/>
* <element name="name" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element name="description" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element name="deviceSecurityMode" type="{http://www.cisco.com/AXL/API/8.0}XDeviceSecurityMode" minOccurs="0"/>
* <element name="authenticationMode" type="{http://www.cisco.com/AXL/API/8.0}XAuthenticationMode" minOccurs="0"/>
* <element name="keySize" type="{http://www.cisco.com/AXL/API/8.0}XKeySize" minOccurs="0"/>
* <element name="tftpEncryptedConfig" type="{http://www.cisco.com/AXL/API/8.0}boolean" minOccurs="0"/>
* <element name="nonceValidityTime" type="{http://www.cisco.com/AXL/API/8.0}XInteger" minOccurs="0"/>
* <element name="transportType" type="{http://www.cisco.com/AXL/API/8.0}XTransport" minOccurs="0"/>
* <element name="sipPhonePort" type="{http://www.cisco.com/AXL/API/8.0}XInteger" minOccurs="0"/>
* <element name="enableDigestAuthentication" type="{http://www.cisco.com/AXL/API/8.0}boolean" minOccurs="0"/>
* <element name="excludeDigestCredentials" type="{http://www.cisco.com/AXL/API/8.0}boolean" minOccurs="0"/>
* </sequence>
* <attribute name="uuid" type="{http://www.cisco.com/AXL/API/8.0}XUUID" />
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "LPhoneSecurityProfile", propOrder = {
"phoneType",
"protocol",
"name",
"description",
"deviceSecurityMode",
"authenticationMode",
"keySize",
"tftpEncryptedConfig",
"nonceValidityTime",
"transportType",
"sipPhonePort",
"enableDigestAuthentication",
"excludeDigestCredentials"
})
public class LPhoneSecurityProfile {
protected String phoneType;
protected String protocol;
protected String name;
protected String description;
protected String deviceSecurityMode;
protected String authenticationMode;
protected String keySize;
protected String tftpEncryptedConfig;
protected String nonceValidityTime;
protected String transportType;
protected String sipPhonePort;
protected String enableDigestAuthentication;
protected String excludeDigestCredentials;
@XmlAttribute
protected String uuid;
/**
* Gets the value of the phoneType property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getPhoneType() {
return phoneType;
}
/**
* Sets the value of the phoneType property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setPhoneType(String value) {
this.phoneType = value;
}
/**
* Gets the value of the protocol property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getProtocol() {
return protocol;
}
/**
* Sets the value of the protocol property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setProtocol(String value) {
this.protocol = value;
}
/**
* Gets the value of the name property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getName() {
return name;
}
/**
* Sets the value of the name property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setName(String value) {
this.name = value;
}
/**
* Gets the value of the description property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getDescription() {
return description;
}
/**
* Sets the value of the description property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setDescription(String value) {
this.description = value;
}
/**
* Gets the value of the deviceSecurityMode property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getDeviceSecurityMode() {
return deviceSecurityMode;
}
/**
* Sets the value of the deviceSecurityMode property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setDeviceSecurityMode(String value) {
this.deviceSecurityMode = value;
}
/**
* Gets the value of the authenticationMode property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getAuthenticationMode() {
return authenticationMode;
}
/**
* Sets the value of the authenticationMode property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setAuthenticationMode(String value) {
this.authenticationMode = value;
}
/**
* Gets the value of the keySize property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getKeySize() {
return keySize;
}
/**
* Sets the value of the keySize property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setKeySize(String value) {
this.keySize = value;
}
/**
* Gets the value of the tftpEncryptedConfig property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getTftpEncryptedConfig() {
return tftpEncryptedConfig;
}
/**
* Sets the value of the tftpEncryptedConfig property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setTftpEncryptedConfig(String value) {
this.tftpEncryptedConfig = value;
}
/**
* Gets the value of the nonceValidityTime property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getNonceValidityTime() {
return nonceValidityTime;
}
/**
* Sets the value of the nonceValidityTime property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setNonceValidityTime(String value) {
this.nonceValidityTime = value;
}
/**
* Gets the value of the transportType property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getTransportType() {
return transportType;
}
/**
* Sets the value of the transportType property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setTransportType(String value) {
this.transportType = value;
}
/**
* Gets the value of the sipPhonePort property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getSipPhonePort() {
return sipPhonePort;
}
/**
* Sets the value of the sipPhonePort property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setSipPhonePort(String value) {
this.sipPhonePort = value;
}
/**
* Gets the value of the enableDigestAuthentication property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getEnableDigestAuthentication() {
return enableDigestAuthentication;
}
/**
* Sets the value of the enableDigestAuthentication property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setEnableDigestAuthentication(String value) {
this.enableDigestAuthentication = value;
}
/**
* Gets the value of the excludeDigestCredentials property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getExcludeDigestCredentials() {
return excludeDigestCredentials;
}
/**
* Sets the value of the excludeDigestCredentials property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setExcludeDigestCredentials(String value) {
this.excludeDigestCredentials = value;
}
/**
* Gets the value of the uuid property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getUuid() {
return uuid;
}
/**
* Sets the value of the uuid property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setUuid(String value) {
this.uuid = value;
}
}
| ox-it/cucm-http-api | src/main/java/com/cisco/axl/api/_8/LPhoneSecurityProfile.java | Java | apache-2.0 | 10,171 |
package pokemon.vue;
import pokemon.launcher.PokemonCore;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.Batch;
import com.badlogic.gdx.graphics.g2d.BitmapFont;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
import com.badlogic.gdx.scenes.scene2d.Actor;
import com.badlogic.gdx.scenes.scene2d.actions.*;
public class MyActor extends Actor {
public Texture s=new Texture(Gdx.files.internal("crosshair.png"));
SpriteBatch b=new SpriteBatch();
float x,y;
public MyActor (float x, float y) {
this.x=x;
this.y=y;
System.out.print(PokemonCore.m.getCities().get(0).getX());
this.setBounds(x+PokemonCore.m.getCities().get(0).getX(),y+PokemonCore.m.getCities().get(0).getY(),s.getWidth(),s.getHeight());
/* RepeatAction action = new RepeatAction();
action.setCount(RepeatAction.FOREVER);
action.setAction(Actions.fadeOut(2f));*/
this.addAction(Actions.repeat(RepeatAction.FOREVER,Actions.sequence(Actions.fadeOut(1f),Actions.fadeIn(1f))));
//posx=this.getX();
//posy=this.getY();
//this.addAction(action);
//this.addAction(Actions.sequence(Actions.alpha(0),Actions.fadeIn(2f)));
System.out.println("Actor constructed");
b.getProjectionMatrix().setToOrtho2D(0, 0,640,360);
}
@Override
public void draw (Batch batch, float parentAlpha) {
b.begin();
Color color = getColor();
b.setColor(color.r, color.g, color.b, color.a * parentAlpha);
b.draw(s,this.getX()-15,this.getY()-15,30,30);
b.setColor(color);
b.end();
//System.out.println("Called");
//batch.draw(t,this.getX(),this.getY(),t.getWidth(),t.getHeight());
//batch.draw(s,this.getX()+Minimap.BourgPalette.getX(),this.getY()+Minimap.BourgPalette.getY(),30,30);
}
public void setPosition(float x, float y){
this.setX(x+this.x);
this.setY(y+this.y);
}
}
| yongaro/Pokemon | Pokemon-core/src/main/java/pokemon/vue/MyActor.java | Java | apache-2.0 | 2,197 |
package org.tiltedwindmills.fantasy.mfl.services;
import org.tiltedwindmills.fantasy.mfl.model.LoginResponse;
/**
* Interface defining operations required for logging into an MFL league.
*/
public interface LoginService {
/**
* Login.
*
* @param leagueId the league id
* @param serverId the server id
* @param year the year
* @param franchiseId the franchise id
* @param password the password
* @return the login response
*/
LoginResponse login(int leagueId, int serverId, int year, String franchiseId, String password);
}
| tiltedwindmills/mfl-api | src/main/java/org/tiltedwindmills/fantasy/mfl/services/LoginService.java | Java | apache-2.0 | 571 |
<?php
/* TwigBundle:Exception:exception.rdf.twig */
class __TwigTemplate_70e8b249c1428c255435d8a44ef7c09891fdf8c23551b886c441d0a716433b6a extends Twig_Template
{
public function __construct(Twig_Environment $env)
{
parent::__construct($env);
$this->parent = false;
$this->blocks = array(
);
}
protected function doDisplay(array $context, array $blocks = array())
{
$__internal_526d7a805785be4fb721c754b2cee69154d58ade11c606da9590ba90d330241a = $this->env->getExtension("Symfony\\Bundle\\WebProfilerBundle\\Twig\\WebProfilerExtension");
$__internal_526d7a805785be4fb721c754b2cee69154d58ade11c606da9590ba90d330241a->enter($__internal_526d7a805785be4fb721c754b2cee69154d58ade11c606da9590ba90d330241a_prof = new Twig_Profiler_Profile($this->getTemplateName(), "template", "TwigBundle:Exception:exception.rdf.twig"));
$__internal_eec35cd5a10ba99b284e27c6831565132f96b0a120b58f10f2e9b54513d0d1f7 = $this->env->getExtension("Symfony\\Bridge\\Twig\\Extension\\ProfilerExtension");
$__internal_eec35cd5a10ba99b284e27c6831565132f96b0a120b58f10f2e9b54513d0d1f7->enter($__internal_eec35cd5a10ba99b284e27c6831565132f96b0a120b58f10f2e9b54513d0d1f7_prof = new Twig_Profiler_Profile($this->getTemplateName(), "template", "TwigBundle:Exception:exception.rdf.twig"));
// line 1
$this->loadTemplate("@Twig/Exception/exception.xml.twig", "TwigBundle:Exception:exception.rdf.twig", 1)->display(array_merge($context, array("exception" => (isset($context["exception"]) ? $context["exception"] : $this->getContext($context, "exception")))));
$__internal_526d7a805785be4fb721c754b2cee69154d58ade11c606da9590ba90d330241a->leave($__internal_526d7a805785be4fb721c754b2cee69154d58ade11c606da9590ba90d330241a_prof);
$__internal_eec35cd5a10ba99b284e27c6831565132f96b0a120b58f10f2e9b54513d0d1f7->leave($__internal_eec35cd5a10ba99b284e27c6831565132f96b0a120b58f10f2e9b54513d0d1f7_prof);
}
public function getTemplateName()
{
return "TwigBundle:Exception:exception.rdf.twig";
}
public function isTraitable()
{
return false;
}
public function getDebugInfo()
{
return array ( 25 => 1,);
}
/** @deprecated since 1.27 (to be removed in 2.0). Use getSourceContext() instead */
public function getSource()
{
@trigger_error('The '.__METHOD__.' method is deprecated since version 1.27 and will be removed in 2.0. Use getSourceContext() instead.', E_USER_DEPRECATED);
return $this->getSourceContext()->getCode();
}
public function getSourceContext()
{
return new Twig_Source("{% include '@Twig/Exception/exception.xml.twig' with { 'exception': exception } %}
", "TwigBundle:Exception:exception.rdf.twig", "C:\\wamp64\\www\\Symfony\\vendor\\symfony\\symfony\\src\\Symfony\\Bundle\\TwigBundle/Resources/views/Exception/exception.rdf.twig");
}
}
| messaoudiDEV/citypocketBackoffice | Symfony/var/cache/dev/twig/43/43468dad29714cf35fffa471cafcb8fedae808ea624963fc40a0b533af7edd3e.php | PHP | apache-2.0 | 2,965 |
/* Copyright (c) 2015 "Naftoreiclag" https://github.com/Naftoreiclag
*
* Distributed under the Apache License Version 2.0 (http://www.apache.org/licenses/)
* See accompanying file LICENSE
*/
#include "nrsalPrimitives.h"
nrsalPrimitives::nrsalPrimitives()
{
//ctor
}
nrsalPrimitives::~nrsalPrimitives()
{
//dtor
}
| Naftoreiclag/VS7C | src/nrsalPrimitives.cpp | C++ | apache-2.0 | 322 |
package org.ns.vk.cachegrabber.ui;
import java.awt.event.ActionEvent;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.AbstractAction;
import org.ns.func.Callback;
import org.ns.ioc.IoC;
import org.ns.vk.cachegrabber.api.Application;
import org.ns.vk.cachegrabber.api.vk.Audio;
import org.ns.vk.cachegrabber.api.vk.VKApi;
/**
*
* @author stupak
*/
public class TestAction extends AbstractAction {
public TestAction() {
super("Test action");
}
@Override
public void actionPerformed(ActionEvent e) {
VKApi vkApi = IoC.get(Application.class).getVKApi();
String ownerId = "32659923";
String audioId = "259636837";
vkApi.getById(ownerId, audioId, new Callback<Audio>() {
@Override
public void call(Audio audio) {
Logger.getLogger(TestAction.class.getName()).log(Level.INFO, "loaded audio: {0}", audio);
}
});
}
}
| nikolaas/vk-cache-grabber | src/main/java/org/ns/vk/cachegrabber/ui/TestAction.java | Java | apache-2.0 | 994 |
package com.mapswithme.maps.maplayer.traffic;
import androidx.annotation.MainThread;
import androidx.annotation.NonNull;
import com.mapswithme.util.log.Logger;
import com.mapswithme.util.log.LoggerFactory;
import java.util.ArrayList;
import java.util.List;
@MainThread
public enum TrafficManager
{
INSTANCE;
private final static String TAG = TrafficManager.class.getSimpleName();
@NonNull
private final Logger mLogger = LoggerFactory.INSTANCE.getLogger(LoggerFactory.Type.TRAFFIC);
@NonNull
private final TrafficState.StateChangeListener mStateChangeListener = new TrafficStateListener();
@NonNull
private TrafficState mState = TrafficState.DISABLED;
@NonNull
private final List<TrafficCallback> mCallbacks = new ArrayList<>();
private boolean mInitialized = false;
public void initialize()
{
mLogger.d(TAG, "Initialization of traffic manager and setting the listener for traffic state changes");
TrafficState.nativeSetListener(mStateChangeListener);
mInitialized = true;
}
public void toggle()
{
checkInitialization();
if (isEnabled())
disable();
else
enable();
}
private void enable()
{
mLogger.d(TAG, "Enable traffic");
TrafficState.nativeEnable();
}
private void disable()
{
checkInitialization();
mLogger.d(TAG, "Disable traffic");
TrafficState.nativeDisable();
}
public boolean isEnabled()
{
checkInitialization();
return TrafficState.nativeIsEnabled();
}
public void attach(@NonNull TrafficCallback callback)
{
checkInitialization();
if (mCallbacks.contains(callback))
{
throw new IllegalStateException("A callback '" + callback
+ "' is already attached. Check that the 'detachAll' method was called.");
}
mLogger.d(TAG, "Attach callback '" + callback + "'");
mCallbacks.add(callback);
postPendingState();
}
private void postPendingState()
{
mStateChangeListener.onTrafficStateChanged(mState.ordinal());
}
public void detachAll()
{
checkInitialization();
if (mCallbacks.isEmpty())
{
mLogger.w(TAG, "There are no attached callbacks. Invoke the 'detachAll' method " +
"only when it's really needed!", new Throwable());
return;
}
for (TrafficCallback callback : mCallbacks)
mLogger.d(TAG, "Detach callback '" + callback + "'");
mCallbacks.clear();
}
private void checkInitialization()
{
if (!mInitialized)
throw new AssertionError("Traffic manager is not initialized!");
}
public void setEnabled(boolean enabled)
{
checkInitialization();
if (isEnabled() == enabled)
return;
if (enabled)
enable();
else
disable();
}
private class TrafficStateListener implements TrafficState.StateChangeListener
{
@Override
@MainThread
public void onTrafficStateChanged(int index)
{
TrafficState newTrafficState = TrafficState.values()[index];
mLogger.d(TAG, "onTrafficStateChanged current state = " + mState
+ " new value = " + newTrafficState);
if (mState == newTrafficState)
return;
mState = newTrafficState;
mState.activate(mCallbacks);
}
}
public interface TrafficCallback
{
void onEnabled();
void onDisabled();
void onWaitingData();
void onOutdated();
void onNetworkError();
void onNoData();
void onExpiredData();
void onExpiredApp();
}
}
| rokuz/omim | android/src/com/mapswithme/maps/maplayer/traffic/TrafficManager.java | Java | apache-2.0 | 3,514 |
/*-
* #%L
* Simmetrics - Examples
* %%
* Copyright (C) 2014 - 2021 Simmetrics 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.
* #L%
*/
package com.github.mpkorstanje.simmetrics.example;
import static com.github.mpkorstanje.simmetrics.builders.StringDistanceBuilder.with;
import com.github.mpkorstanje.simmetrics.StringDistance;
import com.github.mpkorstanje.simmetrics.builders.StringDistanceBuilder;
import com.github.mpkorstanje.simmetrics.metrics.EuclideanDistance;
import com.github.mpkorstanje.simmetrics.metrics.StringDistances;
import com.github.mpkorstanje.simmetrics.tokenizers.Tokenizers;
/**
* The StringDistances utility class contains a predefined list of well
* known distance metrics for strings.
*/
final class StringDistanceExample {
/**
* Two strings can be compared using a predefined distance metric.
*/
static float example01() {
String str1 = "This is a sentence. It is made of words";
String str2 = "This sentence is similar. It has almost the same words";
StringDistance metric = StringDistances.levenshtein();
return metric.distance(str1, str2); // 30.0000
}
/**
* A tokenizer is included when the metric is a set or list metric. For the
* euclidean distance, it is a whitespace tokenizer.
*
* Note that most predefined metrics are setup with a whitespace tokenizer.
*/
static float example02() {
String str1 = "A quirky thing it is. This is a sentence.";
String str2 = "This sentence is similar. A quirky thing it is.";
StringDistance metric = StringDistances.euclideanDistance();
return metric.distance(str1, str2); // 2.0000
}
/**
* Using the string distance builder distance metrics can be customized.
* Instead of a whitespace tokenizer a q-gram tokenizer is used.
*
* For more examples see StringDistanceBuilderExample.
*/
static float example03() {
String str1 = "A quirky thing it is. This is a sentence.";
String str2 = "This sentence is similar. A quirky thing it is.";
StringDistance metric =
StringDistanceBuilder.with(new EuclideanDistance<>())
.tokenize(Tokenizers.qGram(3))
.build();
return metric.distance(str1, str2); // 4.8989
}
}
| mpkorstanje/simmetrics | simmetrics-example/src/main/java/com/github/mpkorstanje/simmetrics/example/StringDistanceExample.java | Java | apache-2.0 | 2,695 |
/**
* Copyright (C) 2009 The Android Open Source Project
*
* 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 de.hdodenhof.androidstatemachine;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Looper;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import java.io.FileDescriptor;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.HashMap;
import java.util.Vector;
/**
* <p>The state machine defined here is a hierarchical state machine which processes messages
* and can have states arranged hierarchically.</p>
*
* <p>A state is a <code>State</code> object and must implement
* <code>processMessage</code> and optionally <code>enter/exit/getName</code>.
* The enter/exit methods are equivalent to the construction and destruction
* in Object Oriented programming and are used to perform initialization and
* cleanup of the state respectively. The <code>getName</code> method returns the
* name of the state the default implementation returns the class name it may be
* desirable to have this return the name of the state instance name instead.
* In particular if a particular state class has multiple instances.</p>
*
* <p>When a state machine is created <code>addState</code> is used to build the
* hierarchy and <code>setInitialState</code> is used to identify which of these
* is the initial state. After construction the programmer calls <code>start</code>
* which initializes and starts the state machine. The first action the StateMachine
* is to the invoke <code>enter</code> for all of the initial state's hierarchy,
* starting at its eldest parent. The calls to enter will be done in the context
* of the StateMachines Handler not in the context of the call to start and they
* will be invoked before any messages are processed. For example, given the simple
* state machine below mP1.enter will be invoked and then mS1.enter. Finally,
* messages sent to the state machine will be processed by the current state,
* in our simple state machine below that would initially be mS1.processMessage.</p>
<code>
mP1
/ \
mS2 mS1 ----> initial state
</code>
* <p>After the state machine is created and started, messages are sent to a state
* machine using <code>sendMessage</code> and the messages are created using
* <code>obtainMessage</code>. When the state machine receives a message the
* current state's <code>processMessage</code> is invoked. In the above example
* mS1.processMessage will be invoked first. The state may use <code>transitionTo</code>
* to change the current state to a new state</p>
*
* <p>Each state in the state machine may have a zero or one parent states and if
* a child state is unable to handle a message it may have the message processed
* by its parent by returning false or NOT_HANDLED. If a message is never processed
* <code>unhandledMessage</code> will be invoked to give one last chance for the state machine
* to process the message.</p>
*
* <p>When all processing is completed a state machine may choose to call
* <code>transitionToHaltingState</code>. When the current <code>processingMessage</code>
* returns the state machine will transfer to an internal <code>HaltingState</code>
* and invoke <code>halting</code>. Any message subsequently received by the state
* machine will cause <code>haltedProcessMessage</code> to be invoked.</p>
*
* <p>If it is desirable to completely stop the state machine call <code>quit</code> or
* <code>quitNow</code>. These will call <code>exit</code> of the current state and its parents,
* call <code>onQuiting</code> and then exit Thread/Loopers.</p>
*
* <p>In addition to <code>processMessage</code> each <code>State</code> has
* an <code>enter</code> method and <code>exit</code> method which may be overridden.</p>
*
* <p>Since the states are arranged in a hierarchy transitioning to a new state
* causes current states to be exited and new states to be entered. To determine
* the list of states to be entered/exited the common parent closest to
* the current state is found. We then exit from the current state and its
* parent's up to but not including the common parent state and then enter all
* of the new states below the common parent down to the destination state.
* If there is no common parent all states are exited and then the new states
* are entered.</p>
*
* <p>Two other methods that states can use are <code>deferMessage</code> and
* <code>sendMessageAtFrontOfQueue</code>. The <code>sendMessageAtFrontOfQueue</code> sends
* a message but places it on the front of the queue rather than the back. The
* <code>deferMessage</code> causes the message to be saved on a list until a
* transition is made to a new state. At which time all of the deferred messages
* will be put on the front of the state machine queue with the oldest message
* at the front. These will then be processed by the new current state before
* any other messages that are on the queue or might be added later. Both of
* these are protected and may only be invoked from within a state machine.</p>
*
* <p>To illustrate some of these properties we'll use state machine with an 8
* state hierarchy:</p>
<code>
mP0
/ \
mP1 mS0
/ \
mS2 mS1
/ \ \
mS3 mS4 mS5 ---> initial state
</code>
* <p>After starting mS5 the list of active states is mP0, mP1, mS1 and mS5.
* So the order of calling processMessage when a message is received is mS5,
* mS1, mP1, mP0 assuming each processMessage indicates it can't handle this
* message by returning false or NOT_HANDLED.</p>
*
* <p>Now assume mS5.processMessage receives a message it can handle, and during
* the handling determines the machine should change states. It could call
* transitionTo(mS4) and return true or HANDLED. Immediately after returning from
* processMessage the state machine runtime will find the common parent,
* which is mP1. It will then call mS5.exit, mS1.exit, mS2.enter and then
* mS4.enter. The new list of active states is mP0, mP1, mS2 and mS4. So
* when the next message is received mS4.processMessage will be invoked.</p>
*
* <p>Now for some concrete examples, here is the canonical HelloWorld as a state machine.
* It responds with "Hello World" being printed to the log for every message.</p>
<code>
class HelloWorld extends StateMachine {
HelloWorld(String name) {
super(name);
addState(mState1);
setInitialState(mState1);
}
public static HelloWorld makeHelloWorld() {
HelloWorld hw = new HelloWorld("hw");
hw.start();
return hw;
}
class State1 extends State {
@Override public boolean processMessage(Message message) {
log("Hello World");
return HANDLED;
}
}
State1 mState1 = new State1();
}
void testHelloWorld() {
HelloWorld hw = makeHelloWorld();
hw.sendMessage(hw.obtainMessage());
}
</code>
* <p>A more interesting state machine is one with four states
* with two independent parent states.</p>
<code>
mP1 mP2
/ \
mS2 mS1
</code>
* <p>Here is a description of this state machine using pseudo code.</p>
<code>
state mP1 {
enter { log("mP1.enter"); }
exit { log("mP1.exit"); }
on msg {
CMD_2 {
send(CMD_3);
defer(msg);
transitonTo(mS2);
return HANDLED;
}
return NOT_HANDLED;
}
}
INITIAL
state mS1 parent mP1 {
enter { log("mS1.enter"); }
exit { log("mS1.exit"); }
on msg {
CMD_1 {
transitionTo(mS1);
return HANDLED;
}
return NOT_HANDLED;
}
}
state mS2 parent mP1 {
enter { log("mS2.enter"); }
exit { log("mS2.exit"); }
on msg {
CMD_2 {
send(CMD_4);
return HANDLED;
}
CMD_3 {
defer(msg);
transitionTo(mP2);
return HANDLED;
}
return NOT_HANDLED;
}
}
state mP2 {
enter {
log("mP2.enter");
send(CMD_5);
}
exit { log("mP2.exit"); }
on msg {
CMD_3, CMD_4 { return HANDLED; }
CMD_5 {
transitionTo(HaltingState);
return HANDLED;
}
return NOT_HANDLED;
}
}
</code>
* <p>The implementation is below and also in StateMachineTest:</p>
<code>
class Hsm1 extends StateMachine {
public static final int CMD_1 = 1;
public static final int CMD_2 = 2;
public static final int CMD_3 = 3;
public static final int CMD_4 = 4;
public static final int CMD_5 = 5;
public static Hsm1 makeHsm1() {
log("makeHsm1 E");
Hsm1 sm = new Hsm1("hsm1");
sm.start();
log("makeHsm1 X");
return sm;
}
Hsm1(String name) {
super(name);
log("ctor E");
// Add states, use indentation to show hierarchy
addState(mP1);
addState(mS1, mP1);
addState(mS2, mP1);
addState(mP2);
// Set the initial state
setInitialState(mS1);
log("ctor X");
}
class P1 extends State {
@Override public void enter() {
log("mP1.enter");
}
@Override public boolean processMessage(Message message) {
boolean retVal;
log("mP1.processMessage what=" + message.what);
switch(message.what) {
case CMD_2:
// CMD_2 will arrive in mS2 before CMD_3
sendMessage(obtainMessage(CMD_3));
deferMessage(message);
transitionTo(mS2);
retVal = HANDLED;
break;
default:
// Any message we don't understand in this state invokes unhandledMessage
retVal = NOT_HANDLED;
break;
}
return retVal;
}
@Override public void exit() {
log("mP1.exit");
}
}
class S1 extends State {
@Override public void enter() {
log("mS1.enter");
}
@Override public boolean processMessage(Message message) {
log("S1.processMessage what=" + message.what);
if (message.what == CMD_1) {
// Transition to ourself to show that enter/exit is called
transitionTo(mS1);
return HANDLED;
} else {
// Let parent process all other messages
return NOT_HANDLED;
}
}
@Override public void exit() {
log("mS1.exit");
}
}
class S2 extends State {
@Override public void enter() {
log("mS2.enter");
}
@Override public boolean processMessage(Message message) {
boolean retVal;
log("mS2.processMessage what=" + message.what);
switch(message.what) {
case(CMD_2):
sendMessage(obtainMessage(CMD_4));
retVal = HANDLED;
break;
case(CMD_3):
deferMessage(message);
transitionTo(mP2);
retVal = HANDLED;
break;
default:
retVal = NOT_HANDLED;
break;
}
return retVal;
}
@Override public void exit() {
log("mS2.exit");
}
}
class P2 extends State {
@Override public void enter() {
log("mP2.enter");
sendMessage(obtainMessage(CMD_5));
}
@Override public boolean processMessage(Message message) {
log("P2.processMessage what=" + message.what);
switch(message.what) {
case(CMD_3):
break;
case(CMD_4):
break;
case(CMD_5):
transitionToHaltingState();
break;
}
return HANDLED;
}
@Override public void exit() {
log("mP2.exit");
}
}
@Override
void onHalting() {
log("halting");
synchronized (this) {
this.notifyAll();
}
}
P1 mP1 = new P1();
S1 mS1 = new S1();
S2 mS2 = new S2();
P2 mP2 = new P2();
}
</code>
* <p>If this is executed by sending two messages CMD_1 and CMD_2
* (Note the synchronize is only needed because we use hsm.wait())</p>
<code>
Hsm1 hsm = makeHsm1();
synchronize(hsm) {
hsm.sendMessage(obtainMessage(hsm.CMD_1));
hsm.sendMessage(obtainMessage(hsm.CMD_2));
try {
// wait for the messages to be handled
hsm.wait();
} catch (InterruptedException e) {
loge("exception while waiting " + e.getMessage());
}
}
</code>
* <p>The output is:</p>
<code>
D/hsm1 ( 1999): makeHsm1 E
D/hsm1 ( 1999): ctor E
D/hsm1 ( 1999): ctor X
D/hsm1 ( 1999): mP1.enter
D/hsm1 ( 1999): mS1.enter
D/hsm1 ( 1999): makeHsm1 X
D/hsm1 ( 1999): mS1.processMessage what=1
D/hsm1 ( 1999): mS1.exit
D/hsm1 ( 1999): mS1.enter
D/hsm1 ( 1999): mS1.processMessage what=2
D/hsm1 ( 1999): mP1.processMessage what=2
D/hsm1 ( 1999): mS1.exit
D/hsm1 ( 1999): mS2.enter
D/hsm1 ( 1999): mS2.processMessage what=2
D/hsm1 ( 1999): mS2.processMessage what=3
D/hsm1 ( 1999): mS2.exit
D/hsm1 ( 1999): mP1.exit
D/hsm1 ( 1999): mP2.enter
D/hsm1 ( 1999): mP2.processMessage what=3
D/hsm1 ( 1999): mP2.processMessage what=4
D/hsm1 ( 1999): mP2.processMessage what=5
D/hsm1 ( 1999): mP2.exit
D/hsm1 ( 1999): halting
</code>
*/
public class StateMachine {
// Name of the state machine and used as logging tag
private String mName;
/** Message.what value when quitting */
private static final int SM_QUIT_CMD = -1;
/** Message.what value when initializing */
private static final int SM_INIT_CMD = -2;
/**
* Convenience constant that maybe returned by processMessage
* to indicate the the message was processed and is not to be
* processed by parent states
*/
public static final boolean HANDLED = true;
/**
* Convenience constant that maybe returned by processMessage
* to indicate the the message was NOT processed and is to be
* processed by parent states
*/
public static final boolean NOT_HANDLED = false;
/**
* StateMachine logging record.
*/
public static class LogRec {
private StateMachine mSm;
private long mTime;
private int mWhat;
private String mInfo;
private IState mState;
private IState mOrgState;
private IState mDstState;
/**
* Constructor
*
* @param msg
* @param state the state which handled the message
* @param orgState is the first state the received the message but
* did not processes the message.
* @param transToState is the state that was transitioned to after the message was
* processed.
*/
LogRec(StateMachine sm, Message msg, String info, IState state, IState orgState,
IState transToState) {
update(sm, msg, info, state, orgState, transToState);
}
/**
* Update the information in the record.
* @param state that handled the message
* @param orgState is the first state the received the message
* @param dstState is the state that was the transition target when logging
*/
public void update(StateMachine sm, Message msg, String info, IState state, IState orgState,
IState dstState) {
mSm = sm;
mTime = System.currentTimeMillis();
mWhat = (msg != null) ? msg.what : 0;
mInfo = info;
mState = state;
mOrgState = orgState;
mDstState = dstState;
}
/**
* @return time stamp
*/
public long getTime() {
return mTime;
}
/**
* @return msg.what
*/
public long getWhat() {
return mWhat;
}
/**
* @return the command that was executing
*/
public String getInfo() {
return mInfo;
}
/**
* @return the state that handled this message
*/
public IState getState() {
return mState;
}
/**
* @return the state destination state if a transition is occurring or null if none.
*/
public IState getDestState() {
return mDstState;
}
/**
* @return the original state that received the message.
*/
public IState getOriginalState() {
return mOrgState;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("time=");
Calendar c = Calendar.getInstance();
c.setTimeInMillis(mTime);
sb.append(String.format("%tm-%td %tH:%tM:%tS.%tL", c, c, c, c, c, c));
sb.append(" processed=");
sb.append(mState == null ? "<null>" : mState.getName());
sb.append(" org=");
sb.append(mOrgState == null ? "<null>" : mOrgState.getName());
sb.append(" dest=");
sb.append(mDstState == null ? "<null>" : mDstState.getName());
sb.append(" what=");
String what = mSm != null ? mSm.getWhatToString(mWhat) : "";
if (TextUtils.isEmpty(what)) {
sb.append(mWhat);
sb.append("(0x");
sb.append(Integer.toHexString(mWhat));
sb.append(")");
} else {
sb.append(what);
}
if (!TextUtils.isEmpty(mInfo)) {
sb.append(" ");
sb.append(mInfo);
}
return sb.toString();
}
}
/**
* A list of log records including messages recently processed by the state machine.
*
* The class maintains a list of log records including messages
* recently processed. The list is finite and may be set in the
* constructor or by calling setSize. The public interface also
* includes size which returns the number of recent records,
* count which is the number of records processed since the
* the last setSize, get which returns a record and
* add which adds a record.
*/
private static class LogRecords {
private static final int DEFAULT_SIZE = 20;
private Vector<LogRec> mLogRecVector = new Vector<LogRec>();
private int mMaxSize = DEFAULT_SIZE;
private int mOldestIndex = 0;
private int mCount = 0;
private boolean mLogOnlyTransitions = false;
/**
* private constructor use add
*/
private LogRecords() {
}
/**
* Set size of messages to maintain and clears all current records.
*
* @param maxSize number of records to maintain at anyone time.
*/
synchronized void setSize(int maxSize) {
mMaxSize = maxSize;
mCount = 0;
mLogRecVector.clear();
}
synchronized void setLogOnlyTransitions(boolean enable) {
mLogOnlyTransitions = enable;
}
synchronized boolean logOnlyTransitions() {
return mLogOnlyTransitions;
}
/**
* @return the number of recent records.
*/
synchronized int size() {
return mLogRecVector.size();
}
/**
* @return the total number of records processed since size was set.
*/
synchronized int count() {
return mCount;
}
/**
* Clear the list of records.
*/
synchronized void cleanup() {
mLogRecVector.clear();
}
/**
* @return the information on a particular record. 0 is the oldest
* record and size()-1 is the newest record. If the index is to
* large null is returned.
*/
synchronized LogRec get(int index) {
int nextIndex = mOldestIndex + index;
if (nextIndex >= mMaxSize) {
nextIndex -= mMaxSize;
}
if (nextIndex >= size()) {
return null;
} else {
return mLogRecVector.get(nextIndex);
}
}
/**
* Add a processed message.
*
* @param msg
* @param messageInfo to be stored
* @param state that handled the message
* @param orgState is the first state the received the message but
* did not processes the message.
* @param transToState is the state that was transitioned to after the message was
* processed.
*
*/
synchronized void add(StateMachine sm, Message msg, String messageInfo, IState state,
IState orgState, IState transToState) {
mCount += 1;
if (mLogRecVector.size() < mMaxSize) {
mLogRecVector.add(new LogRec(sm, msg, messageInfo, state, orgState, transToState));
} else {
LogRec pmi = mLogRecVector.get(mOldestIndex);
mOldestIndex += 1;
if (mOldestIndex >= mMaxSize) {
mOldestIndex = 0;
}
pmi.update(sm, msg, messageInfo, state, orgState, transToState);
}
}
}
private static class SmHandler extends Handler {
/** true if StateMachine has quit */
private boolean mHasQuit = false;
/** The debug flag */
private boolean mDbg = false;
/** The SmHandler object, identifies that message is internal */
private static final Object mSmHandlerObj = new Object();
/** The current message */
private Message mMsg;
/** A list of log records including messages this state machine has processed */
private LogRecords mLogRecords = new LogRecords();
/** true if construction of the state machine has not been completed */
private boolean mIsConstructionCompleted;
/** Stack used to manage the current hierarchy of states */
private StateInfo mStateStack[];
/** Top of mStateStack */
private int mStateStackTopIndex = -1;
/** A temporary stack used to manage the state stack */
private StateInfo mTempStateStack[];
/** The top of the mTempStateStack */
private int mTempStateStackCount;
/** State used when state machine is halted */
private HaltingState mHaltingState = new HaltingState();
/** State used when state machine is quitting */
private QuittingState mQuittingState = new QuittingState();
/** Reference to the StateMachine */
private StateMachine mSm;
/**
* Information about a state.
* Used to maintain the hierarchy.
*/
private class StateInfo {
/** The state */
State state;
/** The parent of this state, null if there is no parent */
StateInfo parentStateInfo;
/** True when the state has been entered and on the stack */
boolean active;
/**
* Convert StateInfo to string
*/
@Override
public String toString() {
return "state=" + state.getName() + ",active=" + active + ",parent="
+ ((parentStateInfo == null) ? "null" : parentStateInfo.state.getName());
}
}
/** The map of all of the states in the state machine */
private HashMap<State, StateInfo> mStateInfo = new HashMap<State, StateInfo>();
/** The initial state that will process the first message */
private State mInitialState;
/** The destination state when transitionTo has been invoked */
private State mDestState;
/** The list of deferred messages */
private ArrayList<Message> mDeferredMessages = new ArrayList<Message>();
/**
* State entered when transitionToHaltingState is called.
*/
private class HaltingState extends State {
@Override
public boolean processMessage(Message msg) {
mSm.haltedProcessMessage(msg);
return true;
}
}
/**
* State entered when a valid quit message is handled.
*/
private class QuittingState extends State {
@Override
public boolean processMessage(Message msg) {
return NOT_HANDLED;
}
}
/**
* Handle messages sent to the state machine by calling
* the current state's processMessage. It also handles
* the enter/exit calls and placing any deferred messages
* back onto the queue when transitioning to a new state.
*/
@Override
public final void handleMessage(Message msg) {
if (!mHasQuit) {
if (mDbg) mSm.log("handleMessage: E msg.what=" + msg.what);
/** Save the current message */
mMsg = msg;
/** State that processed the message */
State msgProcessedState = null;
if (mIsConstructionCompleted) {
/** Normal path */
msgProcessedState = processMsg(msg);
} else if (!mIsConstructionCompleted && (mMsg.what == SM_INIT_CMD)
&& (mMsg.obj == mSmHandlerObj)) {
/** Initial one time path. */
mIsConstructionCompleted = true;
invokeEnterMethods(0);
} else {
throw new RuntimeException("StateMachine.handleMessage: "
+ "The start method not called, received msg: " + msg);
}
performTransitions(msgProcessedState, msg);
// We need to check if mSm == null here as we could be quitting.
if (mDbg && mSm != null) mSm.log("handleMessage: X");
}
}
/**
* Do any transitions
* @param msgProcessedState is the state that processed the message
*/
private void performTransitions(State msgProcessedState, Message msg) {
/**
* If transitionTo has been called, exit and then enter
* the appropriate states. We loop on this to allow
* enter and exit methods to use transitionTo.
*/
State orgState = mStateStack[mStateStackTopIndex].state;
/**
* Record whether message needs to be logged before we transition and
* and we won't log special messages SM_INIT_CMD or SM_QUIT_CMD which
* always set msg.obj to the handler.
*/
boolean recordLogMsg = mSm.recordLogRec(mMsg) && (msg.obj != mSmHandlerObj);
if (mLogRecords.logOnlyTransitions()) {
/** Record only if there is a transition */
if (mDestState != null) {
mLogRecords.add(mSm, mMsg, mSm.getLogRecString(mMsg), msgProcessedState,
orgState, mDestState);
}
} else if (recordLogMsg) {
/** Record message */
mLogRecords.add(mSm, mMsg, mSm.getLogRecString(mMsg), msgProcessedState, orgState,
mDestState);
}
State destState = mDestState;
if (destState != null) {
/**
* Process the transitions including transitions in the enter/exit methods
*/
while (true) {
if (mDbg) mSm.log("handleMessage: new destination call exit/enter");
/**
* Determine the states to exit and enter and return the
* common ancestor state of the enter/exit states. Then
* invoke the exit methods then the enter methods.
*/
StateInfo commonStateInfo = setupTempStateStackWithStatesToEnter(destState);
invokeExitMethods(commonStateInfo);
int stateStackEnteringIndex = moveTempStateStackToStateStack();
invokeEnterMethods(stateStackEnteringIndex);
/**
* Since we have transitioned to a new state we need to have
* any deferred messages moved to the front of the message queue
* so they will be processed before any other messages in the
* message queue.
*/
moveDeferredMessageAtFrontOfQueue();
if (destState != mDestState) {
// A new mDestState so continue looping
destState = mDestState;
} else {
// No change in mDestState so we're done
break;
}
}
mDestState = null;
}
/**
* After processing all transitions check and
* see if the last transition was to quit or halt.
*/
if (destState != null) {
if (destState == mQuittingState) {
/**
* Call onQuitting to let subclasses cleanup.
*/
mSm.onQuitting();
cleanupAfterQuitting();
} else if (destState == mHaltingState) {
/**
* Call onHalting() if we've transitioned to the halting
* state. All subsequent messages will be processed in
* in the halting state which invokes haltedProcessMessage(msg);
*/
mSm.onHalting();
}
}
}
/**
* Cleanup all the static variables and the looper after the SM has been quit.
*/
private final void cleanupAfterQuitting() {
if (mSm.mSmThread != null) {
// If we made the thread then quit looper which stops the thread.
getLooper().quit();
mSm.mSmThread = null;
}
mSm.mSmHandler = null;
mSm = null;
mMsg = null;
mLogRecords.cleanup();
mStateStack = null;
mTempStateStack = null;
mStateInfo.clear();
mInitialState = null;
mDestState = null;
mDeferredMessages.clear();
mHasQuit = true;
}
/**
* Complete the construction of the state machine.
*/
private final void completeConstruction() {
if (mDbg) mSm.log("completeConstruction: E");
/**
* Determine the maximum depth of the state hierarchy
* so we can allocate the state stacks.
*/
int maxDepth = 0;
for (StateInfo si : mStateInfo.values()) {
int depth = 0;
for (StateInfo i = si; i != null; depth++) {
i = i.parentStateInfo;
}
if (maxDepth < depth) {
maxDepth = depth;
}
}
if (mDbg) mSm.log("completeConstruction: maxDepth=" + maxDepth);
mStateStack = new StateInfo[maxDepth];
mTempStateStack = new StateInfo[maxDepth];
setupInitialStateStack();
/** Sending SM_INIT_CMD message to invoke enter methods asynchronously */
sendMessageAtFrontOfQueue(obtainMessage(SM_INIT_CMD, mSmHandlerObj));
if (mDbg) mSm.log("completeConstruction: X");
}
/**
* Process the message. If the current state doesn't handle
* it, call the states parent and so on. If it is never handled then
* call the state machines unhandledMessage method.
* @return the state that processed the message
*/
private final State processMsg(Message msg) {
StateInfo curStateInfo = mStateStack[mStateStackTopIndex];
if (mDbg) {
mSm.log("processMsg: " + curStateInfo.state.getName());
}
if (isQuit(msg)) {
transitionTo(mQuittingState);
} else {
while (!curStateInfo.state.processMessage(msg)) {
/**
* Not processed
*/
curStateInfo = curStateInfo.parentStateInfo;
if (curStateInfo == null) {
/**
* No parents left so it's not handled
*/
mSm.unhandledMessage(msg);
break;
}
if (mDbg) {
mSm.log("processMsg: " + curStateInfo.state.getName());
}
}
}
return (curStateInfo != null) ? curStateInfo.state : null;
}
/**
* Call the exit method for each state from the top of stack
* up to the common ancestor state.
*/
private final void invokeExitMethods(StateInfo commonStateInfo) {
while ((mStateStackTopIndex >= 0)
&& (mStateStack[mStateStackTopIndex] != commonStateInfo)) {
State curState = mStateStack[mStateStackTopIndex].state;
if (mDbg) mSm.log("invokeExitMethods: " + curState.getName());
curState.exit();
mStateStack[mStateStackTopIndex].active = false;
mStateStackTopIndex -= 1;
}
}
/**
* Invoke the enter method starting at the entering index to top of state stack
*/
private final void invokeEnterMethods(int stateStackEnteringIndex) {
for (int i = stateStackEnteringIndex; i <= mStateStackTopIndex; i++) {
if (mDbg) mSm.log("invokeEnterMethods: " + mStateStack[i].state.getName());
mStateStack[i].state.enter();
mStateStack[i].active = true;
}
}
/**
* Move the deferred message to the front of the message queue.
*/
private final void moveDeferredMessageAtFrontOfQueue() {
/**
* The oldest messages on the deferred list must be at
* the front of the queue so start at the back, which
* as the most resent message and end with the oldest
* messages at the front of the queue.
*/
for (int i = mDeferredMessages.size() - 1; i >= 0; i--) {
Message curMsg = mDeferredMessages.get(i);
if (mDbg) mSm.log("moveDeferredMessageAtFrontOfQueue; what=" + curMsg.what);
sendMessageAtFrontOfQueue(curMsg);
}
mDeferredMessages.clear();
}
/**
* Move the contents of the temporary stack to the state stack
* reversing the order of the items on the temporary stack as
* they are moved.
*
* @return index into mStateStack where entering needs to start
*/
private final int moveTempStateStackToStateStack() {
int startingIndex = mStateStackTopIndex + 1;
int i = mTempStateStackCount - 1;
int j = startingIndex;
while (i >= 0) {
if (mDbg) mSm.log("moveTempStackToStateStack: i=" + i + ",j=" + j);
mStateStack[j] = mTempStateStack[i];
j += 1;
i -= 1;
}
mStateStackTopIndex = j - 1;
if (mDbg) {
mSm.log("moveTempStackToStateStack: X mStateStackTop=" + mStateStackTopIndex
+ ",startingIndex=" + startingIndex + ",Top="
+ mStateStack[mStateStackTopIndex].state.getName());
}
return startingIndex;
}
/**
* Setup the mTempStateStack with the states we are going to enter.
*
* This is found by searching up the destState's ancestors for a
* state that is already active i.e. StateInfo.active == true.
* The destStae and all of its inactive parents will be on the
* TempStateStack as the list of states to enter.
*
* @return StateInfo of the common ancestor for the destState and
* current state or null if there is no common parent.
*/
private final StateInfo setupTempStateStackWithStatesToEnter(State destState) {
/**
* Search up the parent list of the destination state for an active
* state. Use a do while() loop as the destState must always be entered
* even if it is active. This can happen if we are exiting/entering
* the current state.
*/
mTempStateStackCount = 0;
StateInfo curStateInfo = mStateInfo.get(destState);
do {
mTempStateStack[mTempStateStackCount++] = curStateInfo;
curStateInfo = curStateInfo.parentStateInfo;
} while ((curStateInfo != null) && !curStateInfo.active);
if (mDbg) {
mSm.log("setupTempStateStackWithStatesToEnter: X mTempStateStackCount="
+ mTempStateStackCount + ",curStateInfo: " + curStateInfo);
}
return curStateInfo;
}
/**
* Initialize StateStack to mInitialState.
*/
private final void setupInitialStateStack() {
if (mDbg) {
mSm.log("setupInitialStateStack: E mInitialState=" + mInitialState.getName());
}
StateInfo curStateInfo = mStateInfo.get(mInitialState);
for (mTempStateStackCount = 0; curStateInfo != null; mTempStateStackCount++) {
mTempStateStack[mTempStateStackCount] = curStateInfo;
curStateInfo = curStateInfo.parentStateInfo;
}
// Empty the StateStack
mStateStackTopIndex = -1;
moveTempStateStackToStateStack();
}
/**
* @return current message
*/
private final Message getCurrentMessage() {
return mMsg;
}
/**
* @return current state
*/
private final IState getCurrentState() {
return mStateStack[mStateStackTopIndex].state;
}
/**
* Add a new state to the state machine. Bottom up addition
* of states is allowed but the same state may only exist
* in one hierarchy.
*
* @param state the state to add
* @param parent the parent of state
* @return stateInfo for this state
*/
private final StateInfo addState(State state, State parent) {
if (mDbg) {
mSm.log("addStateInternal: E state=" + state.getName() + ",parent="
+ ((parent == null) ? "" : parent.getName()));
}
StateInfo parentStateInfo = null;
if (parent != null) {
parentStateInfo = mStateInfo.get(parent);
if (parentStateInfo == null) {
// Recursively add our parent as it's not been added yet.
parentStateInfo = addState(parent, null);
}
}
StateInfo stateInfo = mStateInfo.get(state);
if (stateInfo == null) {
stateInfo = new StateInfo();
mStateInfo.put(state, stateInfo);
}
// Validate that we aren't adding the same state in two different hierarchies.
if ((stateInfo.parentStateInfo != null)
&& (stateInfo.parentStateInfo != parentStateInfo)) {
throw new RuntimeException("state already added");
}
stateInfo.state = state;
stateInfo.parentStateInfo = parentStateInfo;
stateInfo.active = false;
if (mDbg) mSm.log("addStateInternal: X stateInfo: " + stateInfo);
return stateInfo;
}
/**
* Constructor
*
* @param looper for dispatching messages
* @param sm the hierarchical state machine
*/
private SmHandler(Looper looper, StateMachine sm) {
super(looper);
mSm = sm;
addState(mHaltingState, null);
addState(mQuittingState, null);
}
/** @see StateMachine#setInitialState(State) */
private final void setInitialState(State initialState) {
if (mDbg) mSm.log("setInitialState: initialState=" + initialState.getName());
mInitialState = initialState;
}
/** @see StateMachine#transitionTo(IState) */
private final void transitionTo(IState destState) {
mDestState = (State) destState;
if (mDbg) mSm.log("transitionTo: destState=" + mDestState.getName());
}
/** @see StateMachine#deferMessage(Message) */
private final void deferMessage(Message msg) {
if (mDbg) mSm.log("deferMessage: msg=" + msg.what);
/* Copy the "msg" to "newMsg" as "msg" will be recycled */
Message newMsg = obtainMessage();
newMsg.copyFrom(msg);
mDeferredMessages.add(newMsg);
}
/** @see StateMachine#quit() */
private final void quit() {
if (mDbg) mSm.log("quit:");
sendMessage(obtainMessage(SM_QUIT_CMD, mSmHandlerObj));
}
/** @see StateMachine#quitNow() */
private final void quitNow() {
if (mDbg) mSm.log("quitNow:");
sendMessageAtFrontOfQueue(obtainMessage(SM_QUIT_CMD, mSmHandlerObj));
}
/** Validate that the message was sent by quit or quitNow. */
private final boolean isQuit(Message msg) {
return (msg.what == SM_QUIT_CMD) && (msg.obj == mSmHandlerObj);
}
/** @see StateMachine#isDbg() */
private final boolean isDbg() {
return mDbg;
}
/** @see StateMachine#setDbg(boolean) */
private final void setDbg(boolean dbg) {
mDbg = dbg;
}
}
private SmHandler mSmHandler;
private HandlerThread mSmThread;
/**
* Initialize.
*
* @param looper for this state machine
* @param name of the state machine
*/
private void initStateMachine(String name, Looper looper) {
mName = name;
mSmHandler = new SmHandler(looper, this);
}
/**
* Constructor creates a StateMachine with its own thread.
*
* @param name of the state machine
*/
protected StateMachine(String name) {
mSmThread = new HandlerThread(name);
mSmThread.start();
Looper looper = mSmThread.getLooper();
initStateMachine(name, looper);
}
/**
* Constructor creates a StateMachine using the looper.
*
* @param name of the state machine
*/
protected StateMachine(String name, Looper looper) {
initStateMachine(name, looper);
}
/**
* Constructor creates a StateMachine using the handler.
*
* @param name of the state machine
*/
protected StateMachine(String name, Handler handler) {
initStateMachine(name, handler.getLooper());
}
/**
* Add a new state to the state machine
* @param state the state to add
* @param parent the parent of state
*/
protected final void addState(State state, State parent) {
mSmHandler.addState(state, parent);
}
/**
* Add a new state to the state machine, parent will be null
* @param state to add
*/
protected final void addState(State state) {
mSmHandler.addState(state, null);
}
/**
* Set the initial state. This must be invoked before
* and messages are sent to the state machine.
*
* @param initialState is the state which will receive the first message.
*/
protected final void setInitialState(State initialState) {
mSmHandler.setInitialState(initialState);
}
/**
* @return current message
*/
protected final Message getCurrentMessage() {
// mSmHandler can be null if the state machine has quit.
SmHandler smh = mSmHandler;
if (smh == null) return null;
return smh.getCurrentMessage();
}
/**
* @return current state
*/
protected final IState getCurrentState() {
// mSmHandler can be null if the state machine has quit.
SmHandler smh = mSmHandler;
if (smh == null) return null;
return smh.getCurrentState();
}
/**
* transition to destination state. Upon returning
* from processMessage the current state's exit will
* be executed and upon the next message arriving
* destState.enter will be invoked.
*
* this function can also be called inside the enter function of the
* previous transition target, but the behavior is undefined when it is
* called mid-way through a previous transition (for example, calling this
* in the enter() routine of a intermediate node when the current transition
* target is one of the nodes descendants).
*
* @param destState will be the state that receives the next message.
*/
protected final void transitionTo(IState destState) {
mSmHandler.transitionTo(destState);
}
/**
* transition to halt state. Upon returning
* from processMessage we will exit all current
* states, execute the onHalting() method and then
* for all subsequent messages haltedProcessMessage
* will be called.
*/
protected final void transitionToHaltingState() {
mSmHandler.transitionTo(mSmHandler.mHaltingState);
}
/**
* Defer this message until next state transition.
* Upon transitioning all deferred messages will be
* placed on the queue and reprocessed in the original
* order. (i.e. The next state the oldest messages will
* be processed first)
*
* @param msg is deferred until the next transition.
*/
protected final void deferMessage(Message msg) {
mSmHandler.deferMessage(msg);
}
/**
* Called when message wasn't handled
*
* @param msg that couldn't be handled.
*/
protected void unhandledMessage(Message msg) {
if (mSmHandler.mDbg) loge(" - unhandledMessage: msg.what=" + msg.what);
}
/**
* Called for any message that is received after
* transitionToHalting is called.
*/
protected void haltedProcessMessage(Message msg) {
}
/**
* This will be called once after handling a message that called
* transitionToHalting. All subsequent messages will invoke
* {@link StateMachine#haltedProcessMessage(Message)}
*/
protected void onHalting() {
}
/**
* This will be called once after a quit message that was NOT handled by
* the derived StateMachine. The StateMachine will stop and any subsequent messages will be
* ignored. In addition, if this StateMachine created the thread, the thread will
* be stopped after this method returns.
*/
protected void onQuitting() {
}
/**
* @return the name
*/
public final String getName() {
return mName;
}
/**
* Set number of log records to maintain and clears all current records.
*
* @param maxSize number of messages to maintain at anyone time.
*/
public final void setLogRecSize(int maxSize) {
mSmHandler.mLogRecords.setSize(maxSize);
}
/**
* Set to log only messages that cause a state transition
*
* @param enable {@code true} to enable, {@code false} to disable
*/
public final void setLogOnlyTransitions(boolean enable) {
mSmHandler.mLogRecords.setLogOnlyTransitions(enable);
}
/**
* @return number of log records
*/
public final int getLogRecSize() {
// mSmHandler can be null if the state machine has quit.
SmHandler smh = mSmHandler;
if (smh == null) return 0;
return smh.mLogRecords.size();
}
/**
* @return the total number of records processed
*/
public final int getLogRecCount() {
// mSmHandler can be null if the state machine has quit.
SmHandler smh = mSmHandler;
if (smh == null) return 0;
return smh.mLogRecords.count();
}
/**
* @return a log record, or null if index is out of range
*/
public final LogRec getLogRec(int index) {
// mSmHandler can be null if the state machine has quit.
SmHandler smh = mSmHandler;
if (smh == null) return null;
return smh.mLogRecords.get(index);
}
/**
* @return a copy of LogRecs as a collection
*/
public final Collection<LogRec> copyLogRecs() {
Vector<LogRec> vlr = new Vector<LogRec>();
SmHandler smh = mSmHandler;
if (smh != null) {
for (LogRec lr : smh.mLogRecords.mLogRecVector) {
vlr.add(lr);
}
}
return vlr;
}
/**
* Add the string to LogRecords.
*
* @param string
*/
protected void addLogRec(String string) {
// mSmHandler can be null if the state machine has quit.
SmHandler smh = mSmHandler;
if (smh == null) return;
smh.mLogRecords.add(this, smh.getCurrentMessage(), string, smh.getCurrentState(),
smh.mStateStack[smh.mStateStackTopIndex].state, smh.mDestState);
}
/**
* @return true if msg should be saved in the log, default is true.
*/
protected boolean recordLogRec(Message msg) {
return true;
}
/**
* Return a string to be logged by LogRec, default
* is an empty string. Override if additional information is desired.
*
* @param msg that was processed
* @return information to be logged as a String
*/
protected String getLogRecString(Message msg) {
return "";
}
/**
* @return the string for msg.what
*/
protected String getWhatToString(int what) {
return null;
}
/**
* @return Handler, maybe null if state machine has quit.
*/
public final Handler getHandler() {
return mSmHandler;
}
/**
* Get a message and set Message.target state machine handler.
*
* Note: The handler can be null if the state machine has quit,
* which means target will be null and may cause a AndroidRuntimeException
* in MessageQueue#enqueMessage if sent directly or if sent using
* StateMachine#sendMessage the message will just be ignored.
*
* @return A Message object from the global pool
*/
public final Message obtainMessage() {
return Message.obtain(mSmHandler);
}
/**
* Get a message and set Message.target state machine handler, what.
*
* Note: The handler can be null if the state machine has quit,
* which means target will be null and may cause a AndroidRuntimeException
* in MessageQueue#enqueMessage if sent directly or if sent using
* StateMachine#sendMessage the message will just be ignored.
*
* @param what is the assigned to Message.what.
* @return A Message object from the global pool
*/
public final Message obtainMessage(int what) {
return Message.obtain(mSmHandler, what);
}
/**
* Get a message and set Message.target state machine handler,
* what and obj.
*
* Note: The handler can be null if the state machine has quit,
* which means target will be null and may cause a AndroidRuntimeException
* in MessageQueue#enqueMessage if sent directly or if sent using
* StateMachine#sendMessage the message will just be ignored.
*
* @param what is the assigned to Message.what.
* @param obj is assigned to Message.obj.
* @return A Message object from the global pool
*/
public final Message obtainMessage(int what, Object obj) {
return Message.obtain(mSmHandler, what, obj);
}
/**
* Get a message and set Message.target state machine handler,
* what, arg1 and arg2
*
* Note: The handler can be null if the state machine has quit,
* which means target will be null and may cause a AndroidRuntimeException
* in MessageQueue#enqueMessage if sent directly or if sent using
* StateMachine#sendMessage the message will just be ignored.
*
* @param what is assigned to Message.what
* @param arg1 is assigned to Message.arg1
* @return A Message object from the global pool
*/
public final Message obtainMessage(int what, int arg1) {
// use this obtain so we don't match the obtain(h, what, Object) method
return Message.obtain(mSmHandler, what, arg1, 0);
}
/**
* Get a message and set Message.target state machine handler,
* what, arg1 and arg2
*
* Note: The handler can be null if the state machine has quit,
* which means target will be null and may cause a AndroidRuntimeException
* in MessageQueue#enqueMessage if sent directly or if sent using
* StateMachine#sendMessage the message will just be ignored.
*
* @param what is assigned to Message.what
* @param arg1 is assigned to Message.arg1
* @param arg2 is assigned to Message.arg2
* @return A Message object from the global pool
*/
public final Message obtainMessage(int what, int arg1, int arg2) {
return Message.obtain(mSmHandler, what, arg1, arg2);
}
/**
* Get a message and set Message.target state machine handler,
* what, arg1, arg2 and obj
*
* Note: The handler can be null if the state machine has quit,
* which means target will be null and may cause a AndroidRuntimeException
* in MessageQueue#enqueMessage if sent directly or if sent using
* StateMachine#sendMessage the message will just be ignored.
*
* @param what is assigned to Message.what
* @param arg1 is assigned to Message.arg1
* @param arg2 is assigned to Message.arg2
* @param obj is assigned to Message.obj
* @return A Message object from the global pool
*/
public final Message obtainMessage(int what, int arg1, int arg2, Object obj) {
return Message.obtain(mSmHandler, what, arg1, arg2, obj);
}
/**
* Enqueue a message to this state machine.
*
* Message is ignored if state machine has quit.
*/
public final void sendMessage(int what) {
// mSmHandler can be null if the state machine has quit.
SmHandler smh = mSmHandler;
if (smh == null) return;
smh.sendMessage(obtainMessage(what));
}
/**
* Enqueue a message to this state machine.
*
* Message is ignored if state machine has quit.
*/
public final void sendMessage(int what, Object obj) {
// mSmHandler can be null if the state machine has quit.
SmHandler smh = mSmHandler;
if (smh == null) return;
smh.sendMessage(obtainMessage(what, obj));
}
/**
* Enqueue a message to this state machine.
*
* Message is ignored if state machine has quit.
*/
public final void sendMessage(int what, int arg1) {
// mSmHandler can be null if the state machine has quit.
SmHandler smh = mSmHandler;
if (smh == null) return;
smh.sendMessage(obtainMessage(what, arg1));
}
/**
* Enqueue a message to this state machine.
*
* Message is ignored if state machine has quit.
*/
public final void sendMessage(int what, int arg1, int arg2) {
// mSmHandler can be null if the state machine has quit.
SmHandler smh = mSmHandler;
if (smh == null) return;
smh.sendMessage(obtainMessage(what, arg1, arg2));
}
/**
* Enqueue a message to this state machine.
*
* Message is ignored if state machine has quit.
*/
public final void sendMessage(int what, int arg1, int arg2, Object obj) {
// mSmHandler can be null if the state machine has quit.
SmHandler smh = mSmHandler;
if (smh == null) return;
smh.sendMessage(obtainMessage(what, arg1, arg2, obj));
}
/**
* Enqueue a message to this state machine.
*
* Message is ignored if state machine has quit.
*/
public final void sendMessage(Message msg) {
// mSmHandler can be null if the state machine has quit.
SmHandler smh = mSmHandler;
if (smh == null) return;
smh.sendMessage(msg);
}
/**
* Enqueue a message to this state machine after a delay.
*
* Message is ignored if state machine has quit.
*/
public final void sendMessageDelayed(int what, long delayMillis) {
// mSmHandler can be null if the state machine has quit.
SmHandler smh = mSmHandler;
if (smh == null) return;
smh.sendMessageDelayed(obtainMessage(what), delayMillis);
}
/**
* Enqueue a message to this state machine after a delay.
*
* Message is ignored if state machine has quit.
*/
public final void sendMessageDelayed(int what, Object obj, long delayMillis) {
// mSmHandler can be null if the state machine has quit.
SmHandler smh = mSmHandler;
if (smh == null) return;
smh.sendMessageDelayed(obtainMessage(what, obj), delayMillis);
}
/**
* Enqueue a message to this state machine after a delay.
*
* Message is ignored if state machine has quit.
*/
public final void sendMessageDelayed(int what, int arg1, long delayMillis) {
// mSmHandler can be null if the state machine has quit.
SmHandler smh = mSmHandler;
if (smh == null) return;
smh.sendMessageDelayed(obtainMessage(what, arg1), delayMillis);
}
/**
* Enqueue a message to this state machine after a delay.
*
* Message is ignored if state machine has quit.
*/
public final void sendMessageDelayed(int what, int arg1, int arg2, long delayMillis) {
// mSmHandler can be null if the state machine has quit.
SmHandler smh = mSmHandler;
if (smh == null) return;
smh.sendMessageDelayed(obtainMessage(what, arg1, arg2), delayMillis);
}
/**
* Enqueue a message to this state machine after a delay.
*
* Message is ignored if state machine has quit.
*/
public final void sendMessageDelayed(int what, int arg1, int arg2, Object obj,
long delayMillis) {
// mSmHandler can be null if the state machine has quit.
SmHandler smh = mSmHandler;
if (smh == null) return;
smh.sendMessageDelayed(obtainMessage(what, arg1, arg2, obj), delayMillis);
}
/**
* Enqueue a message to this state machine after a delay.
*
* Message is ignored if state machine has quit.
*/
public final void sendMessageDelayed(Message msg, long delayMillis) {
// mSmHandler can be null if the state machine has quit.
SmHandler smh = mSmHandler;
if (smh == null) return;
smh.sendMessageDelayed(msg, delayMillis);
}
/**
* Enqueue a message to the front of the queue for this state machine.
* Protected, may only be called by instances of StateMachine.
*
* Message is ignored if state machine has quit.
*/
protected final void sendMessageAtFrontOfQueue(int what) {
// mSmHandler can be null if the state machine has quit.
SmHandler smh = mSmHandler;
if (smh == null) return;
smh.sendMessageAtFrontOfQueue(obtainMessage(what));
}
/**
* Enqueue a message to the front of the queue for this state machine.
* Protected, may only be called by instances of StateMachine.
*
* Message is ignored if state machine has quit.
*/
protected final void sendMessageAtFrontOfQueue(int what, Object obj) {
// mSmHandler can be null if the state machine has quit.
SmHandler smh = mSmHandler;
if (smh == null) return;
smh.sendMessageAtFrontOfQueue(obtainMessage(what, obj));
}
/**
* Enqueue a message to the front of the queue for this state machine.
* Protected, may only be called by instances of StateMachine.
*
* Message is ignored if state machine has quit.
*/
protected final void sendMessageAtFrontOfQueue(int what, int arg1) {
// mSmHandler can be null if the state machine has quit.
SmHandler smh = mSmHandler;
if (smh == null) return;
smh.sendMessageAtFrontOfQueue(obtainMessage(what, arg1));
}
/**
* Enqueue a message to the front of the queue for this state machine.
* Protected, may only be called by instances of StateMachine.
*
* Message is ignored if state machine has quit.
*/
protected final void sendMessageAtFrontOfQueue(int what, int arg1, int arg2) {
// mSmHandler can be null if the state machine has quit.
SmHandler smh = mSmHandler;
if (smh == null) return;
smh.sendMessageAtFrontOfQueue(obtainMessage(what, arg1, arg2));
}
/**
* Enqueue a message to the front of the queue for this state machine.
* Protected, may only be called by instances of StateMachine.
*
* Message is ignored if state machine has quit.
*/
protected final void sendMessageAtFrontOfQueue(int what, int arg1, int arg2, Object obj) {
// mSmHandler can be null if the state machine has quit.
SmHandler smh = mSmHandler;
if (smh == null) return;
smh.sendMessageAtFrontOfQueue(obtainMessage(what, arg1, arg2, obj));
}
/**
* Enqueue a message to the front of the queue for this state machine.
* Protected, may only be called by instances of StateMachine.
*
* Message is ignored if state machine has quit.
*/
protected final void sendMessageAtFrontOfQueue(Message msg) {
// mSmHandler can be null if the state machine has quit.
SmHandler smh = mSmHandler;
if (smh == null) return;
smh.sendMessageAtFrontOfQueue(msg);
}
/**
* Removes a message from the message queue.
* Protected, may only be called by instances of StateMachine.
*/
protected final void removeMessages(int what) {
// mSmHandler can be null if the state machine has quit.
SmHandler smh = mSmHandler;
if (smh == null) return;
smh.removeMessages(what);
}
/**
* Validate that the message was sent by
* {@link StateMachine#quit} or {@link StateMachine#quitNow}.
* */
protected final boolean isQuit(Message msg) {
// mSmHandler can be null if the state machine has quit.
SmHandler smh = mSmHandler;
if (smh == null) return msg.what == SM_QUIT_CMD;
return smh.isQuit(msg);
}
/**
* Quit the state machine after all currently queued up messages are processed.
*/
protected final void quit() {
// mSmHandler can be null if the state machine is already stopped.
SmHandler smh = mSmHandler;
if (smh == null) return;
smh.quit();
}
/**
* Quit the state machine immediately all currently queued messages will be discarded.
*/
protected final void quitNow() {
// mSmHandler can be null if the state machine is already stopped.
SmHandler smh = mSmHandler;
if (smh == null) return;
smh.quitNow();
}
/**
* @return if debugging is enabled
*/
public boolean isDbg() {
// mSmHandler can be null if the state machine has quit.
SmHandler smh = mSmHandler;
if (smh == null) return false;
return smh.isDbg();
}
/**
* Set debug enable/disabled.
*
* @param dbg is true to enable debugging.
*/
public void setDbg(boolean dbg) {
// mSmHandler can be null if the state machine has quit.
SmHandler smh = mSmHandler;
if (smh == null) return;
smh.setDbg(dbg);
}
/**
* Start the state machine.
*/
public void start() {
// mSmHandler can be null if the state machine has quit.
SmHandler smh = mSmHandler;
if (smh == null) return;
/** Send the complete construction message */
smh.completeConstruction();
}
/**
* Dump the current state.
*
* @param fd
* @param pw
* @param args
*/
public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
pw.println(getName() + ":");
pw.println(" total records=" + getLogRecCount());
for (int i = 0; i < getLogRecSize(); i++) {
pw.printf(" rec[%d]: %s\n", i, getLogRec(i).toString());
pw.flush();
}
pw.println("curState=" + getCurrentState().getName());
}
/**
* Log with debug and add to the LogRecords.
*
* @param s is string log
*/
protected void logAndAddLogRec(String s) {
addLogRec(s);
log(s);
}
/**
* Log with debug
*
* @param s is string log
*/
protected void log(String s) {
Log.d(mName, s);
}
/**
* Log with debug attribute
*
* @param s is string log
*/
protected void logd(String s) {
Log.d(mName, s);
}
/**
* Log with verbose attribute
*
* @param s is string log
*/
protected void logv(String s) {
Log.v(mName, s);
}
/**
* Log with info attribute
*
* @param s is string log
*/
protected void logi(String s) {
Log.i(mName, s);
}
/**
* Log with warning attribute
*
* @param s is string log
*/
protected void logw(String s) {
Log.w(mName, s);
}
/**
* Log with error attribute
*
* @param s is string log
*/
protected void loge(String s) {
Log.e(mName, s);
}
/**
* Log with error attribute
*
* @param s is string log
* @param e is a Throwable which logs additional information.
*/
protected void loge(String s, Throwable e) {
Log.e(mName, s, e);
}
}
| hdodenhof/AndroidStateMachine | library/src/main/java/de/hdodenhof/androidstatemachine/StateMachine.java | Java | apache-2.0 | 68,024 |
// stdafx.cpp : source file that includes just the standard includes
// importkeyboard.pch will be the pre-compiled header
// stdafx.obj will contain the pre-compiled type information
#include "stdafx.h"
// TODO: reference any additional headers you need in STDAFX.H
// and not in this file
| tavultesoft/keymanweb | windows/src/test/mnemonic-to-positional/importkeyboard/importkeyboard/stdafx.cpp | C++ | apache-2.0 | 293 |
namespace GeolocationBoundingBox.Google.Json
{
public class Geometry
{
public Location location { get; set; }
public string location_type { get; set; }
public Viewport viewport { get; set; }
public Bounds bounds { get; set; }
}
} | saitolabs/geolocation-bounding-box | src/GeolocationBoundingBox.Google/Json/Geometry.cs | C# | apache-2.0 | 273 |
package th.ac.kmitl.ce.ooad.cest.repository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import th.ac.kmitl.ce.ooad.cest.domain.Course;
import th.ac.kmitl.ce.ooad.cest.domain.Faculty;
import java.util.List;
public interface CourseRepository extends CrudRepository<Course, Long>{
Course findFirstByCourseId(String courseId);
Course findFirstByCourseName(String courseName);
List<Course> findByCourseNameContainingOrCourseIdContainingOrderByCourseNameAsc(String courseName, String courseId);
List<Course> findByFacultyOrderByCourseNameAsc(Faculty faculty);
List<Course> findByDepartmentOrderByCourseNameAsc(String department);
@Query("select c from Course c where c.department = ?2 or c.department = '' and c.faculty = ?1 order by c.courseName")
List<Course> findByFacultyAndDepartmentOrNone(Faculty faculty, String department);
}
| CE-KMITL-OOAD-2015/CE-SMART-TRACKER-DEV | CE Smart Tracker Server/src/main/java/th/ac/kmitl/ce/ooad/cest/repository/CourseRepository.java | Java | apache-2.0 | 930 |
macimport os
import subprocess
name = "gobuildmaster"
current_hash = ""
for line in os.popen("md5sum " + name).readlines():
current_hash = line.split(' ')[0]
# Move the old version over
for line in os.popen('cp ' + name + ' old' + name).readlines():
print line.strip()
# Rebuild
for line in os.popen('go build').readlines():
print line.strip()
size_1 = os.path.getsize('./old' + name)
size_2 = os.path.getsize('./' + name)
lines = os.popen('ps -ef | grep ' + name).readlines()
running = False
for line in lines:
if "./" + name in line:
running = True
new_hash = ""
for line in os.popen("md5sum " + name).readlines():
new_hash = line.split(' ')[0]
if size_1 != size_2 or new_hash != current_hash or not running:
if not running:
for line in os.popen('cat out.txt | mail -E -s "Crash Report ' + name + '" brotherlogic@gmail.com').readlines():
pass
for line in os.popen('echo "" > out.txt').readlines():
pass
for line in os.popen('killall ' + name).readlines():
pass
subprocess.Popen(['./' + name])
| brotherlogic/gobuildmaster | BuildAndRun.py | Python | apache-2.0 | 1,102 |
# Copyright 2012 OpenStack Foundation
# 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.
import json
from six.moves.urllib import parse as urllib
from tempest_lib import exceptions as lib_exc
from tempest.api_schema.response.compute.v2_1 import images as schema
from tempest.common import service_client
from tempest.common import waiters
class ImagesClientJSON(service_client.ServiceClient):
def create_image(self, server_id, name, meta=None):
"""Creates an image of the original server."""
post_body = {
'createImage': {
'name': name,
}
}
if meta is not None:
post_body['createImage']['metadata'] = meta
post_body = json.dumps(post_body)
resp, body = self.post('servers/%s/action' % str(server_id),
post_body)
self.validate_response(schema.create_image, resp, body)
return service_client.ResponseBody(resp, body)
def list_images(self, params=None):
"""Returns a list of all images filtered by any parameters."""
url = 'images'
if params:
url += '?%s' % urllib.urlencode(params)
resp, body = self.get(url)
body = json.loads(body)
self.validate_response(schema.list_images, resp, body)
return service_client.ResponseBodyList(resp, body['images'])
def list_images_with_detail(self, params=None):
"""Returns a detailed list of images filtered by any parameters."""
url = 'images/detail'
if params:
url += '?%s' % urllib.urlencode(params)
resp, body = self.get(url)
body = json.loads(body)
self.validate_response(schema.list_images_details, resp, body)
return service_client.ResponseBodyList(resp, body['images'])
def show_image(self, image_id):
"""Returns the details of a single image."""
resp, body = self.get("images/%s" % str(image_id))
self.expected_success(200, resp.status)
body = json.loads(body)
self.validate_response(schema.get_image, resp, body)
return service_client.ResponseBody(resp, body['image'])
def delete_image(self, image_id):
"""Deletes the provided image."""
resp, body = self.delete("images/%s" % str(image_id))
self.validate_response(schema.delete, resp, body)
return service_client.ResponseBody(resp, body)
def wait_for_image_status(self, image_id, status):
"""Waits for an image to reach a given status."""
waiters.wait_for_image_status(self, image_id, status)
def list_image_metadata(self, image_id):
"""Lists all metadata items for an image."""
resp, body = self.get("images/%s/metadata" % str(image_id))
body = json.loads(body)
self.validate_response(schema.image_metadata, resp, body)
return service_client.ResponseBody(resp, body['metadata'])
def set_image_metadata(self, image_id, meta):
"""Sets the metadata for an image."""
post_body = json.dumps({'metadata': meta})
resp, body = self.put('images/%s/metadata' % str(image_id), post_body)
body = json.loads(body)
self.validate_response(schema.image_metadata, resp, body)
return service_client.ResponseBody(resp, body['metadata'])
def update_image_metadata(self, image_id, meta):
"""Updates the metadata for an image."""
post_body = json.dumps({'metadata': meta})
resp, body = self.post('images/%s/metadata' % str(image_id), post_body)
body = json.loads(body)
self.validate_response(schema.image_metadata, resp, body)
return service_client.ResponseBody(resp, body['metadata'])
def get_image_metadata_item(self, image_id, key):
"""Returns the value for a specific image metadata key."""
resp, body = self.get("images/%s/metadata/%s" % (str(image_id), key))
body = json.loads(body)
self.validate_response(schema.image_meta_item, resp, body)
return service_client.ResponseBody(resp, body['meta'])
def set_image_metadata_item(self, image_id, key, meta):
"""Sets the value for a specific image metadata key."""
post_body = json.dumps({'meta': meta})
resp, body = self.put('images/%s/metadata/%s' % (str(image_id), key),
post_body)
body = json.loads(body)
self.validate_response(schema.image_meta_item, resp, body)
return service_client.ResponseBody(resp, body['meta'])
def delete_image_metadata_item(self, image_id, key):
"""Deletes a single image metadata key/value pair."""
resp, body = self.delete("images/%s/metadata/%s" %
(str(image_id), key))
self.validate_response(schema.delete, resp, body)
return service_client.ResponseBody(resp, body)
def is_resource_deleted(self, id):
try:
self.show_image(id)
except lib_exc.NotFound:
return True
return False
@property
def resource_type(self):
"""Returns the primary type of resource this client works with."""
return 'image'
| yamt/tempest | tempest/services/compute/json/images_client.py | Python | apache-2.0 | 5,741 |
using System;
using System.Data;
using System.Text;
using System.Data.SqlClient;
using Maticsoft.DBUtility;//ÇëÏÈÌí¼ÓÒýÓÃ
namespace TSM.DAL
{
/// <summary>
/// Êý¾Ý·ÃÎÊÀàCK_People¡£
/// </summary>
public class CK_People
{
public CK_People()
{}
#region ³ÉÔ±·½·¨
/// <summary>
/// µÃµ½×î´óID
/// </summary>
public int GetMaxId()
{
return DbHelperSQL.GetMaxID("CK_PeopleID", "CK_People");
}
/// <summary>
/// ÊÇ·ñ´æÔڸüǼ
/// </summary>
public bool Exists(int CK_PeopleID)
{
StringBuilder strSql=new StringBuilder();
strSql.Append("select count(1) from CK_People");
strSql.Append(" where CK_PeopleID=@CK_PeopleID ");
SqlParameter[] parameters = {
new SqlParameter("@CK_PeopleID", SqlDbType.Int,4)};
parameters[0].Value = CK_PeopleID;
return DbHelperSQL.Exists(strSql.ToString(),parameters);
}
/// <summary>
/// Ôö¼ÓÒ»ÌõÊý¾Ý
/// </summary>
public int Add(TSM.Model.CK_People model)
{
StringBuilder strSql=new StringBuilder();
strSql.Append("insert into CK_People(");
strSql.Append("CK_PeopleName,CK_PhoneNo,CK_Comment)");
strSql.Append(" values (");
strSql.Append("@CK_PeopleName,@CK_PhoneNo,@CK_Comment)");
strSql.Append(";select @@IDENTITY");
SqlParameter[] parameters = {
new SqlParameter("@CK_PeopleName", SqlDbType.VarChar,32),
new SqlParameter("@CK_PhoneNo", SqlDbType.VarChar,32),
new SqlParameter("@CK_Comment", SqlDbType.VarChar,100)};
parameters[0].Value = model.CK_PeopleName;
parameters[1].Value = model.CK_PhoneNo;
parameters[2].Value = model.CK_Comment;
object obj = DbHelperSQL.GetSingle(strSql.ToString(),parameters);
if (obj == null)
{
return 1;
}
else
{
return Convert.ToInt32(obj);
}
}
/// <summary>
/// ¸üÐÂÒ»ÌõÊý¾Ý
/// </summary>
public void Update(TSM.Model.CK_People model)
{
StringBuilder strSql=new StringBuilder();
strSql.Append("update CK_People set ");
strSql.Append("CK_PeopleName=@CK_PeopleName,");
strSql.Append("CK_PhoneNo=@CK_PhoneNo,");
strSql.Append("CK_Comment=@CK_Comment");
strSql.Append(" where CK_PeopleID=@CK_PeopleID ");
SqlParameter[] parameters = {
new SqlParameter("@CK_PeopleID", SqlDbType.Int,4),
new SqlParameter("@CK_PeopleName", SqlDbType.VarChar,32),
new SqlParameter("@CK_PhoneNo", SqlDbType.VarChar,32),
new SqlParameter("@CK_Comment", SqlDbType.VarChar,100)};
parameters[0].Value = model.CK_PeopleID;
parameters[1].Value = model.CK_PeopleName;
parameters[2].Value = model.CK_PhoneNo;
parameters[3].Value = model.CK_Comment;
DbHelperSQL.ExecuteSql(strSql.ToString(),parameters);
}
/// <summary>
/// ɾ³ýÒ»ÌõÊý¾Ý
/// </summary>
public void Delete(int CK_PeopleID)
{
StringBuilder strSql=new StringBuilder();
strSql.Append("delete from CK_People ");
strSql.Append(" where CK_PeopleID=@CK_PeopleID ");
SqlParameter[] parameters = {
new SqlParameter("@CK_PeopleID", SqlDbType.Int,4)};
parameters[0].Value = CK_PeopleID;
DbHelperSQL.ExecuteSql(strSql.ToString(),parameters);
}
/// <summary>
/// µÃµ½Ò»¸ö¶ÔÏóʵÌå
/// </summary>
public TSM.Model.CK_People GetModel(int CK_PeopleID)
{
StringBuilder strSql=new StringBuilder();
strSql.Append("select top 1 CK_PeopleID,CK_PeopleName,CK_PhoneNo,CK_Comment from CK_People ");
strSql.Append(" where CK_PeopleID=@CK_PeopleID ");
SqlParameter[] parameters = {
new SqlParameter("@CK_PeopleID", SqlDbType.Int,4)};
parameters[0].Value = CK_PeopleID;
TSM.Model.CK_People model=new TSM.Model.CK_People();
DataSet ds=DbHelperSQL.Query(strSql.ToString(),parameters);
if(ds.Tables[0].Rows.Count>0)
{
if(ds.Tables[0].Rows[0]["CK_PeopleID"].ToString()!="")
{
model.CK_PeopleID=int.Parse(ds.Tables[0].Rows[0]["CK_PeopleID"].ToString());
}
model.CK_PeopleName=ds.Tables[0].Rows[0]["CK_PeopleName"].ToString();
model.CK_PhoneNo=ds.Tables[0].Rows[0]["CK_PhoneNo"].ToString();
model.CK_Comment=ds.Tables[0].Rows[0]["CK_Comment"].ToString();
return model;
}
else
{
return null;
}
}
/// <summary>
/// »ñµÃÊý¾ÝÁбí
/// </summary>
public DataSet GetList(string strWhere)
{
StringBuilder strSql=new StringBuilder();
strSql.Append("select CK_PeopleID,CK_PeopleName,CK_PhoneNo,CK_Comment ");
strSql.Append(" FROM CK_People ");
if(strWhere.Trim()!="")
{
strSql.Append(" where "+strWhere);
}
return DbHelperSQL.Query(strSql.ToString());
}
/// <summary>
/// »ñµÃǰ¼¸ÐÐÊý¾Ý
/// </summary>
public DataSet GetList(int Top,string strWhere,string filedOrder)
{
StringBuilder strSql=new StringBuilder();
strSql.Append("select ");
if(Top>0)
{
strSql.Append(" top "+Top.ToString());
}
strSql.Append(" CK_PeopleID,CK_PeopleName,CK_PhoneNo,CK_Comment ");
strSql.Append(" FROM CK_People ");
if(strWhere.Trim()!="")
{
strSql.Append(" where "+strWhere);
}
strSql.Append(" order by " + filedOrder);
return DbHelperSQL.Query(strSql.ToString());
}
/// <summary>
/// ·ÖÒ³»ñÈ¡Êý¾ÝÁбí
/// </summary>
public DataSet GetList(int PageSize,int PageIndex,string strWhere)
{
SqlParameter[] parameters = {
new SqlParameter("@tblName", SqlDbType.VarChar, 255),
new SqlParameter("@fldName", SqlDbType.VarChar, 255),
new SqlParameter("@PageSize", SqlDbType.Int),
new SqlParameter("@PageIndex", SqlDbType.Int),
new SqlParameter("@IsReCount", SqlDbType.Bit),
new SqlParameter("@OrderType", SqlDbType.Bit),
new SqlParameter("@strWhere", SqlDbType.VarChar,1000),
};
parameters[0].Value = "CK_People";
parameters[1].Value = "CK_PeopleID";
parameters[2].Value = PageSize;
parameters[3].Value = PageIndex;
parameters[4].Value = 0;
parameters[5].Value = 0;
parameters[6].Value = strWhere;
return DbHelperSQL.RunProcedure("UP_GetRecordByPage",parameters,"ds");
}
#endregion ³ÉÔ±·½·¨
}
}
| kamiba/FineUIDemo | DAL/CK_People.cs | C# | apache-2.0 | 6,177 |
/*
* Licensed to GraphHopper GmbH under one or more contributor
* license agreements. See the NOTICE file distributed with this work for
* additional information regarding copyright ownership.
*
* GraphHopper GmbH 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 com.graphhopper.jsprit.core.util;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
import com.graphhopper.jsprit.core.algorithm.listener.AlgorithmEndsListener;
import com.graphhopper.jsprit.core.problem.VehicleRoutingProblem;
import com.graphhopper.jsprit.core.problem.job.Job;
import com.graphhopper.jsprit.core.problem.solution.VehicleRoutingProblemSolution;
import com.graphhopper.jsprit.core.problem.solution.route.VehicleRoute;
public class SolutionVerifier implements AlgorithmEndsListener {
@Override
public void informAlgorithmEnds(VehicleRoutingProblem problem, Collection<VehicleRoutingProblemSolution> solutions) {
for (VehicleRoutingProblemSolution solution : solutions) {
Set<Job> jobsInSolution = new HashSet<Job>();
for (VehicleRoute route : solution.getRoutes()) {
jobsInSolution.addAll(route.getTourActivities().getJobs());
}
if (jobsInSolution.size() != problem.getJobs().size()) {
throw new IllegalStateException("we are at the end of the algorithm and still have not found a valid solution." +
"This cannot be.");
}
}
}
}
| balage1551/jsprit | jsprit-core/src/main/java/com/graphhopper/jsprit/core/util/SolutionVerifier.java | Java | apache-2.0 | 2,020 |
package jp.ac.keio.bio.fun.xitosbml.image;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map.Entry;
import ij.ImagePlus;
import ij.ImageStack;
import ij.process.ByteProcessor;
/**
* The class Filler, which provides several morphological operations for filling holes in the image.
* Date Created: Feb 21, 2017
*
* @author Kaito Ii <ii@fun.bio.keio.ac.jp>
* @author Akira Funahashi <funa@bio.keio.ac.jp>
*/
public class Filler {
/** The ImageJ image object. */
private ImagePlus image;
/** The width of an image. */
private int width;
/** The height of an image. */
private int height;
/** The depth of an image. */
private int depth;
/** The width of an image including padding. */
private int lwidth;
/** The height of an image including padding. */
private int lheight;
/** The depth of an image including padding. */
private int ldepth;
/** The mask which stores the label of each pixel. */
private int[] mask;
/**
* The hashmap of pixel value. <labelnumber, pixel value>.
* The domain which has pixel value = 0 will have a label = 1.
*/
private HashMap<Integer, Byte> hashPix = new HashMap<Integer, Byte>(); // label number, pixel value
/** The raw data (1D byte array) of the image. */
private byte[] pixels;
/** The raw data (1D int array) of inverted the image. */
private int[] invert;
/**
* Fill a hole in the given image (ImagePlus object) by morphology operation,
* and returns the filled image.
*
* @param image the ImageJ image object
* @return the filled ImageJ image (ImagePlus) object
*/
public ImagePlus fill(ImagePlus image){
this.width = image.getWidth();
this.height = image.getHeight();
this.depth = image.getStackSize();
this.image = image;
pixels = ImgProcessUtil.copyMat(image);
invertMat();
label();
if (checkHole()) {
while (checkHole()) {
fillHole();
hashPix.clear();
label();
}
ImageStack stack = createStack();
image.setStack(stack);
image.updateImage();
}
return image;
}
/**
* Fill a hole in the given image ({@link SpatialImage} object) by morphology operation,
* and returns the filled image as ImageJ image object.
*
* @param spImg the SpatialImage object
* @return the filled ImageJ image (ImagePlus) object
*/
public ImagePlus fill(SpatialImage spImg){
this.width = spImg.getWidth();
this.height = spImg.getHeight();
this.depth = spImg.getDepth();
this.image = spImg.getImage();
this.pixels = spImg.getRaw();
invertMat();
label();
if(checkHole()){
while(checkHole()){
fillHole();
hashPix.clear();
label();
}
ImageStack stack = createStack();
image.setStack(stack);
image.updateImage();
}
return image;
}
/**
* Creates the stack of images from raw data (1D array) of image (pixels[]),
* and returns the stack of images.
*
* @return the stack of images
*/
private ImageStack createStack(){
ImageStack altimage = new ImageStack(width, height);
for(int d = 0 ; d < depth ; d++){
byte[] matrix = new byte[width * height];
System.arraycopy(pixels, d * height * width, matrix, 0, matrix.length);
altimage.addSlice(new ByteProcessor(width,height,matrix,null));
}
return altimage;
}
/**
* Create an inverted 1D array of an image (invert[]) from 1D array of an image (pixels[]).
* Each pixel value will be inverted (0 -> 1, otherwise -> 0). For example, the Black and White
* binary image will be converted to a White and Black binary image.
*/
private void invertMat(){
lwidth = width + 2;
lheight = height + 2;
if(depth < 3) ldepth = depth;
else ldepth = depth + 2;
invert = new int[lwidth * lheight * ldepth];
mask = new int[lwidth * lheight * ldepth];
if (ldepth > depth) { // 3D image
for (int d = 0; d < ldepth; d++) {
for (int h = 0; h < lheight; h++) {
for (int w = 0; w < lwidth; w++) {
if (d == 0 || d == ldepth - 1 || h == 0 || h == lheight - 1 || w == 0 || w == lwidth - 1) {
invert[d * lheight * lwidth + h * lwidth + w] = 1;
mask[d * lheight * lwidth + h * lwidth + w] = 1;
continue;
}
if (pixels[(d - 1) * height * width + (h - 1) * width + w - 1] == 0)
invert[d * lheight * lwidth + h * lwidth + w] = 1;
else
invert[d * lheight * lwidth + h * lwidth + w] = 0;
}
}
}
} else { // 2D image
for (int d = 0; d < ldepth; d++) {
for (int h = 0; h < lheight; h++) {
for (int w = 0; w < lwidth; w++) {
if(h == 0 || h == lheight - 1 || w == 0 || w == lwidth - 1){
invert[d * lheight * lwidth + h * lwidth + w] = 1;
mask[d * lheight * lwidth + h * lwidth + w] = 1;
continue;
}
if (pixels[d * height * width + (h - 1) * width + w - 1] == 0)
invert[d * lheight * lwidth + h * lwidth + w] = 1;
else
invert[d * lheight * lwidth + h * lwidth + w] = 0;
}
}
}
}
}
/** The label count. */
private int labelCount;
/**
* Assign a label (label number) to each pixel.
* The label number will be stored in mask[] array.
* The domain which has pixel value = 0 will have a label = 1.
*/
public void label(){
hashPix.put(1, (byte)0);
labelCount = 2;
if (ldepth > depth) {
for (int d = 1; d < ldepth - 1; d++) {
for (int h = 1; h < lheight - 1; h++) {
for (int w = 1; w < lwidth - 1; w++) {
if (invert[d * lheight * lwidth + h * lwidth + w] == 1 && pixels[(d-1) * height * width + (h-1) * width + w - 1] == 0) {
mask[d * lheight * lwidth + h * lwidth + w] = setLabel(w, h, d, pixels[(d-1) * height * width + (h-1) * width + w - 1]);
}else{
mask[d * lheight * lwidth + h * lwidth + w] = setbackLabel(w, h, d, pixels[(d-1) * height * width + (h-1) * width + w - 1]);
}
}
}
}
}else{
for (int d = 0; d < ldepth; d++) {
for (int h = 1; h < lheight - 1; h++) {
for (int w = 1; w < lwidth - 1; w++) {
if (invert[d * lheight * lwidth + h * lwidth + w] == 1 && pixels[d * height * width + (h-1) * width + w - 1] == 0) {
mask[d * lheight * lwidth + h * lwidth + w] = setLabel(w, h, d, pixels[d * height * width + (h-1) * width + w - 1]);
}else{
mask[d * lheight * lwidth + h * lwidth + w] = setbackLabel(w, h, d, pixels[d * height * width + (h-1) * width + w - 1]);
}
}
}
}
}
}
/**
* Check whether a hole exists in the hashmap of pixels (HashMap<label number, pixel value>).
*
* @return true, if a hole exists
*/
public boolean checkHole(){
if(Collections.frequency(hashPix.values(), (byte) 0) > 1)
return true;
else
return false;
}
/**
* Fill a hole in the hashmap of pixels (HashMap<label number, pixel value> by morphology operation.
* The fill operation will be applied to each domain (which has unique label number).
*/
public void fillHole(){
for(Entry<Integer, Byte> e : hashPix.entrySet()){
if(!e.getKey().equals(1) && e.getValue().equals((byte)0)){
fill(e.getKey());
}
}
}
/**
* Fill a hole in the hashmap of pixels (HashMap<label number, pixel value> by morphology operation.
* The hole will be filled with the pixel value of adjacent pixel.
*
* @param labelNum the label number
*/
public void fill(int labelNum){
if (ldepth > depth) { // 3D image
for (int d = 1; d < ldepth; d++) {
for (int h = 1; h < lheight - 1; h++) {
for (int w = 1; w < lwidth - 1; w++) {
if (mask[d * lheight * lwidth + h * lwidth + w] == labelNum ) {
pixels[(d-1) * height * width + (h-1) * width + w - 1] = checkAdjacentsLabel(w, h, d, labelNum);
}
}
}
}
} else { // 2D image
for (int d = 0; d < ldepth; d++) {
for (int h = 1; h < lheight - 1; h++) {
for (int w = 1; w < lwidth - 1; w++) {
if (mask[d * lheight * lwidth + h * lwidth + w] == labelNum ) {
pixels[d * height * width + (h-1) * width + w - 1] = checkAdjacentsLabel(w, h, d, labelNum);
}
}
}
}
}
}
/**
* Check adjacent pixels whether it contains the given label (labelNum).
* If all the adjacent pixels have same label with given label, then return 0.
* If the adjacent pixels contain different labels, then returns the pixel
* value of most enclosing adjacent domain.
*
* @param w the x offset
* @param h the y offset
* @param d the z offset
* @param labelNum the label number
* @return the pixel value of most enclosing adjacent domain if different domain exists, otherwise 0
*/
public byte checkAdjacentsLabel(int w, int h, int d, int labelNum){
List<Byte> adjVal = new ArrayList<Byte>();
//check right
if(mask[d * lheight * lwidth + h * lwidth + w + 1] != labelNum)
adjVal.add(hashPix.get(mask[d * lheight * lwidth + h * lwidth + w + 1]));
//check left
if(mask[d * lheight * lwidth + h * lwidth + w - 1] != labelNum)
adjVal.add(hashPix.get(mask[d * lheight * lwidth + h * lwidth + w - 1]));
//check down
if(mask[d * lheight * lwidth + (h+1) * lwidth + w ] != labelNum)
adjVal.add(hashPix.get(mask[d * lheight * lwidth + (h+1) * lwidth + w]));
//check up
if(mask[d * lheight * lwidth + (h-1) * lwidth + w ] != labelNum)
adjVal.add(hashPix.get(mask[d * lheight * lwidth + (h-1) * lwidth + w]));
//check above
if(d != depth - 1 && mask[(d+1) * lheight * lwidth + h * lwidth + w] != labelNum)
adjVal.add(hashPix.get(mask[(d+1) * lheight * lwidth + h * lwidth + w]));
//check below
if(d != 0 && mask[(d-1) * lheight * lwidth + h * lwidth + w] != labelNum)
adjVal.add(hashPix.get(mask[(d - 1) * lheight * lwidth + h * lwidth + w]));
if(adjVal.isEmpty())
return 0;
int max = 0;
int count = 0;
int freq, temp; Byte val = 0;
for(int n = 0 ; n < adjVal.size() ; n++){
val = adjVal.get(n);
if(val == 0)
continue;
freq = Collections.frequency(adjVal, val);
temp = val & 0xFF;
if(freq > count){
max = temp;
count = freq;
}
if(freq == count && max < temp){
max = temp;
count = freq;
}
}
return (byte) max;
}
/**
* Sets the label of the given pixel (x offset, y offset, z offset) with its pixel value.
* Checks whether the adjacent pixel has the zero pixel value, and its label is already assigned.
*
* @param w the x offset
* @param h the y offset
* @param d the z offset
* @param pixVal the pixel value
* @return the label as integer value
*/
private int setLabel(int w , int h, int d, byte pixVal){
List<Integer> adjVal = new ArrayList<Integer>();
//check left
if(mask[d * lheight * lwidth + h * lwidth + w - 1] != 0 && hashPix.get(mask[d * lheight * lwidth + h * lwidth + w - 1]) == (byte)0)
adjVal.add(mask[d * lheight * lwidth + h * lwidth + w - 1]);
//check up
if(mask[d * lheight * lwidth + (h-1) * lwidth + w ] != 0 && hashPix.get(mask[d * lheight * lwidth + (h-1) * lwidth + w]) == (byte)0)
adjVal.add(mask[d * lheight * lwidth + (h-1) * lwidth + w]);
//check below
if(d != 0 && mask[(d-1) * lheight * lwidth + h * lwidth + w] != 0 && hashPix.get(mask[(d-1) * lheight * lwidth + h * lwidth + w]) == (byte)0)
adjVal.add(mask[(d-1) * lheight * lwidth + h * lwidth + w]);
if(adjVal.isEmpty()){
hashPix.put(labelCount, pixVal);
return labelCount++;
}
Collections.sort(adjVal);
//if all element are same or list has only one element
if(Collections.frequency(adjVal, adjVal.get(0)) == adjVal.size())
return adjVal.get(0);
int min = adjVal.get(0);
for(int i = 1; i < adjVal.size(); i++){
if(min == adjVal.get(i))
continue;
rewriteLabel(d, min, adjVal.get(i));
hashPix.remove(adjVal.get(i));
}
return min;
}
/**
* Sets back the label of the given pixel (x offset, y offset, z offset) with its pixel value.
* Checks whether the adjacent pixel has the non-zero pixel value, and its label is already assigned.
*
* @param w the x offset
* @param h the y offset
* @param d the z offset
* @param pixVal the pixel value
* @return the label as integer value
*/
private int setbackLabel(int w , int h, int d, byte pixVal){
List<Integer> adjVal = new ArrayList<Integer>();
//check left
if(mask[d * lheight * lwidth + h * lwidth + w - 1] != 0 && hashPix.get(mask[d * lheight * lwidth + h * lwidth + w - 1]) != (byte)0)
adjVal.add(mask[d * lheight * lwidth + h * lwidth + w - 1]);
//check up
if(mask[d * lheight * lwidth + (h-1) * lwidth + w ] != 0 && hashPix.get(mask[d * lheight * lwidth + (h-1) * lwidth + w]) != (byte)0)
adjVal.add(mask[d * lheight * lwidth + (h-1) * lwidth + w]);
//check below
if(d != 0 && mask[(d-1) * lheight * lwidth + h * lwidth + w] != 0 && hashPix.get(mask[(d-1) * lheight * lwidth + h * lwidth + w]) != (byte)0)
adjVal.add(mask[(d-1) * lheight * lwidth + h * lwidth + w]);
if(adjVal.isEmpty()){
hashPix.put(labelCount, pixVal);
return labelCount++;
}
Collections.sort(adjVal);
//if all element are same or list has only one element
if(Collections.frequency(adjVal, adjVal.get(0)) == adjVal.size())
return adjVal.get(0);
int min = adjVal.get(0);
for(int i = 1; i < adjVal.size(); i++){
if(min == adjVal.get(i))
continue;
hashPix.remove(adjVal.get(i));
rewriteLabel(d, min, adjVal.get(i));
}
return min;
}
/**
* Replace the label of pixels in the spatial image which has "before" to "after".
*
* @param dEnd the end of the depth
* @param after the label to set by this replacement
* @param before the label to be replaced
*/
private void rewriteLabel(int dEnd, int after, int before){
if (ldepth > depth) {
for (int d = 1; d <= dEnd; d++) {
for (int h = 1; h < lheight - 1; h++) {
for (int w = 1; w < lwidth - 1; w++) {
if (mask[d * lheight * lwidth + h * lwidth + w] == before)
mask[d * lheight * lwidth + h * lwidth + w] = after;
}
}
}
}else{
for (int d = 0; d <= dEnd; d++) {
for (int h = 1; h < lheight - 1; h++) {
for (int w = 1; w < lwidth - 1; w++) {
if (mask[d * lheight * lwidth + h * lwidth + w] == before)
mask[d * lheight * lwidth + h * lwidth + w] = after;
}
}
}
}
}
}
| spatialsimulator/XitoSBML | src/main/java/jp/ac/keio/bio/fun/xitosbml/image/Filler.java | Java | apache-2.0 | 14,320 |
package org.ak.gitanalyzer.http.processor;
import org.ak.gitanalyzer.util.writer.CSVWriter;
import org.ak.gitanalyzer.util.writer.HTMLWriter;
import java.text.NumberFormat;
import java.util.Collection;
import java.util.function.BiConsumer;
import java.util.function.Function;
/**
* Created by Andrew on 02.12.2016.
*/
public class ProcessorMock extends BaseAnalysisProcessor {
public ProcessorMock(NumberFormat nf) {
super(nf);
}
@Override
public <T> String getCSVForReport(String[] headers, Collection<T> collection, BiConsumer<T, StringBuilder> consumer) {
return super.getCSVForReport(headers, collection, consumer);
}
@Override
public <T> String getJSONForTable(Collection<T> collection, BiConsumer<T, StringBuilder> consumer) {
return super.getJSONForTable(collection, consumer);
}
@Override
public <T> String getJSONFor2D(Collection<T> collection, BiConsumer<T, StringBuilder> consumer) {
return super.getJSONFor2D(collection, consumer);
}
@Override
public <T> String getJSONForGraph(Collection<T> collection, Function<T, Integer> nodeIdSupplier, TriConsumer<T, StringBuilder, Integer> consumer) {
return super.getJSONForGraph(collection, nodeIdSupplier, consumer);
}
@Override
public String getTypeString(double weight, double thickThreshold, double normalThreshold) {
return super.getTypeString(weight, thickThreshold, normalThreshold);
}
public HTMLWriter getHtmlWriter() {
return htmlWriter;
}
public CSVWriter getCsvWriter() {
return csvWriter;
}
}
| AndreyKunin/git-analyzer | src/test/java/org/ak/gitanalyzer/http/processor/ProcessorMock.java | Java | apache-2.0 | 1,622 |
# require './lib/class_extensions'
# require './lib/mylogger'
# DEV Only requries above.
require './lib/code_detector'
require './lib/dsl/style_dsl'
require './lib/dsl/selector_dsl'
require './lib/tag_helper'
require './lib/html/html_class_finder'
require './lib/html/style_list'
require './lib/highlighter/highlighters_enum'
require './lib/theme_store'
# Do bunch of apply, then invoke end_apply to close the style tag
class StyleGenerator
include HtmlClassFinder, HighlightersEnum, CodeDetector
def initialize(tag_helper, lang = 'none')
@tag_helper = tag_helper
# $logger.info(lang)
# # theming.
# @colorizer = if lang == 'git' || iscmd
# DarkColorizer.new
# elsif ['asp', 'csharp'].include?(lang)
# VisualStudioColorizer.new
# else
# LightColorizer.new
# end
# $logger.debug(@colorizer)
@lang = lang
end
def style_front(front_card_block)
front_style = style {}
front_style.styles << build_main
no_tag = @tag_helper.untagged? || @tag_helper.back_only?
front_style.styles << build_tag unless no_tag
tags = find(front_card_block, :span)
build_code(tags) { |style| front_style.styles << style }
front_style.styles << build_inline if inline?(front_card_block)
front_style
end
def style_back(back_card_block)
back_style = style(get_theme) {}
back_style.styles << build_main
no_tag = @tag_helper.untagged? || @tag_helper.front_only?
back_style.styles << build_tag unless no_tag
back_style.styles << build_figure if @tag_helper.figure?
back_style.styles << build_command if command?(back_card_block)
back_style.styles << build_well if well?(back_card_block)
back_style.styles << build_inline if inline?(back_card_block)
tags = find(back_card_block, :span)
build_code(tags) { |style| back_style.styles << style }
back_style
end
def get_theme
case @lang
when HighlightersEnum::RUBY
ThemeStore::SublimeText2_Sunburst_Ruby
else
ThemeStore::Default
end
end
def build_main
select 'div.main' do
font_size '16pt'
text_align 'left'
end
end
def build_tag
select 'span.tag' do
background_color '#5BC0DE'
border_radius '5px'
color 'white'
font_size '14pt'
padding '2px'
margin_right '10px'
end
end
def build_answer_only
select 'span.answer' do
background_color '#D9534F'
border_radius '5px'
color 'white'
display 'table'
font_weight 'bold'
margin '0 auto'
padding '2px 5px'
end
end
def build_figure
select '.fig', :line_height, '70%'
end
def build_inline
select 'code.inline' do
background_color '#F1F1F1'
border '1px solid #DDD'
border_radius '5px'
color 'black'
font_family 'monaco, courier'
font_size '13pt'
padding_left '2px'
padding_right '2px'
end
end
def build_command
select 'code.command' do
color 'white'
background_color 'black'
end
end
def build_well
select 'code.well' do
background_color '#F1F1F1'
border '1px solid #E3E3E3'
border_radius '4px'
box_shadow 'inset 0 1px 1px rgba(0, 0, 0, 0.05)'
color 'black'
display 'block'
font_family 'monaco, courier'
font_size '14pt'
margin_bottom '20px'
min_height '20px'
padding '19px'
end
end
def build_code(tags)
style_list = StyleList.new(tags)
style_list.add('keyword', :color, '#7E0854')
style_list.add('comment', :color, '#417E60')
style_list.add('quote', :color, '#1324BF')
style_list.add('var', :color, '#426F9C')
style_list.add('url', :color, 'blue')
style_list.add('html', :color, '#446FBD')
style_list.add('attr', :color, '#6D8600')
style_list.add('cls', :color, '#6D8600')
style_list.add('num', :color, '#812050')
style_list.add('opt', :color, 'darkgray')
# style_list.add('cmd', :color, '#7E0854')
# Per language Styles
style_list.add('phptag', :color, '#FC0D1B') if @lang == PHP
style_list.add('ann', :color, '#FC0D1B') if @lang == JAVA
style_list.add('symbol', :color, '#808080') if @lang == ASP
if @lang == GIT
style_list.add('opt', :color, 'black')
style_list.add('cmd', :color, '#FFFF9B')
end
style_list.each { |style| yield style }
end
end
# # tag_helper = TagHelper.new(tags: [])
# # tag_helper = TagHelper.new(tags: [:Concept])
# tag_helper = TagHelper.new(tags: [:FB])
# # tag_helper = TagHelper.new(tags: [:BF])
# generator = StyleGenerator.new(tag_helper)
# puts( generator.style_back(['span class="keyword comment"']) )
| roycetech/Anki-Tools | anki_card_maker/lib/html/style_generator.rb | Ruby | apache-2.0 | 4,672 |
"""A client for the REST API of imeji instances."""
import logging
from collections import OrderedDict
import requests
from six import string_types
from pyimeji import resource
from pyimeji.config import Config
log = logging.getLogger(__name__)
class ImejiError(Exception):
def __init__(self, message, error):
super(ImejiError, self).__init__(message)
self.error = error.get('error') if isinstance(error, dict) else error
class GET(object):
"""Handle GET requests.
This includes requests
- to retrieve single objects,
- to fetch lists of object references (which are returned as `OrderedDict` mapping
object `id` to additional metadata present in the response).
"""
def __init__(self, api, name):
"""Initialize a handler.
:param api: An Imeji API instance.
:param name: Name specifying the kind of object(s) to retrieve. We check whether\
this name has a plural "s" to determine if a list is to be retrieved.
"""
self._list = name.endswith('s')
self.rsc = getattr(resource, (name[:-1] if self._list else name).capitalize())
self.api = api
self.name = name
self.path = name
if not self._list:
self.path += 's'
def __call__(self, id='', **kw):
"""Calling the handler initiates an HTTP request to the imeji server.
:param id: If a single object is to be retrieved it must be specified by id.
:return: An OrderedDict mapping id to additional metadata for lists, a \
:py:class:`pyimeji.resource.Resource` instance for single objects.
"""
if not self._list and not id:
raise ValueError('no id given')
if id:
id = '/' + id
res = self.api._req('/%s%s' % (self.path, id), params=kw)
if not self._list:
return self.rsc(res, self.api)
return OrderedDict([(d['id'], d) for d in res])
class Imeji(object):
"""The client.
>>> api = Imeji(service_url='http://demo.imeji.org/imeji/')
>>> collection_id = list(api.collections().keys())[0]
>>> collection = api.collection(collection_id)
>>> collection = api.create('collection', title='the new collection')
>>> item = collection.add_item(fetchUrl='http://example.org')
>>> item.delete()
"""
def __init__(self, cfg=None, service_url=None):
self.cfg = cfg or Config()
self.service_url = service_url or self.cfg.get('service', 'url')
user = self.cfg.get('service', 'user', default=None)
password = self.cfg.get('service', 'password', default=None)
self.session = requests.Session()
if user and password:
self.session.auth = (user, password)
def _req(self, path, method='get', json=True, assert_status=200, **kw):
"""Make a request to the API of an imeji instance.
:param path: HTTP path.
:param method: HTTP method.
:param json: Flag signalling whether the response should be treated as JSON.
:param assert_status: Expected HTTP response status of a successful request.
:param kw: Additional keyword parameters will be handed through to the \
appropriate function of the requests library.
:return: The return value of the function of the requests library or a decoded \
JSON object/array.
"""
method = getattr(self.session, method.lower())
res = method(self.service_url + '/rest' + path, **kw)
status_code = res.status_code
if json:
try:
res = res.json()
except ValueError: # pragma: no cover
log.error(res.text[:1000])
raise
if assert_status:
if status_code != assert_status:
log.error(
'got HTTP %s, expected HTTP %s' % (status_code, assert_status))
log.error(res.text[:1000] if hasattr(res, 'text') else res)
raise ImejiError('Unexpected HTTP status code', res)
return res
def __getattr__(self, name):
"""Names of resource classes are accepted and resolved as dynamic attribute names.
This allows convenient retrieval of resources as api.<resource-class>(id=<id>),
or api.<resource-class>s(q='x').
"""
return GET(self, name)
def create(self, rsc, **kw):
if isinstance(rsc, string_types):
cls = getattr(resource, rsc.capitalize())
rsc = cls(kw, self)
return rsc.save()
def delete(self, rsc):
return rsc.delete()
def update(self, rsc, **kw):
for k, v in kw.items():
setattr(rsc, k, v)
return rsc.save()
| xrotwang/pyimeji | pyimeji/api.py | Python | apache-2.0 | 4,739 |
using MatrixApi.Domain;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.Data.Json;
namespace MatrixPhone.DataModel
{
public static class UserDataSource
{
public static User user = new User();
public static User GetUser() {
return user;
}
public static async void Login(string Email, string Password)
{
user.Email = Email;
user.Password = Password;
var httpClient = new appHttpClient();
var response = await httpClient.GetAsync("Users");
try
{
response.EnsureSuccessStatusCode(); // Throw on error code.
} catch {
user = new User();
}
var result = await response.Content.ReadAsStringAsync();
user = JsonConvert.DeserializeObject<User>(result);
}
public static string Auth()
{
var authText = string.Format("{0}:{1}", user.Email, user.Password);
return Convert.ToBase64String(Encoding.UTF8.GetBytes(authText));
}
}
}
| jdehlin/MatrixApi | MatrixPhone/DataModel/UserDataSource.cs | C# | apache-2.0 | 1,203 |
// svgmap.js 0.2.0
//
// Copyright (c) 2014 jalal @ gnomedia
//
// 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.
//
var SvgMap = function (opts) {
/*global Snap:false, console:false */
'use strict';
console.log("SvgMap initializing");
var defaults = {
svgid: '',
mapurl: '',
mapid: '',
coordsurl: '',
hoverFill: '#fff',
strokeColor: '#000',
resultid: 'results'
};
var svgid = opts.svgid || defaults.svgid,
mapurl = opts.mapurl || defaults.mapurl,
mapid = opts.mapid || defaults.mapid,
coordsurl = opts.coordsurl || defaults.coordsurl,
strokeColor = opts.strokeColor || defaults.strokeColor,
hoverFill = opts.hoverFill || defaults.hoverFill,
resultid = opts.resultid || defaults.resultid;
var i, w, h, areas, pre;
var s = new Snap(svgid);
var group = s.group();
Snap.load(mapurl, function (f) {
i = f.select('image');
h = i.attr('height');
w = i.attr('width');
group.append(f);
s.attr({
viewBox: [0, 0, w, h]
});
var newmap = document.getElementById('newmap');
if (newmap) {
newmap.style.height = h + 'px';
newmap.style.maxWidth = w + 'px';
}
});
var shadow = new Snap(svgid);
areas = document.getElementsByTagName('area');
var area;
for (var j = areas.length - 1; j >= 0; j--) {
area = areas[j];
// console.log("Coord: " + area.coords);
var coords = area.coords.split(',');
var path = 'M ';
if (coords.length) {
for (var k = 0; k < coords.length; k += 2) {
if (!k) {pre = ''; } else {pre = ' L '; }
path += pre + coords[k] + ',' + coords[k + 1];
}
}
var p = new Snap();
var el = p.path(path);
el.attr({ id: area.title, fill: 'none', stroke: strokeColor, link: area.href, d: path, title: area.title});
el.hover(function () {
this.attr('fill', hoverFill);
}, function () {
this.attr('fill', 'transparent');
});
el.click(function () {
// console.log('click: ' + this.attr('id'));
hideAll();
show('Clicked: ' + this.attr('id'));
});
el.touchstart(function () {
console.log('touch: ' + this.attr('id'));
this.attr('fill', hoverFill);
hideAll();
show('Touched: ' + this.attr('id'));
});
el.touchend(function () {
this.attr('fill', 'transparent');
});
shadow.append(el);
}
function hideAll() {
var el = document.getElementById(resultid);
if (el) {el.style.display = "none"; }
// $(resultid).hide();
}
function show(txt) {
var el = document.getElementById(resultid);
if (el) {
el.style.display = "";
if (el.firstChild) {
el.removeChild(el.firstChild);
}
var t = document.createTextNode(txt);
el.appendChild(t);
}
}
};
| jalal/svgmap | js/svgmap.js | JavaScript | apache-2.0 | 3,661 |
package com.yezi.text.widget;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.SwitchCompat;
import android.view.View;
import android.widget.CompoundButton;
import com.yezi.text.activity.AdapterSampleActivity;
import com.yezi.text.activity.AnimatorSampleActivity;
import com.yezi.text.R;
public class MyRecycleview extends AppCompatActivity {
private boolean enabledGrid = false;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mycycleview);
findViewById(R.id.btn_animator_sample).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent i = new Intent(MyRecycleview.this, AnimatorSampleActivity.class);
i.putExtra("GRID", enabledGrid);
startActivity(i);
}
});
findViewById(R.id.btn_adapter_sample).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent i = new Intent(MyRecycleview.this, AdapterSampleActivity.class);
i.putExtra("GRID", enabledGrid);
startActivity(i);
}
});
((SwitchCompat) findViewById(R.id.grid)).setOnCheckedChangeListener(
new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
enabledGrid = isChecked;
}
});
}
}
| qwertyezi/Test | text/app/src/main/java/com/yezi/text/widget/MyRecycleview.java | Java | apache-2.0 | 1,720 |
/*
* Copyright 2008 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 com.datalint.open.shared.xml;
import java.util.ArrayList;
import java.util.List;
import org.w3c.dom.CDATASection;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.Text;
import com.datalint.open.shared.xml.impl.XMLParserImpl;
/**
* This class represents the client interface to XML parsing.
*/
public class XMLParser {
private static final XMLParserImpl impl = XMLParserImpl.getInstance();
/**
* This method creates a new document, to be manipulated by the DOM API.
*
* @return the newly created document
*/
public static Document createDocument() {
return impl.createDocument();
}
/**
* This method parses a new document from the supplied string, throwing a
* <code>DOMParseException</code> if the parse fails.
*
* @param contents the String to be parsed into a <code>Document</code>
* @return the newly created <code>Document</code>
*/
public static Document parse(String contents) {
return impl.parse(contents);
}
// Update on 2020-05-10, does not work with XPath.
public static Document parseReadOnly(String contents) {
return impl.parseReadOnly(contents);
}
/**
* This method removes all <code>Text</code> nodes which are made up of only
* white space.
*
* @param n the node which is to have all of its whitespace descendents removed.
*/
public static void removeWhitespace(Node n) {
removeWhitespaceInner(n, null);
}
/**
* This method determines whether the browser supports {@link CDATASection} as
* distinct entities from <code>Text</code> nodes.
*
* @return true if the browser supports {@link CDATASection}, otherwise
* <code>false</code>.
*/
public static boolean supportsCDATASection() {
return impl.supportsCDATASection();
}
/*
* The inner recursive method for removeWhitespace
*/
private static void removeWhitespaceInner(Node n, Node parent) {
// This n is removed from the parent if n is a whitespace node
if (parent != null && n instanceof Text && (!(n instanceof CDATASection))) {
Text t = (Text) n;
if (t.getData().matches("[ \t\n]*")) {
parent.removeChild(t);
}
}
if (n.hasChildNodes()) {
int length = n.getChildNodes().getLength();
List<Node> toBeProcessed = new ArrayList<Node>();
// We collect all the nodes to iterate as the child nodes will
// change upon removal
for (int i = 0; i < length; i++) {
toBeProcessed.add(n.getChildNodes().item(i));
}
// This changes the child nodes, but the iterator of nodes never
// changes meaning that this is safe
for (Node childNode : toBeProcessed) {
removeWhitespaceInner(childNode, n);
}
}
}
/**
* Not instantiable.
*/
private XMLParser() {
}
}
| datalint/open | Open/src/main/java/com/datalint/open/shared/xml/XMLParser.java | Java | apache-2.0 | 3,302 |
(function () {
'use strict';
app.service('reportService', reportService);
function reportService($http, $window, $interval, timeAgo, restCall, queryService, dashboardFactory, ngAuthSettings, reportServiceUrl) {
var populateReport = function (report, url) {
function successCallback(response) {
if (response.data.data.length === 0) {
report.status = 'EMPTY'
} else {
report.status = 'SUCCESS';
report.data = response.data.data;
report.getTotal();
console.log(report);
}
}
function errorCallback(error) {
console.log(error);
this.status = 'FAILED';
}
restCall('GET', url, null, successCallback, errorCallback)
}
var getReport = function () {
return {
data: {},
searchParam : {
startdate: null,
enddate: null,
type: "ENTERPRISE",
generateexcel: false,
userid: null,
username: null
},
total : {
totalVendor: 0,
totalDelivery: 0,
totalPending: 0,
totalInProgress: 0,
totalCompleted: 0,
totalCancelled: 0,
totalProductPrice: 0,
totalDeliveryCharge: 0
},
getTotal: function () {
var itSelf = this;
itSelf.total.totalVendor = 0;
itSelf.total.totalDelivery = 0;
itSelf.total.totalPending = 0;
itSelf.total.totalInProgress = 0;
itSelf.total.totalCompleted = 0;
itSelf.total.totalCancelled = 0;
itSelf.total.totalProductPrice = 0;
itSelf.total.totalDeliveryCharge = 0;
angular.forEach(this.data, function (value, key) {
itSelf.total.totalVendor += 1;
itSelf.total.totalDelivery += value.TotalDelivery;
itSelf.total.totalPending += value.TotalPending;
itSelf.total.totalInProgress += value.TotalInProgress;
itSelf.total.totalCompleted += value.TotalCompleted;
itSelf.total.totalCancelled += value.TotalCancelled;
itSelf.total.totalProductPrice += value.TotalProductPrice;
itSelf.total.totalDeliveryCharge += value.TotalDeliveryCharge;
});
console.log(this.total)
},
getUrl: function () {
// FIXME: need to be refactored
if (this.searchParam.type === "BIKE_MESSENGER") {
return reportServiceUrl + "api/report?startdate="+this.searchParam.startdate+"&enddate="+this.searchParam.enddate+"&usertype="+this.searchParam.type;
}
return reportServiceUrl + "api/report?startdate="+this.searchParam.startdate+"&enddate="+this.searchParam.enddate+"&usertype="+this.searchParam.type;
},
getReport: function () {
var reportUrl = this.getUrl();
this.status = 'IN_PROGRESS';
populateReport(this, reportUrl);
},
goToReportJobs : function (user) {
console.log(user)
console.log(this.data)
if (this.searchParam.type === "BIKE_MESSENGER") {
$window.open("#/report/jobs?" + "startdate=" + this.searchParam.startdate + "&enddate="+ this.searchParam.enddate +
"&usertype=BIKE_MESSENGER" + "&userid=" + this.data[user].UserId, '_blank');
} else {
$window.open("#/report/jobs?" + "startdate=" + this.searchParam.startdate + "&enddate="+ this.searchParam.enddate + "&usertype=" + this.searchParam.type + "&username=" + user, '_blank');
}
},
exportExcel : function () {
var excelReportUrl = reportServiceUrl + "api/report?startdate="+this.searchParam.startdate+"&enddate="+this.searchParam.enddate+"&usertype="+this.searchParam.type + "&generateexcel=true";
$window.open(excelReportUrl, '_blank');
},
status : 'NONE'
}
}
return {
getReport: getReport
}
}
})();
| NerdCats/T-Rex | app/services/reportService.js | JavaScript | apache-2.0 | 3,588 |
/*******************************************************************************
* Copyright 2013-2015 alladin-IT 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 at.alladin.rmbt.controlServer;
import java.lang.reflect.Type;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Locale;
import java.util.ResourceBundle;
import javax.naming.NamingException;
import org.joda.time.DateTime;
import org.json.JSONException;
import org.json.JSONObject;
import org.restlet.data.Reference;
import org.restlet.engine.header.Header;
import org.restlet.representation.Representation;
import org.restlet.resource.Options;
import org.restlet.resource.ResourceException;
import org.restlet.util.Series;
import at.alladin.rmbt.db.DbConnection;
import at.alladin.rmbt.shared.ResourceManager;
import at.alladin.rmbt.util.capability.Capabilities;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;
import com.google.gson.JsonPrimitive;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;
public class ServerResource extends org.restlet.resource.ServerResource
{
protected Connection conn;
protected ResourceBundle labels;
protected ResourceBundle settings;
protected Capabilities capabilities = new Capabilities();
public static class MyDateTimeAdapter implements JsonSerializer<DateTime>, JsonDeserializer<DateTime>
{
public JsonElement serialize(DateTime src, Type typeOfSrc, JsonSerializationContext context)
{
return new JsonPrimitive(src.toString());
}
public DateTime deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
throws JsonParseException
{
return new DateTime(json.getAsJsonPrimitive().getAsString());
}
}
public void readCapabilities(final JSONObject request) throws JSONException {
if (request != null) {
if (request.has("capabilities")) {
capabilities = new Gson().fromJson(request.get("capabilities").toString(), Capabilities.class);
}
}
}
public static Gson getGson(boolean prettyPrint)
{
GsonBuilder gb = new GsonBuilder()
.registerTypeAdapter(DateTime.class, new MyDateTimeAdapter());
if (prettyPrint)
gb = gb.setPrettyPrinting();
return gb.create();
}
@Override
public void doInit() throws ResourceException
{
super.doInit();
settings = ResourceManager.getCfgBundle();
// Set default Language for System
Locale.setDefault(new Locale(settings.getString("RMBT_DEFAULT_LANGUAGE")));
labels = ResourceManager.getSysMsgBundle();
try {
if (getQuery().getNames().contains("capabilities")) {
capabilities = new Gson().fromJson(getQuery().getValues("capabilities"), Capabilities.class);
}
} catch (final Exception e) {
e.printStackTrace();
}
// Get DB-Connection
try
{
conn = DbConnection.getConnection();
}
catch (final NamingException e)
{
e.printStackTrace();
}
catch (final SQLException e)
{
System.out.println(labels.getString("ERROR_DB_CONNECTION_FAILED"));
e.printStackTrace();
}
}
@Override
protected void doRelease() throws ResourceException
{
try
{
if (conn != null)
conn.close();
}
catch (final SQLException e)
{
e.printStackTrace();
}
}
@SuppressWarnings("unchecked")
protected void addAllowOrigin()
{
Series<Header> responseHeaders = (Series<Header>) getResponse().getAttributes().get("org.restlet.http.headers");
if (responseHeaders == null)
{
responseHeaders = new Series<>(Header.class);
getResponse().getAttributes().put("org.restlet.http.headers", responseHeaders);
}
responseHeaders.add("Access-Control-Allow-Origin", "*");
responseHeaders.add("Access-Control-Allow-Methods", "GET,POST,OPTIONS");
responseHeaders.add("Access-Control-Allow-Headers", "Content-Type");
responseHeaders.add("Access-Control-Allow-Credentials", "false");
responseHeaders.add("Access-Control-Max-Age", "60");
}
@Options
public void doOptions(final Representation entity)
{
addAllowOrigin();
}
@SuppressWarnings("unchecked")
public String getIP()
{
final Series<Header> headers = (Series<Header>) getRequest().getAttributes().get("org.restlet.http.headers");
final String realIp = headers.getFirstValue("X-Real-IP", true);
if (realIp != null)
return realIp;
else
return getRequest().getClientInfo().getAddress();
}
@SuppressWarnings("unchecked")
public Reference getURL()
{
final Series<Header> headers = (Series<Header>) getRequest().getAttributes().get("org.restlet.http.headers");
final String realURL = headers.getFirstValue("X-Real-URL", true);
if (realURL != null)
return new Reference(realURL);
else
return getRequest().getOriginalRef();
}
protected String getSetting(String key, String lang)
{
if (conn == null)
return null;
try (final PreparedStatement st = conn.prepareStatement(
"SELECT value"
+ " FROM settings"
+ " WHERE key=? AND (lang IS NULL OR lang = ?)"
+ " ORDER BY lang NULLS LAST LIMIT 1");)
{
st.setString(1, key);
st.setString(2, lang);
try (final ResultSet rs = st.executeQuery();)
{
if (rs != null && rs.next())
return rs.getString("value");
}
return null;
}
catch (SQLException e)
{
e.printStackTrace();
return null;
}
}
}
| alladin-IT/open-rmbt | RMBTControlServer/src/at/alladin/rmbt/controlServer/ServerResource.java | Java | apache-2.0 | 7,059 |
package io.github.marktony.reader.qsbk;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.Snackbar;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import java.util.ArrayList;
import io.github.marktony.reader.R;
import io.github.marktony.reader.adapter.QsbkArticleAdapter;
import io.github.marktony.reader.data.Qiushibaike;
import io.github.marktony.reader.interfaze.OnRecyclerViewClickListener;
import io.github.marktony.reader.interfaze.OnRecyclerViewLongClickListener;
/**
* Created by Lizhaotailang on 2016/8/4.
*/
public class QsbkFragment extends Fragment
implements QsbkContract.View {
private QsbkContract.Presenter presenter;
private QsbkArticleAdapter adapter;
private RecyclerView recyclerView;
private SwipeRefreshLayout refreshLayout;
public QsbkFragment() {
// requires empty constructor
}
public static QsbkFragment newInstance(int page) {
return new QsbkFragment();
}
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.joke_list_fragment, container, false);
initViews(view);
presenter.loadArticle(true);
refreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {
presenter.loadArticle(true);
adapter.notifyDataSetChanged();
if (refreshLayout.isRefreshing()){
refreshLayout.setRefreshing(false);
}
}
});
recyclerView.setOnScrollListener(new RecyclerView.OnScrollListener() {
boolean isSlidingToLast = false;
@Override
public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
LinearLayoutManager manager = (LinearLayoutManager) recyclerView.getLayoutManager();
// 当不滚动时
if (newState == RecyclerView.SCROLL_STATE_IDLE) {
// 获取最后一个完全显示的itemposition
int lastVisibleItem = manager.findLastCompletelyVisibleItemPosition();
int totalItemCount = manager.getItemCount();
// 判断是否滚动到底部并且是向下滑动
if (lastVisibleItem == (totalItemCount - 1) && isSlidingToLast) {
presenter.loadMore();
}
}
super.onScrollStateChanged(recyclerView, newState);
}
@Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
isSlidingToLast = dy > 0;
}
});
return view;
}
@Override
public void setPresenter(QsbkContract.Presenter presenter) {
if (presenter != null) {
this.presenter = presenter;
}
}
@Override
public void initViews(View view) {
recyclerView = (RecyclerView) view.findViewById(R.id.qsbk_rv);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
refreshLayout = (SwipeRefreshLayout) view.findViewById(R.id.refresh);
}
@Override
public void showResult(ArrayList<Qiushibaike.Item> articleList) {
if (adapter == null) {
adapter = new QsbkArticleAdapter(getActivity(), articleList);
recyclerView.setAdapter(adapter);
} else {
adapter.notifyDataSetChanged();
}
adapter.setOnItemClickListener(new OnRecyclerViewClickListener() {
@Override
public void OnClick(View v, int position) {
presenter.shareTo(position);
}
});
adapter.setOnItemLongClickListener(new OnRecyclerViewLongClickListener() {
@Override
public void OnLongClick(View view, int position) {
presenter.copyToClipboard(position);
}
});
}
@Override
public void startLoading() {
refreshLayout.post(new Runnable() {
@Override
public void run() {
refreshLayout.setRefreshing(true);
}
});
}
@Override
public void stopLoading() {
refreshLayout.post(new Runnable() {
@Override
public void run() {
refreshLayout.setRefreshing(false);
}
});
}
@Override
public void showLoadError() {
Snackbar.make(recyclerView, "加载失败", Snackbar.LENGTH_SHORT)
.setAction("重试", new View.OnClickListener() {
@Override
public void onClick(View view) {
presenter.loadArticle(false);
}
}).show();
}
@Override
public void onResume() {
super.onResume();
presenter.start();
}
}
| HeJianF/iReader | app/src/main/java/io/github/marktony/reader/qsbk/QsbkFragment.java | Java | apache-2.0 | 5,506 |
var array = trace ( new Array());
var m = trace ( 0 );
var n = trace ( 3 );
var o = trace ( 5 );
var p = trace ( 7 );
array[0] = m;
array[1] = n;
array[2] = o;
array[3] = p;
var result = new Array();
// FOR-IN Schleife
for ( i in array ) {
result.push(i);
x = i;
z = 7;
}
var a = result;
var b = result[0];
var c = 7;
var d = x; | keil/TbDA | test/dependency_state/rule_forin.js | JavaScript | apache-2.0 | 360 |
/*
* 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.geode.management.internal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.logging.log4j.Logger;
import org.apache.geode.annotations.internal.MakeNotStatic;
import org.apache.geode.distributed.DistributedSystemDisconnectedException;
import org.apache.geode.distributed.internal.InternalDistributedSystem;
import org.apache.geode.internal.cache.InternalCache;
import org.apache.geode.internal.cache.InternalCacheForClientAccess;
import org.apache.geode.logging.internal.log4j.api.LogService;
import org.apache.geode.management.ManagementService;
/**
* Super class to all Management Service
*
* @since GemFire 7.0
*/
public abstract class BaseManagementService extends ManagementService {
private static final Logger logger = LogService.getLogger();
/**
* The main mapping between different resources and Service instance Object can be Cache
*/
@MakeNotStatic
protected static final Map<Object, BaseManagementService> instances =
new HashMap<Object, BaseManagementService>();
/** List of connected <code>DistributedSystem</code>s */
@MakeNotStatic
private static final List<InternalDistributedSystem> systems =
new ArrayList<InternalDistributedSystem>(1);
/** Protected constructor. */
protected BaseManagementService() {}
// Static block to initialize the ConnectListener on the System
static {
initInternalDistributedSystem();
}
/**
* This method will close the service. Any operation on the service instance will throw exception
*/
protected abstract void close();
/**
* This method will close the service. Any operation on the service instance will throw exception
*/
protected abstract boolean isClosed();
/**
* Returns a ManagementService to use for the specified Cache.
*
* @param cache defines the scope of resources to be managed
*/
public static ManagementService getManagementService(InternalCacheForClientAccess cache) {
synchronized (instances) {
BaseManagementService service = instances.get(cache);
if (service == null) {
service = SystemManagementService.newSystemManagementService(cache);
instances.put(cache, service);
}
return service;
}
}
public static ManagementService getExistingManagementService(InternalCache cache) {
synchronized (instances) {
BaseManagementService service = instances.get(cache.getCacheForProcessingClientRequests());
return service;
}
}
/**
* Initialises the distributed system listener
*/
private static void initInternalDistributedSystem() {
synchronized (instances) {
// Initialize our own list of distributed systems via a connect listener
@SuppressWarnings("unchecked")
List<InternalDistributedSystem> existingSystems = InternalDistributedSystem
.addConnectListener(new InternalDistributedSystem.ConnectListener() {
@Override
public void onConnect(InternalDistributedSystem sys) {
addInternalDistributedSystem(sys);
}
});
// While still holding the lock on systems, add all currently known
// systems to our own list
for (InternalDistributedSystem sys : existingSystems) {
try {
if (sys.isConnected()) {
addInternalDistributedSystem(sys);
}
} catch (DistributedSystemDisconnectedException e) {
if (logger.isDebugEnabled()) {
logger.debug("DistributedSystemDisconnectedException {}", e.getMessage(), e);
}
}
}
}
}
/**
* Add an Distributed System and adds a Discon Listener
*/
private static void addInternalDistributedSystem(InternalDistributedSystem sys) {
synchronized (instances) {
sys.addDisconnectListener(new InternalDistributedSystem.DisconnectListener() {
@Override
public String toString() {
return "Disconnect listener for BaseManagementService";
}
@Override
public void onDisconnect(InternalDistributedSystem ss) {
removeInternalDistributedSystem(ss);
}
});
systems.add(sys);
}
}
/**
* Remove a Distributed System from the system lists. If list is empty it closes down all the
* services if not closed
*/
private static void removeInternalDistributedSystem(InternalDistributedSystem sys) {
synchronized (instances) {
systems.remove(sys);
if (systems.isEmpty()) {
for (Object key : instances.keySet()) {
BaseManagementService service = (BaseManagementService) instances.get(key);
try {
if (!service.isClosed()) {
// Service close method should take care of the cleaning up
// activities
service.close();
}
} catch (Exception e) {
if (logger.isDebugEnabled()) {
logger.debug("ManagementException while removing InternalDistributedSystem {}",
e.getMessage(), e);
}
}
}
instances.clear();
}
}
}
}
| davebarnes97/geode | geode-core/src/main/java/org/apache/geode/management/internal/BaseManagementService.java | Java | apache-2.0 | 5,962 |
/*
* Copyright 1999-2020 Alibaba Group Holding Ltd.
*
* 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.csp.sentinel.adapter.okhttp.extractor;
import okhttp3.Connection;
import okhttp3.Request;
/**
* @author zhaoyuguang
*/
public class DefaultOkHttpResourceExtractor implements OkHttpResourceExtractor {
@Override
public String extract(Request request, Connection connection) {
return request.method() + ":" + request.url().toString();
}
}
| alibaba/Sentinel | sentinel-adapter/sentinel-okhttp-adapter/src/main/java/com/alibaba/csp/sentinel/adapter/okhttp/extractor/DefaultOkHttpResourceExtractor.java | Java | apache-2.0 | 997 |
package com.melvin.share.ui.activity;
import android.content.Context;
import android.databinding.DataBindingUtil;
import android.text.TextUtils;
import android.view.View;
import android.widget.LinearLayout;
import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.jcodecraeer.xrecyclerview.ProgressStyle;
import com.melvin.share.R;
import com.melvin.share.Utils.ShapreUtils;
import com.melvin.share.Utils.Utils;
import com.melvin.share.databinding.ActivityOrderEvaluateBinding;
import com.melvin.share.model.Evaluation;
import com.melvin.share.model.WaitPayOrderInfo;
import com.melvin.share.model.list.CommonList;
import com.melvin.share.model.serverReturn.CommonReturnModel;
import com.melvin.share.modelview.acti.OrderEvaluateViewModel;
import com.melvin.share.network.GlobalUrl;
import com.melvin.share.rx.RxActivityHelper;
import com.melvin.share.rx.RxFragmentHelper;
import com.melvin.share.rx.RxModelSubscribe;
import com.melvin.share.rx.RxSubscribe;
import com.melvin.share.ui.activity.common.BaseActivity;
import com.melvin.share.ui.activity.shopcar.ShoppingCarActivity;
import com.melvin.share.ui.fragment.productinfo.ProductEvaluateFragment;
import com.melvin.share.view.MyRecyclerView;
import com.melvin.share.view.RatingBar;
import java.util.HashMap;
import java.util.Map;
import static com.melvin.share.R.id.map;
import static com.melvin.share.R.id.ratingbar;
/**
* Author: Melvin
* <p/>
* Data: 2017/4/8
* <p/>
* 描述: 订单评价页面
*/
public class OderEvaluateActivity extends BaseActivity {
private ActivityOrderEvaluateBinding binding;
private Context mContext = null;
private int starCount;
private WaitPayOrderInfo.OrderBean.OrderItemResponsesBean orderItemResponsesBean;
@Override
protected void initView() {
binding = DataBindingUtil.setContentView(this, R.layout.activity_order_evaluate);
mContext = this;
initWindow();
initToolbar(binding.toolbar);
ininData();
}
private void ininData() {
binding.ratingbar.setOnRatingChangeListener(new RatingBar.OnRatingChangeListener() {
@Override
public void onRatingChange(int var1) {
starCount = var1;
}
});
orderItemResponsesBean = getIntent().getParcelableExtra("orderItemResponsesBean");
if (orderItemResponsesBean != null) {
String[] split = orderItemResponsesBean.mainPicture.split("\\|");
if (split != null && split.length >= 1) {
String url = GlobalUrl.SERVICE_URL + split[0];
Glide.with(mContext)
.load(url)
.placeholder(R.mipmap.logo)
.centerCrop()
.into(binding.image);
}
binding.name.setText(orderItemResponsesBean.productName);
}
}
public void submit(View view) {
String contents = binding.content.getText().toString();
if (TextUtils.isEmpty(contents)) {
Utils.showToast(mContext, "请评价");
}
if (starCount == 0) {
Utils.showToast(mContext, "请评分");
}
Map map = new HashMap();
map.put("orderItemId", orderItemResponsesBean.id);
map.put("startlevel", starCount);
map.put("picture", orderItemResponsesBean.mainPicture);
map.put("content", contents);
ShapreUtils.putParamCustomerId(map);
JsonParser jsonParser = new JsonParser();
JsonObject jsonObject = (JsonObject) jsonParser.parse((new Gson().toJson(map)));
fromNetwork.insertOderItemEvaluation(jsonObject)
.compose(new RxActivityHelper<CommonReturnModel>().ioMain(OderEvaluateActivity.this, true))
.subscribe(new RxSubscribe<CommonReturnModel>(mContext, true) {
@Override
protected void myNext(CommonReturnModel commonReturnModel) {
Utils.showToast(mContext, commonReturnModel.message);
finish();
}
@Override
protected void myError(String message) {
Utils.showToast(mContext, message);
}
});
}
}
| MelvinWang/NewShare | NewShare/app/src/main/java/com/melvin/share/ui/activity/OderEvaluateActivity.java | Java | apache-2.0 | 4,380 |
// (C) Copyright 2015 Martin Dougiamas
//
// 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.
import { Component, OnDestroy } from '@angular/core';
import { Platform, NavParams } from 'ionic-angular';
import { TranslateService } from '@ngx-translate/core';
import { CoreEventsProvider } from '@providers/events';
import { CoreSitesProvider } from '@providers/sites';
import { AddonMessagesProvider } from '../../providers/messages';
import { CoreDomUtilsProvider } from '@providers/utils/dom';
import { CoreUtilsProvider } from '@providers/utils/utils';
import { CoreAppProvider } from '@providers/app';
import { AddonPushNotificationsDelegate } from '@addon/pushnotifications/providers/delegate';
/**
* Component that displays the list of discussions.
*/
@Component({
selector: 'addon-messages-discussions',
templateUrl: 'addon-messages-discussions.html',
})
export class AddonMessagesDiscussionsComponent implements OnDestroy {
protected newMessagesObserver: any;
protected readChangedObserver: any;
protected cronObserver: any;
protected appResumeSubscription: any;
protected loadingMessages: string;
protected siteId: string;
loaded = false;
loadingMessage: string;
discussions: any;
discussionUserId: number;
pushObserver: any;
search = {
enabled: false,
showResults: false,
results: [],
loading: '',
text: ''
};
constructor(private eventsProvider: CoreEventsProvider, sitesProvider: CoreSitesProvider, translate: TranslateService,
private messagesProvider: AddonMessagesProvider, private domUtils: CoreDomUtilsProvider, navParams: NavParams,
private appProvider: CoreAppProvider, platform: Platform, utils: CoreUtilsProvider,
pushNotificationsDelegate: AddonPushNotificationsDelegate) {
this.search.loading = translate.instant('core.searching');
this.loadingMessages = translate.instant('core.loading');
this.siteId = sitesProvider.getCurrentSiteId();
// Update discussions when new message is received.
this.newMessagesObserver = eventsProvider.on(AddonMessagesProvider.NEW_MESSAGE_EVENT, (data) => {
if (data.userId) {
const discussion = this.discussions.find((disc) => {
return disc.message.user == data.userId;
});
if (typeof discussion == 'undefined') {
this.loaded = false;
this.refreshData().finally(() => {
this.loaded = true;
});
} else {
// An existing discussion has a new message, update the last message.
discussion.message.message = data.message;
discussion.message.timecreated = data.timecreated;
}
}
}, this.siteId);
// Update discussions when a message is read.
this.readChangedObserver = eventsProvider.on(AddonMessagesProvider.READ_CHANGED_EVENT, (data) => {
if (data.userId) {
const discussion = this.discussions.find((disc) => {
return disc.message.user == data.userId;
});
if (typeof discussion != 'undefined') {
// A discussion has been read reset counter.
discussion.unread = false;
// Discussions changed, invalidate them.
this.messagesProvider.invalidateDiscussionsCache();
}
}
}, this.siteId);
// Update discussions when cron read is executed.
this.cronObserver = eventsProvider.on(AddonMessagesProvider.READ_CRON_EVENT, (data) => {
this.refreshData();
}, this.siteId);
// Refresh the view when the app is resumed.
this.appResumeSubscription = platform.resume.subscribe(() => {
if (!this.loaded) {
return;
}
this.loaded = false;
this.refreshData();
});
this.discussionUserId = navParams.get('discussionUserId') || false;
// If a message push notification is received, refresh the view.
this.pushObserver = pushNotificationsDelegate.on('receive').subscribe((notification) => {
// New message received. If it's from current site, refresh the data.
if (utils.isFalseOrZero(notification.notif) && notification.site == this.siteId) {
this.refreshData();
}
});
}
/**
* Component loaded.
*/
ngOnInit(): void {
if (this.discussionUserId) {
// There is a discussion to load, open the discussion in a new state.
this.gotoDiscussion(this.discussionUserId);
}
this.fetchData().then(() => {
if (!this.discussionUserId && this.discussions.length > 0) {
// Take first and load it.
this.gotoDiscussion(this.discussions[0].message.user, undefined, true);
}
});
}
/**
* Refresh the data.
*
* @param {any} [refresher] Refresher.
* @return {Promise<any>} Promise resolved when done.
*/
refreshData(refresher?: any): Promise<any> {
return this.messagesProvider.invalidateDiscussionsCache().then(() => {
return this.fetchData().finally(() => {
if (refresher) {
// Actions to take if refresh comes from the user.
this.eventsProvider.trigger(AddonMessagesProvider.READ_CHANGED_EVENT, undefined, this.siteId);
refresher.complete();
}
});
});
}
/**
* Fetch discussions.
*
* @return {Promise<any>} Promise resolved when done.
*/
protected fetchData(): Promise<any> {
this.loadingMessage = this.loadingMessages;
this.search.enabled = this.messagesProvider.isSearchMessagesEnabled();
return this.messagesProvider.getDiscussions().then((discussions) => {
// Convert to an array for sorting.
const discussionsSorted = [];
for (const userId in discussions) {
discussions[userId].unread = !!discussions[userId].unread;
discussionsSorted.push(discussions[userId]);
}
this.discussions = discussionsSorted.sort((a, b) => {
return b.message.timecreated - a.message.timecreated;
});
}).catch((error) => {
this.domUtils.showErrorModalDefault(error, 'addon.messages.errorwhileretrievingdiscussions', true);
}).finally(() => {
this.loaded = true;
});
}
/**
* Clear search and show discussions again.
*/
clearSearch(): void {
this.loaded = false;
this.search.showResults = false;
this.search.text = ''; // Reset searched string.
this.fetchData().finally(() => {
this.loaded = true;
});
}
/**
* Search messages cotaining text.
*
* @param {string} query Text to search for.
* @return {Promise<any>} Resolved when done.
*/
searchMessage(query: string): Promise<any> {
this.appProvider.closeKeyboard();
this.loaded = false;
this.loadingMessage = this.search.loading;
return this.messagesProvider.searchMessages(query).then((searchResults) => {
this.search.showResults = true;
this.search.results = searchResults;
}).catch((error) => {
this.domUtils.showErrorModalDefault(error, 'addon.messages.errorwhileretrievingmessages', true);
}).finally(() => {
this.loaded = true;
});
}
/**
* Navigate to a particular discussion.
*
* @param {number} discussionUserId Discussion Id to load.
* @param {number} [messageId] Message to scroll after loading the discussion. Used when searching.
* @param {boolean} [onlyWithSplitView=false] Only go to Discussion if split view is on.
*/
gotoDiscussion(discussionUserId: number, messageId?: number, onlyWithSplitView: boolean = false): void {
this.discussionUserId = discussionUserId;
const params = {
discussion: discussionUserId,
onlyWithSplitView: onlyWithSplitView
};
if (messageId) {
params['message'] = messageId;
}
this.eventsProvider.trigger(AddonMessagesProvider.SPLIT_VIEW_LOAD_EVENT, params, this.siteId);
}
/**
* Component destroyed.
*/
ngOnDestroy(): void {
this.newMessagesObserver && this.newMessagesObserver.off();
this.readChangedObserver && this.readChangedObserver.off();
this.cronObserver && this.cronObserver.off();
this.appResumeSubscription && this.appResumeSubscription.unsubscribe();
this.pushObserver && this.pushObserver.unsubscribe();
}
}
| jleyva/moodlemobile2 | src/addon/messages/components/discussions/discussions.ts | TypeScript | apache-2.0 | 9,547 |
package clockworktest.water;
import com.clockwork.app.SimpleApplication;
import com.clockwork.audio.AudioNode;
import com.clockwork.audio.LowPassFilter;
import com.clockwork.effect.ParticleEmitter;
import com.clockwork.effect.ParticleMesh;
import com.clockwork.input.KeyInput;
import com.clockwork.input.controls.ActionListener;
import com.clockwork.input.controls.KeyTrigger;
import com.clockwork.light.DirectionalLight;
import com.clockwork.material.Material;
import com.clockwork.material.RenderState.BlendMode;
import com.clockwork.math.ColorRGBA;
import com.clockwork.math.FastMath;
import com.clockwork.math.Quaternion;
import com.clockwork.math.Vector3f;
import com.clockwork.post.FilterPostProcessor;
import com.clockwork.post.filters.BloomFilter;
import com.clockwork.post.filters.DepthOfFieldFilter;
import com.clockwork.post.filters.LightScatteringFilter;
import com.clockwork.renderer.Camera;
import com.clockwork.renderer.queue.RenderQueue.Bucket;
import com.clockwork.renderer.queue.RenderQueue.ShadowMode;
import com.clockwork.scene.Geometry;
import com.clockwork.scene.Node;
import com.clockwork.scene.Spatial;
import com.clockwork.scene.shape.Box;
import com.clockwork.terrain.geomipmap.TerrainQuad;
import com.clockwork.terrain.heightmap.AbstractHeightMap;
import com.clockwork.terrain.heightmap.ImageBasedHeightMap;
import com.clockwork.texture.Texture;
import com.clockwork.texture.Texture.WrapMode;
import com.clockwork.texture.Texture2D;
import com.clockwork.util.SkyFactory;
import com.clockwork.water.WaterFilter;
import java.util.ArrayList;
import java.util.List;
/**
* test
*
*/
public class TestPostWater extends SimpleApplication {
private Vector3f lightDir = new Vector3f(-4.9236743f, -1.27054665f, 5.896916f);
private WaterFilter water;
TerrainQuad terrain;
Material matRock;
AudioNode waves;
LowPassFilter underWaterAudioFilter = new LowPassFilter(0.5f, 0.1f);
LowPassFilter underWaterReverbFilter = new LowPassFilter(0.5f, 0.1f);
LowPassFilter aboveWaterAudioFilter = new LowPassFilter(1, 1);
public static void main(String[] args) {
TestPostWater app = new TestPostWater();
app.start();
}
@Override
public void simpleInitApp() {
setDisplayFps(false);
setDisplayStatView(false);
Node mainScene = new Node("Main Scene");
rootNode.attachChild(mainScene);
createTerrain(mainScene);
DirectionalLight sun = new DirectionalLight();
sun.setDirection(lightDir);
sun.setColor(ColorRGBA.White.clone().multLocal(1.7f));
mainScene.addLight(sun);
DirectionalLight l = new DirectionalLight();
l.setDirection(Vector3f.UNIT_Y.mult(-1));
l.setColor(ColorRGBA.White.clone().multLocal(0.3f));
// mainScene.addLight(l);
flyCam.setMoveSpeed(50);
//cam.setLocation(new Vector3f(-700, 100, 300));
//cam.setRotation(new Quaternion().fromAngleAxis(0.5f, Vector3f.UNIT_Z));
cam.setLocation(new Vector3f(-327.21957f, 61.6459f, 126.884346f));
cam.setRotation(new Quaternion(0.052168474f, 0.9443102f, -0.18395276f, 0.2678024f));
cam.setRotation(new Quaternion().fromAngles(new float[]{FastMath.PI * 0.06f, FastMath.PI * 0.65f, 0}));
Spatial sky = SkyFactory.createSky(assetManager, "Scenes/Beach/FullskiesSunset0068.dds", false);
sky.setLocalScale(350);
mainScene.attachChild(sky);
cam.setFrustumFar(4000);
//cam.setFrustumNear(100);
//private FilterPostProcessor fpp;
water = new WaterFilter(rootNode, lightDir);
FilterPostProcessor fpp = new FilterPostProcessor(assetManager);
fpp.addFilter(water);
BloomFilter bloom = new BloomFilter();
//bloom.getE
bloom.setExposurePower(55);
bloom.setBloomIntensity(1.0f);
fpp.addFilter(bloom);
LightScatteringFilter lsf = new LightScatteringFilter(lightDir.mult(-300));
lsf.setLightDensity(1.0f);
fpp.addFilter(lsf);
DepthOfFieldFilter dof = new DepthOfFieldFilter();
dof.setFocusDistance(0);
dof.setFocusRange(100);
fpp.addFilter(dof);
//
// fpp.addFilter(new TranslucentBucketFilter());
//
// fpp.setNumSamples(4);
water.setWaveScale(0.003f);
water.setMaxAmplitude(2f);
water.setFoamExistence(new Vector3f(1f, 4, 0.5f));
water.setFoamTexture((Texture2D) assetManager.loadTexture("Common/MatDefs/Water/Textures/foam2.jpg"));
//water.setNormalScale(0.5f);
//water.setRefractionConstant(0.25f);
water.setRefractionStrength(0.2f);
//water.setFoamHardness(0.6f);
water.setWaterHeight(initialWaterHeight);
uw = cam.getLocation().y < waterHeight;
waves = new AudioNode(assetManager, "Sound/Environment/Ocean Waves.ogg", false);
waves.setLooping(true);
waves.setReverbEnabled(true);
if (uw) {
waves.setDryFilter(new LowPassFilter(0.5f, 0.1f));
} else {
waves.setDryFilter(aboveWaterAudioFilter);
}
audioRenderer.playSource(waves);
//
viewPort.addProcessor(fpp);
inputManager.addListener(new ActionListener() {
public void onAction(String name, boolean isPressed, float tpf) {
if (isPressed) {
if (name.equals("foam1")) {
water.setFoamTexture((Texture2D) assetManager.loadTexture("Common/MatDefs/Water/Textures/foam.jpg"));
}
if (name.equals("foam2")) {
water.setFoamTexture((Texture2D) assetManager.loadTexture("Common/MatDefs/Water/Textures/foam2.jpg"));
}
if (name.equals("foam3")) {
water.setFoamTexture((Texture2D) assetManager.loadTexture("Common/MatDefs/Water/Textures/foam3.jpg"));
}
if (name.equals("upRM")) {
water.setReflectionMapSize(Math.min(water.getReflectionMapSize() * 2, 4096));
System.out.println("Reflection map size : " + water.getReflectionMapSize());
}
if (name.equals("downRM")) {
water.setReflectionMapSize(Math.max(water.getReflectionMapSize() / 2, 32));
System.out.println("Reflection map size : " + water.getReflectionMapSize());
}
}
}
}, "foam1", "foam2", "foam3", "upRM", "downRM");
inputManager.addMapping("foam1", new KeyTrigger(KeyInput.KEY_1));
inputManager.addMapping("foam2", new KeyTrigger(KeyInput.KEY_2));
inputManager.addMapping("foam3", new KeyTrigger(KeyInput.KEY_3));
inputManager.addMapping("upRM", new KeyTrigger(KeyInput.KEY_PGUP));
inputManager.addMapping("downRM", new KeyTrigger(KeyInput.KEY_PGDN));
// createBox();
// createFire();
}
Geometry box;
private void createBox() {
//creating a transluscent box
box = new Geometry("box", new Box(new Vector3f(0, 0, 0), 50, 50, 50));
Material mat = new Material(assetManager, "Common/MatDefs/Misc/Unshaded.j3md");
mat.setColor("Color", new ColorRGBA(1.0f, 0, 0, 0.3f));
mat.getAdditionalRenderState().setBlendMode(BlendMode.Alpha);
//mat.getAdditionalRenderState().setDepthWrite(false);
//mat.getAdditionalRenderState().setDepthTest(false);
box.setMaterial(mat);
box.setQueueBucket(Bucket.Translucent);
//creating a post view port
// ViewPort post=renderManager.createPostView("transpPost", cam);
// post.setClearFlags(false, true, true);
box.setLocalTranslation(-600, 0, 300);
//attaching the box to the post viewport
//Don't forget to updateGeometricState() the box in the simpleUpdate
// post.attachScene(box);
rootNode.attachChild(box);
}
private void createFire() {
/**
* Uses Texture from CW-test-data library!
*/
ParticleEmitter fire = new ParticleEmitter("Emitter", ParticleMesh.Type.Triangle, 30);
Material mat_red = new Material(assetManager, "Common/MatDefs/Misc/Particle.j3md");
mat_red.setTexture("Texture", assetManager.loadTexture("Effects/Explosion/flame.png"));
fire.setMaterial(mat_red);
fire.setImagesX(2);
fire.setImagesY(2); // 2x2 texture animation
fire.setEndColor(new ColorRGBA(1f, 0f, 0f, 1f)); // red
fire.setStartColor(new ColorRGBA(1f, 1f, 0f, 0.5f)); // yellow
fire.getParticleInfluencer().setInitialVelocity(new Vector3f(0, 2, 0));
fire.setStartSize(10f);
fire.setEndSize(1f);
fire.setGravity(0, 0, 0);
fire.setLowLife(0.5f);
fire.setHighLife(1.5f);
fire.getParticleInfluencer().setVelocityVariation(0.3f);
fire.setLocalTranslation(-350, 40, 430);
fire.setQueueBucket(Bucket.Transparent);
rootNode.attachChild(fire);
}
private void createTerrain(Node rootNode) {
matRock = new Material(assetManager, "Common/MatDefs/Terrain/TerrainLighting.j3md");
matRock.setBoolean("useTriPlanarMapping", false);
matRock.setBoolean("WardIso", true);
matRock.setTexture("AlphaMap", assetManager.loadTexture("Textures/Terrain/splat/alphamap.png"));
Texture heightMapImage = assetManager.loadTexture("Textures/Terrain/splat/mountains512.png");
Texture grass = assetManager.loadTexture("Textures/Terrain/splat/grass.jpg");
grass.setWrap(WrapMode.Repeat);
matRock.setTexture("DiffuseMap", grass);
matRock.setFloat("DiffuseMap_0_scale", 64);
Texture dirt = assetManager.loadTexture("Textures/Terrain/splat/dirt.jpg");
dirt.setWrap(WrapMode.Repeat);
matRock.setTexture("DiffuseMap_1", dirt);
matRock.setFloat("DiffuseMap_1_scale", 16);
Texture rock = assetManager.loadTexture("Textures/Terrain/splat/road.jpg");
rock.setWrap(WrapMode.Repeat);
matRock.setTexture("DiffuseMap_2", rock);
matRock.setFloat("DiffuseMap_2_scale", 128);
Texture normalMap0 = assetManager.loadTexture("Textures/Terrain/splat/grass_normal.jpg");
normalMap0.setWrap(WrapMode.Repeat);
Texture normalMap1 = assetManager.loadTexture("Textures/Terrain/splat/dirt_normal.png");
normalMap1.setWrap(WrapMode.Repeat);
Texture normalMap2 = assetManager.loadTexture("Textures/Terrain/splat/road_normal.png");
normalMap2.setWrap(WrapMode.Repeat);
matRock.setTexture("NormalMap", normalMap0);
matRock.setTexture("NormalMap_1", normalMap2);
matRock.setTexture("NormalMap_2", normalMap2);
AbstractHeightMap heightmap = null;
try {
heightmap = new ImageBasedHeightMap(heightMapImage.getImage(), 0.25f);
heightmap.load();
} catch (Exception e) {
e.printStackTrace();
}
terrain = new TerrainQuad("terrain", 65, 513, heightmap.getHeightMap());
List<Camera> cameras = new ArrayList<Camera>();
cameras.add(getCamera());
terrain.setMaterial(matRock);
terrain.setLocalScale(new Vector3f(5, 5, 5));
terrain.setLocalTranslation(new Vector3f(0, -30, 0));
terrain.setLocked(false); // unlock it so we can edit the height
terrain.setShadowMode(ShadowMode.Receive);
rootNode.attachChild(terrain);
}
//This part is to emulate tides, slightly varrying the height of the water plane
private float time = 0.0f;
private float waterHeight = 0.0f;
private float initialWaterHeight = 90f;//0.8f;
private boolean uw = false;
@Override
public void simpleUpdate(float tpf) {
super.simpleUpdate(tpf);
// box.updateGeometricState();
time += tpf;
waterHeight = (float) Math.cos(((time * 0.6f) % FastMath.TWO_PI)) * 1.5f;
water.setWaterHeight(initialWaterHeight + waterHeight);
if (water.isUnderWater() && !uw) {
waves.setDryFilter(new LowPassFilter(0.5f, 0.1f));
uw = true;
}
if (!water.isUnderWater() && uw) {
uw = false;
//waves.setReverbEnabled(false);
waves.setDryFilter(new LowPassFilter(1, 1f));
//waves.setDryFilter(new LowPassFilter(1,1f));
}
}
}
| PlanetWaves/clockworkengine | branches/3.0/engine/src/test/clockworktest/water/TestPostWater.java | Java | apache-2.0 | 12,539 |
/*******************************************************************************
* Copyright 2002-2016 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.lothar.security.acl.elasticsearch.repository;
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;
import org.springframework.stereotype.Repository;
import com.github.lothar.security.acl.elasticsearch.domain.UnknownStrategyObject;
@Repository
public interface UnknownStrategyRepository
extends ElasticsearchRepository<UnknownStrategyObject, Long> {
}
| lordlothar99/strategy-spring-security-acl | elasticsearch/src/test/java/com/github/lothar/security/acl/elasticsearch/repository/UnknownStrategyRepository.java | Java | apache-2.0 | 1,173 |
/* ------------------------------------------------------------------------- */
//
// Copyright (c) 2010 CubeSoft, 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.
//
/* ------------------------------------------------------------------------- */
using System.Linq;
using System.Windows.Forms;
using Cube.Mixin.String;
namespace Cube.Forms.Behaviors
{
/* --------------------------------------------------------------------- */
///
/// OpenFileBehavior
///
/// <summary>
/// Provides functionality to show a open-file dialog.
/// </summary>
///
/* --------------------------------------------------------------------- */
public class OpenFileBehavior : MessageBehavior<OpenFileMessage>
{
/* ----------------------------------------------------------------- */
///
/// OpenFileBehavior
///
/// <summary>
/// Initializes a new instance of the OpenFileBehavior class
/// with the specified presentable object.
/// </summary>
///
/// <param name="aggregator">Aggregator object.</param>
///
/* ----------------------------------------------------------------- */
public OpenFileBehavior(IAggregator aggregator) : base(aggregator, e =>
{
var view = new OpenFileDialog
{
CheckPathExists = e.CheckPathExists,
Multiselect = e.Multiselect,
Filter = e.GetFilterText(),
FilterIndex = e.GetFilterIndex(),
};
if (e.Text.HasValue()) view.Title = e.Text;
if (e.Value.Any()) view.FileName = e.Value.First();
if (e.InitialDirectory.HasValue()) view.InitialDirectory = e.InitialDirectory;
e.Cancel = view.ShowDialog() != DialogResult.OK;
if (!e.Cancel) e.Value = view.FileNames;
}) { }
}
}
| cube-soft/Cube.Core | Libraries/Forms/Sources/Behaviors/Messages/OpenFileBehavior.cs | C# | apache-2.0 | 2,433 |
package javassist.build;
/**
* A generic build exception when applying a transformer.
* Wraps the real cause of the (probably javassist) root exception.
* @author SNI
*/
@SuppressWarnings("serial")
public class JavassistBuildException extends Exception {
public JavassistBuildException() {
super();
}
public JavassistBuildException(String message, Throwable throwable) {
super(message, throwable);
}
public JavassistBuildException(String message) {
super(message);
}
public JavassistBuildException(Throwable throwable) {
super(throwable);
}
}
| stephanenicolas/javassist-build-plugin-api | src/main/java/javassist/build/JavassistBuildException.java | Java | apache-2.0 | 569 |
package com.hcentive.webservice.soap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ws.server.endpoint.annotation.Endpoint;
import org.springframework.ws.server.endpoint.annotation.PayloadRoot;
import org.springframework.ws.server.endpoint.annotation.RequestPayload;
import org.springframework.ws.server.endpoint.annotation.ResponsePayload;
import com.hcentive.service.FormResponse;
import com.hcentive.webservice.exception.HcentiveSOAPException;
import org.apache.log4j.Logger;
/**
* @author Mebin.Jacob
*Endpoint class.
*/
@Endpoint
public final class FormEndpoint {
private static final String NAMESPACE_URI = "http://hcentive.com/service";
Logger logger = Logger.getLogger(FormEndpoint.class);
@Autowired
FormRepository formRepo;
@PayloadRoot(namespace = NAMESPACE_URI, localPart = "FormResponse")
@ResponsePayload
public FormResponse submitForm(@RequestPayload FormResponse request) throws HcentiveSOAPException {
// GetCountryResponse response = new GetCountryResponse();
// response.setCountry(countryRepository.findCountry(request.getName()));
FormResponse response = null;
logger.debug("AAGAYA");
try{
response = new FormResponse();
response.setForm1(formRepo.findForm("1"));
//make API call
}catch(Exception exception){
throw new HcentiveSOAPException("Something went wrong!!! The exception is --- " + exception);
}
return response;
// return null;
}
}
| mebinjacob/spring-boot-soap | src/main/java/com/hcentive/webservice/soap/FormEndpoint.java | Java | apache-2.0 | 1,458 |
/*
* Copyright 2015 Luca Capra <luca.capra@gmail.com>.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.createnet.compose.data;
/**
*
* @author Luca Capra <luca.capra@gmail.com>
*/
public class GeoPointRecord extends Record<String> {
public Point point;
protected String value;
public GeoPointRecord() {}
public GeoPointRecord(String point) {
this.point = new Point(point);
}
public GeoPointRecord(double latitude, double longitude) {
this.point = new Point(latitude, longitude);
}
@Override
public String getValue() {
return point.toString();
}
@Override
public void setValue(Object value) {
this.value = parseValue(value);
this.point = new Point(this.value);
}
@Override
public String parseValue(Object raw) {
return (String)raw;
}
@Override
public String getType() {
return "geo_point";
}
public class Point {
public double latitude;
public double longitude;
public Point(double latitude, double longitude) {
this.latitude = latitude;
this.longitude = longitude;
}
public Point(String val) {
String[] coords = val.split(",");
longitude = Double.parseDouble(coords[0].trim());
latitude = Double.parseDouble(coords[1].trim());
}
@Override
public String toString() {
return this.longitude + "," + this.latitude;
}
}
}
| muka/compose-java-client | src/main/java/org/createnet/compose/data/GeoPointRecord.java | Java | apache-2.0 | 2,062 |
// ----------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// ----------------------------------------------------------------------------
namespace Microsoft.WindowsAzure.MobileServices.Eventing
{
/// <summary>
/// Represents a mobile service event.
/// </summary>
public interface IMobileServiceEvent
{
/// <summary>
/// Gets the event name.
/// </summary>
string Name { get; }
}
}
| Azure/azure-mobile-apps-net-client | src/Microsoft.Azure.Mobile.Client/Eventing/IMobileServiceEvent.cs | C# | apache-2.0 | 526 |
/*
* Copyright 2016 John Grosh <john.a.grosh@gmail.com>.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.jagrosh.jmusicbot.commands;
import java.util.List;
import java.util.concurrent.TimeUnit;
import com.jagrosh.jdautilities.commandclient.CommandEvent;
import com.jagrosh.jdautilities.menu.pagination.PaginatorBuilder;
import com.jagrosh.jmusicbot.Bot;
import com.jagrosh.jmusicbot.audio.AudioHandler;
import com.jagrosh.jmusicbot.audio.QueuedTrack;
import com.jagrosh.jmusicbot.utils.FormatUtil;
import net.dv8tion.jda.core.Permission;
import net.dv8tion.jda.core.exceptions.PermissionException;
/**
*
* @author John Grosh <john.a.grosh@gmail.com>
*/
public class QueueCmd extends MusicCommand {
private final PaginatorBuilder builder;
public QueueCmd(Bot bot)
{
super(bot);
this.name = "queue";
this.help = "shows the current queue";
this.arguments = "[pagenum]";
this.aliases = new String[]{"list"};
this.bePlaying = true;
this.botPermissions = new Permission[]{Permission.MESSAGE_ADD_REACTION,Permission.MESSAGE_EMBED_LINKS};
builder = new PaginatorBuilder()
.setColumns(1)
.setFinalAction(m -> {try{m.clearReactions().queue();}catch(PermissionException e){}})
.setItemsPerPage(10)
.waitOnSinglePage(false)
.useNumberedItems(true)
.showPageNumbers(true)
.setEventWaiter(bot.getWaiter())
.setTimeout(1, TimeUnit.MINUTES)
;
}
@Override
public void doCommand(CommandEvent event) {
int pagenum = 1;
try{
pagenum = Integer.parseInt(event.getArgs());
}catch(NumberFormatException e){}
AudioHandler ah = (AudioHandler)event.getGuild().getAudioManager().getSendingHandler();
List<QueuedTrack> list = ah.getQueue().getList();
if(list.isEmpty())
{
event.replyWarning("There is no music in the queue!"
+(!ah.isMusicPlaying() ? "" : " Now playing:\n\n**"+ah.getPlayer().getPlayingTrack().getInfo().title+"**\n"+FormatUtil.embedformattedAudio(ah)));
return;
}
String[] songs = new String[list.size()];
long total = 0;
for(int i=0; i<list.size(); i++)
{
total += list.get(i).getTrack().getDuration();
songs[i] = list.get(i).toString();
}
long fintotal = total;
builder.setText((i1,i2) -> getQueueTitle(ah, event.getClient().getSuccess(), songs.length, fintotal))
.setItems(songs)
.setUsers(event.getAuthor())
.setColor(event.getSelfMember().getColor())
;
builder.build().paginate(event.getChannel(), pagenum);
}
private String getQueueTitle(AudioHandler ah, String success, int songslength, long total)
{
StringBuilder sb = new StringBuilder();
if(ah.getPlayer().getPlayingTrack()!=null)
sb.append("**").append(ah.getPlayer().getPlayingTrack().getInfo().title).append("**\n").append(FormatUtil.embedformattedAudio(ah)).append("\n\n");
return sb.append(success).append(" Current Queue | ").append(songslength).append(" entries | `").append(FormatUtil.formatTime(total)).append("` ").toString();
}
}
| Blankscar/NothingToSeeHere | src/main/java/com/jagrosh/jmusicbot/commands/QueueCmd.java | Java | apache-2.0 | 3,885 |
/*
* Copyright 2014-2019 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.opsworks.model;
import java.io.Serializable;
import javax.annotation.Generated;
/**
*
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/opsworks-2013-02-18/DeregisterEcsCluster" target="_top">AWS API
* Documentation</a>
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class DeregisterEcsClusterResult extends com.amazonaws.AmazonWebServiceResult<com.amazonaws.ResponseMetadata> implements Serializable, Cloneable {
/**
* Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
* redacted from this string using a placeholder value.
*
* @return A string representation of this object.
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{");
sb.append("}");
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (obj instanceof DeregisterEcsClusterResult == false)
return false;
DeregisterEcsClusterResult other = (DeregisterEcsClusterResult) obj;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
return hashCode;
}
@Override
public DeregisterEcsClusterResult clone() {
try {
return (DeregisterEcsClusterResult) super.clone();
} catch (CloneNotSupportedException e) {
throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e);
}
}
}
| jentfoo/aws-sdk-java | aws-java-sdk-opsworks/src/main/java/com/amazonaws/services/opsworks/model/DeregisterEcsClusterResult.java | Java | apache-2.0 | 2,373 |
#! /usr/bin/python
import sys
import os
import json
import grpc
import time
import subprocess
from google.oauth2 import service_account
import google.oauth2.credentials
import google.auth.transport.requests
import google.auth.transport.grpc
from google.firestore.v1beta1 import firestore_pb2
from google.firestore.v1beta1 import firestore_pb2_grpc
from google.firestore.v1beta1 import document_pb2
from google.firestore.v1beta1 import document_pb2_grpc
from google.firestore.v1beta1 import common_pb2
from google.firestore.v1beta1 import common_pb2_grpc
from google.firestore.v1beta1 import write_pb2
from google.firestore.v1beta1 import write_pb2_grpc
from google.protobuf import empty_pb2
from google.protobuf import timestamp_pb2
def first_message(database, write):
messages = [
firestore_pb2.WriteRequest(database = database, writes = [])
]
for msg in messages:
yield msg
def generate_messages(database, writes, stream_id, stream_token):
# writes can be an array and append to the messages, so it can write multiple Write
# here just write one as example
messages = [
firestore_pb2.WriteRequest(database=database, writes = []),
firestore_pb2.WriteRequest(database=database, writes = [writes], stream_id = stream_id, stream_token = stream_token)
]
for msg in messages:
yield msg
def main():
fl = os.path.dirname(os.path.abspath(__file__))
fn = os.path.join(fl, 'grpc.json')
with open(fn) as grpc_file:
item = json.load(grpc_file)
creds = item["grpc"]["Write"]["credentials"]
credentials = service_account.Credentials.from_service_account_file("{}".format(creds))
scoped_credentials = credentials.with_scopes(['https://www.googleapis.com/auth/datastore'])
http_request = google.auth.transport.requests.Request()
channel = google.auth.transport.grpc.secure_authorized_channel(scoped_credentials, http_request, 'firestore.googleapis.com:443')
stub = firestore_pb2_grpc.FirestoreStub(channel)
database = item["grpc"]["Write"]["database"]
name = item["grpc"]["Write"]["name"]
first_write = write_pb2.Write()
responses = stub.Write(first_message(database, first_write))
for response in responses:
print("Received message %s" % (response.stream_id))
print(response.stream_token)
value_ = document_pb2.Value(string_value = "foo_boo")
update = document_pb2.Document(name=name, fields={"foo":value_})
writes = write_pb2.Write(update_mask=common_pb2.DocumentMask(field_paths = ["foo"]), update=update)
r2 = stub.Write(generate_messages(database, writes, response.stream_id, response.stream_token))
for r in r2:
print(r.write_results)
if __name__ == "__main__":
main()
| GoogleCloudPlatform/grpc-gcp-python | firestore/examples/end2end/src/Write.py | Python | apache-2.0 | 2,967 |
using Lucene.Net.Support;
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Text;
using System.Threading;
namespace Lucene.Net.Util
{
/*
* 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.
*/
using Directory = Lucene.Net.Store.Directory;
/// <summary>
/// This class emulates the new Java 7 "Try-With-Resources" statement.
/// Remove once Lucene is on Java 7.
/// <para/>
/// @lucene.internal
/// </summary>
[ExceptionToClassNameConvention]
public sealed class IOUtils
{
/// <summary>
/// UTF-8 <see cref="Encoding"/> instance to prevent repeated
/// <see cref="Encoding.UTF8"/> lookups </summary>
[Obsolete("Use Encoding.UTF8 instead.")]
public static readonly Encoding CHARSET_UTF_8 = Encoding.UTF8;
/// <summary>
/// UTF-8 charset string.
/// <para/>Where possible, use <see cref="Encoding.UTF8"/> instead,
/// as using the <see cref="string"/> constant may slow things down. </summary>
/// <seealso cref="Encoding.UTF8"/>
public static readonly string UTF_8 = "UTF-8";
private IOUtils() // no instance
{
}
/// <summary>
/// <para>Disposes all given <c>IDisposable</c>s, suppressing all thrown exceptions. Some of the <c>IDisposable</c>s
/// may be <c>null</c>, they are ignored. After everything is disposed, method either throws <paramref name="priorException"/>,
/// if one is supplied, or the first of suppressed exceptions, or completes normally.</para>
/// <para>Sample usage:
/// <code>
/// IDisposable resource1 = null, resource2 = null, resource3 = null;
/// ExpectedException priorE = null;
/// try
/// {
/// resource1 = ...; resource2 = ...; resource3 = ...; // Acquisition may throw ExpectedException
/// ..do..stuff.. // May throw ExpectedException
/// }
/// catch (ExpectedException e)
/// {
/// priorE = e;
/// }
/// finally
/// {
/// IOUtils.CloseWhileHandlingException(priorE, resource1, resource2, resource3);
/// }
/// </code>
/// </para>
/// </summary>
/// <param name="priorException"> <c>null</c> or an exception that will be rethrown after method completion. </param>
/// <param name="objects"> Objects to call <see cref="IDisposable.Dispose()"/> on. </param>
[Obsolete("Use DisposeWhileHandlingException(Exception, params IDisposable[]) instead.")]
public static void CloseWhileHandlingException(Exception priorException, params IDisposable[] objects)
{
DisposeWhileHandlingException(priorException, objects);
}
/// <summary>
/// Disposes all given <see cref="IDisposable"/>s, suppressing all thrown exceptions. </summary>
/// <seealso cref="DisposeWhileHandlingException(Exception, IDisposable[])"/>
[Obsolete("Use DisposeWhileHandlingException(Exception, IEnumerable<IDisposable>) instead.")]
public static void CloseWhileHandlingException(Exception priorException, IEnumerable<IDisposable> objects)
{
DisposeWhileHandlingException(priorException, objects);
}
/// <summary>
/// Disposes all given <see cref="IDisposable"/>s. Some of the
/// <see cref="IDisposable"/>s may be <c>null</c>; they are
/// ignored. After everything is closed, the method either
/// throws the first exception it hit while closing, or
/// completes normally if there were no exceptions.
/// </summary>
/// <param name="objects">
/// Objects to call <see cref="IDisposable.Dispose()"/> on </param>
[Obsolete("Use Dispose(params IDisposable[]) instead.")]
public static void Close(params IDisposable[] objects)
{
Dispose(objects);
}
/// <summary>
/// Disposes all given <see cref="IDisposable"/>s. </summary>
/// <seealso cref="Dispose(IDisposable[])"/>
[Obsolete("Use Dispose(IEnumerable<IDisposable>) instead.")]
public static void Close(IEnumerable<IDisposable> objects)
{
Dispose(objects);
}
/// <summary>
/// Disposes all given <see cref="IDisposable"/>s, suppressing all thrown exceptions.
/// Some of the <see cref="IDisposable"/>s may be <c>null</c>, they are ignored.
/// </summary>
/// <param name="objects">
/// Objects to call <see cref="IDisposable.Dispose()"/> on </param>
[Obsolete("Use DisposeWhileHandlingException(params IDisposable[]) instead.")]
public static void CloseWhileHandlingException(params IDisposable[] objects)
{
DisposeWhileHandlingException(objects);
}
/// <summary>
/// Disposes all given <see cref="IDisposable"/>s, suppressing all thrown exceptions. </summary>
/// <seealso cref="DisposeWhileHandlingException(IEnumerable{IDisposable})"/>
/// <seealso cref="DisposeWhileHandlingException(IDisposable[])"/>
[Obsolete("Use DisposeWhileHandlingException(IEnumerable<IDisposable>) instead.")]
public static void CloseWhileHandlingException(IEnumerable<IDisposable> objects)
{
DisposeWhileHandlingException(objects);
}
// LUCENENET specific - added overloads starting with Dispose... instead of Close...
/// <summary>
/// <para>Disposes all given <c>IDisposable</c>s, suppressing all thrown exceptions. Some of the <c>IDisposable</c>s
/// may be <c>null</c>, they are ignored. After everything is disposed, method either throws <paramref name="priorException"/>,
/// if one is supplied, or the first of suppressed exceptions, or completes normally.</para>
/// <para>Sample usage:
/// <code>
/// IDisposable resource1 = null, resource2 = null, resource3 = null;
/// ExpectedException priorE = null;
/// try
/// {
/// resource1 = ...; resource2 = ...; resource3 = ...; // Acquisition may throw ExpectedException
/// ..do..stuff.. // May throw ExpectedException
/// }
/// catch (ExpectedException e)
/// {
/// priorE = e;
/// }
/// finally
/// {
/// IOUtils.DisposeWhileHandlingException(priorE, resource1, resource2, resource3);
/// }
/// </code>
/// </para>
/// </summary>
/// <param name="priorException"> <c>null</c> or an exception that will be rethrown after method completion. </param>
/// <param name="objects"> Objects to call <see cref="IDisposable.Dispose()"/> on. </param>
public static void DisposeWhileHandlingException(Exception priorException, params IDisposable[] objects)
{
Exception th = null;
foreach (IDisposable @object in objects)
{
try
{
if (@object != null)
{
@object.Dispose();
}
}
catch (Exception t)
{
AddSuppressed(priorException ?? th, t);
if (th == null)
{
th = t;
}
}
}
if (priorException != null)
{
throw priorException;
}
else
{
ReThrow(th);
}
}
/// <summary>
/// Disposes all given <see cref="IDisposable"/>s, suppressing all thrown exceptions. </summary>
/// <seealso cref="DisposeWhileHandlingException(Exception, IDisposable[])"/>
public static void DisposeWhileHandlingException(Exception priorException, IEnumerable<IDisposable> objects)
{
Exception th = null;
foreach (IDisposable @object in objects)
{
try
{
if (@object != null)
{
@object.Dispose();
}
}
catch (Exception t)
{
AddSuppressed(priorException ?? th, t);
if (th == null)
{
th = t;
}
}
}
if (priorException != null)
{
throw priorException;
}
else
{
ReThrow(th);
}
}
/// <summary>
/// Disposes all given <see cref="IDisposable"/>s. Some of the
/// <see cref="IDisposable"/>s may be <c>null</c>; they are
/// ignored. After everything is closed, the method either
/// throws the first exception it hit while closing, or
/// completes normally if there were no exceptions.
/// </summary>
/// <param name="objects">
/// Objects to call <see cref="IDisposable.Dispose()"/> on </param>
public static void Dispose(params IDisposable[] objects)
{
Exception th = null;
foreach (IDisposable @object in objects)
{
try
{
if (@object != null)
{
@object.Dispose();
}
}
catch (Exception t)
{
AddSuppressed(th, t);
if (th == null)
{
th = t;
}
}
}
ReThrow(th);
}
/// <summary>
/// Disposes all given <see cref="IDisposable"/>s. </summary>
/// <seealso cref="Dispose(IDisposable[])"/>
public static void Dispose(IEnumerable<IDisposable> objects)
{
Exception th = null;
foreach (IDisposable @object in objects)
{
try
{
if (@object != null)
{
@object.Dispose();
}
}
catch (Exception t)
{
AddSuppressed(th, t);
if (th == null)
{
th = t;
}
}
}
ReThrow(th);
}
/// <summary>
/// Disposes all given <see cref="IDisposable"/>s, suppressing all thrown exceptions.
/// Some of the <see cref="IDisposable"/>s may be <c>null</c>, they are ignored.
/// </summary>
/// <param name="objects">
/// Objects to call <see cref="IDisposable.Dispose()"/> on </param>
public static void DisposeWhileHandlingException(params IDisposable[] objects)
{
foreach (var o in objects)
{
try
{
if (o != null)
{
o.Dispose();
}
}
catch (Exception)
{
//eat it
}
}
}
/// <summary>
/// Disposes all given <see cref="IDisposable"/>s, suppressing all thrown exceptions. </summary>
/// <seealso cref="DisposeWhileHandlingException(IDisposable[])"/>
public static void DisposeWhileHandlingException(IEnumerable<IDisposable> objects)
{
foreach (IDisposable @object in objects)
{
try
{
if (@object != null)
{
@object.Dispose();
}
}
catch (Exception)
{
//eat it
}
}
}
/// <summary>
/// Since there's no C# equivalent of Java's Exception.AddSuppressed, we add the
/// suppressed exceptions to a data field via the
/// <see cref="Support.ExceptionExtensions.AddSuppressed(Exception, Exception)"/> method.
/// <para/>
/// The exceptions can be retrieved by calling <see cref="ExceptionExtensions.GetSuppressed(Exception)"/>
/// or <see cref="ExceptionExtensions.GetSuppressedAsList(Exception)"/>.
/// </summary>
/// <param name="exception"> this exception should get the suppressed one added </param>
/// <param name="suppressed"> the suppressed exception </param>
private static void AddSuppressed(Exception exception, Exception suppressed)
{
if (exception != null && suppressed != null)
{
exception.AddSuppressed(suppressed);
}
}
/// <summary>
/// Wrapping the given <see cref="Stream"/> in a reader using a <see cref="Encoding"/>.
/// Unlike Java's defaults this reader will throw an exception if your it detects
/// the read charset doesn't match the expected <see cref="Encoding"/>.
/// <para/>
/// Decoding readers are useful to load configuration files, stopword lists or synonym files
/// to detect character set problems. However, its not recommended to use as a common purpose
/// reader.
/// </summary>
/// <param name="stream"> The stream to wrap in a reader </param>
/// <param name="charSet"> The expected charset </param>
/// <returns> A wrapping reader </returns>
public static TextReader GetDecodingReader(Stream stream, Encoding charSet)
{
return new StreamReader(stream, charSet);
}
/// <summary>
/// Opens a <see cref="TextReader"/> for the given <see cref="FileInfo"/> using a <see cref="Encoding"/>.
/// Unlike Java's defaults this reader will throw an exception if your it detects
/// the read charset doesn't match the expected <see cref="Encoding"/>.
/// <para/>
/// Decoding readers are useful to load configuration files, stopword lists or synonym files
/// to detect character set problems. However, its not recommended to use as a common purpose
/// reader. </summary>
/// <param name="file"> The file to open a reader on </param>
/// <param name="charSet"> The expected charset </param>
/// <returns> A reader to read the given file </returns>
public static TextReader GetDecodingReader(FileInfo file, Encoding charSet)
{
FileStream stream = null;
bool success = false;
try
{
stream = file.OpenRead();
TextReader reader = GetDecodingReader(stream, charSet);
success = true;
return reader;
}
finally
{
if (!success)
{
IOUtils.Dispose(stream);
}
}
}
/// <summary>
/// Opens a <see cref="TextReader"/> for the given resource using a <see cref="Encoding"/>.
/// Unlike Java's defaults this reader will throw an exception if your it detects
/// the read charset doesn't match the expected <see cref="Encoding"/>.
/// <para/>
/// Decoding readers are useful to load configuration files, stopword lists or synonym files
/// to detect character set problems. However, its not recommended to use as a common purpose
/// reader. </summary>
/// <param name="clazz"> The class used to locate the resource </param>
/// <param name="resource"> The resource name to load </param>
/// <param name="charSet"> The expected charset </param>
/// <returns> A reader to read the given file </returns>
public static TextReader GetDecodingReader(Type clazz, string resource, Encoding charSet)
{
Stream stream = null;
bool success = false;
try
{
stream = clazz.GetTypeInfo().Assembly.FindAndGetManifestResourceStream(clazz, resource);
TextReader reader = GetDecodingReader(stream, charSet);
success = true;
return reader;
}
finally
{
if (!success)
{
IOUtils.Dispose(stream);
}
}
}
/// <summary>
/// Deletes all given files, suppressing all thrown <see cref="Exception"/>s.
/// <para/>
/// Note that the files should not be <c>null</c>.
/// </summary>
public static void DeleteFilesIgnoringExceptions(Directory dir, params string[] files)
{
foreach (string name in files)
{
try
{
dir.DeleteFile(name);
}
catch (Exception)
{
// ignore
}
}
}
/// <summary>
/// Copy one file's contents to another file. The target will be overwritten
/// if it exists. The source must exist.
/// </summary>
public static void Copy(FileInfo source, FileInfo target)
{
FileStream fis = null;
FileStream fos = null;
try
{
fis = source.OpenRead();
fos = target.OpenWrite();
byte[] buffer = new byte[1024 * 8];
int len;
while ((len = fis.Read(buffer, 0, buffer.Length)) > 0)
{
fos.Write(buffer, 0, len);
}
}
finally
{
Dispose(fis, fos);
}
}
/// <summary>
/// Simple utilty method that takes a previously caught
/// <see cref="Exception"/> and rethrows either
/// <see cref="IOException"/> or an unchecked exception. If the
/// argument is <c>null</c> then this method does nothing.
/// </summary>
public static void ReThrow(Exception th)
{
if (th != null)
{
if (th is System.IO.IOException)
{
throw th;
}
ReThrowUnchecked(th);
}
}
/// <summary>
/// Simple utilty method that takes a previously caught
/// <see cref="Exception"/> and rethrows it as an unchecked exception.
/// If the argument is <c>null</c> then this method does nothing.
/// </summary>
public static void ReThrowUnchecked(Exception th)
{
if (th != null)
{
throw th;
}
}
// LUCENENET specific: Fsync is pointless in .NET, since we are
// calling FileStream.Flush(true) before the stream is disposed
// which means we never need it at the point in Java where it is called.
// /// <summary>
// /// Ensure that any writes to the given file is written to the storage device that contains it. </summary>
// /// <param name="fileToSync"> The file to fsync </param>
// /// <param name="isDir"> If <c>true</c>, the given file is a directory (we open for read and ignore <see cref="IOException"/>s,
// /// because not all file systems and operating systems allow to fsync on a directory) </param>
// public static void Fsync(string fileToSync, bool isDir)
// {
// // Fsync does not appear to function properly for Windows and Linux platforms. In Lucene version
// // they catch this in IOException branch and return if the call is for the directory.
// // In Lucene.Net the exception is UnauthorizedAccessException and is not handled by
// // IOException block. No need to even attempt to fsync, just return if the call is for directory
// if (isDir)
// {
// return;
// }
// var retryCount = 1;
// while (true)
// {
// FileStream file = null;
// bool success = false;
// try
// {
// // If the file is a directory we have to open read-only, for regular files we must open r/w for the fsync to have an effect.
// // See http://blog.httrack.com/blog/2013/11/15/everything-you-always-wanted-to-know-about-fsync/
// file = new FileStream(fileToSync,
// FileMode.Open, // We shouldn't create a file when syncing.
// // Java version uses FileChannel which doesn't create the file if it doesn't already exist,
// // so there should be no reason for attempting to create it in Lucene.Net.
// FileAccess.Write,
// FileShare.ReadWrite);
// //FileSupport.Sync(file);
// file.Flush(true);
// success = true;
// }
//#pragma warning disable 168
// catch (IOException e)
//#pragma warning restore 168
// {
// if (retryCount == 5)
// {
// throw;
// }
//#if !NETSTANDARD1_6
// try
// {
//#endif
// // Pause 5 msec
// Thread.Sleep(5);
//#if !NETSTANDARD1_6
// }
// catch (ThreadInterruptedException ie)
// {
// var ex = new ThreadInterruptedException(ie.ToString(), ie);
// ex.AddSuppressed(e);
// throw ex;
// }
//#endif
// }
// finally
// {
// if (file != null)
// {
// file.Dispose();
// }
// }
// if (success)
// {
// return;
// }
// retryCount++;
// }
// }
}
} | laimis/lucenenet | src/Lucene.Net/Util/IOUtils.cs | C# | apache-2.0 | 24,051 |
// /*******************************************************************************
// * Copyright 2012-2018 Esri
// *
// * 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.
// ******************************************************************************/
using System;
using System.Collections.ObjectModel;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using Android.Content;
using Android.Runtime;
using Android.Util;
using Android.Views;
using Android.Widget;
using Esri.ArcGISRuntime.Mapping;
using Esri.ArcGISRuntime.Toolkit.Internal;
namespace Esri.ArcGISRuntime.Toolkit.UI.Controls
{
[Register("Esri.ArcGISRuntime.Toolkit.UI.Controls.LayerLegend")]
public partial class LayerLegend
{
private ListView _listView;
private Android.OS.Handler _uithread;
/// <summary>
/// Initializes a new instance of the <see cref="LayerLegend"/> class.
/// </summary>
/// <param name="context">The Context the view is running in, through which it can access resources, themes, etc.</param>
public LayerLegend(Context context)
: base(context ?? throw new ArgumentNullException(nameof(context)))
{
Initialize();
}
/// <summary>
/// Initializes a new instance of the <see cref="LayerLegend"/> class.
/// </summary>
/// <param name="context">The Context the view is running in, through which it can access resources, themes, etc.</param>
/// <param name="attr">The attributes of the AXML element declaring the view.</param>
public LayerLegend(Context context, IAttributeSet? attr)
: base(context ?? throw new ArgumentNullException(nameof(context)), attr)
{
Initialize();
}
[MemberNotNull(nameof(_listView), nameof(_uithread))]
private void Initialize()
{
_uithread = new Android.OS.Handler(Context!.MainLooper!);
_listView = new ListView(Context)
{
ClipToOutline = true,
Clickable = false,
ChoiceMode = ChoiceMode.None,
LayoutParameters = new LayoutParams(LayoutParams.WrapContent, LayoutParams.WrapContent),
ScrollingCacheEnabled = false,
PersistentDrawingCache = PersistentDrawingCaches.NoCache,
};
AddView(_listView);
}
private void Refresh()
{
if (_listView == null)
{
return;
}
if (LayerContent == null)
{
_listView.Adapter = null;
return;
}
if (LayerContent is ILoadable loadable)
{
if (loadable.LoadStatus != LoadStatus.Loaded)
{
loadable.Loaded += Layer_Loaded;
loadable.LoadAsync();
return;
}
}
var items = new ObservableCollection<LegendInfo>();
LoadRecursive(items, LayerContent, IncludeSublayers);
_listView.Adapter = new LayerLegendAdapter(Context, items);
_listView.SetHeightBasedOnChildren();
}
private void Layer_Loaded(object sender, System.EventArgs e)
{
if (sender is ILoadable loadable)
{
loadable.Loaded -= Layer_Loaded;
}
_uithread.Post(Refresh);
}
/// <inheritdoc />
protected override void OnMeasure(int widthMeasureSpec, int heightMeasureSpec)
{
base.OnMeasure(widthMeasureSpec, heightMeasureSpec);
// Initialize dimensions of root layout
MeasureChild(_listView, widthMeasureSpec, MeasureSpec.MakeMeasureSpec(MeasureSpec.GetSize(heightMeasureSpec), MeasureSpecMode.AtMost));
// Calculate the ideal width and height for the view
var desiredWidth = PaddingLeft + PaddingRight + _listView.MeasuredWidth;
var desiredHeight = PaddingTop + PaddingBottom + _listView.MeasuredHeight;
// Get the width and height of the view given any width and height constraints indicated by the width and height spec values
var width = ResolveSize(desiredWidth, widthMeasureSpec);
var height = ResolveSize(desiredHeight, heightMeasureSpec);
SetMeasuredDimension(width, height);
}
/// <inheritdoc />
protected override void OnLayout(bool changed, int l, int t, int r, int b)
{
// Forward layout call to the root layout
_listView.Layout(PaddingLeft, PaddingTop, _listView.MeasuredWidth + PaddingLeft, _listView.MeasuredHeight + PaddingBottom);
}
}
} | Esri/arcgis-toolkit-dotnet | src/Toolkit/Toolkit.Android/UI/Controls/LayerLegend/LayerLegend.Android.cs | C# | apache-2.0 | 5,339 |
package com.google.api.ads.adwords.jaxws.v201509.cm;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlType;
/**
*
* Represents a criterion belonging to a shared set.
*
*
* <p>Java class for SharedCriterion complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="SharedCriterion">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="sharedSetId" type="{http://www.w3.org/2001/XMLSchema}long" minOccurs="0"/>
* <element name="criterion" type="{https://adwords.google.com/api/adwords/cm/v201509}Criterion" minOccurs="0"/>
* <element name="negative" type="{http://www.w3.org/2001/XMLSchema}boolean" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "SharedCriterion", propOrder = {
"sharedSetId",
"criterion",
"negative"
})
public class SharedCriterion {
protected Long sharedSetId;
protected Criterion criterion;
protected Boolean negative;
/**
* Gets the value of the sharedSetId property.
*
* @return
* possible object is
* {@link Long }
*
*/
public Long getSharedSetId() {
return sharedSetId;
}
/**
* Sets the value of the sharedSetId property.
*
* @param value
* allowed object is
* {@link Long }
*
*/
public void setSharedSetId(Long value) {
this.sharedSetId = value;
}
/**
* Gets the value of the criterion property.
*
* @return
* possible object is
* {@link Criterion }
*
*/
public Criterion getCriterion() {
return criterion;
}
/**
* Sets the value of the criterion property.
*
* @param value
* allowed object is
* {@link Criterion }
*
*/
public void setCriterion(Criterion value) {
this.criterion = value;
}
/**
* Gets the value of the negative property.
*
* @return
* possible object is
* {@link Boolean }
*
*/
public Boolean isNegative() {
return negative;
}
/**
* Sets the value of the negative property.
*
* @param value
* allowed object is
* {@link Boolean }
*
*/
public void setNegative(Boolean value) {
this.negative = value;
}
}
| gawkermedia/googleads-java-lib | modules/adwords_appengine/src/main/java/com/google/api/ads/adwords/jaxws/v201509/cm/SharedCriterion.java | Java | apache-2.0 | 2,764 |
package de.choesel.blechwiki.model;
import com.j256.ormlite.field.DatabaseField;
import com.j256.ormlite.table.DatabaseTable;
import java.util.UUID;
/**
* Created by christian on 05.05.16.
*/
@DatabaseTable(tableName = "komponist")
public class Komponist {
@DatabaseField(generatedId = true)
private UUID id;
@DatabaseField(canBeNull = true, uniqueCombo = true)
private String name;
@DatabaseField(canBeNull = true)
private String kurzname;
@DatabaseField(canBeNull = true, uniqueCombo = true)
private Integer geboren;
@DatabaseField(canBeNull = true)
private Integer gestorben;
public UUID getId() {
return id;
}
public String getName() {
return name;
}
public String getKurzname() {
return kurzname;
}
public Integer getGeboren() {
return geboren;
}
public Integer getGestorben() {
return gestorben;
}
public void setId(UUID id) {
this.id = id;
}
public void setName(String name) {
this.name = name;
}
public void setKurzname(String kurzname) {
this.kurzname = kurzname;
}
public void setGeboren(Integer geboren) {
this.geboren = geboren;
}
public void setGestorben(Integer gestorben) {
this.gestorben = gestorben;
}
}
| ChristianHoesel/android-blechwiki | app/src/main/java/de/choesel/blechwiki/model/Komponist.java | Java | apache-2.0 | 1,341 |
package server
import (
"fmt"
"math/big"
"net/http"
"strconv"
"time"
"github.com/san-lab/banketh-quorum/banketh/bots"
"github.com/san-lab/banketh-quorum/banketh/cryptobank"
"github.com/san-lab/banketh-quorum/banketh/data"
"github.com/san-lab/banketh-quorum/lib/bank/banktypes"
"github.com/san-lab/banketh-quorum/lib/db"
"github.com/san-lab/banketh-quorum/lib/ethapi"
)
func HandleBackoffice(w http.ResponseWriter, req *http.Request) {
if !logged(w, req) {
reload(w, req, "/")
return
}
req.ParseForm()
whatToShowA, ok := req.Form["whattoshow"]
if !ok || whatToShowA[0] == "Cashins" {
HandleCashins(w, req)
return
} else if whatToShowA[0] == "Cashouts" {
HandleCashouts(w, req)
return
} else if whatToShowA[0] == "PaymentTerminations" {
HandlePaymentTerminations(w, req)
return
}
showError(w, req, "Navigation error")
}
func HandleCashins(w http.ResponseWriter, req *http.Request) {
cashins, err := db.ReadTable(data.DBNAME, data.DBTABLECASHINS, &data.CashinT{}, "", "Time desc")
if err != nil {
showErrorf(w, req, "Unable to read cashin transactions table [%v]", err)
return
}
passdata := map[string]interface{}{
"Cashins": cashins,
"Currency": cryptobank.CURRENCY,
}
placeHeader(w, req)
templates.ExecuteTemplate(w, "cashins.html", passdata)
}
func HandleCashouts(w http.ResponseWriter, req *http.Request) {
cashouts, err := db.ReadTable(data.DBNAME, data.DBTABLECASHOUTS, &data.CashoutT{}, "", "Time desc")
if err != nil {
showErrorf(w, req, "Unable to read cashout transactions table [%v]", err)
return
}
passdata := map[string]interface{}{
"Cashouts": cashouts,
"Currency": cryptobank.CURRENCY,
}
placeHeader(w, req)
templates.ExecuteTemplate(w, "cashouts.html", passdata)
}
func HandlePaymentTerminations(w http.ResponseWriter, req *http.Request) {
paymentTerminations, err := db.ReadTable(data.DBNAME, data.DBTABLEPAYMENTTERMINATIONS, &data.PaymentTerminationT{}, "", "Time desc")
if err != nil {
showErrorf(w, req, "Unable to read payment terminations table [%v]", err)
return
}
passdata := map[string]interface{}{
"PaymentTerminations": paymentTerminations,
"Currency": cryptobank.CURRENCY,
}
placeHeader(w, req)
templates.ExecuteTemplate(w, "paymentterminations.html", passdata)
}
func HandleManualAddFunds(w http.ResponseWriter, req *http.Request) {
if !logged(w, req) {
reload(w, req, "/")
return
}
req.ParseForm()
bankaccountA, ok := req.Form["bankaccount"]
if !ok {
showError(w, req, "Form error")
return
}
banktridA, ok := req.Form["banktrid"]
if !ok {
showError(w, req, "Form error")
return
}
amountA, ok := req.Form["amount"]
if !ok {
showError(w, req, "Form error")
return
}
amount, err := strconv.ParseFloat(amountA[0], 64)
if err != nil {
pushAlertf(w, req, ALERT_DANGER, "Wrong amount argument %v [%v]", amountA[0], err)
reload(w, req, "/backoffice")
return
}
messageA, ok := req.Form["message"]
if !ok {
showError(w, req, "Form error")
return
}
bankethaccountA, ok := req.Form["bankethaccount"]
if !ok {
showError(w, req, "Form error")
return
}
bankethaccount, err := strconv.ParseUint(bankethaccountA[0], 0, 64)
if err != nil {
pushAlertf(w, req, ALERT_DANGER, "Wrong banketh account %v [%v]", bankethaccountA[0], err)
reload(w, req, "/backoffice")
return
}
manyaccounts, err := cryptobank.Many_accounts(ethclient)
if int64(bankethaccount) >= manyaccounts {
pushAlertf(w, req, ALERT_DANGER, "Account %v does not exist in banketh", bankethaccountA[0])
reload(w, req, "/backoffice")
return
}
account, err := cryptobank.Read_account(ethclient, bankethaccount)
if err != nil {
showErrorf(w, req, "Error reading account %v from ethereum node [%v]", bankethaccount, err)
return
}
bankethamount, _ := big.NewFloat(0).Mul(big.NewFloat(amount), big.NewFloat(cryptobank.PRECISION)).Int(nil)
txHash, err := cryptobank.Add_funds(ethclient, int64(bankethaccount), bankethamount)
if err != nil {
pushAlertf(w, req, ALERT_DANGER, "Add_funds method call failed! [%v]", err)
reload(w, req, "/backoffice")
return
}
newT := data.CashinT{
BankTrID: banktridA[0],
Time: db.MyTime(time.Now()),
BankAccount: bankaccountA[0],
BankAmount: amount,
Message: messageA[0],
ToAddress: account.Owner,
ToAccount: int64(bankethaccount),
BankethAmount: big.NewInt(0).Set(bankethamount),
AddFundsOrSubmitPaymentHash: txHash,
ReturnTrID: "",
ReturnMessage: "",
Status: data.CASHIN_STATUS_MANUALLY_FINISHED,
}
err = db.WriteEntry(data.DBNAME, data.DBTABLECASHINS, newT)
if err != nil {
errMsg := fmt.Sprintf("Sent an addFunds call (hash %v) but could not write it to DB! [%v]", err)
pushAlert(w, req, ALERT_DANGER, errMsg)
db.RegisterEvent(data.DBNAME, data.DBTABLEEVENTS, db.EVENT_MANUAL_INTERVENTION_NEEDED,
errMsg+fmt.Sprintf(" - Need manual intervention, we should record the transaction in the DB; projected transaction was %v", newT))
reload(w, req, "/backoffice")
return
}
}
func HandleManualAddTransfer(w http.ResponseWriter, req *http.Request) {
if !logged(w, req) {
reload(w, req, "/")
return
}
req.ParseForm()
banktridA, ok := req.Form["banktrid"]
if !ok {
showError(w, req, "Form error")
return
}
bankaccountA, ok := req.Form["bankaccount"]
if !ok {
showError(w, req, "Form error")
return
}
amountA, ok := req.Form["amount"]
if !ok {
showError(w, req, "Form error")
return
}
amount, err := strconv.ParseFloat(amountA[0], 64)
if err != nil {
pushAlertf(w, req, ALERT_DANGER, "Wrong amount argument %v [%v]", amountA[0], err)
reload(w, req, "/backoffice")
return
}
typeA, ok := req.Form["type"]
if !ok {
showError(w, req, "Form error")
return
}
messageA, ok := req.Form["message"]
if !ok {
showError(w, req, "Form error")
return
}
newTransfer := banktypes.BankTransferT{
TransferID: banktridA[0],
Time: db.MyTime(time.Now()),
Account: bankaccountA[0],
Amount: amount,
Type: typeA[0],
Message: messageA[0],
}
d, err := db.ConnectDB(data.DBNAME)
if err != nil {
pushAlertf(w, req, ALERT_DANGER, "Error connecting to the database [%v]", err)
reload(w, req, "/backoffice")
return
}
not_ok := bots.Process_inbound_transfer(d, &newTransfer)
if not_ok {
pushAlertf(w, req, ALERT_DANGER, "Error processing manual inbound transfer - pls check the console log")
reload(w, req, "/backoffice")
return
}
}
func HandleManualRemoveFunds(w http.ResponseWriter, req *http.Request) {
if !logged(w, req) {
reload(w, req, "/")
return
}
req.ParseForm()
var redeemFundsHash ethapi.Hash
var err error
redeemFundsHashA, ok := req.Form["redeemfundshash"]
if ok && redeemFundsHashA[0] != "" {
redeemFundsHash, err = ethapi.String_to_hash(redeemFundsHashA[0])
if err != nil {
pushAlertf(w, req, ALERT_DANGER, "Bad hash %v [%v]", redeemFundsHashA[0], err)
reload(w, req, "/backoffice")
return
}
}
bankethaccountA, ok := req.Form["bankethaccount"]
if !ok {
showError(w, req, "Form error")
return
}
bankethaccount, err := strconv.ParseUint(bankethaccountA[0], 0, 64)
if err != nil {
pushAlertf(w, req, ALERT_DANGER, "Wrong banketh account %v [%v]", bankethaccountA[0], err)
reload(w, req, "/backoffice")
return
}
manyaccounts, err := cryptobank.Many_accounts(ethclient)
if int64(bankethaccount) >= manyaccounts {
pushAlertf(w, req, ALERT_DANGER, "Account %v does not exist in banketh", bankethaccountA[0])
reload(w, req, "/backoffice")
return
}
account, err := cryptobank.Read_account(ethclient, bankethaccount)
if err != nil {
showErrorf(w, req, "Error reading account %v from ethereum node [%v]", bankethaccount, err)
return
}
amountA, ok := req.Form["amount"]
if !ok {
showError(w, req, "Form error")
return
}
amount, err := strconv.ParseFloat(amountA[0], 64)
if err != nil {
pushAlertf(w, req, ALERT_DANGER, "Wrong amount argument %v [%v]", amountA[0], err)
reload(w, req, "/backoffice")
return
}
bankethamount, _ := big.NewFloat(0).Mul(big.NewFloat(amount), big.NewFloat(cryptobank.PRECISION)).Int(nil)
redemptionModeA, ok := req.Form["redemptionmode"]
if !ok {
showError(w, req, "Form error")
return
}
redemptionMode, err := strconv.ParseUint(redemptionModeA[0], 0, 64)
if err != nil {
pushAlertf(w, req, ALERT_DANGER, "Wrong redemption mode %v [%v]", redemptionModeA[0], err)
reload(w, req, "/backoffice")
return
}
routingInfoA, given := req.Form["routinginfo"]
if given {
if len(routingInfoA[0]) > 32 {
pushAlertf(w, req, ALERT_DANGER, "Wrong routing info (%v)", routingInfoA[0])
reload(w, req, "/backoffice")
return
}
}
var errorCode int64
errorCodeA, given := req.Form["errorcode"]
if given {
errorCode, err = strconv.ParseInt(errorCodeA[0], 0, 64)
if err != nil {
pushAlertf(w, req, ALERT_DANGER, "Wrong redemption error code (%v)", errorCodeA[0])
reload(w, req, "/backoffice")
return
}
}
/*
redemptionCodeSent := big.NewInt(0)
redemptionCodeSentA, given := req.Form["redemptioncodesent"]
if given {
redemptionCodeSent, ok = redemptionCodeSent.SetString(redemptionCodeSentA[0], 0)
if !ok {
pushAlertf(w, req, ALERT_DANGER, "Wrong redemption code (%v)", redemptionCodeSentA[0])
reload(w, req, "/backoffice")
return
}
}
*/
bankaccountA, _ := req.Form["bankaccount"]
banktridA, _ := req.Form["banktrid"]
messageA, _ := req.Form["message"]
txHash, err := cryptobank.Remove_funds(ethclient, int64(bankethaccount), bankethamount, redeemFundsHash, errorCode)
/*
txHash, err := cryptobank.Remove_funds(ethclient, int64(bankethaccount), bankethamount, redemptionCodeSent)
*/
if err != nil {
pushAlertf(w, req, ALERT_DANGER, "Remove_funds method call failed! [%v]", err)
reload(w, req, "/backoffice")
return
}
newT := data.CashoutT{
RedeemFundsHash: redeemFundsHash,
Time: db.MyTime(time.Now()),
FromAccount: int64(bankethaccount),
FromAddress: account.Owner,
BankethAmount: big.NewInt(0).Set(bankethamount),
RedemptionMode: redemptionMode,
RoutingInfo: routingInfoA[0],
ErrorCode: errorCode,
RemoveFundsHash: txHash,
// MakeTransferHash: // Not neccessary, since this is a known cashout
BankAccount: bankaccountA[0],
BankAmount: amount,
BankTrID: banktridA[0],
Message: messageA[0],
Status: data.CASHOUT_STATUS_MANUALLY_FINISHED,
}
err = db.WriteEntry(data.DBNAME, data.DBTABLECASHOUTS, newT)
if err != nil {
errMsg := fmt.Sprintf("Sent an remove_funds call (hash %v) but could not write it to DB! [%v]", err)
pushAlert(w, req, ALERT_DANGER, errMsg)
db.RegisterEvent(data.DBNAME, data.DBTABLEEVENTS, db.EVENT_MANUAL_INTERVENTION_NEEDED,
errMsg+fmt.Sprintf(" - Need manual intervention, we should record the transaction in the DB; projected transaction was %v", newT))
reload(w, req, "/backoffice")
return
}
}
| hesusruiz/fabricaudit | requires/san-lab/banketh-quorum/banketh/server/handleBackoffice.go | GO | apache-2.0 | 11,104 |
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/first_run/first_run.h"
#include "base/command_line.h"
#include "base/file_util.h"
#include "base/files/file_path.h"
#include "base/path_service.h"
#include "base/process_util.h"
#include "base/string_util.h"
#include "base/strings/string_piece.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/first_run/first_run_internal.h"
#include "chrome/browser/importer/importer_host.h"
#include "chrome/browser/process_singleton.h"
#include "chrome/browser/shell_integration.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/installer/util/google_update_settings.h"
#include "chrome/installer/util/master_preferences.h"
#include "content/public/common/result_codes.h"
#include "googleurl/src/gurl.h"
#include "ui/base/ui_base_switches.h"
namespace first_run {
namespace internal {
bool IsOrganicFirstRun() {
// We treat all installs as organic.
return true;
}
// TODO(port): This is just a piece of the silent import functionality from
// ImportSettings for Windows. It would be nice to get the rest of it ported.
bool ImportBookmarks(const base::FilePath& import_bookmarks_path) {
const CommandLine& cmdline = *CommandLine::ForCurrentProcess();
CommandLine import_cmd(cmdline.GetProgram());
// Propagate user data directory switch.
if (cmdline.HasSwitch(switches::kUserDataDir)) {
import_cmd.AppendSwitchPath(switches::kUserDataDir,
cmdline.GetSwitchValuePath(switches::kUserDataDir));
}
// Since ImportSettings is called before the local state is stored on disk
// we pass the language as an argument. GetApplicationLocale checks the
// current command line as fallback.
import_cmd.AppendSwitchASCII(switches::kLang,
g_browser_process->GetApplicationLocale());
import_cmd.CommandLine::AppendSwitchPath(switches::kImportFromFile,
import_bookmarks_path);
// The importer doesn't need to do any background networking tasks so disable
// them.
import_cmd.CommandLine::AppendSwitch(switches::kDisableBackgroundNetworking);
// Time to launch the process that is going to do the import. We'll wait
// for the process to return.
base::LaunchOptions options;
options.wait = true;
return base::LaunchProcess(import_cmd, options, NULL);
}
base::FilePath MasterPrefsPath() {
// The standard location of the master prefs is next to the chrome binary.
base::FilePath master_prefs;
if (!PathService::Get(base::DIR_EXE, &master_prefs))
return base::FilePath();
return master_prefs.AppendASCII(installer::kDefaultMasterPrefs);
}
} // namespace internal
} // namespace first_run
| plxaye/chromium | src/chrome/browser/first_run/first_run_linux.cc | C++ | apache-2.0 | 2,876 |
package request
import (
"bytes"
"encoding/json"
"io/ioutil"
)
// A Handlers provides a collection of handlers for various stages of handling requests.
type Handlers struct {
RequestHandler func(*Request, *interface{}) error
ResponseHandler func(*Request, *interface{}) error
}
// RequestHandler encodes a structure into a JSON string
func RequestHandler(request *Request, input *interface{}) error {
jsonstr, err := json.Marshal(&input)
request.HTTPRequest.Body = ioutil.NopCloser(bytes.NewBuffer(jsonstr))
return err
}
// ResponseHandler decodes a JSON string into a structure.
func ResponseHandler(request *Request, output *interface{}) error {
return json.Unmarshal(request.Body, &output)
}
// ListResponseHandler extracts results from a JSON envelope and decodes them into a structure.
// https://docs.atlas.mongodb.com/api/#lists
func ListResponseHandler(request *Request, output *interface{}) error {
var objmap map[string]*json.RawMessage
err := json.Unmarshal(request.Body, &objmap)
if err != nil {
return err
}
return json.Unmarshal(*objmap["results"], &output)
}
| visit1985/atlasgo | common/request/handlers.go | GO | apache-2.0 | 1,144 |
package org.judal.examples.java.model.array;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.GregorianCalendar;
import javax.jdo.JDOException;
import org.judal.storage.DataSource;
import org.judal.storage.EngineFactory;
import org.judal.storage.java.ArrayRecord;
import org.judal.storage.relational.RelationalDataSource;
/**
* Extend ArrayRecord in order to create model classes manageable by JUDAL.
* Add your getters and setters for database fields.
*/
public class Student extends ArrayRecord {
private static final long serialVersionUID = 1L;
public static final String TABLE_NAME = "student";
public Student() throws JDOException {
this(EngineFactory.getDefaultRelationalDataSource());
}
public Student(RelationalDataSource dataSource) throws JDOException {
super(dataSource, TABLE_NAME);
}
@Override
public void store(DataSource dts) throws JDOException {
// Generate the student Id. from a sequence if it is not provided
if (isNull("id_student"))
setId ((int) dts.getSequence("seq_student").nextValue());
super.store(dts);
}
public int getId() {
return getInt("id_student");
}
public void setId(final int id) {
put("id_student", id);
}
public String getFirstName() {
return getString("first_name");
}
public void setFirstName(final String firstName) {
put("first_name", firstName);
}
public String getLastName() {
return getString("last_name");
}
public void setLastName(final String lastName) {
put("last_name", lastName);
}
public Calendar getDateOfBirth() {
return getCalendar("date_of_birth");
}
public void setDateOfBirth(final Calendar dob) {
put("date_of_birth", dob);
}
public void setDateOfBirth(final String yyyyMMdd) throws ParseException {
SimpleDateFormat dobFormat = new SimpleDateFormat("yyyy-MM-dd");
Calendar cal = new GregorianCalendar();
cal.setTime(dobFormat.parse(yyyyMMdd));
setDateOfBirth(cal);
}
public byte[] getPhoto() {
return getBytes("photo");
}
public void setPhoto(final byte[] photoData) {
put("photo", photoData);
}
}
| sergiomt/judal | aexample/src/main/java/org/judal/examples/java/model/array/Student.java | Java | apache-2.0 | 2,209 |
using IntelliTect.Coalesce.CodeGeneration.Generation;
using IntelliTect.Coalesce.Tests.Util;
using IntelliTect.Coalesce.Validation;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.Text;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xunit;
namespace IntelliTect.Coalesce.CodeGeneration.Tests
{
public class CodeGenTestBase
{
protected GenerationExecutor BuildExecutor()
{
return new GenerationExecutor(
new Configuration.CoalesceConfiguration
{
WebProject = new Configuration.ProjectConfiguration
{
RootNamespace = "MyProject"
}
},
Microsoft.Extensions.Logging.LogLevel.Information
);
}
protected async Task AssertSuiteOutputCompiles(IRootGenerator suite)
{
var project = new DirectoryInfo(Directory.GetCurrentDirectory())
.FindFileInAncestorDirectory("IntelliTect.Coalesce.CodeGeneration.Tests.csproj")
.Directory;
var suiteName = suite.GetType().Name;
suite = suite
.WithOutputPath(Path.Combine(project.FullName, "out", suiteName));
var validationResult = ValidateContext.Validate(suite.Model);
Assert.Empty(validationResult.Where(r => r.IsError));
await suite.GenerateAsync();
var generators = suite
.GetGeneratorsFlattened()
.OfType<IFileGenerator>()
.Where(g => g.EffectiveOutputPath.EndsWith(".cs"))
.ToList();
var tasks = generators.Select(gen => (Generator: gen, Output: gen.GetOutputAsync()));
await Task.WhenAll(tasks.Select(t => t.Output ));
var dtoFiles = tasks
.Select((task) => CSharpSyntaxTree.ParseText(
SourceText.From(new StreamReader(task.Output.Result).ReadToEnd()),
path: task.Generator.EffectiveOutputPath
))
.ToArray();
var comp = ReflectionRepositoryFactory.GetCompilation(dtoFiles);
AssertSuccess(comp);
}
protected void AssertSuccess(CSharpCompilation comp)
{
var errors = comp
.GetDiagnostics()
.Where(d => d.Severity >= Microsoft.CodeAnalysis.DiagnosticSeverity.Error);
Assert.All(errors, error =>
{
var loc = error.Location;
Assert.False(true, "\"" + error.ToString() +
$"\" near:```\n" +
loc.SourceTree.ToString().Substring(loc.SourceSpan.Start, loc.SourceSpan.Length) +
"\n```"
);
});
}
}
}
| IntelliTect/Coalesce | src/IntelliTect.Coalesce.CodeGeneration.Tests/CodeGenTestBase.cs | C# | apache-2.0 | 2,936 |
using System.ComponentModel;
using AcceptFramework.Domain.Evaluation;
namespace AcceptFramework.Repository.Evaluation
{
[DataObject]
public class EvaluationParagraphScoringRepository : RepositoryBase<EvaluationParagraphScoring>
{
}
}
| accept-project/accept-api | AcceptFramework/Repository/Evaluation/EvaluationParagraphScoringRepository.cs | C# | apache-2.0 | 254 |
import sys
sys.path.append("helper")
import web
from helper import session
web.config.debug = False
urls = (
"/", "controller.start.index",
"/1", "controller.start.one",
"/2", "controller.start.two",
)
app = web.application(urls, globals())
sessions = session.Sessions()
if __name__ == "__main__":
app.run()
| 0x00/web.py-jinja2-pyjade-bootstrap | app.py | Python | apache-2.0 | 331 |
/*
* Copyright 2010-2016 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.
*/
#include <aws/core/client/AWSError.h>
#include <aws/redshift/RedshiftErrorMarshaller.h>
#include <aws/redshift/RedshiftErrors.h>
using namespace Aws::Client;
using namespace Aws::Redshift;
AWSError<CoreErrors> RedshiftErrorMarshaller::FindErrorByName(const char* errorName) const
{
AWSError<CoreErrors> error = RedshiftErrorMapper::GetErrorForName(errorName);
if(error.GetErrorType() != CoreErrors::UNKNOWN)
{
return error;
}
return AWSErrorMarshaller::FindErrorByName(errorName);
} | ambasta/aws-sdk-cpp | aws-cpp-sdk-redshift/source/RedshiftErrorMarshaller.cpp | C++ | apache-2.0 | 1,074 |
package org.spincast.core.routing;
import java.util.List;
import org.spincast.core.exchange.RequestContext;
/**
* The result of the router, when asked to find matches for
* a request.
*/
public interface RoutingResult<R extends RequestContext<?>> {
/**
* The handlers matching the route (a main handler + filters, if any),
* in order they have to be called.
*/
public List<RouteHandlerMatch<R>> getRouteHandlerMatches();
/**
* The main route handler and its information, from the routing result.
*/
public RouteHandlerMatch<R> getMainRouteHandlerMatch();
}
| spincast/spincast-framework | spincast-core-parent/spincast-core/src/main/java/org/spincast/core/routing/RoutingResult.java | Java | apache-2.0 | 609 |
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package king.flow.common;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import java.io.File;
import java.nio.charset.Charset;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import king.flow.action.business.ShowClockAction;
import king.flow.data.TLSResult;
import king.flow.view.Action;
import king.flow.view.Action.CleanAction;
import king.flow.view.Action.EjectCardAction;
import king.flow.view.Action.WithdrawCardAction;
import king.flow.view.Action.EncryptKeyboardAction;
import king.flow.view.Action.HideAction;
import king.flow.view.Action.InsertICardAction;
import king.flow.view.Action.LimitInputAction;
import king.flow.view.Action.MoveCursorAction;
import king.flow.view.Action.NumericPadAction;
import king.flow.view.Action.OpenBrowserAction;
import king.flow.view.Action.PlayMediaAction;
import king.flow.view.Action.PlayVideoAction;
import king.flow.view.Action.PrintPassbookAction;
import king.flow.view.Action.RunCommandAction;
import king.flow.view.Action.RwFingerPrintAction;
import king.flow.view.Action.SetFontAction;
import king.flow.view.Action.SetPrinterAction;
import king.flow.view.Action.ShowComboBoxAction;
import king.flow.view.Action.ShowGridAction;
import king.flow.view.Action.ShowTableAction;
import king.flow.view.Action.Swipe2In1CardAction;
import king.flow.view.Action.SwipeCardAction;
import king.flow.view.Action.UploadFileAction;
import king.flow.view.Action.UseTipAction;
import king.flow.view.Action.VirtualKeyboardAction;
import king.flow.view.Action.WriteICardAction;
import king.flow.view.ComponentEnum;
import king.flow.view.DefinedAction;
import king.flow.view.DeviceEnum;
import king.flow.view.JumpAction;
import king.flow.view.MsgSendAction;
/**
*
* @author LiuJin
*/
public class CommonConstants {
public static final String APP_STARTUP_ENTRY = "bank.exe";
public static final Charset UTF8 = Charset.forName("UTF-8");
static final File[] SYS_ROOTS = File.listRoots();
public static final int DRIVER_COUNT = SYS_ROOTS.length;
public static final String XML_NODE_PREFIX = "N_";
public static final String REVERT = "re_";
public static final String BID = "bid";
public static final String UID_PREFIX = "<" + TLSResult.UID + ">";
public static final String UID_AFFIX = "</" + TLSResult.UID + ">";
public static final String DEFAULT_DATE_FORMATE = "yyyy-MM-dd";
public static final String VALID_BANK_CARD = "validBankCard";
public static final String BALANCED_PAY_MAC = "balancedPayMAC";
public static final String CANCEL_ENCRYPTION_KEYBOARD = "[CANCEL]";
public static final String QUIT_ENCRYPTION_KEYBOARD = "[QUIT]";
public static final String INVALID_ENCRYPTION_LENGTH = "encryption.keyboard.type.length.prompt";
public static final String TIMEOUT_ENCRYPTION_TYPE = "encryption.keyboard.type.timeout.prompt";
public static final String ERROR_ENCRYPTION_TYPE = "encryption.keyboard.type.fail.prompt";
public static final int CONTAINER_KEY = Integer.MAX_VALUE;
public static final int NORMAL = 0;
public static final int ABNORMAL = 1;
public static final int BALANCE = 12345;
public static final int RESTART_SIGNAL = 1;
public static final int DOWNLOAD_KEY_SIGNAL = 1;
public static final int UPDATE_SIGNAL = 1;
public static final int WATCHDOG_CHECK_INTERVAL = 5;
public static final String VERSION;
public static final long DEBUG_MODE_PROGRESS_TIME = TimeUnit.SECONDS.toMillis(3);
public static final long RUN_MODE_PROGRESS_TIME = TimeUnit.SECONDS.toMillis(1);
// public static final String VERSION = Paths.get(".").toAbsolutePath().normalize().toString();
static {
String workingPath = System.getProperty("user.dir");
final int lastIndexOf = workingPath.lastIndexOf('_');
if (lastIndexOf != -1 && lastIndexOf < workingPath.length() - 1) {
VERSION = workingPath.substring(lastIndexOf + 1);
} else {
VERSION = "Unknown";
}
}
/* JMX configuration */
private static String getJmxRmiUrl(int port) {
return "service:jmx:rmi:///jndi/rmi://localhost:" + port + "/jmxrmi";
}
public static final int APP_JMX_RMI_PORT = 9998;
public static final String APP_JMX_RMI_URL = getJmxRmiUrl(APP_JMX_RMI_PORT);
public static final int WATCHDOG_JMX_RMI_PORT = 9999;
public static final String WATCHDOG_JMX_RMI_URL = getJmxRmiUrl(WATCHDOG_JMX_RMI_PORT);
/* system variable pattern */
public static final String SYSTEM_VAR_PATTERN = "\\$\\{(_?\\p{Alpha}+_\\p{Alpha}+)+\\}";
public static final String TEXT_MINGLED_SYSTEM_VAR_PATTERN = ".*" + SYSTEM_VAR_PATTERN + ".*";
public static final String TERMINAL_ID_SYS_VAR = "TERMINAL_ID";
/* swing default config */
public static final int DEFAULT_TABLE_ROW_COUNT = 15;
public static final int TABLE_ROW_HEIGHT = 25;
public static final int DEFAULT_VIDEO_REPLAY_INTERVAL_SECOND = 20;
/* packet header ID */
public static final int GENERAL_MSG_CODE = 0; //common message
public static final int REGISTRY_MSG_CODE = 1; //terminal registration message
public static final int KEY_DOWNLOAD_MSG_CODE = 2; //download secret key message
public static final int MANAGER_MSG_CODE = 100; //management message
/*MAX_MESSAGES_PER_READ refers to DefaultChannelConfig, AdaptiveRecvByteBufAllocator, FixedRecvByteBufAllocator */
public static final int MAX_MESSAGES_PER_READ = 64; //how many read actions in one message conversation
public static final int MIN_RECEIVED_BUFFER_SIZE = 1024; //1024 bytes
public static final int RECEIVED_BUFFER_SIZE = 32 * 1024; //32k bytes
public static final int MAX_RECEIVED_BUFFER_SIZE = 64 * 1024; //64k bytes
/* keyboard cipher key */
public static final String WORK_SECRET_KEY = "workSecretKey";
public static final String MA_KEY = "maKey";
public static final String MASTER_KEY = "masterKey";
/* packet result flag */
public static final int SUCCESSFUL_MSG_CODE = 0;
/* xml jaxb context */
public static final String NET_CONF_PACKAGE_CONTEXT = "king.flow.net";
public static final String TLS_PACKAGE_CONTEXT = "king.flow.data";
public static final String UI_CONF_PACKAGE_CONTEXT = "king.flow.view";
public static final String KING_FLOW_BACKGROUND = "king.flow.background";
public static final String KING_FLOW_PROGRESS = "king.flow.progress";
public static final String TEXT_TYPE_TOOL_CONFIG = "chinese.text.type.config";
public static final String COMBOBOX_ITEMS_PROPERTY_PATTERN = "([^,/]*/[^,/]*,)*+([^,/]*/[^,/]*){1}+";
public static final String ADVANCED_TABLE_TOTAL_PAGES = "total";
public static final String ADVANCED_TABLE_VALUE = "value";
public static final String ADVANCED_TABLE_CURRENT_PAGE = "current";
/* card-reading state */
public static final int INVALID_CARD_STATE = -1;
public static final int MAGNET_CARD_STATE = 2;
public static final int IC_CARD_STATE = 3;
/* union-pay transaction type */
public static final String UNION_PAY_REGISTRATION = "1";
public static final String UNION_PAY_TRANSACTION = "3";
public static final String UNION_PAY_TRANSACTION_BALANCE = "4";
/* card affiliation type */
public static final String CARD_AFFILIATION_INTERNAL = "1";
public static final String CARD_AFFILIATION_EXTERNAL = "2";
/* supported driver types */
static final ImmutableSet<DeviceEnum> SUPPORTED_DEVICES = new ImmutableSet.Builder<DeviceEnum>()
.add(DeviceEnum.IC_CARD)
.add(DeviceEnum.CASH_SAVER)
.add(DeviceEnum.GZ_CARD)
.add(DeviceEnum.HIS_CARD)
.add(DeviceEnum.KEYBOARD)
.add(DeviceEnum.MAGNET_CARD)
.add(DeviceEnum.MEDICARE_CARD)
.add(DeviceEnum.PATIENT_CARD)
.add(DeviceEnum.PID_CARD)
.add(DeviceEnum.PKG_8583)
.add(DeviceEnum.PRINTER)
.add(DeviceEnum.SENSOR_CARD)
.add(DeviceEnum.TWO_IN_ONE_CARD)
.build();
/* action-component relationship map */
public static final String JUMP_ACTION = JumpAction.class.getSimpleName();
public static final String SET_FONT_ACTION = SetFontAction.class.getSimpleName();
public static final String CLEAN_ACTION = CleanAction.class.getSimpleName();
public static final String HIDE_ACTION = HideAction.class.getSimpleName();
public static final String USE_TIP_ACTION = UseTipAction.class.getSimpleName();
public static final String PLAY_MEDIA_ACTION = PlayMediaAction.class.getSimpleName();
public static final String SEND_MSG_ACTION = MsgSendAction.class.getSimpleName();
public static final String MOVE_CURSOR_ACTION = MoveCursorAction.class.getSimpleName();
public static final String LIMIT_INPUT_ACTION = LimitInputAction.class.getSimpleName();
public static final String SHOW_COMBOBOX_ACTION = ShowComboBoxAction.class.getSimpleName();
public static final String SHOW_TABLE_ACTION = ShowTableAction.class.getSimpleName();
public static final String SHOW_CLOCK_ACTION = ShowClockAction.class.getSimpleName();
public static final String OPEN_BROWSER_ACTION = OpenBrowserAction.class.getSimpleName();
public static final String RUN_COMMAND_ACTION = RunCommandAction.class.getSimpleName();
public static final String OPEN_VIRTUAL_KEYBOARD_ACTION = VirtualKeyboardAction.class.getSimpleName();
public static final String PRINT_RECEIPT_ACTION = SetPrinterAction.class.getSimpleName();
public static final String INSERT_IC_ACTION = InsertICardAction.class.getSimpleName();
public static final String WRITE_IC_ACTION = WriteICardAction.class.getSimpleName();
public static final String BALANCE_TRANS_ACTION = "BalanceTransAction";
public static final String PRINT_PASSBOOK_ACTION = PrintPassbookAction.class.getSimpleName();
public static final String UPLOAD_FILE_ACTION = UploadFileAction.class.getSimpleName();
public static final String SWIPE_CARD_ACTION = SwipeCardAction.class.getSimpleName();
public static final String SWIPE_TWO_IN_ONE_CARD_ACTION = Swipe2In1CardAction.class.getSimpleName();
public static final String EJECT_CARD_ACTION = EjectCardAction.class.getSimpleName();
public static final String WITHDRAW_CARD_ACTION = WithdrawCardAction.class.getSimpleName();
public static final String READ_WRITE_FINGERPRINT_ACTION = RwFingerPrintAction.class.getSimpleName();
public static final String PLAY_VIDEO_ACTION = PlayVideoAction.class.getSimpleName();
public static final String CUSTOMIZED_ACTION = DefinedAction.class.getSimpleName();
public static final String ENCRYPT_KEYBORAD_ACTION = EncryptKeyboardAction.class.getSimpleName();
public static final String SHOW_GRID_ACTION = ShowGridAction.class.getSimpleName();
public static final String TYPE_NUMERIC_PAD_ACTION = NumericPadAction.class.getSimpleName();
public static final String WEB_LOAD_ACTION = Action.WebLoadAction.class.getSimpleName();
static final Map<ComponentEnum, List<String>> ACTION_COMPONENT_MAP = new ImmutableMap.Builder<ComponentEnum, List<String>>()
.put(ComponentEnum.BUTTON, new ImmutableList.Builder<String>()
.add(CUSTOMIZED_ACTION)
.add(JUMP_ACTION)
.add(SET_FONT_ACTION)
.add(CLEAN_ACTION)
.add(HIDE_ACTION)
.add(USE_TIP_ACTION)
.add(PLAY_MEDIA_ACTION)
.add(OPEN_BROWSER_ACTION)
.add(RUN_COMMAND_ACTION)
.add(OPEN_VIRTUAL_KEYBOARD_ACTION)
.add(PRINT_RECEIPT_ACTION)
.add(SEND_MSG_ACTION)
.add(INSERT_IC_ACTION)
.add(WRITE_IC_ACTION)
.add(MOVE_CURSOR_ACTION)
.add(PRINT_PASSBOOK_ACTION)
.add(UPLOAD_FILE_ACTION)
.add(BALANCE_TRANS_ACTION)
.add(EJECT_CARD_ACTION)
.add(WITHDRAW_CARD_ACTION)
.add(WEB_LOAD_ACTION)
.build())
.put(ComponentEnum.COMBO_BOX, new ImmutableList.Builder<String>()
.add(CUSTOMIZED_ACTION)
.add(SET_FONT_ACTION)
.add(USE_TIP_ACTION)
.add(SHOW_COMBOBOX_ACTION)
.add(SWIPE_CARD_ACTION)
.add(SWIPE_TWO_IN_ONE_CARD_ACTION)
.add(PLAY_MEDIA_ACTION)
.add(MOVE_CURSOR_ACTION)
.build())
.put(ComponentEnum.LABEL, new ImmutableList.Builder<String>()
.add(CUSTOMIZED_ACTION)
.add(SET_FONT_ACTION)
.add(USE_TIP_ACTION)
.add(SHOW_CLOCK_ACTION)
.build())
.put(ComponentEnum.TEXT_FIELD, new ImmutableList.Builder<String>()
.add(CUSTOMIZED_ACTION)
.add(SET_FONT_ACTION)
.add(LIMIT_INPUT_ACTION)
.add(USE_TIP_ACTION)
.add(PLAY_MEDIA_ACTION)
.add(READ_WRITE_FINGERPRINT_ACTION)
.add(OPEN_VIRTUAL_KEYBOARD_ACTION)
.add(MOVE_CURSOR_ACTION)
.build())
.put(ComponentEnum.PASSWORD_FIELD, new ImmutableList.Builder<String>()
.add(CUSTOMIZED_ACTION)
.add(SET_FONT_ACTION)
.add(LIMIT_INPUT_ACTION)
.add(USE_TIP_ACTION)
.add(PLAY_MEDIA_ACTION)
.add(READ_WRITE_FINGERPRINT_ACTION)
.add(MOVE_CURSOR_ACTION)
.add(ENCRYPT_KEYBORAD_ACTION)
.build())
.put(ComponentEnum.TABLE, new ImmutableList.Builder<String>()
.add(CUSTOMIZED_ACTION)
.add(SET_FONT_ACTION)
.add(USE_TIP_ACTION)
.add(SHOW_TABLE_ACTION)
.build())
.put(ComponentEnum.ADVANCED_TABLE, new ImmutableList.Builder<String>()
.add(CUSTOMIZED_ACTION)
.add(SET_FONT_ACTION)
.add(SHOW_TABLE_ACTION)
.add(SEND_MSG_ACTION)
.build())
.put(ComponentEnum.VIDEO_PLAYER, new ImmutableList.Builder<String>()
.add(CUSTOMIZED_ACTION)
.add(PLAY_VIDEO_ACTION)
.build())
.put(ComponentEnum.GRID, new ImmutableList.Builder<String>()
.add(SHOW_GRID_ACTION)
.build())
.put(ComponentEnum.NUMERIC_PAD, new ImmutableList.Builder<String>()
.add(TYPE_NUMERIC_PAD_ACTION)
.build())
.build();
}
| toyboxman/yummy-xml-UI | xml-UI/src/main/java/king/flow/common/CommonConstants.java | Java | apache-2.0 | 15,275 |
package ca.qc.bergeron.marcantoine.crammeur.android.repository.crud.sqlite;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import ca.qc.bergeron.marcantoine.crammeur.librairy.annotations.Entity;
import ca.qc.bergeron.marcantoine.crammeur.librairy.exceptions.KeyException;
import ca.qc.bergeron.marcantoine.crammeur.android.models.Client;
import ca.qc.bergeron.marcantoine.crammeur.android.repository.crud.SQLiteTemplate;
import ca.qc.bergeron.marcantoine.crammeur.librairy.repository.i.Repository;
/**
* Created by Marc-Antoine on 2017-01-11.
*/
public final class SQLiteClient extends SQLiteTemplate<Client,Integer> implements ca.qc.bergeron.marcantoine.crammeur.android.repository.crud.sqlite.i.SQLiteClient {
public SQLiteClient(Repository pRepository, Context context) {
super(Client.class,Integer.class,pRepository, context);
}
@Override
protected Client convertCursorToEntity(@NonNull Cursor pCursor) {
Client o = new Client();
o.Id = pCursor.getInt(pCursor.getColumnIndex(mId.getAnnotation(Entity.Id.class).name()));
o.Name = pCursor.getString(pCursor.getColumnIndex(F_CLIENT_NAME));
o.EMail = pCursor.getString(pCursor.getColumnIndex(F_CLIENT_EMAIL));
return o;
}
@Override
protected Integer convertCursorToId(@NonNull Cursor pCursor) {
Integer result;
result = pCursor.getInt(pCursor.getColumnIndex(mId.getAnnotation(Entity.Id.class).name()));
return result;
}
@Override
public void create() {
mDB.execSQL(CREATE_TABLE_CLIENTS);
}
@NonNull
@Override
public Integer save(@NonNull Client pData) throws KeyException {
ContentValues values = new ContentValues();
try {
if (pData.Id == null) {
pData.Id = this.getKey(pData);
}
values.put(mId.getAnnotation(Entity.Id.class).name(), mKey.cast(mId.get(pData)));
values.put(F_CLIENT_NAME, pData.Name);
values.put(F_CLIENT_EMAIL, pData.EMail);
if (mId.get(pData) == null || !this.contains(mKey.cast(mId.get(pData)))) {
mId.set(pData, (int) mDB.insert(T_CLIENTS, null, values));
} else {
mDB.update(T_CLIENTS, values, mId.getAnnotation(Entity.Id.class).name() + "=?", new String[]{String.valueOf(pData.Id)});
}
return pData.Id;
} catch (IllegalAccessException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
@Nullable
@Override
public Integer getKey(@NonNull Client pEntity) {
Integer result = null;
try {
if (mId.get(pEntity) != null) return (Integer) mId.get(pEntity);
String[] columns = new String[] {F_ID};
String where = "LOWER(" + F_CLIENT_NAME + ")=LOWER(?) AND LOWER(" + F_CLIENT_EMAIL + ")=LOWER(?)";
String[] whereArgs = new String[] {pEntity.Name,pEntity.EMail};
// limit 1 row = "1";
Cursor cursor = mDB.query(T_CLIENTS, columns, where, whereArgs, null, null, null, "1");
if (cursor.moveToFirst()) {
result = cursor.getInt(cursor.getColumnIndex(F_ID));
}
} catch (IllegalAccessException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
return result;
}
}
| crammeur/MyInvoices | crammeurAndroid/src/main/java/ca/qc/bergeron/marcantoine/crammeur/android/repository/crud/sqlite/SQLiteClient.java | Java | apache-2.0 | 3,537 |
/**
* @license AngularJS v1.3.0-build.2690+sha.be7c02c
* (c) 2010-2014 Google, Inc. http://angularjs.org
* License: MIT
*/
(function(window, angular, undefined) {'use strict';
/**
* @ngdoc module
* @name ngCookies
* @description
*
* # ngCookies
*
* The `ngCookies` module provides a convenient wrapper for reading and writing browser cookies.
*
*
* <div doc-module-components="ngCookies"></div>
*
* See {@link ngCookies.$cookies `$cookies`} and
* {@link ngCookies.$cookieStore `$cookieStore`} for usage.
*/
angular.module('ngCookies', ['ng']).
/**
* @ngdoc service
* @name $cookies
*
* @description
* Provides read/write access to browser's cookies.
*
* Only a simple Object is exposed and by adding or removing properties to/from this object, new
* cookies are created/deleted at the end of current $eval.
* The object's properties can only be strings.
*
* Requires the {@link ngCookies `ngCookies`} module to be installed.
*
* @example
*
* ```js
* function ExampleController($cookies) {
* // Retrieving a cookie
* var favoriteCookie = $cookies.myFavorite;
* // Setting a cookie
* $cookies.myFavorite = 'oatmeal';
* }
* ```
*/
factory('$cookies', ['$rootScope', '$browser', function ($rootScope, $browser) {
var cookies = {},
lastCookies = {},
lastBrowserCookies,
runEval = false,
copy = angular.copy,
isUndefined = angular.isUndefined;
//creates a poller fn that copies all cookies from the $browser to service & inits the service
$browser.addPollFn(function() {
var currentCookies = $browser.cookies();
if (lastBrowserCookies != currentCookies) { //relies on browser.cookies() impl
lastBrowserCookies = currentCookies;
copy(currentCookies, lastCookies);
copy(currentCookies, cookies);
if (runEval) $rootScope.$apply();
}
})();
runEval = true;
//at the end of each eval, push cookies
//TODO: this should happen before the "delayed" watches fire, because if some cookies are not
// strings or browser refuses to store some cookies, we update the model in the push fn.
$rootScope.$watch(push);
return cookies;
/**
* Pushes all the cookies from the service to the browser and verifies if all cookies were
* stored.
*/
function push() {
var name,
value,
browserCookies,
updated;
//delete any cookies deleted in $cookies
for (name in lastCookies) {
if (isUndefined(cookies[name])) {
$browser.cookies(name, undefined);
}
}
//update all cookies updated in $cookies
for(name in cookies) {
value = cookies[name];
if (!angular.isString(value)) {
value = '' + value;
cookies[name] = value;
}
if (value !== lastCookies[name]) {
$browser.cookies(name, value);
updated = true;
}
}
//verify what was actually stored
if (updated){
updated = false;
browserCookies = $browser.cookies();
for (name in cookies) {
if (cookies[name] !== browserCookies[name]) {
//delete or reset all cookies that the browser dropped from $cookies
if (isUndefined(browserCookies[name])) {
delete cookies[name];
} else {
cookies[name] = browserCookies[name];
}
updated = true;
}
}
}
}
}]).
/**
* @ngdoc service
* @name $cookieStore
* @requires $cookies
*
* @description
* Provides a key-value (string-object) storage, that is backed by session cookies.
* Objects put or retrieved from this storage are automatically serialized or
* deserialized by angular's toJson/fromJson.
*
* Requires the {@link ngCookies `ngCookies`} module to be installed.
*
* @example
*
* ```js
* function ExampleController($cookieStore) {
* // Put cookie
* $cookieStore.put('myFavorite','oatmeal');
* // Get cookie
* var favoriteCookie = $cookieStore.get('myFavorite');
* // Removing a cookie
* $cookieStore.remove('myFavorite');
* }
* ```
*/
factory('$cookieStore', ['$cookies', function($cookies) {
return {
/**
* @ngdoc method
* @name $cookieStore#get
*
* @description
* Returns the value of given cookie key
*
* @param {string} key Id to use for lookup.
* @returns {Object} Deserialized cookie value.
*/
get: function(key) {
var value = $cookies[key];
return value ? angular.fromJson(value) : value;
},
/**
* @ngdoc method
* @name $cookieStore#put
*
* @description
* Sets a value for given cookie key
*
* @param {string} key Id for the `value`.
* @param {Object} value Value to be stored.
*/
put: function(key, value) {
$cookies[key] = angular.toJson(value);
},
/**
* @ngdoc method
* @name $cookieStore#remove
*
* @description
* Remove given cookie
*
* @param {string} key Id of the key-value pair to delete.
*/
remove: function(key) {
delete $cookies[key];
}
};
}]);
})(window, window.angular);
| yawo/pepeto | code/client/js/node_modules/bower_components/angular-cookies/angular-cookies.js | JavaScript | apache-2.0 | 5,642 |
/* -------------------------------------------------------------------------- *
* Simbody(tm): SimTKmath *
* -------------------------------------------------------------------------- *
* This is part of the SimTK biosimulation toolkit originating from *
* Simbios, the NIH National Center for Physics-Based Simulation of *
* Biological Structures at Stanford, funded under the NIH Roadmap for *
* Medical Research, grant U54 GM072970. See https://simtk.org/home/simbody. *
* *
* Portions copyright (c) 2010-13 Stanford University and the Authors. *
* Authors: Peter Eastman, Michael Sherman *
* Contributors: *
* *
* 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 "SimTKmath.h"
#include <algorithm>
using std::pair; using std::make_pair;
#include <iostream>
using std::cout; using std::endl;
#include <set>
// Define this if you want to see voluminous output from MPR (XenoCollide)
//#define MPR_DEBUG
namespace SimTK {
//==============================================================================
// CONTACT TRACKER
//==============================================================================
//------------------------------------------------------------------------------
// ESTIMATE IMPLICIT PAIR CONTACT USING MPR
//------------------------------------------------------------------------------
// Generate a rough guess at the contact points. Point P is returned in A's
// frame and point Q is in B's frame, but all the work here is done in frame A.
// See Snethen, G. "XenoCollide: Complex Collision Made Simple", Game
// Programming Gems 7, pp.165-178.
//
// Note that we intend to use this on smooth convex objects. That means there
// can be no guarantee about how many iterations this will take to converge; it
// may take a very long time for objects that are just barely touching. On the
// other hand we only need an approximate answer because we're going to polish
// the solution to machine precision using a Newton iteration afterwards.
namespace {
// Given a direction in shape A's frame, calculate the support point of the
// Minkowski difference shape A-B in that direction. To do that we find A's
// support point P in that direction, and B's support point Q in the opposite
// direction; i.e. what would be -B's support in the original direction. Then
// return the vector v=(P-Q) expressed in A's frame.
struct Support {
Support(const ContactGeometry& shapeA, const ContactGeometry& shapeB,
const Transform& X_AB, const UnitVec3& dirInA)
: shapeA(shapeA), shapeB(shapeB), X_AB(X_AB)
{ computeSupport(dirInA); }
// Calculate a new set of supports for the same shapes.
void computeSupport(const UnitVec3& dirInA) {
const UnitVec3 dirInB = ~X_AB.R() * dirInA; // 15 flops
dir = dirInA;
A = shapeA.calcSupportPoint( dirInA); // varies; 40 flops for ellipsoid
B = shapeB.calcSupportPoint(-dirInB); // "
v = A - X_AB*B; // 21 flops
depth = dot(v,dir); // 5 flops
}
Support& operator=(const Support& src) {
dir = src.dir; A = src.A; B = src.B; v = src.v;
return *this;
}
void swap(Support& other) {
std::swap(dir, other.dir);
std::swap(A,other.A); std::swap(B,other.B); std::swap(v,other.v);
}
void getResult(Vec3& pointP_A, Vec3& pointQ_B, UnitVec3& normalInA) const
{ pointP_A = A; pointQ_B = B; normalInA = dir; }
UnitVec3 dir; // A support direction, exp in A
Vec3 A; // support point in direction dir on shapeA, expressed in A
Vec3 B; // support point in direction -dir on shapeB, expressed in B
Vec3 v; // support point A-B in Minkowski difference shape, exp. in A
Real depth; // v . dir (positive when origin is below support plane)
private:
const ContactGeometry& shapeA;
const ContactGeometry& shapeB;
const Transform& X_AB;
};
const Real MPRAccuracy = Real(.05); // 5% of the surface dimensions
const Real SqrtMPRAccuracy = Real(.2236); // roughly sqrt(MPRAccuracy)
}
/*static*/ bool ContactTracker::
estimateConvexImplicitPairContactUsingMPR
(const ContactGeometry& shapeA, const ContactGeometry& shapeB,
const Transform& X_AB,
Vec3& pointP, Vec3& pointQ, UnitVec3& dirInA, int& numIterations)
{
const Rotation& R_AB = X_AB.R();
numIterations = 0;
// Get some cheap, rough scaling information.
// TODO: ideally this would be done using local curvature information.
// A reasonable alternative would be to use the smallest dimension of the
// shape's oriented bounding box.
// We're going to assume the smallest radius is 1/4 of the bounding
// sphere radius.
Vec3 cA, cB; Real rA, rB;
shapeA.getBoundingSphere(cA,rA); shapeB.getBoundingSphere(cB,rB);
const Real lengthScale = Real(0.25)*std::min(rA,rB);
const Real areaScale = Real(1.5)*square(lengthScale); // ~area of octant
// If we determine the depth to within a small fraction of the scale,
// or localize the contact area to a small fraction of the surface area,
// that is good enough and we can stop.
const Real depthGoal = MPRAccuracy*lengthScale;
const Real areaGoal = SqrtMPRAccuracy*areaScale;
#ifdef MPR_DEBUG
printf("\nMPR acc=%g: r=%g, depthGoal=%g areaGoal=%g\n",
MPRAccuracy, std::min(rA,rB), depthGoal, areaGoal);
#endif
// Phase 1: Portal Discovery
// -------------------------
// Compute an interior point v0 that is known to be inside the Minkowski
// difference, and a ray dir1 directed from that point to the origin.
const Vec3 v0 = ( Support(shapeA, shapeB, X_AB, UnitVec3( XAxis)).v
+ Support(shapeA, shapeB, X_AB, UnitVec3(-XAxis)).v)/2;
if (v0 == 0) {
// This is a pathological case: the two objects are directly on top of
// each other with their centers at exactly the same place. Just
// return *some* vaguely plausible contact.
pointP = shapeA.calcSupportPoint( UnitVec3( XAxis));
pointQ = shapeB.calcSupportPoint(~R_AB*UnitVec3(-XAxis)); // in B
dirInA = XAxis;
return true;
}
// Support 1's direction is initially the "origin ray" that points from
// interior point v0 to the origin.
Support s1(shapeA, shapeB, X_AB, UnitVec3(-v0));
// Test for NaN once and get out to avoid getting stuck in loops below.
if (isNaN(s1.depth)) {
pointP = pointQ = NaN;
dirInA = UnitVec3();
return false;
}
if (s1.depth <= 0) { // origin outside 1st support plane
s1.getResult(pointP, pointQ, dirInA);
return false;
}
if (s1.v % v0 == 0) { // v0 perpendicular to support plane; origin inside
s1.getResult(pointP, pointQ, dirInA);
return true;
}
// Find support point perpendicular to plane containing origin, interior
// point v0, and first support v1.
Support s2(shapeA, shapeB, X_AB, UnitVec3(s1.v % v0));
if (s2.depth <= 0) { // origin is outside 2nd support plane
s2.getResult(pointP, pointQ, dirInA);
return false;
}
// Find support perpendicular to plane containing interior point v0 and
// first two support points v1 and v2. Make sure it is on the side that
// is closer to the origin; fix point ordering if necessary.
UnitVec3 d3 = UnitVec3((s1.v-v0)%(s2.v-v0));
if (~d3*v0 > 0) { // oops -- picked the wrong side
s1.swap(s2);
d3 = -d3;
}
Support s3(shapeA, shapeB, X_AB, d3);
if (s3.depth <= 0) { // origin is outside 3rd support plane
s3.getResult(pointP, pointQ, dirInA);
return false;
}
// We now have a candidate portal (triangle v1,v2,v3). We have to refine it
// until the origin ray -v0 intersects the candidate. Check against the
// three planes of the tetrahedron that contain v0. By construction above
// we know the origin is inside the v0,v1,v2 face already.
// We should find a candidate portal very fast, probably in 1 or 2
// iterations. We'll allow an absurdly large number of
// iterations and then abort just to make sure we don't get stuck in an
// infinite loop.
const Real MaxCandidateIters = 100; // should never get anywhere near this
int candidateIters = 0;
while (true) {
++candidateIters;
SimTK_ERRCHK_ALWAYS(candidateIters <= MaxCandidateIters,
"ContactTracker::estimateConvexImplicitPairContactUsingMPR()",
"Unable to find a candidate portal; should never happen.");
if (~v0*(s1.v % s3.v) < -SignificantReal)
s2 = s3; // origin outside v0,v1,v3 face; replace v2
else if (~v0*(s3.v % s2.v) < -SignificantReal)
s1 = s3; // origin outside v0,v2,v3 face; replace v1
else
break;
// Choose new candidate. The keepers are in v1 and v2; get a new v3.
s3.computeSupport(UnitVec3((s1.v-v0) % (s2.v-v0)));
}
// Phase 2: Portal Refinement
// --------------------------
// We have a portal (triangle v1,v2,v3) that the origin ray passes through.
// Now we need to refine v1,v2,v3 until we have portal such that the origin
// is inside the tetrahedron v0,v1,v2,v3.
const int MinTriesToFindSeparatingPlane = 5;
const int MaxTriesToImproveContact = 5;
int triesToFindSeparatingPlane=0, triesToImproveContact=0;
while (true) {
++numIterations;
// Get the normal to the portal, oriented in the general direction of
// the origin ray (i.e., the outward normal).
const Vec3 portalVec = (s2.v-s1.v) % (s3.v-s1.v);
const Real portalArea = portalVec.norm(), ooPortalArea = 1/portalArea;
UnitVec3 portalDir(portalVec*ooPortalArea, true);
if (~portalDir*v0 > 0)
portalDir = -portalDir;
// Any portal vertex is a vector from the origin to the portal plane.
// Dot one of them with the portal outward normal to get the origin
// depth (positive if inside).
const Real depth = ~s1.v*portalDir;
// Find new support in portal direction.
Support s4(shapeA, shapeB, X_AB, portalDir);
if (s4.depth <= 0) { // origin is outside new support plane
s4.getResult(pointP, pointQ, dirInA);
return false;
}
const Real depthChange = std::abs(s4.depth - depth);
bool mustReturn=false, okToReturn=false;
if (depth >= 0) { // We found a contact.
mustReturn = (++triesToImproveContact >= MaxTriesToImproveContact);
okToReturn = true;
} else { // No contact yet.
okToReturn =
(++triesToFindSeparatingPlane >= MinTriesToFindSeparatingPlane);
mustReturn = false;
}
bool accuracyAchieved =
(depthChange <= depthGoal || portalArea <= areaGoal);
#ifdef MPR_DEBUG
printf(" depth=%g, change=%g area=%g changeFrac=%g areaFrac=%g\n",
depth, depthChange, portalArea,
depthChange/depthGoal, portalArea/areaGoal);
printf(" accuracyAchieved=%d okToReturn=%d mustReturn=%d\n",
accuracyAchieved, okToReturn, mustReturn);
#endif
if (mustReturn || (okToReturn && accuracyAchieved)) {
// The origin is inside the portal, so we have an intersection.
// Compute the barycentric coordinates of the origin ray's
// intersection with the portal, and map back to the two surfaces.
const Vec3 origin = v0+v0*(~portalDir*(s1.v-v0)/(~portalDir*v0));
const Real area1 = ~portalDir*((s2.v-origin)%(s3.v-origin));
const Real area2 = ~portalDir*((s3.v-origin)%(s1.v-origin));
const Real u = area1*ooPortalArea;
const Real v = area2*ooPortalArea;
const Real w = 1-u-v;
// Compute the contact points in their own shape's frame.
pointP = u*s1.A + v*s2.A + w*s3.A;
pointQ = u*s1.B + v*s2.B + w*s3.B;
dirInA = portalDir;
return true;
}
// We know the origin ray entered the (v1,v2,v3,v4) tetrahedron via the
// (v1,v2,v3) face (the portal). New portal is the face that it exits.
const Vec3 v4v0 = s4.v % v0;
if (~s1.v * v4v0 > 0) {
if (~s2.v * v4v0 > 0) s1 = s4; // v4,v2,v3 (new portal)
else s3 = s4; // v1,v2,v4
} else {
if (~s3.v * v4v0 > 0) s2 = s4; // v1,v4,v3
else s1 = s4; // v4,v2,v3 again
}
}
}
//------------------------------------------------------------------------------
// REFINE IMPLICIT PAIR
//------------------------------------------------------------------------------
// We have a rough estimate of the contact points. Use Newton iteration to
// refine them. If the surfaces are separated, this will find the points of
// closest approach. If contacting, this will find the points of maximium
// penetration.
// Returns true if the desired accuracy is achieved, regardless of whether the
// surfaces are separated or in contact.
/*static*/ bool ContactTracker::
refineImplicitPair
(const ContactGeometry& shapeA, Vec3& pointP, // in/out (in A)
const ContactGeometry& shapeB, Vec3& pointQ, // in/out (in B)
const Transform& X_AB, Real accuracyRequested,
Real& accuracyAchieved, int& numIterations)
{
// If the initial guess is very bad, or the ellipsoids pathological we
// may have to crawl along for a while at the beginning.
const int MaxSlowIterations = 8;
const int MaxIterations = MaxSlowIterations + 8;
const Real MinStepFrac = Real(1e-6); // if we can't take at least this
// fraction of Newton step, give it up
Vec6 err = findImplicitPairError(shapeA, pointP, shapeB, pointQ, X_AB);
accuracyAchieved = err.norm();
Vector errVec(6, &err[0], true); // share space with err
Mat66 J; // to hold the Jacobian
Matrix JMat(6,6,6,&J(0,0)); // share space with J
Vec6 delta;
Vector deltaVec(6, &delta[0], true); // share space with delta
numIterations = 0;
while ( accuracyAchieved > accuracyRequested
&& numIterations < MaxIterations)
{
++numIterations;
J = calcImplicitPairJacobian(shapeA, pointP, shapeB, pointQ,
X_AB, err);
// Try to use LU factorization; fall back to QTZ if singular.
FactorLU lu(JMat);
if (!lu.isSingular())
lu.solve(errVec, deltaVec); // writes into delta also
else {
FactorQTZ qtz(JMat, SqrtEps);
qtz.solve(errVec, deltaVec); // writes into delta also
}
// Line search for safety in case starting guess bad. Don't accept
// any move that makes things worse.
Real f = 2; // scale back factor
Vec3 oldP = pointP, oldQ = pointQ;
Real oldAccuracyAchieved = accuracyAchieved;
do {
f /= 2;
pointP = oldP - f*delta.getSubVec<3>(0);
pointQ = oldQ - f*delta.getSubVec<3>(3);
err = findImplicitPairError(shapeA, pointP, shapeB, pointQ, X_AB);
accuracyAchieved = err.norm();
} while (accuracyAchieved > oldAccuracyAchieved && f > MinStepFrac);
const bool noProgressMade = (accuracyAchieved > oldAccuracyAchieved);
if (noProgressMade) { // Restore best points and fall through.
pointP = oldP;
pointQ = oldQ;
}
if ( noProgressMade
|| (f < 1 && numIterations >= MaxSlowIterations)) // Too slow.
{
// We don't appear to be getting anywhere. Just project the
// points onto the surfaces and then exit.
bool inside;
UnitVec3 normal;
pointP = shapeA.findNearestPoint(pointP, inside, normal);
pointQ = shapeB.findNearestPoint(pointQ, inside, normal);
err = findImplicitPairError(shapeA, pointP, shapeB, pointQ, X_AB);
accuracyAchieved = err.norm();
break;
}
}
return accuracyAchieved <= accuracyRequested;
}
//------------------------------------------------------------------------------
// FIND IMPLICIT PAIR ERROR
//------------------------------------------------------------------------------
// We're given two implicitly-defined shapes A and B and candidate surface
// contact points P (for A) and Q (for B). There are six equations that real
// contact points should satisfy. Here we return the errors in each of those
// equations; if all six terms are zero these are contact points.
//
// Per profiling, this gets called a lot at runtime, so keep it tight!
/*static*/ Vec6 ContactTracker::
findImplicitPairError
(const ContactGeometry& shapeA, const Vec3& pointP, // in A
const ContactGeometry& shapeB, const Vec3& pointQ, // in B
const Transform& X_AB)
{
// Compute the function value and normal vector for each object.
const Function& fA = shapeA.getImplicitFunction();
const Function& fB = shapeB.getImplicitFunction();
// Avoid some heap allocations by using stack arrays.
Vec3 xData;
Vector x(3, &xData[0], true); // shares space with xdata
int compData; // just one integer
ArrayView_<int> components(&compData, &compData+1);
Vec3 gradA, gradB;
xData = pointP; // writes into Vector x also
for (int i = 0; i < 3; i++) {
components[0] = i;
gradA[i] = fA.calcDerivative(components, x);
}
Real errorA = fA.calcValue(x);
xData = pointQ; // writes into Vector x also
for (int i = 0; i < 3; i++) {
components[0] = i;
gradB[i] = fB.calcDerivative(components, x);
}
Real errorB = fB.calcValue(x);
// Construct a coordinate frame for each object.
// TODO: this needs some work to make sure it is as stable as possible
// so the perpendicularity errors are stable as the solution advances
// and especially as the Jacobian is calculated by perturbation.
UnitVec3 nA(-gradA);
UnitVec3 nB(X_AB.R()*(-gradB));
UnitVec3 uA(std::abs(nA[0])>Real(0.5)? nA%Vec3(0, 1, 0) : nA%Vec3(1, 0, 0));
UnitVec3 uB(std::abs(nB[0])>Real(0.5)? nB%Vec3(0, 1, 0) : nB%Vec3(1, 0, 0));
Vec3 vA = nA%uA; // Already a unit vector, so we don't need to normalize it.
Vec3 vB = nB%uB;
// Compute the error vector. The components indicate, in order, that nA
// must be perpendicular to both tangents of object B, that the separation
// vector should be zero or perpendicular to the tangents of object A, and
// that both points should be on their respective surfaces.
Vec3 delta = pointP-X_AB*pointQ;
return Vec6(~nA*uB, ~nA*vB, ~delta*uA, ~delta*vA, errorA, errorB);
}
//------------------------------------------------------------------------------
// CALC IMPLICIT PAIR JACOBIAN
//------------------------------------------------------------------------------
// Differentiate the findImplicitPairError() with respect to changes in the
// locations of points P and Q in their own surface frames.
/*static*/ Mat66 ContactTracker::calcImplicitPairJacobian
(const ContactGeometry& shapeA, const Vec3& pointP,
const ContactGeometry& shapeB, const Vec3& pointQ,
const Transform& X_AB, const Vec6& err0)
{
Real dt = SqrtEps;
Vec3 d1 = dt*Vec3(1, 0, 0);
Vec3 d2 = dt*Vec3(0, 1, 0);
Vec3 d3 = dt*Vec3(0, 0, 1);
Vec6 err1 = findImplicitPairError(shapeA, pointP+d1, shapeB, pointQ, X_AB)
- err0;
Vec6 err2 = findImplicitPairError(shapeA, pointP+d2, shapeB, pointQ, X_AB)
- err0;
Vec6 err3 = findImplicitPairError(shapeA, pointP+d3, shapeB, pointQ, X_AB)
- err0;
Vec6 err4 = findImplicitPairError(shapeA, pointP, shapeB, pointQ+d1, X_AB)
- err0;
Vec6 err5 = findImplicitPairError(shapeA, pointP, shapeB, pointQ+d2, X_AB)
- err0;
Vec6 err6 = findImplicitPairError(shapeA, pointP, shapeB, pointQ+d3, X_AB)
- err0;
return Mat66(err1, err2, err3, err4, err5, err6) / dt;
// This is a Central Difference derivative (you should use a somewhat
// larger dt in this case). However, I haven't seen any evidence that this
// helps, even for some very eccentric ellipsoids. (sherm 20130408)
//Vec6 err1 = findImplicitPairError(shapeA, pointP+d1, shapeB, pointQ, X_AB)
// - findImplicitPairError(shapeA, pointP-d1, shapeB, pointQ, X_AB);
//Vec6 err2 = findImplicitPairError(shapeA, pointP+d2, shapeB, pointQ, X_AB)
// - findImplicitPairError(shapeA, pointP-d2, shapeB, pointQ, X_AB);
//Vec6 err3 = findImplicitPairError(shapeA, pointP+d3, shapeB, pointQ, X_AB)
// - findImplicitPairError(shapeA, pointP-d3, shapeB, pointQ, X_AB);
//Vec6 err4 = findImplicitPairError(shapeA, pointP, shapeB, pointQ+d1, X_AB)
// - findImplicitPairError(shapeA, pointP, shapeB, pointQ-d1, X_AB);
//Vec6 err5 = findImplicitPairError(shapeA, pointP, shapeB, pointQ+d2, X_AB)
// - findImplicitPairError(shapeA, pointP, shapeB, pointQ-d2, X_AB);
//Vec6 err6 = findImplicitPairError(shapeA, pointP, shapeB, pointQ+d3, X_AB)
// - findImplicitPairError(shapeA, pointP, shapeB, pointQ-d3, X_AB);
//return Mat66(err1, err2, err3, err4, err5, err6) / (2*dt);
}
//==============================================================================
// HALFSPACE-SPHERE CONTACT TRACKER
//==============================================================================
// Cost is 21 flops if no contact, 67 with contact.
bool ContactTracker::HalfSpaceSphere::trackContact
(const Contact& priorStatus,
const Transform& X_GH,
const ContactGeometry& geoHalfSpace,
const Transform& X_GS,
const ContactGeometry& geoSphere,
Real cutoff,
Contact& currentStatus) const
{
SimTK_ASSERT
( geoHalfSpace.getTypeId()==ContactGeometry::HalfSpace::classTypeId()
&& geoSphere.getTypeId()==ContactGeometry::Sphere::classTypeId(),
"ContactTracker::HalfSpaceSphere::trackContact()");
// No need for an expensive dynamic cast here; we know what we have.
const ContactGeometry::Sphere& sphere =
ContactGeometry::Sphere::getAs(geoSphere);
const Rotation R_HG = ~X_GH.R(); // inverse rotation; no flops
// p_HC is vector from H origin to S's center C
const Vec3 p_HC = R_HG*(X_GS.p() - X_GH.p()); // 18 flops
// Calculate depth of sphere center C given that the halfspace occupies
// all of x>0 space.
const Real r = sphere.getRadius();
const Real depth = p_HC[0] + r; // 1 flop
if (depth <= -cutoff) { // 2 flops
currentStatus.clear(); // not touching
return true; // successful return
}
// Calculate the rest of the X_HS transform as required by Contact.
const Transform X_HS(R_HG*X_GS.R(), p_HC); // 45 flops
const UnitVec3 normal_H(Vec3(-1,0,0), true); // 0 flops
const Vec3 origin_H = Vec3(depth/2, p_HC[1], p_HC[2]); // 1 flop
// The surfaces are contacting (or close enough to be interesting).
// The sphere's radius is also the effective radius.
currentStatus = CircularPointContact(priorStatus.getSurface1(), Infinity,
priorStatus.getSurface2(), r,
X_HS, r, depth, origin_H, normal_H);
return true; // success
}
bool ContactTracker::HalfSpaceSphere::predictContact
(const Contact& priorStatus,
const Transform& X_GS1, const SpatialVec& V_GS1, const SpatialVec& A_GS1,
const ContactGeometry& surface1,
const Transform& X_GS2, const SpatialVec& V_GS2, const SpatialVec& A_GS2,
const ContactGeometry& surface2,
Real cutoff,
Real intervalOfInterest,
Contact& predictedStatus) const
{ SimTK_ASSERT_ALWAYS(!"implemented",
"ContactTracker::HalfSpaceSphere::predictContact() not implemented yet.");
return false; }
bool ContactTracker::HalfSpaceSphere::initializeContact
(const Transform& X_GS1, const SpatialVec& V_GS1,
const ContactGeometry& surface1,
const Transform& X_GS2, const SpatialVec& V_GS2,
const ContactGeometry& surface2,
Real cutoff,
Real intervalOfInterest,
Contact& contactStatus) const
{ SimTK_ASSERT_ALWAYS(!"implemented",
"ContactTracker::HalfSpaceSphere::initializeContact() not implemented yet.");
return false; }
//==============================================================================
// HALFSPACE-ELLIPSOID CONTACT TRACKER
//==============================================================================
// Cost is ~135 flops if no contact, ~425 with contact.
// The contact point on the ellipsoid must be the unique point that has its
// outward-facing normal in the opposite direction of the half space normal.
// We can find that point very fast and see how far it is from the half
// space surface. If it is close enough, we'll evaluate the curvatures at
// that point in preparation for generating forces with Hertz theory.
bool ContactTracker::HalfSpaceEllipsoid::trackContact
(const Contact& priorStatus,
const Transform& X_GH,
const ContactGeometry& geoHalfSpace,
const Transform& X_GE,
const ContactGeometry& geoEllipsoid,
Real cutoff,
Contact& currentStatus) const
{
SimTK_ASSERT
( geoHalfSpace.getTypeId()==ContactGeometry::HalfSpace::classTypeId()
&& geoEllipsoid.getTypeId()==ContactGeometry::Ellipsoid::classTypeId(),
"ContactTracker::HalfSpaceEllipsoid::trackContact()");
// No need for an expensive dynamic cast here; we know what we have.
const ContactGeometry::Ellipsoid& ellipsoid =
ContactGeometry::Ellipsoid::getAs(geoEllipsoid);
// Our half space occupies the +x half so the normal is -x.
const Transform X_HE = ~X_GH*X_GE; // 63 flops
// Halfspace normal is -x, so the ellipsoid normal we're looking for is
// in the half space's +x direction.
const UnitVec3& n_E = (~X_HE.R()).x(); // halfspace normal in E
const Vec3 Q_E = ellipsoid.findPointWithThisUnitNormal(n_E); // 40 flops
const Vec3 Q_H = X_HE*Q_E; // Q measured from half space origin (18 flops)
const Real depth = Q_H[0]; // x > 0 is penetrated
if (depth <= -cutoff) { // 2 flops
currentStatus.clear(); // not touching
return true; // successful return
}
// The surfaces are contacting (or close enough to be interesting).
// The ellipsoid's principal curvatures k at the contact point are also
// the curvatures of the contact paraboloid since the half space doesn't
// add anything interesting.
Transform X_EQ; Vec2 k;
ellipsoid.findParaboloidAtPointWithNormal(Q_E, n_E, X_EQ, k); // 220 flops
// We have the contact paraboloid expressed in frame Q but Qz=n_E has the
// wrong sign since we have to express it using the half space normal.
// We have to end up with a right handed frame, so one of x or y has
// to be negated too. (6 flops)
Rotation& R_EQ = X_EQ.updR();
R_EQ.setRotationColFromUnitVecTrustMe(ZAxis, -R_EQ.z()); // changing X_EQ
R_EQ.setRotationColFromUnitVecTrustMe(XAxis, -R_EQ.x());
// Now the frame is pointing in the right direction. Measure and express in
// half plane frame, then shift origin to half way between contact point
// Q on the undeformed ellipsoid and the corresponding contact point P
// on the undeformed half plane surface. It's easier to do this shift
// in H since it is in the -Hx direction.
Transform X_HC = X_HE*X_EQ; X_HC.updP()[0] -= depth/2; // 65 flops
currentStatus = EllipticalPointContact(priorStatus.getSurface1(),
priorStatus.getSurface2(),
X_HE, X_HC, k, depth);
return true; // success
}
bool ContactTracker::HalfSpaceEllipsoid::predictContact
(const Contact& priorStatus,
const Transform& X_GS1, const SpatialVec& V_GS1, const SpatialVec& A_GS1,
const ContactGeometry& surface1,
const Transform& X_GS2, const SpatialVec& V_GS2, const SpatialVec& A_GS2,
const ContactGeometry& surface2,
Real cutoff,
Real intervalOfInterest,
Contact& predictedStatus) const
{ SimTK_ASSERT_ALWAYS(!"implemented",
"ContactTracker::HalfSpaceEllipsoid::predictContact() not implemented yet.");
return false; }
bool ContactTracker::HalfSpaceEllipsoid::initializeContact
(const Transform& X_GS1, const SpatialVec& V_GS1,
const ContactGeometry& surface1,
const Transform& X_GS2, const SpatialVec& V_GS2,
const ContactGeometry& surface2,
Real cutoff,
Real intervalOfInterest,
Contact& contactStatus) const
{ SimTK_ASSERT_ALWAYS(!"implemented",
"ContactTracker::HalfSpaceEllipsoid::initializeContact() not implemented yet.");
return false; }
//==============================================================================
// SPHERE-SPHERE CONTACT TRACKER
//==============================================================================
// Cost is 12 flops if no contact, 139 if contact
bool ContactTracker::SphereSphere::trackContact
(const Contact& priorStatus,
const Transform& X_GS1,
const ContactGeometry& geoSphere1,
const Transform& X_GS2,
const ContactGeometry& geoSphere2,
Real cutoff, // 0 for contact
Contact& currentStatus) const
{
SimTK_ASSERT
( geoSphere1.getTypeId()==ContactGeometry::Sphere::classTypeId()
&& geoSphere2.getTypeId()==ContactGeometry::Sphere::classTypeId(),
"ContactTracker::SphereSphere::trackContact()");
// No need for an expensive dynamic casts here; we know what we have.
const ContactGeometry::Sphere& sphere1 =
ContactGeometry::Sphere::getAs(geoSphere1);
const ContactGeometry::Sphere& sphere2 =
ContactGeometry::Sphere::getAs(geoSphere2);
currentStatus.clear();
// Find the vector from sphere center C1 to C2, expressed in G.
const Vec3 p_12_G = X_GS2.p() - X_GS1.p(); // 3 flops
const Real d2 = p_12_G.normSqr(); // 5 flops
const Real r1 = sphere1.getRadius();
const Real r2 = sphere2.getRadius();
const Real rr = r1 + r2; // 1 flop
// Quick check. If separated we can return nothing, unless we were
// in contact last time in which case we have to return one last
// Contact indicating that contact has been broken and by how much.
if (d2 > square(rr+cutoff)) { // 3 flops
if (!priorStatus.getContactId().isValid())
return true; // successful return: still separated
const Real separation = std::sqrt(d2) - rr; // > cutoff, ~25 flops
const Transform X_S1S2(~X_GS1.R()*X_GS2.R(),
~X_GS1.R()*p_12_G); // 60 flops
currentStatus = BrokenContact(priorStatus.getSurface1(),
priorStatus.getSurface2(),
X_S1S2, separation);
return true;
}
const Real d = std::sqrt(d2); // ~20 flops
if (d < SignificantReal) { // 1 flop
// TODO: If the centers are coincident we should use past information
// to determine the most likely normal. For now just fail.
return false;
}
const Transform X_S1S2(~X_GS1.R()*X_GS2.R(),
~X_GS1.R()*p_12_G);// 60 flops
const Vec3& p_12 = X_S1S2.p(); // center-to-center vector in S1
const Real depth = rr - d; // >0 for penetration (1 flop)
const Real r = r1*r2/rr; // r=r1r2/(r1+r2)=1/(1/r1+1/r2) ~20 flops
const UnitVec3 normal_S1(p_12/d, true); // 1/ + 3* = ~20 flops
const Vec3 origin_S1 = (r1 - depth/2)*normal_S1; // 5 flops
// The surfaces are contacting (or close enough to be interesting).
currentStatus = CircularPointContact(priorStatus.getSurface1(), r1,
priorStatus.getSurface2(), r2,
X_S1S2, r, depth,
origin_S1, normal_S1);
return true; // success
}
bool ContactTracker::SphereSphere::predictContact
(const Contact& priorStatus,
const Transform& X_GS1, const SpatialVec& V_GS1, const SpatialVec& A_GS1,
const ContactGeometry& surface1,
const Transform& X_GS2, const SpatialVec& V_GS2, const SpatialVec& A_GS2,
const ContactGeometry& surface2,
Real cutoff,
Real intervalOfInterest,
Contact& predictedStatus) const
{ SimTK_ASSERT_ALWAYS(!"implemented",
"ContactTracker::SphereSphere::predictContact() not implemented yet.");
return false; }
bool ContactTracker::SphereSphere::initializeContact
(const Transform& X_GS1, const SpatialVec& V_GS1,
const ContactGeometry& surface1,
const Transform& X_GS2, const SpatialVec& V_GS2,
const ContactGeometry& surface2,
Real cutoff,
Real intervalOfInterest,
Contact& contactStatus) const
{ SimTK_ASSERT_ALWAYS(!"implemented",
"ContactTracker::SphereSphere::initializeContact() not implemented yet.");
return false; }
//==============================================================================
// HALFSPACE - TRIANGLE MESH CONTACT TRACKER
//==============================================================================
// Cost is TODO
bool ContactTracker::HalfSpaceTriangleMesh::trackContact
(const Contact& priorStatus,
const Transform& X_GH,
const ContactGeometry& geoHalfSpace,
const Transform& X_GM,
const ContactGeometry& geoMesh,
Real cutoff,
Contact& currentStatus) const
{
SimTK_ASSERT_ALWAYS
( ContactGeometry::HalfSpace::isInstance(geoHalfSpace)
&& ContactGeometry::TriangleMesh::isInstance(geoMesh),
"ContactTracker::HalfSpaceTriangleMesh::trackContact()");
// We can't handle a "proximity" test, only penetration.
SimTK_ASSERT_ALWAYS(cutoff==0,
"ContactTracker::HalfSpaceTriangleMesh::trackContact()");
// No need for an expensive dynamic cast here; we know what we have.
const ContactGeometry::TriangleMesh& mesh =
ContactGeometry::TriangleMesh::getAs(geoMesh);
// Transform giving mesh (S2) frame in the halfspace (S1) frame.
const Transform X_HM = (~X_GH)*X_GM;
// Normal is halfspace -x direction; xdir is first column of R_MH.
// That's a unit vector and -unitvec is also a unit vector so this
// doesn't require normalization.
const UnitVec3 hsNormal_M = -(~X_HM.R()).x();
// Find the height of the halfspace face along the normal, measured
// from the mesh origin.
const Real hsFaceHeight_M = dot((~X_HM).p(), hsNormal_M);
// Now collect all the faces that are all or partially below the
// halfspace surface.
std::set<int> insideFaces;
processBox(mesh, mesh.getOBBTreeNode(), X_HM,
hsNormal_M, hsFaceHeight_M, insideFaces);
if (insideFaces.empty()) {
currentStatus.clear(); // not touching
return true; // successful return
}
currentStatus = TriangleMeshContact(priorStatus.getSurface1(),
priorStatus.getSurface2(),
X_HM,
std::set<int>(), insideFaces);
return true; // success
}
bool ContactTracker::HalfSpaceTriangleMesh::predictContact
(const Contact& priorStatus,
const Transform& X_GS1, const SpatialVec& V_GS1, const SpatialVec& A_GS1,
const ContactGeometry& surface1,
const Transform& X_GS2, const SpatialVec& V_GS2, const SpatialVec& A_GS2,
const ContactGeometry& surface2,
Real cutoff,
Real intervalOfInterest,
Contact& predictedStatus) const
{ SimTK_ASSERT_ALWAYS(!"implemented",
"ContactTracker::HalfSpaceTriangleMesh::predictContact() not implemented yet.");
return false; }
bool ContactTracker::HalfSpaceTriangleMesh::initializeContact
(const Transform& X_GS1, const SpatialVec& V_GS1,
const ContactGeometry& surface1,
const Transform& X_GS2, const SpatialVec& V_GS2,
const ContactGeometry& surface2,
Real cutoff,
Real intervalOfInterest,
Contact& contactStatus) const
{ SimTK_ASSERT_ALWAYS(!"implemented",
"ContactTracker::HalfSpaceTriangleMesh::initializeContact() not implemented yet.");
return false; }
// Check a single OBB and its contents (recursively) against the halfspace,
// appending any penetrating faces to the insideFaces list.
void ContactTracker::HalfSpaceTriangleMesh::processBox
(const ContactGeometry::TriangleMesh& mesh,
const ContactGeometry::TriangleMesh::OBBTreeNode& node,
const Transform& X_HM, const UnitVec3& hsNormal_M, Real hsFaceHeight_M,
std::set<int>& insideFaces) const
{ // First check against the node's bounding box.
const OrientedBoundingBox& bounds = node.getBounds();
const Transform& X_MB = bounds.getTransform(); // box frame in mesh
const Vec3 p_BC = bounds.getSize()/2; // from box origin corner to center
// Express the half space normal in the box frame, then reflect it into
// the first (+,+,+) quadrant where it is the normal of a different
// but symmetric and more convenient half space.
const UnitVec3 octant1hsNormal_B = (~X_MB.R()*hsNormal_M).abs();
// Dot our octant1 radius p_BC with our octant1 normal to get
// the extent of the box from its center in the direction of the octant1
// reflection of the halfspace.
const Real extent = dot(p_BC, octant1hsNormal_B);
// Compute the height of the box center over the mesh origin,
// measured along the real halfspace normal.
const Vec3 boxCenter_M = X_MB*p_BC;
const Real boxCenterHeight_M = dot(boxCenter_M, hsNormal_M);
// Subtract the halfspace surface position to get the height of the
// box center over the halfspace.
const Real boxCenterHeight = boxCenterHeight_M - hsFaceHeight_M;
if (boxCenterHeight >= extent)
return; // no penetration
if (boxCenterHeight <= -extent) {
addAllTriangles(node, insideFaces); // box is entirely in halfspace
return;
}
// Box is partially penetrated into halfspace. If it is not a leaf node,
// check its children.
if (!node.isLeafNode()) {
processBox(mesh, node.getFirstChildNode(), X_HM, hsNormal_M,
hsFaceHeight_M, insideFaces);
processBox(mesh, node.getSecondChildNode(), X_HM, hsNormal_M,
hsFaceHeight_M, insideFaces);
return;
}
// This is a leaf OBB node that is penetrating, so some of its triangles
// may be penetrating.
const Array_<int>& triangles = node.getTriangles();
for (int i = 0; i < (int) triangles.size(); i++) {
for (int vx=0; vx < 3; ++vx) {
const int vertex = mesh.getFaceVertex(triangles[i], vx);
const Vec3& vertexPos = mesh.getVertexPosition(vertex);
const Real vertexHeight_M = dot(vertexPos, hsNormal_M);
if (vertexHeight_M < hsFaceHeight_M) {
insideFaces.insert(triangles[i]);
break; // done with this face
}
}
}
}
void ContactTracker::HalfSpaceTriangleMesh::addAllTriangles
(const ContactGeometry::TriangleMesh::OBBTreeNode& node,
std::set<int>& insideFaces) const
{
if (node.isLeafNode()) {
const Array_<int>& triangles = node.getTriangles();
for (int i = 0; i < (int) triangles.size(); i++)
insideFaces.insert(triangles[i]);
}
else {
addAllTriangles(node.getFirstChildNode(), insideFaces);
addAllTriangles(node.getSecondChildNode(), insideFaces);
}
}
//==============================================================================
// SPHERE - TRIANGLE MESH CONTACT TRACKER
//==============================================================================
// Cost is TODO
bool ContactTracker::SphereTriangleMesh::trackContact
(const Contact& priorStatus,
const Transform& X_GS,
const ContactGeometry& geoSphere,
const Transform& X_GM,
const ContactGeometry& geoMesh,
Real cutoff,
Contact& currentStatus) const
{
SimTK_ASSERT_ALWAYS
( ContactGeometry::Sphere::isInstance(geoSphere)
&& ContactGeometry::TriangleMesh::isInstance(geoMesh),
"ContactTracker::SphereTriangleMesh::trackContact()");
// We can't handle a "proximity" test, only penetration.
SimTK_ASSERT_ALWAYS(cutoff==0,
"ContactTracker::SphereTriangleMesh::trackContact()");
// No need for an expensive dynamic cast here; we know what we have.
const ContactGeometry::Sphere& sphere =
ContactGeometry::Sphere::getAs(geoSphere);
const ContactGeometry::TriangleMesh& mesh =
ContactGeometry::TriangleMesh::getAs(geoMesh);
// Transform giving mesh (M) frame in the sphere (S) frame.
const Transform X_SM = ~X_GS*X_GM;
// Want the sphere center measured and expressed in the mesh frame.
const Vec3 p_MC = (~X_SM).p();
std::set<int> insideFaces;
processBox(mesh, mesh.getOBBTreeNode(), p_MC, square(sphere.getRadius()),
insideFaces);
if (insideFaces.empty()) {
currentStatus.clear(); // not touching
return true; // successful return
}
currentStatus = TriangleMeshContact(priorStatus.getSurface1(),
priorStatus.getSurface2(),
X_SM,
std::set<int>(), insideFaces);
return true; // success
}
// Check a single OBB and its contents (recursively) against the sphere
// whose center location in M and radius squared is given, appending any
// penetrating faces to the insideFaces list.
void ContactTracker::SphereTriangleMesh::processBox
(const ContactGeometry::TriangleMesh& mesh,
const ContactGeometry::TriangleMesh::OBBTreeNode& node,
const Vec3& center_M, Real radius2,
std::set<int>& insideFaces) const
{ // First check against the node's bounding box.
const Vec3 nearest_M = node.getBounds().findNearestPoint(center_M);
if ((nearest_M-center_M).normSqr() >= radius2)
return; // no intersection possible
// Bounding box is penetrating. If it's not a leaf node, check its children.
if (!node.isLeafNode()) {
processBox(mesh, node.getFirstChildNode(), center_M, radius2,
insideFaces);
processBox(mesh, node.getSecondChildNode(), center_M, radius2,
insideFaces);
return;
}
// This is a leaf node that may be penetrating; check the triangles.
const Array_<int>& triangles = node.getTriangles();
for (unsigned i = 0; i < triangles.size(); i++) {
Vec2 uv;
Vec3 nearest_M = mesh.findNearestPointToFace
(center_M, triangles[i], uv);
if ((nearest_M-center_M).normSqr() < radius2)
insideFaces.insert(triangles[i]);
}
}
bool ContactTracker::SphereTriangleMesh::predictContact
(const Contact& priorStatus,
const Transform& X_GS1, const SpatialVec& V_GS1, const SpatialVec& A_GS1,
const ContactGeometry& surface1,
const Transform& X_GS2, const SpatialVec& V_GS2, const SpatialVec& A_GS2,
const ContactGeometry& surface2,
Real cutoff,
Real intervalOfInterest,
Contact& predictedStatus) const
{ SimTK_ASSERT_ALWAYS(!"implemented",
"ContactTracker::SphereTriangleMesh::predictContact() not implemented yet.");
return false; }
bool ContactTracker::SphereTriangleMesh::initializeContact
(const Transform& X_GS1, const SpatialVec& V_GS1,
const ContactGeometry& surface1,
const Transform& X_GS2, const SpatialVec& V_GS2,
const ContactGeometry& surface2,
Real cutoff,
Real intervalOfInterest,
Contact& contactStatus) const
{ SimTK_ASSERT_ALWAYS(!"implemented",
"ContactTracker::SphereTriangleMesh::initializeContact() not implemented yet.");
return false; }
//==============================================================================
// TRIANGLE MESH - TRIANGLE MESH CONTACT TRACKER
//==============================================================================
// Cost is TODO
bool ContactTracker::TriangleMeshTriangleMesh::trackContact
(const Contact& priorStatus,
const Transform& X_GM1,
const ContactGeometry& geoMesh1,
const Transform& X_GM2,
const ContactGeometry& geoMesh2,
Real cutoff,
Contact& currentStatus) const
{
SimTK_ASSERT_ALWAYS
( ContactGeometry::TriangleMesh::isInstance(geoMesh1)
&& ContactGeometry::TriangleMesh::isInstance(geoMesh2),
"ContactTracker::TriangleMeshTriangleMesh::trackContact()");
// We can't handle a "proximity" test, only penetration.
SimTK_ASSERT_ALWAYS(cutoff==0,
"ContactTracker::TriangleMeshTriangleMesh::trackContact()");
// No need for an expensive dynamic cast here; we know what we have.
const ContactGeometry::TriangleMesh& mesh1 =
ContactGeometry::TriangleMesh::getAs(geoMesh1);
const ContactGeometry::TriangleMesh& mesh2 =
ContactGeometry::TriangleMesh::getAs(geoMesh2);
// Transform giving mesh2 (M2) frame in the mesh1 (M1) frame.
const Transform X_M1M2 = ~X_GM1*X_GM2;
std::set<int> insideFaces1, insideFaces2;
// Get M2's bounding box in M1's frame.
const OrientedBoundingBox
mesh2Bounds_M1 = X_M1M2*mesh2.getOBBTreeNode().getBounds();
// Find the faces that are actually intersecting faces on the other
// surface (this doesn't yet include faces that may be completely buried).
findIntersectingFaces(mesh1, mesh2,
mesh1.getOBBTreeNode(), mesh2.getOBBTreeNode(),
mesh2Bounds_M1, X_M1M2, insideFaces1, insideFaces2);
// It should never be the case that one set of faces is empty and the
// other isn't, however it is conceivable that roundoff error could cause
// this to happen so we'll check both lists.
if (insideFaces1.empty() && insideFaces2.empty()) {
currentStatus.clear(); // not touching
return true; // successful return
}
// There was an intersection. We now need to identify every triangle and
// vertex of each mesh that is inside the other mesh. We found the border
// intersections above; now we have to fill in the buried faces.
findBuriedFaces(mesh1, mesh2, ~X_M1M2, insideFaces1);
findBuriedFaces(mesh2, mesh1, X_M1M2, insideFaces2);
currentStatus = TriangleMeshContact(priorStatus.getSurface1(),
priorStatus.getSurface2(),
X_M1M2,
insideFaces1, insideFaces2);
return true; // success
}
void ContactTracker::TriangleMeshTriangleMesh::
findIntersectingFaces
(const ContactGeometry::TriangleMesh& mesh1,
const ContactGeometry::TriangleMesh& mesh2,
const ContactGeometry::TriangleMesh::OBBTreeNode& node1,
const ContactGeometry::TriangleMesh::OBBTreeNode& node2,
const OrientedBoundingBox& node2Bounds_M1,
const Transform& X_M1M2,
std::set<int>& triangles1,
std::set<int>& triangles2) const
{ // See if the bounding boxes intersect.
if (!node1.getBounds().intersectsBox(node2Bounds_M1))
return;
// If either node is not a leaf node, process the children recursively.
if (!node1.isLeafNode()) {
if (!node2.isLeafNode()) {
const OrientedBoundingBox firstChildBounds =
X_M1M2*node2.getFirstChildNode().getBounds();
const OrientedBoundingBox secondChildBounds =
X_M1M2*node2.getSecondChildNode().getBounds();
findIntersectingFaces(mesh1, mesh2, node1.getFirstChildNode(), node2.getFirstChildNode(), firstChildBounds, X_M1M2, triangles1, triangles2);
findIntersectingFaces(mesh1, mesh2, node1.getFirstChildNode(), node2.getSecondChildNode(), secondChildBounds, X_M1M2, triangles1, triangles2);
findIntersectingFaces(mesh1, mesh2, node1.getSecondChildNode(), node2.getFirstChildNode(), firstChildBounds, X_M1M2, triangles1, triangles2);
findIntersectingFaces(mesh1, mesh2, node1.getSecondChildNode(), node2.getSecondChildNode(), secondChildBounds, X_M1M2, triangles1, triangles2);
}
else {
findIntersectingFaces(mesh1, mesh2, node1.getFirstChildNode(), node2, node2Bounds_M1, X_M1M2, triangles1, triangles2);
findIntersectingFaces(mesh1, mesh2, node1.getSecondChildNode(), node2, node2Bounds_M1, X_M1M2, triangles1, triangles2);
}
return;
}
else if (!node2.isLeafNode()) {
const OrientedBoundingBox firstChildBounds =
X_M1M2*node2.getFirstChildNode().getBounds();
const OrientedBoundingBox secondChildBounds =
X_M1M2*node2.getSecondChildNode().getBounds();
findIntersectingFaces(mesh1, mesh2, node1, node2.getFirstChildNode(), firstChildBounds, X_M1M2, triangles1, triangles2);
findIntersectingFaces(mesh1, mesh2, node1, node2.getSecondChildNode(), secondChildBounds, X_M1M2, triangles1, triangles2);
return;
}
// These are both leaf nodes, so check triangles for intersections.
const Array_<int>& node1triangles = node1.getTriangles();
const Array_<int>& node2triangles = node2.getTriangles();
for (unsigned i = 0; i < node2triangles.size(); i++) {
const int face2 = node2triangles[i];
Vec3 a1 = X_M1M2*mesh2.getVertexPosition(mesh2.getFaceVertex(face2, 0));
Vec3 a2 = X_M1M2*mesh2.getVertexPosition(mesh2.getFaceVertex(face2, 1));
Vec3 a3 = X_M1M2*mesh2.getVertexPosition(mesh2.getFaceVertex(face2, 2));
const Geo::Triangle A(a1,a2,a3);
for (unsigned j = 0; j < node1triangles.size(); j++) {
const int face1 = node1triangles[j];
const Vec3& b1 = mesh1.getVertexPosition(mesh1.getFaceVertex(face1, 0));
const Vec3& b2 = mesh1.getVertexPosition(mesh1.getFaceVertex(face1, 1));
const Vec3& b3 = mesh1.getVertexPosition(mesh1.getFaceVertex(face1, 2));
const Geo::Triangle B(b1,b2,b3);
if (A.overlapsTriangle(B))
{ // The triangles intersect.
triangles1.insert(face1);
triangles2.insert(face2);
}
}
}
}
static const int Outside = -1;
static const int Unknown = 0;
static const int Boundary = 1;
static const int Inside = 2;
void ContactTracker::TriangleMeshTriangleMesh::
findBuriedFaces(const ContactGeometry::TriangleMesh& mesh, // M
const ContactGeometry::TriangleMesh& otherMesh, // O
const Transform& X_OM,
std::set<int>& insideFaces) const
{
// Find which faces are inside.
// We're passed in the list of Boundary faces, that is, those faces of
// "mesh" that intersect faces of "otherMesh".
Array_<int> faceType(mesh.getNumFaces(), Unknown);
for (std::set<int>::iterator iter = insideFaces.begin();
iter != insideFaces.end(); ++iter)
faceType[*iter] = Boundary;
for (int i = 0; i < (int) faceType.size(); i++) {
if (faceType[i] == Unknown) {
// Trace a ray from its center to determine whether it is inside.
const Vec3 origin_O = X_OM * mesh.findCentroid(i);
const UnitVec3 direction_O = X_OM.R()* mesh.getFaceNormal(i);
Real distance;
int face;
Vec2 uv;
if ( otherMesh.intersectsRay(origin_O, direction_O, distance,
face, uv)
&& ~direction_O*otherMesh.getFaceNormal(face) > 0)
{
faceType[i] = Inside;
insideFaces.insert(i);
} else
faceType[i] = Outside;
// Recursively mark adjacent inside or outside Faces.
tagFaces(mesh, faceType, insideFaces, i, 0);
}
}
}
//TODO: the following method uses depth-first recursion to iterate through
//unmarked faces. For a large mesh this was observed to produce a stack
//overflow in OpenSim. Here we limit the recursion depth; after we get that
//deep we'll pop back out and do another expensive intersectsRay() test in
//the method above.
static const int MaxRecursionDepth = 500;
void ContactTracker::TriangleMeshTriangleMesh::
tagFaces(const ContactGeometry::TriangleMesh& mesh,
Array_<int>& faceType,
std::set<int>& triangles,
int index,
int depth) const
{
for (int i = 0; i < 3; i++) {
const int edge = mesh.getFaceEdge(index, i);
const int face = (mesh.getEdgeFace(edge, 0) == index
? mesh.getEdgeFace(edge, 1)
: mesh.getEdgeFace(edge, 0));
if (faceType[face] == Unknown) {
faceType[face] = faceType[index];
if (faceType[index] > 0)
triangles.insert(face);
if (depth < MaxRecursionDepth)
tagFaces(mesh, faceType, triangles, face, depth+1);
}
}
}
bool ContactTracker::TriangleMeshTriangleMesh::predictContact
(const Contact& priorStatus,
const Transform& X_GS1, const SpatialVec& V_GS1, const SpatialVec& A_GS1,
const ContactGeometry& surface1,
const Transform& X_GS2, const SpatialVec& V_GS2, const SpatialVec& A_GS2,
const ContactGeometry& surface2,
Real cutoff,
Real intervalOfInterest,
Contact& predictedStatus) const
{ SimTK_ASSERT_ALWAYS(!"implemented",
"ContactTracker::TriangleMeshTriangleMesh::predictContact() not implemented yet.");
return false; }
bool ContactTracker::TriangleMeshTriangleMesh::initializeContact
(const Transform& X_GS1, const SpatialVec& V_GS1,
const ContactGeometry& surface1,
const Transform& X_GS2, const SpatialVec& V_GS2,
const ContactGeometry& surface2,
Real cutoff,
Real intervalOfInterest,
Contact& contactStatus) const
{ SimTK_ASSERT_ALWAYS(!"implemented",
"ContactTracker::TriangleMeshTriangleMesh::initializeContact() not implemented yet.");
return false; }
//==============================================================================
// CONVEX IMPLICIT SURFACE PAIR CONTACT TRACKER
//==============================================================================
// This will return an elliptical point contact.
bool ContactTracker::ConvexImplicitPair::trackContact
(const Contact& priorStatus,
const Transform& X_GA,
const ContactGeometry& shapeA,
const Transform& X_GB,
const ContactGeometry& shapeB,
Real cutoff,
Contact& currentStatus) const
{
SimTK_ASSERT_ALWAYS
( shapeA.isConvex() && shapeA.isSmooth()
&& shapeB.isConvex() && shapeB.isSmooth(),
"ContactTracker::ConvexImplicitPair::trackContact()");
// We'll work in the shape A frame.
const Transform X_AB = ~X_GA*X_GB; // 63 flops
const Rotation& R_AB = X_AB.R();
// 1. Get a rough guess at the contact points P and Q and contact normal.
Vec3 pointP_A, pointQ_B; // on A and B, resp.
UnitVec3 norm_A;
int numMPRIters;
const bool mightBeContact = estimateConvexImplicitPairContactUsingMPR
(shapeA, shapeB, X_AB,
pointP_A, pointQ_B, norm_A, numMPRIters);
#ifdef MPR_DEBUG
std::cout << "MPR: " << (mightBeContact?"MAYBE":"NO") << std::endl;
std::cout << " P=" << X_GA*pointP_A << " Q=" << X_GB*pointQ_B << std::endl;
std::cout << " N=" << X_GA.R()*norm_A << std::endl;
#endif
if (!mightBeContact) {
currentStatus.clear(); // definitely not touching
return true; // successful return
}
// 2. Refine the contact points to near machine precision.
const Real accuracyRequested = SignificantReal;
Real accuracyAchieved; int numNewtonIters;
bool converged = refineImplicitPair(shapeA, pointP_A, shapeB, pointQ_B,
X_AB, accuracyRequested, accuracyAchieved, numNewtonIters);
const Vec3 pointQ_A = X_AB*pointQ_B; // Q on B, measured & expressed in A
// 3. Compute the curvatures and surface normals of the two surfaces at
// P and Q. Once we have the first normal we can check whether there was
// actually any contact and duck out early if not.
Rotation R_AP; Vec2 curvatureP;
shapeA.calcCurvature(pointP_A, curvatureP, R_AP);
// If the surfaces are in contact then the vector from Q on surface B
// (supposedly inside A) to P on surface A (supposedly inside B) should be
// aligned with the outward normal on A.
const Real depth = dot(pointP_A-pointQ_A, R_AP.z());
#ifdef MPR_DEBUG
printf("MPR %2d iters, Newton %2d iters->accuracy=%g depth=%g\n",
numMPRIters, numNewtonIters, accuracyAchieved, depth);
#endif
if (depth <= 0) {
currentStatus.clear(); // not touching
return true; // successful return
}
// The surfaces are in contact.
Rotation R_BQ; Vec2 curvatureQ;
shapeB.calcCurvature(pointQ_B, curvatureQ, R_BQ);
const UnitVec3 maxDirB_A(R_AB*R_BQ.x()); // re-express in A
// 4. Compute the effective contact frame C and corresponding relative
// curvatures.
Transform X_AC; Vec2 curvatureC;
// Define the contact frame origin to be at the midpoint of P and Q.
X_AC.updP() = (pointP_A+pointQ_A)/2;
// Determine the contact frame orientations and composite curvatures.
ContactGeometry::combineParaboloids(R_AP, curvatureP,
maxDirB_A, curvatureQ,
X_AC.updR(), curvatureC);
// 5. Return the elliptical point contact for force generation.
currentStatus = EllipticalPointContact(priorStatus.getSurface1(),
priorStatus.getSurface2(),
X_AB, X_AC, curvatureC, depth);
return true; // success
}
bool ContactTracker::ConvexImplicitPair::predictContact
(const Contact& priorStatus,
const Transform& X_GS1, const SpatialVec& V_GS1, const SpatialVec& A_GS1,
const ContactGeometry& surface1,
const Transform& X_GS2, const SpatialVec& V_GS2, const SpatialVec& A_GS2,
const ContactGeometry& surface2,
Real cutoff,
Real intervalOfInterest,
Contact& predictedStatus) const
{ SimTK_ASSERT_ALWAYS(!"implemented",
"ContactTracker::ConvexImplicitPair::predictContact() not implemented yet.");
return false; }
bool ContactTracker::ConvexImplicitPair::initializeContact
(const Transform& X_GS1, const SpatialVec& V_GS1,
const ContactGeometry& surface1,
const Transform& X_GS2, const SpatialVec& V_GS2,
const ContactGeometry& surface2,
Real cutoff,
Real intervalOfInterest,
Contact& contactStatus) const
{ SimTK_ASSERT_ALWAYS(!"implemented",
"ContactTracker::ConvexImplicitPair::initializeContact() not implemented yet.");
return false; }
//==============================================================================
// GENERAL IMPLICIT SURFACE PAIR CONTACT TRACKER
//==============================================================================
// This will return an elliptical point contact. TODO: should return a set
// of contacts.
//TODO: not implemented yet -- this is just the Convex-convex code here.
bool ContactTracker::GeneralImplicitPair::trackContact
(const Contact& priorStatus,
const Transform& X_GA,
const ContactGeometry& shapeA,
const Transform& X_GB,
const ContactGeometry& shapeB,
Real cutoff,
Contact& currentStatus) const
{
SimTK_ASSERT_ALWAYS
( shapeA.isSmooth() && shapeB.isSmooth(),
"ContactTracker::GeneralImplicitPair::trackContact()");
// TODO: this won't work unless the shapes are actually convex.
return ConvexImplicitPair(shapeA.getTypeId(),shapeB.getTypeId())
.trackContact(priorStatus, X_GA, shapeA, X_GB, shapeB,
cutoff, currentStatus);
}
bool ContactTracker::GeneralImplicitPair::predictContact
(const Contact& priorStatus,
const Transform& X_GS1, const SpatialVec& V_GS1, const SpatialVec& A_GS1,
const ContactGeometry& surface1,
const Transform& X_GS2, const SpatialVec& V_GS2, const SpatialVec& A_GS2,
const ContactGeometry& surface2,
Real cutoff,
Real intervalOfInterest,
Contact& predictedStatus) const
{ SimTK_ASSERT_ALWAYS(!"implemented",
"ContactTracker::GeneralImplicitPair::predictContact() not implemented yet.");
return false; }
bool ContactTracker::GeneralImplicitPair::initializeContact
(const Transform& X_GS1, const SpatialVec& V_GS1,
const ContactGeometry& surface1,
const Transform& X_GS2, const SpatialVec& V_GS2,
const ContactGeometry& surface2,
Real cutoff,
Real intervalOfInterest,
Contact& contactStatus) const
{ SimTK_ASSERT_ALWAYS(!"implemented",
"ContactTracker::GeneralImplicitPair::initializeContact() not implemented yet.");
return false; }
} // namespace SimTK
| elen4/simbody | SimTKmath/Geometry/src/ContactTracker.cpp | C++ | apache-2.0 | 64,663 |
using System;
namespace TheUnacademicPortfolio.Commons.Dtos
{
public class BaseDto
{
public Guid Id { get; set; }
}
} | pichardoJ/TheUnacademicPortfolio | src/TheUnacademicPortfolio.Commons/Dtos/BaseDto.cs | C# | apache-2.0 | 141 |
/*
* Copyright 2015 - 2021 TU Dortmund
*
* 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 de.learnlib.alex.learning.services;
import de.learnlib.alex.data.entities.ProjectEnvironment;
import de.learnlib.alex.data.entities.ProjectUrl;
import de.learnlib.alex.data.entities.actions.Credentials;
import java.util.HashMap;
import java.util.Map;
/**
* Class to mange a URL and get URL based on this.
*/
public class BaseUrlManager {
private final Map<String, ProjectUrl> urlMap;
/** Advanced constructor which sets the base url field. */
public BaseUrlManager(ProjectEnvironment environment) {
this.urlMap = new HashMap<>();
environment.getUrls().forEach(u -> this.urlMap.put(u.getName(), u));
}
/**
* Get the absolute URL of a path, i.e. based on the base url (base url + '/' + path'), as String
* and insert the credentials if possible.
*
* @param path
* The path to append on the base url.
* @param credentials
* The credentials to insert into the URL.
* @return An absolute URL as String
*/
public String getAbsoluteUrl(String urlName, String path, Credentials credentials) {
final String url = combineUrls(urlMap.get(urlName).getUrl(), path);
return BaseUrlManager.getUrlWithCredentials(url, credentials);
}
public String getAbsoluteUrl(String urlName, String path) {
final String url = combineUrls(urlMap.get(urlName).getUrl(), path);
return BaseUrlManager.getUrlWithCredentials(url, null);
}
/**
* Append apiPath to basePath and make sure that only one '/' is between them.
*
* @param basePath
* The prefix of the new URL.
* @param apiPath
* The suffix of the new URL.
* @return The combined URL.
*/
private String combineUrls(String basePath, String apiPath) {
if (basePath.endsWith("/") && apiPath.startsWith("/")) {
// both have a '/' -> remove one
return basePath + apiPath.substring(1);
} else if (!basePath.endsWith("/") && !apiPath.startsWith("/")) {
// no one has a '/' -> add one
return basePath + "/" + apiPath;
} else {
// exact 1. '/' in between -> good to go
return basePath + apiPath;
}
}
private static String getUrlWithCredentials(String url, Credentials credentials) {
if (credentials != null && credentials.areValid()) {
return url.replaceFirst("^(http[s]?://)", "$1"
+ credentials.getName() + ":"
+ credentials.getPassword() + "@");
} else {
return url;
}
}
}
| LearnLib/alex | backend/src/main/java/de/learnlib/alex/learning/services/BaseUrlManager.java | Java | apache-2.0 | 3,225 |
/*
* Copyright 2015 Cognitive Medical Systems, Inc (http://www.cognitivemedciine.com).
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.socraticgrid.hl7.services.orders.model.types.orderitems;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.socraticgrid.hl7.services.orders.model.OrderItem;
import org.socraticgrid.hl7.services.orders.model.primatives.Code;
import org.socraticgrid.hl7.services.orders.model.primatives.Identifier;
import org.socraticgrid.hl7.services.orders.model.primatives.Period;
import org.socraticgrid.hl7.services.orders.model.primatives.Quantity;
import org.socraticgrid.hl7.services.orders.model.primatives.Ratio;
public class MedicationOrderItem extends OrderItem
{
/**
*
*/
private static final long serialVersionUID = 1L;
private String additionalDosageIntructions;
private String comment;
private Quantity dispenseQuantity= new Quantity();
private String dosageInstructions;
private Code dosageMethod;
private Quantity dosageQuantity = new Quantity();
private Ratio dosageRate = new Ratio();
private Code dosageSite = new Code();
private Date dosageTiming;
private Period dosageTimingPeriod = new Period();
private List<Identifier> drug = new ArrayList<Identifier>(0);
private Date endDate;
private Quantity expectedSupplyDuration = new Quantity();
private Ratio maxDosePerPeriod = new Ratio();
private List<Identifier> medication = new ArrayList<Identifier>(0);
private int numberOfRepeatsAllowed=0;
private Code prescriber;
private Code route = new Code();
private String schedule;
private Date startDate;
/**
* @return the additionalDosageIntructions
*/
public String getAdditionalDosageIntructions() {
return additionalDosageIntructions;
}
/**
* @return the comment
*/
public String getComment() {
return comment;
}
/**
* @return the dispenseQuantity
*/
public Quantity getDispenseQuantity() {
return dispenseQuantity;
}
/**
* @return the dosageInstructions
*/
public String getDosageInstructions() {
return dosageInstructions;
}
/**
* @return the dosageMethod
*/
public Code getDosageMethod() {
return dosageMethod;
}
/**
* @return the dosageQuantity
*/
public Quantity getDosageQuantity() {
return dosageQuantity;
}
/**
* @return the dosageRate
*/
public Ratio getDosageRate() {
return dosageRate;
}
/**
* @return the dosageSite
*/
public Code getDosageSite() {
return dosageSite;
}
/**
* @return the dosageTiming
*/
public Date getDosageTiming() {
return dosageTiming;
}
/**
* @return the dosageTimingPeriod
*/
public Period getDosageTimingPeriod() {
return dosageTimingPeriod;
}
/**
* @return the drug
*/
public List<Identifier> getDrug() {
return drug;
}
/**
* @return the endDate
*/
public Date getEndDate() {
return endDate;
}
/**
* @return the expectedSupplyDuration
*/
public Quantity getExpectedSupplyDuration() {
return expectedSupplyDuration;
}
/**
* @return the maxDosePerPeriod
*/
public Ratio getMaxDosePerPeriod() {
return maxDosePerPeriod;
}
/**
* @return the medication
*/
public List<Identifier> getMedication() {
return medication;
}
/**
* @return the numberOfRepeatsAllowed
*/
public int getNumberOfRepeatsAllowed() {
return numberOfRepeatsAllowed;
}
/**
* @return the prescriber
*/
public Code getPrescriber() {
return prescriber;
}
/**
* @return the route
*/
public Code getRoute() {
return route;
}
/**
* @return the schedule
*/
public String getSchedule() {
return schedule;
}
/**
* @return the startDate
*/
public Date getStartDate() {
return startDate;
}
/**
* @param additionalDosageIntructions the additionalDosageIntructions to set
*/
public void setAdditionalDosageIntructions(String additionalDosageIntructions) {
this.additionalDosageIntructions = additionalDosageIntructions;
}
/**
* @param comment the comment to set
*/
public void setComment(String comment) {
this.comment = comment;
}
/**
* @param dispenseQuantity the dispenseQuantity to set
*/
public void setDispenseQuantity(Quantity dispenseQuantity) {
this.dispenseQuantity = dispenseQuantity;
}
/**
* @param dosageInstructions the dosageInstructions to set
*/
public void setDosageInstructions(String dosageInstructions) {
this.dosageInstructions = dosageInstructions;
}
/**
* @param dosageMethod the dosageMethod to set
*/
public void setDosageMethod(Code dosageMethod) {
this.dosageMethod = dosageMethod;
}
/**
* @param dosageQuantity the dosageQuantity to set
*/
public void setDosageQuantity(Quantity dosageQuantity) {
this.dosageQuantity = dosageQuantity;
}
/**
* @param dosageRate the dosageRate to set
*/
public void setDosageRate(Ratio dosageRate) {
this.dosageRate = dosageRate;
}
/**
* @param dosageSite the dosageSite to set
*/
public void setDosageSite(Code dosageSite) {
this.dosageSite = dosageSite;
}
/**
* @param dosageTiming the dosageTiming to set
*/
public void setDosageTiming(Date dosageTiming) {
this.dosageTiming = dosageTiming;
}
/**
* @param dosageTimingPeriod the dosageTimingPeriod to set
*/
public void setDosageTimingPeriod(Period dosageTimingPeriod) {
this.dosageTimingPeriod = dosageTimingPeriod;
}
/**
* @param drug the drug to set
*/
public void setDrug(List<Identifier> drug) {
this.drug = drug;
}
/**
* @param endDate the endDate to set
*/
public void setEndDate(Date endDate) {
this.endDate = endDate;
}
/**
* @param expectedSupplyDuration the expectedSupplyDuration to set
*/
public void setExpectedSupplyDuration(Quantity expectedSupplyDuration) {
this.expectedSupplyDuration = expectedSupplyDuration;
}
/**
* @param maxDosePerPeriod the maxDosePerPeriod to set
*/
public void setMaxDosePerPeriod(Ratio maxDosePerPeriod) {
this.maxDosePerPeriod = maxDosePerPeriod;
}
/**
* @param medication the medication to set
*/
public void setMedication(List<Identifier> medication) {
this.medication = medication;
}
/**
* @param numberOfRepeatsAllowed the numberOfRepeatsAllowed to set
*/
public void setNumberOfRepeatsAllowed(int numberOfRepeatsAllowed) {
this.numberOfRepeatsAllowed = numberOfRepeatsAllowed;
}
/**
* @param prescriber the prescriber to set
*/
public void setPrescriber(Code prescriber) {
this.prescriber = prescriber;
}
/**
* @param route the route to set
*/
public void setRoute(Code route) {
this.route = route;
}
/**
* @param schedule the schedule to set
*/
public void setSchedule(String schedule) {
this.schedule = schedule;
}
/**
* @param startDate the startDate to set
*/
public void setStartDate(Date startDate) {
this.startDate = startDate;
}
}
| SocraticGrid/OMS-API | src/main/java/org/socraticgrid/hl7/services/orders/model/types/orderitems/MedicationOrderItem.java | Java | apache-2.0 | 7,408 |