repo_name
stringlengths 6
101
| path
stringlengths 4
300
| text
stringlengths 7
1.31M
|
|---|---|---|
UBessle/wekan
|
packages/wekan-cfs-data-man/client/data-man-api.js
|
/**
* @method DataMan
* @public
* @constructor
* @param {File|Blob|ArrayBuffer|Uint8Array|String} data The data that you want to manipulate.
* @param {String} [type] The data content (MIME) type, if known. Required if the first argument is an ArrayBuffer, Uint8Array, or URL
*/
DataMan = function DataMan(data, type) {
var self = this;
if (!data) {
throw new Error("DataMan constructor requires a data argument");
}
// The end result of all this is that we will have one of the following set:
// - self.blob
// - self.url
// Unless we already have in-memory data, we don't load anything into memory
// and instead rely on obtaining a read stream when the time comes.
if (typeof File !== "undefined" && data instanceof File) {
self.blob = data; // File inherits from Blob so this is OK
self._type = data.type;
} else if (typeof Blob !== "undefined" && data instanceof Blob) {
self.blob = data;
self._type = data.type;
} else if (typeof ArrayBuffer !== "undefined" && data instanceof ArrayBuffer || EJSON.isBinary(data)) {
if (typeof Blob === "undefined") {
throw new Error("Browser must support Blobs to handle an ArrayBuffer or Uint8Array");
}
if (!type) {
throw new Error("DataMan constructor requires a type argument when passed an ArrayBuffer or Uint8Array");
}
self.blob = new Blob([data], {type: type});
self._type = type;
} else if (typeof data === "string") {
if (data.slice(0, 5) === "data:") {
self._type = data.slice(5, data.indexOf(';'));
self.blob = dataURItoBlob(data, self._type);
} else if (data.slice(0, 5) === "http:" || data.slice(0, 6) === "https:") {
if (!type) {
throw new Error("DataMan constructor requires a type argument when passed a URL");
}
self.url = data;
self._type = type;
} else {
throw new Error("DataMan constructor received unrecognized data string");
}
} else {
throw new Error("DataMan constructor received data that it doesn't support");
}
};
/**
* @method DataMan.prototype.getBlob
* @public
* @param {Function} [callback] - callback(error, blob)
* @returns {undefined|Blob}
*
* Passes a Blob representing this data to a callback or returns
* the Blob if no callback is provided. A callback is required
* if getting a Blob for a URL.
*/
DataMan.prototype.getBlob = function dataManGetBlob(callback) {
var self = this;
if (callback) {
if (self.blob) {
callback(null, self.blob);
} else if (self.url) {
var xhr = new XMLHttpRequest();
xhr.open('GET', self.url, true);
xhr.responseType = "blob";
xhr.onload = function(data) {
self.blob = xhr.response;
callback(null, self.blob);
};
xhr.onerror = function(err) {
callback(err);
};
xhr.send();
}
} else {
if (self.url)
throw new Error('DataMan.getBlob requires a callback when managing a URL');
return self.blob;
}
};
/**
* @method DataMan.prototype.getBinary
* @public
* @param {Number} [start] - First byte position to read.
* @param {Number} [end] - Last byte position to read.
* @param {Function} callback - callback(error, binaryData)
* @returns {undefined}
*
* Passes a Uint8Array representing this data to a callback.
*/
DataMan.prototype.getBinary = function dataManGetBinary(start, end, callback) {
var self = this;
if (typeof start === "function") {
callback = start;
}
callback = callback || defaultCallback;
function read(blob) {
if (typeof FileReader === "undefined") {
callback(new Error("Browser does not support FileReader"));
return;
}
var reader = new FileReader();
reader.onload = function(evt) {
callback(null, new Uint8Array(evt.target.result));
};
reader.onerror = function(err) {
callback(err);
};
reader.readAsArrayBuffer(blob);
}
self.getBlob(function (error, blob) {
if (error) {
callback(error);
} else {
if (typeof start === "number" && typeof end === "number") {
var size = blob.size;
// Return the requested chunk of binary data
if (start >= size) {
callback(new Error("DataMan.getBinary: start position beyond end of data (" + size + ")"));
return;
}
end = Math.min(size, end);
var slice = blob.slice || blob.webkitSlice || blob.mozSlice;
if (typeof slice === 'undefined') {
callback(new Error('Browser does not support File.slice'));
return;
}
read(slice.call(blob, start, end, self._type));
} else {
// Return the entire binary data
read(blob);
}
}
});
};
/** @method DataMan.prototype.saveAs
* @public
* @param {String} [filename]
* @return {undefined}
*
* Tells the browser to save the data like a normal downloaded file,
* using the provided filename.
*
*/
DataMan.prototype.saveAs = function dataManSaveAs(filename) {
var self = this;
if (typeof window === "undefined")
throw new Error("window must be defined to use saveLocal");
if (!window.saveAs) {
console.warn('DataMan.saveAs: window.saveAs not supported by this browser - add cfs-filesaver package');
return;
}
self.getBlob(function (error, blob) {
if (error) {
throw error;
} else {
window.saveAs(blob, filename);
}
});
};
/**
* @method DataMan.prototype.getDataUri
* @public
* @param {function} callback callback(err, dataUri)
*/
DataMan.prototype.getDataUri = function dataManGetDataUri(callback) {
// XXX: We could consider using: URL.createObjectURL(blob);
// This will create a reference to the blob data instead of a clone
// This is part of the File API - as the rest - Not sure how to generally
// support from IE10, FF26, Chrome 31, safari 7, opera 19, ios 6, android 4
var self = this;
if (typeof callback !== 'function')
throw new Error("getDataUri requires callback function");
if (typeof FileReader === "undefined") {
callback(new Error("Browser does not support FileReader"));
return;
}
var fileReader = new FileReader();
fileReader.onload = function(event) {
var dataUri = event.target.result;
callback(null, dataUri);
};
fileReader.onerror = function(err) {
callback(err);
};
self.getBlob(function (error, blob) {
if (error) {
callback(error);
} else {
fileReader.readAsDataURL(blob);
}
});
};
/**
* @method DataMan.prototype.size
* @public
* @param {function} [callback] callback(err, size)
*
* Passes the size of the data to the callback, if provided,
* or returns it. A callback is required to get the size of a URL on the client.
*/
DataMan.prototype.size = function dataManSize(callback) {
var self = this;
if (callback) {
if (typeof self._size === "number") {
callback(null, self._size);
} else {
self.getBlob(function (error, blob) {
if (error) {
callback(error);
} else {
self._size = blob.size;
callback(null, self._size);
}
});
}
} else {
if (self.url) {
throw new Error("On the client, DataMan.size requires a callback when getting size for a URL on the client");
} else if (typeof self._size === "number") {
return self._size;
} else {
var blob = self.getBlob();
self._size = blob.size;
return self._size;
}
}
};
/**
* @method DataMan.prototype.type
* @public
*
* Returns the type of the data.
*/
DataMan.prototype.type = function dataManType() {
return this._type;
};
/**
* @method dataURItoBlob
* @private
* @param {String} dataURI The data URI
* @param {String} dataTYPE The content type
* @returns {Blob} A new Blob instance
*
* Converts a data URI to a Blob.
*/
function dataURItoBlob(dataURI, dataTYPE) {
var str = atob(dataURI.split(',')[1]), array = [];
for(var i = 0; i < str.length; i++) array.push(str.charCodeAt(i));
return new Blob([new Uint8Array(array)], {type: dataTYPE});
}
/**
* @method defaultCallback
* @private
* @param {Error} [err]
* @returns {undefined}
*
* Can be used as a default callback for client methods that need a callback.
* Simply throws the provided error if there is one.
*/
function defaultCallback(err) {
if (err) {
// Show gentle error if Meteor error
if (err instanceof Meteor.Error) {
console.error(err.message);
} else {
// Normal error, just throw error
throw err;
}
}
}
|
discourse/discourse-ember-source
|
dist/es/ember-template-compiler/tests/plugins/assert-reserved-named-arguments-test.js
|
import { compile } from '../../index';
import { moduleFor, AbstractTestCase } from 'internal-test-helpers';
moduleFor('ember-template-compiler: assert-reserved-named-arguments', class extends AbstractTestCase {
[`@test '@arguments' is reserved`]() {
expectAssertion(() => {
compile(`{{@arguments}}`, {
moduleName: 'baz/foo-bar'
});
}, `'@arguments' is reserved. ('baz/foo-bar' @ L1:C2) `);
expectAssertion(() => {
compile(`{{#if @arguments}}Yup{{/if}}`, {
moduleName: 'baz/foo-bar'
});
}, `'@arguments' is reserved. ('baz/foo-bar' @ L1:C6) `);
expectAssertion(() => {
compile(`{{input type=(if @arguments "bar" "baz")}}`, {
moduleName: 'baz/foo-bar'
});
}, `'@arguments' is reserved. ('baz/foo-bar' @ L1:C17) `);
}
[`@test '@args' is reserved`]() {
expectAssertion(() => {
compile(`{{@args}}`, {
moduleName: 'baz/foo-bar'
});
}, `'@args' is reserved. ('baz/foo-bar' @ L1:C2) `);
expectAssertion(() => {
compile(`{{#if @args}}Yup{{/if}}`, {
moduleName: 'baz/foo-bar'
});
}, `'@args' is reserved. ('baz/foo-bar' @ L1:C6) `);
expectAssertion(() => {
compile(`{{input type=(if @args "bar" "baz")}}`, {
moduleName: 'baz/foo-bar'
});
}, `'@args' is reserved. ('baz/foo-bar' @ L1:C17) `);
}
[`@test '@block' is reserved`]() {
expectAssertion(() => {
compile(`{{@block}}`, {
moduleName: 'baz/foo-bar'
});
}, `'@block' is reserved. ('baz/foo-bar' @ L1:C2) `);
expectAssertion(() => {
compile(`{{#if @block}}Yup{{/if}}`, {
moduleName: 'baz/foo-bar'
});
}, `'@block' is reserved. ('baz/foo-bar' @ L1:C6) `);
expectAssertion(() => {
compile(`{{input type=(if @block "bar" "baz")}}`, {
moduleName: 'baz/foo-bar'
});
}, `'@block' is reserved. ('baz/foo-bar' @ L1:C17) `);
}
[`@test '@else' is reserved`]() {
expectAssertion(() => {
compile(`{{@else}}`, {
moduleName: 'baz/foo-bar'
});
}, `'@else' is reserved. ('baz/foo-bar' @ L1:C2) `);
expectAssertion(() => {
compile(`{{#if @else}}Yup{{/if}}`, {
moduleName: 'baz/foo-bar'
});
}, `'@else' is reserved. ('baz/foo-bar' @ L1:C6) `);
expectAssertion(() => {
compile(`{{input type=(if @else "bar" "baz")}}`, {
moduleName: 'baz/foo-bar'
});
}, `'@else' is reserved. ('baz/foo-bar' @ L1:C17) `);
} // anything else that doesn't start with a lower case letter
[`@test '@Arguments' is reserved`]() {
expectAssertion(() => {
compile(`{{@Arguments}}`, {
moduleName: 'baz/foo-bar'
});
}, `'@Arguments' is reserved. ('baz/foo-bar' @ L1:C2) `);
expectAssertion(() => {
compile(`{{#if @Arguments}}Yup{{/if}}`, {
moduleName: 'baz/foo-bar'
});
}, `'@Arguments' is reserved. ('baz/foo-bar' @ L1:C6) `);
expectAssertion(() => {
compile(`{{input type=(if @Arguments "bar" "baz")}}`, {
moduleName: 'baz/foo-bar'
});
}, `'@Arguments' is reserved. ('baz/foo-bar' @ L1:C17) `);
}
[`@test '@Args' is reserved`]() {
expectAssertion(() => {
compile(`{{@Args}}`, {
moduleName: 'baz/foo-bar'
});
}, `'@Args' is reserved. ('baz/foo-bar' @ L1:C2) `);
expectAssertion(() => {
compile(`{{#if @Args}}Yup{{/if}}`, {
moduleName: 'baz/foo-bar'
});
}, `'@Args' is reserved. ('baz/foo-bar' @ L1:C6) `);
expectAssertion(() => {
compile(`{{input type=(if @Args "bar" "baz")}}`, {
moduleName: 'baz/foo-bar'
});
}, `'@Args' is reserved. ('baz/foo-bar' @ L1:C17) `);
}
[`@test '@FOO' is reserved`]() {
expectAssertion(() => {
compile(`{{@FOO}}`, {
moduleName: 'baz/foo-bar'
});
}, `'@FOO' is reserved. ('baz/foo-bar' @ L1:C2) `);
expectAssertion(() => {
compile(`{{#if @FOO}}Yup{{/if}}`, {
moduleName: 'baz/foo-bar'
});
}, `'@FOO' is reserved. ('baz/foo-bar' @ L1:C6) `);
expectAssertion(() => {
compile(`{{input type=(if @FOO "bar" "baz")}}`, {
moduleName: 'baz/foo-bar'
});
}, `'@FOO' is reserved. ('baz/foo-bar' @ L1:C17) `);
}
[`@test '@Foo' is reserved`]() {
expectAssertion(() => {
compile(`{{@Foo}}`, {
moduleName: 'baz/foo-bar'
});
}, `'@Foo' is reserved. ('baz/foo-bar' @ L1:C2) `);
expectAssertion(() => {
compile(`{{#if @Foo}}Yup{{/if}}`, {
moduleName: 'baz/foo-bar'
});
}, `'@Foo' is reserved. ('baz/foo-bar' @ L1:C6) `);
expectAssertion(() => {
compile(`{{input type=(if @Foo "bar" "baz")}}`, {
moduleName: 'baz/foo-bar'
});
}, `'@Foo' is reserved. ('baz/foo-bar' @ L1:C17) `);
}
[`@test '@.' is reserved`]() {
expectAssertion(() => {
compile(`{{@.}}`, {
moduleName: 'baz/foo-bar'
});
}, `'@.' is reserved. ('baz/foo-bar' @ L1:C2) `);
expectAssertion(() => {
compile(`{{#if @.}}Yup{{/if}}`, {
moduleName: 'baz/foo-bar'
});
}, `'@.' is reserved. ('baz/foo-bar' @ L1:C6) `);
expectAssertion(() => {
compile(`{{input type=(if @. "bar" "baz")}}`, {
moduleName: 'baz/foo-bar'
});
}, `'@.' is reserved. ('baz/foo-bar' @ L1:C17) `);
}
[`@test '@_' is reserved`]() {
expectAssertion(() => {
compile(`{{@_}}`, {
moduleName: 'baz/foo-bar'
});
}, `'@_' is reserved. ('baz/foo-bar' @ L1:C2) `);
expectAssertion(() => {
compile(`{{#if @_}}Yup{{/if}}`, {
moduleName: 'baz/foo-bar'
});
}, `'@_' is reserved. ('baz/foo-bar' @ L1:C6) `);
expectAssertion(() => {
compile(`{{input type=(if @_ "bar" "baz")}}`, {
moduleName: 'baz/foo-bar'
});
}, `'@_' is reserved. ('baz/foo-bar' @ L1:C17) `);
}
[`@test '@-' is reserved`]() {
expectAssertion(() => {
compile(`{{@-}}`, {
moduleName: 'baz/foo-bar'
});
}, `'@-' is reserved. ('baz/foo-bar' @ L1:C2) `);
expectAssertion(() => {
compile(`{{#if @-}}Yup{{/if}}`, {
moduleName: 'baz/foo-bar'
});
}, `'@-' is reserved. ('baz/foo-bar' @ L1:C6) `);
expectAssertion(() => {
compile(`{{input type=(if @- "bar" "baz")}}`, {
moduleName: 'baz/foo-bar'
});
}, `'@-' is reserved. ('baz/foo-bar' @ L1:C17) `);
}
[`@test '@$' is reserved`]() {
expectAssertion(() => {
compile(`{{@$}}`, {
moduleName: 'baz/foo-bar'
});
}, `'@$' is reserved. ('baz/foo-bar' @ L1:C2) `);
expectAssertion(() => {
compile(`{{#if @$}}Yup{{/if}}`, {
moduleName: 'baz/foo-bar'
});
}, `'@$' is reserved. ('baz/foo-bar' @ L1:C6) `);
expectAssertion(() => {
compile(`{{input type=(if @$ "bar" "baz")}}`, {
moduleName: 'baz/foo-bar'
});
}, `'@$' is reserved. ('baz/foo-bar' @ L1:C17) `);
}
[`@test '@__ARGS__' is reserved`]() {
expectAssertion(() => {
compile(`<Foo @__ARGS__="bar" />`, {
moduleName: 'baz/foo-bar'
});
}, `'@__ARGS__' is reserved. ('baz/foo-bar' @ L1:C5) `);
expectAssertion(() => {
compile(`{{foo __ARGS__="bar"}}`, {
moduleName: 'baz/foo-bar'
});
}, `'__ARGS__' is reserved. ('baz/foo-bar' @ L1:C6) `);
expectAssertion(() => {
compile(`{{#let (component "foo" __ARGS__="bar") as |c|}}{{c}}{{/let}}`, {
moduleName: 'baz/foo-bar'
});
}, `'__ARGS__' is reserved. ('baz/foo-bar' @ L1:C24) `);
expectAssertion(() => {
compile(`{{@__ARGS__}}`, {
moduleName: 'baz/foo-bar'
});
}, `'@__ARGS__' is reserved. ('baz/foo-bar' @ L1:C2) `);
expectAssertion(() => {
compile(`{{#if @__ARGS__}}Yup{{/if}}`, {
moduleName: 'baz/foo-bar'
});
}, `'@__ARGS__' is reserved. ('baz/foo-bar' @ L1:C6) `);
expectAssertion(() => {
compile(`{{input type=(if @__ARGS__ "bar" "baz")}}`, {
moduleName: 'baz/foo-bar'
});
}, `'@__ARGS__' is reserved. ('baz/foo-bar' @ L1:C17) `);
}
[`@test '@' is de facto reserved (parse error)`](assert) {
assert.throws(() => {
compile('{{@}}', {
moduleName: 'baz/foo-bar'
});
}, /Expecting 'ID'/);
assert.throws(() => {
compile('{{#if @}}Yup{{/if}}', {
moduleName: 'baz/foo-bar'
});
}, /Expecting 'ID'/);
assert.throws(() => {
compile('{{input type=(if @ "bar" "baz")}}', {
moduleName: 'baz/foo-bar'
});
}, /Expecting 'ID'/);
}
[`@test '@0' is de facto reserved (parse error)`](assert) {
assert.throws(() => {
compile('{{@0}}', {
moduleName: 'baz/foo-bar'
});
}, /Expecting 'ID'/);
assert.throws(() => {
compile('{{#if @0}}Yup{{/if}}', {
moduleName: 'baz/foo-bar'
});
}, /Expecting 'ID'/);
assert.throws(() => {
compile('{{input type=(if @0 "bar" "baz")}}', {
moduleName: 'baz/foo-bar'
});
}, /Expecting 'ID'/);
}
[`@test '@1' is de facto reserved (parse error)`](assert) {
assert.throws(() => {
compile('{{@1}}', {
moduleName: 'baz/foo-bar'
});
}, /Expecting 'ID'/);
assert.throws(() => {
compile('{{#if @1}}Yup{{/if}}', {
moduleName: 'baz/foo-bar'
});
}, /Expecting 'ID'/);
assert.throws(() => {
compile('{{input type=(if @1 "bar" "baz")}}', {
moduleName: 'baz/foo-bar'
});
}, /Expecting 'ID'/);
}
[`@test '@2' is de facto reserved (parse error)`](assert) {
assert.throws(() => {
compile('{{@2}}', {
moduleName: 'baz/foo-bar'
});
}, /Expecting 'ID'/);
assert.throws(() => {
compile('{{#if @2}}Yup{{/if}}', {
moduleName: 'baz/foo-bar'
});
}, /Expecting 'ID'/);
assert.throws(() => {
compile('{{input type=(if @2 "bar" "baz")}}', {
moduleName: 'baz/foo-bar'
});
}, /Expecting 'ID'/);
}
[`@test '@@' is de facto reserved (parse error)`](assert) {
assert.throws(() => {
compile('{{@@}}', {
moduleName: 'baz/foo-bar'
});
}, /Expecting 'ID'/);
assert.throws(() => {
compile('{{#if @@}}Yup{{/if}}', {
moduleName: 'baz/foo-bar'
});
}, /Expecting 'ID'/);
assert.throws(() => {
compile('{{input type=(if @@ "bar" "baz")}}', {
moduleName: 'baz/foo-bar'
});
}, /Expecting 'ID'/);
}
[`@test '@=' is de facto reserved (parse error)`](assert) {
assert.throws(() => {
compile('{{@=}}', {
moduleName: 'baz/foo-bar'
});
}, /Expecting 'ID'/);
assert.throws(() => {
compile('{{#if @=}}Yup{{/if}}', {
moduleName: 'baz/foo-bar'
});
}, /Expecting 'ID'/);
assert.throws(() => {
compile('{{input type=(if @= "bar" "baz")}}', {
moduleName: 'baz/foo-bar'
});
}, /Expecting 'ID'/);
}
[`@test '@!' is de facto reserved (parse error)`](assert) {
assert.throws(() => {
compile('{{@!}}', {
moduleName: 'baz/foo-bar'
});
}, /Expecting 'ID'/);
assert.throws(() => {
compile('{{#if @!}}Yup{{/if}}', {
moduleName: 'baz/foo-bar'
});
}, /Expecting 'ID'/);
assert.throws(() => {
compile('{{input type=(if @! "bar" "baz")}}', {
moduleName: 'baz/foo-bar'
});
}, /Expecting 'ID'/);
}
});
|
General-ITer/Flask-Introduction
|
day04/app/__init__.py
|
from flask import Flask
from .views import init_blue
from .ext import init_ext
from .settings import *
def create_app(enev):
app = Flask(__name__,template_folder=template_folder,static_folder=static_folder)
app.config.from_object(conf.get(enev))
init_ext(app)
init_blue(app)
return app
|
PareshGupta-WAL/mapbox-gl-native
|
platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/maps/widgets/MyLocationView.java
|
package com.mapbox.mapboxsdk.maps.widgets;
import android.animation.ValueAnimator;
import android.content.Context;
import android.graphics.Camera;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.PointF;
import android.graphics.PorterDuff;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.location.Location;
import android.os.Bundle;
import android.os.Parcelable;
import android.os.SystemClock;
import android.support.annotation.ColorInt;
import android.support.annotation.FloatRange;
import android.support.annotation.IntRange;
import android.support.annotation.NonNull;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;
import com.mapbox.mapboxsdk.camera.CameraPosition;
import com.mapbox.mapboxsdk.camera.CameraUpdateFactory;
import com.mapbox.mapboxsdk.constants.MyBearingTracking;
import com.mapbox.mapboxsdk.constants.MyLocationTracking;
import com.mapbox.mapboxsdk.geometry.LatLng;
import com.mapbox.mapboxsdk.location.LocationListener;
import com.mapbox.mapboxsdk.location.LocationServices;
import com.mapbox.mapboxsdk.maps.MapboxMap;
import com.mapbox.mapboxsdk.maps.Projection;
import java.lang.ref.WeakReference;
/**
* UI element overlaid on a map to show the user's location.
*/
public class MyLocationView extends View {
private MyLocationBehavior myLocationBehavior;
private MapboxMap mapboxMap;
private Projection projection;
private int[] contentPadding = new int[4];
private Location location;
private LatLng latLng;
private LatLng interpolatedLocation;
private LatLng previousLocation;
private long locationUpdateTimestamp;
private float gpsDirection;
private float previousDirection;
private float accuracy;
private Paint accuracyPaint;
private ValueAnimator locationChangeAnimator;
private ValueAnimator accuracyAnimator;
private ValueAnimator directionAnimator;
private ValueAnimator.AnimatorUpdateListener invalidateSelfOnUpdateListener =
new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animation) {
invalidate();
}
};
private Drawable foregroundDrawable;
private Drawable foregroundBearingDrawable;
private Drawable backgroundDrawable;
private int foregroundTintColor;
private int backgroundTintColor;
private Rect foregroundBounds;
private Rect backgroundBounds;
private int backgroundOffsetLeft;
private int backgroundOffsetTop;
private int backgroundOffsetRight;
private int backgroundOffsetBottom;
private Matrix matrix;
private Camera camera;
private PointF screenLocation;
// camera vars
private float bearing;
private float tilt;
@MyLocationTracking.Mode
private int myLocationTrackingMode;
@MyBearingTracking.Mode
private int myBearingTrackingMode;
private GpsLocationListener userLocationListener;
private CompassListener compassListener;
public MyLocationView(Context context) {
super(context);
init(context);
}
public MyLocationView(Context context, AttributeSet attrs) {
super(context, attrs);
init(context);
}
public MyLocationView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init(context);
}
private void init(Context context) {
if(isInEditMode()){
return;
}
setEnabled(false);
// setup LayoutParams
ViewGroup.LayoutParams lp = new ViewGroup.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT);
setLayoutParams(lp);
matrix = new Matrix();
camera = new Camera();
camera.setLocation(0, 0, -1000);
accuracyPaint = new Paint();
myLocationBehavior = new MyLocationBehaviorFactory().getBehavioralModel(MyLocationTracking.TRACKING_NONE);
compassListener = new CompassListener(context);
}
public final void setForegroundDrawables(Drawable defaultDrawable, Drawable bearingDrawable) {
if (defaultDrawable == null) {
return;
}
if (bearingDrawable == null) {
// if user only provided one resource
// use same for bearing mode
bearingDrawable = defaultDrawable.getConstantState().newDrawable();
}
if (backgroundDrawable == null) {
// if the user didn't provide a background resource we will use the foreground resource instead,
// we need to create a new drawable to handle tinting correctly
backgroundDrawable = defaultDrawable.getConstantState().newDrawable();
}
if (defaultDrawable.getIntrinsicWidth() != bearingDrawable.getIntrinsicWidth() || defaultDrawable.getIntrinsicHeight() != bearingDrawable.getIntrinsicHeight()) {
throw new RuntimeException("The dimensions from location and bearing drawables should be match");
}
foregroundDrawable = defaultDrawable;
foregroundBearingDrawable = bearingDrawable;
setForegroundDrawableTint(foregroundTintColor);
invalidateBounds();
}
public final void setForegroundDrawableTint(@ColorInt int color) {
if (color != Color.TRANSPARENT) {
foregroundTintColor = color;
if (foregroundDrawable != null) {
foregroundDrawable.mutate().setColorFilter(color, PorterDuff.Mode.SRC_IN);
}
if (foregroundBearingDrawable != null) {
foregroundBearingDrawable.mutate().setColorFilter(color, PorterDuff.Mode.SRC_IN);
}
}
invalidate();
}
public final void setShadowDrawable(Drawable drawable) {
setShadowDrawable(drawable, 0, 0, 0, 0);
}
public final void setShadowDrawable(Drawable drawable, int left, int top, int right, int bottom) {
if (drawable != null) {
backgroundDrawable = drawable;
}
backgroundOffsetLeft = left;
backgroundOffsetTop = top;
backgroundOffsetRight = right;
backgroundOffsetBottom = bottom;
setShadowDrawableTint(backgroundTintColor);
invalidateBounds();
}
public final void setShadowDrawableTint(@ColorInt int color) {
if (color != Color.TRANSPARENT) {
backgroundTintColor = color;
if (backgroundDrawable == null) {
return;
}
backgroundDrawable.mutate().setColorFilter(color, PorterDuff.Mode.SRC_IN);
}
invalidate();
}
public final void setAccuracyTint(@ColorInt int color) {
int alpha = accuracyPaint.getAlpha();
accuracyPaint.setColor(color);
accuracyPaint.setAlpha(alpha);
invalidate();
}
public final void setAccuracyAlpha(@IntRange(from = 0, to = 255) int alpha) {
accuracyPaint.setAlpha(alpha);
invalidate();
}
private void invalidateBounds() {
if (backgroundDrawable == null || foregroundDrawable == null || foregroundBearingDrawable == null) {
return;
}
int backgroundWidth = backgroundDrawable.getIntrinsicWidth();
int backgroundHeight = backgroundDrawable.getIntrinsicHeight();
int horizontalOffset = backgroundOffsetLeft - backgroundOffsetRight;
int verticalOffset = backgroundOffsetTop - backgroundOffsetBottom;
backgroundBounds = new Rect(-backgroundWidth / 2 + horizontalOffset, -backgroundHeight / 2 + verticalOffset, backgroundWidth / 2 + horizontalOffset, backgroundHeight / 2 + verticalOffset);
backgroundDrawable.setBounds(backgroundBounds);
int foregroundWidth = foregroundDrawable.getIntrinsicWidth();
int foregroundHeight = foregroundDrawable.getIntrinsicHeight();
foregroundBounds = new Rect(-foregroundWidth / 2, -foregroundHeight / 2, foregroundWidth / 2, foregroundHeight / 2);
foregroundDrawable.setBounds(foregroundBounds);
foregroundBearingDrawable.setBounds(foregroundBounds);
// invoke a new draw
invalidate();
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
if (location == null || foregroundBounds == null || backgroundBounds == null || accuracyAnimator == null || screenLocation == null) {
// Not ready yet
return;
}
final PointF pointF = screenLocation;
float metersPerPixel = (float) projection.getMetersPerPixelAtLatitude(location.getLatitude());
float accuracyPixels = (Float) accuracyAnimator.getAnimatedValue() / metersPerPixel / 2;
float maxRadius = getWidth() / 2;
accuracyPixels = accuracyPixels <= maxRadius ? accuracyPixels : maxRadius;
// put matrix in origin
matrix.reset();
// apply tilt to camera
camera.save();
camera.rotate(tilt, 0, bearing);
// map camera matrix on our matrix
camera.getMatrix(matrix);
//
if (myBearingTrackingMode != MyBearingTracking.NONE && directionAnimator != null) {
matrix.preRotate((Float) directionAnimator.getAnimatedValue());
}
// put matrix at location of MyLocationView
matrix.postTranslate(pointF.x, pointF.y);
// concat our matrix on canvas
canvas.concat(matrix);
// restore orientation from camera
camera.restore();
// draw circle
canvas.drawCircle(0, 0, accuracyPixels, accuracyPaint);
// draw shadow
if (backgroundDrawable != null) {
backgroundDrawable.draw(canvas);
}
// draw foreground
if (myBearingTrackingMode == MyBearingTracking.NONE) {
if (foregroundDrawable != null) {
foregroundDrawable.draw(canvas);
}
} else if (foregroundBearingDrawable != null && foregroundBounds != null) {
foregroundBearingDrawable.draw(canvas);
}
}
public void setTilt(@FloatRange(from = 0, to = 60.0f) double tilt) {
this.tilt = (float) tilt;
}
public void setBearing(double bearing) {
this.bearing = (float) bearing;
}
public void setCameraPosition(CameraPosition position) {
setTilt(position.tilt);
setBearing(position.bearing);
}
public void onPause() {
compassListener.onPause();
toggleGps(false);
}
public void onResume() {
if (myBearingTrackingMode == MyBearingTracking.COMPASS) {
compassListener.onResume();
}
if (isEnabled()) {
toggleGps(true);
}
}
public void update() {
if (isEnabled()) {
myLocationBehavior.invalidate();
} else {
setVisibility(View.INVISIBLE);
}
}
public void setMapboxMap(MapboxMap mapboxMap) {
this.mapboxMap = mapboxMap;
this.projection = mapboxMap.getProjection();
}
@Override
public void setEnabled(boolean enabled) {
super.setEnabled(enabled);
setVisibility(enabled ? View.VISIBLE : View.INVISIBLE);
toggleGps(enabled);
}
@Override
protected Parcelable onSaveInstanceState() {
Bundle bundle = new Bundle();
bundle.putParcelable("superState", super.onSaveInstanceState());
bundle.putFloat("tilt", tilt);
return bundle;
}
@Override
public void onRestoreInstanceState(Parcelable state){
if (state instanceof Bundle){
Bundle bundle = (Bundle) state;
tilt = bundle.getFloat("tilt");
state = bundle.getParcelable("superState");
}
super.onRestoreInstanceState(state);
}
/**
* Enabled / Disable GPS location updates along with updating the UI
*
* @param enableGps true if GPS is to be enabled, false if GPS is to be disabled
*/
private void toggleGps(boolean enableGps) {
LocationServices locationServices = LocationServices.getLocationServices(getContext());
if (enableGps) {
// Set an initial location if one available
Location lastLocation = locationServices.getLastLocation();
if (lastLocation != null) {
setLocation(lastLocation);
}
if (userLocationListener == null) {
userLocationListener = new GpsLocationListener(this);
}
locationServices.addLocationListener(userLocationListener);
} else {
// Disable location and user dot
location = null;
locationServices.removeLocationListener(userLocationListener);
}
locationServices.toggleGPS(enableGps);
}
public Location getLocation() {
return location;
}
public void setLocation(Location location) {
if (location == null) {
this.location = null;
return;
}
this.location = location;
myLocationBehavior.updateLatLng(location);
}
public void setMyBearingTrackingMode(@MyBearingTracking.Mode int myBearingTrackingMode) {
this.myBearingTrackingMode = myBearingTrackingMode;
if (myBearingTrackingMode == MyBearingTracking.COMPASS) {
compassListener.onResume();
} else {
compassListener.onPause();
if (myLocationTrackingMode == MyLocationTracking.TRACKING_FOLLOW) {
// always face north
gpsDirection = bearing;
setCompass(gpsDirection);
}
}
invalidate();
update();
}
public void setMyLocationTrackingMode(@MyLocationTracking.Mode int myLocationTrackingMode) {
this.myLocationTrackingMode = myLocationTrackingMode;
MyLocationBehaviorFactory factory = new MyLocationBehaviorFactory();
myLocationBehavior = factory.getBehavioralModel(myLocationTrackingMode);
if (myLocationTrackingMode != MyLocationTracking.TRACKING_NONE && location != null) {
// center map directly if we have a location fix
myLocationBehavior.updateLatLng(location);
mapboxMap.moveCamera(CameraUpdateFactory.newLatLng(new LatLng(location)));
}
invalidate();
update();
}
private void setCompass(float bearing) {
float oldDir = previousDirection;
if (directionAnimator != null) {
oldDir = (Float) directionAnimator.getAnimatedValue();
directionAnimator.end();
directionAnimator = null;
}
float newDir = bearing;
float diff = oldDir - newDir;
if (diff > 180.0f) {
newDir += 360.0f;
} else if (diff < -180.0f) {
newDir -= 360.f;
}
previousDirection = newDir;
directionAnimator = ValueAnimator.ofFloat(oldDir, newDir);
directionAnimator.setDuration(375);
directionAnimator.addUpdateListener(invalidateSelfOnUpdateListener);
directionAnimator.start();
}
public float getCenterX() {
return getX() + getMeasuredWidth() / 2;
}
public float getCenterY() {
return getY() + getMeasuredHeight() / 2;
}
public void setContentPadding(int[] padding) {
contentPadding = padding;
}
private static class GpsLocationListener implements LocationListener {
private WeakReference<MyLocationView> mUserLocationView;
public GpsLocationListener(MyLocationView myLocationView) {
mUserLocationView = new WeakReference<>(myLocationView);
}
/**
* Callback method for receiving location updates from LocationServices.
*
* @param location The new Location data
*/
@Override
public void onLocationChanged(Location location) {
MyLocationView locationView = mUserLocationView.get();
if (locationView != null) {
locationView.setLocation(location);
}
}
}
private class CompassListener implements SensorEventListener {
private SensorManager mSensorManager;
private Sensor mAccelerometer;
private Sensor mMagnetometer;
private boolean paused;
private float mCurrentDegree = 0f;
private float[] mOrientation = new float[3];
private float[] mGData = new float[3];
private float[] mMData = new float[3];
private float[] mR = new float[16];
private float[] mI = new float[16];
// Controls the sensor updateLatLng rate in milliseconds
private static final int UPDATE_RATE_MS = 500;
// Compass data
private long mCompassUpdateNextTimestamp = 0;
public CompassListener(Context context) {
mSensorManager = (SensorManager) context.getSystemService(Context.SENSOR_SERVICE);
mAccelerometer = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
mMagnetometer = mSensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD);
}
public void onResume() {
paused = false;
mSensorManager.registerListener(this, mAccelerometer, SensorManager.SENSOR_DELAY_GAME);
mSensorManager.registerListener(this, mMagnetometer, SensorManager.SENSOR_DELAY_GAME);
}
public void onPause() {
paused = true;
mSensorManager.unregisterListener(this, mAccelerometer);
mSensorManager.unregisterListener(this, mMagnetometer);
}
@Override
public void onSensorChanged(SensorEvent event) {
if (paused) {
return;
}
int type = event.sensor.getType();
if (type == Sensor.TYPE_ACCELEROMETER) {
System.arraycopy(event.values, 0, mGData, 0, 3);
} else if (type == Sensor.TYPE_MAGNETIC_FIELD) {
System.arraycopy(event.values, 0, mMData, 0, 3);
} else {
// we should not be here.
return;
}
long currentTime = SystemClock.elapsedRealtime();
if (currentTime < mCompassUpdateNextTimestamp) {
return;
}
SensorManager.getRotationMatrix(mR, mI, mGData, mMData);
SensorManager.getOrientation(mR, mOrientation);
setCompass(mCurrentDegree = (int) (mOrientation[0] * 180.0f / Math.PI));
mCompassUpdateNextTimestamp = currentTime + UPDATE_RATE_MS;
}
public float getCurrentDegree() {
return mCurrentDegree;
}
public boolean isPaused() {
return paused;
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
}
private class MarkerCoordinateAnimatorListener implements ValueAnimator.AnimatorUpdateListener {
private MyLocationBehavior behavior;
private double fromLat;
private double fromLng;
private double toLat;
private double toLng;
private MarkerCoordinateAnimatorListener(MyLocationBehavior myLocationBehavior, LatLng from, LatLng to) {
behavior = myLocationBehavior;
fromLat = from.getLatitude();
fromLng = from.getLongitude();
toLat = to.getLatitude();
toLng = to.getLongitude();
}
@Override
public void onAnimationUpdate(ValueAnimator animation) {
float frac = animation.getAnimatedFraction();
double latitude = fromLat + (toLat - fromLat) * frac;
double longitude = fromLng + (toLng - fromLng) * frac;
behavior.updateLatLng(latitude, longitude);
update();
}
}
private class MyLocationBehaviorFactory {
public MyLocationBehavior getBehavioralModel(@MyLocationTracking.Mode int mode) {
if (mode == MyLocationTracking.TRACKING_NONE) {
return new MyLocationShowBehavior();
} else {
return new MyLocationTrackingBehavior();
}
}
}
private abstract class MyLocationBehavior {
abstract void updateLatLng(@NonNull Location location);
public void updateLatLng(double lat, double lon) {
if (latLng != null) {
latLng.setLatitude(lat);
latLng.setLongitude(lon);
}
}
protected void updateAccuracy(@NonNull Location location) {
if (accuracyAnimator != null && accuracyAnimator.isRunning()) {
// use current accuracy as a starting point
accuracy = (Float) accuracyAnimator.getAnimatedValue();
accuracyAnimator.end();
}
accuracyAnimator = ValueAnimator.ofFloat(accuracy * 10, location.getAccuracy() * 10);
accuracyAnimator.setDuration(750);
accuracyAnimator.start();
accuracy = location.getAccuracy();
}
abstract void invalidate();
}
private class MyLocationTrackingBehavior extends MyLocationBehavior {
@Override
void updateLatLng(@NonNull Location location) {
if (latLng == null) {
// first location fix
latLng = new LatLng(location);
locationUpdateTimestamp = SystemClock.elapsedRealtime();
}
// updateLatLng timestamp
long previousUpdateTimeStamp = locationUpdateTimestamp;
locationUpdateTimestamp = SystemClock.elapsedRealtime();
// calculate animation duration
long locationUpdateDuration;
if (previousUpdateTimeStamp == 0) {
locationUpdateDuration = 0;
} else {
locationUpdateDuration = locationUpdateTimestamp - previousUpdateTimeStamp;
}
// calculate interpolated location
previousLocation = latLng;
latLng = new LatLng(location);
interpolatedLocation = new LatLng((latLng.getLatitude() + previousLocation.getLatitude()) / 2, (latLng.getLongitude() + previousLocation.getLongitude()) / 2);
// build new camera
CameraPosition.Builder builder = new CameraPosition.Builder().target(interpolatedLocation);
// add direction
if (myBearingTrackingMode == MyBearingTracking.GPS) {
if (location.hasBearing()) {
builder.bearing(location.getBearing());
}
gpsDirection = location.getBearing();
setCompass(gpsDirection);
} else if (myBearingTrackingMode == MyBearingTracking.COMPASS) {
if (!compassListener.isPaused()) {
builder.bearing(compassListener.getCurrentDegree());
setCompass(0);
}
}
// accuracy
updateAccuracy(location);
// ease to new camera position with a linear interpolator
mapboxMap.easeCamera(CameraUpdateFactory.newCameraPosition(builder.build()), (int) locationUpdateDuration, false /*linear interpolator*/);
}
@Override
void invalidate() {
int[] mapPadding = mapboxMap.getPadding();
float x = (getWidth() + mapPadding[0] - mapPadding[2]) / 2 + (contentPadding[0] - contentPadding[2]) / 2;
float y = (getHeight() - mapPadding[3] + mapPadding[1]) / 2 + (contentPadding[1] - contentPadding[3]) / 2;
screenLocation = new PointF(x, y);
MyLocationView.this.invalidate();
}
}
private class MyLocationShowBehavior extends MyLocationBehavior {
@Override
void updateLatLng(@NonNull final Location location) {
if (latLng == null) {
// first location update
latLng = new LatLng(location);
locationUpdateTimestamp = SystemClock.elapsedRealtime();
}
// update LatLng location
previousLocation = latLng;
latLng = new LatLng(location);
// update LatLng direction
if (myBearingTrackingMode == MyBearingTracking.GPS && location.hasBearing()) {
gpsDirection = location.getBearing();
setCompass(gpsDirection);
}
// update LatLng accuracy
updateAccuracy(location);
// calculate updateLatLng time + add some extra offset to improve animation
long previousUpdateTimeStamp = locationUpdateTimestamp;
locationUpdateTimestamp = SystemClock.elapsedRealtime();
long locationUpdateDuration = (long) ((locationUpdateTimestamp - previousUpdateTimeStamp) * 1.3);
// calculate interpolated entity
interpolatedLocation = new LatLng((latLng.getLatitude() + previousLocation.getLatitude()) / 2, (latLng.getLongitude() + previousLocation.getLongitude()) / 2);
// animate changes
if (locationChangeAnimator != null) {
locationChangeAnimator.end();
locationChangeAnimator = null;
}
locationChangeAnimator = ValueAnimator.ofFloat(0.0f, 1.0f);
locationChangeAnimator.setDuration((long) (locationUpdateDuration * 1.2));
locationChangeAnimator.addUpdateListener(new MarkerCoordinateAnimatorListener(this,
previousLocation, interpolatedLocation
));
locationChangeAnimator.start();
// use interpolated location as current location
latLng = interpolatedLocation;
}
@Override
void invalidate() {
screenLocation = projection.toScreenLocation(latLng);
MyLocationView.this.invalidate();
}
}
}
|
eikmadsen/rankdb
|
blobstore/maxsize_test.go
|
package blobstore_test
// Copyright 2019 Vivino. All rights reserved
//
// See LICENSE file for license details
import (
"bytes"
"context"
"crypto/rand"
"fmt"
"testing"
"time"
"github.com/Vivino/rankdb/blobstore"
"github.com/Vivino/rankdb/blobstore/bstest"
"github.com/Vivino/rankdb/blobstore/memstore"
"github.com/Vivino/rankdb/log"
"github.com/Vivino/rankdb/log/testlogger"
)
func TestNewMaxSizeStore(t *testing.T) {
ctx := log.WithLogger(context.Background(), testlogger.New(t))
testCases := []struct {
maxSize int
dataSize int
}{
{
maxSize: 2048,
dataSize: 2048 * 10,
},
{
maxSize: 2000,
dataSize: 2048 * 10,
},
{
maxSize: 2048,
dataSize: 2047,
},
{
maxSize: 2048,
dataSize: 2046,
},
{
maxSize: 2048,
dataSize: 2045,
},
{
maxSize: 2048,
dataSize: 0,
},
}
for _, test := range testCases {
t.Run(fmt.Sprintf("max%d-data%d", test.maxSize, test.dataSize), func(t *testing.T) {
store := memstore.NewMemStore()
tester := blobstore.NewTestStore(store)
var maxSize = test.maxSize
mss, err := blobstore.NewMaxSizeStore(tester, maxSize)
if err != nil {
t.Fatal(err)
}
var data = make([]byte, test.dataSize)
const testSet = "test-set"
const testKey = "test-key"
_, _ = rand.Read(data)
tester.SetCallback = func(set, key string, b []byte) {
if set != testSet {
t.Errorf("set mismatch, %q (got) != %q (want)", set, testSet)
}
if len(b) > maxSize {
t.Errorf("size too big, %v (got) > %v (want)", len(b), maxSize)
}
if !t.Failed() {
t.Logf("blob %q/%q %v bytes, ok", set, key, len(b))
}
}
err = mss.Set(ctx, testSet, testKey, data)
if err != nil {
t.Fatal(err)
}
read, err := mss.Get(ctx, testSet, testKey)
if err != nil {
t.Fatal(err)
}
if !bytes.Equal(data, read) {
t.Fatal("bytes mismatch")
}
t.Log("Read back ok")
err = mss.Delete(ctx, testSet, testKey)
if err != nil {
t.Fatal(err)
}
stored := store.Dir(testSet)
if len(stored) != 0 {
t.Error("failed to delete elements: ", stored)
}
if !t.Failed() {
t.Log("Items deleted")
}
// Test overwriting with shorter.
err = mss.Set(ctx, testSet, testKey, data)
if err != nil {
t.Fatal(err)
}
err = mss.Set(ctx, testSet, testKey, data[:len(data)/2])
if err != nil {
t.Fatal(err)
}
err = mss.Delete(ctx, testSet, testKey)
if err != nil {
t.Fatal(err)
}
stored = store.Dir(testSet)
if len(stored) != 0 {
t.Error("failed to delete elements: ", stored)
}
if !t.Failed() {
t.Log("Items deleted (after smaller)")
}
})
}
}
func TestMaxSizeStoreGen(t *testing.T) {
t.Parallel()
logger := testlogger.New(t)
ctx := log.WithLogger(context.Background(), logger)
m := memstore.NewMemStore()
mss, err := blobstore.NewMaxSizeStore(m, bstest.MaxBlobSize/4)
if err != nil {
t.Fatal(err)
}
st := bstest.NewTest(mss, t)
st.All(ctx)
}
func TestMaxSizeStoreLazy(t *testing.T) {
t.Parallel()
logger := testlogger.New(t)
ctx := log.WithLogger(context.Background(), logger)
m := memstore.NewMemStore()
mss, err := blobstore.NewMaxSizeStore(m, bstest.MaxBlobSize/4)
if err != nil {
t.Fatal(err)
}
ls, err := blobstore.NewLazySaver(mss, blobstore.WithLazySaveOption.SaveTimeout(time.Millisecond))
if err != nil {
t.Fatal(err)
}
st := bstest.NewTest(ls, t)
st.All(ctx)
}
func TestMaxSizeStoreRetryErrors(t *testing.T) {
t.Parallel()
logger := testlogger.New(t)
ctx := log.WithLogger(context.Background(), logger)
m := memstore.NewMemStore()
ts := blobstore.NewTestStore(m)
// Fail 15% of the time.
ts.FailGet(blobstore.TestFailPct(15, 1337))
ts.FailSet(blobstore.TestFailPct(15, 13370))
ts.FailDelete(blobstore.TestFailPct(15, 133700))
rs, err := blobstore.NewRetryStore(ts)
if err != nil {
t.Fatal(err)
}
mss, err := blobstore.NewMaxSizeStore(rs, bstest.MaxBlobSize/4)
if err != nil {
t.Fatal(err)
}
st := bstest.NewTest(mss, t)
st.All(ctx)
}
|
bauman/clips-rules-rebuild
|
clipspy-1.0.0/clips/clips_build.py
|
<gh_stars>0
# Copyright (c) 2016-2021, <NAME>
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# 1. Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
# 3. Neither the name of the copyright holder 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 HOLDER 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.
from cffi import FFI
ffibuilder = FFI()
CLIPS_SOURCE = """
#include <clips.h>
/* Return true if the template is implied. */
bool ImpliedDeftemplate(Deftemplate *template)
{
return template->implied;
}
/* User Defined Functions support. */
static void python_function(Environment *env, UDFContext *udfc, UDFValue *out);
int DefinePythonFunction(Environment *environment)
{
return AddUDF(
environment, "python-function",
NULL, UNBOUNDED, UNBOUNDED, NULL,
python_function, "python_function", NULL);
}
"""
with open("lib/clips.cdef") as cdef_file:
CLIPS_CDEF = cdef_file.read()
ffibuilder.set_source("_clips",
CLIPS_SOURCE,
libraries=["clips"],
include_dirs=["../core-6.40/"])
ffibuilder.cdef(CLIPS_CDEF)
if __name__ == "__main__":
ffibuilder.compile(verbose=True)
|
smagill/opensphere-desktop
|
open-sphere-plugins/my-places/src/main/java/io/opensphere/myplaces/importer/DataElementPointExporter.java
|
package io.opensphere.myplaces.importer;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.EventQueue;
import java.text.SimpleDateFormat;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import javax.swing.BorderFactory;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import org.apache.commons.lang3.StringUtils;
import io.opensphere.core.Toolbox;
import io.opensphere.core.control.action.MenuOption;
import io.opensphere.core.export.ExportException;
import io.opensphere.core.model.Altitude.ReferenceLevel;
import io.opensphere.core.model.time.TimeSpan;
import io.opensphere.core.preferences.ListToolPreferences;
import io.opensphere.core.util.AwesomeIconSolid;
import io.opensphere.core.util.MemoizingSupplier;
import io.opensphere.core.util.collections.New;
import io.opensphere.core.util.lang.Pair;
import io.opensphere.core.util.swing.EventQueueUtilities;
import io.opensphere.core.util.swing.GenericFontIcon;
import io.opensphere.core.util.swing.input.ViewPanel;
import io.opensphere.mantle.data.DataTypeInfo;
import io.opensphere.mantle.data.element.DataElement;
import io.opensphere.mantle.data.element.MapDataElement;
import io.opensphere.mantle.data.geom.MapGeometrySupport;
import io.opensphere.mantle.data.geom.MapLocationGeometrySupport;
import io.opensphere.mantle.mp.MapAnnotationPointRegistry;
import io.opensphere.mantle.mp.MutableMapAnnotationPoint;
import io.opensphere.mantle.mp.event.impl.MapAnnotationCreatedEvent;
import io.opensphere.mantle.mp.impl.DefaultMapAnnotationPoint;
import io.opensphere.mantle.util.MantleToolboxUtils;
import io.opensphere.mantle.util.TimeSpanUtility;
/**
* An exporter that creates points from {@link DataElement}s.
*/
public class DataElementPointExporter extends AbstractDataElementExporter
{
/** The name of the command / menu option to save to places. */
private static final String SAVE_TO_PLACES_COMMAND = "Save to Places...";
/** The none string. */
private static final String NONE = "NONE";
/** The map annotation point registry. */
private MapAnnotationPointRegistry myMapAnnotationPointRegistry;
@Override
public MenuOption getMenuOption()
{
return new MenuOption(SAVE_TO_PLACES_COMMAND, SAVE_TO_PLACES_COMMAND, "Creates new places from the selected features",
new GenericFontIcon(AwesomeIconSolid.MAP_MARKER_ALT, Color.WHITE));
}
@Override
public void setToolbox(Toolbox toolbox)
{
super.setToolbox(toolbox);
myMapAnnotationPointRegistry = MantleToolboxUtils.getMantleToolbox(toolbox).getMapAnnotationPointRegistry();
}
@Override
protected void export(DataTypeInfo dataType, Collection<? extends MapDataElement> elements) throws ExportException
{
if (!acceptSize(elements.size()))
{
return;
}
Supplier<Pair<String, String>> titleAndDesc = new MemoizingSupplier<>(
() -> EventQueueUtilities.happyOnEdt(() -> getTitleAndDescription(dataType)));
List<MutableMapAnnotationPoint> points = elements.stream()
.filter(e -> e.getMapGeometrySupport() instanceof MapLocationGeometrySupport)
.map(e -> createPoint(e, titleAndDesc)).collect(Collectors.toList());
if (!points.isEmpty())
{
if (points.get(0) != null)
{
getToolbox().getEventManager().publishEvent(new MapAnnotationCreatedEvent(this, points));
}
// else the user cancelled
}
else
{
throw new ExportException("The selected data do not contain any points.");
}
}
/**
* Creates a map point from the data element.
*
* @param dataElement the data element
* @param titleAndDesc the title/description supplier
* @return the map point
*/
private MutableMapAnnotationPoint createPoint(MapDataElement dataElement, Supplier<Pair<String, String>> titleAndDesc)
{
Pair<String, String> pair = titleAndDesc.get();
if (pair == null)
{
return null;
}
String title = getValue(dataElement, pair.getFirstObject());
if (StringUtils.isBlank(title))
{
title = "Untitled";
}
String desc = getValue(dataElement, pair.getSecondObject());
if (NONE.equals(desc))
{
desc = null;
}
return createDefaultMapAnnotationPoint(dataElement, title, desc);
}
/**
* Creates a DefaultMapAnnotationPoint.
*
* @param mapElement the map data element
* @param title the title
* @param desc the description
* @return the DefaultMapAnnotationPoint
*/
private DefaultMapAnnotationPoint createDefaultMapAnnotationPoint(MapDataElement mapElement, String title, String desc)
{
DefaultMapAnnotationPoint mp = new DefaultMapAnnotationPoint(myMapAnnotationPointRegistry.getUserDefaultPoint());
MapGeometrySupport mgs = mapElement.getMapGeometrySupport();
if (mgs instanceof MapLocationGeometrySupport)
{
MapLocationGeometrySupport mlgs = (MapLocationGeometrySupport)mgs;
mp.setLat(mlgs.getLocation().getLatD(), this);
mp.setLon(mlgs.getLocation().getLonD(), this);
mp.setTitle(title, this);
mp.getAnnoSettings().setDotOn(true, this);
mp.setVisible(true, this);
if (desc != null)
{
mp.setDescription(desc, this);
}
if (mlgs.getLocation().getAltitudeReference() == ReferenceLevel.ELLIPSOID)
{
mp.setAltitude(mlgs.getLocation().getAltM(), null);
}
}
return mp;
}
/**
* Gets the title and description from the user.
*
* @param dataType the data type
* @return the title and description pair
*/
private Pair<String, String> getTitleAndDescription(DataTypeInfo dataType)
{
assert EventQueue.isDispatchThread();
List<String> columns = New.list(dataType.getMetaDataInfo().getKeyNames());
JComboBox<String> titleChoiceCB = new JComboBox<>(columns.toArray(new String[columns.size()]));
if (columns.contains("TITLE"))
{
titleChoiceCB.setSelectedItem("TITLE");
}
columns.add(0, NONE);
JComboBox<String> descChoiceCB = new JComboBox<>(columns.toArray(new String[columns.size()]));
ViewPanel cfgPanel = new ViewPanel();
cfgPanel.addLabelComponent("Title Column:", titleChoiceCB);
cfgPanel.addLabelComponent("Description Column:", descChoiceCB);
cfgPanel.setBorder(BorderFactory.createEmptyBorder(8, 0, 0, 0));
JPanel questionPanel = new JPanel(new BorderLayout());
questionPanel.add(new JLabel("Please choose title and description columns:"), BorderLayout.NORTH);
questionPanel.add(cfgPanel, BorderLayout.CENTER);
int result = JOptionPane.showConfirmDialog(getToolbox().getUIRegistry().getMainFrameProvider().get(), questionPanel,
"Map Point Creation Options", JOptionPane.OK_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE);
if (result == JOptionPane.OK_OPTION)
{
String titleColumn = (String)titleChoiceCB.getSelectedItem();
String descColumn = (String)descChoiceCB.getSelectedItem();
return new Pair<>(titleColumn, descColumn);
}
return null;
}
/**
* Gets the value.
*
* @param dataElement the map data element
* @param column the column
* @return the value
*/
private String getValue(MapDataElement dataElement, String column)
{
String timeKey = dataElement.getDataTypeInfo().getMetaDataInfo().getTimeKey();
Object value = Objects.equals(timeKey, column) ? dataElement.getTimeSpan() : dataElement.getMetaData().getValue(column);
return convertToString(value);
}
/**
* Convert to string.
*
* @param value the value
* @return the string
*/
private String convertToString(Object value)
{
if (value == null)
{
return null;
}
else if (value instanceof TimeSpan || value instanceof Date)
{
int timePrecision = getToolbox().getPreferencesRegistry().getPreferences(ListToolPreferences.class)
.getInt(ListToolPreferences.LIST_TOOL_TIME_PRECISION_DIGITS, 0);
SimpleDateFormat format = ListToolPreferences.getSimpleDateFormatForPrecision(timePrecision);
return value instanceof TimeSpan ? TimeSpanUtility.formatTimeSpan(format, (TimeSpan)value) : format.format(value);
}
else
{
return value.toString();
}
}
}
|
miniworld-project/miniworld_core
|
miniworld/model/network/backends/EmulationNodeNetworkBackend.py
|
from io import StringIO
from miniworld import config
from miniworld.Scenario import scenario_config
from miniworld.log import get_node_logger
from miniworld.model.network.backends.NetworkMixin import NetworkMixin
from miniworld.model.network.interface import Interfaces, Interface
from miniworld.util import NetUtil
__author__ = '<NAME>'
def get_cmd_rename_mgmt_interface():
# TODO: #63: generic solution? works only if image has iproute2 installed :/
CMD_RENAME_MANAGEMENT_INTERFACE = """
# name management interface
last_eth=$(ls -1 /sys/class/net/|grep {iface_prefix}|tail -n 1)
ip link set name {mgmt_iface} $last_eth
ifconfig {mgmt_iface} up
""".format(mgmt_iface=config.get_bridge_tap_name(), iface_prefix=scenario_config.get_network_links_nic_prefix())
return CMD_RENAME_MANAGEMENT_INTERFACE
class EmulationNodeNetworkBackend(NetworkMixin):
"""
This class enables each :py:class:`.EmulationNode` to handle network backend stuff differently by encapsulating these methods into an extra class.
For example the base :py:class:`.NetworkBackendEmulationNode`.
Attributes
----------
network_backend_boot_strapper : NetworkBackendBootStrapper
"""
def __init__(self, network_backend_bootstrapper, node_id,
# network
interfaces=None, management_switch=False):
super(EmulationNodeNetworkBackend, self).__init__(network_backend_bootstrapper)
self.node_id = node_id
self.nlog = get_node_logger(self.node_id)
if interfaces is None:
self.interfaces = Interfaces.Interfaces.factory([Interface.Mesh])
else:
self.interfaces = interfaces
if management_switch:
self.interfaces.append(Interfaces.Interfaces.factory([Interface.Management])[0])
# let the management interface be the last one
self.interfaces.sort()
def _start(self, *args, **kwargs):
pass
def reset(self):
pass
#############################################################
# EmulationNode notifications
#############################################################
# TODO: DOC
def after_pre_shell_commands(self, emulation_node):
pass
def do_network_config_after_pre_shell_commands(self, emulation_node):
# Rename Management Interface and set ip
if config.is_management_switch_enabled():
emulation_node.virtualization_layer.run_commands_eager(StringIO(get_cmd_rename_mgmt_interface()))
self.nic_mgmt_ipv4_config(emulation_node)
self.nic_ipv4_config(emulation_node)
#########################################
# Network Config
#########################################
# TODO: DOC, sublcass methods
def _nic_ipv4_config(self, emulation_node):
for _if in self.interfaces.filter_normal_interfaces():
idx = self.interfaces.index(_if)
ip = _if.get_ip(emulation_node.id)
netmask = _if.get_netmask()
cmd_ip_change = NetUtil.get_ip_addr_change_cmd(
"%s%s" % (scenario_config.get_network_links_nic_prefix(), idx),
ip, netmask)
emulation_node.virtualization_layer.run_commands_eager(StringIO(cmd_ip_change))
def _nic_mgmt_ipv4_config(self, emulation_node):
for _if in self.interfaces.filter_mgmt():
ip = _if.get_ip(emulation_node.id)
netmask = _if.get_netmask()
# TODO: #63: we dont know if renaming worked, therefore try to rename both ethX and mgmt
cmd_ip_change = NetUtil.get_ip_addr_change_cmd(config.get_bridge_tap_name(), ip, netmask)
emulation_node.virtualization_layer.run_commands_eager(StringIO(cmd_ip_change))
def nic_ipv4_config(self, emulation_node):
pass
def nic_mgmt_ipv4_config(self, emulation_node):
self._nic_mgmt_ipv4_config(emulation_node)
|
veg/flea-web-app
|
tests/unit/utils/utils-test.js
|
<gh_stars>1-10
import { test } from 'ember-qunit';
import { refToAlnCoords, alignmentTicks, zeroIndex } from 'flea-web-app/utils/utils';
test("it computes alignmentTicks", function(assert){
var data = [2, 3, 4, 5, 6, 7, 8, 9, 11, 12, 13];
var a2r = data.map(c => zeroIndex(c));
var stop = 14;
var r2a = refToAlnCoords(a2r, stop)[0];
var tick = 5;
var result = alignmentTicks(a2r, r2a, tick);
var expected = [0, 3, 8, 10];
assert.deepEqual(result, expected);
assert.equal(a2r[result[0]], zeroIndex(2));
assert.equal(a2r[result[1]], zeroIndex(5));
assert.equal(a2r[result[2]], zeroIndex(11));
assert.equal(a2r[result[3]], zeroIndex(13));
});
|
Richard-Cao226/java
|
src/com/codefortomorrow/advanced/chapter14/practice/account/PasswordMismatchException.java
|
package com.codefortomorrow.advanced.chapter14.practice.account;
public class PasswordMismatchException {}
|
davidraditya/OAI-Powder
|
cmake_targets/lte_build_oai/build/CMakeFiles/Rel14/MeasResultCSI-RS-List-r12.c
|
/*
* Generated by asn1c-0.9.24 (http://lionet.info/asn1c)
* From ASN.1 module "EUTRA-RRC-Definitions"
* found in "fixed_grammar.asn"
* `asn1c -gen-PER`
*/
#include "MeasResultCSI-RS-List-r12.h"
static asn_per_constraints_t asn_PER_type_MeasResultCSI_RS_List_r12_constr_1 GCC_NOTUSED = {
{ APC_UNCONSTRAINED, -1, -1, 0, 0 },
{ APC_CONSTRAINED, 3, 3, 1, 8 } /* (SIZE(1..8)) */,
0, 0 /* No PER value map */
};
static asn_TYPE_member_t asn_MBR_MeasResultCSI_RS_List_r12_1[] = {
{ ATF_POINTER, 0, 0,
(ASN_TAG_CLASS_UNIVERSAL | (16 << 2)),
0,
&asn_DEF_MeasResultCSI_RS_r12,
0, /* Defer constraints checking to the member type */
0, /* No PER visible constraints */
0,
""
},
};
static ber_tlv_tag_t asn_DEF_MeasResultCSI_RS_List_r12_tags_1[] = {
(ASN_TAG_CLASS_UNIVERSAL | (16 << 2))
};
static asn_SET_OF_specifics_t asn_SPC_MeasResultCSI_RS_List_r12_specs_1 = {
sizeof(struct MeasResultCSI_RS_List_r12),
offsetof(struct MeasResultCSI_RS_List_r12, _asn_ctx),
0, /* XER encoding is XMLDelimitedItemList */
};
asn_TYPE_descriptor_t asn_DEF_MeasResultCSI_RS_List_r12 = {
"MeasResultCSI-RS-List-r12",
"MeasResultCSI-RS-List-r12",
SEQUENCE_OF_free,
SEQUENCE_OF_print,
SEQUENCE_OF_constraint,
SEQUENCE_OF_decode_ber,
SEQUENCE_OF_encode_der,
SEQUENCE_OF_decode_xer,
SEQUENCE_OF_encode_xer,
SEQUENCE_OF_decode_uper,
SEQUENCE_OF_encode_uper,
SEQUENCE_OF_decode_aper,
SEQUENCE_OF_encode_aper,
SEQUENCE_OF_compare,
0, /* Use generic outmost tag fetcher */
asn_DEF_MeasResultCSI_RS_List_r12_tags_1,
sizeof(asn_DEF_MeasResultCSI_RS_List_r12_tags_1)
/sizeof(asn_DEF_MeasResultCSI_RS_List_r12_tags_1[0]), /* 1 */
asn_DEF_MeasResultCSI_RS_List_r12_tags_1, /* Same as above */
sizeof(asn_DEF_MeasResultCSI_RS_List_r12_tags_1)
/sizeof(asn_DEF_MeasResultCSI_RS_List_r12_tags_1[0]), /* 1 */
&asn_PER_type_MeasResultCSI_RS_List_r12_constr_1,
asn_MBR_MeasResultCSI_RS_List_r12_1,
1, /* Single element */
&asn_SPC_MeasResultCSI_RS_List_r12_specs_1 /* Additional specs */
};
|
xuwaters/cp-algorithms
|
09-graphs/08-flows/01-max-flow/max_flow.go
|
package max_flow
//
//
// for each edge: used / capacity
//
// adj[i][j] = capacity
// adj[j][i] = used
//
// loop: find augment path from S to T
//
// if used < capacity: can walk in direction of edge
// if used > 0 : can walk in reverse direction of edge
//
//
// int n;
// vector<vector<int>> capacity;
// vector<vector<int>> adj;
//
// int bfs(int s, int t, vector<int>& parent) {
// fill(parent.begin(), parent.end(), -1);
// parent[s] = -2;
// queue<pair<int, int>> q;
// q.push({s, INF});
//
// while (!q.empty()) {
// int cur = q.front().first;
// int flow = q.front().second;
// q.pop();
//
// for (int next : adj[cur]) {
// if (parent[next] == -1 && capacity[cur][next]) {
// parent[next] = cur;
// int new_flow = min(flow, capacity[cur][next]);
// if (next == t)
// return new_flow;
// q.push({next, new_flow});
// }
// }
// }
//
// return 0;
// }
//
// int maxflow(int s, int t) {
// int flow = 0;
// vector<int> parent(n);
// int new_flow;
// while (new_flow = bfs(s, t, parent)) {
// flow += new_flow;
// int cur = t;
// while (cur != s) {
// int prev = parent[cur];
// capacity[prev][cur] -= new_flow;
// capacity[cur][prev] += new_flow;
// cur = prev;
// }
// }
// return flow;
// }
//
|
johngmyers/jmxutils
|
src/test/java/org/weakref/jmx/TestInheritanceBase.java
|
/**
* Copyright 2009 <NAME>
*
* 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.weakref.jmx;
import java.lang.reflect.Method;
import java.util.Map;
import org.testng.Assert;
import org.testng.annotations.Test;
public abstract class TestInheritanceBase
{
protected final Class<?> target;
protected final Class<?> source;
/**
* @param target class to resolve
* @param source class providing the annotation
*/
TestInheritanceBase(Class<?> target, Class<?> source)
{
this.target = target;
this.source = source;
}
public Class<?> getTargetClass()
{
return target;
}
public Method getTargetMethod() throws NoSuchMethodException
{
return target.getMethod("method");
}
public Method expected() throws NoSuchMethodException
{
return source.getDeclaredMethod("method");
}
@Test
public void testResolver() throws NoSuchMethodException
{
Map<Method, Method> map = AnnotationUtils.findManagedMethods(getTargetClass());
Method annotatedMethod = map.get(getTargetMethod());
Assert.assertEquals(annotatedMethod, expected());
}
}
|
ranarango/fuegos-orinoquia
|
src/04_exploration/02_compute_fire_return_interval.py
|
# -----------------------------------------------------------------------
# Author: <NAME>
#
# Purpose: Computes the return interval pixel-wise for each window. The
# return interval is computed following the equation: RI = (n + 1) / m,
# where n corresponds to the number of years on record and m corresponds
# to the number of burned pixels along the time dimension.
# -----------------------------------------------------------------------
import os
import numpy as np
import xarray as xr
from osgeo import gdalconst
from src.utils.constants import REGIONS, NODATA_VALUE
from src.utils.functions import array_to_raster
if __name__ == "__main__":
# Project's root
os.chdir("../..")
output_folder = "data/tif/fri"
if not os.path.exists(output_folder):
os.makedirs(output_folder)
for region in REGIONS:
window_ds = xr.open_dataset(
f"data/nc/MODIS/MCD64A1/MCD64A1_500m_{region['name']}.nc",
mask_and_scale=False,
)
# Compute the number of years from the first to the last date of
# recorded data in the NetCDF4 file.
nyears = np.diff(window_ds.time.dt.year[[0, -1]])
# Compute per pixel number of burn events (i.e. number of times
# the pixel's Burn Date value is greater than 0). The result is
# masked to avoid divisions by zero in NoData pixels or pixels
# where no burn events were found.
burn_events = (window_ds["Burn_Date"] > 0).sum(axis=0)
burn_events = np.ma.array(burn_events, mask=(burn_events == 0))
# Compute return interval with the (n + 1) / n equation and fill
# the masked pixels with a predefined NoData value.
return_interval = (nyears + 1) / burn_events
return_interval = return_interval.filled(NODATA_VALUE)
# Create output GeoTIFF file using metadata from the NetCDF4
# file.
save_to = os.path.join(output_folder, f"RI_500m_{region['name']}.tif")
sr = window_ds.rio.crs.to_wkt()
gt = window_ds.rio.transform()
array_to_raster(
return_interval,
save_to,
sr,
gt,
gdtype=gdalconst.GDT_Float32,
driver="GTiff",
nd_val=NODATA_VALUE,
options=["COMPRESS=LZW"],
)
|
smith-30/algos
|
atcoder/contest/20190908/c/main.go
|
package main
import (
"bufio"
"fmt"
"math"
"os"
"strconv"
)
var sc = bufio.NewScanner(os.Stdin)
func init() {
sc.Split(bufio.ScanWords)
}
func nextInt() int {
sc.Scan()
i, e := strconv.ParseInt(sc.Text(), 10, 64)
if e != nil {
panic(e)
}
return int(i)
}
func main() {
n := nextInt()
a := make([]int, 0, n)
bb := make([]int, n-1)
for index := 0; index < n-1; index++ {
bb[index] = nextInt()
}
f := bb[0]
ff := bb[1:]
a = append(a, f)
for _, item := range ff {
a = append(a, Min(item, f))
f = item
}
a = append(a, f)
// f := bb[n-2]
// a = append(a, f)
// ff := bb[0 : n-2]
// fmt.Printf("%#v\n", ff)
// for _, item := range ff {
// a = append(a, Min(item, f))
// f = item
// }
// a = append(a, f)
var re int
for _, item := range a {
re += item
}
fmt.Println(re)
}
func Min(nums ...int) int {
if len(nums) == 0 {
panic("function min() requires at least one argument.")
}
res := nums[0]
for i := 0; i < len(nums); i++ {
res = int(math.Min(float64(res), float64(nums[i])))
}
return res
}
func Max(nums ...int) int {
if len(nums) == 0 {
panic("function max() requires at least one argument.")
}
res := nums[0]
for i := 0; i < len(nums); i++ {
res = int(math.Max(float64(res), float64(nums[i])))
}
return res
}
|
pjshea/bluebox-ng
|
example/mapPing.js
|
#!/usr/bin/env node
/*
Copyright <NAME> <<EMAIL>>
This code may only be used under the MIT license found at
https://opensource.org/licenses/MIT.
*/
'use strict';
const Bluebox = require('../');
const bBox = new Bluebox();
bBox.events.on('info', (info) => {
/* eslint-disable no-console */
console.log('Event with extra info:');
console.log(info);
});
bBox.run('gather/network/map/ping', { rhosts: '192.168.0.0/24' })
.then((res) => {
console.log('Result:');
console.log(res);
})
.catch((err) => {
console.log('Error:');
console.log(err);
/* eslint-enable no-console */
});
|
ktotheoz/pixellight
|
Base/PLRenderer/include/PLRenderer/Renderer/SamplerStates.h
|
/*********************************************************\
* File: SamplerStates.h *
*
* Copyright (C) 2002-2013 The PixelLight Team (http://www.pixellight.org/)
*
* This file is part of PixelLight.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software
* and associated documentation files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or
* substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
* BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
\*********************************************************/
#ifndef __PLRENDERER_SAMPLERSTATES_H__
#define __PLRENDERER_SAMPLERSTATES_H__
#pragma once
//[-------------------------------------------------------]
//[ Includes ]
//[-------------------------------------------------------]
#include <PLCore/Base/Object.h>
#include "PLRenderer/PLRenderer.h"
#include "PLRenderer/Renderer/Types.h"
//[-------------------------------------------------------]
//[ Namespace ]
//[-------------------------------------------------------]
namespace PLRenderer {
//[-------------------------------------------------------]
//[ Classes ]
//[-------------------------------------------------------]
/**
* @brief
* Sampler states RTTI wrapper class
*/
class SamplerStates : public PLCore::Object {
//[-------------------------------------------------------]
//[ RTTI interface ]
//[-------------------------------------------------------]
pl_class(PLRENDERER_RTTI_EXPORT, SamplerStates, "PLRenderer", PLCore::Object, "Sampler states RTTI wrapper class")
// Attributes
// Address modes
pl_attribute(AddressU, pl_enum_type(TextureAddressing::Enum), TextureAddressing::Wrap, ReadWrite, GetSet, "Texture-address mode for the u/s coordinate", "")
pl_attribute(AddressV, pl_enum_type(TextureAddressing::Enum), TextureAddressing::Wrap, ReadWrite, GetSet, "Texture-address mode for the v/t coordinate", "")
pl_attribute(AddressW, pl_enum_type(TextureAddressing::Enum), TextureAddressing::Wrap, ReadWrite, GetSet, "Texture-address mode for the w/r coordinate", "")
// Filter
pl_attribute(MagFilter, pl_enum_type(TextureFiltering::Enum), TextureFiltering::Linear, ReadWrite, GetSet, "Magnification filter", "")
pl_attribute(MinFilter, pl_enum_type(TextureFiltering::Enum), TextureFiltering::Linear, ReadWrite, GetSet, "Minification filter", "")
pl_attribute(MipFilter, pl_enum_type(TextureFiltering::Enum), TextureFiltering::Linear, ReadWrite, GetSet, "Mipmap filter to use during minification", "")
// Filter
pl_attribute(MipmapLODBias, float, 0.0f, ReadWrite, GetSet, "Mipmap level of detail (LOD) bias", "")
pl_attribute(MaxMapLevel, PLCore::uint32, 1000, ReadWrite, GetSet, "LOD index of largest map to use. Values range from 0 to (n-1) where 0 is the largest", "")
pl_attribute(MaxAnisotropy, PLCore::uint32, 1, ReadWrite, GetSet, "Maximum anisotropy", "")
pl_class_end
//[-------------------------------------------------------]
//[ Public RTTI get/set functions ]
//[-------------------------------------------------------]
public:
// Address modes
inline TextureAddressing::Enum GetAddressU() const;
inline void SetAddressU(TextureAddressing::Enum nValue);
inline TextureAddressing::Enum GetAddressV() const;
inline void SetAddressV(TextureAddressing::Enum nValue);
inline TextureAddressing::Enum GetAddressW() const;
inline void SetAddressW(TextureAddressing::Enum nValue);
// Filter
inline TextureFiltering::Enum GetMagFilter() const;
inline void SetMagFilter(TextureFiltering::Enum nValue);
inline TextureFiltering::Enum GetMinFilter() const;
inline void SetMinFilter(TextureFiltering::Enum nValue);
inline TextureFiltering::Enum GetMipFilter() const;
inline void SetMipFilter(TextureFiltering::Enum nValue);
// Filter
inline float GetMipmapLODBias() const;
inline void SetMipmapLODBias(float fValue);
inline PLCore::uint32 GetMaxMapLevel() const;
inline void SetMaxMapLevel(int nValue);
inline PLCore::uint32 GetMaxAnisotropy() const;
inline void SetMaxAnisotropy(PLCore::uint32 nValue);
//[-------------------------------------------------------]
//[ Public functions ]
//[-------------------------------------------------------]
public:
/**
* @brief
* Constructor
*/
PLRENDERER_API SamplerStates();
/**
* @brief
* Copy constructor
*
* @param[in] cSource
* Source to copy from
*/
PLRENDERER_API SamplerStates(const SamplerStates &cSource);
/**
* @brief
* Destructor
*/
PLRENDERER_API virtual ~SamplerStates();
/**
* @brief
* Retrieves a sampler-state value
*
* @param[in] nState
* State variable that is being queried. This parameter can
* be any member of the sampler enumerated type.
*
* @return
* The value of the queried sampler state variable
*/
inline PLCore::uint32 Get(Sampler::Enum nState) const;
/**
* @brief
* Sets a single sampler-state parameter
*
* @param[in] nState
* State variable that is being modified. This parameter
* can be any member of the sampler enumerated type.
* @param[in] nValue
* New value for the sampler state to be set. The meaning of
* this parameter is dependent on the value specified for nState.
* For example, if nState is Sampler::AddressU, the second parameter
* must be one member of the Sampler::AddressU enumerated type. (e.g. TextureAddressing::Wrap)
* You can also set the value to unknown - then this state is ignored.
*
* @return
* 'true' if all went fine, else 'false'
*/
inline bool Set(Sampler::Enum nState, PLCore::uint32 nValue);
/**
* @brief
* Copy operator
*
* @param[in] cSource
* Source to copy from
*
* @return
* This class
*/
inline SamplerStates &operator =(const SamplerStates &cSource);
//[-------------------------------------------------------]
//[ Private data ]
//[-------------------------------------------------------]
private:
// Exported variables
PLCore::uint32 m_nSS[Sampler::Number]; /**< List of sampler states (see Sampler) */
};
//[-------------------------------------------------------]
//[ Namespace ]
//[-------------------------------------------------------]
} // PLRenderer
//[-------------------------------------------------------]
//[ Implementation ]
//[-------------------------------------------------------]
#include "PLRenderer/Renderer/SamplerStates.inl"
#endif // __PLRENDERER_SAMPLERSTATES_H__
|
carlosmaniero/ascii-engine
|
ascii_engine/fragments/utils.py
|
<filename>ascii_engine/fragments/utils.py
def get_max_line_width(fragment):
if not fragment:
return 0
bigger_line = max(fragment, key=len)
return len(bigger_line)
def calculate_fragments_length_sum(fragments):
return sum(map(len, fragments))
|
AnthonyNg404/61A
|
lab/lab08/tests/shuffle.py
|
test = {
'name': 'shuffle',
'points': 0,
'suites': [
{
'cases': [
{
'code': r"""
>>> shuffle(range(6))
[0, 3, 1, 4, 2, 5]
>>> suits = ['♡', '♢', '♤', '♧']
>>> cards = [card(n) + suit for n in range(1,14) for suit in suits]
>>> cards[:12]
['A♡', 'A♢', 'A♤', 'A♧', '2♡', '2♢', '2♤', '2♧', '3♡', '3♢', '3♤', '3♧']
>>> cards[26:30]
['7♤', '7♧', '8♡', '8♢']
>>> shuffle(cards)[:12]
['A♡', '7♤', 'A♢', '7♧', 'A♤', '8♡', 'A♧', '8♢', '2♡', '8♤', '2♢', '8♧']
>>> shuffle(shuffle(cards))[:12]
['A♡', '4♢', '7♤', '10♧', 'A♢', '4♤', '7♧', 'J♡', 'A♤', '4♧', '8♡', 'J♢']
>>> cards[:12] # Should not be changed
['A♡', 'A♢', 'A♤', 'A♧', '2♡', '2♢', '2♤', '2♧', '3♡', '3♢', '3♤', '3♧']
""",
'hidden': False,
'locked': False
}
],
'scored': True,
'setup': '>>> from lab08_extra import *',
'teardown': '',
'type': 'doctest'
}
]
}
|
dreedyman/apache-river
|
qa/src/main/java/org/apache/river/test/impl/start/SerializedServiceDescriptors.java
|
<gh_stars>0
/*
* 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.river.test.impl.start;
import org.apache.river.qa.harness.Test;
import org.apache.river.qa.harness.TestException;
import org.apache.river.start.lifecycle.LifeCycle;
import org.apache.river.start.NonActivatableServiceDescriptor;
import org.apache.river.start.ServiceDescriptor;
import org.apache.river.start.SharedActivatableServiceDescriptor;
import org.apache.river.start.SharedActivationGroupDescriptor;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;
import java.util.Arrays;
import java.util.logging.Level;
import net.jini.security.BasicProxyPreparer;
import net.jini.security.ProxyPreparer;
import net.jini.config.EmptyConfiguration;
public class SerializedServiceDescriptors extends StarterBase implements Test {
private static LifeCycle lc =
new LifeCycle() { // default, no-op object
public boolean unregister(Object impl) { return false; }
};
private static ProxyPreparer pp = new BasicProxyPreparer();
public void run() throws Exception {
NonActivatableServiceDescriptor nasdWithExtras =
new NonActivatableServiceDescriptor(
"http://resendes:8080/mercury-dl.jar",
"http://resendes:8086/policy.mercury",
"http://resendes:8080/mercury.jar",
"org.apache.river.mercury.TransientMercuryBogusImpl",
new String[] {
"http://resendes:8089/mercury_service_trans.config"
},
lc,
pp);
NonActivatableServiceDescriptor nasdWithoutExtras =
new NonActivatableServiceDescriptor(
"http://resendes:8080/mercury-dl.jar",
"http://resendes:8086/policy.mercury",
"http://resendes:8080/mercury.jar",
"org.apache.river.mercury.TransientMercuryBogusImpl",
new String[] {
"http://resendes:8089/mercury_service_trans.config"
});
LifeCycle DefaultLifeCycle = nasdWithoutExtras.getLifeCycle();
ProxyPreparer DefaultPreparer = nasdWithoutExtras.getServicePreparer();
String sharedVmLog = "/tmp/sharedvm.log";
String[] sharedvm_props = new String[] {// server properties
"org.apache.river.start.activatewrapper.debug", "init",
};
SharedActivationGroupDescriptor sharedvm =
new SharedActivationGroupDescriptor(
"/view/resendes/vob/jive/policy/policy.sharedvm",
"/view/resendes/vob/jive/lib/bogus_sharedvm.jar",
sharedVmLog,
"/bin/java", //server command
new String[] {// server options
"-ea",
},
sharedvm_props);
SharedActivatableServiceDescriptor sasd =
new SharedActivatableServiceDescriptor(
"http://resendes:8080/mercury-dl.jar",
"http://resendes:8086/policy.mercury",
"http://resendes:8080/mercury.jar",
"org.apache.river.mercury.MailboxBogusImpl",
sharedVmLog,
new String[] {
"http://resendes:8089/mercury_service_act.config"
},
true);
SharedActivatableServiceDescriptor sasdWithExtras =
new SharedActivatableServiceDescriptor(
"http://resendes:8080/mercury-dl.jar",
"http://resendes:8086/policy.mercury",
"http://resendes:8080/mercury.jar",
"org.apache.river.mercury.MailboxBogusImpl",
sharedVmLog,
new String[] {
"http://resendes:8089/mercury_service_act.config"
},
pp,
pp,
true,
"localhost",
1234);
ServiceDescriptor[] serviceDescriptors =
new ServiceDescriptor[] {
// sasdWithExtras & nasdWithExtras not written because
// default/recovered preparer and lifecycle objects won't match.
nasdWithoutExtras,
sharedvm,
sasd
};
// Serialize service descriptors to a file
FileOutputStream f = new FileOutputStream("tmp");
ObjectOutput oos = new ObjectOutputStream(f);
oos.writeObject(nasdWithExtras);
oos.writeObject(nasdWithoutExtras);
oos.writeObject(sharedvm);
oos.writeObject(sasd);
oos.writeObject(sasdWithExtras);
oos.writeObject(serviceDescriptors);
oos.flush();
oos.close();
logger.log(Level.INFO, "Wrote: " + nasdWithExtras);
logger.log(Level.INFO, "Wrote: " + nasdWithoutExtras);
logger.log(Level.INFO, "Wrote: " + sharedvm);
logger.log(Level.INFO, "Wrote: " + sasd);
logger.log(Level.INFO, "Wrote: " + sasdWithExtras);
logger.log(Level.INFO, "Wrote: " + Arrays.asList(serviceDescriptors));
// Deserialize objects from a file.
FileInputStream in = new FileInputStream("tmp");
ObjectInputStream ois = new ObjectInputStream(in);
NonActivatableServiceDescriptor nasdWithExtras_r =
(NonActivatableServiceDescriptor)ois.readObject();
nasdWithExtras_r.setLifeCycle(lc);
nasdWithExtras_r.setServicePreparer(pp);
NonActivatableServiceDescriptor nasdWithoutExtras_r =
(NonActivatableServiceDescriptor)ois.readObject();
SharedActivationGroupDescriptor sharedvm_r =
(SharedActivationGroupDescriptor)ois.readObject();
SharedActivatableServiceDescriptor sasd_r =
(SharedActivatableServiceDescriptor)ois.readObject();
SharedActivatableServiceDescriptor sasdWithExtras_r =
(SharedActivatableServiceDescriptor)ois.readObject();
//sasdWithExtras_r.setLifeCycle(lc);
sasdWithExtras_r.setServicePreparer(pp);
sasdWithExtras_r.setInnerProxyPreparer(pp);
ServiceDescriptor[] recovered =
(ServiceDescriptor[])ois.readObject();
ois.close();
logger.log(Level.INFO, "Read: " + nasdWithExtras_r);
logger.log(Level.INFO, "Read: " + nasdWithoutExtras_r);
logger.log(Level.INFO, "Read: " + sharedvm_r);
logger.log(Level.INFO, "Read: " + sasd_r);
logger.log(Level.INFO, "Read: " + sasdWithExtras_r);
logger.log(Level.INFO, "Read: " + Arrays.asList(recovered));
if (!verifyNonActivatableServiceDescriptors(nasdWithExtras, nasdWithExtras_r)) {
throw new TestException(
"Written and recovered NonActivatableServiceDescriptors don't match");
}
if (!verifyNonActivatableServiceDescriptors(nasdWithoutExtras, nasdWithoutExtras_r)) {
throw new TestException(
"Written and recovered NonActivatableServiceDescriptors don't match");
}
if (!verifySharedActivationGroupDescriptors(sharedvm, sharedvm_r)) {
throw new TestException(
"Written and recovered SharedActivationGroupDescriptors don't match");
}
if (!verifySharedActivatableServiceDescriptors(sasd, sasd_r)) {
throw new TestException(
"Written and recovered SharedActivatableServiceDescriptors don't match");
}
if (!verifySharedActivatableServiceDescriptors(sasdWithExtras, sasdWithExtras_r)) {
throw new TestException(
"Written and recovered SharedActivatableServiceDescriptors don't match");
}
if (!verifyServiceDescriptors(serviceDescriptors, recovered)) {
throw new TestException(
"Written and recovered ServiceDescriptor[] don't match");
}
//Do some negative tests - Ensure bad descriptor doesn't match
NonActivatableServiceDescriptor bogus_nasd =
new NonActivatableServiceDescriptor(
nasdWithoutExtras.getExportCodebase(),
nasdWithoutExtras.getPolicy(),
nasdWithoutExtras.getImportCodebase(),
nasdWithoutExtras.getImplClassName() + "_bogus",
nasdWithoutExtras.getServerConfigArgs(),
nasdWithoutExtras.getLifeCycle());
if (verifyNonActivatableServiceDescriptors(bogus_nasd, nasdWithoutExtras)) {
throw new TestException("Bogus NASD passed verification");
}
//Do some negative tests - Ensure setLifeCycle can't be called after creation
try {
nasdWithoutExtras.create(EmptyConfiguration.INSTANCE); //Original descriptor
} catch (Exception e) {
logger.log(Level.INFO, "exception creating NASD ... ignoring", e);
}
try {
nasdWithoutExtras.setLifeCycle(lc);
} catch (IllegalStateException ie) {
logger.log(Level.INFO, "Expected exception setting NASD LifeCycle ... ignoring", ie);
} catch (Exception e) {
e.printStackTrace();
throw new TestException("Unexpected exception: " + e);
}
try {
nasdWithoutExtras_r.create(EmptyConfiguration.INSTANCE); //Recovered descriptor
} catch (Exception e) {
logger.log(Level.INFO, "exception creating recovered NASD ... ignoring", e);
}
try {
nasdWithoutExtras_r.setLifeCycle(lc);
} catch (IllegalStateException ie) {
logger.log(Level.INFO, "Expected exception setting recovered NASD LifeCycle ... ignoring", ie);
} catch (Exception e) {
e.printStackTrace();
throw new TestException("Unexpected exception: " + e);
}
//Do some negative tests - Ensure bad descriptor doesn't match
SharedActivatableServiceDescriptor bogus_sasd =
new SharedActivatableServiceDescriptor(
sasd.getExportCodebase(),
sasd.getPolicy(),
sasd.getImportCodebase(),
sasd.getImplClassName(),
sasd.getSharedGroupLog() + "_bogus",
sasd.getServerConfigArgs(),
sasd.getRestart());
if (verifySharedActivatableServiceDescriptors(bogus_sasd, sasd)) {
throw new TestException("Bogus SASD passed verification");
}
//Do some negative tests - Ensure setLifeCycle can't be called after creation
try {
sasd.create(EmptyConfiguration.INSTANCE); //Original descriptor
} catch (Exception e) {
logger.log(Level.INFO, "exception creating SASD ... ignoring", e);
}
try {
sasd.setLifeCycle(lc);
} catch (IllegalStateException ie) {
logger.log(Level.INFO, "Expected exception setting SASD LifeCycle ... ignoring", ie);
} catch (Exception e) {
e.printStackTrace();
throw new TestException("Unexpected exception: " + e);
}
try {
sasd_r.create(EmptyConfiguration.INSTANCE); //Recovered descriptor
} catch (Exception e) {
logger.log(Level.INFO, "exception creating recovered SASD ... ignoring", e);
}
try {
sasd_r.setLifeCycle(lc);
} catch (IllegalStateException ie) {
logger.log(Level.INFO, "Expected exception setting recovered SASD LifeCycle ... ignoring", ie);
} catch (Exception e) {
e.printStackTrace();
throw new TestException("Unexpected exception: " + e);
}
SharedActivationGroupDescriptor bogus_sharedvm =
new SharedActivationGroupDescriptor(
sharedvm.getPolicy(),
sharedvm.getClasspath(),
sharedvm.getLog() + "_bogus",
sharedvm.getServerCommand(),
sharedvm.getServerOptions(),
sharedvm_props);
if (verifySharedActivationGroupDescriptors(bogus_sharedvm, sharedvm)) {
throw new TestException("Bogus SAGD passed verification");
}
}
private static boolean verifyServiceDescriptors(
ServiceDescriptor[] wrote, ServiceDescriptor[] read)
{
if (wrote.length != read.length) {
logger.log(Level.INFO, "read length [" + read.length
+ "] doesn't match written length [" + wrote.length + "]");
return false;
}
for (int i=0; i < wrote.length; i++) {
if (wrote[i] instanceof SharedActivatableServiceDescriptor) {
SharedActivatableServiceDescriptor sasdw =
(SharedActivatableServiceDescriptor)wrote[i];
SharedActivatableServiceDescriptor sasdr =
(SharedActivatableServiceDescriptor)read[i];
if (!verifySharedActivatableServiceDescriptors(sasdw, sasdr)) {
return false;
}
} else if (wrote[i] instanceof NonActivatableServiceDescriptor) {
NonActivatableServiceDescriptor nasdw =
(NonActivatableServiceDescriptor)wrote[i];
NonActivatableServiceDescriptor nasdr =
(NonActivatableServiceDescriptor)read[i];
if (!verifyNonActivatableServiceDescriptors(nasdw, nasdr)) {
return false;
}
} else if (wrote[i] instanceof SharedActivationGroupDescriptor) {
SharedActivationGroupDescriptor sagdw =
(SharedActivationGroupDescriptor)wrote[i];
SharedActivationGroupDescriptor sagdr =
(SharedActivationGroupDescriptor)read[i];
if (!verifySharedActivationGroupDescriptors(sagdw, sagdr)) {
return false;
}
} else {
logger.log(Level.INFO, "ServiceDescriptor " + wrote[i]
+ " not handled");
return false;
}
}
return true;
}
private static boolean verifySharedActivatableServiceDescriptors(
SharedActivatableServiceDescriptor wrote, SharedActivatableServiceDescriptor read)
{
if (verifyNonActivatableServiceDescriptors(wrote, read) &&
wrote.getSharedGroupLog().equals(read.getSharedGroupLog()) &&
(wrote.getRestart() == read.getRestart()) &&
wrote.getActivationSystemHost().equals(read.getActivationSystemHost()) &&
(wrote.getActivationSystemPort() == read.getActivationSystemPort()))
{
logger.log(Level.FINE, "Written SASD [" + wrote + "] does match "
+ "recovered SASD [" + read + "]");
return true;
}
logger.log(Level.INFO, "Written SASD [" + wrote + "] DOESN'T match "
+ "recovered SASD [" + read + "]");
return false;
}
private static boolean verifyNonActivatableServiceDescriptors(
NonActivatableServiceDescriptor wrote, NonActivatableServiceDescriptor read)
{
if (wrote.getExportCodebase().equals(read.getExportCodebase()) &&
wrote.getPolicy().equals(read.getPolicy()) &&
wrote.getImportCodebase().equals(read.getImportCodebase()) &&
wrote.getImplClassName().equals(read.getImplClassName()) &&
Arrays.equals(wrote.getServerConfigArgs(), read.getServerConfigArgs()) &&
wrote.getLifeCycle().equals(read.getLifeCycle()) &&
(wrote.getServicePreparer()==null?
read.getServicePreparer()==null:
wrote.getServicePreparer().equals(read.getServicePreparer())))
{
logger.log(Level.FINE, "Written NASD [" + wrote + "] does match "
+ "recovered NASD [" + read + "]");
return true;
}
logger.log(Level.INFO, "Written NASD [" + wrote + "] DOESN'T match "
+ "recovered NASD [" + read + "]");
return false;
}
private static boolean verifySharedActivationGroupDescriptors(
SharedActivationGroupDescriptor wrote, SharedActivationGroupDescriptor read)
{
if (wrote.getPolicy().equals(read.getPolicy()) &&
wrote.getClasspath().equals(read.getClasspath()) &&
wrote.getLog().equals(read.getLog()) &&
wrote.getServerCommand().equals(read.getServerCommand()) &&
Arrays.equals(wrote.getServerOptions(), read.getServerOptions()) &&
wrote.getServerProperties().equals(read.getServerProperties()) &&
wrote.getActivationSystemHost().equals(read.getActivationSystemHost()) &&
(wrote.getActivationSystemPort() == read.getActivationSystemPort()))
{
logger.log(Level.FINE, "Written SAGD [" + wrote + "] does match "
+ "recovered SAGD [" + read + "]");
return true;
}
logger.log(Level.INFO, "Written SAGD [" + wrote + "] DOESN'T match "
+ "recovered SAGD [" + read + "]");
return false;
}
}
|
RyanLiu0808/GdeiAssistant
|
src/main/java/edu/gdei/gdeiassistant/Repository/Mysql/GdeiAssistant/Mapper/Profile/ProfileMapper.java
|
<filename>src/main/java/edu/gdei/gdeiassistant/Repository/Mysql/GdeiAssistant/Mapper/Profile/ProfileMapper.java
package edu.gdei.gdeiassistant.Repository.Mysql.GdeiAssistant.Mapper.Profile;
import edu.gdei.gdeiassistant.Pojo.Entity.Introduction;
import edu.gdei.gdeiassistant.Pojo.Entity.Profile;
import org.apache.ibatis.annotations.*;
import org.apache.ibatis.type.JdbcType;
import java.util.Date;
public interface ProfileMapper {
@Select("select * from profile where username=#{username} limit 1")
@Results(id = "Profile", value = {
@Result(property = "username", column = "username"),
@Result(property = "kickname", column = "kickname"),
@Result(property = "gender", column = "gender"),
@Result(property = "birthday", column = "birthday", javaType = Date.class, jdbcType = JdbcType.DATE),
@Result(property = "degree", column = "degree"),
@Result(property = "faculty", column = "faculty"),
@Result(property = "major", column = "major"),
@Result(property = "enrollment", column = "enrollment"),
@Result(property = "profession", column = "profession"),
@Result(property = "highSchool", column = "high_school"),
@Result(property = "juniorHighSchool", column = "junior_high_school"),
@Result(property = "primarySchool", column = "primary_school"),
@Result(property = "region", column = "region"),
@Result(property = "state", column = "state"),
@Result(property = "city", column = "city")
})
Profile selectUserProfile(String username) throws Exception;
@Select("select * from introduction where username=#{username} limit 1")
@Results(id = "Introduction", value = {
@Result(property = "introductionContent", column = "introduction"),
@Result(property = "username", column = "username")
})
Introduction selectUserIntroduction(String username) throws Exception;
@Insert("insert into profile (username,kickname) values (#{username},#{kickname})")
void initUserProfile(@Param("username") String username, @Param("kickname") String kickname) throws Exception;
@Insert("insert into introduction (username) values (#{username})")
void initUserIntroduction(String username) throws Exception;
@Update("update profile set kickname=#{kickname} where username=#{username}")
void updateKickname(Profile profile);
@Update("update profile set gender=#{gender} where username=#{username}")
void updateGender(Profile profile);
@Update("update profile set birthday=#{birthday} where username=#{username}")
void updateBirthday(Profile profile);
@Update("update profile set faculty=#{faculty} where username=#{username}")
void updateFaculty(Profile profile);
@Update("update profile set major=#{major} where username=#{username}")
void updateMajor(Profile profile);
@Update("update profile set degree=#{degree} where username=#{username}")
void updateDegree(Profile profile);
@Update("update profile set enrollment=#{enrollment} where username=#{username}")
void updateEnrollment(Profile profile);
@Update("update profile set profession=#{profession} where username=#{username}")
void updateProfession(Profile profile);
@Update("update profile set region=#{region},state=#{state},city=#{city} where username=#{username}")
void updateLocation(Profile profile);
@Update("update profile set high_school=#{highSchool} where username=#{username}")
void updateHighSchool(Profile profile);
@Update("update profile set junior_high_school=#{juniorHighSchool} where username=#{username}")
void updateJuniorHighSchool(Profile profile);
@Update("update profile set primary_school=#{primarySchool} where username=#{username}")
void updatePrimarySchool(Profile profile);
@Update("update profile set kickname=#{kickname},gender=null,birthday=null,enrollment=null,profession=null,region=null" +
",state=null,city=null,high_school=null,junior_high_school=null,primary_school=null where username=#{username}")
void resetUserProfile(@Param("username") String username, @Param("kickname") String kickname) throws Exception;
@Update("update introduction set introduction=null where username=#{username}")
void resetUserIntroduction(@Param("username") String username);
@Update("update introduction set introduction=#{introduction} where username=#{username}")
void updateUserIntroduction(@Param("username") String username, @Param("introduction") String introduction) throws Exception;
}
|
StrayDoki/math
|
stan/math/prim/mat/fun/inverse.hpp
|
<filename>stan/math/prim/mat/fun/inverse.hpp<gh_stars>0
#ifndef STAN_MATH_PRIM_MAT_FUN_INVERSE_HPP
#define STAN_MATH_PRIM_MAT_FUN_INVERSE_HPP
#include <stan/math/prim/mat/fun/Eigen.hpp>
#include <stan/math/prim/mat/err/check_nonempty.hpp>
#include <stan/math/prim/mat/err/check_square.hpp>
namespace stan {
namespace math {
/**
* Returns the inverse of the specified matrix.
* @param m Specified matrix.
* @return Inverse of the matrix.
*/
template <typename T, int R, int C>
inline Eigen::Matrix<T, R, C> inverse(const Eigen::Matrix<T, R, C>& m) {
check_nonempty("inverse", "m", m);
check_square("inverse", "m", m);
return m.inverse();
}
} // namespace math
} // namespace stan
#endif
|
ITIJavaTeam6/ChatApp
|
Chat App Client/src/chat/client/view/JHyperlinkLabel.java
|
<filename>Chat App Client/src/chat/client/view/JHyperlinkLabel.java
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package chat.client.view;
/**
*
* @author AmoOOOnA
*/
import java.awt.Color;
import java.awt.Cursor;
import java.awt.Graphics;
import java.awt.Insets;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JLabel;
public class JHyperlinkLabel extends JLabel {
private Color underlineColor = null;
public JHyperlinkLabel(String label) {
super(label);
setForeground(Color.BLUE.darker());
setCursor(new Cursor(Cursor.HAND_CURSOR));
addMouseListener(new HyperlinkLabelMouseAdapter());
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(underlineColor == null ? getForeground() : underlineColor);
Insets insets = getInsets();
int left = insets.left;
if (getIcon() != null) {
left += getIcon().getIconWidth() + getIconTextGap();
}
g.drawLine(left, getHeight() - 1 - insets.bottom, (int) getPreferredSize().getWidth()
- insets.right, getHeight() - 1 - insets.bottom);
}
public class HyperlinkLabelMouseAdapter extends MouseAdapter {
@Override
public void mouseClicked(MouseEvent e) {
System.out.println(getText());
}
}
public Color getUnderlineColor() {
return underlineColor;
}
public void setUnderlineColor(Color underlineColor) {
this.underlineColor = underlineColor;
}
}
|
YourName0729/competitive-programming
|
Kattis/reverserot.cpp
|
//
// https://open.kattis.com/problems/reverserot
#include <iostream>
#include <string>
#include <vector>
#include <sstream>
#include <map>
#include <cmath>
#include <queue>
#include <algorithm>
#include <stack>
#include <deque>
#include <numeric>
#include <iomanip>
#define forcase int __t;cin>>__t;getchar();for(int ___t=1;___t<=__t;___t++)
#define For(i, n) for(int i=0;i<n;i++)
using ll = long long;
using namespace std;
const ll INF = 1000000010;
const ll MOD = 1000000007;
const int dx[8] = {1, 0, -1, 0, 1, 1, -1, -1};
const int dy[8] = {0, 1, 0, -1, 1, -1, 1, -1};
void fast() {
ios::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
}
string ss = "ABCDEFGHIJKLMNOPQRSTUVWXYZ_.";
int at(char c) {
if ('A' <= c && c <= 'Z') return c - 'A';
if (c == '_') return 26;
return 27;
}
int main() {
//fast();
int n;
string s;
while (cin >> n && n != 0) {
cin >> s;
For (i, s.length()) {
s[i] = ss[(at(s[i]) + n) % ss.length()];
}
For (i, s.length()) {
cout << s[s.length() - i - 1];
}
cout << '\n';
}
return 0;
}
|
hekailiang/actor-server
|
actor-api/src/main/scala/com/secretapp/backend/data/message/rpc/file/UploadConfig.scala
|
<gh_stars>1-10
package com.secretapp.backend.data.message.rpc.file
import com.secretapp.backend.data.message.ProtobufMessage
import com.secretapp.backend.protocol.codecs.utils.protobuf._
import im.actor.messenger.{ api => protobuf }
import scodec.bits.BitVector
@SerialVersionUID(1L)
case class UploadConfig(serverData: BitVector) extends ProtobufMessage
{
def toProto = protobuf.UploadConfig(serverData)
}
object UploadConfig {
def fromProto(r: protobuf.UploadConfig): UploadConfig = r match {
case protobuf.UploadConfig(serverData) => UploadConfig(serverData)
}
}
|
gummybuns/dorm
|
cerami/datatype/number.py
|
from .base_number import BaseNumber
class Number(BaseNumber):
"""An alias for BaseNumber"""
pass
|
SebastianNiama/DataStructrures-CodeTraining
|
DataSructures/src/main/java/PriorityQueues1/ColaPrioridad1.java
|
//Se podria decir que es un array estatico de colas.:
//La clase que representa la tabla, a su vez, utiliza la clase ColaLista
package PriorityQueues1;
import Queues.ColaLista;//Xq vamos a usar colas
public class ColaPrioridad1 {
protected ColaLista []tabla;//Un arrays de Colas
protected int maxPrioridad;
/*
El constructor es el responsable de establecer
el número de prioridades y definir el array:
*/
public ColaPrioridad1(int n) throws Exception {
if(n<1) throw new Exception("Error en prioridad "+n);
maxPrioridad = n;
//Inicializo mi array de listas enlazadas(con Colas):
tabla = new ColaLista[maxPrioridad+1];
//Creo una nueva lista enlazada/cola para cada celda de la TABLA
for(int i=0; i<=maxPrioridad;) tabla[i++] = new ColaLista();
}
/* INSERTAR:
La operación añade una nueva tarea, un elemento, a la cola de prioridades.
La tarea se inserta en la cola tabla[prioridad], siendo prioridad la asociada
a la tarea.
La complejidad de añadir un elemento es la requerida por la operación de
insertar en la cola tabla[p]. Por consiguiente, la operación tiene
complejidad constante (tiempo constante). O(1)
*/
public void insertarEnPrioridad(Tarea t) throws Exception{
int p = t.numPrioridad();
if(p >=0 && p<=maxPrioridad) tabla[p].insertar(t);//Inserto objeto en lista
else throw new Exception("Tarea con prioridad fuera de rango. ");
}
//ELEMENTO DE MAXIMA PRIORIDAD;
//El sig metodo me devuelve el valor minimo (max prioridad)
public Tarea elementoMin() throws Exception{
int i=0;
int indiceCola =-1;
//Busqueda de la primera cola, no vacia.
do{
if(!tabla[i].colaVacia()){//Si la primera cola, no esta vacía
indiceCola =i;// =0; (Va cambiando)
i = maxPrioridad +1;//termina el bucle.
}else i++;
}while(i<= maxPrioridad);
if(indiceCola !=-1)
return (Tarea)tabla[indiceCola].frenteCola();//Me devuelve un objeto.
else throw new Exception("Cola de prioridades vacia");
}
//La operación quitarMin sigue los mismos pasos que elementoMin, con la diferencia de
//que devuelve y retira el elemento frente de la cola de mayor prioridad:
public Tarea quitarMin() throws Exception{
int i=0;
int indiceCola =-1;
//Busqueda de la primera cola, no vacia.
do{
if(!tabla[i].colaVacia()){//Si la primera cola, no esta vacía
indiceCola =i;// =0; (Va cambiando)
i = maxPrioridad +1;//termina el bucle.
}else i++;
}while(i<= maxPrioridad);
if(indiceCola !=-1)
return (Tarea)tabla[indiceCola].quitar();//Me devuelve un objeto.
else throw new Exception("Cola de prioridades vacia");
}
//La operación colaPrioridadVacia comprueba que cada una de las colas está vacía.
public boolean colaPrioridadvacia(){
int i=0;
while(tabla[i].colaVacia() && i<maxPrioridad) i++;
return tabla[i].colaVacia();
}
}
|
meodaiduoi/onos
|
apps/packet-throttle/app/src/main/java/org/onosproject/packetthrottle/PacketThrottleManager.java
|
<reponame>meodaiduoi/onos
/*
* Copyright 2019-present Open Networking Foundation
*
* 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.onosproject.packetthrottle;
import com.google.common.collect.ImmutableMap;
import org.osgi.service.component.annotations.Modified;
import org.osgi.service.component.annotations.Reference;
import org.osgi.service.component.annotations.ReferenceCardinality;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.Activate;
import org.osgi.service.component.annotations.Deactivate;
import org.onosproject.cfg.ComponentConfigService;
import org.onosproject.net.packet.PacketInFilter;
import org.onosproject.net.packet.PacketService;
import org.onosproject.net.packet.packetfilter.DefaultPacketInFilter;
import org.onosproject.net.packet.packetfilter.ArpPacketClassifier;
import org.onosproject.net.packet.packetfilter.Dhcp6IndirectPacketClassifier;
import org.onosproject.net.packet.packetfilter.Dhcp6DirectPacketClassifier;
import org.onosproject.net.packet.packetfilter.DhcpPacketClassifier;
import org.onosproject.net.packet.packetfilter.NAPacketClassifier;
import org.onosproject.net.packet.packetfilter.NSPacketClassifier;
import org.onosproject.net.packet.packetfilter.IcmpPacketClassifier;
import org.onosproject.net.packet.packetfilter.Icmp6PacketClassifier;
import org.onosproject.packetthrottle.api.PacketThrottleService;
import static org.onosproject.packetthrottle.OsgiPropertyConstants.PROP_PPS_ARP;
import static org.onosproject.packetthrottle.OsgiPropertyConstants.PPS_ARP_DEFAULT;
import static org.onosproject.packetthrottle.OsgiPropertyConstants.PROP_PPS_DHCP;
import static org.onosproject.packetthrottle.OsgiPropertyConstants.PPS_DHCP_DEFAULT;
import static org.onosproject.packetthrottle.OsgiPropertyConstants.PROP_PPS_NS;
import static org.onosproject.packetthrottle.OsgiPropertyConstants.PPS_NS_DEFAULT;
import static org.onosproject.packetthrottle.OsgiPropertyConstants.PROP_PPS_NA;
import static org.onosproject.packetthrottle.OsgiPropertyConstants.PPS_NA_DEFAULT;
import static org.onosproject.packetthrottle.OsgiPropertyConstants.PROP_PPS_DHCP6_DIRECT;
import static org.onosproject.packetthrottle.OsgiPropertyConstants.PPS_DHCP6_DIRECT_DEFAULT;
import static org.onosproject.packetthrottle.OsgiPropertyConstants.PROP_PPS_DHCP6_INDIRECT;
import static org.onosproject.packetthrottle.OsgiPropertyConstants.PPS_DHCP6_INDIRECT_DEFAULT;
import static org.onosproject.packetthrottle.OsgiPropertyConstants.PROP_PPS_ICMP;
import static org.onosproject.packetthrottle.OsgiPropertyConstants.PPS_ICMP_DEFAULT;
import static org.onosproject.packetthrottle.OsgiPropertyConstants.PROP_PPS_ICMP6;
import static org.onosproject.packetthrottle.OsgiPropertyConstants.PPS_ICMP6_DEFAULT;
import static org.onosproject.packetthrottle.OsgiPropertyConstants.PROP_WIN_SIZE_ARP_MS;
import static org.onosproject.packetthrottle.OsgiPropertyConstants.WIN_SIZE_ARP_MS_DEFAULT;
import static org.onosproject.packetthrottle.OsgiPropertyConstants.PROP_WIN_SIZE_DHCP_MS;
import static org.onosproject.packetthrottle.OsgiPropertyConstants.WIN_SIZE_DHCP_MS_DEFAULT;
import static org.onosproject.packetthrottle.OsgiPropertyConstants.PROP_WIN_SIZE_NA_MS;
import static org.onosproject.packetthrottle.OsgiPropertyConstants.WIN_SIZE_NA_MS_DEFAULT;
import static org.onosproject.packetthrottle.OsgiPropertyConstants.PROP_WIN_SIZE_NS_MS;
import static org.onosproject.packetthrottle.OsgiPropertyConstants.WIN_SIZE_NS_MS_DEFAULT;
import static org.onosproject.packetthrottle.OsgiPropertyConstants.PROP_WIN_SIZE_DHCP6_DIRECT_MS;
import static org.onosproject.packetthrottle.OsgiPropertyConstants.WIN_SIZE_DHCP6_DIRECT_MS_DEFAULT;
import static org.onosproject.packetthrottle.OsgiPropertyConstants.PROP_WIN_SIZE_DHCP6_INDIRECT_MS;
import static org.onosproject.packetthrottle.OsgiPropertyConstants.WIN_SIZE_DHCP6_INDIRECT_MS_DEFAULT;
import static org.onosproject.packetthrottle.OsgiPropertyConstants.PROP_WIN_SIZE_ICMP_MS;
import static org.onosproject.packetthrottle.OsgiPropertyConstants.WIN_SIZE_ICMP_MS_DEFAULT;
import static org.onosproject.packetthrottle.OsgiPropertyConstants.PROP_WIN_SIZE_ICMP6_MS;
import static org.onosproject.packetthrottle.OsgiPropertyConstants.WIN_SIZE_ICMP6_MS_DEFAULT;
import static org.onosproject.packetthrottle.OsgiPropertyConstants.PROP_GUARD_TIME_ARP_SEC;
import static org.onosproject.packetthrottle.OsgiPropertyConstants.GUARD_TIME_ARP_SEC_DEFAULT;
import static org.onosproject.packetthrottle.OsgiPropertyConstants.PROP_GUARD_TIME_DHCP_SEC;
import static org.onosproject.packetthrottle.OsgiPropertyConstants.GUARD_TIME_DHCP_SEC_DEFAULT;
import static org.onosproject.packetthrottle.OsgiPropertyConstants.PROP_GUARD_TIME_NS_SEC;
import static org.onosproject.packetthrottle.OsgiPropertyConstants.GUARD_TIME_NS_SEC_DEFAULT;
import static org.onosproject.packetthrottle.OsgiPropertyConstants.PROP_GUARD_TIME_NA_SEC;
import static org.onosproject.packetthrottle.OsgiPropertyConstants.GUARD_TIME_NA_SEC_DEFAULT;
import static org.onosproject.packetthrottle.OsgiPropertyConstants.PROP_GUARD_TIME_DHCP6_DIRECT_SEC;
import static org.onosproject.packetthrottle.OsgiPropertyConstants.GUARD_TIME_DHCP6_DIRECT_SEC_DEFAULT;
import static org.onosproject.packetthrottle.OsgiPropertyConstants.PROP_GUARD_TIME_DHCP6_INDIRECT_SEC;
import static org.onosproject.packetthrottle.OsgiPropertyConstants.GUARD_TIME_DHCP6_INDIRECT_SEC_DEFAULT;
import static org.onosproject.packetthrottle.OsgiPropertyConstants.PROP_GUARD_TIME_ICMP_SEC;
import static org.onosproject.packetthrottle.OsgiPropertyConstants.GUARD_TIME_ICMP_SEC_DEFAULT;
import static org.onosproject.packetthrottle.OsgiPropertyConstants.PROP_GUARD_TIME_ICMP6_SEC;
import static org.onosproject.packetthrottle.OsgiPropertyConstants.GUARD_TIME_ICMP6_SEC_DEFAULT;
import static org.onosproject.packetthrottle.OsgiPropertyConstants.PROP_WIN_THRES_ARP;
import static org.onosproject.packetthrottle.OsgiPropertyConstants.WIN_THRES_ARP_DEFAULT;
import static org.onosproject.packetthrottle.OsgiPropertyConstants.PROP_WIN_THRES_DHCP;
import static org.onosproject.packetthrottle.OsgiPropertyConstants.WIN_THRES_DHCP_DEFAULT;
import static org.onosproject.packetthrottle.OsgiPropertyConstants.PROP_WIN_THRES_NS;
import static org.onosproject.packetthrottle.OsgiPropertyConstants.WIN_THRES_NS_DEFAULT;
import static org.onosproject.packetthrottle.OsgiPropertyConstants.PROP_WIN_THRES_NA;
import static org.onosproject.packetthrottle.OsgiPropertyConstants.WIN_THRES_NA_DEFAULT;
import static org.onosproject.packetthrottle.OsgiPropertyConstants.PROP_WIN_THRES_DHCP6_DIRECT;
import static org.onosproject.packetthrottle.OsgiPropertyConstants.WIN_THRES_DHCP6_DIRECT_DEFAULT;
import static org.onosproject.packetthrottle.OsgiPropertyConstants.PROP_WIN_THRES_DHCP6_INDIRECT;
import static org.onosproject.packetthrottle.OsgiPropertyConstants.WIN_THRES_DHCP6_INDIRECT_DEFAULT;
import static org.onosproject.packetthrottle.OsgiPropertyConstants.PROP_WIN_THRES_ICMP;
import static org.onosproject.packetthrottle.OsgiPropertyConstants.WIN_THRES_ICMP_DEFAULT;
import static org.onosproject.packetthrottle.OsgiPropertyConstants.PROP_WIN_THRES_ICMP6;
import static org.onosproject.packetthrottle.OsgiPropertyConstants.WIN_THRES_ICMP6_DEFAULT;
import org.osgi.service.component.ComponentContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Dictionary;
import java.util.HashMap;
import java.util.Map;
import static com.google.common.base.Strings.isNullOrEmpty;
import static org.onlab.util.Tools.get;
/**
* Manage the packet throttle for various type of packets.
*/
@Component(
immediate = true,
service = PacketThrottleService.class,
property = {
PROP_PPS_ARP + ":Integer=" + PPS_ARP_DEFAULT,
PROP_PPS_DHCP + ":Integer=" + PPS_DHCP_DEFAULT,
PROP_PPS_NS + ":Integer=" + PPS_NS_DEFAULT,
PROP_PPS_NA + ":Integer=" + PPS_NA_DEFAULT,
PROP_PPS_DHCP6_DIRECT + ":Integer=" + PPS_DHCP6_DIRECT_DEFAULT,
PROP_PPS_DHCP6_INDIRECT + ":Integer=" + PPS_DHCP6_INDIRECT_DEFAULT,
PROP_PPS_ICMP + ":Integer=" + PPS_ICMP_DEFAULT,
PROP_PPS_ICMP6 + ":Integer=" + PPS_ICMP6_DEFAULT,
PROP_WIN_SIZE_ARP_MS + ":Integer=" + WIN_SIZE_ARP_MS_DEFAULT,
PROP_WIN_SIZE_DHCP_MS + ":Integer=" + WIN_SIZE_DHCP_MS_DEFAULT,
PROP_WIN_SIZE_NA_MS + ":Integer=" + WIN_SIZE_NA_MS_DEFAULT,
PROP_WIN_SIZE_NS_MS + ":Integer=" + WIN_SIZE_NS_MS_DEFAULT,
PROP_WIN_SIZE_DHCP6_DIRECT_MS + ":Integer=" + WIN_SIZE_DHCP6_DIRECT_MS_DEFAULT,
PROP_WIN_SIZE_DHCP6_INDIRECT_MS + ":Integer=" + WIN_SIZE_DHCP6_INDIRECT_MS_DEFAULT,
PROP_WIN_SIZE_ICMP_MS + ":Integer=" + WIN_SIZE_ICMP_MS_DEFAULT,
PROP_WIN_SIZE_ICMP6_MS + ":Integer=" + WIN_SIZE_ICMP6_MS_DEFAULT,
PROP_GUARD_TIME_ARP_SEC + ":Integer=" + GUARD_TIME_ARP_SEC_DEFAULT,
PROP_GUARD_TIME_DHCP_SEC + ":Integer=" + GUARD_TIME_DHCP_SEC_DEFAULT,
PROP_GUARD_TIME_NS_SEC + ":Integer=" + GUARD_TIME_NS_SEC_DEFAULT,
PROP_GUARD_TIME_NA_SEC + ":Integer=" + GUARD_TIME_NA_SEC_DEFAULT,
PROP_GUARD_TIME_DHCP6_DIRECT_SEC + ":Integer=" + GUARD_TIME_DHCP6_DIRECT_SEC_DEFAULT,
PROP_GUARD_TIME_DHCP6_INDIRECT_SEC + ":Integer=" + GUARD_TIME_DHCP6_INDIRECT_SEC_DEFAULT,
PROP_GUARD_TIME_ICMP_SEC + ":Integer=" + GUARD_TIME_ICMP_SEC_DEFAULT,
PROP_GUARD_TIME_ICMP6_SEC + ":Integer=" + GUARD_TIME_ICMP6_SEC_DEFAULT,
PROP_WIN_THRES_ARP + ":Integer=" + WIN_THRES_ARP_DEFAULT,
PROP_WIN_THRES_DHCP + ":Integer=" + WIN_THRES_DHCP_DEFAULT,
PROP_WIN_THRES_NS + ":Integer=" + WIN_THRES_NS_DEFAULT,
PROP_WIN_THRES_NA + ":Integer=" + WIN_THRES_NA_DEFAULT,
PROP_WIN_THRES_DHCP6_DIRECT + ":Integer=" + WIN_THRES_DHCP6_DIRECT_DEFAULT,
PROP_WIN_THRES_DHCP6_INDIRECT + ":Integer=" + WIN_THRES_DHCP6_INDIRECT_DEFAULT,
PROP_WIN_THRES_ICMP + ":Integer=" + WIN_THRES_ICMP_DEFAULT,
PROP_WIN_THRES_ICMP6 + ":Integer=" + WIN_THRES_ICMP6_DEFAULT
}
)
public class PacketThrottleManager implements PacketThrottleService {
private final Logger log = LoggerFactory.getLogger(getClass());
protected static final String ARP_FILTER = "arpFilter";
protected static final String DHCP_FILTER = "dhcpFilter";
protected static final String NS_FILTER = "nsFilter";
protected static final String NA_FILTER = "naFilter";
protected static final String DHCP6_DIRECT_FILTER = "dhcp6DirectFilter";
protected static final String DHCP6_INDIRECT_FILTER = "dhcp6IndirectFilter";
protected static final String ICMP_FILTER = "icmpFilter";
protected static final String ICMP6_FILTER = "icmp6Filter";
@Reference(cardinality = ReferenceCardinality.MANDATORY)
PacketService packetService;
@Reference(cardinality = ReferenceCardinality.MANDATORY)
protected ComponentConfigService configService;
/**
* Parameter to set packet per second rate for all filter types.
*/
private int ppsArp = PPS_ARP_DEFAULT;
private int ppsDhcp = PPS_DHCP_DEFAULT;
private int ppsNs = PPS_NS_DEFAULT;
private int ppsNa = PPS_NA_DEFAULT;
private int ppsDhcp6Direct = PPS_DHCP6_DIRECT_DEFAULT;
private int ppsDhcp6Indirect = PPS_DHCP6_INDIRECT_DEFAULT;
private int ppsIcmp = PPS_ICMP_DEFAULT;
private int ppsIcmp6 = PPS_ICMP6_DEFAULT;
/**
* Parameter to set window size in milli seconds to check overflow of packets.
*/
private int winSizeArp = WIN_SIZE_ARP_MS_DEFAULT;
private int winSizeDhcp = WIN_SIZE_DHCP_MS_DEFAULT;
private int winSizeNs = WIN_SIZE_NS_MS_DEFAULT;
private int winSizeNa = WIN_SIZE_NA_MS_DEFAULT;
private int winSizeDhcp6Direct = WIN_SIZE_DHCP6_DIRECT_MS_DEFAULT;
private int winSizeDhcp6Indirect = WIN_SIZE_DHCP6_INDIRECT_MS_DEFAULT;
private int winSizeIcmp = WIN_SIZE_ICMP_MS_DEFAULT;
private int winSizeIcmp6 = WIN_SIZE_ICMP6_MS_DEFAULT;
/**
* Time duration for which no more packets will be processed for a given filter type
* provided consecutive overflow windows happens.
*/
private int guardTimeArp = GUARD_TIME_ARP_SEC_DEFAULT;
private int guardTimeDhcp = GUARD_TIME_DHCP_SEC_DEFAULT;
private int guardTimeNs = GUARD_TIME_NS_SEC_DEFAULT;
private int guardTimeNa = GUARD_TIME_NA_SEC_DEFAULT;
private int guardTimeDhcp6Direct = GUARD_TIME_DHCP6_DIRECT_SEC_DEFAULT;
private int guardTimeDhcp6Indirect = GUARD_TIME_DHCP6_INDIRECT_SEC_DEFAULT;
private int guardTimeIcmp = GUARD_TIME_ICMP_SEC_DEFAULT;
private int guardTimeIcmp6 = GUARD_TIME_ICMP6_SEC_DEFAULT;
/**
* Consecutive overflow window threshold.
*/
private int winThresArp = WIN_THRES_ARP_DEFAULT;
private int winThresDhcp = WIN_THRES_DHCP_DEFAULT;
private int winThresNs = WIN_THRES_NS_DEFAULT;
private int winThresNa = WIN_THRES_NA_DEFAULT;
private int winThresDhcp6Direct = WIN_THRES_DHCP6_DIRECT_DEFAULT;
private int winThresDhcp6Indirect = WIN_THRES_DHCP6_INDIRECT_DEFAULT;
private int winThresIcmp = WIN_THRES_ICMP_DEFAULT;
private int winThresIcmp6 = WIN_THRES_ICMP6_DEFAULT;
private Map<String, PacketInFilter> mapCounterFilter = new HashMap<>();
@Activate
protected void activate() {
log.info("Started");
configService.registerProperties(getClass());
createAllFilters();
}
@Deactivate
protected void deactivate() {
configService.unregisterProperties(getClass(), false);
removeAllFilters();
log.info("Stopped");
}
private void checkChangeInPps(ComponentContext context) {
Dictionary<?, ?> properties = context.getProperties();
int newPpsArp, newPpsDhcp, newPpsNs, newPpsNa, newPpsDhcp6Direct;
int newPpsDhcp6Indirect, newPpsIcmp, newPpsIcmp6;
try {
String s = get(properties, PROP_PPS_ARP);
newPpsArp = isNullOrEmpty(s) ? ppsArp : Integer.parseInt(s.trim());
s = get(properties, PROP_PPS_DHCP);
newPpsDhcp = isNullOrEmpty(s) ? ppsDhcp : Integer.parseInt(s.trim());
s = get(properties, PROP_PPS_NS);
newPpsNs = isNullOrEmpty(s) ? ppsNs : Integer.parseInt(s.trim());
s = get(properties, PROP_PPS_NA);
newPpsNa = isNullOrEmpty(s) ? ppsNa : Integer.parseInt(s.trim());
s = get(properties, PROP_PPS_DHCP6_DIRECT);
newPpsDhcp6Direct = isNullOrEmpty(s) ? ppsDhcp6Direct : Integer.parseInt(s.trim());
s = get(properties, PROP_PPS_DHCP6_INDIRECT);
newPpsDhcp6Indirect = isNullOrEmpty(s) ? ppsDhcp6Indirect : Integer.parseInt(s.trim());
s = get(properties, PROP_PPS_ICMP);
newPpsIcmp = isNullOrEmpty(s) ? ppsIcmp : Integer.parseInt(s.trim());
s = get(properties, PROP_PPS_ICMP6);
newPpsIcmp6 = isNullOrEmpty(s) ? ppsIcmp6 : Integer.parseInt(s.trim());
} catch (NumberFormatException | ClassCastException e) {
newPpsArp = PPS_ARP_DEFAULT;
newPpsDhcp = PPS_DHCP_DEFAULT;
newPpsNs = PPS_NS_DEFAULT;
newPpsNa = PPS_NA_DEFAULT;
newPpsDhcp6Direct = PPS_DHCP6_DIRECT_DEFAULT;
newPpsDhcp6Indirect = PPS_DHCP6_INDIRECT_DEFAULT;
newPpsIcmp = PPS_ICMP_DEFAULT;
newPpsIcmp6 = PPS_ICMP6_DEFAULT;
}
if (newPpsArp != ppsArp) {
ppsArp = newPpsArp;
mapCounterFilter.get(ARP_FILTER).setPps(ppsArp);
}
if (newPpsDhcp != ppsDhcp) {
ppsDhcp = newPpsDhcp;
mapCounterFilter.get(DHCP_FILTER).setPps(ppsDhcp);
}
if (newPpsNs != ppsNs) {
ppsNs = newPpsNs;
mapCounterFilter.get(NS_FILTER).setPps(ppsNs);
}
if (newPpsNa != ppsNa) {
ppsNa = newPpsNa;
mapCounterFilter.get(NA_FILTER).setPps(ppsNa);
}
if (newPpsDhcp6Direct != ppsDhcp6Direct) {
ppsDhcp6Direct = newPpsDhcp6Direct;
mapCounterFilter.get(DHCP6_DIRECT_FILTER).setPps(ppsDhcp6Direct);
}
if (newPpsDhcp6Indirect != ppsDhcp6Indirect) {
ppsDhcp6Indirect = newPpsDhcp6Indirect;
mapCounterFilter.get(DHCP6_INDIRECT_FILTER).setPps(ppsDhcp6Indirect);
}
if (newPpsIcmp != ppsIcmp) {
ppsIcmp = newPpsIcmp;
mapCounterFilter.get(ICMP_FILTER).setPps(ppsIcmp);
}
if (newPpsIcmp6 != ppsIcmp6) {
ppsIcmp6 = newPpsIcmp6;
mapCounterFilter.get(ICMP6_FILTER).setPps(ppsIcmp6);
}
}
private void checkChangeInWinSize(ComponentContext context) {
Dictionary<?, ?> properties = context.getProperties();
int newWinSizeArp, newWinSizeDhcp, newWinSizeNs, newWinSizeNa;
int newWinSizeDhcp6Direct, newWinSizeDhcp6Indirect, newWinSizeIcmp, newWinSizeIcmp6;
try {
String s = get(properties, PROP_WIN_SIZE_ARP_MS);
newWinSizeArp = isNullOrEmpty(s) ? winSizeArp : Integer.parseInt(s.trim());
s = get(properties, PROP_WIN_SIZE_DHCP_MS);
newWinSizeDhcp = isNullOrEmpty(s) ? winSizeDhcp : Integer.parseInt(s.trim());
s = get(properties, PROP_WIN_SIZE_NS_MS);
newWinSizeNs = isNullOrEmpty(s) ? winSizeNs : Integer.parseInt(s.trim());
s = get(properties, PROP_WIN_SIZE_NA_MS);
newWinSizeNa = isNullOrEmpty(s) ? winSizeNa : Integer.parseInt(s.trim());
s = get(properties, PROP_WIN_SIZE_DHCP6_DIRECT_MS);
newWinSizeDhcp6Direct = isNullOrEmpty(s) ? winSizeDhcp6Direct : Integer.parseInt(s.trim());
s = get(properties, PROP_WIN_SIZE_DHCP6_INDIRECT_MS);
newWinSizeDhcp6Indirect = isNullOrEmpty(s) ? winSizeDhcp6Indirect : Integer.parseInt(s.trim());
s = get(properties, PROP_WIN_SIZE_ICMP_MS);
newWinSizeIcmp = isNullOrEmpty(s) ? winSizeIcmp : Integer.parseInt(s.trim());
s = get(properties, PROP_WIN_SIZE_ICMP6_MS);
newWinSizeIcmp6 = isNullOrEmpty(s) ? winSizeIcmp6 : Integer.parseInt(s.trim());
} catch (NumberFormatException | ClassCastException e) {
newWinSizeArp = WIN_SIZE_ARP_MS_DEFAULT;
newWinSizeDhcp = WIN_SIZE_DHCP_MS_DEFAULT;
newWinSizeNs = WIN_SIZE_NS_MS_DEFAULT;
newWinSizeNa = WIN_SIZE_NA_MS_DEFAULT;
newWinSizeDhcp6Direct = WIN_SIZE_DHCP6_DIRECT_MS_DEFAULT;
newWinSizeDhcp6Indirect = WIN_SIZE_DHCP6_INDIRECT_MS_DEFAULT;
newWinSizeIcmp = WIN_SIZE_ICMP_MS_DEFAULT;
newWinSizeIcmp6 = WIN_SIZE_ICMP6_MS_DEFAULT;
}
if (newWinSizeArp != winSizeArp) {
winSizeArp = newWinSizeArp;
mapCounterFilter.get(ARP_FILTER).setWinSize(winSizeArp);
}
if (newWinSizeDhcp != winSizeDhcp) {
winSizeDhcp = newWinSizeDhcp;
mapCounterFilter.get(DHCP_FILTER).setWinSize(winSizeDhcp);
}
if (newWinSizeNs != winSizeNs) {
winSizeNs = newWinSizeNs;
mapCounterFilter.get(NS_FILTER).setWinSize(winSizeNs);
}
if (newWinSizeNa != winSizeNa) {
winSizeNa = newWinSizeNa;
mapCounterFilter.get(NA_FILTER).setWinSize(winSizeNa);
}
if (newWinSizeDhcp6Direct != winSizeDhcp6Direct) {
winSizeDhcp6Direct = newWinSizeDhcp6Direct;
mapCounterFilter.get(DHCP6_DIRECT_FILTER).setWinSize(winSizeDhcp6Direct);
}
if (newWinSizeDhcp6Indirect != winSizeDhcp6Indirect) {
winSizeDhcp6Indirect = newWinSizeDhcp6Indirect;
mapCounterFilter.get(DHCP6_INDIRECT_FILTER).setWinSize(winSizeDhcp6Indirect);
}
if (newWinSizeIcmp != winSizeIcmp) {
winSizeIcmp = newWinSizeIcmp;
mapCounterFilter.get(ICMP_FILTER).setWinSize(winSizeIcmp);
}
if (newWinSizeIcmp6 != winSizeIcmp6) {
winSizeIcmp6 = newWinSizeIcmp6;
mapCounterFilter.get(ICMP6_FILTER).setWinSize(winSizeIcmp6);
}
}
private void checkChangeInGuardTime(ComponentContext context) {
Dictionary<?, ?> properties = context.getProperties();
int newGuardTimeArp, newGuardTimeDhcp, newGuardTimeNs, newGuardTimeNa;
int newGuardTimeDhcp6Direct, newGuardTimeDhcp6Indirect, newGuardTimeIcmp, newGuardTimeIcmp6;
try {
String s = get(properties, PROP_GUARD_TIME_ARP_SEC);
newGuardTimeArp = isNullOrEmpty(s) ? guardTimeArp : Integer.parseInt(s.trim());
s = get(properties, PROP_GUARD_TIME_DHCP_SEC);
newGuardTimeDhcp = isNullOrEmpty(s) ? guardTimeDhcp : Integer.parseInt(s.trim());
s = get(properties, PROP_GUARD_TIME_NS_SEC);
newGuardTimeNs = isNullOrEmpty(s) ? guardTimeNs : Integer.parseInt(s.trim());
s = get(properties, PROP_GUARD_TIME_NA_SEC);
newGuardTimeNa = isNullOrEmpty(s) ? guardTimeNa : Integer.parseInt(s.trim());
s = get(properties, PROP_GUARD_TIME_DHCP6_DIRECT_SEC);
newGuardTimeDhcp6Direct = isNullOrEmpty(s) ? guardTimeDhcp6Direct : Integer.parseInt(s.trim());
s = get(properties, PROP_GUARD_TIME_DHCP6_INDIRECT_SEC);
newGuardTimeDhcp6Indirect = isNullOrEmpty(s) ? guardTimeDhcp6Indirect : Integer.parseInt(s.trim());
s = get(properties, PROP_GUARD_TIME_ICMP_SEC);
newGuardTimeIcmp = isNullOrEmpty(s) ? guardTimeIcmp : Integer.parseInt(s.trim());
s = get(properties, PROP_GUARD_TIME_ICMP6_SEC);
newGuardTimeIcmp6 = isNullOrEmpty(s) ? guardTimeIcmp6 : Integer.parseInt(s.trim());
} catch (NumberFormatException | ClassCastException e) {
newGuardTimeArp = GUARD_TIME_ARP_SEC_DEFAULT;
newGuardTimeDhcp = GUARD_TIME_DHCP_SEC_DEFAULT;
newGuardTimeNs = GUARD_TIME_NS_SEC_DEFAULT;
newGuardTimeNa = GUARD_TIME_NA_SEC_DEFAULT;
newGuardTimeDhcp6Direct = GUARD_TIME_DHCP6_DIRECT_SEC_DEFAULT;
newGuardTimeDhcp6Indirect = GUARD_TIME_DHCP6_INDIRECT_SEC_DEFAULT;
newGuardTimeIcmp = GUARD_TIME_ICMP_SEC_DEFAULT;
newGuardTimeIcmp6 = GUARD_TIME_ICMP6_SEC_DEFAULT;
}
if (newGuardTimeArp != guardTimeArp) {
guardTimeArp = newGuardTimeArp;
mapCounterFilter.get(ARP_FILTER).setGuardTime(guardTimeArp);
}
if (newGuardTimeDhcp != guardTimeDhcp) {
guardTimeDhcp = newGuardTimeDhcp;
mapCounterFilter.get(DHCP_FILTER).setGuardTime(guardTimeDhcp);
}
if (newGuardTimeNs != guardTimeNs) {
guardTimeNs = newGuardTimeNs;
mapCounterFilter.get(NS_FILTER).setGuardTime(guardTimeNs);
}
if (newGuardTimeNa != guardTimeNa) {
guardTimeNa = newGuardTimeNa;
mapCounterFilter.get(NA_FILTER).setGuardTime(guardTimeNa);
}
if (newGuardTimeDhcp6Direct != guardTimeDhcp6Direct) {
guardTimeDhcp6Direct = newGuardTimeDhcp6Direct;
mapCounterFilter.get(DHCP6_DIRECT_FILTER).setGuardTime(guardTimeDhcp6Direct);
}
if (newGuardTimeDhcp6Indirect != guardTimeDhcp6Indirect) {
guardTimeDhcp6Indirect = newGuardTimeDhcp6Indirect;
mapCounterFilter.get(DHCP6_INDIRECT_FILTER).setGuardTime(guardTimeDhcp6Indirect);
}
if (newGuardTimeIcmp != guardTimeIcmp) {
guardTimeIcmp = newGuardTimeIcmp;
mapCounterFilter.get(ICMP_FILTER).setGuardTime(guardTimeIcmp);
}
if (newGuardTimeIcmp6 != guardTimeIcmp6) {
guardTimeIcmp6 = newGuardTimeIcmp6;
mapCounterFilter.get(ICMP6_FILTER).setGuardTime(guardTimeIcmp6);
}
}
private void checkChangeInWinThres(ComponentContext context) {
Dictionary<?, ?> properties = context.getProperties();
int newWinThresArp, newWinThresDhcp, newWinThresNs, newWinThresNa;
int newWinThresDhcp6Direct, newWinThresDhcp6Indirect, newWinThresIcmp, newWinThresIcmp6;
try {
String s = get(properties, PROP_WIN_THRES_ARP);
newWinThresArp = isNullOrEmpty(s) ? winThresArp : Integer.parseInt(s.trim());
s = get(properties, PROP_WIN_THRES_DHCP);
newWinThresDhcp = isNullOrEmpty(s) ? winThresDhcp : Integer.parseInt(s.trim());
s = get(properties, PROP_WIN_THRES_NS);
newWinThresNs = isNullOrEmpty(s) ? winThresNs : Integer.parseInt(s.trim());
s = get(properties, PROP_WIN_THRES_NA);
newWinThresNa = isNullOrEmpty(s) ? winThresNa : Integer.parseInt(s.trim());
s = get(properties, PROP_WIN_THRES_DHCP6_DIRECT);
newWinThresDhcp6Direct = isNullOrEmpty(s) ? winThresDhcp6Direct : Integer.parseInt(s.trim());
s = get(properties, PROP_WIN_THRES_DHCP6_INDIRECT);
newWinThresDhcp6Indirect = isNullOrEmpty(s) ? winThresDhcp6Indirect : Integer.parseInt(s.trim());
s = get(properties, PROP_WIN_THRES_ICMP);
newWinThresIcmp = isNullOrEmpty(s) ? winThresIcmp : Integer.parseInt(s.trim());
s = get(properties, PROP_WIN_THRES_ICMP6);
newWinThresIcmp6 = isNullOrEmpty(s) ? winThresIcmp6 : Integer.parseInt(s.trim());
} catch (NumberFormatException | ClassCastException e) {
newWinThresArp = WIN_THRES_ARP_DEFAULT;
newWinThresDhcp = WIN_THRES_DHCP_DEFAULT;
newWinThresNs = WIN_THRES_NS_DEFAULT;
newWinThresNa = WIN_THRES_NA_DEFAULT;
newWinThresDhcp6Direct = WIN_THRES_DHCP6_DIRECT_DEFAULT;
newWinThresDhcp6Indirect = WIN_THRES_DHCP6_INDIRECT_DEFAULT;
newWinThresIcmp = WIN_THRES_ICMP_DEFAULT;
newWinThresIcmp6 = WIN_THRES_ICMP6_DEFAULT;
}
if (newWinThresArp != winThresArp) {
winThresArp = newWinThresArp;
mapCounterFilter.get(ARP_FILTER).setWinThres(winThresArp);
}
if (newWinThresDhcp != winThresDhcp) {
winThresDhcp = newWinThresDhcp;
mapCounterFilter.get(DHCP_FILTER).setWinThres(winThresDhcp);
}
if (newWinThresNs != winThresNs) {
winThresNs = newWinThresNs;
mapCounterFilter.get(NS_FILTER).setWinThres(winThresNs);
}
if (newWinThresNa != winThresNa) {
winThresNa = newWinThresNa;
mapCounterFilter.get(NA_FILTER).setWinThres(winThresNa);
}
if (newWinThresDhcp6Direct != winThresDhcp6Direct) {
winThresDhcp6Direct = newWinThresDhcp6Direct;
mapCounterFilter.get(DHCP6_DIRECT_FILTER).setWinThres(winThresDhcp6Direct);
}
if (newWinThresDhcp6Indirect != winThresDhcp6Indirect) {
winThresDhcp6Indirect = newWinThresDhcp6Indirect;
mapCounterFilter.get(DHCP6_INDIRECT_FILTER).setWinThres(winThresDhcp6Indirect);
}
if (newWinThresIcmp != winThresIcmp) {
winThresIcmp = newWinThresIcmp;
mapCounterFilter.get(ICMP_FILTER).setWinThres(winThresIcmp);
}
if (newWinThresIcmp6 != winThresIcmp6) {
winThresIcmp6 = newWinThresIcmp6;
mapCounterFilter.get(ICMP6_FILTER).setWinThres(winThresIcmp6);
}
}
@Modified
private void modified(ComponentContext context) {
if (context == null) {
log.info("Default config");
return;
}
checkChangeInPps(context);
checkChangeInWinSize(context);
checkChangeInGuardTime(context);
checkChangeInWinThres(context);
log.info("Reconfigured ppsArp: {} ppsDhcp: {} ppsNs: {} ppsNa: {} " +
"ppsDhcp6Direct: {} ppsDhcp6Indirect: {} ppsIcmp: {} ppsIcmp6: {}",
ppsArp, ppsDhcp, ppsNs, ppsNa, ppsDhcp6Direct, ppsDhcp6Indirect,
ppsIcmp, ppsIcmp6);
log.info("Reconfigured winSizeArp: {} winSizeDhcp: {} winSizeNs: {} winSizeNa: {} " +
"winSizeDhcp6Direct: {} winSizeDhcp6Indirect: {} winSizeIcmp: {} winSizeIcmp6: {}",
winSizeArp, winSizeDhcp, winSizeNs, winSizeNa, winSizeDhcp6Direct,
winSizeDhcp6Indirect, winSizeIcmp, winSizeIcmp6);
log.info("Reconfigured guardTimeArp: {} guardTimeDhcp: {} guardTimeNs: {} guardTimeNa: {} " +
"guardTimeDhcp6Direct: {} guardTimeDhcp6Indirect: {} guardTimeIcmp: {} guardTimeIcmp6: {}",
guardTimeArp, guardTimeDhcp, guardTimeNs, guardTimeNa, guardTimeDhcp6Direct,
guardTimeDhcp6Indirect, guardTimeIcmp, guardTimeIcmp6);
log.info("Reconfigured winThresArp: {} winThresDhcp: {} winThresNs: {} winThresNa: {} " +
"winThresDhcp6Direct: {} winThresDhcp6Indirect: {} winThresIcmp: {} winThresIcmp6: {}",
winThresArp, winThresDhcp, winThresNs, winThresNa, winThresDhcp6Direct,
winThresDhcp6Indirect, winThresIcmp, winThresIcmp6);
}
/**
* Create all required filters.
*/
private void createAllFilters() {
DefaultPacketInFilter filter;
ArpPacketClassifier arp = new ArpPacketClassifier();
filter = new DefaultPacketInFilter(ppsArp, winSizeArp, guardTimeArp, winThresArp, ARP_FILTER, arp);
packetService.addFilter(filter);
mapCounterFilter.put(filter.name(), filter);
DhcpPacketClassifier dhcp4 = new DhcpPacketClassifier();
filter = new DefaultPacketInFilter(ppsDhcp, winSizeDhcp, guardTimeDhcp, winThresDhcp, DHCP_FILTER, dhcp4);
packetService.addFilter(filter);
mapCounterFilter.put(filter.name(), filter);
Dhcp6DirectPacketClassifier dhcp6Direct = new Dhcp6DirectPacketClassifier();
filter = new DefaultPacketInFilter(ppsDhcp6Direct, winSizeDhcp6Direct, guardTimeDhcp6Direct,
winThresDhcp6Direct, DHCP6_DIRECT_FILTER, dhcp6Direct);
packetService.addFilter(filter);
mapCounterFilter.put(filter.name(), filter);
Dhcp6IndirectPacketClassifier dhcp6Indirect = new Dhcp6IndirectPacketClassifier();
filter = new DefaultPacketInFilter(ppsDhcp6Direct, winSizeDhcp6Direct, guardTimeDhcp6Direct,
winThresDhcp6Direct, DHCP6_INDIRECT_FILTER, dhcp6Indirect);
packetService.addFilter(filter);
mapCounterFilter.put(filter.name(), filter);
NAPacketClassifier na = new NAPacketClassifier();
filter = new DefaultPacketInFilter(ppsNa, winSizeNa, guardTimeNa, winThresNa, NA_FILTER, na);
packetService.addFilter(filter);
mapCounterFilter.put(filter.name(), filter);
NSPacketClassifier ns = new NSPacketClassifier();
filter = new DefaultPacketInFilter(ppsNs, winSizeNs, guardTimeNs, winThresNs, NS_FILTER, ns);
packetService.addFilter(filter);
mapCounterFilter.put(filter.name(), filter);
IcmpPacketClassifier icmp = new IcmpPacketClassifier();
filter = new DefaultPacketInFilter(ppsIcmp, winSizeIcmp, guardTimeIcmp, winThresIcmp, ICMP_FILTER, icmp);
packetService.addFilter(filter);
mapCounterFilter.put(filter.name(), filter);
Icmp6PacketClassifier icmp6 = new Icmp6PacketClassifier();
filter = new DefaultPacketInFilter(ppsIcmp6, winSizeIcmp6, guardTimeIcmp6, winThresIcmp6, ICMP6_FILTER, icmp6);
packetService.addFilter(filter);
mapCounterFilter.put(filter.name(), filter);
}
/**
* Delete all the filters.
*/
private void removeAllFilters() {
packetService.clearFilters();
mapCounterFilter.clear();
}
@Override
public Map<String, PacketInFilter> filterMap() {
return ImmutableMap.copyOf(mapCounterFilter);
}
}
|
AI39/cskaoyan14th-project4
|
guns-common-api/src/main/java/com/stylefeng/guns/rest/modular/film/service/FilmIndexService.java
|
<filename>guns-common-api/src/main/java/com/stylefeng/guns/rest/modular/film/service/FilmIndexService.java
package com.stylefeng.guns.rest.modular.film.service;
import com.stylefeng.guns.rest.modular.film.vo.FilmConditionVO;
import com.stylefeng.guns.rest.modular.film.vo.FilmIndexVO;
public interface FilmIndexService {
FilmIndexVO selectFilmIndexData();
FilmConditionVO selectFilmConditionData(int catId, int sourceId, int yearId);
}
|
ReddogStone/jabaku-c
|
Jabaku/math/matrix.h
|
<reponame>ReddogStone/jabaku-c
#ifndef JBK_MATH_MATRIX_H
#define JBK_MATH_MATRIX_H
//============================================
// All math functions assume right hand
// coordinate system.
//============================================
#include "math/scalar.h"
#include "math/vector.h"
#ifdef JBK_MATH_DEFAULT
#include "math/default/matrix_tpl_def.h"
#elif defined(JBK_MATH_XNAMATH)
#include "math/xnamath/matrix_tpl.h"
#else
#pragma message("Math not implemented!")
#endif
//============================================
// Matrix initialization
//============================================
JBKMatrix JBKMatrix_Zero();
JBKMatrix JBKMatrix_Identity();
JBKMatrix JBKMatrix_Set(float v11, float v12, float v13, float v14,
float v21, float v22, float v23, float v24,
float v31, float v32, float v33, float v34,
float v41, float v42, float v43, float v44);
JBKMatrix JBKMatrix_SetV(JBKVector4Reg v1, JBKVector4Reg v2, JBKVector4Reg v3, JBKVector4Ref v4);
//============================================
// Accessors
//============================================
JBKVector4 JBKMatrix_GetR0(JBKMatrixReg m);
JBKVector4 JBKMatrix_GetR1(JBKMatrixReg m);
JBKVector4 JBKMatrix_GetR2(JBKMatrixReg m);
JBKVector4 JBKMatrix_GetR3(JBKMatrixReg m);
//============================================
// Special matrices
//============================================
JBKMatrix JBKMatrix_Scale(JBKVector4Reg scaleVec3);
JBKMatrix JBKMatrix_RotationX(float angle);
JBKMatrix JBKMatrix_RotationY(float angle);
JBKMatrix JBKMatrix_RotationZ(float angle);
JBKMatrix JBKMatrix_RotationNormal(JBKVector4 normalizedAxis, float angle);
JBKMatrix JBKMatrix_Rotation(JBKVector4 axis, float angle);
JBKMatrix JBKMatrix_Translation(JBKVector4Reg transVec3);
JBKMatrix JBKMatrix_Look(JBKVector4Reg pos, JBKVector4Reg dir, JBKVector4Reg up);
JBKMatrix JBKMatrix_LookAt(JBKVector4Reg pos, JBKVector4Reg target, JBKVector4Reg up);
// The following matrices transform into projection space assuming the half Z space (i.e. z in [0, 1])
// for OpenGL or other libraries requiring full Z use JBKMatrix_ToFullZ() and multiply at the end
JBKMatrix JBKMatrix_Orthographic(float width, float height, float nearZ, float farZ);
JBKMatrix JBKMatrix_Perspective(float fovAngleY, float aspectXByY, float nearZ, float farZ);
JBKMatrix JBKMatrix_ToFullZ();
//============================================
// Matrix arithmetics
//============================================
JBKMatrix JBKMatrix_Add(JBKMatrixReg m1, JBKMatrixReg m2);
JBKMatrix JBKMatrix_Sub(JBKMatrixReg m1, JBKMatrixReg m2);
JBKMatrix JBKMatrix_Mul(JBKMatrixReg m1, JBKMatrixReg m2);
JBKMatrix JBKMatrix_MulByScalar(JBKMatrixReg m, JBKScalarReg s);
JBKMatrix JBKMatrix_DivByScalar(JBKMatrixReg m, JBKScalarReg s);
JBKScalar JBKMatrix_Determinant(JBKMatrixReg m);
JBKMatrix JBKMatrix_Inverse(JBKMatrixReg m, JBKScalar* det);
JBKMatrix JBKMatrix_Transpose(JBKMatrixReg m);
//============================================
// Vector transformation
//============================================
JBKVector4 JBKMatrix_TransformVec4(JBKVector4Reg v, JBKMatrixReg m);
JBKVector4 JBKMatrix_TransformVec3(JBKVector4Reg v, JBKMatrixReg m);
#endif // JBK_MATH_MATRIX_H
|
sandeepraju/plivo-java
|
src/main/java/com/plivo/helper/xml/elements/PreAnswer.java
|
<filename>src/main/java/com/plivo/helper/xml/elements/PreAnswer.java
package com.plivo.helper.xml.elements;
import java.util.ArrayList;
public class PreAnswer extends PlivoElement {
public PreAnswer() {
super(E_PREANSWER, null);
this.nestableElements = new ArrayList<String>();
this.nestableElements.add(E_PLAY);
this.nestableElements.add(E_SPEAK);
this.nestableElements.add(E_GETDIGITS);
this.nestableElements.add(E_WAIT);
this.nestableElements.add(E_REDIRECT);
}
}
|
hoehnp/SpaceDesignTool
|
sta-src/Astro-Core/perturbations.h
|
<filename>sta-src/Astro-Core/perturbations.h
/*
This program is free software; you can redistribute it and/or modify it under
the terms of the European Union Public Licence - EUPL v.1.1 as published by
the European Commission.
This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the European Union Public Licence - EUPL v.1.1
for more details.
You should have received a copy of the European Union Public Licence - EUPL v.1.1
along with this program.
Further information about the European Union Public Licence - EUPL v.1.1 can
also be found on the world wide web at http://ec.europa.eu/idabc/eupl
*/
/*
------ Copyright (C) 2010 STA Steering Board (space.trajectory.analysis AT gmail.com) ----
*/
/*
------------------ Author: <NAME> -------------------------------------------------
------------------ E-mail: (<EMAIL>) ----------------------------
*/
#ifndef PERTURBATIONS_H
#define PERTURBATIONS_H
#include "statevector.h"
#include "Scenario/scenario.h"
#include "Astro-Core/stabody.h"
#include <Eigen/Core>
USING_PART_OF_NAMESPACE_EIGEN
/**
* Abstract base class of all perturbations.
*/
class Perturbations
{
public:
Perturbations();
virtual ~Perturbations();
/**
* Abstract function calculating perturbing acceleration knowing the position of the body.
*/
virtual Vector3d calculateAcceleration(sta::StateVector state, double mjd, double dt);
};
/**
* Class representing planet's gravity field perturbation.
*/
class GravityPerturbations : public Perturbations
{
public:
GravityPerturbations(const StaBody* centralBody, const ScenarioGravityModel*);
~GravityPerturbations();
/**
* Return the central celestial body .
*/
const StaBody* body() const {return m_body;}
/**
* Return the number of zonals.
*/
int zonalCount() const { return m_zonalCount; }
/**
* Return the number of tesserals.
*/
int tesseralCount() const { return m_tesseralCount; }
/**
* Return the perturbing acceleration due to the planet's gravity field.
*/
virtual Vector3d calculateAcceleration(sta::StateVector, double, double);
private:
/**
* Function to load gravity constants from the gravity model file;
* Only the zonal (or tesseral) harmonics whose index is below the maximum zonal (or tesseral)
* index will be loaded.
*/
void loadGravityConstants();
const StaBody* m_body;
QString m_modelName;
int m_zonalCount;
int m_tesseralCount;
VectorXd J;
MatrixXd JJ;
MatrixXd gamma;
};
/**
* Function to calculate the factorial, used in the conversion from normalized to canonic harmonic coefficients.
*/
double factorial(int);
/**
* Function to calculate the double factorial, used in the calculation of Legendre polynomials.
*/
double doublefactorial(int);
/**
* Class representing Atmospheric Drag perturbation.
*/
class AtmosphericDragPerturbations : public Perturbations
{
public:
AtmosphericDragPerturbations(const QString& atmosphereModel);
virtual ~AtmosphericDragPerturbations();
/**
* Return the string containing the name of the atmospheric model.
*/
QString atmosphericModel() const {return m_atmosphericModel;}
/**
* Return the central celestial body .
*/
const StaBody* body() const {return m_body;}
/**
* Return the body surface area.
*/
double surface() const {return m_surface;}
/**
* Return the mass of the vehicle.
*/
double mass() const {return m_mass;}
/**
* Return the string of the name of the file containig the cd coefficients.
*/
QString cdCoefficients() const {return m_cdCoefficients;}
/**
* Return the perturbing acceleration due to the atmospheric drag.
*/
virtual Vector3d calculateAcceleration(sta::StateVector, double, double);
private:
QString m_atmosphericModel;
const StaBody* m_body;
double m_surface;
double m_mass;
QString m_cdCoefficients;
};
/**
* Class representing Solar Pressure perturbation.
*/
class SolarPressurePerturbations : public Perturbations
{
public:
SolarPressurePerturbations(StaBody* centralBody,
double reflectivity,
double albedo,
double ir,
double mass,
double surfaceArea);
virtual ~SolarPressurePerturbations();
/**
* Return the central celestial body .
*/
const StaBody* body() const {return m_body;}
/**
* Return the reflectivity of the vehicle.
*/
double reflectivity() const {return m_reflectivity;}
/**
* Return true if the albedo is taken into account in the simulation
*/
bool albedo() const {return m_albedo;}
/**
* Return true if the infra-red radiation is taken into account in the simulation
*/
bool ir() const {return m_ir;}
/**
* Return the body surface area.
*/
double surface() const {return m_surface;}
/**
* Return the mass of the vehicle.
*/
double mass() const {return m_mass;}
/**
* Return the perturbing acceleration due to the solar pressure.
*/
virtual Vector3d calculateAcceleration(sta::StateVector, double, double);
private:
const StaBody* m_body;
double m_reflectivity;
bool m_albedo;
bool m_ir;
double m_surface;
double m_mass;
};
/**
* Return the albedo reflectivity coefficient given the StaBody.
*/
double albedoReflectivityCoefficient(const StaBody*);
/**
* Return the infra-red radiation flux given the StaBody.
*/
double irRadiationFlux(const StaBody*);
/**
* Class representing External Bodies perturbation.
*/
class ExternalBodyPerturbations : public Perturbations
{
public:
ExternalBodyPerturbations(const StaBody* centralBody,
const QList<const StaBody*>& bodies);
virtual ~ExternalBodyPerturbations();
/**
* Return the central celestial body .
*/
const StaBody* body() const {return m_body;}
/**
* Return the list of perturbing celestial bodies.
*/
QList<const StaBody*> perturbingBodyList() const {return m_perturbingBodyList;}
/**
* Return the perturbing acceleration due to third bodies.
*/
virtual Vector3d calculateAcceleration(sta::StateVector, double, double);
private:
const StaBody* m_body;
QList<const StaBody*> m_perturbingBodyList;
};
/**
* Class representing Space Debris collisions perturbation.
*/
class DebrisPerturbations : public Perturbations
{
public:
DebrisPerturbations(const StaBody* centralBody,
double mass,
double surfaceArea);
virtual ~DebrisPerturbations();
/**
* Return the central celestial body .
*/
const StaBody* body() const {return m_body;}
/**
* Return the mass of the vehicle.
*/
double mass() const {return m_mass;}
/**
* Return the surface of the vehicle.
*/
double surface() const {return m_surface;}
/**
* Return the number of debris impacts already counted.
*/
VectorXd counterDebris() const {return m_counterDebris;}
/**
* Return the number of meteoroids impacts already counted.
*/
VectorXd counterMeteoroids() const {return m_counterMeteoroids;}
/**
* Set the number of impacts for a given diameter of debris.
*/
void setCounterDebris(int i, double counterd) {m_counterDebris(i) = counterd;}
/**
* Set the number of impacts for a given diameter of meteoroids.
*/
void setCounterMeteoroids(int i, double counterm) {m_counterMeteoroids(i) = counterm;}
/**
* Return the perturbing acceleration due to debris collisions perturbation.
*/
virtual Vector3d calculateAcceleration(sta::StateVector, double, double);
/**
* Load from a file the statistic data about the debris collisions.
*/
void loadStatistics(QString, VectorXd& , VectorXd&, VectorXd&, VectorXd&, int&);
private:
const StaBody* m_body;
double m_mass;
double m_surface;
double m_time;
VectorXd m_counterDebris;
VectorXd m_counterMeteoroids;
};
/**
* Function: evaluation of Legendre's associated function using recursive form.
* Source: Vallado, Fundamentals of Astrodynamics and Applications
* @param x The argument
* @param l The degree of polynomial
* @param m The order of derivative
* @return The evaluation of Legendre associated function
* Author: <NAME>
* E-mail: <EMAIL>
*/
double legendre (double x, int l, int m);
/**
* Generate a random number between inf and sup.
*/
double randomNumber(double inf, double sup);
#endif // PERTURBATIONS_H
|
alexNeto/previsao-tempo
|
src/test/java/com/ts/previsao/tempo/utils/UrlBuilderTest.java
|
package com.ts.previsao.tempo.utils;
import static org.junit.Assert.assertEquals;
import org.junit.Before;
import org.junit.Test;
public class UrlBuilderTest {
private UrlBuilder urlBuilder;
@Before
public void setUp() {
this.urlBuilder = new UrlBuilder();
}
@Test
public void testa_acao_de_procura_cidade() {
String esperado = "listaCidades?city=PARAMETRO";
assertEquals(esperado, this.urlBuilder.defineParametros(Acoes.PROCURAR_CIDADE));
}
@Test
public void testa_acao_de_previsao_de_7_dias() {
String esperado = "cidade/7dias/PARAMETRO/previsao.xml";
assertEquals(esperado, this.urlBuilder.defineParametros(Acoes.PREVISAO_7_DIAS));
}
@Test
public void testa_acao_desconhecida() {
String esperado = "";
assertEquals(esperado, this.urlBuilder.defineParametros(Acoes.PROCURA_ESTADO));
}
// TODO - implementar testes para metodo make
// public String make(Acoes acao, String parametro) {
// StringBuilder urlBuilder = new StringBuilder();
// urlBuilder.append(this.url).append("/");
// urlBuilder.append(this.dataType).append("/");
// urlBuilder.append(defineParametros(acao));
// return urlBuilder.toString().replace("PARAMETRO", parametro);
// }
}
|
CiscoDevNet/ydk-cpp
|
cisco-ios-xr/ydk/models/cisco_ios_xr/Cisco_IOS_XR_ncs5500_coherent_portmode_cfg.hpp
|
#ifndef _CISCO_IOS_XR_NCS5500_COHERENT_PORTMODE_CFG_
#define _CISCO_IOS_XR_NCS5500_COHERENT_PORTMODE_CFG_
#include <memory>
#include <vector>
#include <string>
#include <ydk/types.hpp>
#include <ydk/errors.hpp>
namespace cisco_ios_xr {
namespace Cisco_IOS_XR_ncs5500_coherent_portmode_cfg {
class DiffSel : public ydk::Enum
{
public:
static const ydk::Enum::YLeaf disable;
static const ydk::Enum::YLeaf enable;
static int get_enum_value(const std::string & name) {
if (name == "disable") return 0;
if (name == "enable") return 1;
return -1;
}
};
class ModSel : public ydk::Enum
{
public:
static const ydk::Enum::YLeaf qpsk;
static const ydk::Enum::YLeaf Y_8qam;
static const ydk::Enum::YLeaf Y_16qam;
static int get_enum_value(const std::string & name) {
if (name == "qpsk") return 1;
if (name == "8qam") return 2;
if (name == "16qam") return 3;
return -1;
}
};
class FecSel : public ydk::Enum
{
public:
static const ydk::Enum::YLeaf Y_15sdfec;
static const ydk::Enum::YLeaf Y_25sdfec;
static const ydk::Enum::YLeaf Y_15sdfecde;
static const ydk::Enum::YLeaf otu7staircase;
static int get_enum_value(const std::string & name) {
if (name == "15sdfec") return 0;
if (name == "25sdfec") return 1;
if (name == "15sdfecde") return 2;
if (name == "otu7staircase") return 3;
return -1;
}
};
class SpeedSel : public ydk::Enum
{
public:
static const ydk::Enum::YLeaf Y_100g;
static const ydk::Enum::YLeaf Y_150g;
static const ydk::Enum::YLeaf Y_200g;
static int get_enum_value(const std::string & name) {
if (name == "100g") return 100000000;
if (name == "150g") return 150000000;
if (name == "200g") return 200000000;
return -1;
}
};
}
}
#endif /* _CISCO_IOS_XR_NCS5500_COHERENT_PORTMODE_CFG_ */
|
atorber/easy-chatbot-manager-mp
|
miniprogram/page/weui/example/msg/msg.js
|
import CustomPage from '../../base/CustomPage'
CustomPage({
onShareAppMessage() {
return {
title: 'msg',
path: 'page/weui/example/msg/msg'
}
},
openSuccess() {
wx.navigateTo({
url: 'msg_success'
})
},
openText() {
wx.navigateTo({
url: 'msg_text'
})
},
openTextPrimary() {
wx.navigateTo({
url: 'msg_text_primary'
})
},
openFail() {
wx.navigateTo({
url: 'msg_fail'
})
}
})
|
manggoguy/parsec-modified
|
pkgs/libs/mesa/src/src/mesa/drivers/dri/mga/mgavb.c
|
<filename>pkgs/libs/mesa/src/src/mesa/drivers/dri/mga/mgavb.c
/*
* Copyright 2000-2001 VA Linux Systems, Inc.
* All Rights Reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* on the rights to use, copy, modify, merge, publish, distribute, sub
* license, and/or sell copies of the Software, and to permit persons to whom
* the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice (including the next
* paragraph) shall be included in all copies or substantial portions of the
* Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL
* VA LINUX SYSTEMS AND/OR ITS SUPPLIERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*
* Authors:
* <NAME> <<EMAIL>>
*/
/* $XFree86: xc/lib/GL/mesa/src/drv/mga/mgavb.c,v 1.15 2003/03/26 20:43:49 tsi Exp $ */
#include <stdlib.h>
#include "mgacontext.h"
#include "mgavb.h"
#include "mgatris.h"
#include "mgaioctl.h"
#include "mga_xmesa.h"
#include "glheader.h"
#include "mtypes.h"
#include "imports.h"
#include "macros.h"
#include "colormac.h"
#include "tnl/t_context.h"
#include "swrast_setup/swrast_setup.h"
#include "swrast/swrast.h"
#define MGA_TEX1_BIT 0x1
#define MGA_TEX0_BIT 0x2
#define MGA_RGBA_BIT 0x4
#define MGA_SPEC_BIT 0x8
#define MGA_FOG_BIT 0x10
#define MGA_XYZW_BIT 0x20
#define MGA_PTEX_BIT 0x40
#define MGA_MAX_SETUP 0x80
static struct {
void (*emit)( GLcontext *, GLuint, GLuint, void *, GLuint );
tnl_interp_func interp;
tnl_copy_pv_func copy_pv;
GLboolean (*check_tex_sizes)( GLcontext *ctx );
GLuint vertex_size;
GLuint vertex_format;
} setup_tab[MGA_MAX_SETUP];
#define TINY_VERTEX_FORMAT 0
#define NOTEX_VERTEX_FORMAT 0
#define TEX0_VERTEX_FORMAT (MGA_A|MGA_S|MGA_F)
#define TEX1_VERTEX_FORMAT (MGA_A|MGA_S|MGA_F|MGA_T2)
#define PROJ_TEX1_VERTEX_FORMAT 0
#define TEX2_VERTEX_FORMAT 0
#define TEX3_VERTEX_FORMAT 0
#define PROJ_TEX3_VERTEX_FORMAT 0
#define DO_XYZW (IND & MGA_XYZW_BIT)
#define DO_RGBA (IND & MGA_RGBA_BIT)
#define DO_SPEC (IND & MGA_SPEC_BIT)
#define DO_FOG (IND & MGA_FOG_BIT)
#define DO_TEX0 (IND & MGA_TEX0_BIT)
#define DO_TEX1 (IND & MGA_TEX1_BIT)
#define DO_TEX2 0
#define DO_TEX3 0
#define DO_PTEX (IND & MGA_PTEX_BIT)
#define VERTEX mgaVertex
#define VERTEX_COLOR mga_color_t
#define LOCALVARS mgaContextPtr mmesa = MGA_CONTEXT(ctx);
#define GET_VIEWPORT_MAT() mmesa->hw_viewport
#define GET_TEXSOURCE(n) mmesa->tmu_source[n]
#define GET_VERTEX_FORMAT() mmesa->vertex_format
#define GET_VERTEX_STORE() mmesa->verts
#define GET_VERTEX_SIZE() mmesa->vertex_size * sizeof(GLuint)
#define HAVE_HW_VIEWPORT 0
#define HAVE_HW_DIVIDE 0
#define HAVE_RGBA_COLOR 0
#define HAVE_TINY_VERTICES 0
#define HAVE_NOTEX_VERTICES 0
#define HAVE_TEX0_VERTICES 1
#define HAVE_TEX1_VERTICES 1
#define HAVE_TEX2_VERTICES 0
#define HAVE_TEX3_VERTICES 0
#define HAVE_PTEX_VERTICES 0
#define UNVIEWPORT_VARS \
const GLfloat dx = - mmesa->drawX - SUBPIXEL_X; \
const GLfloat dy = (mmesa->driDrawable->h + \
mmesa->drawY + SUBPIXEL_Y); \
const GLfloat sz = 1.0 / mmesa->depth_scale
#define UNVIEWPORT_X(x) x + dx;
#define UNVIEWPORT_Y(y) - y + dy;
#define UNVIEWPORT_Z(z) z * sz;
#define PTEX_FALLBACK() FALLBACK(ctx, MGA_FALLBACK_TEXTURE, 1)
#define INTERP_VERTEX setup_tab[mmesa->SetupIndex].interp
#define COPY_PV_VERTEX setup_tab[mmesa->SetupIndex].copy_pv
/***********************************************************************
* Generate pv-copying and translation functions *
***********************************************************************/
#define TAG(x) mga_##x
#include "tnl_dd/t_dd_vb.c"
/***********************************************************************
* Generate vertex emit and interp functions *
***********************************************************************/
#define IND (MGA_XYZW_BIT|MGA_RGBA_BIT)
#define TAG(x) x##_wg
#include "tnl_dd/t_dd_vbtmp.h"
#define IND (MGA_XYZW_BIT|MGA_RGBA_BIT|MGA_SPEC_BIT)
#define TAG(x) x##_wgs
#include "tnl_dd/t_dd_vbtmp.h"
#define IND (MGA_XYZW_BIT|MGA_RGBA_BIT|MGA_TEX0_BIT)
#define TAG(x) x##_wgt0
#include "tnl_dd/t_dd_vbtmp.h"
#define IND (MGA_XYZW_BIT|MGA_RGBA_BIT|MGA_TEX0_BIT|MGA_TEX1_BIT)
#define TAG(x) x##_wgt0t1
#include "tnl_dd/t_dd_vbtmp.h"
#define IND (MGA_XYZW_BIT|MGA_RGBA_BIT|MGA_TEX0_BIT|MGA_PTEX_BIT)
#define TAG(x) x##_wgpt0
#include "tnl_dd/t_dd_vbtmp.h"
#define IND (MGA_XYZW_BIT|MGA_RGBA_BIT|MGA_SPEC_BIT|MGA_TEX0_BIT)
#define TAG(x) x##_wgst0
#include "tnl_dd/t_dd_vbtmp.h"
#define IND (MGA_XYZW_BIT|MGA_RGBA_BIT|MGA_SPEC_BIT|MGA_TEX0_BIT|MGA_TEX1_BIT)
#define TAG(x) x##_wgst0t1
#include "tnl_dd/t_dd_vbtmp.h"
#define IND (MGA_XYZW_BIT|MGA_RGBA_BIT|MGA_SPEC_BIT|MGA_TEX0_BIT|MGA_PTEX_BIT)
#define TAG(x) x##_wgspt0
#include "tnl_dd/t_dd_vbtmp.h"
#define IND (MGA_XYZW_BIT|MGA_RGBA_BIT|MGA_FOG_BIT)
#define TAG(x) x##_wgf
#include "tnl_dd/t_dd_vbtmp.h"
#define IND (MGA_XYZW_BIT|MGA_RGBA_BIT|MGA_FOG_BIT|MGA_SPEC_BIT)
#define TAG(x) x##_wgfs
#include "tnl_dd/t_dd_vbtmp.h"
#define IND (MGA_XYZW_BIT|MGA_RGBA_BIT|MGA_FOG_BIT|MGA_TEX0_BIT)
#define TAG(x) x##_wgft0
#include "tnl_dd/t_dd_vbtmp.h"
#define IND (MGA_XYZW_BIT|MGA_RGBA_BIT|MGA_FOG_BIT|MGA_TEX0_BIT|MGA_TEX1_BIT)
#define TAG(x) x##_wgft0t1
#include "tnl_dd/t_dd_vbtmp.h"
#define IND (MGA_XYZW_BIT|MGA_RGBA_BIT|MGA_FOG_BIT|MGA_TEX0_BIT|MGA_PTEX_BIT)
#define TAG(x) x##_wgfpt0
#include "tnl_dd/t_dd_vbtmp.h"
#define IND (MGA_XYZW_BIT|MGA_RGBA_BIT|MGA_FOG_BIT|MGA_SPEC_BIT|MGA_TEX0_BIT)
#define TAG(x) x##_wgfst0
#include "tnl_dd/t_dd_vbtmp.h"
#define IND (MGA_XYZW_BIT|MGA_RGBA_BIT|MGA_FOG_BIT|MGA_SPEC_BIT|MGA_TEX0_BIT|MGA_TEX1_BIT)
#define TAG(x) x##_wgfst0t1
#include "tnl_dd/t_dd_vbtmp.h"
#define IND (MGA_XYZW_BIT|MGA_RGBA_BIT|MGA_FOG_BIT|MGA_SPEC_BIT|MGA_TEX0_BIT|MGA_PTEX_BIT)
#define TAG(x) x##_wgfspt0
#include "tnl_dd/t_dd_vbtmp.h"
#define IND (MGA_TEX0_BIT)
#define TAG(x) x##_t0
#include "tnl_dd/t_dd_vbtmp.h"
#define IND (MGA_TEX0_BIT|MGA_TEX1_BIT)
#define TAG(x) x##_t0t1
#include "tnl_dd/t_dd_vbtmp.h"
#define IND (MGA_FOG_BIT)
#define TAG(x) x##_f
#include "tnl_dd/t_dd_vbtmp.h"
#define IND (MGA_FOG_BIT|MGA_TEX0_BIT)
#define TAG(x) x##_ft0
#include "tnl_dd/t_dd_vbtmp.h"
#define IND (MGA_FOG_BIT|MGA_TEX0_BIT|MGA_TEX1_BIT)
#define TAG(x) x##_ft0t1
#include "tnl_dd/t_dd_vbtmp.h"
#define IND (MGA_RGBA_BIT)
#define TAG(x) x##_g
#include "tnl_dd/t_dd_vbtmp.h"
#define IND (MGA_RGBA_BIT|MGA_SPEC_BIT)
#define TAG(x) x##_gs
#include "tnl_dd/t_dd_vbtmp.h"
#define IND (MGA_RGBA_BIT|MGA_TEX0_BIT)
#define TAG(x) x##_gt0
#include "tnl_dd/t_dd_vbtmp.h"
#define IND (MGA_RGBA_BIT|MGA_TEX0_BIT|MGA_TEX1_BIT)
#define TAG(x) x##_gt0t1
#include "tnl_dd/t_dd_vbtmp.h"
#define IND (MGA_RGBA_BIT|MGA_SPEC_BIT|MGA_TEX0_BIT)
#define TAG(x) x##_gst0
#include "tnl_dd/t_dd_vbtmp.h"
#define IND (MGA_RGBA_BIT|MGA_SPEC_BIT|MGA_TEX0_BIT|MGA_TEX1_BIT)
#define TAG(x) x##_gst0t1
#include "tnl_dd/t_dd_vbtmp.h"
#define IND (MGA_RGBA_BIT|MGA_FOG_BIT)
#define TAG(x) x##_gf
#include "tnl_dd/t_dd_vbtmp.h"
#define IND (MGA_RGBA_BIT|MGA_FOG_BIT|MGA_SPEC_BIT)
#define TAG(x) x##_gfs
#include "tnl_dd/t_dd_vbtmp.h"
#define IND (MGA_RGBA_BIT|MGA_FOG_BIT|MGA_TEX0_BIT)
#define TAG(x) x##_gft0
#include "tnl_dd/t_dd_vbtmp.h"
#define IND (MGA_RGBA_BIT|MGA_FOG_BIT|MGA_TEX0_BIT|MGA_TEX1_BIT)
#define TAG(x) x##_gft0t1
#include "tnl_dd/t_dd_vbtmp.h"
#define IND (MGA_RGBA_BIT|MGA_FOG_BIT|MGA_SPEC_BIT|MGA_TEX0_BIT)
#define TAG(x) x##_gfst0
#include "tnl_dd/t_dd_vbtmp.h"
#define IND (MGA_RGBA_BIT|MGA_FOG_BIT|MGA_SPEC_BIT|MGA_TEX0_BIT|MGA_TEX1_BIT)
#define TAG(x) x##_gfst0t1
#include "tnl_dd/t_dd_vbtmp.h"
static void init_setup_tab( void )
{
init_wg();
init_wgs();
init_wgt0();
init_wgt0t1();
init_wgpt0();
init_wgst0();
init_wgst0t1();
init_wgspt0();
init_wgf();
init_wgfs();
init_wgft0();
init_wgft0t1();
init_wgfpt0();
init_wgfst0();
init_wgfst0t1();
init_wgfspt0();
init_t0();
init_t0t1();
init_f();
init_ft0();
init_ft0t1();
init_g();
init_gs();
init_gt0();
init_gt0t1();
init_gst0();
init_gst0t1();
init_gf();
init_gfs();
init_gft0();
init_gft0t1();
init_gfst0();
init_gfst0t1();
}
void mgaPrintSetupFlags(char *msg, GLuint flags )
{
fprintf(stderr, "%s: %d %s%s%s%s%s%s\n",
msg,
(int)flags,
(flags & MGA_XYZW_BIT) ? " xyzw," : "",
(flags & MGA_RGBA_BIT) ? " rgba," : "",
(flags & MGA_SPEC_BIT) ? " spec," : "",
(flags & MGA_FOG_BIT) ? " fog," : "",
(flags & MGA_TEX0_BIT) ? " tex-0," : "",
(flags & MGA_TEX1_BIT) ? " tex-1," : "");
}
void mgaCheckTexSizes( GLcontext *ctx )
{
mgaContextPtr mmesa = MGA_CONTEXT( ctx );
TNLcontext *tnl = TNL_CONTEXT(ctx);
/*fprintf(stderr, "%s\n", __FUNCTION__);*/
if (!setup_tab[mmesa->SetupIndex].check_tex_sizes(ctx)) {
mmesa->SetupIndex |= MGA_PTEX_BIT;
mmesa->SetupNewInputs = ~0;
if (!mmesa->Fallback &&
!(ctx->_TriangleCaps & (DD_TRI_LIGHT_TWOSIDE|DD_TRI_UNFILLED))) {
tnl->Driver.Render.Interp = setup_tab[mmesa->SetupIndex].interp;
tnl->Driver.Render.CopyPV = setup_tab[mmesa->SetupIndex].copy_pv;
}
if (mmesa->Fallback) {
tnl->Driver.Render.Start(ctx);
}
}
}
void mgaBuildVertices( GLcontext *ctx,
GLuint start,
GLuint count,
GLuint newinputs )
{
mgaContextPtr mmesa = MGA_CONTEXT( ctx );
GLuint stride = mmesa->vertex_size * sizeof(int);
GLubyte *v = ((GLubyte *)mmesa->verts + (start * stride));
newinputs |= mmesa->SetupNewInputs;
mmesa->SetupNewInputs = 0;
if (!newinputs)
return;
if (newinputs & VERT_BIT_POS) {
setup_tab[mmesa->SetupIndex].emit( ctx, start, count, v, stride );
} else {
GLuint ind = 0;
if (newinputs & VERT_BIT_COLOR0)
ind |= MGA_RGBA_BIT;
if (newinputs & VERT_BIT_COLOR1)
ind |= MGA_SPEC_BIT;
if (newinputs & VERT_BIT_TEX0)
ind |= MGA_TEX0_BIT;
if (newinputs & VERT_BIT_TEX1)
ind |= MGA_TEX0_BIT|MGA_TEX1_BIT;
if (newinputs & VERT_BIT_FOG)
ind |= MGA_FOG_BIT;
if (mmesa->SetupIndex & MGA_PTEX_BIT)
ind = ~0;
ind &= mmesa->SetupIndex;
if (ind) {
setup_tab[ind].emit( ctx, start, count, v, stride );
}
}
}
void mgaChooseVertexState( GLcontext *ctx )
{
mgaContextPtr mmesa = MGA_CONTEXT( ctx );
TNLcontext *tnl = TNL_CONTEXT(ctx);
GLuint ind = MGA_XYZW_BIT|MGA_RGBA_BIT;
if (ctx->_TriangleCaps & DD_SEPARATE_SPECULAR)
ind |= MGA_SPEC_BIT;
if (ctx->Fog.Enabled)
ind |= MGA_FOG_BIT;
if (ctx->Texture._EnabledUnits & 0x2) {
/* unit 1 enabled */
if (ctx->Texture._EnabledUnits & 0x1) {
/* unit 0 enabled */
ind |= MGA_TEX1_BIT|MGA_TEX0_BIT;
}
else {
ind |= MGA_TEX0_BIT;
}
}
else if (ctx->Texture._EnabledUnits & 0x1) {
/* unit 0 enabled */
ind |= MGA_TEX0_BIT;
}
mmesa->SetupIndex = ind;
if (ctx->_TriangleCaps & (DD_TRI_LIGHT_TWOSIDE|DD_TRI_UNFILLED)) {
tnl->Driver.Render.Interp = mga_interp_extras;
tnl->Driver.Render.CopyPV = mga_copy_pv_extras;
} else {
tnl->Driver.Render.Interp = setup_tab[ind].interp;
tnl->Driver.Render.CopyPV = setup_tab[ind].copy_pv;
}
if (setup_tab[ind].vertex_format != mmesa->vertex_format) {
FLUSH_BATCH(mmesa);
mmesa->dirty |= MGA_UPLOAD_PIPE;
mmesa->vertex_format = setup_tab[ind].vertex_format;
mmesa->vertex_size = setup_tab[ind].vertex_size;
}
}
void *mga_emit_contiguous_verts( GLcontext *ctx,
GLuint start,
GLuint count,
void *dest)
{
mgaContextPtr mmesa = MGA_CONTEXT(ctx);
GLuint stride = mmesa->vertex_size * 4;
setup_tab[mmesa->SetupIndex].emit( ctx, start, count, dest, stride );
return (void *)((char *)dest + stride * (count - start));
}
void mgaInitVB( GLcontext *ctx )
{
mgaContextPtr mmesa = MGA_CONTEXT(ctx);
GLuint size = TNL_CONTEXT(ctx)->vb.Size;
mmesa->verts = (GLubyte *)ALIGN_MALLOC(size * sizeof(mgaVertex), 32);
{
static int firsttime = 1;
if (firsttime) {
init_setup_tab();
firsttime = 0;
}
}
mmesa->dirty |= MGA_UPLOAD_PIPE;
mmesa->vertex_format = setup_tab[0].vertex_format;
mmesa->vertex_size = setup_tab[0].vertex_size;
}
void mgaFreeVB( GLcontext *ctx )
{
mgaContextPtr mmesa = MGA_CONTEXT(ctx);
if (mmesa->verts) {
ALIGN_FREE(mmesa->verts);
mmesa->verts = 0;
}
}
|
shaylinj/Web_Project
|
PhotoApplicationRepo/src/test/java/za/ac/nwu/repo/persistence/imageTest.java
|
package za.ac.nwu.repo.persistence;
import za.ac.nwu.domain.persistence.Photo;
import za.ac.nwu.repo.config.RepositoryTestConfiguration;
import org.hibernate.annotations.Cascade;
import org.hibernate.annotations.CascadeType;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.jupiter.api.DisplayName;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;
import javax.transaction.Transactional;
import static org.junit.Assert.*;
@RunWith(SpringRunner.class)
@DataJpaTest
@ContextConfiguration(classes = {RepositoryTestConfiguration.class})
public interface imageTest
{
@Autowired
ImageRepo imageRepo;
@Before
public void setUp() throws Exception {
}
@After
public void tearDown() throws Exception {
}
@Transactional
@Test
@DisplayName("Update image metadata.")
public void updateImage() {
Image image = imageRepo.findImageId(3);
assertNotNull(image);
int result = imageRepo.updateImage("<NAME>", "Johannesburg", "<NAME>", 3);
assertEquals(result, 3);
}
@Transactional
@Cascade(CascadeType.ALL)
@Test(expected = DataIntegrityViolationException.class)
@DisplayName("Delete image by id and link.")
public void deleteImageIdAndImageLink() {
Image image = imageRepo.findImageId(2);
assertNotNull(image);
int value = imageRepo.deleteImageIdAndImageLink(2, "IMG_002.jpeg");
assertEquals(value, 2);
}
@Test
@DisplayName("Find photo by id.")
public void findImageId() {
Image image = imageRepo.findImageId(1);
assertNotNull(image);
assertEquals("Cape Town", image.getPhotoLocation());
}
@Test
@DisplayName("Verify photo exists")
public void existImageIdAndImageLink() {
boolean value = imageRepo.existImageIdAndImageLink(4, "IMG_004.jpeg");
assertTrue(value);
}
}
|
plimkilde/DHMQC
|
qc/contours.py
|
# -*- coding: utf-8 -*-
import os,sys
import shutil
from argparse import ArgumentParser
import subprocess
import tempfile
import time
import datetime
import random
from osgeo import gdal
from osgeo import ogr
from osgeo import osr
import numpy as np
from scipy.signal import convolve2d
from . import dhmqc_constants as constants
gdal.UseExceptions()
ogr.UseExceptions()
# Can be called from a project file containing following statements:
#TESTNAME="contours"
#INPUT_TILE_CONNECTION=r"dtm_bro.sqlite"
#TARGS=[r"""dbname='dbname' host='IP-nummer' port='5432' user='user' password='<PASSWORD>'""",
#r"P:\ath\to\dtm_without_bridges.vrt",
#"-schema", "kurvtest"]
#print (TARGS)
extent = 200
target_resolution = 1.6 # værdier til generalisering af kurver
interval = 0.5
progname=os.path.basename(__file__)
parser=ArgumentParser(description="calculate a 1km contour file with 50 cm interval",prog=progname)
parser.add_argument("tilename", help="Tilename to calculate (eg 1km_6666_666)")
parser.add_argument("dbout", help="sqlite file for output")
parser.add_argument("dtm_path", help="path to terrain file (vrt or large tiff)")
parser.add_argument("-schema", help="if using a postgis db it may be beneficial to add a schema name")
buf = float(extent)
# 1km grid kurveberegning
#Get the extent from a tilename (1km_NNNN_EEE). Can return a wkt)
def create1km(tilename, buf, return_wkt=False):
#might throw an exception - wrap in try, except...
tile_size = 1000
N,E=tilename.split("_")[1:3]
N=int(N)
E=int(E)
xt=(E*tile_size-buf,N*tile_size-buf,(E+1)*tile_size+buf,(N+1)*tile_size+buf)
if return_wkt:
wkt="POLYGON(("
for dx,dy in ((0,0),(0,1),(1,1),(1,0)):
wkt+="{0:.2f} {1:.2f},".format(xt[2*dx],xt[2*dy+1])
wkt+="{0:.2f} {1:.2f}))".format(xt[0],xt[1])
return wkt
#x1,y1,x2,y2 - fits into the array_geometry.bbox_to_polygon method
return xt
# 10km grid kurveberegning
# Get the extent from a tilename (10km_NNN_EEE). Can return a wkt)
def create10km(tilename, buf, return_wkt=False):
#might throw an exception - wrap in try, except...
tile_size = 10000
N,E=tilename.split("_")[1:3]
N=int(N)
E=int(E)
xt=(E*tile_size-buf,N*tile_size-buf,(E+1)*tile_size+buf,(N+1)*tile_size+buf)
if return_wkt:
wkt="POLYGON(("
for dx,dy in ((0,0),(0,1),(1,1),(1,0)):
wkt+="{0:.2f} {1:.2f},".format(xt[2*dx],xt[2*dy+1])
wkt+="{0:.2f} {1:.2f}))".format(xt[0],xt[1])
return wkt
#x1,y1,x2,y2 - fits into the array_geometry.bbox_to_polygon method
return xt
# Gauss filter til brug i beregning - NIKS PILLE
def gauss_smooth_geotiff(input_filename, output_filename, kernel_width, georef_stddev):
"""
Perform Gaussian smoothing on a one-band GeoTIFF file.
Args:
input_filename: Filename of the input GeoTIFF file.
output_filename: Filename of the output GeoTIFF file (the smoothed data).
kernel_width: (Integer) size in pixels of the Gaussian kernel.
georef_stddev: Standard deviation of the Gaussian distribution, in georeferenced units.
"""
kernel_x, kernel_y = np.meshgrid(np.arange(0, kernel_width) + 0.5 - 0.5*kernel_width, 0.5*kernel_width - np.arange(0, kernel_width) - 0.5)
input_datasrc = gdal.Open(input_filename)
input_band = input_datasrc.GetRasterBand(1)
input_geo_transform = input_datasrc.GetGeoTransform()
input_projection = input_datasrc.GetProjection()
input_nodata_value = input_band.GetNoDataValue()
input_array_data_raw = input_band.ReadAsArray()
# Prepare Gauss kernel
kernel_georef_x = input_geo_transform[1] * kernel_x
kernel_georef_y = -input_geo_transform[5] * kernel_y
kernel_georef_r = np.sqrt(kernel_georef_x**2 + kernel_georef_y**2)
kernel_georef_gauss = 1./np.sqrt(2*np.pi*georef_stddev**2) * np.exp(-kernel_georef_r**2/(2*georef_stddev**2))
# Perform convolution on data and mask
input_array_data = input_array_data_raw.copy()
input_array_data[input_array_data_raw == input_nodata_value] = 0.0 #avoid propagating NaNs
input_array_mask = (input_array_data_raw != input_nodata_value).astype(np.float)
convolved_weights = convolve2d(input_array_mask, kernel_georef_gauss, mode='same')
convolved_array_data = convolve2d(input_array_data, kernel_georef_gauss, mode='same')
output_array_data = np.full_like(input_array_data, np.nan)
# Normalize each pixel from the convolved data based on the convolved mask
output_mask = convolved_weights != 0.0
output_array_data[output_mask] = convolved_array_data[output_mask] / convolved_weights[output_mask]
num_output_rows, num_output_cols = output_array_data.shape
output_driver = gdal.GetDriverByName("GTiff")
output_datasrc = output_driver.Create(output_filename, num_output_cols, num_output_rows, 1, gdal.GDT_Float32)
output_datasrc.SetProjection(input_projection)
output_datasrc.SetGeoTransform(input_geo_transform)
output_band = output_datasrc.GetRasterBand(1)
output_band.SetNoDataValue(input_nodata_value)
output_band.WriteArray(output_array_data)
output_band.FlushCache()
def main(args):
pargs=parser.parse_args(args[1:])
dtm_path = pargs.dtm_path
tilename = constants.get_tilename(pargs.tilename)
blindspot = open(os.devnull, 'w')
#obsolete checks from old code. Kept it here anyway but needs tidying up. Check could be better with "if '1km' in tilename..."
if tilename[0:3] == '1km':
create1km(tilename, buf)
bbox = create1km(tilename, buf)
bbox_tile = create1km(tilename, buf=0)
elif tilename[0:4] == '10km':
create10km(tilename)
bbox = create10km(tilename, buf)
bbox_tile = create10km(tilename, buf=0)
# Temporary library for calculation
temp_dir = tempfile.mkdtemp()
bbox_kmname = '%s %s %s %s' %(bbox_tile[0], bbox_tile[1], bbox_tile[2], bbox_tile[3])
bbox_grid = '%s %s %s %s' %(bbox[0], bbox[2], bbox[1], bbox[3])
bbox_te = '%s %s %s %s' %(bbox[0], bbox[1], bbox[2], bbox[3])
"""
Kurveberegning
"""
# print ("-----cutting dtm hard-----\n")
temp_dtm_hard = os.path.join(temp_dir,'temp_dtm_hard.tif')
exestr = 'gdalwarp -of GTiff -tr %s %s -tap -dstnodata -9999 -r bilinear -s_srs epsg:25832 -t_srs epsg:25832 -te %s %s %s -q' %(target_resolution, target_resolution, bbox_te, dtm_path, temp_dtm_hard)
subprocess.call(exestr, shell=True)
# print ("\n-----Finished cutting-----\n\n")
# print ("-----running gauss filter-----\n")
temp_dtm_gauss = os.path.join(temp_dir,'gauss.tif')
gauss_smooth_geotiff(temp_dtm_hard, temp_dtm_gauss, 3, 12)
# print ("\n-----gauss filter complete-----\n\n")
# print ("-----calculate roughness index-----\n")
temp_dtm_rough = os.path.join(temp_dir,'temp_dtm_rough.tif')
exestr = 'gdaldem roughness -of GTiff %s %s -q' %(temp_dtm_hard, temp_dtm_rough)
subprocess.call(exestr, shell=True)
# print ("\n-----Finished roughness calc-----\n\n")
# print ("-----joining dtm after roughness-----\n")
temp_dtm_join = os.path.join(temp_dir,'temp_dtm_join.tif')
exestr = 'gdal_calc -A %s -B %s -C %s --calc="(A<5)*C+(A>=5)*(A<=10)*((((A-5.0)/(10.0-5))*B)+(1-((A-5.0)/(10.0-5)))*C)+(A>10)*B" --outfile=%s --NoDataValue=-9999 --quiet' %(temp_dtm_rough, temp_dtm_hard, temp_dtm_gauss, temp_dtm_join)
subprocess.check_call(exestr, shell=True)
# print ("\n-----Finished cutting-----\n\n")
#Following has been commented out - for using a land polygon. Not implemented for now.
# rasterizing "GeoDK landpolygon", to cut nodata outside coastal line
# print ('geodk landpolygon til raster')
# temp_landraster = os.path.join(temp_dir,'temp_landraster.tif')
# exestr = 'gdal_rasterize -tr %s %s -burn 1 -init 0 -a_nodata -9999 -te %s -ot Float32 -of GTiff %s %s' %(target_resolution, target_resolution, bbox_te, landpolygon, temp_landraster)
# subprocess.call(exestr, shell=True)
# print ("-----cutting landmass-----\n")
# temp_dtm_kun_land = os.path.join(temp_dir,'temp_dtm_kun_land.tif')
# exestr = 'gdal_calc -A %s -B %s --calc="(A*B)" --outfile=%s --NoDataValue=-9999' %(temp_dtm_join, temp_landraster, temp_dtm_kun_land)
# subprocess.call(exestr, shell=True)
# print ("\n-----Finished cutting-----\n\n")
# print ("-----Contouring------\n")
temp_contours = os.path.join(temp_dir,'temp_contours.shp')
exestr= 'gdal_contour -a kote -i %s -f "ESRI Shapefile" %s %s' %(interval, temp_dtm_join, temp_contours)
subprocess.call(exestr, shell=True, stdout=blindspot)
# print ("\n-----Contouring finished------\n\n")
exestr = 'ogrinfo %s -sql "alter table temp_contours add column km_name string" -q' %(temp_contours)
subprocess.call(exestr, shell=True)
# print ("-----km_name added to table------\n")
exestr = 'ogrinfo %s -dialect SQLite -sql "update temp_contours set km_name=\'%s\' " -q' %(temp_contours, tilename)
subprocess.call(exestr, shell=True)
# print ("-----km_name update------\n")
print ("-----inserting to db------\n")
# Ekstrempunkter og kurveberegning til database.
"""
Skema skal eksistere i forvejen. Tabel behøver ikke.
"""
#if dbout is an sqlite connection it will be generated. Works with a MP set low.
if '.sqlite' in pargs.dbout:
if not os.path.isfile(pargs.dbout):
time.sleep(random.randint(0,20))
exestr = """ogr2ogr -f SQLite -a_srs epsg:25832 -dsco SPATIALITE=YES %s %s -lco SPATIAL_INDEX=NO -nln contours -clipdst %s -nlt PROMOTE_TO_MULTI -skipfailures""" %(pargs.dbout,temp_contours,bbox_kmname)
if os.path.isfile(pargs.dbout):
exestr = """ogr2ogr -f SQLite -a_srs epsg:25832 -append %s %s -nln contours -clipdst %s -nlt PROMOTE_TO_MULTI -skipfailures""" %(pargs.dbout, temp_contours, bbox_kmname)
else:
exestr = """ogr2ogr -f SQLite -a_srs epsg:25832 -append %s %s -nln contours -clipdst %s -nlt PROMOTE_TO_MULTI -skipfailures""" %(pargs.dbout, temp_contours, bbox_kmname)
subprocess.call(exestr, shell=True, stdout=blindspot)
else:
#if dbout is NOT sqlite, we will write to the postgis db, also using the -schema attrib
exestr = """ogr2ogr -f PostgreSQL PG:"%s" %s -nln %s.f_contours -nlt PROMOTE_TO_MULTI -append -clipdst %s""" %(pargs.dbout, temp_contours, pargs.schema, bbox_kmname)
subprocess.call(exestr, shell=True)
#print ("\n-----All finished-----\n\n\n\n\n")
shutil.rmtree(temp_dir)
if __name__=="__main__":
main(sys.argv)
|
minhtrung2606/remitano_funny_videos
|
model/GeneralFailureResp.js
|
const Response = require('./Response');
class GeneralFailureResponse extends Response {
constructor(detail) {
super(false, `Requested operation Failed. ${detail}`);
}
}
const HTML_CODE = 500;
GeneralFailureResponse.handle = (res, detail = '') => {
const respose = new GeneralFailureResponse(detail);
res.status(HTML_CODE).json(respose);
};
module.exports = GeneralFailureResponse;
|
eperret/omakase
|
src/test/java/com/salesforce/omakase/test/util/TemplatesHelper.java
|
<filename>src/test/java/com/salesforce/omakase/test/util/TemplatesHelper.java
/*
* Copyright (c) 2015, salesforce.com, 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 salesforce.com, 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 com.salesforce.omakase.test.util;
/**
* Common CSS source template strings for unit testing.
*
* @author nmcwilliams
*/
@SuppressWarnings("JavaDoc")
public final class TemplatesHelper {
public static final String GENERIC_CSS_SOURCE = ".test {\n" +
" color: #16ff2b;\n" +
"}\n" +
"\n" +
"#test2 {\n" +
" margin: 5px 10px;\n" +
" padding: 10px;\n" +
" border: 1px solid red;\n" +
" border-radius: 10px;\n" +
"}\n" +
"\n" +
"a:link {\n" +
" color: blue;\n" +
" text-decoration: none;\n" +
"}\n" +
"\n" +
"a:hover, a:focus {\n" +
" color: red;\n" +
" text-decoration: red;\n" +
"}";
private static final String TEMPLATE_SELECTOR = "%s { color: red; }";
private static final String TEMPLATE_PROPERTY_VALUE = ".test { %s: %s; }";
/** do not construct */
private TemplatesHelper() {}
/**
* Gets a basic rule with the given selector.
*
* @param selector
* The full selector string.
*
* @return The CSS source code.
*/
public static String fillSelector(String selector) {
return String.format(TEMPLATE_SELECTOR, selector);
}
/**
* Gets a basic rule with the given property name and value.
*
* @param name
* The property name.
* @param value
* The property value.
*
* @return The CSS source code.
*/
public static String fillDeclaration(String name, String value) {
return String.format(TEMPLATE_PROPERTY_VALUE, name, value);
}
/**
* Gets a version of {@link #GENERIC_CSS_SOURCE} that's a lot lot longer.
*
* @return The source.
*/
public static StringBuilder longSource() {
StringBuilder src = new StringBuilder(GENERIC_CSS_SOURCE.length() * 40);
for (int i = 0; i < 40; i++) {
src.append(GENERIC_CSS_SOURCE).append("\n\n");
}
return src;
}
/**
* Combines a CSS source with an expected result (e.g., parsing result) to be used in unit test verification.
*
* @param <T>
* Type of the expected result.
* @param source
* The complete CSS source.
* @param expected
* The expected result.
*
* @return A new {@link SourceWithExpectedResult} instance.
*/
public static <T> SourceWithExpectedResult<T> withExpectedResult(String source, T expected) {
SourceWithExpectedResult<T> ts = new SourceWithExpectedResult<>();
ts.source = source;
ts.expected = expected;
return ts;
}
/**
* A CSS source combined with a generic result.
*
* @param <T>
* The type of the result.
*/
public static final class SourceWithExpectedResult<T> {
/** The CSS source */
public String source;
/** The expected result */
public T expected;
}
}
|
dlasalle/domlib
|
tests/hashtable_all_test.c
|
#include "test.h"
#define N 1000000
#define M ((N)/2)
#define K 33
sint_t test(void)
{
sint_t i, j;
ss_ht_t * map = ss_ht_create(N,M);
for (i=0;i<M;++i) {
j = i*K;
ss_ht_put(j,j+10,map);
}
ss_ht_put(2*N,3,map);
ss_ht_put(3*N,4,map);
ss_ht_put(4*N,5,map);
for (i=0;i<M;++i) {
j = i*K;
TESTEQUALS(ss_ht_get(j,map),j+10,PF_SINT_T);
}
TESTEQUALS(ss_ht_get(2*N,map),3,PF_SINT_T);
for (i=M;i>M/2;) {
--i;
j = i*K;
TESTEQUALS(ss_ht_remove(j,map),j+10,PF_SINT_T);
}
for (i=0;i<M/2;++i) {
j = i*K;
TESTEQUALS(ss_ht_remove(j,map),j+10,PF_SINT_T);
}
TESTEQUALS(ss_ht_remove(4*N,map),5,PF_SINT_T);
TESTEQUALS(ss_ht_remove(2*N,map),3,PF_SINT_T);
TESTEQUALS(ss_ht_remove(3*N,map),4,PF_SINT_T);
TESTEQUALS(map->size,0UL,PF_SIZE_T);
ss_ht_free(map);
return 0;
}
|
laohubuzaijia/fbthrift
|
thrift/compiler/mustache/template_type.cpp
|
<reponame>laohubuzaijia/fbthrift
/*
The source code contained in this file is based on the original code by
<NAME> (https://github.com/no1msd/mstch). The original license by Daniel
Sipka can be read below:
The MIT License (MIT)
Copyright (c) 2015 <NAME>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#include "thrift/compiler/mustache/template_type.h"
namespace apache {
namespace thrift {
namespace mstch {
template_type::template_type(const std::string& str, const delim_type& delims)
: m_open(delims.first), m_close(delims.second) {
tokenize(str);
strip_whitespace();
}
template_type::template_type(const std::string& str)
: m_open("{{"), m_close("}}") {
tokenize(str);
strip_whitespace();
}
void template_type::process_text(citer begin, citer end) {
if (begin == end) {
return;
}
auto start = begin;
for (auto it = begin; it != end; ++it) {
if (*it == '\n' || it == end - 1) {
m_tokens.push_back({{start, it + 1}});
start = it + 1;
}
}
}
void template_type::tokenize(const std::string& tmp) {
citer beg = tmp.begin();
auto npos = std::string::npos;
for (std::size_t cur_pos = 0; cur_pos < tmp.size();) {
auto open_pos = tmp.find(m_open, cur_pos);
auto close_pos =
tmp.find(m_close, open_pos == npos ? open_pos : open_pos + 1);
if (close_pos != npos && open_pos != npos) {
process_text(beg + cur_pos, beg + open_pos);
cur_pos = close_pos + m_close.size();
m_tokens.push_back(
{{beg + open_pos, beg + close_pos + m_close.size()},
m_open.size(),
m_close.size()});
if (cur_pos == tmp.size()) {
m_tokens.push_back({{""}});
m_tokens.back().eol(true);
}
if (*(beg + open_pos + m_open.size()) == '=' &&
*(beg + close_pos - 1) == '=') {
auto tok_beg = beg + open_pos + m_open.size() + 1;
auto tok_end = beg + close_pos - 1;
auto front_skip = first_not_ws(tok_beg, tok_end);
auto back_skip = first_not_ws(reverse(tok_end), reverse(tok_beg));
m_open = {front_skip, beg + tmp.find(' ', front_skip - beg)};
m_close = {beg + tmp.rfind(' ', back_skip - beg) + 1, back_skip + 1};
}
} else {
process_text(beg + cur_pos, tmp.end());
cur_pos = close_pos;
}
}
}
void template_type::strip_whitespace() {
auto erases = std::vector<bool>();
erases.resize(m_tokens.size());
auto line_begin = m_tokens.begin();
bool has_tag = false, non_space = false;
for (auto it = m_tokens.begin(); it != m_tokens.end(); ++it) {
auto type = (*it).token_type();
if (type != token::type::text && type != token::type::variable) {
has_tag = true;
} else if (!(*it).ws_only()) {
non_space = true;
}
if ((*it).eol()) {
if (has_tag && !non_space) {
store_prefixes(line_begin);
auto c = line_begin;
for (bool end = false; !end; ++c) {
if ((end = (*c).eol())) {
it = c - 1;
}
if ((*c).ws_only()) {
erases[c - m_tokens.begin()] = true;
}
}
}
non_space = has_tag = false;
line_begin = it + 1;
}
}
size_t compact = 0;
for (size_t expanded = 0; expanded < m_tokens.size(); ++expanded) {
if (!erases[expanded]) {
std::swap(m_tokens[compact], m_tokens[expanded]);
++compact;
}
}
m_tokens.erase(m_tokens.begin() + compact, m_tokens.end());
}
void template_type::store_prefixes(std::vector<token>::iterator beg) {
for (auto cur = beg; !(*cur).eol(); ++cur) {
if ((*cur).token_type() == token::type::partial && cur != beg &&
(*(cur - 1)).ws_only()) {
(*cur).partial_prefix((*(cur - 1)).raw());
}
}
}
} // namespace mstch
} // namespace thrift
} // namespace apache
|
stigger/AppleScript-IDEA
|
src/main/java/com/intellij/plugin/applescript/lang/ide/highlighting/AppleScriptSyntaxHighlighterFactory.java
|
/*
* Copyright (C) 2014, Cast & Crew (R) Software, LLC
* All rights reserved. Unauthorized disclosure or distribution is prohibited.
*/
package com.intellij.plugin.applescript.lang.ide.highlighting;
import com.intellij.openapi.fileTypes.SyntaxHighlighter;
import com.intellij.openapi.fileTypes.SyntaxHighlighterFactory;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vfs.VirtualFile;
import org.jetbrains.annotations.NotNull;
public class AppleScriptSyntaxHighlighterFactory extends SyntaxHighlighterFactory {
@NotNull
@Override
public SyntaxHighlighter getSyntaxHighlighter(Project project, VirtualFile virtualFile) {
return new AppleScriptSyntaxHighlighter();
}
}
|
HeyLey/catboost
|
catboost/libs/helpers/wx_test.h
|
<filename>catboost/libs/helpers/wx_test.h
#pragma once
#include <util/generic/vector.h>
#include <util/generic/ymath.h>
#include <util/generic/algorithm.h>
/*
* Inspired by vpdelta@ FML implementation
*/
struct TWxTestResult {
double WPlus = 0;
double WMinus = 0;
double PValue = 0;
};
TWxTestResult WxTest(const TVector<double>& baseline,
const TVector<double>& test);
|
gaurav46/heroic
|
discovery/simple/src/main/java/com/spotify/heroic/cluster/discovery/simple/SrvRecordDiscovery.java
|
/*
* Copyright (c) 2015 Spotify AB.
*
* 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 com.spotify.heroic.cluster.discovery.simple;
import java.net.URI;
import java.util.List;
import java.util.Optional;
import javax.inject.Inject;
import javax.inject.Named;
import org.xbill.DNS.DClass;
import org.xbill.DNS.Lookup;
import org.xbill.DNS.Record;
import org.xbill.DNS.SRVRecord;
import org.xbill.DNS.Type;
import com.google.common.collect.ImmutableList;
import com.spotify.heroic.cluster.ClusterDiscovery;
import eu.toolchain.async.AsyncFramework;
import eu.toolchain.async.AsyncFuture;
import lombok.RequiredArgsConstructor;
import lombok.ToString;
import lombok.extern.slf4j.Slf4j;
@RequiredArgsConstructor
@ToString
@Slf4j
public class SrvRecordDiscovery implements ClusterDiscovery {
public static final String DEFAULT_PROTOCOL = "nativerpc";
public static final int DEFAULT_PORT = 1394;
@Inject
private AsyncFramework async;
@Inject
@Named("records")
private List<String> records;
@Inject
@Named("protocol")
private Optional<String> protocol;
@Inject
@Named("port")
private Optional<Integer> port;
@Override
public AsyncFuture<List<URI>> find() {
final ImmutableList.Builder<AsyncFuture<List<URI>>> lookups = ImmutableList.builder();
for (final String record : records) {
lookups.add(async.call(() -> {
log.info("Resolving SRV records for: {}", record);
final Lookup lookup = new Lookup(record, Type.SRV, DClass.IN);
final Record[] result = lookup.run();
if (lookup.getResult() != Lookup.SUCCESSFUL) {
log.error("Failed to lookup record: {}: {}", record, lookup.getErrorString());
return ImmutableList.<URI> of();
}
final ImmutableList.Builder<URI> results = ImmutableList.builder();
if (result != null) {
for (final Record a : result) {
final SRVRecord srv = (SRVRecord) a;
results.add(new URI(protocol.orElse(DEFAULT_PROTOCOL) + "://"
+ srv.getTarget().canonicalize() + ":"
+ port.orElse(DEFAULT_PORT)));
}
}
return results.build();
}));
}
return async.collect(lookups.build()).directTransform(all -> {
final ImmutableList.Builder<URI> results = ImmutableList.builder();
all.forEach(results::addAll);
return results.build();
});
}
}
|
chihlee/phantomjs
|
src/qt/qtbase/src/tools/qdoc/codemarker.h
|
/****************************************************************************
**
** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of the tools applications of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL21$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://qt.digia.com/licensing. For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 or version 3 as published by the Free
** Software Foundation and appearing in the file LICENSE.LGPLv21 and
** LICENSE.LGPLv3 included in the packaging of this file. Please review the
** following information to ensure the GNU Lesser General Public License
** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** $QT_END_LICENSE$
**
****************************************************************************/
/*
codemarker.h
*/
#ifndef CODEMARKER_H
#define CODEMARKER_H
#include <qpair.h>
#include "atom.h"
#include "node.h"
QT_BEGIN_NAMESPACE
class Config;
typedef QMultiMap<QString, Node*> MemberMap; // the string is the member signature
typedef QPair<const QmlClassNode*, MemberMap> ClassMap; // the node is the QML type
typedef QList<ClassMap*> ClassMapList;
typedef QPair<QStringList, NodeList> KeysAndNodes;
typedef QPair<const QmlClassNode*, KeysAndNodes> ClassKeysNodes;
typedef QList<ClassKeysNodes*> ClassKeysNodesList;
struct Section
{
QString name;
QString divClass;
QString singularMember;
QString pluralMember;
QStringList keys;
NodeList members;
NodeList reimpMembers;
QList<QPair<InnerNode *, int> > inherited;
ClassKeysNodesList classKeysNodesList_;
Section() { }
Section(const QString& name0,
const QString& divClass0,
const QString& singularMember0,
const QString& pluralMember0)
: name(name0),
divClass(divClass0),
singularMember(singularMember0),
pluralMember(pluralMember0) { }
~Section();
void appendMember(Node* node) { members.append(node); }
void appendReimpMember(Node* node) { reimpMembers.append(node); }
};
struct FastSection
{
const InnerNode *parent_;
QString name;
QString divClass;
QString singularMember;
QString pluralMember;
QMultiMap<QString, Node *> memberMap;
QMultiMap<QString, Node *> reimpMemberMap;
ClassMapList classMapList_;
QList<QPair<InnerNode *, int> > inherited;
FastSection(const InnerNode *parent,
const QString& name0,
const QString& divClass0,
const QString& singularMember0,
const QString& pluralMember0)
: parent_(parent),
name(name0),
divClass(divClass0),
singularMember(singularMember0),
pluralMember(pluralMember0) { }
~FastSection();
bool isEmpty() const {
return (memberMap.isEmpty() &&
inherited.isEmpty() &&
reimpMemberMap.isEmpty() &&
classMapList_.isEmpty());
}
};
class CodeMarker
{
public:
enum SynopsisStyle { Summary, Detailed, Subpage, Accessors };
enum Status { Compat, Obsolete, Okay };
CodeMarker();
virtual ~CodeMarker();
virtual void initializeMarker(const Config& config);
virtual void terminateMarker();
virtual bool recognizeCode(const QString& code) = 0;
virtual bool recognizeExtension(const QString& ext) = 0;
virtual bool recognizeLanguage(const QString& lang) = 0;
virtual Atom::Type atomType() const = 0;
virtual QString markedUpCode(const QString& code,
const Node *relative,
const Location &location) = 0;
virtual QString markedUpSynopsis(const Node *node,
const Node *relative,
SynopsisStyle style) = 0;
virtual QString markedUpQmlItem(const Node* , bool) { return QString(); }
virtual QString markedUpName(const Node *node) = 0;
virtual QString markedUpFullName(const Node *node,
const Node *relative = 0) = 0;
virtual QString markedUpEnumValue(const QString &enumValue,
const Node *relative) = 0;
virtual QString markedUpIncludes(const QStringList& includes) = 0;
virtual QString functionBeginRegExp(const QString& funcName) = 0;
virtual QString functionEndRegExp(const QString& funcName) = 0;
virtual QList<Section> sections(const InnerNode *inner,
SynopsisStyle style,
Status status) = 0;
virtual QList<Section> qmlSections(QmlClassNode* qmlClassNode,
SynopsisStyle style,
Status status = Okay);
virtual QStringList macRefsForNode(Node* node);
static void initialize(const Config& config);
static void terminate();
static CodeMarker *markerForCode(const QString& code);
static CodeMarker *markerForFileName(const QString& fileName);
static CodeMarker *markerForLanguage(const QString& lang);
static const Node *nodeForString(const QString& string);
static QString stringForNode(const Node *node);
QString typified(const QString &string);
protected:
virtual QString sortName(const Node *node, const QString* name = 0);
QString protect(const QString &string);
QString taggedNode(const Node* node);
QString taggedQmlNode(const Node* node);
QString linkTag(const Node *node, const QString& body);
void insert(FastSection &fastSection,
Node *node,
SynopsisStyle style,
Status status);
bool insertReimpFunc(FastSection& fs, Node* node, Status status);
void append(QList<Section>& sectionList, const FastSection& fastSection, bool includeKeys = false);
private:
QString macName(const Node *parent, const QString &name = QString());
static QString defaultLang;
static QList<CodeMarker *> markers;
};
QT_END_NAMESPACE
#endif
|
J-VOL/mage
|
Mage.Sets/src/mage/cards/c/ChaosDragon.java
|
<filename>Mage.Sets/src/mage/cards/c/ChaosDragon.java
package mage.cards.c;
import mage.MageInt;
import mage.abilities.Ability;
import mage.abilities.common.AttacksEachCombatStaticAbility;
import mage.abilities.common.BeginningOfCombatTriggeredAbility;
import mage.abilities.effects.OneShotEffect;
import mage.abilities.effects.RestrictionEffect;
import mage.abilities.keyword.FlyingAbility;
import mage.abilities.keyword.HasteAbility;
import mage.cards.CardImpl;
import mage.cards.CardSetInfo;
import mage.constants.*;
import mage.game.Game;
import mage.game.permanent.Permanent;
import mage.players.Player;
import java.util.*;
/**
* @author TheElk801
*/
public final class ChaosDragon extends CardImpl {
public ChaosDragon(UUID ownerId, CardSetInfo setInfo) {
super(ownerId, setInfo, new CardType[]{CardType.CREATURE}, "{1}{R}{R}");
this.subtype.add(SubType.DRAGON);
this.power = new MageInt(4);
this.toughness = new MageInt(4);
// Flying
this.addAbility(FlyingAbility.getInstance());
// Haste
this.addAbility(HasteAbility.getInstance());
// Chaos Dragon attacks each combat if able.
this.addAbility(new AttacksEachCombatStaticAbility());
// At the beginning of combat on your turn, each player rolls a d20. If one or more opponents had the highest result, Chaos Dragon can't attack those players or planeswalkers they control this combat.
this.addAbility(new BeginningOfCombatTriggeredAbility(
new ChaosDragonEffect(), TargetController.YOU, false
));
}
private ChaosDragon(final ChaosDragon card) {
super(card);
}
@Override
public ChaosDragon copy() {
return new ChaosDragon(this);
}
}
class ChaosDragonEffect extends OneShotEffect {
ChaosDragonEffect() {
super(Outcome.Benefit);
staticText = "each player rolls a d20. If one or more opponents had the highest result, " +
"{this} can't attack those players or planeswalkers they control this combat";
}
private ChaosDragonEffect(final ChaosDragonEffect effect) {
super(effect);
}
@Override
public ChaosDragonEffect copy() {
return new ChaosDragonEffect(this);
}
@Override
public boolean apply(Game game, Ability source) {
Map<Integer, Set<UUID>> playerMap = new HashMap<>();
for (UUID playerId : game.getState().getPlayersInRange(source.getControllerId(), game)) {
Player player = game.getPlayer(playerId);
if (player == null) {
return false;
}
playerMap.computeIfAbsent(player.rollDice(outcome, source, game, 20), x -> new HashSet<>()).add(playerId);
}
int max = playerMap.keySet().stream().mapToInt(x -> x).max().orElse(0);
game.addEffect(new ChaosDragonRestrictionEffect(playerMap.get(max)), source);
return true;
}
}
class ChaosDragonRestrictionEffect extends RestrictionEffect {
private final Set<UUID> playerSet = new HashSet<>();
public ChaosDragonRestrictionEffect(Set<UUID> playerSet) {
super(Duration.EndOfCombat, Outcome.Benefit);
this.playerSet.addAll(playerSet);
}
ChaosDragonRestrictionEffect(final ChaosDragonRestrictionEffect effect) {
super(effect);
this.playerSet.addAll(effect.playerSet);
}
@Override
public boolean applies(Permanent permanent, Ability source, Game game) {
return permanent.equals(source.getSourcePermanentIfItStillExists(game));
}
@Override
public boolean canAttack(Permanent attacker, UUID defenderId, Ability source, Game game, boolean canUseChooseDialogs) {
if (playerSet.contains(defenderId)) {
return false;
}
Permanent planeswalker = game.getPermanent(defenderId);
return planeswalker == null || !playerSet.contains(planeswalker.getControllerId());
}
@Override
public ChaosDragonRestrictionEffect copy() {
return new ChaosDragonRestrictionEffect(this);
}
}
|
jmthompson2015/gamefinder
|
converter/MechanicGenerator.js
|
const R = require("ramda");
const CharacterConverter = require("./CharacterConverter.js");
const FileLoader = require("./FileLoader.js");
const FileWriter = require("./FileWriter.js");
const MechanicGenerator = {};
const INPUT_FILE = "GameDetail.json";
const PROPERTY = "mechanics";
const OUTPUT_FILE = "../artifact/Mechanic.js";
const HEADER = `const Mechanic = `;
const FOOTER = `
Object.freeze(Mechanic);
export default Mechanic;`;
MechanicGenerator.convert = () => {
FileLoader.loadLocalFile(INPUT_FILE).then(data => {
const gameToDetail = JSON.parse(data);
const gameDetails = Object.values(gameToDetail);
const reduceFunction1 = (accum, detail) =>
detail[PROPERTY] ? R.concat(detail[PROPERTY], accum) : accum;
const allItem = R.reduce(reduceFunction1, [], gameDetails);
const pipeFunction = R.pipe(
R.dissoc("type"),
R.dissoc("count")
);
const reduceFunction2 = (accum, item) => {
const newItem0 = pipeFunction(item);
const newName = CharacterConverter.convert(newItem0.name);
const newItem = R.assoc("name", newName, newItem0);
return R.assoc(newItem.id, newItem, accum);
};
const itemMap = R.reduce(reduceFunction2, {}, allItem);
const content = `${HEADER}${JSON.stringify(itemMap, null, " ")}${FOOTER}`;
FileWriter.writeFile(OUTPUT_FILE, content);
});
};
MechanicGenerator.convert();
|
Justis-Lamanna/Fracktail_3
|
src/main/java/com/github/milomarten/fracktail3/modules/moon/MoonPhase.java
|
package com.github.milomarten.fracktail3.modules.moon;
import lombok.Data;
@Data
public class MoonPhase {
private final double angle;
public boolean isFull() {
return getCoverage() > 99.5;
}
public boolean isNew() {
return getCoverage() < 0.5;
}
public boolean isWaning() {
return angle < 0;
}
public boolean isWaxing() {
return angle > 0;
}
public double getCoverage() {
return Math.abs(angle);
}
}
|
phatblat/macOSPrivateFrameworks
|
PrivateFrameworks/FinderKit/FI_TSearchScopeSliceController.h
|
//
// Generated by class-dump 3.5 (64 bit).
//
// class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2013 by <NAME>.
//
#import <FinderKit/FI_TViewController.h>
@class NSObject<TSearchScopeSliceControllerDelegate>;
__attribute__((visibility("hidden")))
@interface FI_TSearchScopeSliceController : FI_TViewController
{
}
- (void)setScopePlusMinusButtonTitle:(_Bool)arg1;
- (void)setScopePlusMinusButtonEnabled:(_Bool)arg1;
- (void)setSaveButtonEnabled:(_Bool)arg1;
- (id)currentScopeString;
- (unsigned long long)scopeSelection;
- (void)setScopeSelection:(unsigned long long)arg1;
- (void)setButtonTitles:(const vector_757c8b87 *)arg1 andToolTips:(const vector_757c8b87 *)arg2;
@property __weak NSObject<TSearchScopeSliceControllerDelegate> *scopeSliceDelegate; // @dynamic scopeSliceDelegate;
- (id)scopeSlice;
- (id)nibName;
@end
|
uc43/TTQP
|
library/imports/b7/b7908bd0-d96a-43fb-bf8e-86a3c7beee1c.js
|
<filename>library/imports/b7/b7908bd0-d96a-43fb-bf8e-86a3c7beee1c.js<gh_stars>0
"use strict";
cc._RF.push(module, 'b7908vQ2WpD+7+OhqPHvu4c', 'HomeBottomView');
// Script/HomeScript/HomeBottomView/HomeBottomView.js
"use strict";
var socket = require("websocketScript");
cc.Class({
extends: cc.Component,
properties: {
menusBtnArray: [cc.Node],
// 红点,顺序分别是 签到、邮件、活动
emailRedPointIcon: [cc.Node],
// 更多
moreView: cc.Node
},
onLoad: function onLoad() {
// 红点主推接口
onfire.on("HomeGetRedPointHandle", this.onRedPointHandle.bind(this));
var windowSize = cc.view.getVisibleSize();
var intervalX = 4;
var menusW = (windowSize.width - intervalX * (this.menusBtnArray.length - 1)) / this.menusBtnArray.length;
for (var j = 0; j < this.menusBtnArray.length; j++) {
var menusBtn = this.menusBtnArray[j];
if (j == 5) {
menusBtn.width = menusW + 10;
menusBtn.setPosition(cc.p((intervalX + menusW) * j - 5, 0));
} else {
menusBtn.width = menusW;
menusBtn.setPosition(cc.p((intervalX + menusW) * j, 0));
}
}
// 调整moreView的位置
this.moreView.setPosition(cc.p((windowSize.width - this.moreView.width) / 2 - menusW / 4 * 5.3, -310));
},
/**
* 配置邮件按钮右上角的红点图标
*/
onRedPointHandle: function onRedPointHandle(data) {
//
}
});
cc._RF.pop();
|
TheAwesomeGem/BlockDropsTweaker
|
src/main/java/net/theawesomegem/blockdropstweaker/common/event/EventHandlerCommon.java
|
<reponame>TheAwesomeGem/BlockDropsTweaker<gh_stars>1-10
package net.theawesomegem.blockdropstweaker.common.event;
import net.minecraft.block.Block;
import net.minecraft.block.state.IBlockState;
import net.minecraft.enchantment.Enchantment;
import net.minecraft.enchantment.EnchantmentHelper;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.util.math.MathHelper;
import net.minecraft.world.World;
import net.minecraft.world.biome.Biome;
import net.minecraftforge.event.world.BlockEvent;
import net.minecraftforge.event.world.BlockEvent.HarvestDropsEvent;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
import net.theawesomegem.blockdropstweaker.common.blockconfig.BlockDropData;
import net.theawesomegem.blockdropstweaker.common.blockconfig.ConfigurationHandler;
import net.theawesomegem.blockdropstweaker.common.blockconfig.DropData;
import net.theawesomegem.blockdropstweaker.common.blockconfig.FortuneQuantityData;
import net.theawesomegem.blockdropstweaker.hook.GameStageHook;
import net.theawesomegem.blockdropstweaker.hook.TConstructHook;
import java.util.AbstractMap.SimpleEntry;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Random;
/**
* Created by TheAwesomeGem on 12/21/2017.
*/
public class EventHandlerCommon
{
@SubscribeEvent
public void onBreakBlock(BlockEvent.BreakEvent e)
{
World world = e.getWorld();
if(world.isRemote)
return;
IBlockState blockState = e.getState();
Block block = blockState.getBlock();
String blockID = block.getRegistryName().toString();
int metadata = block.getMetaFromState(blockState);
BlockDropData blockDropData = ConfigurationHandler.getBlockDropData(block, blockID, metadata);
if(blockDropData == null)
return;
e.setExpToDrop(0);
}
@SubscribeEvent
public void onHarvestBlock(HarvestDropsEvent e)
{
World world = e.getWorld();
if(world.isRemote)
return;
ItemStack toolUsed = ItemStack.EMPTY;
if(e.getHarvester() != null && e.getHarvester().isEntityAlive())
{
EntityPlayer player = e.getHarvester();
ItemStack itemStack = player.getHeldItemMainhand();
if(!itemStack.isEmpty())
toolUsed = itemStack.copy();
}
IBlockState blockState = e.getState();
Block block = blockState.getBlock();
String blockID = block.getRegistryName().toString();
int metadata = block.getMetaFromState(blockState);
Random random = world.rand;
int exp = 0;
BlockDropData blockDropData = ConfigurationHandler.getBlockDropData(block, blockID, metadata);
if(blockDropData == null)
return;
if(!GameStageHook.isGameStage(e.getHarvester(), blockDropData))
{
/* TODO: Uncomment this if it gets to be a problem.
if(blockDropData.replace)
e.getDrops().clear();*/
return;
}
if(!TConstructHook.isModifier(toolUsed, blockDropData))
{
/* TODO: Uncomment this if it gets to be a problem.
if(blockDropData.replace)
e.getDrops().clear();*/
return;
}
if(!TConstructHook.isTrait(toolUsed, blockDropData))
{
/* TODO: Uncomment this if it gets to be a problem.
if(blockDropData.replace)
e.getDrops().clear();*/
return;
}
if(!hasEnchantment(toolUsed, blockDropData))
{
/* TODO: Uncomment this if it gets to be a problem.
if(blockDropData.replace)
e.getDrops().clear();*/
return;
}
if(!hasNBT(toolUsed, blockDropData))
{
/* TODO: Uncomment this if it gets to be a problem.
if(blockDropData.replace)
e.getDrops().clear();*/
return;
}
int yPos = e.getPos().getY();
if(!(yPos >= blockDropData.minYLevel && yPos <= blockDropData.maxYLevel))
{
/* TODO: Uncomment this if it gets to be a problem.
if(blockDropData.replace)
e.getDrops().clear();*/
return;
}
if(!isToolAllowed(toolUsed, blockDropData))
{
/* TODO: Uncomment this if it gets to be a problem.
if(blockDropData.replace)
e.getDrops().clear();*/
return;
}
Biome biome = world.getBiome(e.getPos());
String biomeID = biome.getRegistryName().toString();
if(!isBiomeAllowed(biomeID, blockDropData))
{
/* TODO: Uncomment this if it gets to be a problem.
if(blockDropData.replace)
e.getDrops().clear();*/
return;
}
int fortuneLevel = e.getFortuneLevel();
int chance = blockDropData.fortunechance.get(fortuneLevel);
List<ItemStack> dropList = new ArrayList<>();
ItemStack silkTouchItem = ItemStack.EMPTY;
if(!blockDropData.replace)
{
dropList.addAll(e.getDrops());
}
if (e.isSilkTouching() && blockDropData.allowsilktouch)
{
silkTouchItem = getSilkTouchDrop(block, blockState);
}
ItemStack itemToRemove = ItemStack.EMPTY;
for(ItemStack itemStack : dropList)
{
if(itemStack.isItemEqual(silkTouchItem))
itemToRemove = itemStack;
}
if(!itemToRemove.isEmpty())
dropList.remove(itemToRemove);
if(!silkTouchItem.isEmpty())
dropList.add(silkTouchItem);
e.getDrops().clear();
Entry<List<ItemStack>, Integer> dropExpEntry = getDrops(random, blockDropData, fortuneLevel, toolUsed, yPos, biomeID, e.getHarvester());
dropList.addAll(dropExpEntry.getKey());
int perc = MathHelper.getInt(random, 0, 100);
if(chance >= perc)
{
exp += MathHelper.getInt(world.rand, blockDropData.minExp, blockDropData.maxExp);
exp += dropExpEntry.getValue();
if(exp > 0)
{
block.dropXpOnBlockBreak(world, e.getPos(), exp);
}
e.getDrops().addAll(dropList);
}
else if(blockDropData.dropsilktouchalways)
{
if (!silkTouchItem.isEmpty())
{
e.getDrops().add(silkTouchItem);
}
}
}
public static boolean hasNBT(ItemStack toolItem, DropData dropData)
{
if(dropData.nbtList.isEmpty() && dropData.nbtBlacklist)
return true;
if(toolItem.isEmpty())
return dropData.nbtBlacklist;
if(!toolItem.hasTagCompound())
return dropData.nbtBlacklist;
boolean nbtExist = false;
for(String nbt : dropData.nbtList)
{
if(toolItem.getTagCompound().hasKey(nbt))
{
nbtExist = true;
break;
}
}
if(dropData.nbtBlacklist && nbtExist)
return false;
if((!dropData.nbtBlacklist) && (!nbtExist))
return false;
return true;
}
public static boolean hasNBT(ItemStack toolItem, BlockDropData blockDropData)
{
if(blockDropData.nbtList.isEmpty() && blockDropData.nbtBlacklist)
return true;
if(toolItem.isEmpty())
return blockDropData.nbtBlacklist;
if(!toolItem.hasTagCompound())
return blockDropData.nbtBlacklist;
boolean nbtExist = false;
for(String nbt : blockDropData.nbtList)
{
if(toolItem.getTagCompound().hasKey(nbt))
{
nbtExist = true;
break;
}
}
if(blockDropData.nbtBlacklist && nbtExist)
return false;
if((!blockDropData.nbtBlacklist) && (!nbtExist))
return false;
return true;
}
private boolean hasEnchantment(ItemStack toolItem, DropData dropData)
{
if(dropData.enchantmentList.isEmpty() && dropData.enchantmentBlacklist)
return true;
if(toolItem.isEmpty())
return dropData.enchantmentBlacklist;
if(!toolItem.isItemEnchanted())
return dropData.enchantmentBlacklist;
boolean enchantmentExist = false;
for(String enchantment : dropData.enchantmentList)
{
Enchantment enchantmentObj = Enchantment.getEnchantmentByLocation(enchantment);
if(enchantmentObj == null)
continue;
if (EnchantmentHelper.getEnchantmentLevel(enchantmentObj, toolItem) > 0)
{
enchantmentExist = true;
break;
}
}
if(dropData.enchantmentBlacklist && enchantmentExist)
return false;
if((!dropData.enchantmentBlacklist) && (!enchantmentExist))
return false;
return true;
}
private boolean hasEnchantment(ItemStack toolItem, BlockDropData blockDropData)
{
if(blockDropData.enchantmentList.isEmpty() && blockDropData.enchantmentBlacklist)
return true;
if(toolItem.isEmpty())
return blockDropData.enchantmentBlacklist;
if(!toolItem.isItemEnchanted())
return blockDropData.enchantmentBlacklist;
boolean enchantmentExist = false;
for(String enchantment : blockDropData.enchantmentList)
{
Enchantment enchantmentObj = Enchantment.getEnchantmentByLocation(enchantment);
if(enchantmentObj == null)
continue;
if (EnchantmentHelper.getEnchantmentLevel(enchantmentObj, toolItem) > 0)
{
enchantmentExist = true;
break;
}
}
if(blockDropData.enchantmentBlacklist && enchantmentExist)
return false;
if((!blockDropData.enchantmentBlacklist) && (!enchantmentExist))
return false;
return true;
}
private boolean isToolAllowed(ItemStack toolItem, BlockDropData blockDropData)
{
for(String minedWith : blockDropData.tools)
{
if(blockDropData.toolsBlacklist)
{
return !isUsingItem(toolItem, minedWith);
}
else
{
return isUsingItem(toolItem, minedWith);
}
}
return blockDropData.toolsBlacklist;
}
private boolean isBiomeAllowed(String biomeID, BlockDropData blockDropData)
{
if(blockDropData.biomeBlacklist)
{
return !blockDropData.biomes.contains(biomeID);
}
else
{
return blockDropData.biomes.contains(biomeID);
}
}
private Map.Entry<List<ItemStack>, Integer> getDrops(Random random, BlockDropData blockDropData, int fortune, ItemStack heldItem, int yLevel, String biomeID, EntityPlayer harvester)
{
List<ItemStack> drops = new ArrayList<>();
if(blockDropData.dropdatalist.isEmpty())
return new SimpleEntry<>(new ArrayList<>(), 0);
int exp = 0;
for(DropData dropData : blockDropData.dropdatalist)
{
Item item = Item.getByNameOrId(dropData.id);
if(item == null)
continue;
FortuneQuantityData fortuneQuantityData = dropData.fortunequantitymap.get(fortune);
if(fortuneQuantityData == null)
continue;
int chance = dropData.fortunechancemap.get(fortune);
int perc = MathHelper.getInt(random, 1, 100);
if(chance < perc)
continue;
if(!(yLevel >= dropData.minYLevel && yLevel <= dropData.maxYLevel))
continue;
if(!isToolAllowed(heldItem, dropData))
continue;
if(!isBiomeAllowed(biomeID, dropData))
continue;
if(!GameStageHook.isGameStage(harvester, dropData))
continue;
if(!TConstructHook.isModifier(heldItem, dropData))
continue;
if(!TConstructHook.isTrait(heldItem, dropData))
continue;
if(!hasEnchantment(heldItem, dropData))
continue;
if(!hasNBT(heldItem, blockDropData))
continue;
int quantity = MathHelper.getInt(random, fortuneQuantityData.minquantity, fortuneQuantityData.maxquantity);
ItemStack itemStack = new ItemStack(item, quantity, dropData.metadata);
if(dropData.exclusive)
{
drops.clear();
drops.add(itemStack);
exp = MathHelper.getInt(random, dropData.minExp, dropData.maxExp);
break;
}
exp += MathHelper.getInt(random, dropData.minExp, dropData.maxExp);
drops.add(itemStack);
}
return new SimpleEntry<>(drops, exp);
}
private boolean isToolAllowed(ItemStack toolItem, DropData dropData)
{
for(String minedWith : dropData.tools)
{
if(dropData.toolsBlacklist)
{
return !isUsingItem(toolItem, minedWith);
}
else
{
return isUsingItem(toolItem, minedWith);
}
}
return dropData.toolsBlacklist;
}
private boolean isBiomeAllowed(String biomeID, DropData dropData)
{
if(dropData.biomeBlacklist)
{
return !dropData.biomes.contains(biomeID);
}
else
{
return dropData.biomes.contains(biomeID);
}
}
private ItemStack getSilkTouchDrop(Block block, IBlockState state)
{
Item item = Item.getItemFromBlock(block);
int i = 0;
if (item.getHasSubtypes())
{
i = block.getMetaFromState(state);
}
return new ItemStack(item, 1, i);
}
private boolean isUsingItem(ItemStack heldItem, String itemData)
{
if(heldItem.isEmpty())
return false;
String[] itemArray = itemData.split(",");
String itemID = itemArray[0];
String metadata = itemArray[1];
Item item = Item.getByNameOrId(itemID);
if (item == null)
return false;
ItemStack itemStack;
if (metadata.equals("*"))
{
itemStack = new ItemStack(item, heldItem.getCount());
return !itemStack.isEmpty() && itemStack.getItem().equals(heldItem.getItem());
}
else
{
itemStack = new ItemStack(item, heldItem.getCount(), Integer.parseInt(metadata));
return ItemStack.areItemsEqual(heldItem, itemStack);
}
}
}
|
hjc851/Dataset2-HowToDetectAdvancedSourceCodePlagiarism
|
Variant Programs/1-5/13/ontogenetic/AmountRearing.java
|
<filename>Variant Programs/1-5/13/ontogenetic/AmountRearing.java
package ontogenetic;
public class AmountRearing {
public static synchronized void placedWhen(double prey) {
bringCommonMeterGoalkeeper().soarTcs(prey);
}
private synchronized double letAfootHours() {
return this.liveDays;
}
private AmountRearing() {
this.liveDays = (0);
}
private static AmountRearing combinedOpportunityCarer = null;
private synchronized void soarTcs(double aiming) {
this.liveDays = (aiming);
}
private double liveDays = 0.0;
public static synchronized AmountRearing bringCommonMeterGoalkeeper() {
if (combinedOpportunityCarer == null) combinedOpportunityCarer = (new AmountRearing());
return combinedOpportunityCarer;
}
public static synchronized double contemporaryMoment() {
return bringCommonMeterGoalkeeper().letAfootHours();
}
}
|
paper/LeetCodeV2
|
Algorithms/561. Array Partition I.js
|
/**
* Given an array of 2n integers, your task is to group these integers into n pairs of integer,
* say (a1, b1), (a2, b2), ..., (an, bn) which makes sum of min(ai, bi) for all i from 1 to n as large as possible.
*
* Example 1:
* Input: [1,4,3,2]
*
* Output: 4
* Explanation: n is 2, and the maximum sum of pairs is 4.
* Note:
* n is a positive integer, which is in the range of [1, 10000].
* All the integers in the array will be in the range of [-10000, 10000].
*
* 证明:http://www.voidcn.com/blog/huanghanqian/article/p-6572441.html
* ①.假设在每对(ai,bi)中,bi>=ai(顺序不影响min,所以调换顺序没有关系)
* ②.令 Sm = min(a1, b1) + min(a2, b2) + ... + min(an, bn) ,那么该题所要求的就是最大的Sm。由①可得,Sm = a1 + a2 + ... + an.
* ③.令Sa = a1 + b1 + a2 + b2 + ... + an + bn. Sa是一个常量。
* ④.令di = |ai - bi|. 由①可得,di = bi - ai. 令Sd = d1 + d2 + ... + dn.
* ⑤.所以Sa = a1 + a1 + d1 + a2 + a2 + d2 + ... + an + an + di = 2Sm + Sd => Sm = (Sa - Sd) / 2.
* 为了得到最大的Sm,考虑到Sa是一个常量,所以我们期望Sd最小。
* ⑥所以这个问题转化为另一个问题:找到一个数组中的pairs (ai,bi),使得|ai-bi|(ai和bi之间的距离)之和最小。
*/
/**
* @param {number[]} nums
* @return {number}
*/
var arrayPairSum = function(nums) {
nums.sort(function (a, b) {
return a - b;
});
var len = nums.length;
var sum = 0;
for(var i=0; i<len; i+=2) {
sum += nums[i];
}
return sum;
};
|
t-mochizuki/cpp-study
|
AtCoder/ABC122/abc122C.cpp
|
#include <stdio.h>
#include <iostream>
#include <string>
#include <vector>
using namespace std;
#define REP(a, i, n) for (int i = a; i < n; ++i)
int main() {
int N, Q;
cin >> N >> Q;
string S;
cin >> S;
int cnt = 0;
vector<int> v;
v.push_back(cnt);
REP(1, i, S.length()) {
if (S[i - 1] == 'A' && S[i] == 'C') {
cnt++;
}
v.push_back(cnt);
}
int l[Q], r[Q];
REP(0, i, Q) {
cin >> l[i] >> r[i];
l[i]--; r[i]--;
}
REP(0, i, Q) {
int ans = v[r[i]] - v[l[i]];
cout << ans << endl;
}
return 0;
}
|
13824125580/higan
|
higan/fc/cartridge/chip/vrc1.cpp
|
<reponame>13824125580/higan
struct VRC1 : Chip {
VRC1(Board& board) : Chip(board) {
}
auto addrPRG(uint addr) const -> uint {
uint bank = 0x0f;
if((addr & 0xe000) == 0x8000) bank = prgBank[0];
if((addr & 0xe000) == 0xa000) bank = prgBank[1];
if((addr & 0xe000) == 0xc000) bank = prgBank[2];
return (bank * 0x2000) + (addr & 0x1fff);
}
auto addrCHR(uint addr) const -> uint {
uint bank = chrBankLo[(bool)(addr & 0x1000)];
bank |= chrBankHi[(bool)(addr & 0x1000)] << 4;
return (bank * 0x1000) + (addr & 0x0fff);
}
auto addrCIRAM(uint addr) const -> uint {
switch(mirror) {
case 0: return ((addr & 0x0400) >> 0) | (addr & 0x03ff); //vertical mirroring
case 1: return ((addr & 0x0800) >> 1) | (addr & 0x03ff); //horizontal mirroring
}
throw;
}
auto writeIO(uint addr, uint8 data) -> void {
switch(addr & 0xf000) {
case 0x8000:
prgBank[0] = data & 0x0f;
break;
case 0x9000:
chrBankHi[1] = data & 0x04;
chrBankHi[0] = data & 0x02;
mirror = data & 0x01;
break;
case 0xa000:
prgBank[1] = data & 0x0f;
break;
case 0xc000:
prgBank[2] = data & 0x0f;
break;
case 0xe000:
chrBankLo[0] = data & 0x0f;
break;
case 0xf000:
chrBankLo[1] = data & 0x0f;
break;
}
}
auto power() -> void {
for(auto& n : prgBank) n = 0;
for(auto& n : chrBankLo) n = 0;
for(auto& n : chrBankHi) n = 0;
mirror = 0;
}
auto serialize(serializer& s) -> void {
for(auto& n : prgBank) s.integer(n);
for(auto& n : chrBankLo) s.integer(n);
for(auto& n : chrBankHi) s.integer(n);
s.integer(mirror);
}
uint4 prgBank[3];
uint4 chrBankLo[2];
bool chrBankHi[2];
bool mirror;
};
|
ivan-sysoi/django-photoslib
|
photoslib/__init__.py
|
<reponame>ivan-sysoi/django-photoslib
default_app_config = 'photoslib.apps.PhotosLibConfig'
|
anderslatif/dev_env_2019
|
3._Bike_Shop/src/components/ProductViews.js
|
import React, { Component } from 'react'
import Loader from 'react-loader-spinner'
import Slider from "react-slick";
import { DateRangePicker } from 'react-dates';
import 'react-dates/lib/css/_datepicker.css';
// import Carousel from 'nuka-carousel';
class ProductViews extends Component {
constructor(props) {
super(props)
this.state = {
loaderState: true
}
}
componentDidMount() {
setTimeout(() => {
this.setState((prevState) => ({loaderState: !prevState.loaderState}))
}, 200)
}
render(props) {
let { products, selectedProduct } = this.props;
var settings = {
dots: true,
infinite: true,
speed: 500,
slidesToShow: 1,
slidesToScroll: 1,
arrows:true,
easing:"linear",
autoplay:true
};
return (
<div className="product__views">
<div className="product__views--wrapper">
<svg className="close__views" onClick={this.props.closeViews}>
<use href="./image/sprite.svg#icon-cross"></use>
</svg>
{
this.state.loaderState
&&
<div className="loader__products">
<Loader type="ThreeDots" color="#somecolor" height={32} width={32} />
</div>
}
<div className="inner__contentWrapper">
<div className="inner__contentWrapper--image">
{/* <Carousel> */}
<Slider {...settings}>
{
products.map((images) => {
if(images.productId === selectedProduct) {
return images.productListImage.map((image, index) => {
return <div className="image__contain"><img src={image} alt="" key={index}/></div>
})
}
})
}
</Slider>
{/* </Carousel> */}
</div>
<div className="inner__contentWrapper--controllers">
{
products.map((datas) => {
if(datas.productId === selectedProduct) {
return(
<div className="datas__wrapper" key={datas.productId}>
<div className="datas__wrapper--title">
<h2>{datas.productName}</h2>
</div>
<div className="datas__wrapper--price">
<p>${datas.productPrice}</p>
</div>
<div className="datas__wrapper--datapicker">
will insert airbnb data-range picker
</div>
<div className="datas__wrapper--addToCart">
<button>add to cart</button>
</div>
</div>
);
}
})
}
</div>
</div>
</div>
{/* ProductViews */}
</div>
)
}
}
export default ProductViews;
|
Shaika-Dzari/bluekarbon-node
|
app/utils/htmlutils.js
|
<filename>app/utils/htmlutils.js
let config = require('../config/config');
let Remarkable = require('remarkable');
const remarkable = new Remarkable();
const sanitizeUrl = (str) => {
let oneStr = str || '';
oneStr = oneStr.replace(/[!$?*&#\\]/, '');
oneStr = oneStr.replace(/[^a-z0-9_\-]/gi, '_');
return oneStr.toLowerCase();
}
const removeCtrlChar = (text) => {
if (text) {
text = text.replace(/(?:\r\n|\r|\n)/g, '');
}
return text;
}
const escapeCtrlChar = (text) => {
if (text) {
text = text.replace(/\\n/g, '\\\\n')
.replace(/(\\\")/g, '\\\\"')
.replace(/\//g, '\\\\/')
.replace(/\\b/g, '\\\\b')
.replace(/\\f/g, '\\\\f')
.replace(/\\t/g, '\\\\t')
;
}
return text;
}
const mkToHtml = (text) => {
if (text) {
return remarkable.render(text);
}
return null;
}
function computePrettyUrl(msgs) {
if (msgs) {
let newmsgs;
if (Array.isArray(msgs)) {
newmsgs = [];
for (let m of msgs) {
let am = m.dataValues;
am.permurl = am.id + '--' + am.prettyurl;
newmsgs.push(am);
}
} else {
newmsgs = msgs.dataValues;
newmsgs.permurl = msgs.id + '--' + msgs.prettyurl;
}
return newmsgs;
}
return msgs;
}
module.exports = {
sanitizeUrl: sanitizeUrl,
mkToHtml: mkToHtml,
computePrettyUrl: computePrettyUrl,
removeCtrlChar: removeCtrlChar,
escapeCtrlChar: escapeCtrlChar
}
|
hys9958/tajo
|
tajo-client/src/main/java/org/apache/tajo/cli/tsql/commands/HelpCommand.java
|
<filename>tajo-client/src/main/java/org/apache/tajo/cli/tsql/commands/HelpCommand.java
/**
* 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.tajo.cli.tsql.commands;
import java.io.PrintWriter;
import org.apache.tajo.cli.tsql.TajoCli;
import org.apache.tajo.util.VersionInfo;
public class HelpCommand extends TajoShellCommand {
private String targetDocVersion = "";
public HelpCommand(TajoCli.TajoCliContext context) {
super(context);
}
@Override
public String getCommand() {
return "\\?";
}
@Override
public String [] getAliases() {
return new String [] {"\\help"};
}
@Override
public void invoke(String[] cmd) throws Exception {
if(targetDocVersion.equalsIgnoreCase("")) {
targetDocVersion = getDocumentationVersion();
}
if (cmd.length == 1) {
PrintWriter sout = context.getOutput();
sout.println();
sout.println("General");
sout.println(" \\copyright show Apache License 2.0");
sout.println(" \\version show Tajo version");
sout.println(" \\? show help");
sout.println(" \\? [COMMAND] show help of a given command");
sout.println(" \\help alias of \\?");
sout.println(" \\q quit tsql");
sout.println();
sout.println();
sout.println("Informational");
sout.println(" \\l list databases");
sout.println(" \\c show current database");
sout.println(" \\c [DBNAME] connect to new database");
sout.println(" \\d list tables");
sout.println(" \\d [TBNAME] describe table");
sout.println(" \\df list functions");
sout.println(" \\df NAME describe function");
sout.println();
sout.println();
sout.println("Tool");
sout.println(" \\! execute a linux shell command");
sout.println(" \\dfs execute a dfs command");
sout.println(" \\admin execute tajo admin command");
sout.println();
sout.println();
sout.println("Variables");
sout.println(" \\set [[NAME] [VALUE] set session variable or list session variables");
sout.println(" \\unset NAME unset session variable");
sout.println();
sout.println();
sout.println("Documentations");
sout.println(" tsql guide http://tajo.apache.org/docs/" + targetDocVersion + "/cli.html");
sout.println(" Query language http://tajo.apache.org/docs/" + targetDocVersion + "/sql_language.html");
sout.println(" Functions http://tajo.apache.org/docs/" + targetDocVersion + "/functions.html");
sout.println(" Backup & restore http://tajo.apache.org/docs/" + targetDocVersion + "/backup_and_restore.html");
sout.println(" Configuration http://tajo.apache.org/docs/" + targetDocVersion + "/configuration.html");
sout.println();
} else if (cmd.length == 2) {
String slashCommand = "\\" + cmd[1];
if (context.getCommands().containsKey(slashCommand)) {
context.getCommands().get(slashCommand).printHelp();
} else {
context.getOutput().println("Command not found: " + cmd[1]);
}
}
}
private String getDocumentationVersion() {
String tajoVersion = "", docVersion = "", docDefaultVersion = "current";
String tajoFullVersion = VersionInfo.getVersion();
int delimiterIdx = tajoFullVersion.indexOf("-");
if (delimiterIdx > -1) {
tajoVersion = tajoFullVersion.substring(0, delimiterIdx);
} else {
tajoVersion = tajoFullVersion;
}
if(tajoVersion.equalsIgnoreCase("")) {
docVersion = docDefaultVersion;
} else {
docVersion = tajoVersion;
}
return docVersion;
}
@Override
public String getUsage() {
return "";
}
@Override
public String getDescription() {
return "show command lists and their usages";
}
}
|
Bewalticus/gocd
|
server/src/main/webapp/WEB-INF/rails/spec/models/stage_history_api_model_spec.rb
|
<filename>server/src/main/webapp/WEB-INF/rails/spec/models/stage_history_api_model_spec.rb<gh_stars>1-10
#
# Copyright 2019 ThoughtWorks, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
require 'rails_helper'
describe StageHistoryAPIModel do
include APIModelMother
describe "should initialize correctly" do
it "should populate correct data" do
@pagination_view_model = create_pagination_model
@stage_view_model = [create_stage_model]
stage_history_api_model = StageHistoryAPIModel.new(@pagination_view_model, @stage_view_model)
expect(stage_history_api_model.pagination.page_size).to eq(10)
expect(stage_history_api_model.pagination.offset).to eq(1)
expect(stage_history_api_model.pagination.total).to eq(100)
stage_instance_api_model = stage_history_api_model.stages[0]
expect(stage_instance_api_model.id).to eq(456)
expect(stage_instance_api_model.name).to eq('stage name')
expect(stage_instance_api_model.counter).to eq('1')
expect(stage_instance_api_model.approval_type).to eq('manual')
expect(stage_instance_api_model.approved_by).to eq('me')
expect(stage_instance_api_model.result).to eq('passed')
expect(stage_instance_api_model.rerun_of_counter).to eq(1)
expect(stage_instance_api_model.pipeline_name).to eq('pipeline')
expect(stage_instance_api_model.pipeline_counter).to eq(1)
job_history_item_api_model = stage_instance_api_model.jobs[0]
expect(job_history_item_api_model.id).to eq(543)
expect(job_history_item_api_model.name).to eq('job name')
expect(job_history_item_api_model.state).to eq('state')
expect(job_history_item_api_model.result).to eq('result')
expect(job_history_item_api_model.scheduled_date).to eq(12345678)
expect(job_history_item_api_model.rerun).to eq(nil)
expect(job_history_item_api_model.original_job_id).to eq(nil)
expect(job_history_item_api_model.agent_uuid).to eq(nil)
expect(job_history_item_api_model.pipeline_name).to eq(nil)
expect(job_history_item_api_model.pipeline_counter).to eq(nil)
expect(job_history_item_api_model.stage_name).to eq(nil)
expect(job_history_item_api_model.stage_counter).to eq(nil)
end
it "should handle empty data" do
@pagination_view_model = create_empty_pagination_model
@stage_view_model = [create_empty_stage_model]
stage_history_api_model = StageHistoryAPIModel.new(@pagination_view_model, @stage_view_model)
expect(stage_history_api_model.pagination.page_size).to eq(nil)
expect(stage_history_api_model.pagination.offset).to eq(nil)
expect(stage_history_api_model.pagination.total).to eq(nil)
stage_instance_api_model = stage_history_api_model.stages[0]
expect(stage_instance_api_model.id).to eq(nil)
expect(stage_instance_api_model.name).to eq(nil)
expect(stage_instance_api_model.counter).to eq(nil)
expect(stage_instance_api_model.approval_type).to eq(nil)
expect(stage_instance_api_model.approved_by).to eq(nil)
expect(stage_instance_api_model.result).to eq(nil)
expect(stage_instance_api_model.rerun_of_counter).to eq(nil)
expect(stage_instance_api_model.pipeline_name).to eq(nil)
expect(stage_instance_api_model.pipeline_counter).to eq(nil)
job_history_item_api_model = stage_instance_api_model.jobs[0]
expect(job_history_item_api_model.id).to eq(nil)
expect(job_history_item_api_model.name).to eq(nil)
expect(job_history_item_api_model.state).to eq(nil)
expect(job_history_item_api_model.result).to eq(nil)
expect(job_history_item_api_model.scheduled_date).to eq(nil)
expect(job_history_item_api_model.rerun).to eq(nil)
expect(job_history_item_api_model.original_job_id).to eq(nil)
expect(job_history_item_api_model.agent_uuid).to eq(nil)
expect(job_history_item_api_model.pipeline_name).to eq(nil)
expect(job_history_item_api_model.pipeline_counter).to eq(nil)
expect(job_history_item_api_model.stage_name).to eq(nil)
expect(job_history_item_api_model.stage_counter).to eq(nil)
end
end
end
|
kclinden/microsoft-iis-8.5-site-stig-baseline
|
controls/V-76855.rb
|
<reponame>kclinden/microsoft-iis-8.5-site-stig-baseline
control 'V-76855' do
title 'IIS 8.5 website session IDs must be sent to the client using TLS.'
desc "The HTTP protocol is a stateless protocol. To maintain a session, a
session identifier is used. The session identifier is a piece of data that is
used to identify a session and a user. If the session identifier is compromised
by an attacker, the session can be hijacked. By encrypting the session
identifier, the identifier becomes more difficult for an attacker to hijack,
decrypt, and use before the session has expired."
impact 0.5
tag "gtitle": 'SRG-APP-000439-WSR-000152'
tag "gid": 'V-76855'
tag "rid": 'SV-91551r1_rule'
tag "stig_id": 'IISW-SI-000244'
tag "fix_id": 'F-83551r1_fix'
tag "cci": ['CCI-002418']
tag "nist": ['SC-8', 'Rev_4']
tag "false_negatives": nil
tag "false_positives": nil
tag "documentable": false
tag "mitigations": nil
tag "severity_override_guidance": false
tag "potential_impacts": nil
tag "third_party_tools": nil
tag "mitigation_controls": nil
tag "responsibility": nil
tag "ia_controls": nil
tag "check": "Follow the procedures below for each site hosted on the IIS 8.5
web server:
Access the IIS 8.5 Manager.
Select the website being reviewed.
Under \"Management\" section, double-click the \"Configuration Editor\" icon.
From the \"Section:\" drop-down list, select “system.webServer/asp\".
Expand the \"session\" section.
Verify the \"keepSessionIdSecure\" is set to \"True\".
If the \"keepSessionIdSecure\" is not set to \"True\", this is a finding."
tag "fix": "Follow the procedures below for each site hosted on the IIS 8.5
web server:
Access the IIS 8.5 Manager.
Select the website being reviewed.
Under \"Management\" section, double-click the \"Configuration Editor\" icon.
From the \"Section:\" drop-down list, select “system.webServer/asp\".
Expand the \"session\" section.
Select \"True\" for the \"keepSessionIdSecure\" setting.
Select \"Apply\" from the \"Actions\" pane."
get_names = command("Get-Website | select name | findstr /v 'name ---'").stdout.strip.split("\r\n")
get_keepSessionIdSecure = command('Get-WebConfigurationProperty -pspath "IIS:\Sites\*" -Filter system.webServer/asp -name * | select -expand session | select -expand keepSessionIdSecure').stdout.strip.split("\r\n")
get_keepSessionIdSecure.zip(get_names).each do |keepSessionIdSecure, names|
n = names.strip
describe "The IIS site: #{n} website keepSessionIdSecure enabled setting" do
subject { keepSessionIdSecure }
it { should cmp 'True' }
end
end
if get_names.empty?
impact 0.0
desc 'There are no IIS sites configured hence the control is Not-Applicable'
describe 'No sites where found to be reviewed' do
skip 'No sites where found to be reviewed'
end
end
end
|
cryst-al/novoline
|
src/net/ax5.java
|
package net;
import java.util.List;
import net.aMN;
import net.aTi;
import net.aXe;
import net.cq;
import net.rX;
import viaversion.viaversion.api.PacketWrapper;
import viaversion.viaversion.api.Via;
import viaversion.viaversion.api.remapper.PacketHandler;
import viaversion.viaversion.api.type.Type;
class ax5 implements PacketHandler {
final aMN a;
ax5(aMN var1) {
this.a = var1;
}
public void handle(PacketWrapper var1) throws Exception {
List var3 = (List)var1.get(rX.a, 0);
int var4 = ((Integer)var1.get(Type.VAR_INT, 0)).intValue();
aXe.b();
cq var5 = (cq)var1.user().b(cq.class);
if(var5.hasEntity(var4)) {
((aTi)this.a.c.get(aTi.class)).handleMetadata(var4, var3, var1.user());
}
Via.getPlatform().getLogger().warning("Unable to find entity for metadata, entity ID: " + var4);
var3.clear();
}
private static Exception a(Exception var0) {
return var0;
}
}
|
dsm-fudan/KV-match
|
src/main/java/cn/edu/fudan/dsm/kvmatch/operator/file/TimeSeriesNodeIterator.java
|
<filename>src/main/java/cn/edu/fudan/dsm/kvmatch/operator/file/TimeSeriesNodeIterator.java
/*
* Copyright 2017 <NAME>
*
* 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 cn.edu.fudan.dsm.kvmatch.operator.file;
import cn.edu.fudan.dsm.kvmatch.common.Pair;
import cn.edu.fudan.dsm.kvmatch.common.entity.TimeSeriesNode;
import java.io.*;
import java.util.Iterator;
/**
* Created by <NAME> on 17-8-25.
*/
public class TimeSeriesNodeIterator implements Iterator<Pair<Long, TimeSeriesNode>> {
// private FileHandler fileHandler;
private DataInputStream dis;
private int fetchSize;
private long length;
private long pos;
private Pair<Long, TimeSeriesNode> next = null;
public TimeSeriesNodeIterator(File file, int fetchSize) throws FileNotFoundException {
// this.fileHandler = fileHandler;
this.dis = new DataInputStream(new BufferedInputStream(new FileInputStream(file)));
this.fetchSize = fetchSize;
this.length = file.length();
// this.length = fileHandler.getFile().length();
this.pos = 0;
}
@Override
public boolean hasNext() {
if (next == null) {
try {
if (pos < length) {
byte[] bytes = new byte[fetchSize];
pos += dis.read(bytes);
// byte[] bytes = fileHandler.read(pos, fetchSize);
TimeSeriesNode node = new TimeSeriesNode();
node.parseBytes(bytes);
next = new Pair<>(pos + 1, node);
// pos += fetchSize;
}
return next != null;
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return true;
}
@Override
public Pair<Long, TimeSeriesNode> next() {
if (!hasNext()) {
return null;
}
Pair<Long, TimeSeriesNode> temp = next;
next = null;
return temp;
}
}
|
JayeshB92/ishapi
|
app/controllers/ishapi/reports_controller.rb
|
require_dependency "ishapi/application_controller"
module Ishapi
class ReportsController < ApplicationController
def show
@report = Report.unscoped.find_by :name_seo => params[:name_seo]
authorize! :show, @report
end
def index
authorize! :index, Report
@reports = Report.all
if params[:cityname]
city = City.find_by :cityname => params[:cityname]
@reports = @reports.where( :city_id => city.id )
end
if params[:domain]
site = Site.find_by :domain => params[:domain], :lang => :en
@reports = @reports.where( :site_id => site.id )
end
if params[:tag]
tag = Tag.find_by(:name => params[:tag])
@reports = @reports.where(:tag_ids => tag)
end
@reports = @reports.page( params[:reports_page] ).per( 10 )
end
end
end
|
embedthis/ejscript
|
src/core/src/ejsString.c
|
<reponame>embedthis/ejscript
/**
ejsString.c - Ejscript string class
Copyright (c) All Rights Reserved. See details at the end of the file.
*/
/********************************** Includes **********************************/
#include "ejs.h"
#include "pcre.h"
/*********************************** Locals ***********************************/
// TODO - should not be fixed
#if !defined(ME_MAX_REGEX_MATCHES)
#define ME_MAX_REGEX_MATCHES 128
#endif
static int internHashSizes[] = {
389, 769, 1543, 3079, 6151, 12289, 24593, 49157, 98317, 196613, 0
};
/***************************** Forward Declarations ***************************/
static EjsString *buildString(Ejs *ejs, EjsString *result, wchar *str, ssize len);
static ssize indexof(wchar *str, ssize len, EjsString *pattern, ssize patternLength, int dir);
static void linkString(EjsString *head, EjsString *sp);
static void manageIntern(EjsIntern *intern, int flags);
static int rebuildIntern(EjsIntern *intern);
static void unlinkString(EjsString *sp);
/************************************* Code ***********************************/
/*
Cast the string operand to a primitive type
*/
static EjsAny *castString(Ejs *ejs, EjsString *sp, EjsType *type)
{
assert(sp);
assert(type);
switch (type->sid) {
case S_Boolean:
if (sp != ESV(empty)) {
return ESV(true);
}
return ESV(false);
case S_Number:
return ejsParse(ejs, sp->value, S_Number);
case S_Path:
return ejsCreatePath(ejs, sp);
case S_RegExp:
return ejsParseRegExp(ejs, sp);
case S_String:
return sp;
case S_Uri:
return ejsCreateUri(ejs, sp);
default:
ejsThrowTypeError(ejs, "Cannot cast to required type");
return 0;
}
}
static EjsString *cloneString(Ejs *ejs, EjsString *sp, bool deep)
{
/* Strings are immutable, interned and shared across all interps */
return sp;
}
/*
Get a string element. Slot numbers correspond to character indicies.
*/
static EjsString *getStringProperty(Ejs *ejs, EjsString *sp, int index)
{
if (index < 0 || index >= sp->length) {
return ESV(empty);
}
return ejsCreateString(ejs, &sp->value[index], 1);
}
static EjsAny *coerceStringOperands(Ejs *ejs, EjsAny *lhs, int opcode, EjsAny *rhs)
{
switch (opcode) {
/*
Binary operators
*/
case EJS_OP_ADD:
return ejsInvokeOperator(ejs, lhs, opcode, ejsToString(ejs, rhs));
/*
Overloaded operators
*/
case EJS_OP_MUL:
if (ejsIs(ejs, rhs, Number)) {
return ejsInvokeOperator(ejs, ejsToNumber(ejs, lhs), opcode, rhs);
}
return ejsInvokeOperator(ejs, lhs, opcode, ejsToNumber(ejs, rhs));
case EJS_OP_REM:
return 0;
case EJS_OP_AND: case EJS_OP_DIV: case EJS_OP_OR:
case EJS_OP_SHL: case EJS_OP_SHR: case EJS_OP_SUB: case EJS_OP_USHR: case EJS_OP_XOR:
return ejsInvokeOperator(ejs, ejsToNumber(ejs, lhs), opcode, rhs);
case EJS_OP_COMPARE_EQ: case EJS_OP_COMPARE_NE:
case EJS_OP_COMPARE_LE: case EJS_OP_COMPARE_LT:
case EJS_OP_COMPARE_GE: case EJS_OP_COMPARE_GT:
return ejsInvokeOperator(ejs, lhs, opcode, ejsToString(ejs, rhs));
case EJS_OP_COMPARE_STRICTLY_NE:
return ESV(true);
case EJS_OP_COMPARE_STRICTLY_EQ:
return ESV(false);
/*
Unary operators
*/
case EJS_OP_LOGICAL_NOT:
return ejsInvokeOperator(ejs, ejsToBoolean(ejs, lhs), opcode, rhs);
case EJS_OP_NOT:
case EJS_OP_NEG:
return ejsInvokeOperator(ejs, ejsToNumber(ejs, lhs), opcode, rhs);
case EJS_OP_COMPARE_NOT_ZERO:
case EJS_OP_COMPARE_TRUE:
return (((EjsString*) lhs) ? ESV(true) : ESV(false));
case EJS_OP_COMPARE_ZERO:
case EJS_OP_COMPARE_FALSE:
return (((EjsString*) lhs) ? ESV(false): ESV(true));
case EJS_OP_COMPARE_UNDEFINED:
case EJS_OP_COMPARE_NULL:
return ESV(false);
default:
ejsThrowTypeError(ejs, "Opcode %d not valid for type %@", opcode, TYPE(lhs)->qname.name);
return ESV(undefined);
}
}
static EjsAny *invokeStringOperator(Ejs *ejs, EjsString *lhs, int opcode, EjsString *rhs, void *data)
{
EjsAny *result, *arg;
if (rhs == 0 || TYPE(lhs) != TYPE(rhs)) {
if (!ejsIs(ejs, lhs, String) || !ejsIs(ejs, rhs, String)) {
if ((result = coerceStringOperands(ejs, lhs, opcode, rhs)) != 0) {
return result;
}
}
}
/*
Types now match, both strings
*/
switch (opcode) {
case EJS_OP_COMPARE_STRICTLY_EQ:
case EJS_OP_COMPARE_EQ:
// OPT -- should use lhs == rhs
if (lhs->value == rhs->value) {
assert(lhs == rhs);
return ESV(true);
}
return ESV(false);
case EJS_OP_COMPARE_NE:
case EJS_OP_COMPARE_STRICTLY_NE:
// OPT -- should use lhs == rhs
if (lhs->value != rhs->value) {
assert(lhs != rhs);
return ESV(true);
}
return ESV(false);
case EJS_OP_COMPARE_LT:
return ejsCreateBoolean(ejs,
mprMemcmp(lhs->value, lhs->length * sizeof(wchar), rhs->value, rhs->length * sizeof(wchar)) < 0);
case EJS_OP_COMPARE_LE:
return ejsCreateBoolean(ejs,
mprMemcmp(lhs->value, lhs->length * sizeof(wchar), rhs->value, rhs->length * sizeof(wchar)) <= 0);
case EJS_OP_COMPARE_GT:
return ejsCreateBoolean(ejs,
mprMemcmp(lhs->value, lhs->length * sizeof(wchar), rhs->value, rhs->length * sizeof(wchar)) > 0);
case EJS_OP_COMPARE_GE:
return ejsCreateBoolean(ejs,
mprMemcmp(lhs->value, lhs->length * sizeof(wchar), rhs->value, rhs->length * sizeof(wchar)) >= 0);
/*
Unary operators
*/
case EJS_OP_COMPARE_NOT_ZERO:
return ((lhs) ? ESV(true): ESV(false));
case EJS_OP_COMPARE_ZERO:
return ((lhs == 0) ? ESV(true): ESV(false));
case EJS_OP_COMPARE_UNDEFINED:
case EJS_OP_COMPARE_NULL:
case EJS_OP_COMPARE_FALSE:
case EJS_OP_COMPARE_TRUE:
return ESV(false);
/*
Binary operators
*/
case EJS_OP_ADD:
return ejsJoinString(ejs, lhs, rhs);
case EJS_OP_AND: case EJS_OP_DIV: case EJS_OP_OR:
case EJS_OP_SHL: case EJS_OP_SHR: case EJS_OP_USHR: case EJS_OP_XOR:
return ejsInvokeOperator(ejs, ejsToNumber(ejs, lhs), opcode, rhs);
#if EXTENSIONS || 1
/*
Overloaded
*/
case EJS_OP_SUB:
arg = rhs;
return ejsRunFunctionBySlot(ejs, lhs, ES_String_MINUS, 1, &arg);
case EJS_OP_REM:
arg = rhs;
return ejsRunFunctionBySlot(ejs, lhs, ES_String_MOD, 1, &arg);
#endif
case EJS_OP_NEG:
case EJS_OP_LOGICAL_NOT:
case EJS_OP_NOT:
/* Already handled in coerceStringOperands */
default:
ejsThrowTypeError(ejs, "Opcode %d not implemented for type %@", opcode, TYPE(lhs)->qname.name);
return 0;
}
assert(0);
}
/*
Lookup an string index.
*/
static int lookupStringProperty(Ejs *ejs, EjsString *sp, EjsName qname)
{
int index;
// TODO UNICODE
if (!isdigit((uchar) qname.name->value[0])) {
return EJS_ERR;
}
index = ejsAtoi(ejs, qname.name, 10);
if (index < sp->length) {
return index;
}
return EJS_ERR;
}
/************************************ Methods *********************************/
/*
String constructor
function String()
function String(str: String)
*/
static EjsString *stringConstructor(Ejs *ejs, EjsString *sp, int argc, EjsObj **argv)
{
EjsArray *args;
assert(argc == 0 || (argc == 1 && ejsIs(ejs, argv[0], Array)));
sp->length = 0;
if (argc == 1) {
args = (EjsArray*) argv[0];
if (args->length > 0) {
return ejsToString(ejs, ejsGetProperty(ejs, args, 0));
}
}
return ejsInternString(sp);
}
/*
Do a case sensitive comparison between this string and another.
function caseCompare(compare: String): Number
*/
static EjsNumber *caseCompare(Ejs *ejs, EjsString *sp, int argc, EjsObj **argv)
{
int result;
assert(argc == 1 && ejsIs(ejs, argv[0], String));
result = wcmp(sp->value, ((EjsString*) argv[0])->value);
return ejsCreateNumber(ejs, result);
}
/*
Do a case insensitive comparison between this string and another.
function caselessCompare(compare: String): Number
*/
static EjsNumber *caselessCompare(Ejs *ejs, EjsString *sp, int argc, EjsObj **argv)
{
int result;
assert(argc == 1 && ejsIs(ejs, argv[0], String));
result = wcasecmp(sp->value, ((EjsString*) argv[0])->value);
return ejsCreateNumber(ejs, result);
}
/*
Return a string containing the character at a given index
function charAt(index: Number): String
*/
static EjsString *charAt(Ejs *ejs, EjsString *sp, int argc, EjsObj **argv)
{
int index;
assert(argc == 1 && ejsIs(ejs, argv[0], Number));
index = ejsGetInt(ejs, argv[0]);
if (index < 0 || index >= sp->length) {
return ESV(empty);
}
return ejsCreateString(ejs, &sp->value[index], 1);
}
/*
Return an integer containing the character at a given index
function charCodeAt(index: Number = 0): Number
*/
static EjsNumber *charCodeAt(Ejs *ejs, EjsString *sp, int argc, EjsObj **argv)
{
int index;
index = (argc == 1) ? ejsGetInt(ejs, argv[0]) : 0;
if (index < 0) {
index = (int) sp->length -1 ;
}
if (index < 0 || index >= sp->length) {
return ESV(nan);
}
return ejsCreateNumber(ejs, (uchar) sp->value[index]);
}
/*
Catenate args to a string and return a new string.
function concat(...args): String
*/
static EjsString *concatString(Ejs *ejs, EjsString *sp, int argc, EjsObj **argv)
{
EjsArray *args;
EjsString *result, *str;
int i;
assert(argc == 1 && ejsIs(ejs, argv[0], Array));
args = (EjsArray*) argv[0];
result = (EjsString*) ejsClone(ejs, sp, 0);
for (i = 0; i < args->length; i++) {
str = ejsToString(ejs, ejsGetProperty(ejs, args, i));
if ((result = ejsJoinString(ejs, result, str)) == NULL) {
ejsThrowMemoryError(ejs);
return 0;
}
}
return result;
}
/**
Check if a string contains the pattern (string or regexp)
function contains(pattern: Object): Boolean
*/
static EjsBoolean *containsString(Ejs *ejs, EjsString *sp, int argc, EjsObj **argv)
{
EjsObj *pat;
EjsString *spat;
pat = argv[0];
if (ejsIs(ejs, pat, String)) {
spat = (EjsString*) pat;
return ejsCreateBoolean(ejs, wcontains(sp->value, spat->value) != 0);
} else if (ejsIs(ejs, pat, RegExp)) {
EjsRegExp *rp;
int count;
rp = (EjsRegExp*) argv[0];
count = pcre_exec(rp->compiled, NULL, sp->value, (int) sp->length, 0, 0, 0, 0);
return ejsCreateBoolean(ejs, count >= 0);
}
ejsThrowTypeError(ejs, "Wrong argument type");
return 0;
}
/**
Check if a string ends with a given pattern
function endsWith(pattern: String): Boolean
*/
static EjsBoolean *endsWith(Ejs *ejs, EjsString *sp, int argc, EjsObj **argv)
{
EjsString *pattern;
ssize len;
assert(argc == 1 && ejsIs(ejs, argv[0], String));
pattern = (EjsString*) argv[0];
len = pattern->length;
if (len > sp->length) {
return ESV(false);
}
return ejsCreateBoolean(ejs, wncmp(&sp->value[sp->length - len], pattern->value, len) == 0);
}
/*
Lookup a token value. This will be called recursively for each name portion of a token. i.e. ${part.part.part}
*/
static int getTokenValue(Ejs *ejs, EjsObj *obj, cchar *fullToken, cchar *token, MprBuf *buf, EjsAny *missing,
EjsString *join)
{
EjsAny *vp;
EjsString *svalue;
EjsName qname;
char *rest, *first, *str;
rest = (char*) (schr(token, '.') ? sclone(token) : token);
first = ssplit(rest, ".", &rest);
qname.name = ejsCreateStringFromAsc(ejs, first);
qname.space = 0;
if ((vp = ejsGetPropertyByName(ejs, obj, qname)) != 0) {
if (rest && *rest && ejsIsPot(ejs, vp)) {
return getTokenValue(ejs, vp, fullToken, rest, buf, missing, join);
} else {
if (ejsIs(ejs, vp, Array)) {
svalue = ejsJoinArray(ejs, vp, join);
} else {
svalue = ejsToString(ejs, vp);
}
mprPutStringToBuf(buf, svalue->value);
}
} else if (!missing || (vp == ESV(null) || vp == ESV(undefined))) {
ejsThrowReferenceError(ejs, "Missing property %s", fullToken);
return 0;
} else if (missing == ESV(true)) {
mprPutStringToBuf(buf, "${");
mprPutStringToBuf(buf, fullToken);
mprPutCharToBuf(buf, '}');
} else if (missing == ESV(false)) {
/* Omit */;
} else {
str = ejsToMulti(ejs, missing);
// DEPRECATE LEGACY
if (smatch(str, "${}")) {
mprPutStringToBuf(buf, "${");
mprPutStringToBuf(buf, fullToken);
mprPutCharToBuf(buf, '}');
} else {
mprPutStringToBuf(buf, str);
}
}
return 1;
}
/*
function expand(obj: Object, options: Object): String
Options:
missing: String to use for missing properties.
undefined - throw exception
true Keep original token pattern ${token}
false Delete original token pattern
string Replace with string value
Expand ${token} references. Tokens are be simple properties that may include "." references.
*/
static EjsString *expandString(Ejs *ejs, EjsString *sp, int argc, EjsObj **argv)
{
MprBuf *buf;
EjsAny *missing, *obj, *options;
EjsString *join;
char *src, *cp, *tok;
if (!ejsIs(ejs, sp, String)) {
sp = ejsToString(ejs, sp);
}
missing = 0;
join = ejsCreateStringFromAsc(ejs, " ");
if (argc < 1) {
ejsThrowArgError(ejs, "Missing object argument");
return 0;
}
obj = argv[0];
options = (argc >= 2) ? argv[1] : 0;
if (options) {
missing = ejsGetPropertyByName(ejs, options, EN("missing"));
if (!missing) {
// LEGACY DEPRECATED
missing = ejsGetPropertyByName(ejs, options, EN("fill"));
}
}
if (sp->length == 0) {
return ESV(empty);
}
// UNICODE
if (schr(sp->value, '$') == 0) {
return sp;
}
buf = mprCreateBuf(0, 0);
for (src = (char*) sp->value; src < &sp->value[sp->length]; ) {
if (*src == '$' && src[1] == '{') {
if (src > sp->value && src[-1] == '$') {
for (++src; *src != '}' && src < &sp->value[sp->length]; ) {
mprPutCharToBuf(buf, *src++);
}
} else {
src += 2;
for (cp = src; *cp != '}' && cp < &sp->value[sp->length]; cp++) ;
tok = snclone(src, cp - src);
if (!getTokenValue(ejs, obj, tok, tok, buf, missing, join)) {
return 0;
}
src = cp + 1;
}
} else {
mprPutCharToBuf(buf, *src++);
}
}
mprAddNullToBuf(buf);
return ejsCreateString(ejs, mprGetBufStart(buf), mprGetBufLength(buf));
}
PUBLIC EjsString *ejsExpandString(Ejs *ejs, EjsString *sp, EjsObj *tokens)
{
return expandString(ejs, sp, 1, &tokens);
}
/**
Format the arguments
function format(...args): String
Format: %[modifier][width][precision][type]
Modifiers: +- #,
*/
static EjsString *formatString(Ejs *ejs, EjsString *sp, int argc, EjsObj **argv)
{
EjsArray *args, *inner;
EjsString *result;
EjsAny *value;
wchar *buf, fmt[32];
ssize i, flen, start, len, last;
int c, nextArg, kind;
assert(argc == 1 && ejsIs(ejs, argv[0], Array));
args = (EjsArray*) argv[0];
/*
Flatten the args if there is only one element and it is itself an array. This happens when invoked
via the overloaded operator '%' which in turn invokes format()
*/
if (args->length == 1) {
inner = ejsGetProperty(ejs, args, 0);
if (ejsIs(ejs, inner, Array)) {
args = inner;
}
}
if ((result = ejsCreateBareString(ejs, ME_MAX_BUFFER)) == NULL) {
ejsThrowMemoryError(ejs);
return 0;
}
result->length = 0;
/*
Parse the format string and extract one specifier at a time.
*/
last = 0;
for (i = 0, nextArg = 0; i < sp->length; i++) {
c = sp->value[i];
if (c != '%') {
continue;
}
if (i > last) {
result = buildString(ejs, result, &sp->value[last], i - last);
}
/*
Find the end of the format specifier and determine the format type (kind)
*/
start = i++;
i += mspn(&sp->value[i], "-+ #,0*123456789.");
kind = sp->value[i];
if (strchr("cdefginopsSuxX", kind)) {
len = i - start + 1;
wncopy(fmt, (sizeof(fmt) / sizeof(wchar)) - 4, &sp->value[start], len);
if (nextArg < args->length) {
value = ejsGetProperty(ejs, args, nextArg);
} else {
value = ESV(null);
}
buf = 0;
// OPT
switch (kind) {
case 'o':
value = ejsToNumber(ejs, value);
flen = sizeof(fmt) - len + 1;
mtow(&fmt[len - 1], flen, "Lo", 2);
buf = wfmt(fmt, (int64) ejsGetNumber(ejs, value));
break;
case 'd': case 'i': case 'u':
value = ejsToNumber(ejs, value);
flen = sizeof(fmt) - len + 1;
mtow(&fmt[len - 1], flen, ".0f", 3);
buf = wfmt(fmt, ejsGetNumber(ejs, value));
break;
case 'e': case 'g': case 'f':
value = ejsToNumber(ejs, value);
buf = wfmt(fmt, ejsGetNumber(ejs, value));
break;
case 's':
value = ejsToString(ejs, value);
buf = wfmt(fmt, ejsToMulti(ejs, value));
break;
case 'X': case 'x':
buf = wfmt(fmt, (int64) ejsGetNumber(ejs, value));
break;
case 'n':
buf = wfmt(fmt, 0);
break;
case 'c':
buf = wfmt(fmt, (int) ejsGetNumber(ejs, value));
break;
default:
ejsThrowArgError(ejs, "Bad format specifier");
return 0;
}
result = buildString(ejs, result, buf, wlen(buf));
last = i + 1;
nextArg++;
} else if (kind == '%') {
wchar percent[1];
percent[0] = '%';
result = buildString(ejs, result, percent, 1);
last = i + 1;
}
}
if (sp->length > last) {
result = buildString(ejs, result, &sp->value[last], sp->length - last);
}
return ejsInternString(result);
}
/*
Create a string from character codes
static function fromCharCode(...codes): String
*/
static EjsString *fromCharCode(Ejs *ejs, EjsString *unused, int argc, EjsObj **argv)
{
EjsString *result;
EjsArray *args;
EjsObj *vp;
int i;
assert(argc == 1 && ejsIs(ejs, argv[0], Array));
args = (EjsArray*) argv[0];
if ((result = (EjsString*) ejsCreateBareString(ejs, argc + 1)) == NULL) {
return 0;
}
for (i = 0; i < args->length; i++) {
vp = ejsGetProperty(ejs, args, i);
result->value[i] = ejsGetInt(ejs, ejsToNumber(ejs, vp));
}
result->value[i] = '\0';
result->length = args->length;
return ejsInternString(result);
}
/*
Function to iterate and return the next character code.
NOTE: this is not a method of String. Rather, it is a callback function for Iterator
*/
static EjsNumber *nextStringKey(Ejs *ejs, EjsIterator *ip, int argc, EjsObj **argv)
{
EjsString *sp;
sp = (EjsString*) ip->target;
if (!ejsIs(ejs, sp, String)) {
ejsThrowReferenceError(ejs, "Wrong type");
return 0;
}
if (ip->index < sp->length) {
return ejsCreateNumber(ejs, ip->index++);
}
ejsThrowStopIteration(ejs);
return 0;
}
/*
Return the default iterator. This returns the array index names.
iterator function get(): Iterator
*/
static EjsIterator *getStringIterator(Ejs *ejs, EjsObj *sp, int argc, EjsObj **argv)
{
return ejsCreateIterator(ejs, sp, -1, nextStringKey, 0, NULL);
}
/*
Function to iterate and return the next string character (as a string).
NOTE: this is not a method of Array. Rather, it is a callback function for Iterator
*/
static EjsString *nextStringValue(Ejs *ejs, EjsIterator *ip, int argc, EjsObj **argv)
{
EjsString *sp;
sp = (EjsString*) ip->target;
if (!ejsIs(ejs, sp, String)) {
ejsThrowReferenceError(ejs, "Wrong type");
return 0;
}
if (ip->index < sp->length) {
return ejsCreateString(ejs, &sp->value[ip->index++], 1);
}
ejsThrowStopIteration(ejs);
return 0;
}
/*
Return an iterator to return the next array element value.
iterator function getValues(): Iterator
*/
static EjsIterator *getStringValues(Ejs *ejs, EjsObj *sp, int argc, EjsObj **argv)
{
return ejsCreateIterator(ejs, sp, -1, nextStringValue, 0, NULL);
}
/*
Get the length of a string.
@return Returns the number of characters in the string
override function get length(): Number
*/
static EjsNumber *stringLength(Ejs *ejs, EjsString *ap, int argc, EjsObj **argv)
{
return ejsCreateNumber(ejs, (MprNumber) ap->length);
}
/*
Return the position of the first occurance of a substring
function indexOf(pattern: String, startIndex: Number = 0): Number
*/
static EjsNumber *indexOf(Ejs *ejs, EjsString *sp, int argc, EjsObj **argv)
{
EjsString *pattern;
ssize start, index, patternLength;
assert(1 <= argc && argc <= 2);
assert(ejsIs(ejs, argv[0], String));
pattern = (EjsString*) argv[0];
patternLength = (int) pattern->length;
if (argc == 2) {
start = ejsGetInt(ejs, argv[1]);
if (start > sp->length) {
start = sp->length;
}
if (start < 0) {
start = 0;
}
} else {
start = 0;
}
index = indexof(&sp->value[start], sp->length - start, pattern, patternLength, 1);
if (index < 0) {
return ESV(minusOne);
}
return ejsCreateNumber(ejs, (MprNumber) (index + start));
}
static EjsBoolean *isAlpha(Ejs *ejs, EjsString *sp, int argc, EjsObj **argv)
{
wchar *cp;
if (sp->length == 0) {
return ESV(false);
}
for (cp = sp->value; cp < &sp->value[sp->length]; cp++) {
if (*cp & 0x80 || !isalpha((uchar) *cp)) {
return ESV(false);
}
}
return ESV(true);
}
static EjsBoolean *isAlphaNum(Ejs *ejs, EjsString *sp, int argc, EjsObj **argv)
{
wchar *cp;
if (sp->length == 0) {
return ESV(false);
}
for (cp = sp->value; cp < &sp->value[sp->length]; cp++) {
if (*cp & 0x80 || !isalnum((uchar) *cp)) {
return ESV(false);
}
}
return ESV(true);
}
static EjsBoolean *isDigit(Ejs *ejs, EjsString *sp, int argc, EjsObj **argv)
{
wchar *cp;
if (sp->length == 0) {
return ESV(false);
}
for (cp = sp->value; cp < &sp->value[sp->length]; cp++) {
if (*cp & 0x80 || !isdigit((uchar) *cp)) {
return ESV(false);
}
}
return ESV(true);
}
static EjsBoolean *isLower(Ejs *ejs, EjsString *sp, int argc, EjsObj **argv)
{
wchar *cp;
if (sp->length == 0) {
return ESV(false);
}
for (cp = sp->value; cp < &sp->value[sp->length]; cp++) {
if (!islower((int) *cp)) {
return ESV(false);
}
}
return ESV(true);
}
static EjsBoolean *isSpace(Ejs *ejs, EjsString *sp, int argc, EjsObj **argv)
{
wchar *cp;
if (sp->length == 0) {
return ESV(false);
}
for (cp = sp->value; cp < &sp->value[sp->length]; cp++) {
if (*cp & 0x80 || !isspace((uchar) *cp)) {
return ESV(false);
}
}
return ESV(true);
}
static EjsBoolean *isUpper(Ejs *ejs, EjsString *sp, int argc, EjsObj **argv)
{
wchar *cp;
if (sp->length == 0) {
return ESV(false);
}
for (cp = sp->value; cp < &sp->value[sp->length]; cp++) {
if (!isupper((int) *cp)) {
return ESV(false);
}
}
return ESV(true);
}
/*
Return the position of the last occurance of a substring
function lastIndexOf(pattern: String, start: Number = -1): Number
*/
static EjsNumber *lastIndexOf(Ejs *ejs, EjsString *sp, int argc, EjsObj **argv)
{
EjsString *pattern;
ssize start, patternLength, index;
assert(1 <= argc && argc <= 2);
pattern = (EjsString*) argv[0];
patternLength = (int) pattern->length;
if (argc == 2) {
start = ejsGetInt(ejs, argv[1]);
if (start >= (int) sp->length) {
start = (int) sp->length - 1;
}
if (start < 0) {
start = 0;
}
} else {
start = 0;
}
index = indexof(sp->value, sp->length, pattern, patternLength, -1);
if (index < 0) {
return ESV(minusOne);
}
return ejsCreateNumber(ejs, (MprNumber) index);
}
/*
Match a pattern
function match(pattern: RegExp): Array
*/
static EjsArray *match(Ejs *ejs, EjsString *sp, int argc, EjsObj **argv)
{
EjsRegExp *rp;
EjsArray *results;
EjsString *match;
int matches[ME_MAX_REGEX_MATCHES * 3];
int i, count, len, resultCount;
rp = (EjsRegExp*) argv[0];
rp->endLastMatch = 0;
results = NULL;
resultCount = 0;
do {
count = pcre_exec(rp->compiled, NULL, sp->value, (int) sp->length, rp->endLastMatch, 0, matches,
sizeof(matches) / sizeof(int));
if (count <= 0) {
break;
}
if (results == 0) {
results = ejsCreateArray(ejs, count);
}
for (i = 0; i < count * 2; i += 2) {
len = matches[i + 1] - matches[i];
match = ejsCreateString(ejs, &sp->value[matches[i]], len);
ejsSetProperty(ejs, results, resultCount++, match);
if (rp->global) {
if (matches[1] == rp->endLastMatch) {
rp->endLastMatch++;
} else {
rp->endLastMatch = matches[1];
}
break;
}
}
} while (rp->global);
if (results == NULL) {
return ESV(null);
}
return results;
}
static EjsString *printable(Ejs *ejs, EjsString *sp, int argc, EjsObj **argv)
{
EjsString *result;
wchar buf[16];
ssize len;
int i, j, k, nonprint;
nonprint = 0;
for (i = 0; i < sp->length; i++) {
if (!isprint((uchar) sp->value[i])) {
nonprint++;
}
}
if (nonprint == 0) {
return sp;
}
if ((result = ejsCreateBareString(ejs, sp->length + (nonprint * 6) + 1)) == NULL) {
return 0;
}
for (i = 0, j = 0; i < sp->length; i++) {
if (isprint((uchar) sp->value[i])) {
result->value[j++] = sp->value[i];
} else {
result->value[j++] = '\\';
result->value[j++] = 'u';
itosbuf(buf, 4, (uchar) sp->value[i], 16);
len = wlen(buf);
for (k = (int) len; k < 4; k++) {
result->value[j++] = '0';
}
for (k = 0; buf[k]; k++) {
result->value[j++] = buf[k];
}
}
}
result->value[j] = '\0';
result->length = j;
return ejsInternString(result);
}
static EjsString *quote(Ejs *ejs, EjsString *sp, int argc, EjsObj **argv)
{
EjsString *result;
if ((result = ejsCreateBareString(ejs, sp->length + 2)) == NULL) {
return 0;
}
memcpy(&result->value[1], sp->value, sp->length);
result->value[0] = '"';
result->value[sp->length + 1] = '"';
result->value[sp->length + 2] = '\0';
result->length = sp->length + 2;
return ejsInternString(result);
}
/*
Remove characters and return a new string.
function remove(start: Number, end: Number = -1): String
*/
static EjsString *removeCharsFromString(Ejs *ejs, EjsString *sp, int argc, EjsObj **argv)
{
EjsString *result;
ssize start, end, i, j;
assert(1 <= argc && argc <= 2);
start = ejsGetInt(ejs, argv[0]);
end = ejsGetInt(ejs, argv[1]);
if (start < 0) {
start += sp->length;
}
if (start < 0) {
start = 0;
}
if (end < 0) {
end += sp->length;
}
if (end < 0) {
end = 0;
}
if (start >= sp->length) {
start = sp->length - 1;
}
if (end > sp->length) {
end = sp->length;
}
if ((result = ejsCreateBareString(ejs, sp->length - (end - start))) == NULL) {
return 0;
}
for (j = i = 0; i < start; i++, j++) {
result->value[j] = sp->value[i];
}
for (i = end; i < sp->length; i++, j++) {
result->value[j] = sp->value[i];
}
result->value[j] = '\0';
return ejsInternString(result);
}
static EjsString *getReplacementText(Ejs *ejs, EjsFunction *fn, int count, int *matches, EjsString *sp)
{
EjsAny *result, *argv[ME_MAX_REGEX_MATCHES * 3];
int i, offset, argc;
assert(fn);
argc = 0;
argv[argc++] = ejsCreateString(ejs, &sp->value[matches[0]], matches[1] - matches[0]);
for (i = 1; i < count; i++) {
offset = i * 2;
argv[argc++] = ejsCreateString(ejs, &sp->value[matches[offset]], matches[offset + 1] - matches[offset]);
}
argv[argc++] = ejsCreateNumber(ejs, matches[0]);
argv[argc++] = sp;
if ((result = ejsRunFunction(ejs, fn, ejs->global, argc, argv)) == 0) {
return 0;
}
return (EjsString*) ejsToString(ejs, result);
}
/*
Search and replace
function replace(pattern: (String|Regexp), replacement: (String|Function)): String
*/
static EjsString *replace(Ejs *ejs, EjsString *sp, int argc, EjsObj **argv)
{
EjsString *result, *replacement, *pattern;
EjsFunction *replacementFunction;
wchar cbuf[1];
ssize patternLength, index;
int matches[ME_MAX_REGEX_MATCHES * 3], enabled;
result = 0;
if (argc == 1) {
replacement = ESV(empty);
replacementFunction = 0;
} else if (ejsIsFunction(ejs, argv[1])) {
replacementFunction = (EjsFunction*) argv[1];
replacement = 0;
} else {
replacement = (EjsString*) ejsToString(ejs, argv[1]);
replacementFunction = 0;
}
if (ejsIs(ejs, argv[0], RegExp)) {
EjsRegExp *rp;
wchar *cp, *lastReplace, *end;
ssize endLastMatch, startNextMatch, submatch;
int count;
rp = (EjsRegExp*) argv[0];
result = ejsCreateBareString(ejs, ME_MAX_BUFFER);
result->length = 0;
startNextMatch = endLastMatch = 0;
do {
if (startNextMatch > sp->length) {
break;
}
count = pcre_exec(rp->compiled, NULL, sp->value, (int) sp->length, (int) startNextMatch, 0, matches,
sizeof(matches) / sizeof(int));
if (count <= 0) {
break;
}
if (endLastMatch < matches[0]) {
/* Append prior string text */
result = buildString(ejs, result, &sp->value[endLastMatch], matches[0] - endLastMatch);
}
/*
Process the replacement template
*/
if (replacementFunction) {
enabled = mprEnableGC(0);
replacement = getReplacementText(ejs, replacementFunction, count, matches, sp);
mprEnableGC(enabled);
}
end = &replacement->value[replacement->length];
lastReplace = replacement->value;
for (cp = replacement->value; cp < end; ) {
if (*cp == '$') {
if (lastReplace < cp) {
result = buildString(ejs, result, lastReplace, (int) (cp - lastReplace));
}
switch (*++cp) {
case '$':
cbuf[0] = '$';
result = buildString(ejs, result, cbuf, 1);
break;
case '&':
/* Replace the matched string */
result = buildString(ejs, result, &sp->value[matches[0]], matches[1] - matches[0]);
break;
case '`':
/* Insert the portion that preceeds the matched string */
result = buildString(ejs, result, sp->value, matches[0]);
break;
case '\'':
/* Insert the portion that follows the matched string */
result = buildString(ejs, result, &sp->value[matches[1]], sp->length - matches[1]);
break;
default:
/* Insert the nth submatch */
if (isdigit((uchar) *cp)) {
submatch = (int) wtoi(cp);
while (isdigit((uchar) *++cp))
;
cp--;
if (submatch < count) {
submatch *= 2;
result = buildString(ejs, result,
&sp->value[matches[submatch]], matches[submatch + 1] - matches[submatch]);
}
} else {
ejsThrowArgError(ejs, "Bad replacement $ specification");
return 0;
}
}
lastReplace = cp + 1;
}
cp++;
}
if (lastReplace < cp && lastReplace < end) {
result = buildString(ejs, result, lastReplace, (int) (cp - lastReplace));
}
endLastMatch = matches[1];
startNextMatch = endLastMatch;
if (matches[0] == matches[1]) {
/*
A pattern may match but have no length. Step over the position always.
E.g. multline matching ^ or $, or an optional pattern
*/
startNextMatch++;
}
} while (rp->global);
if (endLastMatch < sp->length) {
/* Append remaining string text */
result = buildString(ejs, result, &sp->value[endLastMatch], sp->length - endLastMatch);
}
} else {
pattern = ejsToString(ejs, argv[0]);
patternLength = pattern->length;
index = indexof(sp->value, sp->length, pattern, patternLength, 1);
if (index >= 0) {
if ((result = ejsCreateBareString(ejs, ME_MAX_BUFFER)) == NULL) {
return 0;
}
result->length = 0;
result = buildString(ejs, result, sp->value, index);
if (replacementFunction) {
matches[0] = matches[2] = (int) index;
matches[1] = matches[3] = (int) (index + patternLength);
enabled = mprEnableGC(0);
replacement = getReplacementText(ejs, replacementFunction, 2, matches, sp);
mprEnableGC(enabled);
}
result = buildString(ejs, result, replacement->value, replacement->length);
index += patternLength;
if (index < sp->length) {
result = buildString(ejs, result, &sp->value[index], sp->length - index);
}
} else {
result = ejsClone(ejs, sp, 0);
}
}
return ejsInternString(result);
}
static EjsString *reverseString(Ejs *ejs, EjsString *sp, int argc, EjsObj **argv)
{
EjsString *rp;
wchar *cp;
ssize i;
if (sp->length <= 1) {
return sp;
}
if ((rp = ejsCreateBareString(ejs, sp->length)) == 0) {
return 0;
}
cp = rp->value;
for (i = sp->length - 1; i >= 0; i--) {
*cp++ = sp->value[i];
}
return ejsInternString(rp);
}
/*
Search for a pattern
function search(pattern: (String | RegExp)): Number
*/
static EjsNumber *searchString(Ejs *ejs, EjsString *sp, int argc, EjsObj **argv)
{
EjsRegExp *rp;
EjsString *pattern;
ssize index, patternLength;
int count, matches[ME_MAX_REGEX_MATCHES * 3];
if (ejsIs(ejs, argv[0], String)) {
pattern = (EjsString*) argv[0];
patternLength = (int) pattern->length;
index = indexof(sp->value, sp->length, pattern, patternLength, 1);
return ejsCreateNumber(ejs, (MprNumber) index);
} else if (ejsIs(ejs, argv[0], RegExp)) {
rp = (EjsRegExp*) argv[0];
count = pcre_exec(rp->compiled, NULL, sp->value, (int) sp->length, 0, 0, matches, sizeof(matches) / sizeof(int));
if (count < 0) {
return ESV(minusOne);
}
return ejsCreateNumber(ejs, matches[0]);
} else {
ejsThrowTypeError(ejs, "Wrong argument type");
}
return 0;
}
/*
Return a substring. End is one past the last character.
function slice(start: Number, end: Number = -1, step: Number = 1): String
*/
static EjsString *sliceString(Ejs *ejs, EjsString *sp, int argc, EjsObj **argv)
{
EjsString *result;
ssize start, end, step, i, j, size;
assert(1 <= argc && argc <= 3);
start = ejsGetInt(ejs, argv[0]);
if (argc >= 2) {
end = ejsGetInt(ejs, argv[1]);
} else {
end = sp->length;
}
if (argc == 3) {
step = ejsGetInt(ejs, argv[2]);
} else {
step = 1;
}
if (start < 0) {
start += sp->length;
}
if (start < 0) {
start = 0;
} else if (start >= sp->length) {
start = sp->length;
}
if (end < 0) {
end += sp->length;
}
if (end < 0) {
end = 0;
} if (end >= sp->length) {
end = sp->length;
}
if (step == 0) {
step = 1;
}
size = (start < end) ? end - start : start - end;
if ((result = ejsCreateBareString(ejs, ((size / (ssize) abs(((int) step))) + 1))) == NULL) {
return 0;
}
if (step > 0) {
for (i = start, j = 0; i < end; i += step) {
result->value[j++] = sp->value[i];
}
} else {
for (i = start, j = 0; i > end; i += step) {
result->value[j++] = sp->value[i];
}
}
result->value[j] = '\0';
result->length = j;
return ejsInternString(result);
}
/*
Split a string
function split(delimiter: (String | RegExp), limit: Number = -1): Array
*/
static EjsArray *split(Ejs *ejs, EjsString *sp, int argc, EjsObj **argv)
{
EjsArray *results;
EjsString *elt, *delim;
wchar *cp, *mark, *end;
ssize limit;
assert(1 <= argc && argc <= 2);
limit = (argc == 2) ? ejsGetInt(ejs, argv[1]): MAXSSIZE;
results = ejsCreateArray(ejs, 0);
if (ejsIs(ejs, argv[0], String)) {
delim = (EjsString*) argv[0];
if (delim->length == 0) {
for (cp = sp->value; (--limit != -1) && *cp; cp++) {
ejsSetProperty(ejs, results, -1, ejsCreateString(ejs, cp, 1));
}
} else {
end = &sp->value[sp->length];
for (mark = cp = sp->value; limit > 0 && mark < end; mark++, limit--) {
if (wncmp(mark, delim->value, delim->length) == 0) {
elt = ejsCreateString(ejs, cp, (int) (mark - cp));
ejsSetProperty(ejs, results, -1, elt);
cp = mark + delim->length;
mark = cp - 1;
}
}
elt = ejsCreateString(ejs, cp, (int) (mark - cp));
ejsSetProperty(ejs, results, -1, elt);
}
return results;
} else if (ejsIs(ejs, argv[0], RegExp)) {
EjsRegExp *rp;
EjsString *match;
int matches[ME_MAX_REGEX_MATCHES * 3], count, resultCount;
rp = (EjsRegExp*) argv[0];
rp->endLastMatch = 0;
resultCount = 0;
while (1) {
count = (int) pcre_exec(rp->compiled, NULL, sp->value, (int) sp->length, rp->endLastMatch, 0, matches,
sizeof(matches) / sizeof(int));
if (count <= 0) {
break;
}
match = ejsCreateString(ejs, &sp->value[rp->endLastMatch], matches[0] - rp->endLastMatch);
ejsSetProperty(ejs, results, resultCount++, match);
if (matches[1] == rp->endLastMatch) {
/* Catch patterns that match the empty string - prevents infinite loop */
rp->endLastMatch = matches[1] + 1;
} else {
rp->endLastMatch = matches[1];
}
}
if (rp->endLastMatch < sp->length) {
match = ejsCreateString(ejs, &sp->value[rp->endLastMatch], sp->length - rp->endLastMatch);
ejsSetProperty(ejs, results, resultCount, match);
} else {
ejsSetProperty(ejs, results, resultCount, ESV(empty));
}
return results;
}
ejsThrowTypeError(ejs, "Wrong argument type");
return 0;
}
/**
Check if a string starts with a given pattern
function startsWith(pattern: String): Boolean
*/
static EjsBoolean *startsWith(Ejs *ejs, EjsString *sp, int argc, EjsObj **argv)
{
EjsString *pattern;
assert(argc == 1 && ejsIs(ejs, argv[0], String));
pattern = (EjsString*) argv[0];
return ejsCreateBoolean(ejs, wncmp(&sp->value[0], pattern->value, pattern->length) == 0);
}
/*
Extract a substring. Simple routine with positive indicies.
function substring(start: Number, end: Number = -1): String
*/
static EjsString *substring(Ejs *ejs, EjsString *sp, int argc, EjsObj **argv)
{
ssize start, end, tmp;
start = ejsGetInt(ejs, argv[0]);
if (argc == 2) {
end = ejsGetInt(ejs, argv[1]);
} else {
end = sp->length;
}
if (start < 0) {
start = 0;
}
if (start >= sp->length) {
start = sp->length - 1;
}
if (end < 0) {
end = sp->length;
}
if (end > sp->length) {
end = sp->length;
}
/*
Swap if start is bigger than end
*/
if (start > end) {
tmp = start;
start = end;
end = tmp;
}
return ejsSubstring(ejs, sp, start, (int) (end - start));
}
/*
Convert the string to camelCase. Return a new string.
function toCamel(): String
*/
static EjsString *toCamel(Ejs *ejs, EjsString *sp, int argc, EjsObj **argv)
{
EjsString *result;
if ((result = ejsCreateBareString(ejs, sp->length)) == 0) {
return 0;
}
memcpy(result->value, sp->value, sp->length * sizeof(wchar));
result->value[0] = tolower((uchar) sp->value[0]);
return ejsInternString(result);
}
/*
Convert a string to a literal string representation. Wrap in quotes and backquote any quotes or backquotes.
*/
PUBLIC EjsString *ejsToLiteralString(Ejs *ejs, EjsObj *vp)
{
EjsString *sp;
MprBuf *buf;
int i, c;
if (ejsIs(ejs, vp, String)) {
sp = (EjsString*) vp;
} else {
sp = ejsToString(ejs, vp);
}
buf = mprCreateBuf(0, 0);
mprPutCharToBuf(buf, '"');
for (i = 0; i < sp->length; i++) {
c = sp->value[i];
if (c == '"' || c == '\\') {
mprPutCharToBuf(buf, '\\');
mprPutCharToBuf(buf, c);
} else {
mprPutCharToBuf(buf, c);
}
}
mprPutCharToBuf(buf, '"');
mprAddNullToBuf(buf);
return ejsCreateStringFromAsc(ejs, mprGetBufStart(buf));
}
/*
Convert the string to lower case.
function toLowerCase(locale: String = null): String
*/
static EjsString *toLowerCase(Ejs *ejs, EjsString *sp, int argc, EjsObj **argv)
{
return ejsToLower(ejs, sp);
}
/*
Convert the string to PascalCase. Return a new string.
function toPascal(): String
*/
static EjsString *toPascal(Ejs *ejs, EjsString *sp, int argc, EjsObj **argv)
{
EjsString *result;
if ((result = ejsCreateBareString(ejs, sp->length)) == 0) {
return 0;
}
memcpy(result->value, sp->value, sp->length * sizeof(wchar));
result->value[0] = toupper((uchar) sp->value[0]);
return ejsInternString(result);
}
/*
Convert to a string
override function toString(): String
*/
static EjsString *stringToString(Ejs *ejs, EjsString *sp, int argc, EjsObj **argv)
{
return sp;
}
/*
Convert the string to upper case.
@return Returns a new upper case version of the string.
@spec ejs-11
function toUpperCase(locale: String = null): String
*/
static EjsString *toUpperCase(Ejs *ejs, EjsString *sp, int argc, EjsObj **argv)
{
return ejsToUpper(ejs, sp);
}
/*
Scan the input and tokenize according to the format string
function tokenize(format: String): Array
*/
static EjsArray *tokenize(Ejs *ejs, EjsString *sp, int argc, EjsObj **argv)
{
EjsArray *result;
wchar *cp, *buf;
cchar *fmt;
assert(argc == 1 && ejsIs(ejs, argv[0], String));
buf = sp->value;
fmt = ejsToMulti(ejs, argv[0]);
result = ejsCreateArray(ejs, 0);
for (fmt = ejsToMulti(ejs, argv[0]); *fmt && buf < &sp->value[sp->length]; ) {
if (*fmt++ != '%') {
continue;
}
switch (*fmt) {
case 's':
for (cp = buf; *cp; cp++) {
if (isspace((uchar) *cp)) {
break;
}
}
ejsSetProperty(ejs, result, -1, ejsSubstring(ejs, sp, (int) (buf - sp->value), (int) (cp - buf)));
buf = cp;
break;
case 'd':
ejsSetProperty(ejs, result, -1, ejsParse(ejs, buf, S_Number));
while (*buf && !isspace((uchar) *buf)) {
buf++;
}
break;
default:
ejsThrowArgError(ejs, "Bad format specifier");
return 0;
}
while (*buf && isspace((uchar) *buf)) {
buf++;
}
}
return result;
}
static EjsString *trim(Ejs *ejs, EjsString *sp, EjsString *pattern, int where)
{
wchar *start, *end, *mark;
ssize index, patternLength;
if (pattern == 0) {
start = sp->value;
if (where & MPR_TRIM_START) {
for (; start < &sp->value[sp->length]; start++) {
if (!isspace((uchar) *start)) {
break;
}
}
}
end = &sp->value[sp->length - 1];
if (where & MPR_TRIM_END) {
for (end = &sp->value[sp->length - 1]; end >= start; end--) {
if (!isspace((uchar) *end)) {
break;
}
}
}
end++;
} else {
patternLength = pattern->length;
if (patternLength <= 0 || patternLength > sp->length) {
return sp;
}
mark = sp->value;
if (where & MPR_TRIM_START) {
for (; &mark[patternLength] <= &sp->value[sp->length]; mark += patternLength) {
index = indexof(mark, patternLength, pattern, patternLength, 1);
if (index != 0) {
break;
}
}
}
start = mark;
mark = &sp->value[sp->length - patternLength];
if (where & MPR_TRIM_END) {
for (; mark >= sp->value; mark -= patternLength) {
index = indexof(mark, patternLength, pattern, patternLength, 1);
if (index != 0) {
break;
}
}
}
end = mark + patternLength;
}
return ejsSubstring(ejs, sp, (int) (start - sp->value), (int) (end - start));
}
/**
Returns a trimmed copy of the string. Normally used to trim white space, but can be used to trim any substring
from the start or end of the string.
@param str May be set to a substring to trim from the string. If not set, it defaults to any white space.
@return Returns a (possibly) modified copy of the string
function trim(str: String = null): String
*/
static EjsString *trimString(Ejs *ejs, EjsString *sp, int argc, EjsObj **argv)
{
EjsString *pattern;
if (argc == 0) {
return trim(ejs, sp, NULL, MPR_TRIM_START | MPR_TRIM_END);
} else {
pattern = (EjsString*) ejsToString(ejs, argv[0]);
return trim(ejs, sp, pattern, MPR_TRIM_START | MPR_TRIM_END);
}
}
/*
function trimStart(str: String = null): String
*/
static EjsString *trimStartString(Ejs *ejs, EjsString *sp, int argc, EjsObj **argv)
{
EjsString *pattern;
assert(argc == 0 || (argc == 1 && ejsIs(ejs, argv[0], String)));
if (argc == 0) {
return trim(ejs, sp, NULL, MPR_TRIM_START);
} else {
pattern = (EjsString*) argv[0];
return trim(ejs, sp, pattern, MPR_TRIM_START);
}
}
/*
function trimEnd(str: String = null): String
*/
static EjsString *trimEndString(Ejs *ejs, EjsString *sp, int argc, EjsObj **argv)
{
EjsString *pattern;
assert(argc == 0 || (argc == 1 && ejsIs(ejs, argv[0], String)));
if (argc == 0) {
return trim(ejs, sp, NULL, MPR_TRIM_END);
} else {
pattern = (EjsString*) argv[0];
return trim(ejs, sp, pattern, MPR_TRIM_END);
}
}
/*********************************** Support **********************************/
#if UNUSED
/**
Fast append a string. This modifies the original "dest" string. BEWARE: strings are meant to be immutable.
Only use this when constructing strings.
*/
static int catString(Ejs *ejs, EjsString *dest, char *str, ssize len)
{
EjsString *castSrc;
char *oldBuf, *buf;
int oldLen, newLen;
assert(dest);
castSrc = 0;
oldBuf = dest->value;
oldLen = dest->length;
newLen = oldLen + len + 1;
#if FUTURE
if (newLen < MPR_SLAB_STR_MAX) {
buf = oldBuf;
} else {
#endif
buf = (char*) mprRealloc(oldBuf, newLen);
if (buf == 0) {
return -1;
}
dest->value = buf;
#if FUTURE
}
#endif
memcpy(&buf[oldLen], str, len);
dest->length += len;
buf[dest->length] = '\0';
return 0;
}
#endif
/*
Append the given string to the result
*/
static EjsString *buildString(Ejs *ejs, EjsString *result, wchar *str, ssize len)
{
EjsString *newBuf;
ssize room, size, extra;
assert(result);
room = mprGetBlockSize(result) - sizeof(EjsString);
if ((result->length + len + 1) >= room) {
extra = max(result->length / 8, len);
size = max(result->length + extra, 512);
if ((newBuf = ejsCreateBareString(ejs, size)) == NULL) {
return NULL;
}
memcpy(newBuf->value, result->value, result->length * sizeof(wchar));
newBuf->length = result->length;
result = newBuf;
}
memcpy(&result->value[result->length], str, len * sizeof(wchar));
result->length += len;
result->value[result->length] = 0;
/* Don't intern */
return result;
}
/*
Find a substring. Search forward or backwards. Return the index in the string where the pattern was found.
Return -1 if not found.
*/
static ssize indexof(wchar *str, ssize len, EjsString *pattern, ssize patternLength, int dir)
{
wchar *s1, *s2;
ssize i, j;
assert(dir == 1 || dir == -1);
if (dir > 0) {
for (i = 0; i < len; i++) {
s1 = &str[i];
for (j = 0, s2 = pattern->value; j < patternLength; s1++, s2++, j++) {
if (*s1 != *s2) {
break;
}
}
if (*s2 == '\0') {
return i;
}
}
} else {
for (i = len - 1; i >= 0; i--) {
s1 = &str[i];
for (j = 0, s2 = pattern->value; j < patternLength; s1++, s2++, j++) {
if (*s1 != *s2) {
break;
}
}
if (*s2 == '\0') {
return i;
}
}
}
return -1;
}
/******************************************** String API *******************************************/
PUBLIC int ejsAtoi(Ejs *ejs, EjsString *sp, int radix)
{
int num, i;
num = 0;
for (i = 0; i < (int) sp->length; i++) {
num = num * radix + (sp->value[i] - '0');
}
return num;
}
PUBLIC EjsString *ejsJoinString(Ejs *ejs, EjsString *s1, EjsString *s2)
{
EjsString *result;
ssize len;
if (s1->length == 0) {
return s2;
}
if (s2->length == 0) {
return s1;
}
len = s1->length + s2->length;
if ((result = ejsCreateBareString(ejs, len)) == NULL) {
return NULL;
}
memcpy(result->value, s1->value, s1->length * sizeof(wchar));
memcpy(&result->value[s1->length], s2->value, s2->length * sizeof(wchar));
return ejsInternString(result);
}
/*
Join a set of unicode string arguments onto another.
TODO - rename to join
*/
PUBLIC EjsString *ejsJoinStrings(Ejs *ejs, EjsString *src, ...)
{
EjsString *sp, *result;
va_list args;
ssize len;
va_start(args, src);
for (len = 0, sp = src; sp; ) {
sp = va_arg(args, EjsString*);
len += sp->length;
}
if ((result = ejsCreateBareString(ejs, len)) == NULL) {
return NULL;
}
result->length = 0;
va_start(args, src);
for (sp = src; sp; ) {
sp = va_arg(args, EjsString*);
memcpy(&result->value[result->length], src->value, src->length);
result->length += src->length;
}
va_end(args);
return ejsInternString(result);
}
PUBLIC int ejsStartsWithAsc(Ejs *ejs, EjsString *sp, cchar *pat)
{
ssize i;
assert(sp);
assert(pat);
if (pat == 0 || *pat == '\0') {
return 0;
}
for (i = 0; pat[i] && i < sp->length; i++) {
if (sp->value[i] != pat[i]) {
break;
}
}
if (pat[i]) {
return -1;
}
return 0;
}
PUBLIC int ejsCompareAsc(Ejs *ejs, EjsString *sp, cchar *str)
{
wchar *s1;
cchar *s2;
int rc;
s1 = sp->value;
s2 = str;
if (s1 == 0) {
return -1;
}
if (s2 == 0) {
return 1;
}
if ((cchar*) s1 == s2) {
return 0;
}
for (rc = 0; *s1 && *s2 && rc == 0; s1++, s2++) {
rc = *s1 - *s2;
}
if (rc) {
return rc < 0 ? -1 : 1;
}
if (*s1 == '\0' && *s2) {
return -1;
}
if (*s2 == '\0' && *s1) {
return 1;
}
return rc;
}
/*
Compare interned strings
*/
PUBLIC int ejsCompareString(Ejs *ejs, EjsString *sp1, EjsString *sp2)
{
wchar *s1;
wchar *s2;
int rc;
s1 = sp1->value;
s2 = sp2->value;
if (s1 == s2) {
/* No need to compare interned strings char-by-char */
return 0;
} else if (s1 == 0) {
return -1;
} else if (s2 == 0) {
return 1;
}
for (rc = 0; *s1 && *s2 && rc == 0; s1++, s2++) {
rc = *s1 - *s2;
}
if (rc) {
return rc < 0 ? -1 : 1;
} else if (*s1 == '\0' && *s2) {
return -1;
} else if (*s2 == '\0' && *s1) {
return 1;
}
assert(0);
return 0;
}
PUBLIC int ejsCompareSubstring(Ejs *ejs, EjsString *sp1, EjsString *sp2, ssize offset, ssize len)
{
assert(0 <= len && len < MAXINT);
if (offset < 0 || offset >= sp2->length) {
return -1;
}
return ejsCompareWide(ejs, sp1, &sp2->value[offset], len);
}
PUBLIC int ejsCompareWide(Ejs *ejs, EjsString *sp1, wchar *sp2, ssize len)
{
wchar *s1;
wchar *s2;
int rc;
assert(0 <= len && len < MAXINT);
s1 = sp1->value;
s2 = sp2;
if (s1 == s2) {
return 0;
} else if (s1 == 0) {
return -1;
} else if (s2 == 0) {
return 1;
}
for (rc = 0; len > 0 && *s1 && *s2 && rc == 0; s1++, s2++, len--) {
rc = *s1 - *s2;
}
if (rc) {
return rc < 0 ? -1 : 1;
} else if (len == 0) {
return 0;
} else if (*s1 == 0 && *s2 == 0) {
return 0;
} else if (*s1 == '\0' && *s2) {
return -1;
} else if (*s2 == '\0' && *s1) {
return 1;
}
return 0;
}
/*
Return the index in a unicode string of a given unicode character code. Return -1 if not found.
*/
PUBLIC int ejsContainsChar(Ejs *ejs, EjsString *sp, int charPat)
{
int i;
assert(sp);
for (i = 0; i < sp->length; i++) {
if (sp->value[i] == charPat) {
return i;
}
}
return -1;
}
#if UNUSED && KEEP
/*
Return TRUE if a unicode string contains a given unicode string after doing a case insensitive comparison.
*/
PUBLIC int ejsContainsStringAnyCase(Ejs *ejs, EjsString *sp, EjsString *pat)
{
int i, j;
assert(sp);
assert(pat);
assert(pat->value);
for (i = 0; i < sp->length; i++) {
for (j = 0; j < pat->length; j++) {
// TODO UNICODE - tolower only works for ASCII
if (tolower((uchar) sp->value[i]) != tolower((uchar) pat->value[j])) {
break;
}
}
if (j == pat->length) {
return 1;
}
}
return 0;
}
#endif
PUBLIC int ejsContainsAsc(Ejs *ejs, EjsString *sp, cchar *pat)
{
ssize len;
int i, j, k;
assert(sp);
if (pat == 0 || *pat == '\0' || sp == 0) {
return 0;
}
len = strlen(pat);
for (i = 0; i < sp->length; i++) {
for (j = 0, k = i; j < len; j++, k++) {
if (sp->value[k] != pat[j]) {
break;
}
}
if (j == len) {
return i;
}
}
return -1;
}
PUBLIC int ejsContainsString(Ejs *ejs, EjsString *sp, EjsString *pat)
{
int i, j, k;
assert(sp);
assert(pat);
assert(pat->value);
if (pat == 0) {
return -1;
}
for (i = 0; i < sp->length; i++) {
for (j = 0, k = i; j < pat->length; j++, k++) {
if (sp->value[k] != pat->value[j]) {
break;
}
}
if (j == pat->length) {
return i;
}
}
return -1;
}
PUBLIC char *ejsToMulti(Ejs *ejs, EjsAny *ev)
{
if (ev == 0) {
ev = ESV(empty);
}
if (!ejsIs(ejs, ev, String)) {
if ((ev = ejsCast(ejs, ev, String)) == 0) {
return MPR->emptyString;
}
}
assert(ejsIs(ejs, ev, String));
// UNICODE
#if ME_CHAR_LEN == 1
{
EjsString *s = (EjsString*) ev;
char *ptr;
ptr = mprMemdupMem(s->value, s->length + 1);
ptr[s->length] = '\0';
return ptr;
}
#else
return awtom(((EjsString*) ev)->value, NULL);
#endif
}
PUBLIC EjsString *ejsSprintf(Ejs *ejs, cchar *fmt, ...)
{
va_list ap;
char *result;
assert(fmt);
va_start(ap, fmt);
result = sfmtv(fmt, ap);
va_end(ap);
return ejsCreateStringFromAsc(ejs, result);
}
/*
Get a substring from "src" starting at "start" of length "len"
If len < 0, use entire string.
*/
PUBLIC EjsString *ejsSubstring(Ejs *ejs, EjsString *src, ssize start, ssize len)
{
EjsString *result;
assert(src);
assert(start >= 0);
assert((start + len) <= src->length);
if (len < 0) {
len = src->length - start;
}
if (len < 0 || (start + len) > src->length || start < 0) {
return ESV(empty);
}
len = min(len, src->length);
if ((result = ejsCreateBareString(ejs, len)) == NULL) {
return NULL;
}
memcpy(result->value, &src->value[start], len);
return ejsInternString(result);
}
PUBLIC EjsString *ejsToLower(Ejs *ejs, EjsString *sp)
{
EjsString *result;
int i;
assert(sp);
assert(sp->value);
result = (EjsString*) ejsCreateBareString(ejs, sp->length);
for (i = 0; i < sp->length; i++) {
result->value[i] = tolower((uchar) sp->value[i]);
}
return ejsInternString(result);
}
PUBLIC EjsString *ejsToUpper(Ejs *ejs, EjsString *sp)
{
EjsString *result;
int i;
assert(sp);
assert(sp->value);
result = (EjsString*) ejsCreateBareString(ejs, sp->length);
for (i = 0; i < sp->length; i++) {
result->value[i] = toupper((uchar) sp->value[i]);
}
return ejsInternString(result);
}
#if UNUSED && KEEP
PUBLIC EjsString *ejsTrimString(Ejs *ejs, EjsString *sp, cchar *pat, int flags)
{
EjsString *result;
wchar *start, *end;
cchar *p;
int plen, trimmed;
assert(pat);
start = sp->value;
plen = strlen(pat);
trimmed = 0;
if (flags & MPR_TRIM_START) {
for (; *start; start++) {
for (p = pat; *p; p++) {
if (*start == *p) {
break;
}
}
if (*start != *p) {
break;
}
trimmed++;
}
}
if (flags & MPR_TRIM_END) {
for (end = &sp->value[sp->length]; end > start; end--) {
for (p = pat; *p; p++) {
if (*start == *p) {
break;
}
}
if (*start != *p) {
break;
}
trimmed++;
}
}
result = ejsCreateBareString(ejs, sp->length - trimmed);
memcpy(result->value, start, result->length);
return ejsInternString(result);
}
#endif
PUBLIC EjsString *ejsTruncateString(Ejs *ejs, EjsString *sp, ssize len)
{
EjsString *result;
assert(sp);
len = min(len, sp->length);
result = ejsCreateBareString(ejs, len);
memcpy(result->value, sp->value, len);
return ejsInternString(result);
}
/*********************************** Interning *********************************/
static void revive(EjsString *sp)
{
MprMem *mp;
mp = (MprMem*) MPR_GET_MEM(sp);
mp->mark = MPR->heap->mark;
}
/*
Intern a unicode string. Lookup a string and return an interned string (this may be an existing interned string)
*/
PUBLIC EjsString *ejsInternString(EjsString *str)
{
EjsString *head, *sp;
EjsIntern *ip;
ssize i, len;
int index, step;
ip = ((EjsService*) MPR->ejsService)->intern;
step = 0;
lock(ip);
ip->accesses++;
index = whash(str->value, str->length) % ip->size;
if ((head = &ip->buckets[index]) != NULL) {
for (sp = head->next; sp != head; sp = sp->next, step++) {
if (str == sp) {
revive(sp);
unlock(ip);
return sp;
}
if (sp->length == str->length) {
// TODO but they are the same?
len = min(sp->length, str->length);
// OPT
for (i = 0; i < len; i++) {
if (sp->value[i] != str->value[i]) {
break;
}
}
if (i == sp->length && i == str->length) {
ip->reuse++;
revive(sp);
unlock(ip);
return sp;
}
}
}
}
ip->count++;
linkString(head, str);
if (step > EJS_MAX_COLLISIONS && ip->count > (ip->size/2)) {
/* Remake the entire hash - should not happen often */
// OPT - stop holding lock while rebuildingIntern
rebuildIntern(ip);
}
unlock(ip);
return str;
}
/*
Intern a wide C string and return an interned wide string
*/
PUBLIC EjsString *ejsInternWide(Ejs *ejs, wchar *value, ssize len)
{
EjsString *head, *sp;
EjsIntern *ip;
ssize i, end;
int index, step;
assert(0 <= len && len < MAXINT);
ip = ejs->service->intern;
step = 0;
lock(ip);
// TODO - accesses should be debug only
ip->accesses++;
index = whash(value, len) % ip->size;
if ((head = &ip->buckets[index]) != NULL) {
for (sp = head->next; sp != head; sp = sp->next, step++) {
// TODO - why not compare sp->value with value?
if (sp->length == len) {
end = min(sp->length, len);
for (i = 0; i < end && value[i]; i++) {
if (sp->value[i] != value[i]) {
break;
}
}
if (i == sp->length) {
ip->reuse++;
revive(sp);
unlock(ip);
return sp;
}
}
}
}
if ((sp = ejsAlloc(ejs, ESV(String), (len + 1) * sizeof(wchar))) != NULL) {
memcpy(sp->value, value, len * sizeof(wchar));
sp->value[len] = 0;
}
sp->length = len;
ip->count++;
linkString(head, sp);
if (step > EJS_MAX_COLLISIONS && ip->count > (ip->size/2)) {
/* Remake the entire hash - should not happen often */
// OPT - lock while rebuildingIntern
rebuildIntern(ip);
}
unlock(ip);
return sp;
}
PUBLIC EjsString *ejsInternAsc(Ejs *ejs, cchar *value, ssize len)
{
EjsString *head, *sp;
EjsIntern *ip;
ssize i, end;
int index, step;
assert(0 <= len && len < MAXINT);
step = 0;
ip = ejs->service->intern;
lock(ip);
ip->accesses++;
assert(ip->size > 0);
index = shash(value, len) % ip->size;
if ((head = &ip->buckets[index]) != NULL) {
for (sp = head->next; sp != head; sp = sp->next, step++) {
if (sp->length == len) {
end = min(len, sp->length);
for (i = 0; i < end && value[i]; i++) {
if (sp->value[i] != (uchar) value[i]) {
break;
}
}
if (i == sp->length) {
ip->reuse++;
revive(sp);
unlock(ip);
return sp;
}
}
}
}
if ((sp = ejsAlloc(ejs, ESV(String), (len + 1) * sizeof(wchar))) != NULL) {
#if ME_CHAR_LEN > 1
for (i = 0; i < len; i++) {
sp->value[i] = value[i];
}
sp->length = len;
#else
memcpy(sp->value, value, len * sizeof(wchar));
#endif
sp->value[len] = 0;
}
sp->length = len;
ip->count++;
linkString(head, sp);
if (step > EJS_MAX_COLLISIONS && ip->count > (ip->size/2)) {
/* Remake the entire hash - should not happen often */
// OPT - BAD holding lock while rebuildingIntern
rebuildIntern(ip);
}
unlock(ip);
return sp;
}
#if ME_CHAR_LEN == 1
PUBLIC EjsString *ejsInternMulti(Ejs *ejs, cchar *value, ssize len)
{
return ejsInternAsc(ejs, value, len);
}
#else /* ME_CHAR_LEN > 1 */
PUBLIC EjsString *ejsInternMulti(Ejs *ejs, cchar *value, ssize len)
{
EjsString *head, *sp, src;
ssize i, end;
int index;
assert(0 < len && len < MAXINT);
len = mtow(NULL, MAXSSIZE, value, len);
assert(len < MAXINT);
/*
Have to convert the multibyte string to unicode before comparision. Convert into an EjsString to it is ready
to intern if not found.
*/
if ((src = ejsAlloc(ejs, ESV(String), (len + 1) * sizeof(wchar))) != NULL) {
src->length = mtow(src->value, len + 1, value, len);
value = src->value;
}
lock(ip);
ip->accesses++;
index = whash(value, len) % ip->size;
if ((head = &ip->buckets[index]) != NULL) {
for (sp = head->next; sp != head; sp = sp->next) {
end = min(len, sp->length);
for (i = 0; i < end && value[i]; i++) {
if (sp->value[i] != sp->value[i]) {
break;
}
}
if (i == sp->length && value[i] == 0) {
ip->reuse++;
revive(sp);
unlock(ip);
return sp;
}
}
}
ip->count++;
linkString(head, src);
if (step > EJS_MAX_COLLISIONS && ip->count > (ip->size/2)) {
/* Remake the entire hash - should not happen often */
// OPT - BAD holding lock while rebuildingIntern
rebuildIntern(ip);
}
unlock(ip);
return sp;
}
#endif /* ME_CHAR_LEN > 1 */
static int getInternHashSize(int size)
{
int i;
for (i = 0; i < internHashSizes[i]; i++) {
if (size < internHashSizes[i]) {
return internHashSizes[i];
}
}
return internHashSizes[i - 1];
}
static int rebuildIntern(EjsIntern *ip)
{
EjsString *oldBuckets, *sp, *next, *head;
int i, newSize, oldSize;
assert(ip);
oldBuckets = ip->buckets;
newSize = getInternHashSize(ip->size + 1);
oldSize = 0;
if (oldBuckets) {
oldSize = ip->size;
if (oldSize >= newSize) {
return 0;
}
}
if ((ip->buckets = mprAllocZeroed((newSize * sizeof(EjsString)))) == NULL) {
return MPR_ERR_MEMORY;
}
ip->size = newSize;
for (i = 0; i < newSize; i++) {
sp = &ip->buckets[i];
sp->next = sp->prev = sp;
}
if (oldBuckets) {
for (i = 0; i < oldSize; i++) {
head = &oldBuckets[i];
for (sp = head->next; sp != head; sp = next) {
next = sp->next;
sp->next = sp->prev = sp;
ejsInternString(sp);
}
}
}
return 0;
}
/*
Must be called locked
*/
static void linkString(EjsString *head, EjsString *sp)
{
assert(sp != head);
assert(sp->next == NULL || sp->next == sp);
assert(sp->prev == NULL || sp->next == sp);
sp->next = head->next;
sp->prev = head;
head->next->prev = sp;
head->next = sp;
assert(sp != sp->next);
assert(sp != sp->prev);
}
/*
Unlink a string from the intern cache. This unlinks from the hash chains.
This routine is idempotent. ejsDestroyIntern takes advantage of this.
Must be called locked.
*/
static void unlinkString(EjsString *sp)
{
/*
Some strings are not interned (ejsCreateBareString). These have sp->next == NULL.
*/
if (sp->next) {
sp->prev->next = sp->next;
sp->next->prev = sp->prev;
sp->next = sp->prev = sp;
}
}
/*********************************** Factory **********************************/
PUBLIC EjsString *ejsCreateString(Ejs *ejs, wchar *value, ssize len)
{
if (value == 0) {
return ESV(empty);
}
if (len < 0) {
len = slen(value);
}
return ejsInternWide(ejs, value, len);
}
PUBLIC EjsString *ejsCreateStringFromAsc(Ejs *ejs, cchar *value)
{
if (value == NULL) {
value = "";
}
return ejsInternAsc(ejs, value, slen(value));
}
PUBLIC EjsString *ejsCreateStringFromMulti(Ejs *ejs, cchar *value, ssize len)
{
assert(0 <= len && len < MAXINT);
if (value == 0 || len < 0) {
return ESV(empty);
}
return ejsInternMulti(ejs, value, len);
}
PUBLIC EjsString *ejsCreateStringFromBytes(Ejs *ejs, cchar *value, ssize len)
{
assert(0 <= len && len < MAXINT);
return ejsInternAsc(ejs, value, len);
}
/*
Create an empty string object and do not intern. Caller's should call ejsInternString when the string value is defined.
*/
PUBLIC EjsString *ejsCreateBareString(Ejs *ejs, ssize len)
{
EjsString *sp;
assert(0 <= len && len < MAXINT);
if ((sp = ejsAlloc(ejs, ESV(String), (len + 1) * sizeof(wchar))) != NULL) {
sp->length = len;
sp->value[0] = 0;
sp->value[len] = 0;
}
return sp;
}
#if UNUSED && KEEP
PUBLIC EjsString *ejsCreateNonInternedString(Ejs *ejs, wchar *value, ssize len)
{
EjsString *sp;
assert(0 <= len && len < MAXINT);
if ((sp = ejsAlloc(ejs, ESV(String), (len + 1) * sizeof(wchar))) != NULL) {
memcpy(sp->value, value, (len + 1) * sizeof(wchar));
sp->length = len;
sp->value[len] = 0;
}
return sp;
}
#endif
PUBLIC void ejsManageString(EjsString *sp, int flags)
{
EjsIntern *ip;
MprMem *mp;
if (flags & MPR_MANAGE_MARK) {
mprMark(TYPE(sp));
} else if (flags & MPR_MANAGE_FREE) {
if (sp->next && MPR->ejsService) {
/*
Other threads race with this if doing parallel GC (the default).
The revive() routine may have marked the string, so test here if
it has been revived and only free if not.
OPT - better to be lock free and try lock. If failed, GC will get next time
*/
mp = MPR_GET_MEM(sp);
if (mp->mark != MPR->heap->mark) {
ip = ((EjsService*) MPR->ejsService)->intern;
lock(ip);
/* Must retest here because revive may modify the mark to revive */
if (mp->mark != MPR->heap->mark) {
ip->count--;
assert(ip->count >= 0);
unlinkString(sp);
}
unlock(ip);
}
}
}
}
PUBLIC EjsIntern *ejsCreateIntern(EjsService *sp)
{
EjsIntern *intern;
intern = mprAllocObj(EjsIntern, manageIntern);
intern->mutex = mprCreateLock();
rebuildIntern(intern);
return intern;
}
PUBLIC void ejsDestroyIntern(EjsIntern *ip)
{
ip->size = 0;
ip->buckets = 0;
}
static void manageIntern(EjsIntern *intern, int flags)
{
if (flags & MPR_MANAGE_MARK) {
/* Do not mark strings - prevents GC */
mprMark(intern->buckets);
mprMark(intern->mutex);
} else if (flags & MPR_MANAGE_FREE) {
ejsDestroyIntern(intern);
}
}
PUBLIC void ejsInitStringType(Ejs *ejs, EjsType *type)
{
type->helpers.cast = (EjsCastHelper) castString;
type->helpers.clone = (EjsCloneHelper) cloneString;
type->helpers.getProperty = (EjsGetPropertyHelper) getStringProperty;
type->helpers.invokeOperator = (EjsInvokeOperatorHelper) invokeStringOperator;
type->helpers.lookupProperty = (EjsLookupPropertyHelper) lookupStringProperty;
type->numericIndicies = 1;
}
PUBLIC void ejsConfigureStringType(Ejs *ejs)
{
EjsType *type;
EjsPot *prototype;
if ((type = ejsFinalizeCoreType(ejs, N("ejs", "String"))) == 0) {
return;
}
ejsBindMethod(ejs, type, ES_String_fromCharCode, fromCharCode);
ejsBindConstructor(ejs, type, stringConstructor);
prototype = type->prototype;
ejsBindMethod(ejs, prototype, ES_String_caseCompare, caseCompare);
ejsBindMethod(ejs, prototype, ES_String_caselessCompare, caselessCompare);
ejsBindMethod(ejs, prototype, ES_String_charAt, charAt);
ejsBindMethod(ejs, prototype, ES_String_charCodeAt, charCodeAt);
ejsBindMethod(ejs, prototype, ES_String_concat, concatString);
ejsBindMethod(ejs, prototype, ES_String_contains, containsString);
ejsBindMethod(ejs, prototype, ES_String_endsWith, endsWith);
ejsBindMethod(ejs, prototype, ES_String_expand, expandString);
ejsBindMethod(ejs, prototype, ES_String_format, formatString);
ejsBindMethod(ejs, prototype, ES_String_iterator_get, getStringIterator);
ejsBindMethod(ejs, prototype, ES_String_iterator_getValues, getStringValues);
ejsBindMethod(ejs, prototype, ES_String_indexOf, indexOf);
ejsBindMethod(ejs, prototype, ES_String_isDigit, isDigit);
ejsBindMethod(ejs, prototype, ES_String_isAlpha, isAlpha);
ejsBindMethod(ejs, prototype, ES_String_isAlphaNum, isAlphaNum);
ejsBindMethod(ejs, prototype, ES_String_isLower, isLower);
ejsBindMethod(ejs, prototype, ES_String_isSpace, isSpace);
ejsBindMethod(ejs, prototype, ES_String_isUpper, isUpper);
ejsBindMethod(ejs, prototype, ES_String_lastIndexOf, lastIndexOf);
ejsBindMethod(ejs, prototype, ES_String_length, stringLength);
ejsBindMethod(ejs, prototype, ES_String_match, match);
ejsBindMethod(ejs, prototype, ES_String_remove, removeCharsFromString);
ejsBindMethod(ejs, prototype, ES_String_slice, sliceString);
ejsBindMethod(ejs, prototype, ES_String_split, split);
ejsBindMethod(ejs, prototype, ES_String_printable, printable);
ejsBindMethod(ejs, prototype, ES_String_quote, quote);
ejsBindMethod(ejs, prototype, ES_String_replace, replace);
ejsBindMethod(ejs, prototype, ES_String_reverse, reverseString);
ejsBindMethod(ejs, prototype, ES_String_search, searchString);
ejsBindMethod(ejs, prototype, ES_String_startsWith, startsWith);
ejsBindMethod(ejs, prototype, ES_String_substring, substring);
ejsBindMethod(ejs, prototype, ES_String_toCamel, toCamel);
ejsBindMethod(ejs, prototype, ES_String_toJSON, ejsToLiteralString);
ejsBindMethod(ejs, prototype, ES_String_toLowerCase, toLowerCase);
ejsBindMethod(ejs, prototype, ES_String_toPascal, toPascal);
ejsBindMethod(ejs, prototype, ES_String_toString, stringToString);
ejsBindMethod(ejs, prototype, ES_String_toUpperCase, toUpperCase);
ejsBindMethod(ejs, prototype, ES_String_tokenize, tokenize);
ejsBindMethod(ejs, prototype, ES_String_trim, trimString);
ejsBindMethod(ejs, prototype, ES_String_trimStart, trimStartString);
ejsBindMethod(ejs, prototype, ES_String_trimEnd, trimEndString);
#if FUTURE
ejsBindMethod(ejs, prototype, ES_String_LBRACKET, operLBRACKET);
ejsBindMethod(ejs, prototype, ES_String_PLUS, operPLUS);
ejsBindMethod(ejs, prototype, ES_String_MINUS, operMINUS);
ejsBindMethod(ejs, prototype, ES_String_LT, operLT);
ejsBindMethod(ejs, prototype, ES_String_GT, operGT);
ejsBindMethod(ejs, prototype, ES_String_EQ, operEQ);
ejsBindMethod(ejs, prototype, ES_String_MOD, operMOD);
ejsBindMethod(ejs, prototype, ES_String_MUL, operMUL);
#endif
}
/*
@copy default
Copyright (c) Embedthis Software. All Rights Reserved.
This software is distributed under commercial and open source licenses.
You may use the Embedthis Open Source license or you may acquire a
commercial license from Embedthis Software. You agree to be fully bound
by the terms of either license. Consult the LICENSE.md distributed with
this software for full details and other copyrights.
Local variables:
tab-width: 4
c-basic-offset: 4
End:
vim: sw=4 ts=4 expandtab
@end
*/
|
chimple/fiji
|
app/components/games/RectangularGrid.js
|
import React, { PureComponent, Component } from 'react';
import { View, StyleSheet } from 'react-native';
import PropTypes from 'prop-types'
export default class RectangularGrid extends PureComponent {
_renderChild = (Child, style) => (
<Child />
)
render() {
console.log('RectangularGrid.render')
const cellSize = Math.min(
Math.floor(this.props.style.width / (this.props.numCols)),
Math.floor(this.props.style.height / (this.props.numRows))
)
const padding = Math.floor(cellSize * .05)
const borderRadius = padding * 2
const tileSize = cellSize - padding * 2
const topOffset = padding + Math.floor((this.props.style.height - cellSize * this.props.numRows) / 2)
const leftOffset = padding + Math.floor((this.props.style.width - cellSize * this.props.numCols) / 2)
let result = []
for (let row = 0; row < this.props.numRows; row++) {
for (let col = 0; col < this.props.numCols; col++) {
const id = row * this.props.numCols + col
result.push(this.props.render(id,
{
top: row * cellSize + topOffset,
left: col * cellSize + leftOffset,
position: 'absolute',
width: tileSize,
height: tileSize
}
))
}
}
console.log(result)
return (
<View style={this.props.style}>
{result}
</View>
)
}
}
RectangularGrid.propTypes = {
onPress: PropTypes.func,
onRender: PropTypes.func,
statuses: PropTypes.array,
onStatusChange: PropTypes.func,
numRows: PropTypes.number,
numCols: PropTypes.number,
data: PropTypes.array,
delegateTouch: PropTypes.func,
reverse: PropTypes.bool
}
|
geo-bl-ch/pyramid_oereb
|
pyramid_oereb/standard/hook_methods.py
|
# -*- coding: utf-8 -*-
import datetime
import logging
from mako import exceptions
from mako.template import Template
from pyramid.httpexceptions import HTTPNotFound
from pyramid.path import AssetResolver, DottedNameResolver
from pyramid.response import Response
from sqlalchemy import cast, Text
from pyramid_oereb import Config, database_adapter, route_prefix
from pyramid_oereb.lib import b64
from pyramid_oereb.lib.records.image import ImageRecord
from pyramid_oereb.lib.records.office import OfficeRecord
log = logging.getLogger(__name__)
def get_logo(request):
"""
Returns the requested logo.
Args:
request (pyramid.request.Request): The request containing the logo key matchdict parameter.
Returns:
pyramid.response.Response: The generated response object.
"""
logo_key = request.matchdict.get('logo')
logo_language = request.matchdict.get('language')
if logo_key in Config.get('logo').keys():
logo = Config.get_logo_config(language=logo_language).get(logo_key)
response = request.response
response.status_int = 200
response.body = logo.content
response.content_type = logo.mimetype
return response
raise HTTPNotFound('This logo does not exist.')
def get_municipality(request):
"""
Returns the requested municipality logo from database.
Args:
request (pyramid.request.Request): The request containing the fosnr as matchdict parameter.
Returns:
pyramid.response.Response: The generated response object.
"""
fosnr = request.matchdict.get('fosnr')
source_params = Config.get_municipality_config().get('source').get('params')
session = database_adapter.get_session(source_params.get('db_connection'))
try:
model = DottedNameResolver().resolve(source_params.get('model'))
municipality = session.query(model).filter_by(fosnr=fosnr).first()
if municipality:
logo = getattr(municipality, 'logo', None)
if logo:
response = request.response
response.status_int = 200
response.body = b64.decode(logo)
response.content_type = ImageRecord.get_mimetype(bytearray(response.body))
return response
raise HTTPNotFound()
finally:
session.close()
def get_symbol(request):
"""
Returns the symbol for the requested theme and type code from database.
Args:
request (pyramid.request.Request): The request containing the codes as matchdict parameters.
Returns:
pyramid.response.Response: The generated response object.
"""
theme_code = request.matchdict.get('theme_code')
view_service_id = request.matchdict.get('view_service_id')
type_code = request.matchdict.get('type_code')
plr = None
for p in Config.get('plrs'):
if str(p.get('code')).lower() == str(theme_code).lower():
plr = p
break
if plr is None:
raise HTTPNotFound('No theme with code {}.'.format(theme_code))
source_params = plr.get('source').get('params')
session = database_adapter.get_session(source_params.get('db_connection'))
try:
model = DottedNameResolver().resolve('{module_}.{class_}'.format(
module_=source_params.get('models'),
class_='LegendEntry'
))
legend_entry = session.query(model).filter(
cast(model.type_code, Text) == cast(type_code, Text)
).filter(
model.view_service_id == view_service_id
).first()
if legend_entry:
symbol = getattr(legend_entry, 'symbol', None)
if symbol:
response = request.response
response.status_int = 200
response.body = b64.decode(symbol)
response.content_type = ImageRecord.get_mimetype(bytearray(response.body))
return response
raise HTTPNotFound()
finally:
session.close()
def get_symbol_ref(request, record):
"""
Returns the link to the symbol of the specified public law restriction.
Args:
request (pyramid.request.Request): The current request instance.
record (pyramid_oereb.lib.records.plr.PlrRecord or
pyramid_oereb.lib.records.view_service.LegendEntryRecord): The record of the public law
restriction to get the symbol reference for.
Returns:
uri: The link to the symbol for the specified public law restriction.
"""
return request.route_url(
'{0}/image/symbol'.format(route_prefix),
theme_code=record.theme.code,
view_service_id=record.view_service_id,
type_code=record.type_code,
extension=record.symbol.extension
)
def get_surveying_data_provider(real_estate):
"""
Args:
real_estate (pyramid_oereb.lib.records.real_estate.RealEstateRecord): The real estate for which the
provider of the surveying data should be delivered.
Returns:
provider (pyramid_oereb.lib.records.office.OfficeRecord): The provider who produced the used
surveying data.
"""
provider = OfficeRecord({u'de': u'This is only a dummy'})
return provider
def get_surveying_data_update_date(real_estate):
"""
Gets the date of the latest update of the used survey data data for the
situation map. The method you find here is only matching the standard configuration. But you can provide
your own one if your configuration is different. The only thing you need to take into account is that the
input of this method is always and only a real estate record. And the output of this method must be a
datetime.date object.
Args:
real_estate (pyramid_oereb.lib.records.real_estate.RealEstateRecord): The real
estate for which the last update date of the base data should be indicated
Returns:
update_date (datetime.datetime): The date of the last update of the cadastral base data
"""
update_date = datetime.datetime.now()
return update_date
def produce_sld_content(request):
"""
This is the standard hook method to provide the sld content. Of course you can set it to another one. For
instance to use another template. Or to use other parameters to provide the correctly constructed SLD.
.. note:: What to know about this Method: REQUEST-Method: GET, parameters only as url parameters
When you are replacing this method take care that it has to accept a pyramid request as input and must
deliver a valid SLD wrapped in a pyramid response instance as output. It is in your responsibility.
Args:
request (pyramid.request.Request): The request from the pyramid application.
Returns:
pyramid.response.Response: The
"""
response = request.response
template = Template(
filename=AssetResolver('pyramid_oereb').resolve('standard/templates/sld.xml').abspath(),
input_encoding='utf-8',
output_encoding='utf-8'
)
layer = Config.get_real_estate_config().get('visualisation').get('layer')
template_params = {}
template_params.update(Config.get_real_estate_config().get('visualisation').get('style'))
template_params.update({'layer_name': layer.get('name')})
template_params.update({'identifier': request.params.get('egrid')})
try:
if isinstance(response, Response) and response.content_type == response.default_content_type:
response.content_type = 'application/xml'
response.body = template.render(**template_params)
return response
except Exception:
response.content_type = 'text/html'
response.body = exceptions.html_error_template().render()
return response
def plr_sort_within_themes(extract):
"""
This is the standard hook method to sort a plr list (while respecting the theme order).
This standard hook does no sorting, you can set your configuration to a different method if you need a
specific sorting.
Args:
extract (pyramid_oereb.lib.records.extract.ExtractRecord): The unsorted extract
Returns:
pyramid_oereb.lib.records.extract.ExtractRecord: Returns the updated extract
"""
return extract
|
jhutchings1/zitadel
|
internal/project/repository/eventsourcing/model/project_test.go
|
<reponame>jhutchings1/zitadel
package model
import (
"encoding/json"
es_models "github.com/caos/zitadel/internal/eventstore/models"
"github.com/caos/zitadel/internal/project/model"
"testing"
)
func TestProjectChanges(t *testing.T) {
type args struct {
existing *Project
new *Project
}
type res struct {
changesLen int
}
tests := []struct {
name string
args args
res res
}{
{
name: "project name changes",
args: args{
existing: &Project{Name: "Name"},
new: &Project{Name: "NameChanged"},
},
res: res{
changesLen: 1,
},
},
{
name: "no changes",
args: args{
existing: &Project{Name: "Name"},
new: &Project{Name: "Name"},
},
res: res{
changesLen: 0,
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
changes := tt.args.existing.Changes(tt.args.new)
if len(changes) != tt.res.changesLen {
t.Errorf("got wrong changes len: expected: %v, actual: %v ", tt.res.changesLen, len(changes))
}
})
}
}
func TestProjectFromEvents(t *testing.T) {
type args struct {
event []*es_models.Event
project *Project
}
tests := []struct {
name string
args args
result *Project
}{
{
name: "project from events, ok",
args: args{
event: []*es_models.Event{
&es_models.Event{AggregateID: "AggregateID", Sequence: 1, Type: ProjectAdded},
},
project: &Project{Name: "ProjectName"},
},
result: &Project{ObjectRoot: es_models.ObjectRoot{AggregateID: "AggregateID"}, State: int32(model.ProjectStateActive), Name: "ProjectName"},
},
{
name: "project from events, nil project",
args: args{
event: []*es_models.Event{
&es_models.Event{AggregateID: "AggregateID", Sequence: 1, Type: ProjectAdded},
},
project: nil,
},
result: &Project{ObjectRoot: es_models.ObjectRoot{AggregateID: "AggregateID"}, State: int32(model.ProjectStateActive)},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if tt.args.project != nil {
data, _ := json.Marshal(tt.args.project)
tt.args.event[0].Data = data
}
result, _ := ProjectFromEvents(tt.args.project, tt.args.event...)
if result.Name != tt.result.Name {
t.Errorf("got wrong result name: expected: %v, actual: %v ", tt.result.Name, result.Name)
}
})
}
}
func TestAppendEvent(t *testing.T) {
type args struct {
event *es_models.Event
project *Project
}
tests := []struct {
name string
args args
result *Project
}{
{
name: "append added event",
args: args{
event: &es_models.Event{AggregateID: "AggregateID", Sequence: 1, Type: ProjectAdded},
project: &Project{Name: "ProjectName"},
},
result: &Project{ObjectRoot: es_models.ObjectRoot{AggregateID: "AggregateID"}, State: int32(model.ProjectStateActive), Name: "ProjectName"},
},
{
name: "append change event",
args: args{
event: &es_models.Event{AggregateID: "AggregateID", Sequence: 1, Type: ProjectChanged},
project: &Project{Name: "ProjectName"},
},
result: &Project{ObjectRoot: es_models.ObjectRoot{AggregateID: "AggregateID"}, State: int32(model.ProjectStateActive), Name: "ProjectName"},
},
{
name: "append deactivate event",
args: args{
event: &es_models.Event{AggregateID: "AggregateID", Sequence: 1, Type: ProjectDeactivated},
},
result: &Project{ObjectRoot: es_models.ObjectRoot{AggregateID: "AggregateID"}, State: int32(model.ProjectStateInactive)},
},
{
name: "append reactivate event",
args: args{
event: &es_models.Event{AggregateID: "AggregateID", Sequence: 1, Type: ProjectReactivated},
},
result: &Project{ObjectRoot: es_models.ObjectRoot{AggregateID: "AggregateID"}, State: int32(model.ProjectStateActive)},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if tt.args.project != nil {
data, _ := json.Marshal(tt.args.project)
tt.args.event.Data = data
}
result := new(Project)
result.AppendEvent(tt.args.event)
if result.State != tt.result.State {
t.Errorf("got wrong result state: expected: %v, actual: %v ", tt.result.State, result.State)
}
if result.Name != tt.result.Name {
t.Errorf("got wrong result name: expected: %v, actual: %v ", tt.result.Name, result.Name)
}
if result.ObjectRoot.AggregateID != tt.result.ObjectRoot.AggregateID {
t.Errorf("got wrong result id: expected: %v, actual: %v ", tt.result.ObjectRoot.AggregateID, result.ObjectRoot.AggregateID)
}
})
}
}
func TestAppendDeactivatedEvent(t *testing.T) {
type args struct {
project *Project
}
tests := []struct {
name string
args args
result *Project
}{
{
name: "append reactivate event",
args: args{
project: &Project{},
},
result: &Project{State: int32(model.ProjectStateInactive)},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
tt.args.project.appendDeactivatedEvent()
if tt.args.project.State != tt.result.State {
t.Errorf("got wrong result: expected: %v, actual: %v ", tt.result, tt.args.project)
}
})
}
}
func TestAppendReactivatedEvent(t *testing.T) {
type args struct {
project *Project
}
tests := []struct {
name string
args args
result *Project
}{
{
name: "append reactivate event",
args: args{
project: &Project{},
},
result: &Project{State: int32(model.ProjectStateActive)},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
tt.args.project.appendReactivatedEvent()
if tt.args.project.State != tt.result.State {
t.Errorf("got wrong result: expected: %v, actual: %v ", tt.result, tt.args.project)
}
})
}
}
|
yangziwen/quick-dao
|
quick-dao-core/src/main/java/io/github/yangziwen/quickdao/core/FunctionCriterion.java
|
package io.github.yangziwen.quickdao.core;
import io.github.yangziwen.quickdao.core.util.InvokedMethodExtractor;
import io.github.yangziwen.quickdao.core.util.StringWrapper;
import lombok.Getter;
@Getter
public class FunctionCriterion<E> extends TypedCriterion<E, Object> {
private final InvokedMethodExtractor<E> extractor;
private final SqlFunctionExpression<E> expression;
FunctionCriterion(
SqlFunctionExpression<E> expression,
InvokedMethodExtractor<E> extractor,
TypedCriteria<E> criteria) {
super(expression.getFunc().getName() + "_" + expression.hashCode(), criteria);
this.expression = expression;
this.extractor = extractor;
}
@Override
protected FunctionCriterion<E> autoEnd(boolean autoEnd) {
super.autoEnd(autoEnd);
return this;
}
@Override
public <T> String buildCondition(
EntityMeta<T> entityMeta,
StringWrapper columnWrapper,
StringWrapper placeholderWrapper) {
String expr = getExpression().render(entityMeta, extractor, columnWrapper);
String placeholder = placeholderWrapper.wrap(generatePlaceholderKey());
return getOperator().buildCondition(expr, placeholder);
}
}
|
acidicMercury8/xray-1.0
|
src/xr_3da/xrGame/EffectorShotX.h
|
<gh_stars>1-10
#pragma once
#include "EffectorShot.h"
class CCameraShotEffectorX : public CCameraShotEffector
{
typedef CCameraShotEffector inherited;
public:
CCameraShotEffectorX(float max_angle, float relax_time, float max_angle_horz, float step_angle_horz, float angle_frac = 0.7f);
virtual ~CCameraShotEffectorX();
virtual BOOL Process (Fvector &delta_p, Fvector &delta_d, Fvector &delta_n, float& fFov, float& fFar, float& fAspect);
virtual void GetDeltaAngle (Fvector& delta_angle);
virtual void Shot (float angle);
virtual void Clear ();
protected:
virtual void UpdateActorCamera (float dPitch, float dYaw);
};
|
hsouidi/oanda-robot
|
robot-engine/src/main/java/com/trading/forex/entity/Role.java
|
<filename>robot-engine/src/main/java/com/trading/forex/entity/Role.java
package com.trading.forex.entity;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
/**
* Created by hsouidi on 21/01/18.
*/
@Entity
@Table(name="app_role")
@Data
@NoArgsConstructor
@Builder
@AllArgsConstructor
public class Role {
private static final long serialVersionUID = 1L;
@Id
@Column(name="role_name")
private String roleName;
@Column(name="description")
private String description;
}
|
dworthen/arquero
|
test/format/json-test.js
|
<gh_stars>0
import tape from 'tape';
import tableEqual from '../table-equal';
import ColumnTable from '../../src/table/column-table';
import fromJSON from '../../src/format/from-json';
import toJSON from '../../src/format/to-json';
function data() {
return {
str: ['a', 'b', 'c'],
int: [1, 2, 3],
num: [12.3, 45.6, 78.9],
bool: [true, null, false],
date: [new Date('2010-01-01'), new Date('2015-04-05'), new Date('2020-02-29')]
};
}
const text = '{'
+ '"str":["a","b","c"],'
+ '"int":[1,2,3],'
+ '"num":[12.3,45.6,78.9],'
+ '"bool":[true,null,false],'
+ '"date":["2010-01-01","2015-04-05","2020-02-29"]'
+ '}';
tape('toJSON formats JSON text', t => {
const dt = new ColumnTable(data());
t.equal(toJSON(dt), text, 'json text');
t.equal(
toJSON(dt, { limit: 2, columns: ['str', 'int'] }),
'{"str":["a","b"],"int":[1,2]}',
'json text with limit'
);
t.end();
});
tape('toJSON formats JSON text with format option', t => {
const dt = new ColumnTable(data());
t.equal(
toJSON(dt, { limit: 2, columns: ['str'], format: { str: d => d + '!' } }),
'{"str":["a!","b!"]}',
'json text with custom format'
);
t.end();
});
tape('fromJSON parses JSON text', t => {
const table = fromJSON(text);
t.equal(table.numRows(), 3, 'num rows');
t.equal(table.numCols(), 5, 'num cols');
tableEqual(t, table, data(), 'json parsed data');
t.end();
});
tape('fromJSON parses JSON text with parse option', t => {
const table = fromJSON(text, { parse: { str: d => d + d } });
const d = { ...data(), str: ['aa', 'bb', 'cc'] };
tableEqual(t, table, d, 'json parsed data with custom parse');
t.end();
});
|
dtgit/lftwb
|
app/models/shared_upload.rb
|
<filename>app/models/shared_upload.rb
# == Schema Information
# Schema version: 20090213002439
#
# Table name: shared_uploads
#
# id :integer(4) not null, primary key
# shared_uploadable_id :integer(4)
# shared_uploadable_type :string(255)
# upload_id :integer(4)
# shared_by_id :integer(4)
# created_at :datetime
# updated_at :datetime
#
class SharedUpload < ActiveRecord::Base
include SecureMethods
has_many :comments, :as => :commentable, :dependent => :destroy, :order => 'created_at ASC'
belongs_to :upload
belongs_to :shared_uploadable, :polymorphic => true
belongs_to :shared_by, :class_name => 'User', :foreign_key => 'shared_by_id'
validates_presence_of :shared_uploadable_id, :upload_id, :shared_by_id
def after_create
feed_item = FeedItem.create(:item => self, :creator_id => self.shared_by_id)
if shared_uploadable.is_a?(Group) && shared_uploadable.respond_to?(:feed_to)
(shared_uploadable.feed_to).each{ |u| u.feed_items << feed_item }
elsif shared_uploadable.is_a?(User)
([shared_uploadable, self.shared_by]).each{ |u| u.feed_items << feed_item }
end
end
def can_edit?(user)
shared_uploadable.id == user.id || check_sharer(user)
end
end
|
mediciland/bpanel
|
webapp/store/constants/wallets.js
|
<reponame>mediciland/bpanel
export const ADD_ACCOUNTS = 'ADD_ACCOUNTS';
export const ADD_WALLET = 'ADD_WALLET';
export const REMOVE_WALLET = 'REMOVE_WALLET';
|
seveirbian/unis
|
unisctl/cmd/images.go
|
package cmd
import (
"fmt"
"io/ioutil"
"net/http"
"net/url"
"strings"
"github.com/sirupsen/logrus"
"github.com/spf13/cobra"
)
var imagesUsage = `Usage: unisctl images [OPTIONS]
Options:
-p, --public Show public images (default private images)
-h, --help help for images
`
var allImagesFlag bool
var imagesCmd = &cobra.Command{
Use: "images",
Short: "List images in remote registry",
Long: "List images in remote registry",
Args: cobra.NoArgs,
Run: func(cmd *cobra.Command, args []string) {
// detect whether user has signed in
if ConfigContent.Username == "" || ConfigContent.Password == "" {
fmt.Println("Please signin first!")
logrus.Fatal("Please signin first!")
}
// send different request based on allImagesFlag
var resp *http.Response
var err error
if allImagesFlag {
resp, err = http.PostForm(ConfigContent.Apiserver+"/images/show/public/images", url.Values{"username": {ConfigContent.Username}, "password": {ConfigContent.Password}})
} else {
resp, err = http.PostForm(ConfigContent.Apiserver+"/images/show/"+ConfigContent.Username+"/images", url.Values{"password": {ConfigContent.Password}})
}
// print response
if err != nil {
logrus.Fatal(err)
} else {
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
logrus.Fatal(err)
} else {
var label = ""
label += "REPOSITORY "
label += "TAG "
label += "IMAGE ID "
label += "CREATED "
label += "SIZE "
label += "TYPE "
label += "OWNER "
label += "\n"
imageLine := strings.Split(string(body), "\n")
blankLenth := 10
for _, image := range imageLine {
if image == "" {
break
}
messages := strings.Split(image, " ")
label += messages[0]
label += EmptyString(strings.Count("Repository", "") +
blankLenth - strings.Count(messages[0], ""))
label += messages[1]
label += EmptyString(strings.Count("Tag", "") +
blankLenth - strings.Count(messages[1], ""))
label += messages[2]
label += EmptyString(strings.Count("Image ID", "") +
blankLenth - strings.Count(messages[2], ""))
label += messages[3]
label += EmptyString(strings.Count("Created", "") +
blankLenth - strings.Count(messages[3], ""))
label += messages[4]
label += EmptyString(strings.Count("Size", "") +
blankLenth - strings.Count(messages[4], ""))
label += messages[5]
label += EmptyString(strings.Count("Type", "") +
blankLenth - strings.Count(messages[5], ""))
label += messages[6]
label += EmptyString(strings.Count("Owner", "") +
blankLenth - strings.Count(messages[6], ""))
label += "\n"
}
fmt.Println(label)
}
}
},
}
func init() {
rootCmd.AddCommand(imagesCmd)
imagesCmd.SetUsageTemplate(imagesUsage)
imagesCmd.Flags().BoolVarP(&allImagesFlag, "public", "p", false, "Show public images")
}
|
smoe/nydax
|
frontend/src/components/VerifyAccountModal/UploadVerificationFiles/constants.js
|
<filename>frontend/src/components/VerifyAccountModal/UploadVerificationFiles/constants.js<gh_stars>1-10
const text = {
TITLE: 'Upload Images',
DESCRIPTION: documentName =>
`Upload pictures of your ${documentName} ( JPEG or PNG )`,
SAVE: 'Save',
GO_BACK: 'Go Back',
};
export default text;
|
SecretAgent-YT/JDA
|
src/main/java/net/dv8tion/jda/api/entities/NewsChannel.java
|
<filename>src/main/java/net/dv8tion/jda/api/entities/NewsChannel.java<gh_stars>1-10
package net.dv8tion.jda.api.entities;
import net.dv8tion.jda.api.Permission;
import net.dv8tion.jda.api.exceptions.InsufficientPermissionException;
import net.dv8tion.jda.api.exceptions.MissingAccessException;
import net.dv8tion.jda.api.managers.channel.concrete.NewsChannelManager;
import net.dv8tion.jda.api.requests.RestAction;
import net.dv8tion.jda.api.requests.restaction.ChannelAction;
import net.dv8tion.jda.internal.requests.RestActionImpl;
import net.dv8tion.jda.internal.requests.Route;
import net.dv8tion.jda.internal.utils.Checks;
import javax.annotation.CheckReturnValue;
import javax.annotation.Nonnull;
/**
* Represents {@link BaseGuildMessageChannel} that are News Channels.
*
* The Discord client may refer to these as Announcement Channels.
*
* Members can subscribe channels in their own guilds to receive messages crossposted from this channel.
* This is referred to as following this channel.
*
* Messages sent in this channel can be crossposted, at which point they will be sent (via webhook) to all subscribed channels.
*
* @see Message#getFlags()
* @see net.dv8tion.jda.api.entities.Message.MessageFlag#CROSSPOSTED
*/
public interface NewsChannel extends BaseGuildMessageChannel
{
/**
* Subscribes to the crossposted messages in this channel.
* <br>This will create a {@link Webhook} of type {@link WebhookType#FOLLOWER FOLLOWER} in the target channel.
*
* <p>Possible {@link net.dv8tion.jda.api.requests.ErrorResponse ErrorResponses} include:
* <ul>
* <li>{@link net.dv8tion.jda.api.requests.ErrorResponse#UNKNOWN_CHANNEL UNKNOWN_CHANNEL}
* <br>If the target channel doesn't exist or is not visible to the currently logged in account</li>
*
* <li>{@link net.dv8tion.jda.api.requests.ErrorResponse#MISSING_PERMISSIONS MISSING_PERMISSIONS}
* <br>If the currently logged in account does not have {@link Permission#MANAGE_WEBHOOKS} in the <b>target channel</b></li>
*
* <li>{@link net.dv8tion.jda.api.requests.ErrorResponse#MAX_WEBHOOKS MAX_WEBHOOKS}
* <br>If the target channel already has reached the maximum capacity for webhooks</li>
* </ul>
*
* @param targetChannelId
* The target channel id
*
* @throws IllegalArgumentException
* If null is provided
*
* @return {@link RestAction}
*
* @since 4.2.1
*/
@Nonnull
@CheckReturnValue
RestAction<Webhook.WebhookReference> follow(@Nonnull String targetChannelId);
/**
* Subscribes to the crossposted messages in this channel.
* <br>This will create a {@link Webhook} of type {@link WebhookType#FOLLOWER FOLLOWER} in the target channel.
*
* <p>Possible {@link net.dv8tion.jda.api.requests.ErrorResponse ErrorResponses} include:
* <ul>
* <li>{@link net.dv8tion.jda.api.requests.ErrorResponse#UNKNOWN_CHANNEL UNKNOWN_CHANNEL}
* <br>If the target channel doesn't exist or not visible to the currently logged in account</li>
*
* <li>{@link net.dv8tion.jda.api.requests.ErrorResponse#MISSING_PERMISSIONS MISSING_PERMISSIONS}
* <br>If the currently logged in account does not have {@link Permission#MANAGE_WEBHOOKS} in the <b>target channel</b></li>
*
* <li>{@link net.dv8tion.jda.api.requests.ErrorResponse#MAX_WEBHOOKS MAX_WEBHOOKS}
* <br>If the target channel already has reached the maximum capacity for webhooks</li>
* </ul>
*
* @param targetChannelId
* The target channel id
*
* @return {@link RestAction}
*
* @since 4.2.1
*/
@Nonnull
@CheckReturnValue
default RestAction<Webhook.WebhookReference> follow(long targetChannelId)
{
return follow(Long.toUnsignedString(targetChannelId));
}
/**
* Subscribes to the crossposted messages in this channel.
* <br>This will create a {@link Webhook} of type {@link WebhookType#FOLLOWER FOLLOWER} in the target channel.
*
* <p>Possible {@link net.dv8tion.jda.api.requests.ErrorResponse ErrorResponses} include:
* <ul>
* <li>{@link net.dv8tion.jda.api.requests.ErrorResponse#UNKNOWN_CHANNEL UNKNOWN_CHANNEL}
* <br>If the target channel doesn't exist or not visible to the currently logged in account</li>
*
* <li>{@link net.dv8tion.jda.api.requests.ErrorResponse#MISSING_PERMISSIONS MISSING_PERMISSIONS}
* <br>If the currently logged in account does not have {@link Permission#MANAGE_WEBHOOKS} in the <b>target channel</b></li>
*
* <li>{@link net.dv8tion.jda.api.requests.ErrorResponse#MAX_WEBHOOKS MAX_WEBHOOKS}
* <br>If the target channel already has reached the maximum capacity for webhooks</li>
* </ul>
*
* @param targetChannel
* The target channel
*
* @throws InsufficientPermissionException
* If the currently logged in account does not have {@link Permission#MANAGE_WEBHOOKS} in the <b>target channel</b>.
* @throws IllegalArgumentException
* If null is provided
*
* @return {@link RestAction}
*
* @since 4.2.1
*/
@Nonnull
@CheckReturnValue
default RestAction<Webhook.WebhookReference> follow(@Nonnull TextChannel targetChannel)
{
Checks.notNull(targetChannel, "Target Channel");
Member selfMember = targetChannel.getGuild().getSelfMember();
if (!selfMember.hasAccess(targetChannel))
throw new MissingAccessException(targetChannel, Permission.VIEW_CHANNEL);
if (!selfMember.hasPermission(targetChannel, Permission.MANAGE_WEBHOOKS))
throw new InsufficientPermissionException(targetChannel, Permission.MANAGE_WEBHOOKS);
return follow(targetChannel.getId());
}
/**
* Attempts to crosspost the provided message.
*
* <p>The following {@link net.dv8tion.jda.api.requests.ErrorResponse ErrorResponses} are possible:
* <ul>
* <li>{@link net.dv8tion.jda.api.requests.ErrorResponse#ALREADY_CROSSPOSTED ALREADY_CROSSPOSTED}
* <br>The target message has already been crossposted.</li>
*
* <li>{@link net.dv8tion.jda.api.requests.ErrorResponse#MISSING_ACCESS MISSING_ACCESS}
* <br>The request was attempted after the account lost access to the
* {@link net.dv8tion.jda.api.entities.Guild Guild}
* typically due to being kicked or removed, or after {@link net.dv8tion.jda.api.Permission#VIEW_CHANNEL Permission.VIEW_CHANNEL}
* was revoked in the {@link net.dv8tion.jda.api.entities.TextChannel TextChannel}</li>
*
* <li>{@link net.dv8tion.jda.api.requests.ErrorResponse#MISSING_PERMISSIONS MISSING_PERMISSIONS}
* <br>The request was attempted after the account lost
* {@link net.dv8tion.jda.api.Permission#MESSAGE_MANAGE Permission.MESSAGE_MANAGE} in the TextChannel.</li>
*
* <li>{@link net.dv8tion.jda.api.requests.ErrorResponse#UNKNOWN_MESSAGE UNKNOWN_MESSAGE}
* <br>The provided {@code messageId} is unknown in this MessageChannel, either due to the id being invalid, or
* the message it referred to has already been deleted.</li>
*
* <li>{@link net.dv8tion.jda.api.requests.ErrorResponse#UNKNOWN_CHANNEL UNKNOWN_CHANNEL}
* <br>The request was attempted after the channel was deleted.</li>
* </ul>
*
* @param messageId
* The messageId to crosspost
*
* @throws java.lang.IllegalArgumentException
* If provided {@code messageId} is {@code null} or empty.
* @throws net.dv8tion.jda.api.exceptions.InsufficientPermissionException
* If the currently logged in account does not have
* {@link net.dv8tion.jda.api.Permission#VIEW_CHANNEL Permission.VIEW_CHANNEL} in this channel.
*
* @return {@link net.dv8tion.jda.api.requests.RestAction} - Type: {@link Message}
*
* @since 4.2.1
*/
@Nonnull
@CheckReturnValue
default RestAction<Message> crosspostMessageById(@Nonnull String messageId)
{
Checks.isSnowflake(messageId);
if (!getGuild().getSelfMember().hasAccess(this))
throw new MissingAccessException(this, Permission.VIEW_CHANNEL);
Route.CompiledRoute route = Route.Messages.CROSSPOST_MESSAGE.compile(getId(), messageId);
return new RestActionImpl<>(getJDA(), route,
(response, request) -> request.getJDA().getEntityBuilder().createMessageWithChannel(response.getObject(), this, false));
}
/**
* Attempts to crosspost the provided message.
*
* <p>The following {@link net.dv8tion.jda.api.requests.ErrorResponse ErrorResponses} are possible:
* <ul>
* <li>{@link net.dv8tion.jda.api.requests.ErrorResponse#ALREADY_CROSSPOSTED ALREADY_CROSSPOSTED}
* <br>The target message has already been crossposted.</li>
*
* <li>{@link net.dv8tion.jda.api.requests.ErrorResponse#MISSING_ACCESS MISSING_ACCESS}
* <br>The request was attempted after the account lost access to the
* {@link net.dv8tion.jda.api.entities.Guild Guild}
* typically due to being kicked or removed, or after {@link net.dv8tion.jda.api.Permission#VIEW_CHANNEL Permission.VIEW_CHANNEL}
* was revoked in the {@link net.dv8tion.jda.api.entities.TextChannel TextChannel}</li>
*
* <li>{@link net.dv8tion.jda.api.requests.ErrorResponse#MISSING_PERMISSIONS MISSING_PERMISSIONS}
* <br>The request was attempted after the account lost
* {@link net.dv8tion.jda.api.Permission#MESSAGE_MANAGE Permission.MESSAGE_MANAGE} in the TextChannel.</li>
*
* <li>{@link net.dv8tion.jda.api.requests.ErrorResponse#UNKNOWN_MESSAGE UNKNOWN_MESSAGE}
* <br>The provided {@code messageId} is unknown in this MessageChannel, either due to the id being invalid, or
* the message it referred to has already been deleted.</li>
*
* <li>{@link net.dv8tion.jda.api.requests.ErrorResponse#UNKNOWN_CHANNEL UNKNOWN_CHANNEL}
* <br>The request was attempted after the channel was deleted.</li>
* </ul>
*
* @param messageId
* The messageId to crosspost
*
* @throws net.dv8tion.jda.api.exceptions.InsufficientPermissionException
* If the currently logged in account does not have
* {@link net.dv8tion.jda.api.Permission#VIEW_CHANNEL Permission.VIEW_CHANNEL} in this channel.
*
* @return {@link net.dv8tion.jda.api.requests.RestAction} - Type: {@link Message}
*
* @since 4.2.1
*/
@Nonnull
@CheckReturnValue
default RestAction<Message> crosspostMessageById(long messageId)
{
return crosspostMessageById(Long.toUnsignedString(messageId));
}
@Nonnull
@Override
ChannelAction<NewsChannel> createCopy(@Nonnull Guild guild);
@Nonnull
@Override
default ChannelAction<NewsChannel> createCopy()
{
return createCopy(getGuild());
}
@Nonnull
@Override
NewsChannelManager getManager();
}
|
Grk0/MapsEvolved
|
pymaplib_cpp/src/map_dhm_advanced.cpp
|
#include "map_dhm_advanced.h"
#define _USE_MATH_DEFINES
#include <memory>
#include <cassert>
#include <math.h>
#include "util.h"
#include "bezier.h"
GradientMap::GradientMap(const std::shared_ptr<RasterMap> &orig_map)
: m_orig_map(orig_map)
{
assert(orig_map->GetType() == RasterMap::TYPE_DHM);
}
GeoDrawable::DrawableType GradientMap::GetType() const {
return RasterMap::TYPE_GRADIENT_MAP;
}
unsigned int GradientMap::GetWidth() const {
return m_orig_map->GetWidth();
}
unsigned int GradientMap::GetHeight() const {
return m_orig_map->GetHeight();
}
MapPixelDeltaInt GradientMap::GetSize() const {
return m_orig_map->GetSize();
}
Projection GradientMap::GetProj() const {
return m_orig_map->GetProj();
}
bool GradientMap::PixelToLatLon(const MapPixelCoord &pos, LatLon *result) const
{
return m_orig_map->PixelToLatLon(pos, result);
}
bool GradientMap::LatLonToPixel(const LatLon &pos, MapPixelCoord *result) const
{
return m_orig_map->LatLonToPixel(pos, result);
}
const std::wstring &GradientMap::GetFname() const {
return m_orig_map->GetFname();
}
const std::wstring &GradientMap::GetTitle() const {
return m_orig_map->GetTitle();
}
const std::wstring &GradientMap::GetDescription() const {
return m_orig_map->GetDescription();
}
//static TimeCounter time_counter;
//static TimeCounter time_counter_loaddisc;
#define DEST(xx,yy) dest[(xx) + size.x * (yy)]
#define SRC(xx,yy) src[(xx) + req_size.x * (yy)]
PixelBuf GradientMap::GetRegion(
const MapPixelCoordInt &pos, const MapPixelDeltaInt &size) const
{
auto fixed_bounds_pb = GetRegion_BoundsHelper(*this, pos, size);
if (fixed_bounds_pb.GetData())
return fixed_bounds_pb;
//time_counter_loaddisc.Start();
MapPixelCoordInt req_pos = pos - MapPixelDeltaInt(1, 1);
MapPixelDeltaInt req_size = size + MapPixelDeltaInt(2, 2);
auto orig_data = m_orig_map->GetRegion(req_pos, req_size);
//auto orig_data = LoadBufferFromBMP(L"example.bmp");
PixelBuf result(size.x, size.y);
unsigned int *src = orig_data.GetRawData();
unsigned int *dest = result.GetRawData();
//time_counter_loaddisc.Stop();
//time_counter.Start();
for (int x=0; x < size.x; x++) {
for (int y=0; y < size.y; y++) {
unsigned int elevation = SRC(x+1, y+1);
MapPixelCoordInt pos(x+1, y+1);
MapBezierGradient grad = Fast3x3CenterGradient(src, pos, req_size);
DEST(x, y) = HSV_to_RGB(
255*240/360 - elevation*255/4000,
255,
ValueBetween(0,
static_cast<int>(128+1.25*(grad.x-grad.y)),
255));
}
}
//time_counter.Stop();
return result;
}
#undef DEST
#undef SRC
SteepnessMap::SteepnessMap(const std::shared_ptr<RasterMap> &orig_map)
: m_orig_map(orig_map)
{
assert(orig_map->GetType() == RasterMap::TYPE_DHM);
}
GeoDrawable::DrawableType SteepnessMap::GetType() const {
return RasterMap::TYPE_STEEPNESS_MAP;
}
unsigned int SteepnessMap::GetWidth() const {
return m_orig_map->GetWidth();
}
unsigned int SteepnessMap::GetHeight() const {
return m_orig_map->GetHeight();
}
MapPixelDeltaInt SteepnessMap::GetSize() const {
return m_orig_map->GetSize();
}
Projection SteepnessMap::GetProj() const {
return m_orig_map->GetProj();
}
bool SteepnessMap::PixelToLatLon(const MapPixelCoord &pos, LatLon *result) const
{
return m_orig_map->PixelToLatLon(pos, result);
}
bool SteepnessMap::LatLonToPixel(const LatLon &pos, MapPixelCoord *result) const
{
return m_orig_map->LatLonToPixel(pos, result);
}
const std::wstring &SteepnessMap::GetFname() const {
return m_orig_map->GetFname();
}
const std::wstring &SteepnessMap::GetTitle() const {
return m_orig_map->GetTitle();
}
const std::wstring &SteepnessMap::GetDescription() const {
return m_orig_map->GetDescription();
}
static const unsigned int steepness_colors[] = {
0xffffff, 0xedffed, 0x95fd95, 0x63f563,
0x00e600, 0x00dca2, 0x009ff6, 0x0078ff,
0x0019ff, 0x0007e5, 0x1700b3, 0x5a00b0,
0x80009b, 0x66006d, 0x5d475d, 0x5d5d5d,
0x3f3f3f, 0x272727, 0x000000,
};
#define DEST(xx,yy) dest[(xx) + size.x * (yy)]
#define SRC(xx,yy) src[(xx) + req_size.x * (yy)]
PixelBuf SteepnessMap::GetRegion(
const MapPixelCoordInt &pos, const MapPixelDeltaInt &size) const
{
auto fixed_bounds_pb = GetRegion_BoundsHelper(*this, pos, size);
if (fixed_bounds_pb.GetData())
return fixed_bounds_pb;
double mpp;
if (!MetersPerPixel(m_orig_map, pos + size/2, &mpp)) {
// Return zero-initialized memory block.
return PixelBuf(size.x, size.y);
}
unsigned int bezier_pixels = Bezier::N_POINTS - 1;
double inv_bezier_meters = 1 / (bezier_pixels * mpp);
MapPixelCoordInt req_pos = pos - MapPixelDeltaInt(1, 1);
MapPixelDeltaInt req_size = size + MapPixelDeltaInt(2, 2);
auto orig_data = m_orig_map->GetRegion(req_pos, req_size);
PixelBuf result(size.x, size.y);
unsigned int *src = orig_data.GetRawData();
unsigned int *dest = result.GetRawData();
for (int x=0; x < size.x; x++) {
for (int y=0; y < size.y; y++) {
MapPixelCoordInt pos(x+1, y+1);
MapBezierGradient grad = Fast3x3CenterGradient(src, pos, req_size);
grad *= inv_bezier_meters;
double grad_steepness = atan(grad.Abs());
int color_index = static_cast<int>(grad_steepness / (M_PI / 2) * 18);
DEST(x, y) = steepness_colors[color_index];
}
}
return result;
}
#undef DEST
#undef SRC
|
gsteri1/OG-Platform
|
projects/OG-Analytics/tests/unit/com/opengamma/financial/model/finitedifference/ForwardPDETest.java
|
<gh_stars>1-10
/**
* Copyright (C) 2011 - present by OpenGamma Inc. and the OpenGamma group of companies
*
* Please see distribution for license.
*/
package com.opengamma.financial.model.finitedifference;
import static org.testng.AssertJUnit.assertEquals;
import org.testng.annotations.Test;
import com.opengamma.financial.model.finitedifference.applications.PDEDataBundleProvider;
import com.opengamma.financial.model.interestrate.curve.ForwardCurve;
import com.opengamma.financial.model.interestrate.curve.YieldAndDiscountCurve;
import com.opengamma.financial.model.interestrate.curve.YieldCurve;
import com.opengamma.financial.model.option.pricing.analytic.formula.BlackFunctionData;
import com.opengamma.financial.model.option.pricing.analytic.formula.EuropeanVanillaOption;
import com.opengamma.financial.model.volatility.BlackImpliedVolatilityFormula;
import com.opengamma.financial.model.volatility.surface.AbsoluteLocalVolatilitySurface;
import com.opengamma.math.curve.ConstantDoublesCurve;
import com.opengamma.math.function.Function1D;
import com.opengamma.math.surface.ConstantDoublesSurface;
import com.opengamma.math.surface.Surface;
/**
* Test the forward parabolic PDE for a option price - i.e. gives an option price surface for maturity and strike (for a fixed "now" time and
* spot). Since all strikes and maturities are priced with a single pass of the solver, this is very useful for calibrating to market prices.
* By contrast the backwards PDE gives the price surface for time-to-maturity and spot (for a fixed maturity and strike), so a separate solver
* will need to be run for each maturity and strike. However the greeks (in particular, delta, gamma and theta) can be read straight off
* the backwards PDE.
*/
public class ForwardPDETest {
private static final PDEDataBundleProvider PDE_DATA_PROVIDER = new PDEDataBundleProvider();
private static final BlackImpliedVolatilityFormula BLACK_IMPLIED_VOL = new BlackImpliedVolatilityFormula();
//private static final AnalyticOptionModel<OptionDefinition, StandardOptionDataBundle> BS_MODEL = new BlackScholesMertonModel();
private static BoundaryCondition LOWER;
private static BoundaryCondition UPPER;
private static final double SPOT = 100;
private static final double T = 5.0;
private static final double RATE = 0.05;// TODO change back to 5%
private static final ForwardCurve FORWARD = new ForwardCurve(SPOT,RATE);
private static final YieldAndDiscountCurve YIELD_CURVE = new YieldCurve(ConstantDoublesCurve.from(RATE));
private static final double ATM_VOL = 0.20;
//private static final ZonedDateTime DATE = DateUtil.getUTCDate(2010, 7, 1);
private static final ConvectionDiffusionPDEDataBundle DATA;
@SuppressWarnings("unused")
private static Surface<Double, Double, Double> ZERO_SURFACE;
private static boolean ISCALL = true;
static {
final Function1D<Double, Double> strikeZeroPrice = new Function1D<Double, Double>() {
@SuppressWarnings("synthetic-access")
@Override
public Double evaluate(final Double t) {
if (ISCALL) {
return SPOT;
}
return 0.0;
}
};
LOWER = new DirichletBoundaryCondition(strikeZeroPrice, 0.0);
if (ISCALL) {
UPPER = new DirichletBoundaryCondition(0, 10.0 * SPOT * Math.exp(T * RATE));
// UPPER = new NeumannBoundaryCondition(0.0, 10.0 * SPOT * Math.exp(T * RATE), false);
} else {
UPPER = new NeumannBoundaryCondition(1.0, 10.0 * SPOT * Math.exp(T * RATE), false);
}
DATA = PDE_DATA_PROVIDER.getForwardLocalVol(FORWARD, 1.0, ISCALL, new AbsoluteLocalVolatilitySurface(ConstantDoublesSurface.from(ATM_VOL)));
}
@Test
public void testBlackScholes() {
final boolean print = false;
final ConvectionDiffusionPDESolver solver = new ThetaMethodFiniteDifference(0.5, true);
// ConvectionDiffusionPDESolver solver = new RichardsonExtrapolationFiniteDifference(base);
final int tNodes = 51;
final int xNodes = 101;
final MeshingFunction timeMesh = new ExponentialMeshing(0, T, tNodes, 5.0);
final MeshingFunction spaceMesh = new HyperbolicMeshing(LOWER.getLevel(), UPPER.getLevel(), SPOT, xNodes, 0.01);
// MeshingFunction spaceMesh = new ExponentalMeshing(LOWER.getLevel(), UPPER.getLevel(), xNodes, 0.0);
final PDEGrid1D grid = new PDEGrid1D(timeMesh, spaceMesh);
final PDEFullResults1D res = (PDEFullResults1D) solver.solve(DATA, grid, LOWER, UPPER);
double t, k;
double price;
double impVol;
double lowerK, upperK;
final double tMin = 0.02;
if (print) {
for (int i = 0; i < xNodes; i++) {
System.out.print("\t" + res.getSpaceValue(i));
}
System.out.print("\n");
}
for (int j = 0; j < tNodes; j++) {
t = res.getTimeValue(j);
final double df = YIELD_CURVE.getDiscountFactor(t);
final BlackFunctionData data = new BlackFunctionData(SPOT / df, df, 0.0);
lowerK = SPOT * Math.exp((RATE - ATM_VOL * ATM_VOL / 2) * t - ATM_VOL * Math.sqrt(t) * 3);
upperK = SPOT * Math.exp((RATE - ATM_VOL * ATM_VOL / 2) * t + ATM_VOL * Math.sqrt(t) * 3);
if (print) {
System.out.print(t);
}
for (int i = 0; i < xNodes; i++) {
k = res.getSpaceValue(i);
price = res.getFunctionValue(i, j);
final EuropeanVanillaOption option = new EuropeanVanillaOption(k, t, ISCALL);
if (k > lowerK && k < upperK && t > tMin) {
try {
impVol = BLACK_IMPLIED_VOL.getImpliedVolatility(data, option, price);
} catch (final Exception e) {
impVol = 0.0;
}
assertEquals(ATM_VOL, impVol, 1e-2);
if (print) {
System.out.print("\t" + impVol);
}
} else {
if (print) {
System.out.print("\t" + ATM_VOL);
}
}
}
if (print) {
System.out.print("\n");
}
}
}
}
|
coderZsq/coderZsq.practice.server
|
study-notes/j2ee-collection/java-web/01-Java基础加强/src/com/coderZsq/_01_review/MotherBoard.java
|
<filename>study-notes/j2ee-collection/java-web/01-Java基础加强/src/com/coderZsq/_01_review/MotherBoard.java
package com.coderZsq._01_review;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
// 主板
public class MotherBoard {
// 存储安装的USB设备对象
private static Map<String, IUSB> plugins = new HashMap<>();
static {
Properties p = new Properties();
try {
// 从classpath的根路径去加载plugins.properties文件
InputStream inStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("plugins.properties");
p.load(inStream);
// ---------------------
// 读取Properties文件, 创建USB组件对象
Set<Map.Entry<Object, Object>> entries = p.entrySet();
// mouse=com.coderZsq._01_review.Mouse
for (Map.Entry<Object, Object> entry : entries) {
String className = entry.getValue().toString();
IUSB usbObject = (IUSB) Class.forName(className).newInstance();
plugins.put(entry.getKey().toString(), usbObject);
}
} catch (Exception e) {
e.printStackTrace();
}
}
// 主板通信
public void doWork() {
// 迭代出每一个安装在主板上的组件, 并调用其功能
for (IUSB usb : plugins.values()) {
usb.swapData();
}
}
}
|
PolarizedIons/JamesBot
|
src/test/java/mocks/MockUser.java
|
<filename>src/test/java/mocks/MockUser.java
package mocks;
import org.pircbotx.User;
public class MockUser extends User {
public MockUser(String nick, String ident, String host) {
super(new MockUserHostmask(nick, ident, host));
}
}
|
matrixzz/InterviewPractice
|
src/LongestSubstringKDistinct.java
|
<reponame>matrixzz/InterviewPractice
import java.util.HashMap;
public class LongestSubstringKDistinct {
public int lengthOfLongestSubstringKDistinct(String s, int k) {
if (s == null || s.isEmpty() || k == 0) {
return 0;
} else if (s.length() <= k) {
return s.length();
}
int i = 0, j = 0;
int max = 0;
int current = 0;
HashMap<Character, Integer> map = new HashMap<>();
char[] c = s.toCharArray();
for (; i < c.length; i++) {
if (!map.containsKey(c[i]) && map.keySet().size() < k) {
map.put(c[i], 1);
current++;
} else if (map.containsKey(c[i])) {
int value = map.get(c[i]) + 1;
map.put(c[i], value);
current++;
} else {
while(map.keySet().size() == k) {
int value = map.get(c[j]) - 1;
if (value != 0) {
map.put(c[j], value);
} else {
map.remove(c[j]);
}
j++;
current--;
}
map.put(c[i], 1);
current++;
}
if (current > max) {
max = current;
}
print(map);
}
return max;
}
private void print (HashMap<Character, Integer> map) {
System.out.println("Print: ");
map.forEach((k, v) -> {
System.out.println("Key: " + k + " Value: " + v);
});
}
static public void main (String[] args) {
LongestSubstringKDistinct problem = new LongestSubstringKDistinct();
String s = "eceabceeeee";
int k = 3;
System.out.println(problem.lengthOfLongestSubstringKDistinct(s, k));
}
}
|
troels/compute-runtime
|
shared/source/gen9/hw_info_gen9.cpp
|
<filename>shared/source/gen9/hw_info_gen9.cpp<gh_stars>100-1000
/*
* Copyright (C) 2018-2021 Intel Corporation
*
* SPDX-License-Identifier: MIT
*
*/
#include "shared/source/gen9/hw_info_gen9.h"
namespace NEO {
const char *GfxFamilyMapper<IGFX_GEN9_CORE>::name = "Gen9";
} // namespace NEO
|
nances/INNBook
|
app/src/main/java/com/kaqi/niuniu/ireader/ui/adapter/view/BillBookHolder.java
|
package com.kaqi.niuniu.ireader.ui.adapter.view;
import android.widget.ImageView;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import com.kaqi.niuniu.ireader.App;
import com.kaqi.niuniu.ireader.R;
import com.kaqi.niuniu.ireader.model.bean.BillBookBean;
import com.kaqi.niuniu.ireader.ui.base.adapter.ViewHolderImpl;
import com.kaqi.niuniu.ireader.utils.Constant;
/**
* Created by newbiechen on 17-5-3.
*/
public class BillBookHolder extends ViewHolderImpl<BillBookBean> {
private ImageView mIvPortrait;
private TextView mTvTitle;
private TextView mTvAuthor;
private TextView mTvBrief;
private TextView mTvMsg;
@Override
protected int getItemLayoutId() {
return R.layout.item_book_brief;
}
@Override
public void initView() {
mIvPortrait = findById(R.id.book_brief_iv_portrait);
mTvTitle = findById(R.id.book_brief_tv_title);
mTvAuthor = findById(R.id.book_brief_tv_author);
mTvBrief = findById(R.id.book_brief_tv_brief);
mTvMsg = findById(R.id.book_brief_tv_msg);
}
@Override
public void onBind(BillBookBean value, int pos) {
//头像
Glide.with(App.getContext())
.load(Constant.IMG_BASE_URL+value.getCover())
.placeholder(R.drawable.ic_default_portrait)
.error(R.drawable.ic_load_error)
.fitCenter()
.into(mIvPortrait);
//书单名
mTvTitle.setText(value.getTitle());
//作者
mTvAuthor.setText(value.getAuthor());
//简介
mTvBrief.setText(value.getShortIntro());
//信息
mTvMsg.setText(App.getContext().getString(R.string.nb_book_message,
value.getLatelyFollower(),value.getRetentionRatio()));
}
}
|
sravani-m/Web-Application-Security-Framework
|
venv/lib/python2.7/site-packages/lz4/version.py
|
# coding: utf-8
# file generated by setuptools_scm
# don't change, don't track in version control
version = u'1.1.0'
|
rofl0r/chaos-pp
|
chaos/preprocessor/array/size.h
|
# /* ********************************************************************
# * *
# * (C) Copyright <NAME> 2003-2005. *
# * *
# * Distributed under the Boost Software License, Version 1.0. *
# * (See accompanying file LICENSE). *
# * *
# * See http://chaos-pp.sourceforge.net for most recent version. *
# * *
# ******************************************************************** */
#
# ifndef CHAOS_PREPROCESSOR_ARRAY_SIZE_H
# define CHAOS_PREPROCESSOR_ARRAY_SIZE_H
#
# include <chaos/preprocessor/config.h>
# include <chaos/preprocessor/facilities/split.h>
# include <chaos/preprocessor/lambda/ops.h>
# include <chaos/preprocessor/tuple/rem.h>
#
# /* CHAOS_PP_ARRAY_SIZE */
#
# define CHAOS_PP_ARRAY_SIZE(array) CHAOS_PP_SPLIT(0, CHAOS_PP_TUPLE_REM(2) array)
# define CHAOS_PP_ARRAY_SIZE_ID() CHAOS_PP_ARRAY_SIZE
#
# if CHAOS_PP_VARIADICS
# define CHAOS_PP_ARRAY_SIZE_ CHAOS_PP_LAMBDA(CHAOS_PP_ARRAY_SIZE)
# endif
#
# endif
|
onmyway133/Runtime-Headers
|
macOS/10.13/CoreFoundation.framework/_CFXNotificationTokenRegistration.h
|
<gh_stars>10-100
/* Generated by RuntimeBrowser
Image: /System/Library/Frameworks/CoreFoundation.framework/Versions/A/CoreFoundation
*/
@interface _CFXNotificationTokenRegistration : _CFXNotificationRegistrationBase {
id _handler;
unsigned long long _options;
BOOL _registered;
unsigned long long _token;
}
@property (atomic, readonly, copy) id handler;
@property (atomic, readonly) struct __CFString { }*name;
@property (atomic, readonly) void*object;
@property (atomic, readonly) void*observer;
@property (atomic, readonly) unsigned long long options;
@property (atomic, readwrite, retain) id queue;
@property (getter=isRegistered, atomic, readonly) BOOL registered;
@property (atomic, readonly) unsigned long long token;
+ (id)createTokenRegistration:(int)arg1 token:(unsigned long long)arg2 connection:(id)arg3 notifyToken:(int)arg4 options:(unsigned long long)arg5 queue:(id)arg6 handler:(id)arg7;
+ (id)find:(unsigned long long)arg1;
+ (const struct { long long x1; int (*x2)(); int (*x3)(); int (*x4)(); int (*x5)(); int (*x6)(); }*)keyCallbacks;
+ (void)remove:(unsigned long long)arg1;
- (void)_invalidate;
- (void)_removeFromParent;
- (void)addToObserver:(id)arg1;
- (id)copyHandler;
- (void)dealloc;
- (id)handler;
- (id)initWithToken:(unsigned long long)arg1 options:(unsigned long long)arg2 queue:(id)arg3 handler:(id)arg4;
- (void)invalidate;
- (BOOL)isRegistered;
- (void*)key;
- (struct __CFString { }*)name;
- (void*)object;
- (void*)observer;
- (unsigned long long)options;
- (id)queue;
- (void)removeFromParent;
- (void)setQueue:(id)arg1;
- (unsigned long long)token;
@end
|
sighttviewliu/hashgard
|
x/record/params/record_query_params.go
|
package params
import (
sdk "github.com/cosmos/cosmos-sdk/types"
)
// Param for query record
type RecordQueryParams struct {
StartRecordId string `json:"start_record_id"`
Sender sdk.AccAddress `json:"sender"`
Limit int `json:"limit"`
}
|
RedRock-2017-Summer/freshmanspecial
|
app/src/main/java/com/mredrock/freshmanspecial/CQUPTElegant/View/ExcellenceTechFragment.java
|
<reponame>RedRock-2017-Summer/freshmanspecial<gh_stars>0
package com.mredrock.freshmanspecial.CQUPTElegant.View;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.mredrock.freshmanspecial.Adapter.ExcellenceTechRecAdapter;
import com.mredrock.freshmanspecial.CQUPTElegant.Model.ExcellenceTech;
import com.mredrock.freshmanspecial.R;
import com.mredrock.freshmanspecial.Utils.NetUtil;
import java.io.IOException;
import okhttp3.ResponseBody;
/**
* Created by Anriku on 2017/8/12.
*/
public class ExcellenceTechFragment extends Fragment{
private View view;
private RecyclerView recyclerView;
private GridLayoutManager manager;
private ExcellenceTechRecAdapter adapter;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
view = inflater.inflate(R.layout.special_2017_fragment_excellence_tech,null);
return view;
}
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
initView();
}
private void initView() {
recyclerView = view.findViewById(R.id.special_2017_frg_excellence_tech_rv);
manager = new GridLayoutManager(getContext(),2);
NetUtil.getGetData("http://yangruixin.com/", "excellentTech", NetUtil.TEXT_GET, new NetUtil.HttpCallBackListener() {
@Override
public void onFinish(ResponseBody responseBody) {
Gson gson = new Gson();
try {
ExcellenceTech excellenceTech = gson.fromJson(responseBody.string(),new TypeToken<ExcellenceTech>(){}.getType());
adapter = new ExcellenceTechRecAdapter(getContext(),excellenceTech);
recyclerView.setLayoutManager(manager);
recyclerView.setAdapter(adapter);
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
}
|
aks010/ClusterDuck-Protocol
|
docs/html/search/all_f.js
|
var searchData=
[
['togglereceiveflag_148',['toggleReceiveFlag',['../class_duck.html#a6c165684af138d33424ecb32cf70f53f',1,'Duck']]],
['topic_149',['topic',['../struct_packet.html#a6141794b7f5f88ff6063f9c668e25840',1,'Packet']]],
['topic_5fb_150',['topic_B',['../_duck_lora_8h.html#a1b6b80f65a5bb8817aa1eb5a272567bf',1,'DuckLora.h']]],
['transmitdata_151',['transmitData',['../class_duck_lora.html#a9b9af508f6c47491779d84e62e98501a',1,'DuckLora']]],
['txpower_152',['txPower',['../struct_lora_config_params.html#a9cdc9d4564f3168e28f4c8757b890e14',1,'LoraConfigParams']]]
];
|
MarginC/kame
|
netbsd/sys/arch/x68k/stand/boot_ufs/readufs.h
|
/* from Id: readufs.h,v 1.7 2002/01/26 15:55:51 itohy Exp */
/*
* Written by ITOH, Yasufumi (<EMAIL>)
* Public domain.
*/
#include <ufs/ufs/dir.h>
/*
* filesystem information
*/
struct ufs_info {
enum ufs_fstype {
UFSTYPE_UNKNOWN
#ifdef USE_FFS
, UFSTYPE_FFS
#endif
#ifdef USE_LFS
, UFSTYPE_LFS
#endif
} fstype;
int (*get_inode) __P((ino_t ino, struct dinode *dibuf));
/* superblock information */
u_int32_t bsize; /* fs block size */
u_int32_t nindir; /* # indirect per block */
u_int32_t fsbtodb; /* block -> sector shift count */
union {
#ifdef USE_FFS
struct {
ufs_daddr_t iblkno; /* inode-block offset */
int32_t cgoffset; /* cylinder group offset */
int32_t cgmask; /* cylinder group mask */
int32_t fragshift; /* block to fragmentation */
int32_t inopb; /* # inodes per block */
int32_t ipg; /* # inodes per group */
int32_t fpg; /* # inodes per group * frag */
} u_ffs;
#endif
#ifdef USE_LFS
struct {
u_int32_t version; /* LFS version # */
ufs_daddr_t idaddr; /* ifile inode disk address */
u_int32_t inopb; /* inodes per block (v1) */
/* inodes per frag (v2) */
u_int32_t ifpb; /* inode addrs / ifile block */
u_int32_t ioffset; /* start of inode in ifile */
/* (in sector) */
u_int32_t ibsize; /* size of inode block */
} u_lfs;
#endif
} fs_u;
};
extern struct ufs_info ufs_info;
#define ufs_get_inode(ino, di) ((*ufs_info.get_inode)((ino), (di)))
void RAW_READ __P((void *buf, ufs_daddr_t blkpos, size_t bytelen));
size_t ufs_read __P((struct dinode *di, void *buf, unsigned off, size_t count));
ino_t ufs_lookup __P((ino_t dirino, const char *fn));
ino_t ufs_lookup_path __P((const char *path));
size_t ufs_load_file __P((void *buf, ino_t dirino, const char *fn));
int ufs_init __P((void));
#ifdef USE_FFS
int try_ffs __P((void));
#endif
#ifdef USE_LFS
int try_lfs __P((void));
#endif
#ifdef DEBUG_WITH_STDIO
#include <fcntl.h>
#include <err.h>
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#endif
|
mishazharov/caffeine
|
include/caffeine/IR/Transforms.h
|
#pragma once
/**
* This header is meant to contain a number of transforms which can be used as
* needed.
*
* Most of the time they will probably be used by various types of solvers but
* since they're common functionality it is useful to have them all in one
* place.
*
* To avoid polluting the caffeine namespace unnecessarily I've placed them
* within the caffeine::transforms namespace.
*
* General Notes on Writing a Transform
* ====================================
* In some cases it is correct to perform an in-place substitution of an
* expression node. For example, doing something like
* *expr = *UnaryOp::CreateNot(other_expr))
* is only valid under certain conditions. In all other cases you need to
* rebuild the expression tree with the replaced node.
*
* The required conditions for an in-place transform to be valid are:
* 1. The transform can only use semantics local to the expression node being
* transformed. As an example, replacing not(not(x)) with x is fine, but
* taking an external x = true and using that to replace not(not(x)) in-place
* with true is not.
* 2. The expression node is not being shared across threads. This is due to
* thread-safety concerns but is generally not something the internal
* implementation of a transform algorithm should have to worry about.
*/
#include "caffeine/IR/Operation.h"
#include "caffeine/Model/AssertionList.h"
#include <vector>
namespace caffeine {
class Assertion;
} // namespace caffeine
namespace caffeine::transforms {
/**
* Attempts to convert the assertions into a canonical form that is suitable for
* cache lookups (or one that can be transformed into such a form with little
* effort).
*
* Currently all it does is apply existing constant-folding and remove exactly
* duplicate expressions from the vector but in the future it will do more.
*/
void canonicalize(AssertionList& assertions);
/**
* Generic simplication transform.
*/
void simplify(AssertionList& assertions);
/**
* Rebuild an expression tree using the transform applied by the visitor. This
* will traverse the tree in a depth-first order and apply the transform to each
* node. If no changes are made then existing expression nodes will be reused.
*
* This is primarily useful as a building block towards more advanced
* transformations.
*/
template <typename Visitor>
OpRef rebuild(const OpRef& expression, Visitor& visitor);
template <typename Visitor>
OpRef rebuild(const OpRef& expression, Visitor&& visitor);
} // namespace caffeine::transforms
#include "caffeine/IR/Transforms.inl"
|
gr3gdev/jmonkey-intellij-integration
|
src/main/java/com/jmonkeystore/ide/editor/component/ColorRGBAComponent.java
|
package com.jmonkeystore.ide.editor.component;
import com.jme3.math.ColorRGBA;
import com.jmonkeystore.ide.jme.ColorUtils;
import javax.swing.*;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class ColorRGBAComponent extends Component {
private JPanel contentPanel;
private JLabel propertyNameLabel;
private JLabel colorValueLabel;
private JPanel colorPanel;
public ColorRGBAComponent() {
super(null, null, null);
addColorPanelListener();
}
public ColorRGBAComponent(Object parent, Method getter, Method setter) {
super(parent, getter, setter);
try {
setValue(getter.invoke(parent));
} catch (IllegalAccessException | InvocationTargetException e) {
e.printStackTrace();
}
addColorPanelListener();
}
private void addColorPanelListener() {
colorPanel.addMouseListener(new MouseListener() {
@Override
public void mouseClicked(MouseEvent e) {
ColorDialog colorDialog = new ColorDialog(colorPanel.getBackground());
if (colorDialog.showAndGet()) {
setValue(ColorUtils.toColorRGBA(colorDialog.getColor()));
}
}
@Override
public void mousePressed(MouseEvent e) {
}
@Override
public void mouseReleased(MouseEvent e) {
}
@Override public void mouseEntered(MouseEvent e) {
}
@Override
public void mouseExited(MouseEvent e) {
}
});
}
@Override
public JComponent getJComponent() {
return contentPanel;
}
@Override
public void setValue(Object value) {
super.setValue(value);
ColorRGBA newVal = (ColorRGBA) value;
SwingUtilities.invokeLater(() -> {
colorPanel.setBackground(ColorUtils.fromColorRGBA(newVal));
colorValueLabel.setText(newVal.toString());
bind();
});
}
@Override
public void bind() {
super.bind();
/*
this.jColorChooser.getSelectionModel().addChangeListener(e -> {
setValue(toColorRGBA(jColorChooser.getColor()));
});
*/
}
@Override
public void setPropertyName(String propertyName) {
super.setPropertyName(propertyName);
propertyNameLabel.setText("ColorRGBA: " + propertyName);
}
}
|
thewizardplusplus/wizard-diary
|
scripts/achievements_selects.js
|
<filename>scripts/achievements_selects.js
var AchievementsSelects = {};
$(document).ready(
function() {
var UPDATE_DELAY = 500;
var levels_picker = $('#achievements_levels_select').selectpicker();
var texts_picker = $('#achievements_texts_select').selectpicker();
var detector = new MobileDetect(navigator.userAgent);
var ResetAchievementSelects = function() {
levels_picker.selectpicker('deselectAll');
texts_picker.selectpicker('deselectAll');
};
var UpdateAchievementList = function() {
var data = {
search: {levels: levels_picker.val(), texts: texts_picker.val()}
};
$.fn.yiiListView.update(
'achievements-list',
{url: DEFAULT_CURRENT_URL, data: data}
);
};
var FormatAchievements = function(number) {
number = number || 0;
var unit = '';
var modulo = number % 10;
if (modulo == 1 && (number < 10 || number > 20)) {
unit = 'достижение';
} else if (
modulo > 1 && modulo < 5
&& (number < 10 || number > 20)
) {
unit = 'достижения';
} else {
unit = 'достижений';
}
return number + ' ' + unit;
};
var update_timer = null;
var UpdateWithDelay = function() {
clearTimeout(update_timer);
update_timer = setTimeout(UpdateAchievementList, UPDATE_DELAY);
};
ResetAchievementSelects();
levels_picker.change(UpdateWithDelay);
texts_picker.change(UpdateWithDelay);
if (detector.mobile()) {
levels_picker.selectpicker('mobile');
texts_picker.selectpicker('mobile');
}
$('.achievement-list-reset-button').click(
function() {
ResetAchievementSelects();
UpdateAchievementList();
}
);
$('.achievements-selects-form').submit(
function (event) {
event.preventDefault();
event.stopPropagation();
return false;
}
);
AchievementsSelects = {
afterUpdate: function() {
var total_counter = $('.achievement-list-total-counter').text();
var formatted_total_counter = FormatAchievements(total_counter);
$('.achievement-counter-view').text(formatted_total_counter);
}
};
}
);
|
thinline72/cayenne
|
cayenne-server/src/main/java/org/apache/cayenne/BaseContext.java
|
<filename>cayenne-server/src/main/java/org/apache/cayenne/BaseContext.java
/*****************************************************************
* 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.cayenne;
import org.apache.cayenne.cache.NestedQueryCache;
import org.apache.cayenne.cache.QueryCache;
import org.apache.cayenne.configuration.CayenneRuntime;
import org.apache.cayenne.di.Injector;
import org.apache.cayenne.event.EventManager;
import org.apache.cayenne.exp.ValueInjector;
import org.apache.cayenne.graph.CompoundDiff;
import org.apache.cayenne.graph.GraphDiff;
import org.apache.cayenne.graph.GraphEvent;
import org.apache.cayenne.graph.GraphManager;
import org.apache.cayenne.map.EntityResolver;
import org.apache.cayenne.map.LifecycleEvent;
import org.apache.cayenne.map.ObjEntity;
import org.apache.cayenne.query.ObjectIdQuery;
import org.apache.cayenne.query.Query;
import org.apache.cayenne.query.RefreshQuery;
import org.apache.cayenne.query.Select;
import org.apache.cayenne.reflect.AttributeProperty;
import org.apache.cayenne.reflect.ClassDescriptor;
import org.apache.cayenne.reflect.PropertyDescriptor;
import org.apache.cayenne.reflect.PropertyVisitor;
import org.apache.cayenne.reflect.ToManyProperty;
import org.apache.cayenne.reflect.ToOneProperty;
import org.apache.cayenne.util.ObjectContextGraphAction;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
/**
* A common base superclass for Cayenne ObjectContext implementors.
*
* @since 3.0
*/
public abstract class BaseContext implements ObjectContext {
/**
* A holder of a ObjectContext bound to the current thread.
*
* @since 3.0
*/
protected static final ThreadLocal<ObjectContext> threadObjectContext = new ThreadLocal<ObjectContext>();
/**
* Returns the ObjectContext bound to the current thread.
*
* @since 3.0
* @return the ObjectContext associated with caller thread.
* @throws IllegalStateException
* if there is no ObjectContext bound to the current thread.
*/
public static ObjectContext getThreadObjectContext() throws IllegalStateException {
ObjectContext context = threadObjectContext.get();
if (context == null) {
throw new IllegalStateException("Current thread has no bound ObjectContext.");
}
return context;
}
/**
* Binds a ObjectContext to the current thread. ObjectContext can later be
* retrieved by users in the same thread by calling
* {@link BaseContext#getThreadObjectContext}. Using null parameter will
* unbind currently bound ObjectContext.
*
* @since 3.0
*/
public static void bindThreadObjectContext(ObjectContext context) {
threadObjectContext.set(context);
}
// transient variables that should be reinitialized on deserialization from
// the
// registry
protected transient DataChannel channel;
protected transient QueryCache queryCache;
protected transient EntityResolver entityResolver;
protected boolean validatingObjectsOnCommit = true;
/**
* Graph action that handles property changes
*
* @since 3.1
*/
protected ObjectContextGraphAction graphAction;
/**
* Stores user defined properties associated with this DataContext.
*
* @since 3.0
*/
protected volatile Map<String, Object> userProperties;
protected BaseContext() {
graphAction = new ObjectContextGraphAction(this);
}
/**
* Checks whether this context is attached to Cayenne runtime stack and if
* not, attempts to attach itself to the runtime using Injector returned
* from the call to {@link CayenneRuntime#getThreadInjector()}. If thread
* Injector is not available and the context is not attached, throws
* CayenneRuntimeException.
* <p>
* This method is called internally by the context before access to
* transient variables to allow the context to attach to the stack lazily
* following deserialization.
*
* @return true if the context successfully attached to the thread runtime,
* false - if it was already attached.
* @since 3.1
*/
protected boolean attachToRuntimeIfNeeded() {
if (channel != null) {
return false;
}
Injector injector = CayenneRuntime.getThreadInjector();
if (injector == null) {
throw new CayenneRuntimeException("Can't attach to Cayenne runtime. "
+ "Null injector returned from CayenneRuntime.getThreadInjector()");
}
attachToRuntime(injector);
return true;
}
/**
* Attaches this context to the CayenneRuntime whose Injector is passed as
* an argument to this method.
*
* @since 3.1
*/
protected void attachToRuntime(Injector injector) {
// TODO: nested contexts handling??
attachToChannel(injector.getInstance(DataChannel.class));
setQueryCache(new NestedQueryCache(injector.getInstance(QueryCache.class)));
}
/**
* Attaches to a provided DataChannel.
*
* @since 3.1
*/
protected void attachToChannel(DataChannel channel) {
if (channel == null) {
throw new NullPointerException("Null channel");
}
setChannel(channel);
setEntityResolver(channel.getEntityResolver());
}
@Override
public abstract void commitChanges();
@Override
public abstract void commitChangesToParent();
@Override
public void deleteObject(Object object) throws DeleteDenyException {
deleteObjects(object);
}
@Override
public abstract Collection<?> deletedObjects();
@Override
public DataChannel getChannel() {
attachToRuntimeIfNeeded();
return channel;
}
/**
* Sets a new DataChannel for this context.
*
* @since 3.1
*/
public void setChannel(DataChannel channel) {
this.channel = channel;
}
@Override
public EntityResolver getEntityResolver() {
attachToRuntimeIfNeeded();
return entityResolver;
}
/**
* @since 3.1
*/
public void setEntityResolver(EntityResolver entityResolver) {
this.entityResolver = entityResolver;
}
/**
* Returns whether this ObjectContext performs object validation before
* commit is executed.
*
* @since 1.1
*/
public boolean isValidatingObjectsOnCommit() {
return validatingObjectsOnCommit;
}
/**
* Sets the property defining whether this ObjectContext should perform
* object validation before commit is executed.
*
* @since 1.1
*/
public void setValidatingObjectsOnCommit(boolean flag) {
this.validatingObjectsOnCommit = flag;
}
/**
* @since 3.1
*/
@Override
public <T extends Persistent> T localObject(T objectFromAnotherContext) {
if (objectFromAnotherContext == null) {
throw new NullPointerException("Null object argument");
}
ObjectId id = objectFromAnotherContext.getObjectId();
// first look for the ID in the local GraphManager
synchronized (getGraphManager()) {
T localObject = (T) getGraphManager().getNode(id);
if (localObject != null) {
return localObject;
}
// create a hollow object, optimistically assuming that the ID we
// got from
// 'objectFromAnotherContext' is a valid ID either in the parent
// context or in
// the DB. This essentially defers possible FaultFailureExceptions.
ClassDescriptor descriptor = getEntityResolver().getClassDescriptor(id.getEntityName());
Persistent persistent = (Persistent) descriptor.createObject();
persistent.setObjectContext(this);
persistent.setObjectId(id);
persistent.setPersistenceState(PersistenceState.HOLLOW);
getGraphManager().registerNode(id, persistent);
return (T) persistent;
}
}
@Override
public abstract GraphManager getGraphManager();
@Override
public abstract Collection<?> modifiedObjects();
@Override
public abstract <T> T newObject(Class<T> persistentClass);
@Override
public abstract void registerNewObject(Object object);
@Override
public abstract Collection<?> newObjects();
@Override
public abstract QueryResponse performGenericQuery(Query query);
@Override
public abstract List performQuery(Query query);
/**
* @since 4.0
*/
@SuppressWarnings("unchecked")
@Override
public <T> List<T> select(Select<T> query) {
return performQuery(query);
}
/**
* @since 4.0
*/
@Override
public <T> T selectOne(Select<T> query) {
List<T> objects = select(query);
if (objects.size() == 0) {
return null;
} else if (objects.size() > 1) {
throw new CayenneRuntimeException("Expected zero or one object, instead query matched: " + objects.size());
}
return objects.get(0);
}
/**
* @since 4.0
*/
@Override
public <T> T selectFirst(Select<T> query) {
List<T> objects = select(query);
return (objects == null || objects.isEmpty()) ? null : objects.get(0);
}
/**
* @since 4.0
*/
@Override
public <T> void iterate(Select<T> query, ResultIteratorCallback<T> callback) {
try (ResultIterator<T> it = iterator(query);) {
for (T t : it) {
callback.next(t);
}
}
}
@Override
public abstract <T> ResultIterator<T> iterator(Select<T> query);
@Override
public <T> ResultBatchIterator<T> batchIterator(Select<T> query, int size) {
return new ResultBatchIterator<T>(iterator(query), size);
}
@Override
public void prepareForAccess(Persistent object, String property, boolean lazyFaulting) {
if (object.getPersistenceState() == PersistenceState.HOLLOW) {
ObjectId oid = object.getObjectId();
List<?> objects = performQuery(new ObjectIdQuery(oid, false, ObjectIdQuery.CACHE));
if (objects.size() == 0) {
throw new FaultFailureException(
"Error resolving fault, no matching row exists in the database for ObjectId: " + oid);
} else if (objects.size() > 1) {
throw new FaultFailureException(
"Error resolving fault, more than one row exists in the database for ObjectId: " + oid);
}
// 5/28/2013 - Commented out this block to allow for modifying
// objects in the postLoad callback
// sanity check...
// if (object.getPersistenceState() != PersistenceState.COMMITTED) {
//
// String state =
// PersistenceState.persistenceStateName(object.getPersistenceState());
//
// // TODO: andrus 4/13/2006, modified and deleted states are
// // possible due to
// // a race condition, should we handle them here?
// throw new
// FaultFailureException("Error resolving fault for ObjectId: " +
// oid + " and state (" + state
// +
// "). Possible cause - matching row is missing from the database.");
// }
}
// resolve relationship fault
if (lazyFaulting && property != null) {
ClassDescriptor classDescriptor = getEntityResolver().getClassDescriptor(
object.getObjectId().getEntityName());
PropertyDescriptor propertyDescriptor = classDescriptor.getProperty(property);
// If we don't have a property descriptor, there's not much we can
// do.
// Let the caller know that the specified property could not be
// found and list
// all of the properties that could be so the caller knows what can
// be used.
if (propertyDescriptor == null) {
final StringBuilder errorMessage = new StringBuilder();
errorMessage.append(String.format("Property '%s' is not declared for entity '%s'.", property, object
.getObjectId().getEntityName()));
errorMessage.append(" Declared properties are: ");
// Grab each of the declared properties.
final List<String> properties = new ArrayList<>();
classDescriptor.visitProperties(new PropertyVisitor() {
@Override
public boolean visitAttribute(final AttributeProperty property) {
properties.add(property.getName());
return true;
}
@Override
public boolean visitToOne(final ToOneProperty property) {
properties.add(property.getName());
return true;
}
@Override
public boolean visitToMany(final ToManyProperty property) {
properties.add(property.getName());
return true;
}
});
// Now add the declared property names to the error message.
boolean first = true;
for (String declaredProperty : properties) {
if (first) {
errorMessage.append(String.format("'%s'", declaredProperty));
first = false;
} else {
errorMessage.append(String.format(", '%s'", declaredProperty));
}
}
errorMessage.append(".");
throw new CayenneRuntimeException(errorMessage.toString());
}
// this should trigger fault resolving
propertyDescriptor.readProperty(object);
}
}
@Override
public void propertyChanged(Persistent object, String property, Object oldValue, Object newValue) {
graphAction.handlePropertyChange(object, property, oldValue, newValue);
}
@Override
public abstract void rollbackChanges();
@Override
public abstract void rollbackChangesLocally();
@Override
public abstract Collection<?> uncommittedObjects();
public QueryCache getQueryCache() {
attachToRuntimeIfNeeded();
return queryCache;
}
/**
* Sets a QueryCache to be used for storing cached query results.
*/
public void setQueryCache(QueryCache queryCache) {
this.queryCache = queryCache;
}
/**
* Returns EventManager associated with the ObjectStore.
*
* @since 1.2
*/
@Override
public EventManager getEventManager() {
return channel != null ? channel.getEventManager() : null;
}
@Override
public GraphDiff onSync(ObjectContext originatingContext, GraphDiff changes, int syncType) {
switch (syncType) {
case DataChannel.ROLLBACK_CASCADE_SYNC:
return onContextRollback(originatingContext);
case DataChannel.FLUSH_NOCASCADE_SYNC:
return onContextFlush(originatingContext, changes, false);
case DataChannel.FLUSH_CASCADE_SYNC:
return onContextFlush(originatingContext, changes, true);
default:
throw new CayenneRuntimeException("Unrecognized SyncMessage type: " + syncType);
}
}
GraphDiff onContextRollback(ObjectContext originatingContext) {
rollbackChanges();
return new CompoundDiff();
}
protected abstract GraphDiff onContextFlush(ObjectContext originatingContext, GraphDiff changes, boolean cascade);
/**
* @since 1.2
*/
protected void fireDataChannelCommitted(Object postedBy, GraphDiff changes) {
EventManager manager = getEventManager();
if (manager != null) {
GraphEvent e = new GraphEvent(this, postedBy, changes);
manager.postEvent(e, DataChannel.GRAPH_FLUSHED_SUBJECT);
}
}
/**
* @since 1.2
*/
protected void fireDataChannelRolledback(Object postedBy, GraphDiff changes) {
EventManager manager = getEventManager();
if (manager != null) {
GraphEvent e = new GraphEvent(this, postedBy, changes);
manager.postEvent(e, DataChannel.GRAPH_ROLLEDBACK_SUBJECT);
}
}
/**
* @since 1.2
*/
protected void fireDataChannelChanged(Object postedBy, GraphDiff changes) {
EventManager manager = getEventManager();
if (manager != null) {
GraphEvent e = new GraphEvent(this, postedBy, changes);
manager.postEvent(e, DataChannel.GRAPH_CHANGED_SUBJECT);
}
}
@Override
public void invalidateObjects(Collection<?> objects) {
// don't allow null collections as a matter of coding discipline
if (objects == null) {
throw new NullPointerException("Null collection of objects to invalidate");
}
if (!objects.isEmpty()) {
performGenericQuery(new RefreshQuery(objects));
}
}
/**
* @since 3.1
*/
@Override
public <T> void invalidateObjects(T... objects) {
if (objects != null && objects.length > 0) {
performGenericQuery(new RefreshQuery(Arrays.asList(objects)));
}
}
/**
* Returns a map of user-defined properties associated with this
* DataContext.
*
* @since 3.0
*/
protected Map<String, Object> getUserProperties() {
// as not all users will take advantage of properties, creating the
// map on demand to keep the context lean...
if (userProperties == null) {
synchronized (this) {
if (userProperties == null) {
userProperties = new ConcurrentHashMap<>();
}
}
}
return userProperties;
}
/**
* Returns a user-defined property previously set via 'setUserProperty'.
* Note that it is a caller responsibility to synchronize access to
* properties.
*
* @since 3.0
*/
@Override
public Object getUserProperty(String key) {
return getUserProperties().get(key);
}
/**
* Sets a user-defined property. Note that it is a caller responsibility to
* synchronize access to properties.
*
* @since 3.0
*/
@Override
public void setUserProperty(String key, Object value) {
getUserProperties().put(key, value);
}
/**
* If ObjEntity qualifier is set, asks it to inject initial value to an
* object. Also performs all Persistent initialization operations
*/
protected void injectInitialValue(Object obj) {
// must follow this exact order of property initialization per CAY-653,
// i.e. have
// the id and the context in place BEFORE setPersistence is called
Persistent object = (Persistent) obj;
object.setObjectContext(this);
object.setPersistenceState(PersistenceState.NEW);
GraphManager graphManager = getGraphManager();
synchronized (graphManager) {
graphManager.registerNode(object.getObjectId(), object);
graphManager.nodeCreated(object.getObjectId());
}
ObjEntity entity;
try {
entity = getEntityResolver().getObjEntity(object.getClass());
} catch (CayenneRuntimeException ex) {
// ObjEntity cannot be fetched, ignored
entity = null;
}
if (entity != null) {
if (entity.getDeclaredQualifier() instanceof ValueInjector) {
((ValueInjector) entity.getDeclaredQualifier()).injectValue(object);
}
}
// invoke callbacks
getEntityResolver().getCallbackRegistry().performCallbacks(LifecycleEvent.POST_ADD, object);
}
/**
* @since 3.1
*/
@Override
public <T> void deleteObjects(T... objects) throws DeleteDenyException {
if (objects == null || objects.length == 0) {
return;
}
ObjectContextDeleteAction action = new ObjectContextDeleteAction(this);
for (Object object : objects) {
action.performDelete((Persistent) object);
}
}
@Override
public void deleteObjects(Collection<?> objects) throws DeleteDenyException {
if (objects.isEmpty()) {
return;
}
ObjectContextDeleteAction action = new ObjectContextDeleteAction(this);
// Make a copy to iterate over to avoid ConcurrentModificationException.
List<Object> copy = new ArrayList<>(objects);
for (Object object : copy) {
action.performDelete((Persistent) object);
}
}
}
|
unconed/NFSpace
|
Platform/OSX/Frameworks/CEGUI.framework/Versions/A/Headers/CEGUIPixmapFont.h
|
/***********************************************************************
filename: CEGUIPixmapFont.h
created: 14/6/2006
author: <NAME>
purpose: Implementation of the Font class via static imagesets
*************************************************************************/
/***************************************************************************
* Copyright (C) 2004 - 2006 <NAME> & The CEGUI Development Team
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
***************************************************************************/
#ifndef _CEGUIPixmapFont_h_
#define _CEGUIPixmapFont_h_
#include "CEGUIFont.h"
#include "CEGUIImage.h"
// Start of CEGUI namespace section
namespace CEGUI
{
// Forward declarations for font properties
namespace FontProperties
{
class PixmapImageset;
class PixmapMapping;
};
/*!
\brief
Implementation of the Font class interface using static Imageset's.
To create such a font you must create a Imageset with all the glyphs,
and then define individual glyphs via the Mapping object property
(or via the Mapping XML element).
*/
class PixmapFont : public Font
{
protected:
friend class FontManager;
friend class FontProperties::PixmapImageset;
friend class FontProperties::PixmapMapping;
/// The imageset with the glyphs
Imageset *d_glyphImages;
/// Current X scaling for glyph images
float d_origHorzScaling;
/// true if we're the owners of the imageset
bool d_imagesetOwner;
/*!
\brief
Constructs a new semi-complete Font object. It is the responsability
of the user to define the glyph mapping (via the Mapping property),
and finally call the load() method which will make font available
for use (this is not *required* for PixmapFont, though).
All font parameters that are not initialized are set to sensible
default values.
\param name
The unique name that will be used to identify this Font.
\param fontname
The filename of the font file, which contains the font data.
This can be a TrueType, PostScript, bitmap font etc file.
If resourceGroup is set to the special value of "*",
fontname is interpreted as a imageset name and the respective
Imageset object must be already loaded.
\param resourceGroup
Resource group identifier to be passed to the resource provider
to load the font definition file.
\exception
UnknownObjectException Thrown if no Imageset named \a filename is
present in within the system (when resourceGroup == "*").
*/
PixmapFont (const String& name, const String& fontname,
const String& resourceGroup = "");
/// \copydoc Font::Font
PixmapFont (const XMLAttributes& attributes);
/// \copydoc Font::~Font
virtual ~PixmapFont ();
/// \copydoc Font::updateFont
virtual void updateFont ();
/// \copydoc Font::writeXMLToStream_impl
virtual void writeXMLToStream_impl (XMLSerializer& xml_stream) const;
/*!
\brief
Define a glyph mapping (handle a <Mapping /> XML element)
*/
virtual void defineMapping (const XMLAttributes& attributes);
/*!
\brief
Define a single glyph mapping
*/
void defineMapping (String image_name, utf32 codepoint, float horzAdvance);
/*!
\brief
Register all properties of this class.
*/
void addPixmapFontProperties ();
/*!
\brief
Initialize the imageset.
*/
void reinit ();
public:
/// \copydoc Font::load
virtual void load ();
};
} // End of CEGUI namespace section
#endif // end of guard _CEGUIPixmapFont_h_
|
xiayefeng/net-easy-learn
|
2.1.4-组件通信/src/demo2.js
|
import React,{Component} from 'react';
import './App.css';
class List extends Component{
constructor(props) {
super(props);
this.state = {
data: [
{name: 'a',id:0},
{name: 'b',id:1},
{name: 'c',id:2}
],
}
}
render() {
return (
<div>
{this.state.data.map(item => <p key={item.id}>{item.name}</p>)}
</div>
);
}
clear() {
this.setState({
data: []
})
}
}
class App extends React.Component{
render() {
return (
<div>
<List ref='list'/>
</div>
);
}
componentDidMount() {
window.app = this
// this.refs.list.clear()
}
}
export default App;
|
technoman72/BlocklyArduino_electrified
|
arduino/packages/esp8266/hardware/esp8266/2.5.0/tools/sdk/lwip2/builder/glue-lwip/lwip-git.h
|
#ifndef LWIP_GIT_H
#define LWIP_GIT_H
#include "lwipopts.h"
#include "lwip/netif.h"
#include "user_interface.h"
#define netif_sta (&netif_git[STATION_IF])
#define netif_ap (&netif_git[SOFTAP_IF])
extern struct netif netif_git[2];
#endif // LWIP_GIT_H
|
CypHelp/TestNewWorldDemo
|
AndroidProject/dc/app/src/main/java/com/example/ershou/Util/Url.java
|
<reponame>CypHelp/TestNewWorldDemo<filename>AndroidProject/dc/app/src/main/java/com/example/ershou/Util/Url.java
package com.example.ershou.Util;
public class Url {
public static String url(){
return "http://127.0.0.1:8080/diancan/";
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.