text
stringlengths 2
100k
| meta
dict |
---|---|
/**
* Copyright (C) 2012 10gen Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License, version 3,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* As a special exception, the copyright holders give permission to link the
* code of portions of this program with the OpenSSL library under certain
* conditions as described in each individual source file and distribute
* linked combinations including the program with the OpenSSL library. You
* must comply with the GNU Affero General Public License in all respects
* for all of the code used other than as permitted herein. If you modify
* file(s) with this exception, you may extend this exception to your
* version of the file(s), but you are not obligated to do so. If you do not
* wish to do so, delete this exception statement from your version. If you
* delete this exception statement from all source files in the program,
* then also delete it in the license file.
*/
#include "mongo/platform/basic.h"
#include "mongo/base/status_with.h"
#include "mongo/bson/oid.h"
#include "mongo/s/catalog/type_collection.h"
#include "mongo/unittest/unittest.h"
#include "mongo/util/time_support.h"
namespace {
using namespace mongo;
using unittest::assertGet;
TEST(CollectionType, Empty) {
StatusWith<CollectionType> status = CollectionType::fromBSON(BSONObj());
ASSERT_FALSE(status.isOK());
}
TEST(CollectionType, Basic) {
const OID oid = OID::gen();
StatusWith<CollectionType> status =
CollectionType::fromBSON(BSON(CollectionType::fullNs("db.coll")
<< CollectionType::epoch(oid)
<< CollectionType::updatedAt(Date_t::fromMillisSinceEpoch(1))
<< CollectionType::keyPattern(BSON("a" << 1))
<< CollectionType::defaultCollation(BSON("locale"
<< "fr_CA"))
<< CollectionType::unique(true)));
ASSERT_TRUE(status.isOK());
CollectionType coll = status.getValue();
ASSERT_TRUE(coll.validate().isOK());
ASSERT(coll.getNs() == NamespaceString{"db.coll"});
ASSERT_EQUALS(coll.getEpoch(), oid);
ASSERT_EQUALS(coll.getUpdatedAt(), Date_t::fromMillisSinceEpoch(1));
ASSERT_BSONOBJ_EQ(coll.getKeyPattern().toBSON(), BSON("a" << 1));
ASSERT_BSONOBJ_EQ(coll.getDefaultCollation(),
BSON("locale"
<< "fr_CA"));
ASSERT_EQUALS(coll.getUnique(), true);
ASSERT_EQUALS(coll.getAllowBalance(), true);
ASSERT_EQUALS(coll.getDropped(), false);
}
TEST(CollectionType, EmptyDefaultCollationFailsToParse) {
const OID oid = OID::gen();
StatusWith<CollectionType> status =
CollectionType::fromBSON(BSON(CollectionType::fullNs("db.coll")
<< CollectionType::epoch(oid)
<< CollectionType::updatedAt(Date_t::fromMillisSinceEpoch(1))
<< CollectionType::keyPattern(BSON("a" << 1))
<< CollectionType::defaultCollation(BSONObj())
<< CollectionType::unique(true)));
ASSERT_FALSE(status.isOK());
}
TEST(CollectionType, MissingDefaultCollationParses) {
const OID oid = OID::gen();
StatusWith<CollectionType> status =
CollectionType::fromBSON(BSON(CollectionType::fullNs("db.coll")
<< CollectionType::epoch(oid)
<< CollectionType::updatedAt(Date_t::fromMillisSinceEpoch(1))
<< CollectionType::keyPattern(BSON("a" << 1))
<< CollectionType::unique(true)));
ASSERT_TRUE(status.isOK());
CollectionType coll = status.getValue();
ASSERT_TRUE(coll.validate().isOK());
ASSERT_BSONOBJ_EQ(coll.getDefaultCollation(), BSONObj());
}
TEST(CollectionType, DefaultCollationSerializesCorrectly) {
const OID oid = OID::gen();
StatusWith<CollectionType> status =
CollectionType::fromBSON(BSON(CollectionType::fullNs("db.coll")
<< CollectionType::epoch(oid)
<< CollectionType::updatedAt(Date_t::fromMillisSinceEpoch(1))
<< CollectionType::keyPattern(BSON("a" << 1))
<< CollectionType::defaultCollation(BSON("locale"
<< "fr_CA"))
<< CollectionType::unique(true)));
ASSERT_TRUE(status.isOK());
CollectionType coll = status.getValue();
ASSERT_TRUE(coll.validate().isOK());
BSONObj serialized = coll.toBSON();
ASSERT_BSONOBJ_EQ(serialized["defaultCollation"].Obj(),
BSON("locale"
<< "fr_CA"));
}
TEST(CollectionType, MissingDefaultCollationIsNotSerialized) {
const OID oid = OID::gen();
StatusWith<CollectionType> status =
CollectionType::fromBSON(BSON(CollectionType::fullNs("db.coll")
<< CollectionType::epoch(oid)
<< CollectionType::updatedAt(Date_t::fromMillisSinceEpoch(1))
<< CollectionType::keyPattern(BSON("a" << 1))
<< CollectionType::unique(true)));
ASSERT_TRUE(status.isOK());
CollectionType coll = status.getValue();
ASSERT_TRUE(coll.validate().isOK());
BSONObj serialized = coll.toBSON();
ASSERT_FALSE(serialized["defaultCollation"]);
}
TEST(CollectionType, EpochCorrectness) {
CollectionType coll;
coll.setNs(NamespaceString{"db.coll"});
coll.setUpdatedAt(Date_t::fromMillisSinceEpoch(1));
coll.setKeyPattern(KeyPattern{BSON("a" << 1)});
coll.setUnique(false);
coll.setDropped(false);
// Validation will fail because we don't have epoch set. This ensures that if we read a
// collection with no epoch, we will write back one with epoch.
ASSERT_NOT_OK(coll.validate());
// We should be allowed to set empty epoch for dropped collections
coll.setDropped(true);
coll.setEpoch(OID());
ASSERT_OK(coll.validate());
// We should be allowed to set normal epoch for non-dropped collections
coll.setDropped(false);
coll.setEpoch(OID::gen());
ASSERT_OK(coll.validate());
}
TEST(CollectionType, Pre22Format) {
CollectionType coll = assertGet(CollectionType::fromBSON(BSON("_id"
<< "db.coll"
<< "lastmod"
<< Date_t::fromMillisSinceEpoch(1)
<< "dropped"
<< false
<< "key"
<< BSON("a" << 1)
<< "unique"
<< false)));
ASSERT(coll.getNs() == NamespaceString{"db.coll"});
ASSERT(!coll.getEpoch().isSet());
ASSERT_EQUALS(coll.getUpdatedAt(), Date_t::fromMillisSinceEpoch(1));
ASSERT_BSONOBJ_EQ(coll.getKeyPattern().toBSON(), BSON("a" << 1));
ASSERT_EQUALS(coll.getUnique(), false);
ASSERT_EQUALS(coll.getAllowBalance(), true);
ASSERT_EQUALS(coll.getDropped(), false);
}
TEST(CollectionType, InvalidCollectionNamespace) {
const OID oid = OID::gen();
StatusWith<CollectionType> result =
CollectionType::fromBSON(BSON(CollectionType::fullNs("foo\\bar.coll")
<< CollectionType::epoch(oid)
<< CollectionType::updatedAt(Date_t::fromMillisSinceEpoch(1))
<< CollectionType::keyPattern(BSON("a" << 1))
<< CollectionType::unique(true)));
ASSERT_TRUE(result.isOK());
CollectionType collType = result.getValue();
ASSERT_FALSE(collType.validate().isOK());
}
TEST(CollectionType, BadType) {
const OID oid = OID::gen();
StatusWith<CollectionType> status = CollectionType::fromBSON(
BSON(CollectionType::fullNs() << 1 << CollectionType::epoch(oid)
<< CollectionType::updatedAt(Date_t::fromMillisSinceEpoch(1))
<< CollectionType::keyPattern(BSON("a" << 1))
<< CollectionType::unique(true)));
ASSERT_FALSE(status.isOK());
}
} // namespace
| {
"pile_set_name": "Github"
} |
/*
* RapidMiner
*
* Copyright (C) 2001-2014 by RapidMiner and the contributors
*
* Complete list of developers available at our web site:
*
* http://rapidminer.com
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see http://www.gnu.org/licenses/.
*/
package com.rapidminer.operator.learner.functions.kernel.evosvm;
import com.rapidminer.tools.math.kernels.Kernel;
/**
* This function must be maximized for the search for an optimal hyperplane for
* regression.
*
* @author Ingo Mierswa
* ingomierswa Exp $
*/
public class RegressionOptimizationFunction implements OptimizationFunction {
private double epsilon;
public RegressionOptimizationFunction(double epsilon) {
this.epsilon = epsilon;
}
public double[] getFitness(double[] alphas, double[] ys, Kernel kernel) {
int offset = ys.length;
double matrixSum = 0.0d;
for (int i = 0; i < ys.length; i++) {
for (int j = 0; j < ys.length; j++) {
matrixSum += (alphas[i] - alphas[i + offset]) * (alphas[j] - alphas[j + offset]) * kernel.getDistance(i, j);
}
}
double alphaSum = 0.0d;
for (int i = 0; i < ys.length; i++) {
alphaSum += (alphas[i] + alphas[i + offset]);
}
double labelSum = 0.0d;
for (int i = 0; i < ys.length; i++) {
labelSum += ys[i] * (alphas[i] - alphas[i + offset]);
}
return new double[] { ((-0.5d * matrixSum) - (epsilon * alphaSum) + labelSum), 0.0d };
}
}
| {
"pile_set_name": "Github"
} |
declare module spine {
class Animation {
name: string;
timelines: Array<Timeline>;
timelineIds: Array<boolean>;
duration: number;
constructor(name: string, timelines: Array<Timeline>, duration: number);
hasTimeline(id: number): boolean;
apply(skeleton: Skeleton, lastTime: number, time: number, loop: boolean, events: Array<Event>, alpha: number, blend: MixBlend, direction: MixDirection): void;
static binarySearch(values: ArrayLike<number>, target: number, step?: number): number;
static linearSearch(values: ArrayLike<number>, target: number, step: number): number;
}
interface Timeline {
apply(skeleton: Skeleton, lastTime: number, time: number, events: Array<Event>, alpha: number, blend: MixBlend, direction: MixDirection): void;
getPropertyId(): number;
}
enum MixBlend {
setup = 0,
first = 1,
replace = 2,
add = 3
}
enum MixDirection {
mixIn = 0,
mixOut = 1
}
enum TimelineType {
rotate = 0,
translate = 1,
scale = 2,
shear = 3,
attachment = 4,
color = 5,
deform = 6,
event = 7,
drawOrder = 8,
ikConstraint = 9,
transformConstraint = 10,
pathConstraintPosition = 11,
pathConstraintSpacing = 12,
pathConstraintMix = 13,
twoColor = 14
}
abstract class CurveTimeline implements Timeline {
static LINEAR: number;
static STEPPED: number;
static BEZIER: number;
static BEZIER_SIZE: number;
private curves;
abstract getPropertyId(): number;
constructor(frameCount: number);
getFrameCount(): number;
setLinear(frameIndex: number): void;
setStepped(frameIndex: number): void;
getCurveType(frameIndex: number): number;
setCurve(frameIndex: number, cx1: number, cy1: number, cx2: number, cy2: number): void;
getCurvePercent(frameIndex: number, percent: number): number;
abstract apply(skeleton: Skeleton, lastTime: number, time: number, events: Array<Event>, alpha: number, blend: MixBlend, direction: MixDirection): void;
}
class RotateTimeline extends CurveTimeline {
static ENTRIES: number;
static PREV_TIME: number;
static PREV_ROTATION: number;
static ROTATION: number;
boneIndex: number;
frames: ArrayLike<number>;
constructor(frameCount: number);
getPropertyId(): number;
setFrame(frameIndex: number, time: number, degrees: number): void;
apply(skeleton: Skeleton, lastTime: number, time: number, events: Array<Event>, alpha: number, blend: MixBlend, direction: MixDirection): void;
}
class TranslateTimeline extends CurveTimeline {
static ENTRIES: number;
static PREV_TIME: number;
static PREV_X: number;
static PREV_Y: number;
static X: number;
static Y: number;
boneIndex: number;
frames: ArrayLike<number>;
constructor(frameCount: number);
getPropertyId(): number;
setFrame(frameIndex: number, time: number, x: number, y: number): void;
apply(skeleton: Skeleton, lastTime: number, time: number, events: Array<Event>, alpha: number, blend: MixBlend, direction: MixDirection): void;
}
class ScaleTimeline extends TranslateTimeline {
constructor(frameCount: number);
getPropertyId(): number;
apply(skeleton: Skeleton, lastTime: number, time: number, events: Array<Event>, alpha: number, blend: MixBlend, direction: MixDirection): void;
}
class ShearTimeline extends TranslateTimeline {
constructor(frameCount: number);
getPropertyId(): number;
apply(skeleton: Skeleton, lastTime: number, time: number, events: Array<Event>, alpha: number, blend: MixBlend, direction: MixDirection): void;
}
class ColorTimeline extends CurveTimeline {
static ENTRIES: number;
static PREV_TIME: number;
static PREV_R: number;
static PREV_G: number;
static PREV_B: number;
static PREV_A: number;
static R: number;
static G: number;
static B: number;
static A: number;
slotIndex: number;
frames: ArrayLike<number>;
constructor(frameCount: number);
getPropertyId(): number;
setFrame(frameIndex: number, time: number, r: number, g: number, b: number, a: number): void;
apply(skeleton: Skeleton, lastTime: number, time: number, events: Array<Event>, alpha: number, blend: MixBlend, direction: MixDirection): void;
}
class TwoColorTimeline extends CurveTimeline {
static ENTRIES: number;
static PREV_TIME: number;
static PREV_R: number;
static PREV_G: number;
static PREV_B: number;
static PREV_A: number;
static PREV_R2: number;
static PREV_G2: number;
static PREV_B2: number;
static R: number;
static G: number;
static B: number;
static A: number;
static R2: number;
static G2: number;
static B2: number;
slotIndex: number;
frames: ArrayLike<number>;
constructor(frameCount: number);
getPropertyId(): number;
setFrame(frameIndex: number, time: number, r: number, g: number, b: number, a: number, r2: number, g2: number, b2: number): void;
apply(skeleton: Skeleton, lastTime: number, time: number, events: Array<Event>, alpha: number, blend: MixBlend, direction: MixDirection): void;
}
class AttachmentTimeline implements Timeline {
slotIndex: number;
frames: ArrayLike<number>;
attachmentNames: Array<string>;
constructor(frameCount: number);
getPropertyId(): number;
getFrameCount(): number;
setFrame(frameIndex: number, time: number, attachmentName: string): void;
apply(skeleton: Skeleton, lastTime: number, time: number, events: Array<Event>, alpha: number, blend: MixBlend, direction: MixDirection): void;
}
class DeformTimeline extends CurveTimeline {
slotIndex: number;
attachment: VertexAttachment;
frames: ArrayLike<number>;
frameVertices: Array<ArrayLike<number>>;
constructor(frameCount: number);
getPropertyId(): number;
setFrame(frameIndex: number, time: number, vertices: ArrayLike<number>): void;
apply(skeleton: Skeleton, lastTime: number, time: number, firedEvents: Array<Event>, alpha: number, blend: MixBlend, direction: MixDirection): void;
}
class EventTimeline implements Timeline {
frames: ArrayLike<number>;
events: Array<Event>;
constructor(frameCount: number);
getPropertyId(): number;
getFrameCount(): number;
setFrame(frameIndex: number, event: Event): void;
apply(skeleton: Skeleton, lastTime: number, time: number, firedEvents: Array<Event>, alpha: number, blend: MixBlend, direction: MixDirection): void;
}
class DrawOrderTimeline implements Timeline {
frames: ArrayLike<number>;
drawOrders: Array<Array<number>>;
constructor(frameCount: number);
getPropertyId(): number;
getFrameCount(): number;
setFrame(frameIndex: number, time: number, drawOrder: Array<number>): void;
apply(skeleton: Skeleton, lastTime: number, time: number, firedEvents: Array<Event>, alpha: number, blend: MixBlend, direction: MixDirection): void;
}
class IkConstraintTimeline extends CurveTimeline {
static ENTRIES: number;
static PREV_TIME: number;
static PREV_MIX: number;
static PREV_SOFTNESS: number;
static PREV_BEND_DIRECTION: number;
static PREV_COMPRESS: number;
static PREV_STRETCH: number;
static MIX: number;
static SOFTNESS: number;
static BEND_DIRECTION: number;
static COMPRESS: number;
static STRETCH: number;
ikConstraintIndex: number;
frames: ArrayLike<number>;
constructor(frameCount: number);
getPropertyId(): number;
setFrame(frameIndex: number, time: number, mix: number, softness: number, bendDirection: number, compress: boolean, stretch: boolean): void;
apply(skeleton: Skeleton, lastTime: number, time: number, firedEvents: Array<Event>, alpha: number, blend: MixBlend, direction: MixDirection): void;
}
class TransformConstraintTimeline extends CurveTimeline {
static ENTRIES: number;
static PREV_TIME: number;
static PREV_ROTATE: number;
static PREV_TRANSLATE: number;
static PREV_SCALE: number;
static PREV_SHEAR: number;
static ROTATE: number;
static TRANSLATE: number;
static SCALE: number;
static SHEAR: number;
transformConstraintIndex: number;
frames: ArrayLike<number>;
constructor(frameCount: number);
getPropertyId(): number;
setFrame(frameIndex: number, time: number, rotateMix: number, translateMix: number, scaleMix: number, shearMix: number): void;
apply(skeleton: Skeleton, lastTime: number, time: number, firedEvents: Array<Event>, alpha: number, blend: MixBlend, direction: MixDirection): void;
}
class PathConstraintPositionTimeline extends CurveTimeline {
static ENTRIES: number;
static PREV_TIME: number;
static PREV_VALUE: number;
static VALUE: number;
pathConstraintIndex: number;
frames: ArrayLike<number>;
constructor(frameCount: number);
getPropertyId(): number;
setFrame(frameIndex: number, time: number, value: number): void;
apply(skeleton: Skeleton, lastTime: number, time: number, firedEvents: Array<Event>, alpha: number, blend: MixBlend, direction: MixDirection): void;
}
class PathConstraintSpacingTimeline extends PathConstraintPositionTimeline {
constructor(frameCount: number);
getPropertyId(): number;
apply(skeleton: Skeleton, lastTime: number, time: number, firedEvents: Array<Event>, alpha: number, blend: MixBlend, direction: MixDirection): void;
}
class PathConstraintMixTimeline extends CurveTimeline {
static ENTRIES: number;
static PREV_TIME: number;
static PREV_ROTATE: number;
static PREV_TRANSLATE: number;
static ROTATE: number;
static TRANSLATE: number;
pathConstraintIndex: number;
frames: ArrayLike<number>;
constructor(frameCount: number);
getPropertyId(): number;
setFrame(frameIndex: number, time: number, rotateMix: number, translateMix: number): void;
apply(skeleton: Skeleton, lastTime: number, time: number, firedEvents: Array<Event>, alpha: number, blend: MixBlend, direction: MixDirection): void;
}
}
declare module spine {
class AnimationState {
static emptyAnimation: Animation;
static SUBSEQUENT: number;
static FIRST: number;
static HOLD: number;
static HOLD_MIX: number;
static NOT_LAST: number;
data: AnimationStateData;
tracks: TrackEntry[];
events: Event[];
listeners: AnimationStateListener2[];
queue: EventQueue;
propertyIDs: IntSet;
animationsChanged: boolean;
timeScale: number;
trackEntryPool: Pool<TrackEntry>;
constructor(data: AnimationStateData);
update(delta: number): void;
updateMixingFrom(to: TrackEntry, delta: number): boolean;
apply(skeleton: Skeleton): boolean;
applyMixingFrom(to: TrackEntry, skeleton: Skeleton, blend: MixBlend): number;
applyRotateTimeline(timeline: Timeline, skeleton: Skeleton, time: number, alpha: number, blend: MixBlend, timelinesRotation: Array<number>, i: number, firstFrame: boolean): void;
queueEvents(entry: TrackEntry, animationTime: number): void;
clearTracks(): void;
clearTrack(trackIndex: number): void;
setCurrent(index: number, current: TrackEntry, interrupt: boolean): void;
setAnimation(trackIndex: number, animationName: string, loop: boolean): TrackEntry;
setAnimationWith(trackIndex: number, animation: Animation, loop: boolean): TrackEntry;
addAnimation(trackIndex: number, animationName: string, loop: boolean, delay: number): TrackEntry;
addAnimationWith(trackIndex: number, animation: Animation, loop: boolean, delay: number): TrackEntry;
setEmptyAnimation(trackIndex: number, mixDuration: number): TrackEntry;
addEmptyAnimation(trackIndex: number, mixDuration: number, delay: number): TrackEntry;
setEmptyAnimations(mixDuration: number): void;
expandToIndex(index: number): TrackEntry;
trackEntry(trackIndex: number, animation: Animation, loop: boolean, last: TrackEntry): TrackEntry;
disposeNext(entry: TrackEntry): void;
_animationsChanged(): void;
computeHold(entry: TrackEntry): void;
computeNotLast(entry: TrackEntry): void;
getCurrent(trackIndex: number): TrackEntry;
addListener(listener: AnimationStateListener2): void;
removeListener(listener: AnimationStateListener2): void;
clearListeners(): void;
clearListenerNotifications(): void;
}
class TrackEntry {
animation: Animation;
next: TrackEntry;
mixingFrom: TrackEntry;
mixingTo: TrackEntry;
listener: AnimationStateListener2;
trackIndex: number;
loop: boolean;
holdPrevious: boolean;
eventThreshold: number;
attachmentThreshold: number;
drawOrderThreshold: number;
animationStart: number;
animationEnd: number;
animationLast: number;
nextAnimationLast: number;
delay: number;
trackTime: number;
trackLast: number;
nextTrackLast: number;
trackEnd: number;
timeScale: number;
alpha: number;
mixTime: number;
mixDuration: number;
interruptAlpha: number;
totalAlpha: number;
mixBlend: MixBlend;
timelineMode: number[];
timelineHoldMix: TrackEntry[];
timelinesRotation: number[];
reset(): void;
getAnimationTime(): number;
setAnimationLast(animationLast: number): void;
isComplete(): boolean;
resetRotationDirections(): void;
}
class EventQueue {
objects: Array<any>;
drainDisabled: boolean;
animState: AnimationState;
constructor(animState: AnimationState);
start(entry: TrackEntry): void;
interrupt(entry: TrackEntry): void;
end(entry: TrackEntry): void;
dispose(entry: TrackEntry): void;
complete(entry: TrackEntry): void;
event(entry: TrackEntry, event: Event): void;
drain(): void;
clear(): void;
}
enum EventType {
start = 0,
interrupt = 1,
end = 2,
dispose = 3,
complete = 4,
event = 5
}
interface AnimationStateListener2 {
start(entry: TrackEntry): void;
interrupt(entry: TrackEntry): void;
end(entry: TrackEntry): void;
dispose(entry: TrackEntry): void;
complete(entry: TrackEntry): void;
event(entry: TrackEntry, event: Event): void;
}
abstract class AnimationStateAdapter2 implements AnimationStateListener2 {
start(entry: TrackEntry): void;
interrupt(entry: TrackEntry): void;
end(entry: TrackEntry): void;
dispose(entry: TrackEntry): void;
complete(entry: TrackEntry): void;
event(entry: TrackEntry, event: Event): void;
}
}
declare module spine {
class AnimationStateData {
skeletonData: SkeletonData;
animationToMixTime: Map<number>;
defaultMix: number;
constructor(skeletonData: SkeletonData);
setMix(fromName: string, toName: string, duration: number): void;
setMixWith(from: Animation, to: Animation, duration: number): void;
getMix(from: Animation, to: Animation): number;
}
}
declare module spine {
class AssetManager implements Disposable {
private pathPrefix;
private textureLoader;
private assets;
private errors;
private toLoad;
private loaded;
constructor(textureLoader: (image: HTMLImageElement) => any, pathPrefix?: string);
private static downloadText;
private static downloadBinary;
loadBinary(path: string, success?: (path: string, binary: Uint8Array) => void, error?: (path: string, error: string) => void): void;
loadText(path: string, success?: (path: string, text: string) => void, error?: (path: string, error: string) => void): void;
loadTexture(path: string, success?: (path: string, image: HTMLImageElement) => void, error?: (path: string, error: string) => void): void;
loadTextureData(path: string, data: string, success?: (path: string, image: HTMLImageElement) => void, error?: (path: string, error: string) => void): void;
loadTextureAtlas(path: string, success?: (path: string, atlas: TextureAtlas) => void, error?: (path: string, error: string) => void): void;
get(path: string): any;
remove(path: string): void;
removeAll(): void;
isLoadingComplete(): boolean;
getToLoad(): number;
getLoaded(): number;
dispose(): void;
hasErrors(): boolean;
getErrors(): Map<string>;
}
}
declare module spine {
class AtlasAttachmentLoader implements AttachmentLoader {
atlas: TextureAtlas;
constructor(atlas: TextureAtlas);
newRegionAttachment(skin: Skin, name: string, path: string): RegionAttachment;
newMeshAttachment(skin: Skin, name: string, path: string): MeshAttachment;
newBoundingBoxAttachment(skin: Skin, name: string): BoundingBoxAttachment;
newPathAttachment(skin: Skin, name: string): PathAttachment;
newPointAttachment(skin: Skin, name: string): PointAttachment;
newClippingAttachment(skin: Skin, name: string): ClippingAttachment;
}
}
declare module spine {
enum BlendMode {
Normal = 0,
Additive = 1,
Multiply = 2,
Screen = 3
}
}
declare module spine {
class Bone implements Updatable {
data: BoneData;
skeleton: Skeleton;
parent: Bone;
children: Bone[];
x: number;
y: number;
rotation: number;
scaleX: number;
scaleY: number;
shearX: number;
shearY: number;
ax: number;
ay: number;
arotation: number;
ascaleX: number;
ascaleY: number;
ashearX: number;
ashearY: number;
appliedValid: boolean;
a: number;
b: number;
worldX: number;
c: number;
d: number;
worldY: number;
sorted: boolean;
active: boolean;
constructor(data: BoneData, skeleton: Skeleton, parent: Bone);
isActive(): boolean;
update(): void;
updateWorldTransform(): void;
updateWorldTransformWith(x: number, y: number, rotation: number, scaleX: number, scaleY: number, shearX: number, shearY: number): void;
setToSetupPose(): void;
getWorldRotationX(): number;
getWorldRotationY(): number;
getWorldScaleX(): number;
getWorldScaleY(): number;
updateAppliedTransform(): void;
worldToLocal(world: Vector2): Vector2;
localToWorld(local: Vector2): Vector2;
worldToLocalRotation(worldRotation: number): number;
localToWorldRotation(localRotation: number): number;
rotateWorld(degrees: number): void;
}
}
declare module spine {
class BoneData {
index: number;
name: string;
parent: BoneData;
length: number;
x: number;
y: number;
rotation: number;
scaleX: number;
scaleY: number;
shearX: number;
shearY: number;
transformMode: TransformMode;
skinRequired: boolean;
color: Color;
constructor(index: number, name: string, parent: BoneData);
}
enum TransformMode {
Normal = 0,
OnlyTranslation = 1,
NoRotationOrReflection = 2,
NoScale = 3,
NoScaleOrReflection = 4
}
}
declare module spine {
abstract class ConstraintData {
name: string;
order: number;
skinRequired: boolean;
constructor(name: string, order: number, skinRequired: boolean);
}
}
declare module spine {
class Event {
data: EventData;
intValue: number;
floatValue: number;
stringValue: string;
time: number;
volume: number;
balance: number;
constructor(time: number, data: EventData);
}
}
declare module spine {
class EventData {
name: string;
intValue: number;
floatValue: number;
stringValue: string;
audioPath: string;
volume: number;
balance: number;
constructor(name: string);
}
}
declare module spine {
class IkConstraint implements Updatable {
data: IkConstraintData;
bones: Array<Bone>;
target: Bone;
bendDirection: number;
compress: boolean;
stretch: boolean;
mix: number;
softness: number;
active: boolean;
constructor(data: IkConstraintData, skeleton: Skeleton);
isActive(): boolean;
apply(): void;
update(): void;
apply1(bone: Bone, targetX: number, targetY: number, compress: boolean, stretch: boolean, uniform: boolean, alpha: number): void;
apply2(parent: Bone, child: Bone, targetX: number, targetY: number, bendDir: number, stretch: boolean, softness: number, alpha: number): void;
}
}
declare module spine {
class IkConstraintData extends ConstraintData {
bones: BoneData[];
target: BoneData;
bendDirection: number;
compress: boolean;
stretch: boolean;
uniform: boolean;
mix: number;
softness: number;
constructor(name: string);
}
}
declare module spine {
class PathConstraint implements Updatable {
static NONE: number;
static BEFORE: number;
static AFTER: number;
static epsilon: number;
data: PathConstraintData;
bones: Array<Bone>;
target: Slot;
position: number;
spacing: number;
rotateMix: number;
translateMix: number;
spaces: number[];
positions: number[];
world: number[];
curves: number[];
lengths: number[];
segments: number[];
active: boolean;
constructor(data: PathConstraintData, skeleton: Skeleton);
isActive(): boolean;
apply(): void;
update(): void;
computeWorldPositions(path: PathAttachment, spacesCount: number, tangents: boolean, percentPosition: boolean, percentSpacing: boolean): number[];
addBeforePosition(p: number, temp: Array<number>, i: number, out: Array<number>, o: number): void;
addAfterPosition(p: number, temp: Array<number>, i: number, out: Array<number>, o: number): void;
addCurvePosition(p: number, x1: number, y1: number, cx1: number, cy1: number, cx2: number, cy2: number, x2: number, y2: number, out: Array<number>, o: number, tangents: boolean): void;
}
}
declare module spine {
class PathConstraintData extends ConstraintData {
bones: BoneData[];
target: SlotData;
positionMode: PositionMode;
spacingMode: SpacingMode;
rotateMode: RotateMode;
offsetRotation: number;
position: number;
spacing: number;
rotateMix: number;
translateMix: number;
constructor(name: string);
}
enum PositionMode {
Fixed = 0,
Percent = 1
}
enum SpacingMode {
Length = 0,
Fixed = 1,
Percent = 2
}
enum RotateMode {
Tangent = 0,
Chain = 1,
ChainScale = 2
}
}
declare module spine {
class SharedAssetManager implements Disposable {
private pathPrefix;
private clientAssets;
private queuedAssets;
private rawAssets;
private errors;
constructor(pathPrefix?: string);
private queueAsset;
loadText(clientId: string, path: string): void;
loadJson(clientId: string, path: string): void;
loadTexture(clientId: string, textureLoader: (image: HTMLImageElement) => any, path: string): void;
get(clientId: string, path: string): any;
private updateClientAssets;
isLoadingComplete(clientId: string): boolean;
dispose(): void;
hasErrors(): boolean;
getErrors(): Map<string>;
}
}
declare module spine {
class Skeleton {
data: SkeletonData;
bones: Array<Bone>;
slots: Array<Slot>;
drawOrder: Array<Slot>;
ikConstraints: Array<IkConstraint>;
transformConstraints: Array<TransformConstraint>;
pathConstraints: Array<PathConstraint>;
_updateCache: Updatable[];
updateCacheReset: Updatable[];
skin: Skin;
color: Color;
time: number;
scaleX: number;
scaleY: number;
x: number;
y: number;
constructor(data: SkeletonData);
updateCache(): void;
sortIkConstraint(constraint: IkConstraint): void;
sortPathConstraint(constraint: PathConstraint): void;
sortTransformConstraint(constraint: TransformConstraint): void;
sortPathConstraintAttachment(skin: Skin, slotIndex: number, slotBone: Bone): void;
sortPathConstraintAttachmentWith(attachment: Attachment, slotBone: Bone): void;
sortBone(bone: Bone): void;
sortReset(bones: Array<Bone>): void;
updateWorldTransform(): void;
setToSetupPose(): void;
setBonesToSetupPose(): void;
setSlotsToSetupPose(): void;
getRootBone(): Bone;
findBone(boneName: string): Bone;
findBoneIndex(boneName: string): number;
findSlot(slotName: string): Slot;
findSlotIndex(slotName: string): number;
setSkinByName(skinName: string): void;
setSkin(newSkin: Skin): void;
getAttachmentByName(slotName: string, attachmentName: string): Attachment;
getAttachment(slotIndex: number, attachmentName: string): Attachment;
setAttachment(slotName: string, attachmentName: string): void;
findIkConstraint(constraintName: string): IkConstraint;
findTransformConstraint(constraintName: string): TransformConstraint;
findPathConstraint(constraintName: string): PathConstraint;
getBounds(offset: Vector2, size: Vector2, temp?: Array<number>): void;
update(delta: number): void;
}
}
declare module spine {
class SkeletonBinary {
static AttachmentTypeValues: number[];
static TransformModeValues: TransformMode[];
static PositionModeValues: PositionMode[];
static SpacingModeValues: SpacingMode[];
static RotateModeValues: RotateMode[];
static BlendModeValues: BlendMode[];
static BONE_ROTATE: number;
static BONE_TRANSLATE: number;
static BONE_SCALE: number;
static BONE_SHEAR: number;
static SLOT_ATTACHMENT: number;
static SLOT_COLOR: number;
static SLOT_TWO_COLOR: number;
static PATH_POSITION: number;
static PATH_SPACING: number;
static PATH_MIX: number;
static CURVE_LINEAR: number;
static CURVE_STEPPED: number;
static CURVE_BEZIER: number;
attachmentLoader: AttachmentLoader;
scale: number;
private linkedMeshes;
constructor(attachmentLoader: AttachmentLoader);
readSkeletonData(binary: Uint8Array): SkeletonData;
private readSkin;
private readAttachment;
private readVertices;
private readFloatArray;
private readShortArray;
private readAnimation;
private readCurve;
setCurve(timeline: CurveTimeline, frameIndex: number, cx1: number, cy1: number, cx2: number, cy2: number): void;
}
}
declare module spine {
class SkeletonBounds {
minX: number;
minY: number;
maxX: number;
maxY: number;
boundingBoxes: BoundingBoxAttachment[];
polygons: ArrayLike<number>[];
private polygonPool;
update(skeleton: Skeleton, updateAabb: boolean): void;
aabbCompute(): void;
aabbContainsPoint(x: number, y: number): boolean;
aabbIntersectsSegment(x1: number, y1: number, x2: number, y2: number): boolean;
aabbIntersectsSkeleton(bounds: SkeletonBounds): boolean;
containsPoint(x: number, y: number): BoundingBoxAttachment;
containsPointPolygon(polygon: ArrayLike<number>, x: number, y: number): boolean;
intersectsSegment(x1: number, y1: number, x2: number, y2: number): BoundingBoxAttachment;
intersectsSegmentPolygon(polygon: ArrayLike<number>, x1: number, y1: number, x2: number, y2: number): boolean;
getPolygon(boundingBox: BoundingBoxAttachment): ArrayLike<number>;
getWidth(): number;
getHeight(): number;
}
}
declare module spine {
class SkeletonClipping {
private triangulator;
private clippingPolygon;
private clipOutput;
clippedVertices: number[];
clippedTriangles: number[];
private scratch;
private clipAttachment;
private clippingPolygons;
clipStart(slot: Slot, clip: ClippingAttachment): number;
clipEndWithSlot(slot: Slot): void;
clipEnd(): void;
isClipping(): boolean;
clipTriangles(vertices: ArrayLike<number>, verticesLength: number, triangles: ArrayLike<number>, trianglesLength: number, uvs: ArrayLike<number>, light: Color, dark: Color, twoColor: boolean): void;
clip(x1: number, y1: number, x2: number, y2: number, x3: number, y3: number, clippingArea: Array<number>, output: Array<number>): boolean;
static makeClockwise(polygon: ArrayLike<number>): void;
}
}
declare module spine {
class SkeletonData {
name: string;
bones: BoneData[];
slots: SlotData[];
skins: Skin[];
defaultSkin: Skin;
events: EventData[];
animations: Animation[];
ikConstraints: IkConstraintData[];
transformConstraints: TransformConstraintData[];
pathConstraints: PathConstraintData[];
x: number;
y: number;
width: number;
height: number;
version: string;
hash: string;
fps: number;
imagesPath: string;
audioPath: string;
findBone(boneName: string): BoneData;
findBoneIndex(boneName: string): number;
findSlot(slotName: string): SlotData;
findSlotIndex(slotName: string): number;
findSkin(skinName: string): Skin;
findEvent(eventDataName: string): EventData;
findAnimation(animationName: string): Animation;
findIkConstraint(constraintName: string): IkConstraintData;
findTransformConstraint(constraintName: string): TransformConstraintData;
findPathConstraint(constraintName: string): PathConstraintData;
findPathConstraintIndex(pathConstraintName: string): number;
}
}
declare module spine {
class SkeletonJson {
attachmentLoader: AttachmentLoader;
scale: number;
private linkedMeshes;
constructor(attachmentLoader: AttachmentLoader);
readSkeletonData(json: string | any): SkeletonData;
readAttachment(map: any, skin: Skin, slotIndex: number, name: string, skeletonData: SkeletonData): Attachment;
readVertices(map: any, attachment: VertexAttachment, verticesLength: number): void;
readAnimation(map: any, name: string, skeletonData: SkeletonData): void;
readCurve(map: any, timeline: CurveTimeline, frameIndex: number): void;
getValue(map: any, prop: string, defaultValue: any): any;
static blendModeFromString(str: string): BlendMode;
static positionModeFromString(str: string): PositionMode;
static spacingModeFromString(str: string): SpacingMode;
static rotateModeFromString(str: string): RotateMode;
static transformModeFromString(str: string): TransformMode;
}
}
declare module spine {
class SkinEntry {
slotIndex: number;
name: string;
attachment: Attachment;
constructor(slotIndex: number, name: string, attachment: Attachment);
}
class Skin {
name: string;
attachments: Map<Attachment>[];
bones: BoneData[];
constraints: ConstraintData[];
constructor(name: string);
setAttachment(slotIndex: number, name: string, attachment: Attachment): void;
addSkin(skin: Skin): void;
copySkin(skin: Skin): void;
getAttachment(slotIndex: number, name: string): Attachment;
removeAttachment(slotIndex: number, name: string): void;
getAttachments(): Array<SkinEntry>;
getAttachmentsForSlot(slotIndex: number, attachments: Array<SkinEntry>): void;
clear(): void;
attachAll(skeleton: Skeleton, oldSkin: Skin): void;
}
}
declare module spine {
class Slot {
data: SlotData;
bone: Bone;
color: Color;
darkColor: Color;
private attachment;
private attachmentTime;
deform: number[];
constructor(data: SlotData, bone: Bone);
getAttachment(): Attachment;
setAttachment(attachment: Attachment): void;
setAttachmentTime(time: number): void;
getAttachmentTime(): number;
setToSetupPose(): void;
}
}
declare module spine {
class SlotData {
index: number;
name: string;
boneData: BoneData;
color: Color;
darkColor: Color;
attachmentName: string;
blendMode: BlendMode;
constructor(index: number, name: string, boneData: BoneData);
}
}
declare module spine {
abstract class Texture {
protected _image: HTMLImageElement;
constructor(image: HTMLImageElement);
getImage(): HTMLImageElement;
abstract setFilters(minFilter: TextureFilter, magFilter: TextureFilter): void;
abstract setWraps(uWrap: TextureWrap, vWrap: TextureWrap): void;
abstract dispose(): void;
static filterFromString(text: string): TextureFilter;
static wrapFromString(text: string): TextureWrap;
}
enum TextureFilter {
Nearest = 9728,
Linear = 9729,
MipMap = 9987,
MipMapNearestNearest = 9984,
MipMapLinearNearest = 9985,
MipMapNearestLinear = 9986,
MipMapLinearLinear = 9987
}
enum TextureWrap {
MirroredRepeat = 33648,
ClampToEdge = 33071,
Repeat = 10497
}
class TextureRegion {
renderObject: any;
u: number;
v: number;
u2: number;
v2: number;
width: number;
height: number;
rotate: boolean;
offsetX: number;
offsetY: number;
originalWidth: number;
originalHeight: number;
}
class FakeTexture extends Texture {
setFilters(minFilter: TextureFilter, magFilter: TextureFilter): void;
setWraps(uWrap: TextureWrap, vWrap: TextureWrap): void;
dispose(): void;
}
}
declare module spine {
class TextureAtlas implements Disposable {
pages: TextureAtlasPage[];
regions: TextureAtlasRegion[];
constructor(atlasText: string, textureLoader: (path: string) => any);
private load;
findRegion(name: string): TextureAtlasRegion;
dispose(): void;
}
class TextureAtlasPage {
name: string;
minFilter: TextureFilter;
magFilter: TextureFilter;
uWrap: TextureWrap;
vWrap: TextureWrap;
texture: Texture;
width: number;
height: number;
}
class TextureAtlasRegion extends TextureRegion {
page: TextureAtlasPage;
name: string;
x: number;
y: number;
index: number;
rotate: boolean;
degrees: number;
texture: Texture;
}
}
declare module spine {
class TransformConstraint implements Updatable {
data: TransformConstraintData;
bones: Array<Bone>;
target: Bone;
rotateMix: number;
translateMix: number;
scaleMix: number;
shearMix: number;
temp: Vector2;
active: boolean;
constructor(data: TransformConstraintData, skeleton: Skeleton);
isActive(): boolean;
apply(): void;
update(): void;
applyAbsoluteWorld(): void;
applyRelativeWorld(): void;
applyAbsoluteLocal(): void;
applyRelativeLocal(): void;
}
}
declare module spine {
class TransformConstraintData extends ConstraintData {
bones: BoneData[];
target: BoneData;
rotateMix: number;
translateMix: number;
scaleMix: number;
shearMix: number;
offsetRotation: number;
offsetX: number;
offsetY: number;
offsetScaleX: number;
offsetScaleY: number;
offsetShearY: number;
relative: boolean;
local: boolean;
constructor(name: string);
}
}
declare module spine {
class Triangulator {
private convexPolygons;
private convexPolygonsIndices;
private indicesArray;
private isConcaveArray;
private triangles;
private polygonPool;
private polygonIndicesPool;
triangulate(verticesArray: ArrayLike<number>): Array<number>;
decompose(verticesArray: Array<number>, triangles: Array<number>): Array<Array<number>>;
private static isConcave;
private static positiveArea;
private static winding;
}
}
declare module spine {
interface Updatable {
update(): void;
isActive(): boolean;
}
}
declare module spine {
interface Map<T> {
[key: string]: T;
}
class IntSet {
array: number[];
add(value: number): boolean;
contains(value: number): boolean;
remove(value: number): void;
clear(): void;
}
interface Disposable {
dispose(): void;
}
interface Restorable {
restore(): void;
}
class Color {
r: number;
g: number;
b: number;
a: number;
static WHITE: Color;
static RED: Color;
static GREEN: Color;
static BLUE: Color;
static MAGENTA: Color;
constructor(r?: number, g?: number, b?: number, a?: number);
set(r: number, g: number, b: number, a: number): this;
setFromColor(c: Color): this;
setFromString(hex: string): this;
add(r: number, g: number, b: number, a: number): this;
clamp(): this;
static rgba8888ToColor(color: Color, value: number): void;
static rgb888ToColor(color: Color, value: number): void;
}
class MathUtils {
static PI: number;
static PI2: number;
static radiansToDegrees: number;
static radDeg: number;
static degreesToRadians: number;
static degRad: number;
static clamp(value: number, min: number, max: number): number;
static cosDeg(degrees: number): number;
static sinDeg(degrees: number): number;
static signum(value: number): number;
static toInt(x: number): number;
static cbrt(x: number): number;
static randomTriangular(min: number, max: number): number;
static randomTriangularWith(min: number, max: number, mode: number): number;
}
abstract class Interpolation {
protected abstract applyInternal(a: number): number;
apply(start: number, end: number, a: number): number;
}
class Pow extends Interpolation {
protected power: number;
constructor(power: number);
applyInternal(a: number): number;
}
class PowOut extends Pow {
constructor(power: number);
applyInternal(a: number): number;
}
class Utils {
static SUPPORTS_TYPED_ARRAYS: boolean;
static arrayCopy<T>(source: ArrayLike<T>, sourceStart: number, dest: ArrayLike<T>, destStart: number, numElements: number): void;
static setArraySize<T>(array: Array<T>, size: number, value?: any): Array<T>;
static ensureArrayCapacity<T>(array: Array<T>, size: number, value?: any): Array<T>;
static newArray<T>(size: number, defaultValue: T): Array<T>;
static newFloatArray(size: number): ArrayLike<number>;
static newShortArray(size: number): ArrayLike<number>;
static toFloatArray(array: Array<number>): number[] | Float32Array;
static toSinglePrecision(value: number): number;
static webkit602BugfixHelper(alpha: number, blend: MixBlend): void;
static contains<T>(array: Array<T>, element: T, identity?: boolean): boolean;
}
class DebugUtils {
static logBones(skeleton: Skeleton): void;
}
class Pool<T> {
private items;
private instantiator;
constructor(instantiator: () => T);
obtain(): T;
free(item: T): void;
freeAll(items: ArrayLike<T>): void;
clear(): void;
}
class Vector2 {
x: number;
y: number;
constructor(x?: number, y?: number);
set(x: number, y: number): Vector2;
length(): number;
normalize(): this;
}
class TimeKeeper {
maxDelta: number;
framesPerSecond: number;
delta: number;
totalTime: number;
private lastTime;
private frameCount;
private frameTime;
update(): void;
}
interface ArrayLike<T> {
length: number;
[n: number]: T;
}
class WindowedMean {
values: Array<number>;
addedValues: number;
lastValue: number;
mean: number;
dirty: boolean;
constructor(windowSize?: number);
hasEnoughData(): boolean;
addValue(value: number): void;
getMean(): number;
}
}
declare module spine {
interface VertexEffect {
begin(skeleton: Skeleton): void;
transform(position: Vector2, uv: Vector2, light: Color, dark: Color): void;
end(): void;
}
}
interface Math {
fround(n: number): number;
}
declare module spine {
abstract class Attachment {
name: string;
constructor(name: string);
abstract copy(): Attachment;
}
abstract class VertexAttachment extends Attachment {
private static nextID;
id: number;
bones: Array<number>;
vertices: ArrayLike<number>;
worldVerticesLength: number;
deformAttachment: VertexAttachment;
constructor(name: string);
computeWorldVertices(slot: Slot, start: number, count: number, worldVertices: ArrayLike<number>, offset: number, stride: number): void;
copyTo(attachment: VertexAttachment): void;
}
}
declare module spine {
interface AttachmentLoader {
newRegionAttachment(skin: Skin, name: string, path: string): RegionAttachment;
newMeshAttachment(skin: Skin, name: string, path: string): MeshAttachment;
newBoundingBoxAttachment(skin: Skin, name: string): BoundingBoxAttachment;
newPathAttachment(skin: Skin, name: string): PathAttachment;
newPointAttachment(skin: Skin, name: string): PointAttachment;
newClippingAttachment(skin: Skin, name: string): ClippingAttachment;
}
}
declare module spine {
enum AttachmentType {
Region = 0,
BoundingBox = 1,
Mesh = 2,
LinkedMesh = 3,
Path = 4,
Point = 5,
Clipping = 6
}
}
declare module spine {
class BoundingBoxAttachment extends VertexAttachment {
color: Color;
constructor(name: string);
copy(): Attachment;
}
}
declare module spine {
class ClippingAttachment extends VertexAttachment {
endSlot: SlotData;
color: Color;
constructor(name: string);
copy(): Attachment;
}
}
declare module spine {
class MeshAttachment extends VertexAttachment {
region: TextureRegion;
path: string;
regionUVs: ArrayLike<number>;
uvs: ArrayLike<number>;
triangles: Array<number>;
color: Color;
width: number;
height: number;
hullLength: number;
edges: Array<number>;
private parentMesh;
tempColor: Color;
constructor(name: string);
updateUVs(): void;
getParentMesh(): MeshAttachment;
setParentMesh(parentMesh: MeshAttachment): void;
copy(): Attachment;
newLinkedMesh(): MeshAttachment;
}
}
declare module spine {
class PathAttachment extends VertexAttachment {
lengths: Array<number>;
closed: boolean;
constantSpeed: boolean;
color: Color;
constructor(name: string);
copy(): Attachment;
}
}
declare module spine {
class PointAttachment extends VertexAttachment {
x: number;
y: number;
rotation: number;
color: Color;
constructor(name: string);
computeWorldPosition(bone: Bone, point: Vector2): Vector2;
computeWorldRotation(bone: Bone): number;
copy(): Attachment;
}
}
declare module spine {
class RegionAttachment extends Attachment {
static OX1: number;
static OY1: number;
static OX2: number;
static OY2: number;
static OX3: number;
static OY3: number;
static OX4: number;
static OY4: number;
static X1: number;
static Y1: number;
static C1R: number;
static C1G: number;
static C1B: number;
static C1A: number;
static U1: number;
static V1: number;
static X2: number;
static Y2: number;
static C2R: number;
static C2G: number;
static C2B: number;
static C2A: number;
static U2: number;
static V2: number;
static X3: number;
static Y3: number;
static C3R: number;
static C3G: number;
static C3B: number;
static C3A: number;
static U3: number;
static V3: number;
static X4: number;
static Y4: number;
static C4R: number;
static C4G: number;
static C4B: number;
static C4A: number;
static U4: number;
static V4: number;
x: number;
y: number;
scaleX: number;
scaleY: number;
rotation: number;
width: number;
height: number;
color: Color;
path: string;
rendererObject: any;
region: TextureRegion;
offset: ArrayLike<number>;
uvs: ArrayLike<number>;
tempColor: Color;
constructor(name: string);
updateOffset(): void;
setRegion(region: TextureRegion): void;
computeWorldVertices(bone: Bone, worldVertices: ArrayLike<number>, offset: number, stride: number): void;
copy(): Attachment;
}
}
declare module spine {
class JitterEffect implements VertexEffect {
jitterX: number;
jitterY: number;
constructor(jitterX: number, jitterY: number);
begin(skeleton: Skeleton): void;
transform(position: Vector2, uv: Vector2, light: Color, dark: Color): void;
end(): void;
}
}
declare module spine {
class SwirlEffect implements VertexEffect {
static interpolation: PowOut;
centerX: number;
centerY: number;
radius: number;
angle: number;
private worldX;
private worldY;
constructor(radius: number);
begin(skeleton: Skeleton): void;
transform(position: Vector2, uv: Vector2, light: Color, dark: Color): void;
end(): void;
}
}
declare module spine.webgl {
class AssetManager extends spine.AssetManager {
constructor(context: ManagedWebGLRenderingContext | WebGLRenderingContext, pathPrefix?: string);
}
}
declare module spine.webgl {
class OrthoCamera {
position: Vector3;
direction: Vector3;
up: Vector3;
near: number;
far: number;
zoom: number;
viewportWidth: number;
viewportHeight: number;
projectionView: Matrix4;
inverseProjectionView: Matrix4;
projection: Matrix4;
view: Matrix4;
private tmp;
constructor(viewportWidth: number, viewportHeight: number);
update(): void;
screenToWorld(screenCoords: Vector3, screenWidth: number, screenHeight: number): Vector3;
setViewport(viewportWidth: number, viewportHeight: number): void;
}
}
declare module spine.webgl {
class GLTexture extends Texture implements Disposable, Restorable {
private context;
private texture;
private boundUnit;
private useMipMaps;
constructor(context: ManagedWebGLRenderingContext | WebGLRenderingContext, image: HTMLImageElement, useMipMaps?: boolean);
setFilters(minFilter: TextureFilter, magFilter: TextureFilter): void;
setWraps(uWrap: TextureWrap, vWrap: TextureWrap): void;
update(useMipMaps: boolean): void;
restore(): void;
bind(unit?: number): void;
unbind(): void;
dispose(): void;
}
}
declare module spine.webgl {
const M00 = 0;
const M01 = 4;
const M02 = 8;
const M03 = 12;
const M10 = 1;
const M11 = 5;
const M12 = 9;
const M13 = 13;
const M20 = 2;
const M21 = 6;
const M22 = 10;
const M23 = 14;
const M30 = 3;
const M31 = 7;
const M32 = 11;
const M33 = 15;
class Matrix4 {
temp: Float32Array;
values: Float32Array;
private static xAxis;
private static yAxis;
private static zAxis;
private static tmpMatrix;
constructor();
set(values: ArrayLike<number>): Matrix4;
transpose(): Matrix4;
identity(): Matrix4;
invert(): Matrix4;
determinant(): number;
translate(x: number, y: number, z: number): Matrix4;
copy(): Matrix4;
projection(near: number, far: number, fovy: number, aspectRatio: number): Matrix4;
ortho2d(x: number, y: number, width: number, height: number): Matrix4;
ortho(left: number, right: number, bottom: number, top: number, near: number, far: number): Matrix4;
multiply(matrix: Matrix4): Matrix4;
multiplyLeft(matrix: Matrix4): Matrix4;
lookAt(position: Vector3, direction: Vector3, up: Vector3): this;
static initTemps(): void;
}
}
declare module spine.webgl {
class Mesh implements Disposable, Restorable {
private attributes;
private context;
private vertices;
private verticesBuffer;
private verticesLength;
private dirtyVertices;
private indices;
private indicesBuffer;
private indicesLength;
private dirtyIndices;
private elementsPerVertex;
getAttributes(): VertexAttribute[];
maxVertices(): number;
numVertices(): number;
setVerticesLength(length: number): void;
getVertices(): Float32Array;
maxIndices(): number;
numIndices(): number;
setIndicesLength(length: number): void;
getIndices(): Uint16Array;
getVertexSizeInFloats(): number;
constructor(context: ManagedWebGLRenderingContext | WebGLRenderingContext, attributes: VertexAttribute[], maxVertices: number, maxIndices: number);
setVertices(vertices: Array<number>): void;
setIndices(indices: Array<number>): void;
draw(shader: Shader, primitiveType: number): void;
drawWithOffset(shader: Shader, primitiveType: number, offset: number, count: number): void;
bind(shader: Shader): void;
unbind(shader: Shader): void;
private update;
restore(): void;
dispose(): void;
}
class VertexAttribute {
name: string;
type: VertexAttributeType;
numElements: number;
constructor(name: string, type: VertexAttributeType, numElements: number);
}
class Position2Attribute extends VertexAttribute {
constructor();
}
class Position3Attribute extends VertexAttribute {
constructor();
}
class TexCoordAttribute extends VertexAttribute {
constructor(unit?: number);
}
class ColorAttribute extends VertexAttribute {
constructor();
}
class Color2Attribute extends VertexAttribute {
constructor();
}
enum VertexAttributeType {
Float = 0
}
}
declare module spine.webgl {
class PolygonBatcher implements Disposable {
private context;
private drawCalls;
private isDrawing;
private mesh;
private shader;
private lastTexture;
private verticesLength;
private indicesLength;
private srcBlend;
private dstBlend;
constructor(context: ManagedWebGLRenderingContext | WebGLRenderingContext, twoColorTint?: boolean, maxVertices?: number);
begin(shader: Shader): void;
setBlendMode(srcBlend: number, dstBlend: number): void;
draw(texture: GLTexture, vertices: ArrayLike<number>, indices: Array<number>): void;
private flush;
end(): void;
getDrawCalls(): number;
dispose(): void;
}
}
declare module spine.webgl {
class SceneRenderer implements Disposable {
context: ManagedWebGLRenderingContext;
canvas: HTMLCanvasElement;
camera: OrthoCamera;
batcher: PolygonBatcher;
private twoColorTint;
private batcherShader;
private shapes;
private shapesShader;
private activeRenderer;
skeletonRenderer: SkeletonRenderer;
skeletonDebugRenderer: SkeletonDebugRenderer;
private QUAD;
private QUAD_TRIANGLES;
private WHITE;
constructor(canvas: HTMLCanvasElement, context: ManagedWebGLRenderingContext | WebGLRenderingContext, twoColorTint?: boolean);
begin(): void;
drawSkeleton(skeleton: Skeleton, premultipliedAlpha?: boolean, slotRangeStart?: number, slotRangeEnd?: number): void;
drawSkeletonDebug(skeleton: Skeleton, premultipliedAlpha?: boolean, ignoredBones?: Array<string>): void;
drawTexture(texture: GLTexture, x: number, y: number, width: number, height: number, color?: Color): void;
drawTextureUV(texture: GLTexture, x: number, y: number, width: number, height: number, u: number, v: number, u2: number, v2: number, color?: Color): void;
drawTextureRotated(texture: GLTexture, x: number, y: number, width: number, height: number, pivotX: number, pivotY: number, angle: number, color?: Color, premultipliedAlpha?: boolean): void;
drawRegion(region: TextureAtlasRegion, x: number, y: number, width: number, height: number, color?: Color, premultipliedAlpha?: boolean): void;
line(x: number, y: number, x2: number, y2: number, color?: Color, color2?: Color): void;
triangle(filled: boolean, x: number, y: number, x2: number, y2: number, x3: number, y3: number, color?: Color, color2?: Color, color3?: Color): void;
quad(filled: boolean, x: number, y: number, x2: number, y2: number, x3: number, y3: number, x4: number, y4: number, color?: Color, color2?: Color, color3?: Color, color4?: Color): void;
rect(filled: boolean, x: number, y: number, width: number, height: number, color?: Color): void;
rectLine(filled: boolean, x1: number, y1: number, x2: number, y2: number, width: number, color?: Color): void;
polygon(polygonVertices: ArrayLike<number>, offset: number, count: number, color?: Color): void;
circle(filled: boolean, x: number, y: number, radius: number, color?: Color, segments?: number): void;
curve(x1: number, y1: number, cx1: number, cy1: number, cx2: number, cy2: number, x2: number, y2: number, segments: number, color?: Color): void;
end(): void;
resize(resizeMode: ResizeMode): void;
private enableRenderer;
dispose(): void;
}
enum ResizeMode {
Stretch = 0,
Expand = 1,
Fit = 2
}
}
declare module spine.webgl {
class Shader implements Disposable, Restorable {
private vertexShader;
private fragmentShader;
static MVP_MATRIX: string;
static POSITION: string;
static COLOR: string;
static COLOR2: string;
static TEXCOORDS: string;
static SAMPLER: string;
private context;
private vs;
private vsSource;
private fs;
private fsSource;
private program;
private tmp2x2;
private tmp3x3;
private tmp4x4;
getProgram(): WebGLProgram;
getVertexShader(): string;
getFragmentShader(): string;
getVertexShaderSource(): string;
getFragmentSource(): string;
constructor(context: ManagedWebGLRenderingContext | WebGLRenderingContext, vertexShader: string, fragmentShader: string);
private compile;
private compileShader;
private compileProgram;
restore(): void;
bind(): void;
unbind(): void;
setUniformi(uniform: string, value: number): void;
setUniformf(uniform: string, value: number): void;
setUniform2f(uniform: string, value: number, value2: number): void;
setUniform3f(uniform: string, value: number, value2: number, value3: number): void;
setUniform4f(uniform: string, value: number, value2: number, value3: number, value4: number): void;
setUniform2x2f(uniform: string, value: ArrayLike<number>): void;
setUniform3x3f(uniform: string, value: ArrayLike<number>): void;
setUniform4x4f(uniform: string, value: ArrayLike<number>): void;
getUniformLocation(uniform: string): WebGLUniformLocation;
getAttributeLocation(attribute: string): number;
dispose(): void;
static newColoredTextured(context: ManagedWebGLRenderingContext | WebGLRenderingContext): Shader;
static newTwoColoredTextured(context: ManagedWebGLRenderingContext | WebGLRenderingContext): Shader;
static newColored(context: ManagedWebGLRenderingContext | WebGLRenderingContext): Shader;
}
}
declare module spine.webgl {
class ShapeRenderer implements Disposable {
private context;
private isDrawing;
private mesh;
private shapeType;
private color;
private shader;
private vertexIndex;
private tmp;
private srcBlend;
private dstBlend;
constructor(context: ManagedWebGLRenderingContext | WebGLRenderingContext, maxVertices?: number);
begin(shader: Shader): void;
setBlendMode(srcBlend: number, dstBlend: number): void;
setColor(color: Color): void;
setColorWith(r: number, g: number, b: number, a: number): void;
point(x: number, y: number, color?: Color): void;
line(x: number, y: number, x2: number, y2: number, color?: Color): void;
triangle(filled: boolean, x: number, y: number, x2: number, y2: number, x3: number, y3: number, color?: Color, color2?: Color, color3?: Color): void;
quad(filled: boolean, x: number, y: number, x2: number, y2: number, x3: number, y3: number, x4: number, y4: number, color?: Color, color2?: Color, color3?: Color, color4?: Color): void;
rect(filled: boolean, x: number, y: number, width: number, height: number, color?: Color): void;
rectLine(filled: boolean, x1: number, y1: number, x2: number, y2: number, width: number, color?: Color): void;
x(x: number, y: number, size: number): void;
polygon(polygonVertices: ArrayLike<number>, offset: number, count: number, color?: Color): void;
circle(filled: boolean, x: number, y: number, radius: number, color?: Color, segments?: number): void;
curve(x1: number, y1: number, cx1: number, cy1: number, cx2: number, cy2: number, x2: number, y2: number, segments: number, color?: Color): void;
private vertex;
end(): void;
private flush;
private check;
dispose(): void;
}
enum ShapeType {
Point = 0,
Line = 1,
Filled = 4
}
}
declare module spine.webgl {
class SkeletonDebugRenderer implements Disposable {
boneLineColor: Color;
boneOriginColor: Color;
attachmentLineColor: Color;
triangleLineColor: Color;
pathColor: Color;
clipColor: Color;
aabbColor: Color;
drawBones: boolean;
drawRegionAttachments: boolean;
drawBoundingBoxes: boolean;
drawMeshHull: boolean;
drawMeshTriangles: boolean;
drawPaths: boolean;
drawSkeletonXY: boolean;
drawClipping: boolean;
premultipliedAlpha: boolean;
scale: number;
boneWidth: number;
private context;
private bounds;
private temp;
private vertices;
private static LIGHT_GRAY;
private static GREEN;
constructor(context: ManagedWebGLRenderingContext | WebGLRenderingContext);
draw(shapes: ShapeRenderer, skeleton: Skeleton, ignoredBones?: Array<string>): void;
dispose(): void;
}
}
declare module spine.webgl {
class SkeletonRenderer {
static QUAD_TRIANGLES: number[];
premultipliedAlpha: boolean;
vertexEffect: VertexEffect;
private tempColor;
private tempColor2;
private vertices;
private vertexSize;
private twoColorTint;
private renderable;
private clipper;
private temp;
private temp2;
private temp3;
private temp4;
constructor(context: ManagedWebGLRenderingContext, twoColorTint?: boolean);
draw(batcher: PolygonBatcher, skeleton: Skeleton, slotRangeStart?: number, slotRangeEnd?: number): void;
}
}
declare module spine.webgl {
class Vector3 {
x: number;
y: number;
z: number;
constructor(x?: number, y?: number, z?: number);
setFrom(v: Vector3): Vector3;
set(x: number, y: number, z: number): Vector3;
add(v: Vector3): Vector3;
sub(v: Vector3): Vector3;
scale(s: number): Vector3;
normalize(): Vector3;
cross(v: Vector3): Vector3;
multiply(matrix: Matrix4): Vector3;
project(matrix: Matrix4): Vector3;
dot(v: Vector3): number;
length(): number;
distance(v: Vector3): number;
}
}
declare module spine.webgl {
class ManagedWebGLRenderingContext {
canvas: HTMLCanvasElement | OffscreenCanvas;
gl: WebGLRenderingContext;
private restorables;
constructor(canvasOrContext: HTMLCanvasElement | WebGLRenderingContext, contextConfig?: any);
addRestorable(restorable: Restorable): void;
removeRestorable(restorable: Restorable): void;
}
class WebGLBlendModeConverter {
static ZERO: number;
static ONE: number;
static SRC_COLOR: number;
static ONE_MINUS_SRC_COLOR: number;
static SRC_ALPHA: number;
static ONE_MINUS_SRC_ALPHA: number;
static DST_ALPHA: number;
static ONE_MINUS_DST_ALPHA: number;
static DST_COLOR: number;
static getDestGLBlendMode(blendMode: BlendMode): number;
static getSourceGLBlendMode(blendMode: BlendMode, premultipliedAlpha?: boolean): number;
}
}
| {
"pile_set_name": "Github"
} |
KEYCTL_SUPPORTS_ENCRYPT 0x01
KEYCTL_SUPPORTS_DECRYPT 0x02
KEYCTL_SUPPORTS_SIGN 0x04
KEYCTL_SUPPORTS_VERIFY 0x08
| {
"pile_set_name": "Github"
} |
/*
* Dice heroes is a turn based rpg-strategy game where characters are dice.
* Copyright (C) 2016 Vladislav Protsenko
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.vlaaad.dice.game.tutorial.tasks;
import com.vlaaad.common.gdx.App;
import com.vlaaad.common.tutorial.TutorialTask;
import com.vlaaad.dice.DiceHeroes;
import com.vlaaad.dice.states.GameMapState;
/**
* Created 07.11.13 by vlaaad
*/
public class InitMapStateTask extends TutorialTask {
@Override public void start(Callback callback) {
App app = resources.get("app");
DiceHeroes diceHeroes = (DiceHeroes) app;
GameMapState mapState = (GameMapState) app.getState();
resources.put("map", mapState);
resources.put("userData", diceHeroes.userData);
resources.put("stage", mapState.stage);
callback.taskEnded();
}
}
| {
"pile_set_name": "Github"
} |
Objects type and coordinates
1 (forest): a201 (begin)
Types:
01, 02, 03 - boar
04 - deer
05 - 3 flies
06 - snake
07 - snake
08 - 3 flies
09 - snake
0a - apple (bonus)
0b - apple (bonus)
0c - 2 bees
0d - apple (bonus)
0e - 2 bees
0f - apple (bonus)
2 (underground): dd33 (begin)
Types:
01 - pouch (bonus)
02 - snake
03 - scorpion
04 - pouch (bonus)
05 - zombie
06 - fire
07 - fire
08 - volcano
09 - zombie
0a - bat
0b - worm
0c - box
0d - bat
0e - zombie
0f - volcano
3 (underground2): e73b (begin)
Types:
01 - zombie
02 - bat
03 - worm
04 - worm
05 - fire
06 - fire
07 - zombie
08 - key (item)
09 - ghost
0a - bat
0b - zombie
0c - ghost
0d - fire
0e - ghost
0f - fire
| {
"pile_set_name": "Github"
} |
{
"items": [
{
"action": "pushItemHandler",
"controlKind": "push",
"identifier": "push-item",
"keyEquivalent": "p",
"keyEquivalentModifier": ["command", "shift"],
"menuTitle": "Push Menu Item",
"title": "Bold Push Item",
"macOSUsesAttributedTitle": true,
"usesAttributedTitleInMenu": false,
"toolTip": "The push button's tool-tip.",
"isHidden": false
},
{
"action": "actionItemHandler",
"controlKind": "action",
"usesAttributedTitle": false,
"identifier": "action-item",
"keyEquivalent": "a",
"keyEquivalentModifier": ["command", "shift"],
"title": "Action Item",
"toolTip": "The action button's tool-tip.",
"usesToolTipInMenu": false,
"subitems": [
{
"action": "firstActionSubitemHandler",
"usesAttributedTitle": false,
"identifier": "first-action-subitem",
"imageName": "hand.thumbsup",
"keyEquivalent": "1",
"keyEquivalentModifier": ["command"],
"title": "First Action Subitem",
"toolTip": "The first action's tool-tip."
},
{
"action": "secondActionSubitemHandler",
"usesAttributedTitle": false,
"identifier": "second-action-subitem",
"imageName": "hand.thumbsdown",
"keyEquivalent": "2",
"keyEquivalentModifier": ["command"],
"title": "Second Action Subitem",
"toolTip": "The second action's tool-tip."
}
]
},
{
"action": "segmentedItemHandler",
"controlKind": "segmented",
"usesAttributedTitle": false,
"keyEquivalent": "s",
"keyEquivalentModifier": ["command", "shift"],
"title": "Segmented Item",
"toolTip": "The segmented button's tool-tip.",
"subitems": [
{
"action": "firstSegmentedSubitemHandler",
"usesAttributedTitle": false,
"identifier": "first-segmented-subitem",
"imageName": "chevron-left",
"keyEquivalent": "3",
"keyEquivalentModifier": ["command"],
"title": "First Segmented Subitem",
"toolTip": "The first segment's tool-tip."
},
{
"action": "secondSegmentedSubitemHandler",
"usesAttributedTitle": false,
"identifier": "second-segmented-subitem",
"imageName": "chevron-right",
"keyEquivalent": "4",
"keyEquivalentModifier": ["command"],
"title": "Second Segmented Subitem",
"toolTip": "The second segment's tool-tip."
}
]
}
],
"toolbar": {
"allowsUserCustomization": true,
"displayMode": "iconOnly",
"isVisible": true,
"sizeMode": "regular",
"identifier": "com.bigzlabs.RibbonDemo",
"defaultItems" : ["push-item", "NSToolbarFlexibleSpaceItem", "action-item", "Segmented Item"]
}
}
| {
"pile_set_name": "Github"
} |
target triple = "wasm32-unknown-unknown"
@indirect_bar = internal local_unnamed_addr global i64 ()* @bar, align 4
@indirect_foo = internal local_unnamed_addr global i32 ()* @foo, align 4
declare i32 @foo() local_unnamed_addr
define i64 @bar() {
entry:
ret i64 1
}
define void @call_bar_indirect() local_unnamed_addr #1 {
entry:
%0 = load i64 ()*, i64 ()** @indirect_bar, align 4
%1 = load i32 ()*, i32 ()** @indirect_foo, align 4
%call0 = tail call i64 %0() #2
%call1 = tail call i32 %1() #2
ret void
}
| {
"pile_set_name": "Github"
} |
/*
*
* Copyright 2017 gRPC authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
// Package balancer defines APIs for load balancing in gRPC.
// All APIs in this package are experimental.
package balancer
import (
"context"
"encoding/json"
"errors"
"net"
"strings"
"google.golang.org/grpc/connectivity"
"google.golang.org/grpc/credentials"
"google.golang.org/grpc/internal"
"google.golang.org/grpc/metadata"
"google.golang.org/grpc/resolver"
"google.golang.org/grpc/serviceconfig"
)
var (
// m is a map from name to balancer builder.
m = make(map[string]Builder)
)
// Register registers the balancer builder to the balancer map. b.Name
// (lowercased) will be used as the name registered with this builder. If the
// Builder implements ConfigParser, ParseConfig will be called when new service
// configs are received by the resolver, and the result will be provided to the
// Balancer in UpdateClientConnState.
//
// NOTE: this function must only be called during initialization time (i.e. in
// an init() function), and is not thread-safe. If multiple Balancers are
// registered with the same name, the one registered last will take effect.
func Register(b Builder) {
m[strings.ToLower(b.Name())] = b
}
// unregisterForTesting deletes the balancer with the given name from the
// balancer map.
//
// This function is not thread-safe.
func unregisterForTesting(name string) {
delete(m, name)
}
func init() {
internal.BalancerUnregister = unregisterForTesting
}
// Get returns the resolver builder registered with the given name.
// Note that the compare is done in a case-insensitive fashion.
// If no builder is register with the name, nil will be returned.
func Get(name string) Builder {
if b, ok := m[strings.ToLower(name)]; ok {
return b
}
return nil
}
// SubConn represents a gRPC sub connection.
// Each sub connection contains a list of addresses. gRPC will
// try to connect to them (in sequence), and stop trying the
// remainder once one connection is successful.
//
// The reconnect backoff will be applied on the list, not a single address.
// For example, try_on_all_addresses -> backoff -> try_on_all_addresses.
//
// All SubConns start in IDLE, and will not try to connect. To trigger
// the connecting, Balancers must call Connect.
// When the connection encounters an error, it will reconnect immediately.
// When the connection becomes IDLE, it will not reconnect unless Connect is
// called.
//
// This interface is to be implemented by gRPC. Users should not need a
// brand new implementation of this interface. For the situations like
// testing, the new implementation should embed this interface. This allows
// gRPC to add new methods to this interface.
type SubConn interface {
// UpdateAddresses updates the addresses used in this SubConn.
// gRPC checks if currently-connected address is still in the new list.
// If it's in the list, the connection will be kept.
// If it's not in the list, the connection will gracefully closed, and
// a new connection will be created.
//
// This will trigger a state transition for the SubConn.
UpdateAddresses([]resolver.Address)
// Connect starts the connecting for this SubConn.
Connect()
}
// NewSubConnOptions contains options to create new SubConn.
type NewSubConnOptions struct {
// CredsBundle is the credentials bundle that will be used in the created
// SubConn. If it's nil, the original creds from grpc DialOptions will be
// used.
CredsBundle credentials.Bundle
// HealthCheckEnabled indicates whether health check service should be
// enabled on this SubConn
HealthCheckEnabled bool
}
// ClientConn represents a gRPC ClientConn.
//
// This interface is to be implemented by gRPC. Users should not need a
// brand new implementation of this interface. For the situations like
// testing, the new implementation should embed this interface. This allows
// gRPC to add new methods to this interface.
type ClientConn interface {
// NewSubConn is called by balancer to create a new SubConn.
// It doesn't block and wait for the connections to be established.
// Behaviors of the SubConn can be controlled by options.
NewSubConn([]resolver.Address, NewSubConnOptions) (SubConn, error)
// RemoveSubConn removes the SubConn from ClientConn.
// The SubConn will be shutdown.
RemoveSubConn(SubConn)
// UpdateBalancerState is called by balancer to notify gRPC that some internal
// state in balancer has changed.
//
// gRPC will update the connectivity state of the ClientConn, and will call pick
// on the new picker to pick new SubConn.
UpdateBalancerState(s connectivity.State, p Picker)
// ResolveNow is called by balancer to notify gRPC to do a name resolving.
ResolveNow(resolver.ResolveNowOption)
// Target returns the dial target for this ClientConn.
//
// Deprecated: Use the Target field in the BuildOptions instead.
Target() string
}
// BuildOptions contains additional information for Build.
type BuildOptions struct {
// DialCreds is the transport credential the Balancer implementation can
// use to dial to a remote load balancer server. The Balancer implementations
// can ignore this if it does not need to talk to another party securely.
DialCreds credentials.TransportCredentials
// CredsBundle is the credentials bundle that the Balancer can use.
CredsBundle credentials.Bundle
// Dialer is the custom dialer the Balancer implementation can use to dial
// to a remote load balancer server. The Balancer implementations
// can ignore this if it doesn't need to talk to remote balancer.
Dialer func(context.Context, string) (net.Conn, error)
// ChannelzParentID is the entity parent's channelz unique identification number.
ChannelzParentID int64
// Target contains the parsed address info of the dial target. It is the same resolver.Target as
// passed to the resolver.
// See the documentation for the resolver.Target type for details about what it contains.
Target resolver.Target
}
// Builder creates a balancer.
type Builder interface {
// Build creates a new balancer with the ClientConn.
Build(cc ClientConn, opts BuildOptions) Balancer
// Name returns the name of balancers built by this builder.
// It will be used to pick balancers (for example in service config).
Name() string
}
// ConfigParser parses load balancer configs.
type ConfigParser interface {
// ParseConfig parses the JSON load balancer config provided into an
// internal form or returns an error if the config is invalid. For future
// compatibility reasons, unknown fields in the config should be ignored.
ParseConfig(LoadBalancingConfigJSON json.RawMessage) (serviceconfig.LoadBalancingConfig, error)
}
// PickOptions contains addition information for the Pick operation.
type PickOptions struct {
// FullMethodName is the method name that NewClientStream() is called
// with. The canonical format is /service/Method.
FullMethodName string
}
// DoneInfo contains additional information for done.
type DoneInfo struct {
// Err is the rpc error the RPC finished with. It could be nil.
Err error
// Trailer contains the metadata from the RPC's trailer, if present.
Trailer metadata.MD
// BytesSent indicates if any bytes have been sent to the server.
BytesSent bool
// BytesReceived indicates if any byte has been received from the server.
BytesReceived bool
// ServerLoad is the load received from server. It's usually sent as part of
// trailing metadata.
//
// The only supported type now is *orca_v1.LoadReport.
ServerLoad interface{}
}
var (
// ErrNoSubConnAvailable indicates no SubConn is available for pick().
// gRPC will block the RPC until a new picker is available via UpdateBalancerState().
ErrNoSubConnAvailable = errors.New("no SubConn is available")
// ErrTransientFailure indicates all SubConns are in TransientFailure.
// WaitForReady RPCs will block, non-WaitForReady RPCs will fail.
ErrTransientFailure = errors.New("all SubConns are in TransientFailure")
)
// Picker is used by gRPC to pick a SubConn to send an RPC.
// Balancer is expected to generate a new picker from its snapshot every time its
// internal state has changed.
//
// The pickers used by gRPC can be updated by ClientConn.UpdateBalancerState().
type Picker interface {
// Pick returns the SubConn to be used to send the RPC.
// The returned SubConn must be one returned by NewSubConn().
//
// This functions is expected to return:
// - a SubConn that is known to be READY;
// - ErrNoSubConnAvailable if no SubConn is available, but progress is being
// made (for example, some SubConn is in CONNECTING mode);
// - other errors if no active connecting is happening (for example, all SubConn
// are in TRANSIENT_FAILURE mode).
//
// If a SubConn is returned:
// - If it is READY, gRPC will send the RPC on it;
// - If it is not ready, or becomes not ready after it's returned, gRPC will
// block until UpdateBalancerState() is called and will call pick on the
// new picker. The done function returned from Pick(), if not nil, will be
// called with nil error, no bytes sent and no bytes received.
//
// If the returned error is not nil:
// - If the error is ErrNoSubConnAvailable, gRPC will block until UpdateBalancerState()
// - If the error is ErrTransientFailure:
// - If the RPC is wait-for-ready, gRPC will block until UpdateBalancerState()
// is called to pick again;
// - Otherwise, RPC will fail with unavailable error.
// - Else (error is other non-nil error):
// - The RPC will fail with unavailable error.
//
// The returned done() function will be called once the rpc has finished,
// with the final status of that RPC. If the SubConn returned is not a
// valid SubConn type, done may not be called. done may be nil if balancer
// doesn't care about the RPC status.
Pick(ctx context.Context, opts PickOptions) (conn SubConn, done func(DoneInfo), err error)
}
// Balancer takes input from gRPC, manages SubConns, and collects and aggregates
// the connectivity states.
//
// It also generates and updates the Picker used by gRPC to pick SubConns for RPCs.
//
// HandleSubConnectionStateChange, HandleResolvedAddrs and Close are guaranteed
// to be called synchronously from the same goroutine.
// There's no guarantee on picker.Pick, it may be called anytime.
type Balancer interface {
// HandleSubConnStateChange is called by gRPC when the connectivity state
// of sc has changed.
// Balancer is expected to aggregate all the state of SubConn and report
// that back to gRPC.
// Balancer should also generate and update Pickers when its internal state has
// been changed by the new state.
//
// Deprecated: if V2Balancer is implemented by the Balancer,
// UpdateSubConnState will be called instead.
HandleSubConnStateChange(sc SubConn, state connectivity.State)
// HandleResolvedAddrs is called by gRPC to send updated resolved addresses to
// balancers.
// Balancer can create new SubConn or remove SubConn with the addresses.
// An empty address slice and a non-nil error will be passed if the resolver returns
// non-nil error to gRPC.
//
// Deprecated: if V2Balancer is implemented by the Balancer,
// UpdateClientConnState will be called instead.
HandleResolvedAddrs([]resolver.Address, error)
// Close closes the balancer. The balancer is not required to call
// ClientConn.RemoveSubConn for its existing SubConns.
Close()
}
// SubConnState describes the state of a SubConn.
type SubConnState struct {
ConnectivityState connectivity.State
// TODO: add last connection error
}
// ClientConnState describes the state of a ClientConn relevant to the
// balancer.
type ClientConnState struct {
ResolverState resolver.State
// The parsed load balancing configuration returned by the builder's
// ParseConfig method, if implemented.
BalancerConfig serviceconfig.LoadBalancingConfig
}
// V2Balancer is defined for documentation purposes. If a Balancer also
// implements V2Balancer, its UpdateClientConnState method will be called
// instead of HandleResolvedAddrs and its UpdateSubConnState will be called
// instead of HandleSubConnStateChange.
type V2Balancer interface {
// UpdateClientConnState is called by gRPC when the state of the ClientConn
// changes.
UpdateClientConnState(ClientConnState)
// UpdateSubConnState is called by gRPC when the state of a SubConn
// changes.
UpdateSubConnState(SubConn, SubConnState)
// Close closes the balancer. The balancer is not required to call
// ClientConn.RemoveSubConn for its existing SubConns.
Close()
}
// ConnectivityStateEvaluator takes the connectivity states of multiple SubConns
// and returns one aggregated connectivity state.
//
// It's not thread safe.
type ConnectivityStateEvaluator struct {
numReady uint64 // Number of addrConns in ready state.
numConnecting uint64 // Number of addrConns in connecting state.
numTransientFailure uint64 // Number of addrConns in transientFailure.
}
// RecordTransition records state change happening in subConn and based on that
// it evaluates what aggregated state should be.
//
// - If at least one SubConn in Ready, the aggregated state is Ready;
// - Else if at least one SubConn in Connecting, the aggregated state is Connecting;
// - Else the aggregated state is TransientFailure.
//
// Idle and Shutdown are not considered.
func (cse *ConnectivityStateEvaluator) RecordTransition(oldState, newState connectivity.State) connectivity.State {
// Update counters.
for idx, state := range []connectivity.State{oldState, newState} {
updateVal := 2*uint64(idx) - 1 // -1 for oldState and +1 for new.
switch state {
case connectivity.Ready:
cse.numReady += updateVal
case connectivity.Connecting:
cse.numConnecting += updateVal
case connectivity.TransientFailure:
cse.numTransientFailure += updateVal
}
}
// Evaluate.
if cse.numReady > 0 {
return connectivity.Ready
}
if cse.numConnecting > 0 {
return connectivity.Connecting
}
return connectivity.TransientFailure
}
| {
"pile_set_name": "Github"
} |
๏ปฟ<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<data name="$this.Text" xml:space="preserve">
<value>Envio de arquivos JIRA</value>
</data>
<data name="btnCancel.Text" xml:space="preserve">
<value>Cancelar</value>
</data>
<data name="btnUpload.Text" xml:space="preserve">
<value>Enviar</value>
</data>
<data name="gpSummary.Text" xml:space="preserve">
<value>Sumรกrio</value>
</data>
<data name="lblIssueId.Text" xml:space="preserve">
<value>ID da Questรฃo:</value>
</data>
</root> | {
"pile_set_name": "Github"
} |
/*
* MIT License
*
* Copyright (c) 2015 Douglas Nassif Roma Junior
*
* 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.
*/
package com.github.douglasjunior.bluetoothsamplekotlin;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.ColorMatrix;
import android.graphics.ColorMatrixColorFilter;
import android.graphics.Paint;
/**
* Created by douglas on 30/05/17.
*/
public final class BitmapHelper {
private BitmapHelper(){}
/**
* From https://stackoverflow.com/a/17887577/2826279
*
* @param bmp input bitmap
* @param contrast 0..10 1 is default
* @param brightness -255..255 0 is default
* @return new bitmap
*/
public static Bitmap changeBitmapContrastBrightness(Bitmap bmp, float contrast, float brightness) {
ColorMatrix cm = new ColorMatrix(new float[]
{
contrast, 0, 0, 0, brightness,
0, contrast, 0, 0, brightness,
0, 0, contrast, 0, brightness,
0, 0, 0, 1, 0
});
Bitmap ret = Bitmap.createBitmap(bmp.getWidth(), bmp.getHeight(), bmp.getConfig());
Canvas canvas = new Canvas(ret);
Paint paint = new Paint();
paint.setColorFilter(new ColorMatrixColorFilter(cm));
canvas.drawBitmap(bmp, 0, 0, paint);
return ret;
}
public static Bitmap changeBitmapBlackWhite(Bitmap bmp) {
ColorMatrix cm = new ColorMatrix(new float[]
{
1.5f, 1.5f, 1.5f, 0, 0,
1.5f, 1.5f, 1.5f, 0, 0,
1.5f, 1.5f, 1.5f, 0, 0,
0, 0, 0, 1, 0
});
cm.setSaturation(0);
Bitmap ret = Bitmap.createBitmap(bmp.getWidth(), bmp.getHeight(), bmp.getConfig());
Canvas canvas = new Canvas(ret);
Paint paint = new Paint();
paint.setColorFilter(new ColorMatrixColorFilter(cm));
canvas.drawBitmap(bmp, 0, 0, paint);
return ret;
}
}
| {
"pile_set_name": "Github"
} |
swagger: "2.0"
host: api.postmarkapp.com
basePath: /
info:
description: >
Postmark makes sending and receiving email
incredibly easy.
title: Postmark API
version: 1.0.0
x-apisguru-categories:
- email
x-logo:
url: https://pbs.twimg.com/profile_images/879295889185157120/ZYlwxzeY_400x400.jpg
x-origin:
- format: swagger
url: https://postmarkapp.com/swagger/server.yml
version: "2.0"
x-providerName: postmarkapp.com
x-serviceName: server
consumes:
- application/json
produces:
- application/json
responses:
"422":
description: An error was generated due to incorrect use of the API. See the Message associated with this response for more information.
schema:
$ref: "#/definitions/StandardPostmarkResponse"
"500":
description: Indicates an internal server error occurred.
paths:
/bounces:
get:
operationId: getBounces
parameters:
- description: The token associated with the Server on which this request will operate.
in: header
name: X-Postmark-Server-Token
required: true
type: string
- description: Number of bounces to return per request. Max 500.
in: query
maximum: 500
name: count
required: true
type: integer
- description: Number of bounces to skip.
in: query
name: offset
required: true
type: integer
- description: Filter by type of bounce
enum:
- HardBounce
- Transient
- Unsubscribe
- Subscribe
- AutoResponder
- AddressChange
- DnsError
- SpamNotification
- OpenRelayTest
- Unknown
- SoftBounce
- VirusNotification
- MailFrontier Matador.
- BadEmailAddress
- SpamComplaint
- ManuallyDeactivated
- Unconfirmed
- Blocked
- SMTPApiError
- InboundError
- DMARCPolicy
- TemplateRenderingFailed
in: query
name: type
type: string
- description: Filter by emails that were deactivated by Postmark due to the bounce. Set to true or false. If this isn't specified it will return both active and inactive.
in: query
name: inactive
type: boolean
- description: Filter by email address
format: email
in: query
name: emailFilter
type: string
- description: Filter by messageID
in: query
name: messageID
type: string
- description: Filter by tag
in: query
name: tag
type: string
- description: Filter messages up to the date specified. e.g. `2014-02-01`
format: date
in: query
name: todate
type: string
- description: Filter messages starting from the date specified. e.g. `2014-02-01`
format: date
in: query
name: fromdate
type: string
responses:
"200":
description: OK
schema:
$ref: "#/definitions/BounceSearchResponse"
"422":
$ref: "#/responses/422"
"500":
$ref: "#/responses/500"
summary: Get bounces
tags:
- Bounces API
/bounces/tags:
get:
operationId: getBouncedTags
parameters:
- description: The token associated with the Server on which this request will operate.
in: header
name: X-Postmark-Server-Token
required: true
type: string
responses:
"200":
description: OK
schema:
items:
type: string
type: array
"422":
$ref: "#/responses/422"
"500":
$ref: "#/responses/500"
summary: Get bounced tags
tags:
- Bounces API
"/bounces/{bounceid}":
get:
operationId: getSingleBounce
parameters:
- description: The token associated with the Server on which this request will operate.
in: header
name: X-Postmark-Server-Token
required: true
type: string
- description: The ID of the bounce to retrieve.
format: int64
in: path
name: bounceid
required: true
type: integer
responses:
"200":
description: OK
schema:
$ref: "#/definitions/BounceInfoResponse"
"422":
$ref: "#/responses/422"
"500":
$ref: "#/responses/500"
summary: Get a single bounce
tags:
- Bounces API
"/bounces/{bounceid}/activate":
put:
operationId: activateBounce
parameters:
- description: The token associated with the Server on which this request will operate.
in: header
name: X-Postmark-Server-Token
required: true
type: string
- description: The ID of the Bounce to activate.
format: int64
in: path
name: bounceid
required: true
type: integer
responses:
"200":
description: OK
schema:
$ref: "#/definitions/BounceActivationResponse"
"422":
$ref: "#/responses/422"
"500":
$ref: "#/responses/500"
summary: Activate a bounce
tags:
- Bounces API
"/bounces/{bounceid}/dump":
get:
parameters:
- description: The token associated with the Server on which this request will operate.
in: header
name: X-Postmark-Server-Token
required: true
type: string
- description: The ID for the bounce dump to retrieve.
format: int64
in: path
name: bounceid
required: true
type: integer
responses:
"200":
description: OK
schema:
$ref: "#/definitions/BounceDumpResponse"
"422":
$ref: "#/responses/422"
"500":
$ref: "#/responses/500"
summary: Get bounce dump
tags:
- Bounces API
/deliverystats:
get:
operationId: getDeliveryStats
parameters:
- description: The token associated with the Server on which this request will operate.
in: header
name: X-Postmark-Server-Token
required: true
type: string
responses:
"200":
description: OK
schema:
$ref: "#/definitions/DeliveryStatsResponse"
"422":
$ref: "#/responses/422"
"500":
$ref: "#/responses/500"
summary: Get delivery stats
tags:
- Bounces API
/email:
post:
operationId: sendEmail
parameters:
- description: The token associated with the Server on which this request will operate.
in: header
name: X-Postmark-Server-Token
required: true
type: string
- in: body
name: body
schema:
$ref: "#/definitions/SendEmailRequest"
responses:
"200":
description: OK
schema:
$ref: "#/definitions/SendEmailResponse"
"422":
$ref: "#/responses/422"
"500":
$ref: "#/responses/500"
summary: Send a single email
tags:
- Sending API
/email/batch:
post:
operationId: sendEmailBatch
parameters:
- description: The token associated with the Server on which this request will operate.
in: header
name: X-Postmark-Server-Token
required: true
type: string
- in: body
name: body
schema:
$ref: "#/definitions/SendEmailBatchRequest"
responses:
"200":
description: OK
schema:
$ref: "#/definitions/SendEmailBatchResponse"
"422":
$ref: "#/responses/422"
"500":
$ref: "#/responses/500"
summary: Send a batch of emails
tags:
- Sending API
/email/batchWithTemplates:
post:
operationId: sendEmailBatchWithTemplates
parameters:
- description: The token associated with the Server on which this request will operate.
in: header
name: X-Postmark-Server-Token
required: true
type: string
- in: body
name: body
required: true
schema:
$ref: "#/definitions/SendEmailTemplatedBatchRequest"
responses:
"200":
description: OK
schema:
$ref: "#/definitions/SendEmailBatchResponse"
"422":
$ref: "#/responses/422"
"500":
$ref: "#/responses/500"
summary: Send a batch of email using templates.
tags:
- Sending API
- Templates API
/email/withTemplate:
post:
operationId: sendEmailWithTemplate
parameters:
- description: The token associated with the Server on which this request will operate.
in: header
name: X-Postmark-Server-Token
required: true
type: string
- in: body
name: body
required: true
schema:
$ref: "#/definitions/EmailWithTemplateRequest"
responses:
"200":
description: OK
schema:
$ref: "#/definitions/SendEmailResponse"
"422":
$ref: "#/responses/422"
"500":
$ref: "#/responses/500"
summary: Send an email using a Template
tags:
- Sending API
- Templates API
/messages/inbound:
get:
operationId: searchInboundMessages
parameters:
- description: The token associated with the Server on which this request will operate.
in: header
name: X-Postmark-Server-Token
required: true
type: string
- description: Number of messages to return per request. Max 500.
in: query
name: count
required: true
type: integer
- description: Number of messages to skip
in: query
name: offset
required: true
type: integer
- description: Filter by the user who was receiving the email
format: email
in: query
name: recipient
type: string
- description: Filter by the sender email address
format: email
in: query
name: fromemail
type: string
- description: Filter by email subject
in: query
name: subject
type: string
- description: Filter by mailboxhash
in: query
name: mailboxhash
type: string
- description: Filter by tag
in: query
name: tag
type: string
- description: Filter by status (`blocked`, `processed`, `queued`, `failed`, `scheduled`)
enum:
- blocked
- processed
- queued
- failed
- scheduled
in: query
name: status
type: string
- description: Filter messages up to the date specified. e.g. `2014-02-01`
format: date
in: query
name: todate
type: string
- description: Filter messages starting from the date specified. e.g. `2014-02-01`
format: date
in: query
name: fromdate
type: string
responses:
"200":
description: OK
schema:
$ref: "#/definitions/InboundSearchResponse"
"422":
$ref: "#/responses/422"
"500":
$ref: "#/responses/500"
summary: Inbound message search
tags:
- Messages API
"/messages/inbound/{messageid}/bypass":
put:
operationId: bypassRulesForInboundMessage
parameters:
- description: The token associated with the Server on which this request will operate.
in: header
name: X-Postmark-Server-Token
required: true
type: string
- description: The ID of the message which should bypass inbound rules.
in: path
name: messageid
required: true
type: string
responses:
"200":
description: OK
schema:
$ref: "#/definitions/StandardPostmarkResponse"
"422":
$ref: "#/responses/422"
"500":
$ref: "#/responses/500"
summary: Bypass rules for a blocked inbound message
tags:
- Messages API
"/messages/inbound/{messageid}/details":
get:
operationId: getInboundMessageDetails
parameters:
- description: The token associated with the Server on which this request will operate.
in: header
name: X-Postmark-Server-Token
required: true
type: string
- description: The ID of the message for which to details will be retrieved.
in: path
name: messageid
required: true
type: string
responses:
"200":
description: OK
schema:
$ref: "#/definitions/InboundMessageFullDetailsResponse"
"422":
$ref: "#/responses/422"
"500":
$ref: "#/responses/500"
summary: Inbound message details
tags:
- Messages API
"/messages/inbound/{messageid}/retry":
put:
operationId: retryInboundMessageProcessing
parameters:
- description: The token associated with the Server on which this request will operate.
in: header
name: X-Postmark-Server-Token
required: true
type: string
- description: The ID of the inbound message on which we should retry processing.
in: path
name: messageid
required: true
type: string
responses:
"200":
description: OK
schema:
$ref: "#/definitions/StandardPostmarkResponse"
"422":
$ref: "#/responses/422"
"500":
$ref: "#/responses/500"
summary: Retry a failed inbound message for processing
tags:
- Messages API
/messages/outbound:
get:
operationId: searchOutboundMessages
parameters:
- description: The token associated with the Server on which this request will operate.
in: header
name: X-Postmark-Server-Token
required: true
type: string
- description: Number of messages to return per request. Max 500.
in: query
name: count
required: true
type: integer
- description: Number of messages to skip
in: query
name: offset
required: true
type: integer
- description: Filter by the user who was receiving the email
format: email
in: query
name: recipient
type: string
- description: Filter by the sender email address
format: email
in: query
name: fromemail
type: string
- description: Filter by tag
in: query
name: tag
type: string
- description: Filter by status (`queued` or `sent`)
enum:
- queued
- sent
in: query
name: status
type: string
- description: Filter messages up to the date specified. e.g. `2014-02-01`
format: date
in: query
name: todate
type: string
- description: Filter messages starting from the date specified. e.g. `2014-02-01`
format: date
in: query
name: fromdate
type: string
responses:
"200":
description: OK
schema:
$ref: "#/definitions/OutboundSearchResponse"
"422":
$ref: "#/responses/422"
"500":
$ref: "#/responses/500"
summary: Outbound message search
tags:
- Messages API
/messages/outbound/clicks:
get:
operationId: searchClicksForOutboundMessages
parameters:
- description: The token associated with the Server on which this request will operate.
in: header
name: X-Postmark-Server-Token
required: true
type: string
- description: Number of message clicks to return per request. Max 500.
in: query
name: count
required: true
type: integer
- description: Number of messages to skip
in: query
name: offset
required: true
type: integer
- description: Filter by To, Cc, Bcc
in: query
name: recipient
required: false
type: string
- description: Filter by tag
in: query
name: tag
required: false
type: string
- description: Filter by client name, i.e. Outlook, Gmail
in: query
name: client_name
required: false
type: string
- description: Filter by company, i.e. Microsoft, Apple, Google
in: query
name: client_company
required: false
type: string
- description: Filter by client family, i.e. OS X, Chrome
in: query
name: client_family
required: false
type: string
- description: Filter by full OS name and specific version, i.e. OS X 10.9 Mavericks, Windows 7
in: query
name: os_name
required: false
type: string
- description: Filter by kind of OS used without specific version, i.e. OS X, Windows
in: query
name: os_family
required: false
type: string
- description: Filter by company which produced the OS, i.e. Apple Computer, Inc., Microsoft Corporation
in: query
name: os_company
required: false
type: string
- description: Filter by platform, i.e. webmail, desktop, mobile
in: query
name: platform
required: false
type: string
- description: Filter by country messages were opened in, i.e. Denmark, Russia
in: query
name: country
required: false
type: string
- description: Filter by full name of region messages were opened in, i.e. Moscow, New York
in: query
name: region
required: false
type: string
- description: Filter by full name of region messages were opened in, i.e. Moscow, New York
in: query
name: city
required: false
type: string
responses:
"200":
description: OK
schema:
$ref: "#/definitions/MessageClickSearchResponse"
"422":
$ref: "#/responses/422"
"500":
$ref: "#/responses/500"
summary: Clicks for a all messages
tags:
- Messages API
"/messages/outbound/clicks/{messageid}":
get:
operationId: getClicksForSingleOutboundMessage
parameters:
- description: The token associated with the Server on which this request will operate.
in: header
name: X-Postmark-Server-Token
required: true
type: string
- description: The ID of the Outbound Message for which click statistics should be retrieved.
in: path
name: messageid
required: true
type: string
- default: 1
description: Number of message clicks to return per request. Max 500.
in: query
maximum: 500
minimum: 1
name: count
required: true
type: integer
- default: 0
description: Number of messages to skip.
in: query
minimum: 0
name: offset
required: true
type: integer
responses:
"200":
description: OK
schema:
$ref: "#/definitions/MessageClickSearchResponse"
"422":
$ref: "#/responses/422"
"500":
$ref: "#/responses/500"
summary: Retrieve Message Clicks
tags:
- Messages API
/messages/outbound/opens:
get:
operationId: searchOpensForOutboundMessages
parameters:
- description: The token associated with the Server on which this request will operate.
in: header
name: X-Postmark-Server-Token
required: true
type: string
- description: Number of message opens to return per request. Max 500.
in: query
name: count
required: true
type: integer
- description: Number of messages to skip
in: query
name: offset
required: true
type: integer
- description: Filter by To, Cc, Bcc
in: query
name: recipient
required: false
type: string
- description: Filter by tag
in: query
name: tag
required: false
type: string
- description: Filter by client name, i.e. Outlook, Gmail
in: query
name: client_name
required: false
type: string
- description: Filter by company, i.e. Microsoft, Apple, Google
in: query
name: client_company
required: false
type: string
- description: Filter by client family, i.e. OS X, Chrome
in: query
name: client_family
required: false
type: string
- description: Filter by full OS name and specific version, i.e. OS X 10.9 Mavericks, Windows 7
in: query
name: os_name
required: false
type: string
- description: Filter by kind of OS used without specific version, i.e. OS X, Windows
in: query
name: os_family
required: false
type: string
- description: Filter by company which produced the OS, i.e. Apple Computer, Inc., Microsoft Corporation
in: query
name: os_company
required: false
type: string
- description: Filter by platform, i.e. webmail, desktop, mobile
in: query
name: platform
required: false
type: string
- description: Filter by country messages were opened in, i.e. Denmark, Russia
in: query
name: country
required: false
type: string
- description: Filter by full name of region messages were opened in, i.e. Moscow, New York
in: query
name: region
required: false
type: string
- description: Filter by full name of region messages were opened in, i.e. Moscow, New York
in: query
name: city
required: false
type: string
responses:
"200":
description: OK
schema:
$ref: "#/definitions/MessageOpenSearchResponse"
"422":
$ref: "#/responses/422"
"500":
$ref: "#/responses/500"
summary: Opens for all messages
tags:
- Messages API
"/messages/outbound/opens/{messageid}":
get:
operationId: getOpensForSingleOutboundMessage
parameters:
- description: The token associated with the Server on which this request will operate.
in: header
name: X-Postmark-Server-Token
required: true
type: string
- description: The ID of the Outbound Message for which open statistics should be retrieved.
in: path
name: messageid
required: true
type: string
- default: 1
description: Number of message opens to return per request. Max 500.
in: query
maximum: 500
minimum: 1
name: count
required: true
type: integer
- default: 0
description: Number of messages to skip.
in: query
minimum: 0
name: offset
required: true
type: integer
responses:
"200":
description: OK
schema:
$ref: "#/definitions/MessageOpenSearchResponse"
"422":
$ref: "#/responses/422"
"500":
$ref: "#/responses/500"
summary: Retrieve Message Opens
tags:
- Messages API
"/messages/outbound/{messageid}/details":
get:
operationId: getOutboundMessageDetails
parameters:
- description: The token associated with the Server on which this request will operate.
in: header
name: X-Postmark-Server-Token
required: true
type: string
- description: The ID of the message for which to retrieve details.
in: path
name: messageid
required: true
type: string
responses:
"200":
description: OK
schema:
$ref: "#/definitions/OutboundMessageDetailsResponse"
"422":
$ref: "#/responses/422"
"500":
$ref: "#/responses/500"
summary: Outbound message details
tags:
- Messages API
"/messages/outbound/{messageid}/dump":
get:
operationId: getOutboundMessageDump
parameters:
- description: The token associated with the Server on which this request will operate.
in: header
name: X-Postmark-Server-Token
required: true
type: string
- description: The ID of the message for which to retrieve a dump.
in: path
name: messageid
required: true
type: string
responses:
"200":
description: OK
schema:
$ref: "#/definitions/OutboundMessageDumpResponse"
"422":
$ref: "#/responses/422"
"500":
$ref: "#/responses/500"
summary: Outbound message dump
tags:
- Messages API
/server:
get:
operationId: getCurrentServerConfiguration
parameters:
- description: The token associated with the Server on which this request will operate.
in: header
name: X-Postmark-Server-Token
required: true
type: string
responses:
"200":
description: OK
schema:
$ref: "#/definitions/ServerConfigurationResponse"
"422":
$ref: "#/responses/422"
"500":
$ref: "#/responses/500"
summary: Get Server Configuration
tags:
- Server Configuration API
put:
operationId: editCurrentServerConfiguration
parameters:
- description: The token associated with the Server on which this request will operate.
in: header
name: X-Postmark-Server-Token
required: true
type: string
- description: The settings that should be modified for the current server.
in: body
name: body
schema:
$ref: "#/definitions/EditServerConfigurationRequest"
responses:
"200":
description: OK
schema:
$ref: "#/definitions/ServerConfigurationResponse"
"422":
$ref: "#/responses/422"
"500":
$ref: "#/responses/500"
summary: Edit Server Configuration
tags:
- Server Configuration API
/stats/outbound:
get:
operationId: getOutboundOverviewStatistics
parameters:
- description: The token associated with the Server on which this request will operate.
in: header
name: X-Postmark-Server-Token
required: true
type: string
- description: Filter by tag
in: query
name: tag
type: string
- description: Filter stats starting from the date specified. e.g. `2014-01-01`
format: date
in: query
name: fromdate
type: string
- description: Filter stats up to the date specified. e.g. `2014-02-01`
format: date
in: query
name: todate
type: string
responses:
"200":
description: OK
schema:
$ref: "#/definitions/OutboundOverviewStatsResponse"
"422":
$ref: "#/responses/422"
"500":
$ref: "#/responses/500"
summary: Get outbound overview
tags:
- Stats API
/stats/outbound/bounces:
get:
operationId: getBounceCounts
parameters:
- description: The token associated with the Server on which this request will operate.
in: header
name: X-Postmark-Server-Token
required: true
type: string
- description: Filter by tag
in: query
name: tag
type: string
- description: Filter stats starting from the date specified. e.g. `2014-01-01`
format: date
in: query
name: fromdate
type: string
- description: Filter stats up to the date specified. e.g. `2014-02-01`
format: date
in: query
name: todate
type: string
responses:
"200":
description: OK
schema:
properties:
Days:
items:
properties:
Date:
type: string
HardBounce:
type: integer
SMTPApiError:
type: integer
SoftBounce:
type: integer
Transient:
type: integer
type: array
HardBounce:
type: integer
SMTPApiError:
type: integer
SoftBounce:
type: integer
Transient:
type: integer
"422":
$ref: "#/responses/422"
"500":
$ref: "#/responses/500"
summary: Get bounce counts
tags:
- Stats API
/stats/outbound/clicks:
get:
operationId: getOutboundClickCounts
parameters:
- description: The token associated with the Server on which this request will operate.
in: header
name: X-Postmark-Server-Token
required: true
type: string
- description: Filter by tag
in: query
name: tag
type: string
- description: Filter stats starting from the date specified. e.g. `2014-01-01`
format: date
in: query
name: fromdate
type: string
- description: Filter stats up to the date specified. e.g. `2014-02-01`
format: date
in: query
name: todate
type: string
responses:
"200":
description: OK
schema:
$ref: "#/definitions/DynamicResponse"
"422":
$ref: "#/responses/422"
"500":
$ref: "#/responses/500"
summary: Get click counts
tags:
- Stats API
/stats/outbound/clicks/browserfamilies:
get:
operationId: getOutboundClickCountsByBrowserFamily
parameters:
- description: The token associated with the Server on which this request will operate.
in: header
name: X-Postmark-Server-Token
required: true
type: string
- description: Filter by tag
in: query
name: tag
type: string
- description: Filter stats starting from the date specified. e.g. `2014-01-01`
format: date
in: query
name: fromdate
type: string
- description: Filter stats up to the date specified. e.g. `2014-02-01`
format: date
in: query
name: todate
type: string
responses:
"200":
description: OK
schema:
type: object
"422":
$ref: "#/responses/422"
"500":
$ref: "#/responses/500"
summary: Get browser usage by family
tags:
- Stats API
/stats/outbound/clicks/location:
get:
operationId: getOutboundClickCountsByLocation
parameters:
- description: The token associated with the Server on which this request will operate.
in: header
name: X-Postmark-Server-Token
required: true
type: string
- description: Filter by tag
in: query
name: tag
type: string
- description: Filter stats starting from the date specified. e.g. `2014-01-01`
format: date
in: query
name: fromdate
type: string
- description: Filter stats up to the date specified. e.g. `2014-02-01`
format: date
in: query
name: todate
type: string
responses:
"200":
description: OK
schema:
$ref: "#/definitions/DynamicResponse"
"422":
$ref: "#/responses/422"
"500":
$ref: "#/responses/500"
summary: Get clicks by body location
tags:
- Stats API
/stats/outbound/clicks/platforms:
get:
operationId: getOutboundClickCountsByPlatform
parameters:
- description: The token associated with the Server on which this request will operate.
in: header
name: X-Postmark-Server-Token
required: true
type: string
- description: Filter by tag
in: query
name: tag
type: string
- description: Filter stats starting from the date specified. e.g. `2014-01-01`
format: date
in: query
name: fromdate
type: string
- description: Filter stats up to the date specified. e.g. `2014-02-01`
format: date
in: query
name: todate
type: string
responses:
"200":
description: OK
schema:
$ref: "#/definitions/DynamicResponse"
"422":
$ref: "#/responses/422"
"500":
$ref: "#/responses/500"
summary: Get browser plaform usage
tags:
- Stats API
/stats/outbound/opens:
get:
operationId: getOutboundOpenCounts
parameters:
- description: The token associated with the Server on which this request will operate.
in: header
name: X-Postmark-Server-Token
required: true
type: string
- description: Filter by tag
in: query
name: tag
type: string
- description: Filter stats starting from the date specified. e.g. `2014-01-01`
format: date
in: query
name: fromdate
type: string
- description: Filter stats up to the date specified. e.g. `2014-02-01`
format: date
in: query
name: todate
type: string
responses:
"200":
description: OK
schema:
properties:
Days:
items:
properties:
Date:
type: string
Opens:
type: integer
Unique:
type: integer
type: array
Opens:
type: integer
Unique:
type: integer
"422":
$ref: "#/responses/422"
"500":
$ref: "#/responses/500"
summary: Get email open counts
tags:
- Stats API
/stats/outbound/opens/emailclients:
get:
operationId: getOutboundOpenCountsByEmailClient
parameters:
- description: The token associated with the Server on which this request will operate.
in: header
name: X-Postmark-Server-Token
required: true
type: string
- description: Filter by tag
in: query
name: tag
type: string
- description: Filter stats starting from the date specified. e.g. `2014-01-01`
format: date
in: query
name: fromdate
type: string
- description: Filter stats up to the date specified. e.g. `2014-02-01`
format: date
in: query
name: todate
type: string
responses:
"200":
description: OK
schema:
properties:
Days:
items:
$ref: "#/definitions/DynamicResponse"
type: array
Desktop:
type: integer
Mobile:
type: integer
Unknown:
type: integer
WebMail:
type: integer
"422":
$ref: "#/responses/422"
"500":
$ref: "#/responses/500"
summary: Get email client usage
tags:
- Stats API
/stats/outbound/opens/platforms:
get:
operationId: getOutboundOpenCountsByPlatform
parameters:
- description: The token associated with the Server on which this request will operate.
in: header
name: X-Postmark-Server-Token
required: true
type: string
- description: Filter by tag
in: query
name: tag
type: string
- description: Filter stats starting from the date specified. e.g. `2014-01-01`
format: date
in: query
name: fromdate
type: string
- description: Filter stats up to the date specified. e.g. `2014-02-01`
format: date
in: query
name: todate
type: string
responses:
"200":
description: OK
schema:
properties:
Days:
items:
properties:
Date:
type: string
Desktop:
type: integer
Mobile:
type: integer
Unknown:
type: integer
WebMail:
type: integer
type: array
Desktop:
type: integer
Mobile:
type: integer
Unknown:
type: integer
WebMail:
type: integer
"422":
$ref: "#/responses/422"
"500":
$ref: "#/responses/500"
summary: Get email platform usage
tags:
- Stats API
/stats/outbound/sends:
get:
operationId: getSentCounts
parameters:
- description: The token associated with the Server on which this request will operate.
in: header
name: X-Postmark-Server-Token
required: true
type: string
- description: Filter by tag
in: query
name: tag
type: string
- description: Filter stats starting from the date specified. e.g. `2014-01-01`
format: date
in: query
name: fromdate
type: string
- description: Filter stats up to the date specified. e.g. `2014-02-01`
format: date
in: query
name: todate
type: string
responses:
"200":
description: OK
schema:
$ref: "#/definitions/SentCountsResponse"
"422":
$ref: "#/responses/422"
"500":
$ref: "#/responses/500"
summary: Get sent counts
tags:
- Stats API
/stats/outbound/spam:
get:
operationId: getSpamComplaints
parameters:
- description: The token associated with the Server on which this request will operate.
in: header
name: X-Postmark-Server-Token
required: true
type: string
- description: Filter by tag
in: query
name: tag
type: string
- description: Filter stats starting from the date specified. e.g. `2014-01-01`
format: date
in: query
name: fromdate
type: string
- description: Filter stats up to the date specified. e.g. `2014-02-01`
format: date
in: query
name: todate
type: string
responses:
"200":
description: OK
schema:
properties:
Days:
items:
properties:
Date:
type: string
SpamComplaint:
type: integer
type: array
SpamComplaint:
type: integer
"422":
$ref: "#/responses/422"
"500":
$ref: "#/responses/500"
summary: Get spam complaints
tags:
- Stats API
/stats/outbound/tracked:
get:
operationId: getTrackedEmailCounts
parameters:
- description: The token associated with the Server on which this request will operate.
in: header
name: X-Postmark-Server-Token
required: true
type: string
- description: Filter by tag
in: query
name: tag
type: string
- description: Filter stats starting from the date specified. e.g. `2014-01-01`
format: date
in: query
name: fromdate
type: string
- description: Filter stats starting from the date specified. e.g. `2014-01-01`
format: date
in: query
name: todate
type: string
responses:
"200":
description: OK
schema:
properties:
Days:
items:
properties:
Date:
type: string
Tracked:
type: integer
type: array
Tracked:
type: integer
"422":
$ref: "#/responses/422"
"500":
$ref: "#/responses/500"
summary: Get tracked email counts
tags:
- Stats API
/templates:
get:
operationId: listTemplates
parameters:
- description: The token associated with the Server on which this request will operate.
in: header
name: X-Postmark-Server-Token
required: true
type: string
- description: The number of Templates to return
format: int
in: query
name: Count
required: true
type: number
- description: The number of Templates to "skip" before returning results.
format: int
in: query
name: Offset
required: true
type: number
responses:
"200":
description: OK
schema:
$ref: "#/definitions/TemplateListingResponse"
"422":
$ref: "#/responses/422"
"500":
$ref: "#/responses/500"
summary: Get the Templates associated with this Server
tags:
- Templates API
post:
parameters:
- description: The token associated with the Server on which this request will operate.
in: header
name: X-Postmark-Server-Token
required: true
type: string
- in: body
name: body
required: true
schema:
$ref: "#/definitions/CreateTemplateRequest"
responses:
"200":
description: OK
schema:
$ref: "#/definitions/TemplateRecordResponse"
"422":
$ref: "#/responses/422"
"500":
$ref: "#/responses/500"
summary: Create a Template
tags:
- Templates API
/templates/validate:
post:
operationId: testTemplateContent
parameters:
- description: The token associated with the Server on which this request will operate.
in: header
name: X-Postmark-Server-Token
required: true
type: string
- in: body
name: body
schema:
$ref: "#/definitions/TemplateValidationRequest"
responses:
"200":
description: OK
schema:
$ref: "#/definitions/TemplateValidationResponse"
"422":
$ref: "#/responses/422"
"500":
$ref: "#/responses/500"
summary: Test Template Content
tags:
- Templates API
"/templates/{templateIdOrAlias}":
delete:
operationId: deleteTemplate
parameters:
- description: The token associated with the Server on which this request will operate.
in: header
name: X-Postmark-Server-Token
required: true
type: string
- description: The 'TemplateID' or 'Alias' value for the Template you wish to delete.
in: path
name: templateIdOrAlias
required: true
type: string
responses:
"200":
description: OK
schema:
$ref: "#/definitions/TemplateDetailResponse"
"422":
$ref: "#/responses/422"
"500":
$ref: "#/responses/500"
summary: Delete a Template
tags:
- Templates API
get:
operationId: getSingleTemplate
parameters:
- description: The token associated with the Server on which this request will operate.
in: header
name: X-Postmark-Server-Token
required: true
type: string
- description: The 'TemplateID' or 'Alias' value for the Template you wish to retrieve.
in: path
name: templateIdOrAlias
required: true
type: string
responses:
"200":
description: OK
schema:
$ref: "#/definitions/TemplateDetailResponse"
"422":
$ref: "#/responses/422"
"500":
$ref: "#/responses/500"
summary: Get a Template
tags:
- Templates API
put:
operationId: updateTemplate
parameters:
- description: The token associated with the Server on which this request will operate.
in: header
name: X-Postmark-Server-Token
required: true
type: string
- description: The 'TemplateID' or 'Alias' value for the Template you wish to update.
in: path
name: templateIdOrAlias
required: true
type: string
- in: body
name: body
required: true
schema:
$ref: "#/definitions/EditTemplateRequest"
responses:
"200":
description: OK
schema:
$ref: "#/definitions/TemplateRecordResponse"
"422":
$ref: "#/responses/422"
"500":
$ref: "#/responses/500"
summary: Update a Template
tags:
- Templates API
/triggers/inboundrules:
get:
operationId: listInboundRules
parameters:
- description: The token associated with the Server on which this request will operate.
in: header
name: X-Postmark-Server-Token
required: true
type: string
- description: Number of records to return per request.
in: query
name: count
required: true
type: integer
- description: Number of records to skip.
in: query
name: offset
required: true
type: integer
responses:
"200":
description: OK
schema:
properties:
InboundRules:
items:
properties:
ID:
type: integer
Rule:
format: email
type: string
type: array
TotalCount:
type: integer
"422":
$ref: "#/responses/422"
"500":
$ref: "#/responses/500"
summary: List inbound rule triggers
tags:
- Inbound Rules API
post:
operationId: createInboundRule
parameters:
- description: The token associated with the Server on which this request will operate.
in: header
name: X-Postmark-Server-Token
required: true
type: string
- in: body
name: body
schema:
$ref: "#/definitions/CreateInboundRuleRequest"
responses:
"200":
description: OK
schema:
properties:
ID:
type: integer
Rule:
type: string
"422":
$ref: "#/responses/422"
"500":
$ref: "#/responses/500"
summary: Create an inbound rule trigger
tags:
- Inbound Rules API
"/triggers/inboundrules/{triggerid}":
delete:
operationId: deleteInboundRule
parameters:
- description: The token associated with the Server on which this request will operate.
in: header
name: X-Postmark-Server-Token
required: true
type: string
- description: The ID of the Inbound Rule that should be deleted.
in: path
name: triggerid
required: true
type: integer
responses:
"200":
description: OK
schema:
$ref: "#/definitions/StandardPostmarkResponse"
"422":
$ref: "#/responses/422"
"500":
$ref: "#/responses/500"
summary: Delete a single trigger
tags:
- Inbound Rules API
definitions:
Attachment:
description: An attachment for an email message.
properties:
Content:
type: string
ContentID:
type: string
ContentType:
type: string
Name:
type: string
AttachmentCollection:
items:
$ref: "#/definitions/Attachment"
type: array
BounceActivationResponse:
properties:
Bounce:
$ref: "#/definitions/BounceInfoResponse"
Message:
type: string
BounceCountElement:
properties:
Count:
type: integer
Name:
type: string
Type:
type: string
BounceDumpResponse:
properties:
Body:
description: Raw source of bounce. If no dump is available this will return an empty string.
type: string
BounceInfoResponse:
properties:
BouncedAt:
format: date-time
type: string
CanActivate:
type: boolean
Content:
type: string
Description:
type: string
Details:
type: string
DumpAvailable:
type: boolean
Email:
format: email
type: string
ID:
type: string
Inactive:
type: boolean
MessageID:
type: string
Name:
type: string
Subject:
type: string
Tag:
type: string
Type:
type: string
TypeCode:
type: integer
BounceSearchResponse:
description: ""
properties:
Bounces:
items:
$ref: "#/definitions/BounceInfoResponse"
type: array
TotalCount:
type: integer
CreateInboundRuleRequest:
description: ""
properties:
Rule:
format: email
type: string
CreateTemplateRequest:
description: The contents required for creating a new template.
properties:
Alias:
description: The optional string identifier for referring to this Template (numbers, letters, and '.', '-', '_' characters, starts with a letter).
type: string
HtmlBody:
description: The HTML template definition for this Template.
type: string
Name:
description: The friendly display name for the template.
type: string
Subject:
description: The Subject template definition for this Template.
type: string
TextBody:
description: The Text template definition for this Template.
type: string
required:
- Name
- Subject
DeliveryStatsResponse:
description: ""
properties:
Bounces:
items:
$ref: "#/definitions/BounceCountElement"
type: array
InactiveMails:
type: integer
DynamicResponse:
description: The properties of this object will vary based request parameters.
EditServerConfigurationRequest:
properties:
BounceHookUrl:
type: string
ClickHookUrl:
description: Webhook url allowing real-time notification when tracked links are clicked.
type: string
Color:
enum:
- purple
- blue
- turqoise
- green
- red
- yellow
- grey
type: string
DeliveryHookUrl:
type: string
InboundDomain:
type: string
InboundHookUrl:
type: string
InboundSpamThreshold:
type: integer
Name:
type: string
OpenHookUrl:
type: string
PostFirstOpenOnly:
type: boolean
RawEmailEnabled:
type: boolean
SmtpApiActivated:
type: boolean
TrackLinks:
enum:
- None
- HtmlAndText
- HtmlOnly
- TextOnly
type: string
TrackOpens:
type: boolean
EditTemplateRequest:
description: The contents required for creating a new template.
properties:
Alias:
description: The optional string identifier for referring to this Template (numbers, letters, and '.', '-', '_' characters, starts with a letter).
type: string
HtmlBody:
description: The HTML template definition for this Template.
type: string
Name:
description: The friendly display name for the template.
type: string
Subject:
description: The Subject template definition for this Template.
type: string
TextBody:
description: The Text template definition for this Template.
type: string
required:
- TemplateId
EmailNameAddressPair:
description: ""
properties:
Email:
type: string
Name:
type: string
EmailWithTemplateRequest:
properties:
Attachments:
$ref: "#/definitions/AttachmentCollection"
Bcc:
format: email
type: string
Cc:
format: email
type: string
From:
format: email
type: string
Headers:
$ref: "#/definitions/HeaderCollection"
InlineCss:
default: true
type: boolean
ReplyTo:
type: string
Tag:
type: string
TemplateAlias:
description: Required if 'TemplateId' is not specified.
type: string
TemplateId:
description: Required if 'TemplateAlias' is not specified.
type: integer
TemplateModel:
type: object
To:
format: email
type: string
TrackLinks:
description: Replace links in content to enable "click tracking" stats. Default is 'null', which uses the server's LinkTracking setting'.
enum:
- None
- HtmlAndText
- HtmlOnly
- TextOnly
type: string
TrackOpens:
description: Activate open tracking for this email.
type: boolean
required:
- TemplateId
- TemplateAlias
- TemplateModel
- To
- From
ExtendedMessageClickEventInformation:
description: ""
properties:
ClickLocation:
type: string
Client:
description: ""
properties:
Company:
type: string
Family:
type: string
Name:
type: string
Geo:
properties:
City:
type: string
Coords:
type: string
Country:
type: string
CountryISOCode:
type: string
IP:
type: string
Region:
type: string
RegionISOCode:
type: string
Zip:
type: string
MessageID:
type: string
OS:
properties:
Company:
type: string
Family:
type: string
Name:
type: string
OriginalLink:
type: string
Platform:
type: string
ReceivedAt:
format: date-time
type: string
Recipient:
format: email
type: string
Tag:
type: string
UserAgent:
type: string
ExtendedMessageOpenEventInformation:
description: ""
properties:
Client:
description: ""
properties:
Company:
type: string
Family:
type: string
Name:
type: string
FirstOpen:
type: boolean
Geo:
properties:
City:
type: string
Coords:
type: string
Country:
type: string
CountryISOCode:
type: string
IP:
type: string
Region:
type: string
RegionISOCode:
type: string
Zip:
type: string
MessageID:
type: string
OS:
properties:
Company:
type: string
Family:
type: string
Name:
type: string
Platform:
type: string
ReceivedAt:
format: date-time
type: string
Recipient:
format: email
type: string
Tag:
type: string
UserAgent:
type: string
HeaderCollection:
items:
$ref: "#/definitions/MessageHeader"
type: array
InboundMessageDetail:
description: ""
properties:
Attachments:
$ref: "#/definitions/AttachmentCollection"
Cc:
type: string
CcFull:
items:
$ref: "#/definitions/EmailNameAddressPair"
type: array
Date:
type: string
From:
type: string
FromFull:
description: ""
properties:
Email:
type: string
Name:
type: string
FromName:
type: string
MailboxHash:
type: string
MessageID:
type: string
OriginalRecipient:
type: string
ReplyTo:
type: string
Status:
type: string
Subject:
type: string
Tag:
type: string
To:
type: string
ToFull:
items:
$ref: "#/definitions/EmailNameAddressPair"
type: array
InboundMessageFullDetailsResponse:
properties:
Attachments:
$ref: "#/definitions/AttachmentCollection"
BlockedReason:
type: string
Cc:
type: string
CcFull:
items:
$ref: "#/definitions/EmailNameAddressPair"
type: array
Date:
type: string
From:
type: string
FromFull:
description: ""
properties:
Email:
type: string
Name:
type: string
FromName:
type: string
Headers:
$ref: "#/definitions/HeaderCollection"
HtmlBody:
type: string
MailboxHash:
type: string
MessageID:
type: string
OriginalRecipient:
type: string
ReplyTo:
type: string
Status:
type: string
Subject:
type: string
Tag:
type: string
TextBody:
type: string
To:
type: string
ToFull:
items:
$ref: "#/definitions/EmailNameAddressPair"
type: array
InboundSearchResponse:
description: ""
properties:
InboundMessages:
items:
$ref: "#/definitions/InboundMessageDetail"
type: array
TotalCount:
type: integer
MessageClickSearchResponse:
properties:
Clicks:
items:
$ref: "#/definitions/ExtendedMessageClickEventInformation"
type: array
TotalCount:
type: integer
MessageEventDetails:
description: ""
properties:
Details:
properties:
BounceID:
type: string
DeliveryMessage:
type: string
DestinationIP:
type: string
DestinationServer:
type: string
Summary:
type: string
ReceivedAt:
format: date-time
type: string
Recipient:
type: string
Type:
type: string
MessageHeader:
description: A single header for an email message.
properties:
Name:
description: The header's name.
type: string
Value:
description: The header's value.
type: string
MessageOpenSearchResponse:
properties:
Opens:
items:
$ref: "#/definitions/ExtendedMessageOpenEventInformation"
type: array
TotalCount:
type: integer
OutboundMessageDetail:
description: ""
properties:
Attachments:
$ref: "#/definitions/AttachmentCollection"
Bcc:
items:
$ref: "#/definitions/EmailNameAddressPair"
type: array
Cc:
items:
$ref: "#/definitions/EmailNameAddressPair"
type: array
From:
type: string
MessageID:
type: string
ReceivedAt:
format: date-time
type: string
Recipients:
items:
type: string
type: array
Status:
type: string
Subject:
type: string
Tag:
type: string
To:
items:
$ref: "#/definitions/EmailNameAddressPair"
type: array
TrackLinks:
enum:
- None
- HtmlAndText
- HtmlOnly
- TextOnly
type: string
TrackOpens:
type: boolean
OutboundMessageDetailsResponse:
properties:
Attachments:
$ref: "#/definitions/AttachmentCollection"
Bcc:
items:
$ref: "#/definitions/EmailNameAddressPair"
type: array
Body:
type: string
Cc:
items:
$ref: "#/definitions/EmailNameAddressPair"
type: array
From:
type: string
HtmlBody:
type: string
MessageEvents:
items:
$ref: "#/definitions/MessageEventDetails"
type: array
MessageID:
type: string
ReceivedAt:
format: date-time
type: string
Recipients:
items:
type: string
type: array
Status:
type: string
Subject:
type: string
Tag:
type: string
TextBody:
type: string
To:
items:
$ref: "#/definitions/EmailNameAddressPair"
type: array
TrackLinks:
enum:
- None
- HtmlAndText
- HtmlOnly
- TextOnly
type: string
TrackOpens:
type: boolean
OutboundMessageDumpResponse:
properties:
Body:
description: Raw source of message. If no dump is available this will return an empty string.
type: string
OutboundOverviewStatsResponse:
description: ""
properties:
BounceRate:
type: integer
Bounced:
type: integer
Opens:
type: integer
SMTPAPIErrors:
type: integer
Sent:
type: integer
SpamComplaints:
type: integer
SpamComplaintsRate:
type: integer
TotalClicks:
type: integer
TotalTrackedLinksSent:
type: integer
Tracked:
type: integer
UniqueLinksClicked:
type: integer
UniqueOpens:
type: integer
WithClientRecorded:
type: integer
WithLinkTracking:
type: integer
WithOpenTracking:
type: integer
WithPlatformRecorded:
type: integer
OutboundSearchResponse:
description: ""
properties:
Messages:
items:
$ref: "#/definitions/OutboundMessageDetail"
type: array
TotalCount:
type: integer
SendEmailBatchRequest:
items:
$ref: "#/definitions/SendEmailRequest"
type: array
SendEmailBatchResponse:
items:
$ref: "#/definitions/SendEmailResponse"
type: array
SendEmailRequest:
properties:
Attachments:
$ref: "#/definitions/AttachmentCollection"
Bcc:
description: Bcc recipient email address. Multiple addresses are comma seperated. Max 50.
type: string
Cc:
description: Recipient email address. Multiple addresses are comma seperated. Max 50.
type: string
From:
description: The sender email address. Must have a registered and confirmed Sender Signature.
type: string
Headers:
$ref: "#/definitions/HeaderCollection"
HtmlBody:
description: If no TextBody specified HTML email message
type: string
ReplyTo:
description: Reply To override email address. Defaults to the Reply To set in the sender signature.
type: string
Subject:
description: Email Subject
type: string
Tag:
description: Email tag that allows you to categorize outgoing emails and get detailed statistics.
type: string
TextBody:
description: If no HtmlBody specified Plain text email message
type: string
To:
description: Recipient email address. Multiple addresses are comma seperated. Max 50.
type: string
TrackLinks:
description: Replace links in content to enable "click tracking" stats. Default is 'null', which uses the server's LinkTracking setting'.
enum:
- None
- HtmlAndText
- HtmlOnly
- TextOnly
type: string
TrackOpens:
description: Activate open tracking for this email.
type: boolean
SendEmailResponse:
description: The standard response when a postmark message is sent
properties:
ErrorCode:
type: integer
Message:
type: string
MessageID:
type: string
SubmittedAt:
format: date-time
type: string
To:
type: string
SendEmailTemplatedBatchRequest:
properties:
Messages:
items:
$ref: "#/definitions/EmailWithTemplateRequest"
type: array
SentCountsResponse:
description: The result of a get sent counts operation.
properties:
Days:
items:
properties:
Date:
type: string
Sent:
type: integer
type: array
Sent:
type: integer
ServerConfigurationResponse:
properties:
ApiTokens:
items:
type: string
type: array
BounceHookUrl:
type: string
ClickHookUrl:
type: string
Color:
enum:
- purple
- blue
- turqoise
- green
- red
- yellow
- grey
type: string
DeliveryHookUrl:
type: string
ID:
type: integer
InboundAddress:
format: email
type: string
InboundDomain:
type: string
InboundHash:
type: string
InboundHookUrl:
type: string
InboundSpamThreshold:
type: integer
Name:
type: string
OpenHookUrl:
type: string
PostFirstOpenOnly:
type: boolean
RawEmailEnabled:
type: boolean
ServerLink:
type: string
SmtpApiActivated:
type: boolean
TrackLinks:
enum:
- None
- HtmlAndText
- HtmlOnly
- TextOnly
type: string
TrackOpens:
type: boolean
StandardPostmarkResponse:
description: A Postmark API error.
properties:
ErrorCode:
type: integer
Message:
type: string
TemplateDetailResponse:
properties:
Active:
description: Indicates that this template may be used for sending email.
type: boolean
Alias:
description: The user-supplied alias for this template.
type: string
AssociatedServerId:
description: The ID of the Server with which this template is associated.
type: integer
HtmlBody:
description: The content to use for the HtmlBody when this template is used to send email.
type: string
Name:
description: The display name for the template.
type: string
Subject:
description: The content to use for the Subject when this template is used to send email.
type: string
TemplateID:
description: The ID associated with the template.
type: integer
TextBody:
description: The content to use for the TextBody when this template is used to send email.
type: string
TemplateListingResponse:
properties:
Templates API:
description: Basic information for each Template returned from the query.
items:
$ref: "#/definitions/TemplateRecordResponse"
type: array
TotalCount:
description: The total number of Templates API associated with this server.
type: number
TemplateRecordResponse:
properties:
Active:
description: True if this template is currently available for use.
type: boolean
Alias:
description: The user-supplied alias for this template.
type: string
Name:
description: The display name for this template.
type: string
TemplateId:
description: The associated ID for this template.
format: int
type: number
TemplateValidationError:
properties:
CharacterPosition:
type: integer
Line:
type: integer
Message:
type: string
TemplateValidationRequest:
properties:
HtmlBody:
description: >
The html body content to validate. Must be specified if Subject or
TextBody are not. See our template language documentation for more
information on the syntax for this field.
type: string
InlineCssForHtmlTestRender:
default: true
description: >
When HtmlBody is specified, the test render will have style blocks
inlined as style attributes on matching html elements. You may disable
the css inlining behavior by passing false for this parameter.
type: boolean
Subject:
description: >
The subject content to validate. Must be specified if HtmlBody or
TextBody are not. See our template language documentation for more
information on the syntax for this field.
type: string
TestRenderModel:
description: The model to be used when rendering test content.
type: object
TextBody:
description: >
The text body content to validate. Must be specified if HtmlBody or
Subject are not. See our template language documentation for more
information on the syntax for this field.
type: string
TemplateValidationResponse:
properties:
AllContentIsValid:
type: boolean
HtmlBody:
$ref: "#/definitions/TemplateValidationResult"
Subject:
$ref: "#/definitions/TemplateValidationResult"
SuggestedTemplateModel:
type: object
TextBody:
$ref: "#/definitions/TemplateValidationResult"
TemplateValidationResult:
properties:
ContentIsValid:
type: boolean
RenderedContent:
type: string
ValidationErrors:
items:
$ref: "#/definitions/TemplateValidationError"
type: array
| {
"pile_set_name": "Github"
} |
.tether-element, .tether-element:after, .tether-element:before, .tether-element *, .tether-element *:after, .tether-element *:before {
box-sizing: border-box; }
.tether-element {
position: absolute;
display: none; }
.tether-element.tether-open {
display: block; }
.tether-element.tether-theme-arrows {
max-width: 100%;
max-height: 100%; }
.tether-element.tether-theme-arrows .tether-content {
border-radius: 5px;
position: relative;
font-family: inherit;
background: #fff;
color: inherit;
padding: 1em;
font-size: 1.1em;
line-height: 1.5em;
-webkit-transform: translateZ(0);
transform: translateZ(0);
-webkit-filter: drop-shadow(0 1px 4px rgba(0, 0, 0, 0.2));
filter: drop-shadow(0 1px 4px rgba(0, 0, 0, 0.2)); }
.tether-element.tether-theme-arrows .tether-content:before {
content: "";
display: block;
position: absolute;
width: 0;
height: 0;
border-color: transparent;
border-width: 16px;
border-style: solid; }
.tether-element.tether-theme-arrows.tether-element-attached-bottom.tether-element-attached-center .tether-content {
margin-bottom: 16px; }
.tether-element.tether-theme-arrows.tether-element-attached-bottom.tether-element-attached-center .tether-content:before {
top: 100%;
left: 50%;
margin-left: -16px;
border-top-color: #fff;
border-bottom: 0; }
.tether-element.tether-theme-arrows.tether-element-attached-top.tether-element-attached-center .tether-content {
margin-top: 16px; }
.tether-element.tether-theme-arrows.tether-element-attached-top.tether-element-attached-center .tether-content:before {
bottom: 100%;
left: 50%;
margin-left: -16px;
border-bottom-color: #fff;
border-top: 0; }
.tether-element.tether-theme-arrows.tether-element-attached-right.tether-element-attached-middle .tether-content {
margin-right: 16px; }
.tether-element.tether-theme-arrows.tether-element-attached-right.tether-element-attached-middle .tether-content:before {
left: 100%;
top: 50%;
margin-top: -16px;
border-left-color: #fff;
border-right: 0; }
.tether-element.tether-theme-arrows.tether-element-attached-left.tether-element-attached-middle .tether-content {
margin-left: 16px; }
.tether-element.tether-theme-arrows.tether-element-attached-left.tether-element-attached-middle .tether-content:before {
right: 100%;
top: 50%;
margin-top: -16px;
border-right-color: #fff;
border-left: 0; }
.tether-element.tether-theme-arrows.tether-element-attached-left.tether-target-attached-center .tether-content {
left: -32px; }
.tether-element.tether-theme-arrows.tether-element-attached-right.tether-target-attached-center .tether-content {
left: 32px; }
.tether-element.tether-theme-arrows.tether-element-attached-top.tether-element-attached-left.tether-target-attached-middle .tether-content {
margin-top: 16px; }
.tether-element.tether-theme-arrows.tether-element-attached-top.tether-element-attached-left.tether-target-attached-middle .tether-content:before {
bottom: 100%;
left: 16px;
border-bottom-color: #fff;
border-top: 0; }
.tether-element.tether-theme-arrows.tether-element-attached-top.tether-element-attached-right.tether-target-attached-middle .tether-content {
margin-top: 16px; }
.tether-element.tether-theme-arrows.tether-element-attached-top.tether-element-attached-right.tether-target-attached-middle .tether-content:before {
bottom: 100%;
right: 16px;
border-bottom-color: #fff;
border-top: 0; }
.tether-element.tether-theme-arrows.tether-element-attached-bottom.tether-element-attached-left.tether-target-attached-middle .tether-content {
margin-bottom: 16px; }
.tether-element.tether-theme-arrows.tether-element-attached-bottom.tether-element-attached-left.tether-target-attached-middle .tether-content:before {
top: 100%;
left: 16px;
border-top-color: #fff;
border-bottom: 0; }
.tether-element.tether-theme-arrows.tether-element-attached-bottom.tether-element-attached-right.tether-target-attached-middle .tether-content {
margin-bottom: 16px; }
.tether-element.tether-theme-arrows.tether-element-attached-bottom.tether-element-attached-right.tether-target-attached-middle .tether-content:before {
top: 100%;
right: 16px;
border-top-color: #fff;
border-bottom: 0; }
.tether-element.tether-theme-arrows.tether-element-attached-top.tether-element-attached-left.tether-target-attached-bottom .tether-content {
margin-top: 16px; }
.tether-element.tether-theme-arrows.tether-element-attached-top.tether-element-attached-left.tether-target-attached-bottom .tether-content:before {
bottom: 100%;
left: 16px;
border-bottom-color: #fff;
border-top: 0; }
.tether-element.tether-theme-arrows.tether-element-attached-top.tether-element-attached-right.tether-target-attached-bottom .tether-content {
margin-top: 16px; }
.tether-element.tether-theme-arrows.tether-element-attached-top.tether-element-attached-right.tether-target-attached-bottom .tether-content:before {
bottom: 100%;
right: 16px;
border-bottom-color: #fff;
border-top: 0; }
.tether-element.tether-theme-arrows.tether-element-attached-bottom.tether-element-attached-left.tether-target-attached-top .tether-content {
margin-bottom: 16px; }
.tether-element.tether-theme-arrows.tether-element-attached-bottom.tether-element-attached-left.tether-target-attached-top .tether-content:before {
top: 100%;
left: 16px;
border-top-color: #fff;
border-bottom: 0; }
.tether-element.tether-theme-arrows.tether-element-attached-bottom.tether-element-attached-right.tether-target-attached-top .tether-content {
margin-bottom: 16px; }
.tether-element.tether-theme-arrows.tether-element-attached-bottom.tether-element-attached-right.tether-target-attached-top .tether-content:before {
top: 100%;
right: 16px;
border-top-color: #fff;
border-bottom: 0; }
.tether-element.tether-theme-arrows.tether-element-attached-top.tether-element-attached-right.tether-target-attached-left .tether-content {
margin-right: 16px; }
.tether-element.tether-theme-arrows.tether-element-attached-top.tether-element-attached-right.tether-target-attached-left .tether-content:before {
top: 16px;
left: 100%;
border-left-color: #fff;
border-right: 0; }
.tether-element.tether-theme-arrows.tether-element-attached-top.tether-element-attached-left.tether-target-attached-right .tether-content {
margin-left: 16px; }
.tether-element.tether-theme-arrows.tether-element-attached-top.tether-element-attached-left.tether-target-attached-right .tether-content:before {
top: 16px;
right: 100%;
border-right-color: #fff;
border-left: 0; }
.tether-element.tether-theme-arrows.tether-element-attached-bottom.tether-element-attached-right.tether-target-attached-left .tether-content {
margin-right: 16px; }
.tether-element.tether-theme-arrows.tether-element-attached-bottom.tether-element-attached-right.tether-target-attached-left .tether-content:before {
bottom: 16px;
left: 100%;
border-left-color: #fff;
border-right: 0; }
.tether-element.tether-theme-arrows.tether-element-attached-bottom.tether-element-attached-left.tether-target-attached-right .tether-content {
margin-left: 16px; }
.tether-element.tether-theme-arrows.tether-element-attached-bottom.tether-element-attached-left.tether-target-attached-right .tether-content:before {
bottom: 16px;
right: 100%;
border-right-color: #fff;
border-left: 0; }
| {
"pile_set_name": "Github"
} |
Bmob Android SDK
==========
Bmobๅ็ซฏไบไธบ็งปๅจๅบ็จ็จๅบๆไพไบไธๆดๅฅๅฎๆด็ๅ็ซฏ่งฃๅณๆนๆก,่ฏฆๆ
ๅฏ่ฎฟ้ฎ [ๅฎๆน็ฝ็ซ](http://www.bmob.cn)
# ๅฟซ้ๅ
ฅ้จ
ไธ็ฅ้ๅฆไฝไฝฟ็จBmob Android SDK็ๅผๅ่
ๅฏ็งปๆญฅๆฅ็Bmobๅฎๆนๆไพ็ [Bmob Android SDKๅฟซ้ๅ
ฅ้จๆๆกฃ](http://docs.bmob.cn/android/faststart/index.html?menukey=fast_start&key=start_android)ใ
# Bmobๅฎๆนไฟกๆฏ
- [ๅฎๆน็ฝ็ซ](http://www.bmob.cn)
- [ๅผๅๆๆกฃ](http://docs.bmob.cn/android/developdoc/index.html?menukey=develop_doc&key=develop_android)
- [Bmob่ฎบๅ](http://community.bmob.cn/forum.php)
- [ๆๆฏ้ฎ็ฎฑ]([email protected]) | {
"pile_set_name": "Github"
} |
<?php
require_once(dirname(__FILE__).'/snmp_include.inc');
echo "Checking error handling\n";
var_dump(snmp_set_oid_output_format());
var_dump(snmp_set_oid_output_format(123));
echo "Checking working\n";
var_dump(snmp_set_oid_output_format(SNMP_OID_OUTPUT_FULL));
var_dump(snmp_set_oid_output_format(SNMP_OID_OUTPUT_NUMERIC));
?>
| {
"pile_set_name": "Github"
} |
37
53
32
36
26
50
7
38
29
30
2
50
37
38
28
26
29
20
5
31
33
25
31
36
24
19
37
46
30
35
26
21
41
37
29
24
34
19
31
33
26
4
16
16
26
27
17
17
38
25
39
26
4
33
35
26
37
4
27
35
4
24
37
8
12
9
29
23
11
26
17
20
23
1
33
24
47
10
41
32
36
30
55
45
29
52
7
19
28
8
39
23
4
28
4
19
27
22
4
1
21
34
18
2
23
41
66
4
27
68
32
42
20
15
54
25
23
38
37
13
20
31
38
33
90
30
7
46
70
30
18
33
34
32
10
27
26
25
40
22
4
20
40
36
35
6
4
27
17
14
11
30
15
35
46
31
5
57
4
42
28
31
36
6
49
29
18
6
38
26
12
19
22
30
24
6
26
61
54
38
2
30
28
87
21
25
65
32
37
35
38
34
36
35
2
8
11
23
8
38
18
41
22
12
37
40
56
2
64
76
33
5
30
32
28
22
11
25
26
25
11
5
17
27
23
12
11
4
28
33
32
5
28
46
53
2
34
14
26
4
4
35
38
53
62
28
18
21
23
5
28
44
44
34
26
38
6
20
26
23
33
81
21
23
22
6
18
2
1
10
25
35
50
2
25
23
7
20
1
23
24
33
27
6
45
4
48
5
| {
"pile_set_name": "Github"
} |
<?xml version="1.0"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<groupId>org.jboss</groupId>
<artifactId>jboss-parent</artifactId>
<version>36</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<groupId>io.debezium</groupId>
<artifactId>debezium-parent</artifactId>
<version>1.3.0-SNAPSHOT</version>
<name>Debezium Parent POM</name>
<description>Debezium is an open source change data capture platform</description>
<packaging>pom</packaging>
<url>https://debezium.io</url>
<scm>
<connection>scm:git:[email protected]:debezium/debezium.git</connection>
<developerConnection>scm:git:[email protected]:debezium/debezium.git</developerConnection>
<url>https://github.com/debezium/debezium</url>
<tag>HEAD</tag>
</scm>
<issueManagement>
<system>jira</system>
<url>http://issues.jboss.org/browse/DBZ</url>
</issueManagement>
<licenses>
<license>
<name>Apache Software License 2.0</name>
<url>http://www.apache.org/licenses/LICENSE-2.0</url>
<distribution>repo</distribution>
</license>
</licenses>
<developers>
<developer>
<id>rhauch</id>
<name>Randall Hauch</name>
<organization>Red Hat</organization>
<organizationUrl>http://redhat.com</organizationUrl>
<timezone>-6</timezone>
</developer>
<developer>
<id>gunnarmorling</id>
<name>Gunnar Morling</name>
<organization>Red Hat</organization>
<organizationUrl>http://redhat.com</organizationUrl>
<timezone>+2</timezone>
</developer>
</developers>
<properties>
<!-- Instruct the build to use only UTF-8 encoding for source code -->
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<release>8</release>
<!-- Kafka and it's dependencies MUST reflect what the Kafka version uses -->
<version.kafka>2.6.0</version.kafka>
<version.kafka.scala>2.12</version.kafka.scala>
<version.curator>4.2.0</version.curator>
<version.zookeeper>3.5.8</version.zookeeper>
<version.jackson>2.10.2</version.jackson>
<version.org.slf4j>1.7.30</version.org.slf4j>
<version.log4j>1.2.17</version.log4j>
<!-- check new release version at https://github.com/confluentinc/schema-registry/releases -->
<version.confluent.platform>5.5.1</version.confluent.platform>
<!-- Databases -->
<version.postgresql.driver>42.2.14</version.postgresql.driver>
<version.mysql.server>5.7</version.mysql.server>
<version.mysql.driver>8.0.16</version.mysql.driver>
<version.mysql.binlog>0.23.1</version.mysql.binlog>
<version.mongo.server>3.6</version.mongo.server>
<version.mongo.driver>3.12.3</version.mongo.driver>
<version.sqlserver.driver>7.2.2.jre8</version.sqlserver.driver>
<!-- Connectors -->
<version.com.google.protobuf>3.8.0</version.com.google.protobuf>
<!-- ANTLR -->
<antlr.version>4.7.2</antlr.version>
<!-- Quarkus -->
<quarkus.version>1.7.1.Final</quarkus.version>
<!-- HTTP client -->
<version.okhttp>4.2.2</version.okhttp>
<!-- Scripting -->
<version.groovy>3.0.2</version.groovy>
<version.graalvm.js>20.0.0</version.graalvm.js>
<!-- Testing -->
<version.junit>4.12</version.junit>
<version.fest>1.4</version.fest>
<version.jmh>1.21</version.jmh>
<version.mockito>3.0.0</version.mockito>
<version.awaitility>4.0.1</version.awaitility>
<version.testcontainers>1.12.5</version.testcontainers>
<version.jsonpath>2.4.0</version.jsonpath>
<version.okhttp>4.2.2</version.okhttp>
<!-- Maven Plugins -->
<version.compiler.plugin>3.8.1</version.compiler.plugin>
<version.resources.plugin>3.1.0</version.resources.plugin>
<version.filtering.plugin>3.1.1</version.filtering.plugin>
<version.dependency.plugin>3.1.1</version.dependency.plugin>
<version.enforcer.plugin>3.0.0-M2</version.enforcer.plugin>
<version.jar.plugin>3.0.2</version.jar.plugin>
<version.source.plugin>3.1.0</version.source.plugin>
<version.assembly.plugin>3.1.1</version.assembly.plugin>
<version.war.plugin>2.5</version.war.plugin>
<version.google.formatter.plugin>0.4</version.google.formatter.plugin>
<version.docker.maven.plugin>0.31.0</version.docker.maven.plugin>
<version.staging.plugin>1.6.8</version.staging.plugin>
<version.protoc.maven.plugin>3.8.0</version.protoc.maven.plugin>
<version.javadoc.plugin>3.1.1</version.javadoc.plugin>
<version.code.formatter>2.11.0</version.code.formatter>
<version.surefire.plugin>3.0.0-M3</version.surefire.plugin>
<version.checkstyle.plugin>3.1.1</version.checkstyle.plugin>
<version.release.plugin>2.5.3</version.release.plugin>
<version.impsort>1.3.2</version.impsort>
<version.failsafe.plugin>${version.surefire.plugin}</version.failsafe.plugin>
<version.checkstyle>8.32</version.checkstyle>
<version.revapi.plugin>0.11.5</version.revapi.plugin>
<version.jandex>1.0.8</version.jandex>
<version.revapi-java.plugin>0.21.0</version.revapi-java.plugin>
<version.build-helper.plugin>1.9.1</version.build-helper.plugin>
<!-- Dockerfiles -->
<docker.maintainer>Debezium community</docker.maintainer>
<!--Skip long running tests by default-->
<skipLongRunningTests>true</skipLongRunningTests>
<!-- Don't skip integration tests by default -->
<skipITs>false</skipITs>
<!-- Do not skip formatting source code by default -->
<format.skip>false</format.skip>
<!-- Set formatting default goals -->
<format.formatter.goal>format</format.formatter.goal>
<format.imports.goal>sort</format.imports.goal>
<!-- No debug options by default -->
<debug.argline />
<!-- No modules options by default -->
<modules.argline />
<!-- No test options by default -->
<test.argline />
<!-- Assembly configuration -->
<assembly.descriptor>connector-distribution</assembly.descriptor>
<!-- Needed for pre jdk 9 -->
<useSystemClassLoader>true</useSystemClassLoader>
<!-- Skip the API checks by default. Let the modules opt in. -->
<revapi.skip>true</revapi.skip>
</properties>
<modules>
<module>support/checkstyle</module>
<module>support/ide-configs</module>
<module>support/revapi</module>
<module>debezium-api</module>
<module>debezium-ddl-parser</module>
<module>debezium-assembly-descriptors</module>
<module>debezium-core</module>
<module>debezium-embedded</module>
<module>debezium-connector-mysql</module>
<module>debezium-connector-postgres</module>
<module>debezium-connector-mongodb</module>
<module>debezium-connector-sqlserver</module>
<module>debezium-microbenchmark</module>
<module>debezium-quarkus-outbox</module>
<module>debezium-scripting</module>
<module>debezium-server</module>
<module>debezium-testing</module>
</modules>
<distributionManagement>
<repository>
<id>ossrh</id>
<name>Sonatype Staging Repository</name>
<url>https://oss.sonatype.org/service/local/staging/deploy/maven2</url>
</repository>
<snapshotRepository>
<id>ossrh</id>
<name>OSS Sonatype Nexus Snapshots</name>
<url>https://oss.sonatype.org/content/repositories/snapshots</url>
</snapshotRepository>
</distributionManagement>
<repositories>
<repository>
<id>confluent</id>
<name>Confluent</name>
<url>https://packages.confluent.io/maven/</url>
<snapshots>
<enabled>true</enabled>
<updatePolicy>never</updatePolicy>
</snapshots>
</repository>
<repository>
<id>ossrh</id>
<name>OSS Sonatype Nexus</name>
<url>https://oss.sonatype.org/content/groups/public/</url>
<releases>
<enabled>true</enabled>
<updatePolicy>never</updatePolicy>
</releases>
<snapshots>
<enabled>true</enabled>
<updatePolicy>never</updatePolicy>
</snapshots>
</repository>
</repositories>
<dependencyManagement>
<dependencies>
<!-- Major dependencies -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>${version.jackson}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-joda</artifactId>
<version>${version.jackson}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-yaml</artifactId>
<version>${version.jackson}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>${version.jackson}</version>
<optional>true</optional>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-jsr310</artifactId>
<version>${version.jackson}</version>
<optional>true</optional>
</dependency>
<!-- Kafka Connect -->
<dependency>
<groupId>org.apache.kafka</groupId>
<artifactId>connect-api</artifactId>
<version>${version.kafka}</version>
</dependency>
<dependency>
<groupId>org.apache.kafka</groupId>
<artifactId>connect-runtime</artifactId>
<version>${version.kafka}</version>
</dependency>
<dependency>
<groupId>org.apache.kafka</groupId>
<artifactId>connect-json</artifactId>
<version>${version.kafka}</version>
</dependency>
<dependency>
<groupId>org.apache.kafka</groupId>
<artifactId>connect-file</artifactId>
<version>${version.kafka}</version>
</dependency>
<dependency>
<groupId>org.apache.kafka</groupId>
<artifactId>connect-transforms</artifactId>
<version>${version.kafka}</version>
</dependency>
<!-- Kafka -->
<dependency>
<groupId>org.apache.kafka</groupId>
<artifactId>kafka_${version.kafka.scala}</artifactId>
<version>${version.kafka}</version>
</dependency>
<dependency>
<groupId>org.apache.kafka</groupId>
<artifactId>kafka-clients</artifactId>
<version>${version.kafka}</version>
</dependency>
<dependency>
<groupId>org.apache.zookeeper</groupId>
<artifactId>zookeeper</artifactId>
<version>${version.zookeeper}</version>
</dependency>
<dependency>
<groupId>org.apache.kafka</groupId>
<artifactId>kafka_${version.kafka.scala}</artifactId>
<version>${version.kafka}</version>
<classifier>test</classifier>
</dependency>
<dependency>
<groupId>org.apache.curator</groupId>
<artifactId>curator-test</artifactId>
<version>${version.curator}</version>
</dependency>
<dependency>
<groupId>io.confluent</groupId>
<artifactId>kafka-connect-avro-converter</artifactId>
<version>${version.confluent.platform}</version>
</dependency>
<dependency>
<groupId>org.antlr</groupId>
<artifactId>antlr4-runtime</artifactId>
<version>${antlr.version}</version>
</dependency>
<!-- PostgreSQL connector -->
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>${version.postgresql.driver}</version>
</dependency>
<!--Make sure this version is compatible with the Protbuf-C version used on the server -->
<dependency>
<groupId>com.google.protobuf</groupId>
<artifactId>protobuf-java</artifactId>
<version>${version.com.google.protobuf}</version>
</dependency>
<!-- MySQL JDBC Driver, Binlog reader, Geometry support -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${version.mysql.driver}</version>
</dependency>
<dependency>
<groupId>com.zendesk</groupId>
<artifactId>mysql-binlog-connector-java</artifactId>
<version>${version.mysql.binlog}</version>
</dependency>
<dependency>
<groupId>mil.nga</groupId>
<artifactId>wkb</artifactId>
<version>1.0.2</version>
</dependency>
<!-- MongoDB Java driver -->
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongodb-driver</artifactId>
<version>${version.mongo.driver}</version>
</dependency>
<!-- SQL Server driver -->
<dependency>
<groupId>com.microsoft.sqlserver</groupId>
<artifactId>mssql-jdbc</artifactId>
<version>${version.sqlserver.driver}</version>
</dependency>
<!-- Logging -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${version.org.slf4j}</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>${version.org.slf4j}</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>${version.log4j}</version>
</dependency>
<!-- Scripting -->
<dependency>
<groupId>org.codehaus.groovy</groupId>
<artifactId>groovy</artifactId>
<version>${version.groovy}</version>
</dependency>
<dependency>
<groupId>org.codehaus.groovy</groupId>
<artifactId>groovy-json</artifactId>
<version>${version.groovy}</version>
</dependency>
<dependency>
<groupId>org.codehaus.groovy</groupId>
<artifactId>groovy-jsr223</artifactId>
<version>${version.groovy}</version>
</dependency>
<dependency>
<groupId>org.graalvm.js</groupId>
<artifactId>js</artifactId>
<version>${version.graalvm.js}</version>
</dependency>
<dependency>
<groupId>org.graalvm.js</groupId>
<artifactId>js-scriptengine</artifactId>
<version>${version.graalvm.js}</version>
</dependency>
<!-- Testing utilities -->
<dependency>
<groupId>org.testcontainers</groupId>
<artifactId>testcontainers-bom</artifactId>
<version>${version.testcontainers}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>${version.okhttp}</version>
</dependency>
<!-- Test dependencies -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${version.junit}</version>
</dependency>
<dependency>
<groupId>org.easytesting</groupId>
<artifactId>fest-assert</artifactId>
<version>${version.fest}</version>
</dependency>
<dependency>
<groupId>org.openjdk.jmh</groupId>
<artifactId>jmh-core</artifactId>
<version>${version.jmh}</version>
</dependency>
<dependency>
<groupId>org.openjdk.jmh</groupId>
<artifactId>jmh-generator-annprocess</artifactId>
<version>${version.jmh}</version>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<version>${version.mockito}</version>
</dependency>
<dependency>
<groupId>org.awaitility</groupId>
<artifactId>awaitility</artifactId>
<version>${version.awaitility}</version>
</dependency>
<dependency>
<groupId>com.jayway.jsonpath</groupId>
<artifactId>json-path</artifactId>
<version>${version.jsonpath}</version>
</dependency>
<!-- Debezium artifacts -->
<dependency>
<groupId>io.debezium</groupId>
<artifactId>debezium-api</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>io.debezium</groupId>
<artifactId>debezium-core</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>io.debezium</groupId>
<artifactId>debezium-scripting</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>io.debezium</groupId>
<artifactId>debezium-embedded</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>io.debezium</groupId>
<artifactId>debezium-connector-jdbc</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>io.debezium</groupId>
<artifactId>debezium-connector-postgres</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>io.debezium</groupId>
<artifactId>debezium-connector-postgres-test</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>io.debezium</groupId>
<artifactId>debezium-connector-mysql</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>io.debezium</groupId>
<artifactId>debezium-ddl-parser</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>io.debezium</groupId>
<artifactId>debezium-connector-mongodb</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>io.debezium</groupId>
<artifactId>debezium-connector-sqlserver</artifactId>
<version>${project.version}</version>
</dependency>
<!-- Debezium test artifacts -->
<dependency>
<groupId>io.debezium</groupId>
<artifactId>debezium-core</artifactId>
<version>${project.version}</version>
<type>test-jar</type>
</dependency>
<dependency>
<groupId>io.debezium</groupId>
<artifactId>debezium-embedded</artifactId>
<version>${project.version}</version>
<type>test-jar</type>
</dependency>
<dependency>
<groupId>io.debezium</groupId>
<artifactId>debezium-connector-mysql</artifactId>
<version>${project.version}</version>
<type>test-jar</type>
</dependency>
<dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
<version>2.3.1</version>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
</dependencies>
<build>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-enforcer-plugin</artifactId>
<version>${version.enforcer.plugin}</version>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>${version.compiler.plugin}</version>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-source-plugin</artifactId>
<version>${version.source.plugin}</version>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-javadoc-plugin</artifactId>
<version>${version.javadoc.plugin}</version>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-release-plugin</artifactId>
<version>${version.release.plugin}</version>
</plugin>
<plugin>
<groupId>org.sonatype.plugins</groupId>
<artifactId>nexus-staging-maven-plugin</artifactId>
<version>${version.staging.plugin}</version>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>${version.surefire.plugin}</version>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-checkstyle-plugin</artifactId>
<version>${version.checkstyle.plugin}</version>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-report-plugin</artifactId>
<version>${version.surefire.plugin}</version>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-resources-plugin</artifactId>
<version>${version.resources.plugin}</version>
</plugin>
<plugin>
<groupId>org.apache.maven.shared</groupId>
<artifactId>maven-filtering</artifactId>
<version>${version.filtering.plugin}</version>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<version>${version.dependency.plugin}</version>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-gpg-plugin</artifactId>
<version>${version.gpg.plugin}</version>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-failsafe-plugin</artifactId>
<version>${version.failsafe.plugin}</version>
<configuration>
<argLine>${debug.argline} ${modules.argline} ${test.argline}</argLine>
<useSystemClassLoader>${useSystemClassLoader}</useSystemClassLoader>
</configuration>
</plugin>
<plugin>
<groupId>com.googlecode.maven-java-formatter-plugin</groupId>
<artifactId>maven-java-formatter-plugin</artifactId>
<version>${version.google.formatter.plugin}</version>
</plugin>
<plugin>
<groupId>io.fabric8</groupId>
<artifactId>docker-maven-plugin</artifactId>
<version>${version.docker.maven.plugin}</version>
</plugin>
<plugin>
<groupId>com.github.os72</groupId>
<artifactId>protoc-jar-maven-plugin</artifactId>
<version>${version.protoc.maven.plugin}</version>
</plugin>
<plugin>
<groupId>net.revelc.code.formatter</groupId>
<artifactId>formatter-maven-plugin</artifactId>
<version>${version.code.formatter}</version>
<dependencies>
<dependency>
<groupId>io.debezium</groupId>
<artifactId>debezium-ide-configs</artifactId>
<version>${project.version}</version>
</dependency>
</dependencies>
<configuration>
<configFile>/eclipse/debezium-formatter.xml</configFile>
<skip>${format.skip}</skip>
</configuration>
</plugin>
<plugin>
<groupId>net.revelc.code</groupId>
<artifactId>impsort-maven-plugin</artifactId>
<version>${version.impsort}</version>
<configuration>
<groups>java.,javax.,org.,com.,io.</groups>
<staticGroups>*</staticGroups>
<staticAfter>false</staticAfter>
<skip>${format.skip}</skip>
<removeUnused>true</removeUnused>
</configuration>
</plugin>
<plugin>
<groupId>org.jboss.jandex</groupId>
<artifactId>jandex-maven-plugin</artifactId>
<version>${version.jandex}</version>
</plugin>
<plugin>
<groupId>org.revapi</groupId>
<artifactId>revapi-maven-plugin</artifactId>
<version>${version.revapi.plugin}</version>
<dependencies>
<dependency>
<groupId>io.debezium</groupId>
<artifactId>debezium-revapi</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>org.revapi</groupId>
<artifactId>revapi-java</artifactId>
<version>${version.revapi-java.plugin}</version>
</dependency>
</dependencies>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>build-helper-maven-plugin</artifactId>
<version>${version.build-helper.plugin}</version>
</plugin>
</plugins>
</pluginManagement>
<plugins>
<plugin>
<groupId>net.revelc.code.formatter</groupId>
<artifactId>formatter-maven-plugin</artifactId>
<executions>
<execution>
<phase>process-sources</phase>
<goals>
<goal>${format.formatter.goal}</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>net.revelc.code</groupId>
<artifactId>impsort-maven-plugin</artifactId>
<configuration>
<removeUnused>true</removeUnused>
</configuration>
<executions>
<execution>
<id>sort-imports</id>
<goals>
<goal>${format.imports.goal}</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-source-plugin</artifactId>
<executions>
<execution>
<id>attach-sources</id>
<phase>verify</phase>
<goals>
<goal>jar-no-fork</goal>
</goals>
</execution>
<execution>
<id>attach-test-sources</id>
<goals>
<goal>test-jar-no-fork</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-release-plugin</artifactId>
<configuration>
<pushChanges>false</pushChanges>
<releaseProfiles>docs,assembly,release-sign-artifacts,release</releaseProfiles>
</configuration>
</plugin>
<plugin>
<groupId>org.sonatype.plugins</groupId>
<artifactId>nexus-staging-maven-plugin</artifactId>
<extensions>true</extensions>
<configuration>
<serverId>ossrh</serverId>
<nexusUrl>https://oss.sonatype.org/</nexusUrl>
<autoReleaseAfterClose>false</autoReleaseAfterClose>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>${maven.compiler.source}</source>
<target>${maven.compiler.target}</target>
<encoding>${project.build.sourceEncoding}</encoding>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-resources-plugin</artifactId>
<configuration>
<encoding>${project.build.sourceEncoding}</encoding>
</configuration>
</plugin>
<plugin>
<groupId>com.googlecode.maven-java-formatter-plugin</groupId>
<artifactId>maven-java-formatter-plugin</artifactId>
<configuration>
<configFile>${project.basedir}/support/eclipse-formatting.xml</configFile>
<lineEnding>LF</lineEnding>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-enforcer-plugin</artifactId>
<executions>
<execution>
<id>enforce-maven</id>
<goals>
<goal>enforce</goal>
</goals>
<configuration>
<rules>
<requireMavenVersion>
<version>3.6.3</version>
</requireMavenVersion>
</rules>
</configuration>
</execution>
</executions>
</plugin>
<!--
Build a test-jar for each project, so that src/test/* resources and
classes can be used in other projects. Also customize how the jar
files are assembled.
-->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<executions>
<execution>
<id>test-jar</id>
<goals>
<goal>test-jar</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<systemProperties combine.children="append">
<property>
<name>java.io.tmpdir</name>
<value>${project.build.directory}</value>
</property>
<property>
<name>skipLongRunningTests</name>
<value>${skipLongRunningTests}</value>
</property>
<property>
<name>dbz.test.data.dir</name>
<value>${project.build.directory}/data</value>
</property>
</systemProperties>
<argLine>-Djava.awt.headless=true ${debug.argline} ${modules.argline}</argLine>
<!--runOrder>alphabetical</runOrder-->
<useFile>false</useFile>
<enableAssertions>true</enableAssertions>
<forkCount>${forkCount}</forkCount>
<reuseForks>${reuseForks}</reuseForks>
<useSystemClassLoader>${useSystemClassLoader}</useSystemClassLoader>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-checkstyle-plugin</artifactId>
<dependencies>
<dependency>
<groupId>io.debezium</groupId>
<artifactId>debezium-checkstyle</artifactId>
<version>${project.version}</version>
</dependency>
</dependencies>
<configuration>
<configLocation>checkstyle.xml</configLocation>
<suppressionsLocation>checkstyle-suppressions.xml</suppressionsLocation>
<suppressionsFileExpression>checkstyle.suppressions.file</suppressionsFileExpression>
<consoleOutput>true</consoleOutput>
<failsOnError>true</failsOnError>
<linkXRef>false</linkXRef>
<violationSeverity>error</violationSeverity>
<includeTestSourceDirectory>true</includeTestSourceDirectory>
</configuration>
<executions>
<execution>
<id>check-style</id>
<phase>verify</phase>
<goals>
<goal>checkstyle</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<!-- Serves as support for configuring Revapi -->
<groupId>org.codehaus.mojo</groupId>
<artifactId>build-helper-maven-plugin</artifactId>
<executions>
<execution>
<id>parse-version</id>
<goals>
<!-- This defines the ${parsedVersion.*} properties used in the Revapi config. -->
<goal>parse-version</goal>
</goals>
<phase>validate</phase>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.revapi</groupId>
<artifactId>revapi-maven-plugin</artifactId>
<configuration>
<failOnMissingConfigurationFiles>false</failOnMissingConfigurationFiles>
<!-- Consider changes from the latest .Final version, not from the latest non-snapshot. -->
<versionFormat>\d+\.\d+\.\d+\.Final</versionFormat>
<ignoreSuggestionsFormat>xml</ignoreSuggestionsFormat>
<analysisConfigurationFiles>
<configurationFile>
<!-- common API checking configuration -->
<resource>revapi/revapi-configuration.xml</resource>
</configurationFile>
<configurationFile>
<!-- API changes recorded in the support/revapi module -->
<resource>revapi/debezium-api-changes.xml</resource>
<roots>
<!--
The XML file has "<analysisConfiguration>" root node, underneath which
there are nodes named after each version.
This way we only need a single file for all releases of Debezium.
-->
<root>analysisConfiguration/version-${parsedVersion.majorVersion}.${parsedVersion.minorVersion}.${parsedVersion.incrementalVersion}</root>
</roots>
</configurationFile>
</analysisConfigurationFiles>
</configuration>
<executions>
<execution>
<goals>
<goal>check</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
<profiles>
<!--
###################################################################
Enable remotely debugging on the command line
###################################################################
To use, specify "-Ddebug=true" on the Maven command line
(typically used when running a single test). Then, start
remote debugger (on port 1044) and connect.
-->
<profile>
<id>debug</id>
<activation>
<property>
<name>debug</name>
<value>true</value>
</property>
</activation>
<properties>
<!-- Useful for remotely debugging the unit tests run by Surefire ... -->
<debug.argline>-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=1044</debug.argline>
</properties>
</profile>
<profile>
<id>assembly</id>
<properties>
<skipLongRunningTests>false</skipLongRunningTests>
</properties>
<modules>
<!--module>integration-tests</module-->
</modules>
</profile>
<profile>
<id>release</id>
<properties>
<skipLongRunningTests>false</skipLongRunningTests>
</properties>
</profile>
<profile>
<id>performance</id>
<properties>
<skipLongRunningTests>false</skipLongRunningTests>
</properties>
</profile>
<profile>
<id>docs</id>
<activation>
<activeByDefault>false</activeByDefault>
<property>
<name>docs</name>
<value>true</value>
</property>
</activation>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-javadoc-plugin</artifactId>
<version>${version.javadoc.plugin}</version>
<configuration>
<show>private</show>
<nohelp>true</nohelp>
</configuration>
<executions>
<execution>
<id>attach-javadocs</id>
<goals>
<goal>jar</goal>
</goals>
</execution>
<execution>
<id>attach-test-javadocs</id>
<goals>
<goal>test-jar</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</profile>
<profile>
<id>release-sign-artifacts</id>
<activation>
<property>
<name>performRelease</name>
<value>true</value>
</property>
</activation>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-gpg-plugin</artifactId>
<executions>
<execution>
<id>sign-artifacts</id>
<phase>verify</phase>
<goals>
<goal>sign</goal>
</goals>
<configuration>
<gpgArguments>
<arg>--pinentry-mode</arg>
<arg>loopback</arg>
</gpgArguments>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</profile>
<profile>
<id>jdk11</id>
<activation>
<jdk>11</jdk>
</activation>
<properties>
<modules.argline>--illegal-access=permit</modules.argline>
<!-- When using this profile the following warning pops up,
[WARNING] bootstrap class path not set in conjunction with -source 8 -->
<maven.compiler.source>11</maven.compiler.source>
<maven.compiler.target>11</maven.compiler.target>
<release>11</release>
</properties>
</profile>
</profiles>
</project>
| {
"pile_set_name": "Github"
} |
'''
Given a string, find the longest substring that contains only two unique characters. For example, given "abcbbbbcccbdddadacb", the longest substring that contains 2 unique character is "bcbbbbcccb".
'''
class Solution(object):
def lengthOfLongestSubstringTwoDistinct(self, s):
"""
:type s: str
:rtype: int
"""
if not s:
return 0
unique_char, start, result = {}, 0, 0
for index, char in enumerate(s):
if char in unique_char:
unique_char[s] += 1
else:
unique_char[s] = 1
if len(unique_char) <= 2:
result = max(result, index-start+1)
else:
while len(unique_char) > 2:
char_index = s[start]
count = unique_char[char_index]
if count == 1:
del unique_char[char_index]
else:
unique_char[char_index] -= 1
start += 1
return result
| {
"pile_set_name": "Github"
} |
struct v2f_vertex_lit {
vec2 uv;
vec4 diff;
vec4 spec;
};
struct v2f_img {
vec4 pos;
vec2 uv;
};
struct appdata_img {
vec4 vertex;
vec2 texcoord;
};
struct SurfaceOutput {
vec3 Albedo;
vec3 Normal;
vec3 Emission;
float Specular;
float Gloss;
float Alpha;
};
struct Input {
vec2 uv_MainTex;
vec2 uv_DecalTex;
};
struct v2f_surf {
vec4 pos;
float fog;
vec4 hip_pack0;
vec3 normal;
vec3 lightDir;
};
struct appdata_full {
vec4 vertex;
vec4 tangent;
vec3 normal;
vec4 texcoord;
vec4 texcoord1;
vec4 color;
};
uniform vec4 _Color;
uniform sampler2D _DecalTex;
uniform vec4 _LightColor0;
uniform sampler2D _MainTex;
void surf( in Input IN, inout SurfaceOutput o );
vec4 LightingLambert( in SurfaceOutput s, in vec3 lightDir, in float atten );
vec4 frag_surf( in v2f_surf IN );
void surf( in Input IN, inout SurfaceOutput o ) {
vec4 c;
vec4 decal;
c = texture2D( _MainTex, IN.uv_MainTex);
decal = texture2D( _DecalTex, IN.uv_DecalTex);
c.xyz = mix( c.xyz , decal.xyz , vec3( decal.w ));
c *= _Color;
o.Albedo = c.xyz ;
o.Alpha = c.w ;
}
vec4 LightingLambert( in SurfaceOutput s, in vec3 lightDir, in float atten ) {
float diff;
vec4 c;
diff = max( 0.000000, dot( s.Normal, lightDir));
c.xyz = ((s.Albedo * _LightColor0.xyz ) * ((diff * atten) * 2.00000));
c.w = s.Alpha;
return c;
}
vec4 frag_surf( in v2f_surf IN ) {
Input surfIN;
SurfaceOutput o;
vec3 lightDir;
vec4 c;
surfIN.uv_MainTex = IN.hip_pack0.xy ;
surfIN.uv_DecalTex = IN.hip_pack0.zw ;
o.Albedo = vec3( 0.000000);
o.Emission = vec3( 0.000000);
o.Specular = 0.000000;
o.Alpha = 0.000000;
o.Gloss = 0.000000;
o.Normal = IN.normal;
surf( surfIN, o);
lightDir = IN.lightDir;
c = LightingLambert( o, lightDir, 1.00000);
c.w = 0.000000;
return c;
}
varying vec4 xlv_FOG;
void main() {
vec4 xl_retval;
v2f_surf xlt_IN;
xlt_IN.pos = vec4(0.0);
xlt_IN.fog = float( xlv_FOG);
xlt_IN.hip_pack0 = vec4( gl_TexCoord[0]);
xlt_IN.normal = vec3( gl_TexCoord[1]);
xlt_IN.lightDir = vec3( gl_TexCoord[2]);
xl_retval = frag_surf( xlt_IN);
gl_FragData[0] = vec4( xl_retval);
}
| {
"pile_set_name": "Github"
} |
$('#search_results').html("<%= escape_javascript render :partial => 'extended_search' %>");
$('#search_form_div').html("<%= escape_javascript render :partial => 'form' %>");
$('#focus_options ul li a span').removeClass('active');
<% if params[:type].present? %>
$('#focus_options ul li a span.<%= params[:type].pluralize.downcase %>').addClass('active');
<% else %>
$('#focus_options ul li a span.global').addClass('active');
<% end %>
$('title').text('<%= t('search.name')%> <%= escape_javascript(params[:q].present? ? ": #{params[:q]}" : "")%>');
<% if too_short_query? %>
$('#too_short_error').show();
<% else %>
$('#too_short_error').hide();
<% end %>
$('#global_search_input').removeClass("searching");
setActivityPrivacyTooltips();
| {
"pile_set_name": "Github"
} |
if (e = 1)
doSomething();
while (obj = arr.next())
doSomething();
for (var b; b = arr.next();)
doSomething();
do {
doSomething();
} while (b = arr.next());
if (e /= 1)
doSomething();
while (obj /= arr.next())
doSomething();
for (var b; b /= arr.next();)
doSomething();
do {
doSomething();
} while (b /= arr.next());
function foo(a) {
return a = 1;
}
function bar(a) {
return b.a = 1;
}
| {
"pile_set_name": "Github"
} |
# encoding: utf-8
module RedisCopy
module UI
extend Implements::Interface
def initialize(options)
@options = options
end
def confirm?(prompt)
return super if defined?(super)
raise NotImplementedError
end
def abort(message = nil)
return super if defined?(super)
raise NotImplementedError
end
def notify(message)
return super if defined?(super)
raise NotImplementedError
end
def debug(message)
notify(message) if @options[:debug]
end
end
end
# load the bundled uis:
require_relative 'ui/auto_run'
require_relative 'ui/command_line'
| {
"pile_set_name": "Github"
} |
/*
* Copyright 2015-2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
package com.amazonaws.services.docdb.model.transform;
import java.util.ArrayList;
import javax.xml.stream.events.XMLEvent;
import javax.annotation.Generated;
import com.amazonaws.services.docdb.model.*;
import com.amazonaws.transform.Unmarshaller;
import com.amazonaws.transform.StaxUnmarshallerContext;
import com.amazonaws.transform.SimpleTypeStaxUnmarshallers.*;
/**
* EngineDefaults StAX Unmarshaller
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class EngineDefaultsStaxUnmarshaller implements Unmarshaller<EngineDefaults, StaxUnmarshallerContext> {
public EngineDefaults unmarshall(StaxUnmarshallerContext context) throws Exception {
EngineDefaults engineDefaults = new EngineDefaults();
int originalDepth = context.getCurrentDepth();
int targetDepth = originalDepth + 1;
if (context.isStartOfDocument())
targetDepth += 3;
while (true) {
XMLEvent xmlEvent = context.nextEvent();
if (xmlEvent.isEndDocument())
return engineDefaults;
if (xmlEvent.isAttribute() || xmlEvent.isStartElement()) {
if (context.testExpression("DBParameterGroupFamily", targetDepth)) {
engineDefaults.setDBParameterGroupFamily(StringStaxUnmarshaller.getInstance().unmarshall(context));
continue;
}
if (context.testExpression("Marker", targetDepth)) {
engineDefaults.setMarker(StringStaxUnmarshaller.getInstance().unmarshall(context));
continue;
}
if (context.testExpression("Parameters", targetDepth)) {
engineDefaults.withParameters(new ArrayList<Parameter>());
continue;
}
if (context.testExpression("Parameters/Parameter", targetDepth)) {
engineDefaults.withParameters(ParameterStaxUnmarshaller.getInstance().unmarshall(context));
continue;
}
} else if (xmlEvent.isEndElement()) {
if (context.getCurrentDepth() < originalDepth) {
return engineDefaults;
}
}
}
}
private static EngineDefaultsStaxUnmarshaller instance;
public static EngineDefaultsStaxUnmarshaller getInstance() {
if (instance == null)
instance = new EngineDefaultsStaxUnmarshaller();
return instance;
}
}
| {
"pile_set_name": "Github"
} |
/* *
*
* Popup generator for Stock tools
*
* (c) 2009-2017 Sebastian Bochan
*
* License: www.highcharts.com/license
*
* !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!!
*
* */
'use strict';
import H from '../../Core/Globals.js';
import NavigationBindings from './NavigationBindings.js';
import Pointer from '../../Core/Pointer.js';
import U from '../../Core/Utilities.js';
var addEvent = U.addEvent, createElement = U.createElement, defined = U.defined, getOptions = U.getOptions, isArray = U.isArray, isObject = U.isObject, isString = U.isString, objectEach = U.objectEach, pick = U.pick, wrap = U.wrap;
var indexFilter = /\d/g, PREFIX = 'highcharts-', DIV = 'div', INPUT = 'input', LABEL = 'label', BUTTON = 'button', SELECT = 'select', OPTION = 'option', SPAN = 'span', UL = 'ul', LI = 'li', H3 = 'h3';
/* eslint-disable no-invalid-this, valid-jsdoc */
// onContainerMouseDown blocks internal popup events, due to e.preventDefault.
// Related issue #4606
wrap(Pointer.prototype, 'onContainerMouseDown', function (proceed, e) {
var popupClass = e.target && e.target.className;
// elements is not in popup
if (!(isString(popupClass) &&
popupClass.indexOf(PREFIX + 'popup-field') >= 0)) {
proceed.apply(this, Array.prototype.slice.call(arguments, 1));
}
});
H.Popup = function (parentDiv, iconsURL) {
this.init(parentDiv, iconsURL);
};
H.Popup.prototype = {
/**
* Initialize the popup. Create base div and add close button.
* @private
* @param {Highcharts.HTMLDOMElement} parentDiv
* Container where popup should be placed
* @param {string} iconsURL
* Icon URL
*/
init: function (parentDiv, iconsURL) {
// create popup div
this.container = createElement(DIV, {
className: PREFIX + 'popup'
}, null, parentDiv);
this.lang = this.getLangpack();
this.iconsURL = iconsURL;
// add close button
this.addCloseBtn();
},
/**
* Create HTML element and attach click event (close popup).
* @private
*/
addCloseBtn: function () {
var _self = this, closeBtn;
// create close popup btn
closeBtn = createElement(DIV, {
className: PREFIX + 'popup-close'
}, null, this.container);
closeBtn.style['background-image'] = 'url(' +
this.iconsURL + 'close.svg)';
['click', 'touchstart'].forEach(function (eventName) {
addEvent(closeBtn, eventName, function () {
_self.closePopup();
});
});
},
/**
* Create two columns (divs) in HTML.
* @private
* @param {Highcharts.HTMLDOMElement} container
* Container of columns
* @return {Highcharts.Dictionary<Highcharts.HTMLDOMElement>}
* Reference to two HTML columns (lhsCol, rhsCol)
*/
addColsContainer: function (container) {
var rhsCol, lhsCol;
// left column
lhsCol = createElement(DIV, {
className: PREFIX + 'popup-lhs-col'
}, null, container);
// right column
rhsCol = createElement(DIV, {
className: PREFIX + 'popup-rhs-col'
}, null, container);
// wrapper content
createElement(DIV, {
className: PREFIX + 'popup-rhs-col-wrapper'
}, null, rhsCol);
return {
lhsCol: lhsCol,
rhsCol: rhsCol
};
},
/**
* Create input with label.
* @private
* @param {string} option
* Chain of fields i.e params.styles.fontSize
* @param {string} type
* Indicator type
* @param {Highhcharts.HTMLDOMElement}
* Container where elements should be added
* @param {string} value
* Default value of input i.e period value is 14, extracted from
* defaultOptions (ADD mode) or series options (EDIT mode)
*/
addInput: function (option, type, parentDiv, value) {
var optionParamList = option.split('.'), optionName = optionParamList[optionParamList.length - 1], lang = this.lang, inputName = PREFIX + type + '-' + optionName;
if (!inputName.match(indexFilter)) {
// add label
createElement(LABEL, {
innerHTML: lang[optionName] || optionName,
htmlFor: inputName
}, null, parentDiv);
}
// add input
createElement(INPUT, {
name: inputName,
value: value[0],
type: value[1],
className: PREFIX + 'popup-field'
}, null, parentDiv).setAttribute(PREFIX + 'data-name', option);
},
/**
* Create button.
* @private
* @param {Highcharts.HTMLDOMElement} parentDiv
* Container where elements should be added
* @param {string} label
* Text placed as button label
* @param {string} type
* add | edit | remove
* @param {Function} callback
* On click callback
* @param {Highcharts.HTMLDOMElement} fieldsDiv
* Container where inputs are generated
* @return {Highcharts.HTMLDOMElement}
* HTML button
*/
addButton: function (parentDiv, label, type, callback, fieldsDiv) {
var _self = this, closePopup = this.closePopup, getFields = this.getFields, button;
button = createElement(BUTTON, {
innerHTML: label
}, null, parentDiv);
['click', 'touchstart'].forEach(function (eventName) {
addEvent(button, eventName, function () {
closePopup.call(_self);
return callback(getFields(fieldsDiv, type));
});
});
return button;
},
/**
* Get values from all inputs and create JSON.
* @private
* @param {Highcharts.HTMLDOMElement} - container where inputs are created
* @param {string} - add | edit | remove
* @return {Highcharts.PopupFieldsObject} - fields
*/
getFields: function (parentDiv, type) {
var inputList = parentDiv.querySelectorAll('input'), optionSeries = '#' + PREFIX + 'select-series > option:checked', optionVolume = '#' + PREFIX + 'select-volume > option:checked', linkedTo = parentDiv.querySelectorAll(optionSeries)[0], volumeTo = parentDiv.querySelectorAll(optionVolume)[0], seriesId, param, fieldsOutput;
fieldsOutput = {
actionType: type,
linkedTo: linkedTo && linkedTo.getAttribute('value'),
fields: {}
};
[].forEach.call(inputList, function (input) {
param = input.getAttribute(PREFIX + 'data-name');
seriesId = input.getAttribute(PREFIX + 'data-series-id');
// params
if (seriesId) {
fieldsOutput.seriesId = input.value;
}
else if (param) {
fieldsOutput.fields[param] = input.value;
}
else {
// type like sma / ema
fieldsOutput.type = input.value;
}
});
if (volumeTo) {
fieldsOutput.fields['params.volumeSeriesID'] = volumeTo.getAttribute('value');
}
return fieldsOutput;
},
/**
* Reset content of the current popup and show.
* @private
*/
showPopup: function () {
var popupDiv = this.container, toolbarClass = PREFIX + 'annotation-toolbar', popupCloseBtn = popupDiv
.querySelectorAll('.' + PREFIX + 'popup-close')[0];
// reset content
popupDiv.innerHTML = '';
// reset toolbar styles if exists
if (popupDiv.className.indexOf(toolbarClass) >= 0) {
popupDiv.classList.remove(toolbarClass);
// reset toolbar inline styles
popupDiv.removeAttribute('style');
}
// add close button
popupDiv.appendChild(popupCloseBtn);
popupDiv.style.display = 'block';
},
/**
* Hide popup.
* @private
*/
closePopup: function () {
this.popup.container.style.display = 'none';
},
/**
* Create content and show popup.
* @private
* @param {string} - type of popup i.e indicators
* @param {Highcharts.Chart} - chart
* @param {Highcharts.AnnotationsOptions} - options
* @param {Function} - on click callback
*/
showForm: function (type, chart, options, callback) {
this.popup = chart.navigationBindings.popup;
// show blank popup
this.showPopup();
// indicator form
if (type === 'indicators') {
this.indicators.addForm.call(this, chart, options, callback);
}
// annotation small toolbar
if (type === 'annotation-toolbar') {
this.annotations.addToolbar.call(this, chart, options, callback);
}
// annotation edit form
if (type === 'annotation-edit') {
this.annotations.addForm.call(this, chart, options, callback);
}
// flags form - add / edit
if (type === 'flag') {
this.annotations.addForm.call(this, chart, options, callback, true);
}
},
/**
* Return lang definitions for popup.
* @private
* @return {Highcharts.Dictionary<string>} - elements translations.
*/
getLangpack: function () {
return getOptions().lang.navigation.popup;
},
annotations: {
/**
* Create annotation simple form. It contains two buttons
* (edit / remove) and text label.
* @private
* @param {Highcharts.Chart} - chart
* @param {Highcharts.AnnotationsOptions} - options
* @param {Function} - on click callback
*/
addToolbar: function (chart, options, callback) {
var _self = this, lang = this.lang, popupDiv = this.popup.container, showForm = this.showForm, toolbarClass = PREFIX + 'annotation-toolbar', button;
// set small size
if (popupDiv.className.indexOf(toolbarClass) === -1) {
popupDiv.className += ' ' + toolbarClass;
}
// set position
popupDiv.style.top = chart.plotTop + 10 + 'px';
// create label
createElement(SPAN, {
innerHTML: pick(
// Advanced annotations:
lang[options.langKey] || options.langKey,
// Basic shapes:
options.shapes && options.shapes[0].type)
}, null, popupDiv);
// add buttons
button = this.addButton(popupDiv, lang.removeButton || 'remove', 'remove', callback, popupDiv);
button.className += ' ' + PREFIX + 'annotation-remove-button';
button.style['background-image'] = 'url(' +
this.iconsURL + 'destroy.svg)';
button = this.addButton(popupDiv, lang.editButton || 'edit', 'edit', function () {
showForm.call(_self, 'annotation-edit', chart, options, callback);
}, popupDiv);
button.className += ' ' + PREFIX + 'annotation-edit-button';
button.style['background-image'] = 'url(' +
this.iconsURL + 'edit.svg)';
},
/**
* Create annotation simple form.
* It contains fields with param names.
* @private
* @param {Highcharts.Chart} chart
* Chart
* @param {Object} options
* Options
* @param {Function} callback
* On click callback
* @param {boolean} [isInit]
* If it is a form declared for init annotation
*/
addForm: function (chart, options, callback, isInit) {
var popupDiv = this.popup.container, lang = this.lang, bottomRow, lhsCol;
// create title of annotations
lhsCol = createElement('h2', {
innerHTML: lang[options.langKey] || options.langKey,
className: PREFIX + 'popup-main-title'
}, null, popupDiv);
// left column
lhsCol = createElement(DIV, {
className: PREFIX + 'popup-lhs-col ' + PREFIX + 'popup-lhs-full'
}, null, popupDiv);
bottomRow = createElement(DIV, {
className: PREFIX + 'popup-bottom-row'
}, null, popupDiv);
this.annotations.addFormFields.call(this, lhsCol, chart, '', options, [], true);
this.addButton(bottomRow, isInit ?
(lang.addButton || 'add') :
(lang.saveButton || 'save'), isInit ? 'add' : 'save', callback, popupDiv);
},
/**
* Create annotation's form fields.
* @private
* @param {Highcharts.HTMLDOMElement} parentDiv
* Div where inputs are placed
* @param {Highcharts.Chart} chart
* Chart
* @param {string} parentNode
* Name of parent to create chain of names
* @param {Highcharts.AnnotationsOptions} options
* Options
* @param {Array<unknown>} storage
* Array where all items are stored
* @param {boolean} [isRoot]
* Recursive flag for root
*/
addFormFields: function (parentDiv, chart, parentNode, options, storage, isRoot) {
var _self = this, addFormFields = this.annotations.addFormFields, addInput = this.addInput, lang = this.lang, parentFullName, titleName;
objectEach(options, function (value, option) {
// create name like params.styles.fontSize
parentFullName = parentNode !== '' ?
parentNode + '.' + option : option;
if (isObject(value)) {
if (
// value is object of options
!isArray(value) ||
// array of objects with params. i.e labels in Fibonacci
(isArray(value) && isObject(value[0]))) {
titleName = lang[option] || option;
if (!titleName.match(indexFilter)) {
storage.push([
true,
titleName,
parentDiv
]);
}
addFormFields.call(_self, parentDiv, chart, parentFullName, value, storage, false);
}
else {
storage.push([
_self,
parentFullName,
'annotation',
parentDiv,
value
]);
}
}
});
if (isRoot) {
storage = storage.sort(function (a) {
return a[1].match(/format/g) ? -1 : 1;
});
storage.forEach(function (genInput) {
if (genInput[0] === true) {
createElement(SPAN, {
className: PREFIX + 'annotation-title',
innerHTML: genInput[1]
}, null, genInput[2]);
}
else {
addInput.apply(genInput[0], genInput.splice(1));
}
});
}
}
},
indicators: {
/**
* Create indicator's form. It contains two tabs (ADD and EDIT) with
* content.
* @private
*/
addForm: function (chart, _options, callback) {
var tabsContainers, indicators = this.indicators, lang = this.lang, buttonParentDiv;
// add tabs
this.tabs.init.call(this, chart);
// get all tabs content divs
tabsContainers = this.popup.container
.querySelectorAll('.' + PREFIX + 'tab-item-content');
// ADD tab
this.addColsContainer(tabsContainers[0]);
indicators.addIndicatorList.call(this, chart, tabsContainers[0], 'add');
buttonParentDiv = tabsContainers[0]
.querySelectorAll('.' + PREFIX + 'popup-rhs-col')[0];
this.addButton(buttonParentDiv, lang.addButton || 'add', 'add', callback, buttonParentDiv);
// EDIT tab
this.addColsContainer(tabsContainers[1]);
indicators.addIndicatorList.call(this, chart, tabsContainers[1], 'edit');
buttonParentDiv = tabsContainers[1]
.querySelectorAll('.' + PREFIX + 'popup-rhs-col')[0];
this.addButton(buttonParentDiv, lang.saveButton || 'save', 'edit', callback, buttonParentDiv);
this.addButton(buttonParentDiv, lang.removeButton || 'remove', 'remove', callback, buttonParentDiv);
},
/**
* Create HTML list of all indicators (ADD mode) or added indicators
* (EDIT mode).
* @private
*/
addIndicatorList: function (chart, parentDiv, listType) {
var _self = this, lhsCol = parentDiv.querySelectorAll('.' + PREFIX + 'popup-lhs-col')[0], rhsCol = parentDiv.querySelectorAll('.' + PREFIX + 'popup-rhs-col')[0], isEdit = listType === 'edit', series = (isEdit ?
chart.series : // EDIT mode
chart.options.plotOptions // ADD mode
), addFormFields = this.indicators.addFormFields, rhsColWrapper, indicatorList, item;
// create wrapper for list
indicatorList = createElement(UL, {
className: PREFIX + 'indicator-list'
}, null, lhsCol);
rhsColWrapper = rhsCol
.querySelectorAll('.' + PREFIX + 'popup-rhs-col-wrapper')[0];
objectEach(series, function (serie, value) {
var seriesOptions = serie.options;
if (serie.params ||
seriesOptions && seriesOptions.params) {
var indicatorNameType = _self.indicators.getNameType(serie, value), indicatorType = indicatorNameType.type;
item = createElement(LI, {
className: PREFIX + 'indicator-list',
innerHTML: indicatorNameType.name
}, null, indicatorList);
['click', 'touchstart'].forEach(function (eventName) {
addEvent(item, eventName, function () {
addFormFields.call(_self, chart, isEdit ? serie : series[indicatorType], indicatorNameType.type, rhsColWrapper);
// add hidden input with series.id
if (isEdit && serie.options) {
createElement(INPUT, {
type: 'hidden',
name: PREFIX + 'id-' + indicatorType,
value: serie.options.id
}, null, rhsColWrapper)
.setAttribute(PREFIX + 'data-series-id', serie.options.id);
}
});
});
}
});
// select first item from the list
if (indicatorList.childNodes.length > 0) {
indicatorList.childNodes[0].click();
}
},
/**
* Extract full name and type of requested indicator.
* @private
* @param {Highcharts.Series} series
* Series which name is needed. (EDIT mode - defaultOptions.series, ADD
* mode - indicator series).
* @param {string} - indicator type like: sma, ema, etc.
* @return {Object} - series name and type like: sma, ema, etc.
*/
getNameType: function (series, type) {
var options = series.options, seriesTypes = H.seriesTypes,
// add mode
seriesName = seriesTypes[type] &&
seriesTypes[type].prototype.nameBase || type.toUpperCase(), seriesType = type;
// edit
if (options && options.type) {
seriesType = series.options.type;
seriesName = series.name;
}
return {
name: seriesName,
type: seriesType
};
},
/**
* List all series with unique ID. Its mandatory for indicators to set
* correct linking.
* @private
* @param {string} type
* Indicator type like: sma, ema, etc.
* @param {string} optionName
* Type of select i.e series or volume.
* @param {Highcharts.Chart} chart
* Chart
* @param {Highcharts.HTMLDOMElement} parentDiv
* Element where created HTML list is added
* @param {string} selectedOption
* optional param for default value in dropdown
*/
listAllSeries: function (type, optionName, chart, parentDiv, selectedOption) {
var selectName = PREFIX + optionName + '-type-' + type, lang = this.lang, selectBox, seriesOptions;
createElement(LABEL, {
innerHTML: lang[optionName] || optionName,
htmlFor: selectName
}, null, parentDiv);
// select type
selectBox = createElement(SELECT, {
name: selectName,
className: PREFIX + 'popup-field'
}, null, parentDiv);
selectBox.setAttribute('id', PREFIX + 'select-' + optionName);
// list all series which have id - mandatory for creating indicator
chart.series.forEach(function (serie) {
seriesOptions = serie.options;
if (!seriesOptions.params &&
seriesOptions.id &&
seriesOptions.id !== PREFIX + 'navigator-series') {
createElement(OPTION, {
innerHTML: seriesOptions.name || seriesOptions.id,
value: seriesOptions.id
}, null, selectBox);
}
});
if (defined(selectedOption)) {
selectBox.value = selectedOption;
}
},
/**
* Create typical inputs for chosen indicator. Fields are extracted from
* defaultOptions (ADD mode) or current indicator (ADD mode). Two extra
* fields are added:
* - hidden input - contains indicator type (required for callback)
* - select - list of series which can be linked with indicator
* @private
* @param {Highcharts.Chart} chart
* Chart
* @param {Highcharts.Series} series
* Indicator
* @param {string} seriesType
* Indicator type like: sma, ema, etc.
* @param {Highcharts.HTMLDOMElement} rhsColWrapper
* Element where created HTML list is added
*/
addFormFields: function (chart, series, seriesType, rhsColWrapper) {
var fields = series.params || series.options.params, getNameType = this.indicators.getNameType;
// reset current content
rhsColWrapper.innerHTML = '';
// create title (indicator name in the right column)
createElement(H3, {
className: PREFIX + 'indicator-title',
innerHTML: getNameType(series, seriesType).name
}, null, rhsColWrapper);
// input type
createElement(INPUT, {
type: 'hidden',
name: PREFIX + 'type-' + seriesType,
value: seriesType
}, null, rhsColWrapper);
// list all series with id
this.indicators.listAllSeries.call(this, seriesType, 'series', chart, rhsColWrapper, series.linkedParent && fields.volumeSeriesID);
if (fields.volumeSeriesID) {
this.indicators.listAllSeries.call(this, seriesType, 'volume', chart, rhsColWrapper, series.linkedParent && series.linkedParent.options.id);
}
// add param fields
this.indicators.addParamInputs.call(this, chart, 'params', fields, seriesType, rhsColWrapper);
},
/**
* Recurent function which lists all fields, from params object and
* create them as inputs. Each input has unique `data-name` attribute,
* which keeps chain of fields i.e params.styles.fontSize.
* @private
* @param {Highcharts.Chart} chart
* Chart
* @param {string} parentNode
* Name of parent to create chain of names
* @param {Highcharts.PopupFieldsDictionary<string>} fields
* Params which are based for input create
* @param {string} type
* Indicator type like: sma, ema, etc.
* @param {Highcharts.HTMLDOMElement} parentDiv
* Element where created HTML list is added
*/
addParamInputs: function (chart, parentNode, fields, type, parentDiv) {
var _self = this, addParamInputs = this.indicators.addParamInputs, addInput = this.addInput, parentFullName;
objectEach(fields, function (value, fieldName) {
// create name like params.styles.fontSize
parentFullName = parentNode + '.' + fieldName;
if (isObject(value)) {
addParamInputs.call(_self, chart, parentFullName, value, type, parentDiv);
}
else if (
// skip volume field which is created by addFormFields
parentFullName !== 'params.volumeSeriesID') {
addInput.call(_self, parentFullName, type, parentDiv, [value, 'text'] // all inputs are text type
);
}
});
},
/**
* Get amount of indicators added to chart.
* @private
* @return {number} - Amount of indicators
*/
getAmount: function () {
var series = this.series, counter = 0;
series.forEach(function (serie) {
var seriesOptions = serie.options;
if (serie.params ||
seriesOptions && seriesOptions.params) {
counter++;
}
});
return counter;
}
},
tabs: {
/**
* Init tabs. Create tab menu items, tabs containers
* @private
* @param {Highcharts.Chart} chart
* Reference to current chart
*/
init: function (chart) {
var tabs = this.tabs, indicatorsCount = this.indicators.getAmount.call(chart), firstTab; // run by default
// create menu items
firstTab = tabs.addMenuItem.call(this, 'add');
tabs.addMenuItem.call(this, 'edit', indicatorsCount);
// create tabs containers
tabs.addContentItem.call(this, 'add');
tabs.addContentItem.call(this, 'edit');
tabs.switchTabs.call(this, indicatorsCount);
// activate first tab
tabs.selectTab.call(this, firstTab, 0);
},
/**
* Create tab menu item
* @private
* @param {string} tabName
* `add` or `edit`
* @param {number} [disableTab]
* Disable tab when 0
* @return {Highcharts.HTMLDOMElement}
* Created HTML tab-menu element
*/
addMenuItem: function (tabName, disableTab) {
var popupDiv = this.popup.container, className = PREFIX + 'tab-item', lang = this.lang, menuItem;
if (disableTab === 0) {
className += ' ' + PREFIX + 'tab-disabled';
}
// tab 1
menuItem = createElement(SPAN, {
innerHTML: lang[tabName + 'Button'] || tabName,
className: className
}, null, popupDiv);
menuItem.setAttribute(PREFIX + 'data-tab-type', tabName);
return menuItem;
},
/**
* Create tab content
* @private
* @return {HTMLDOMElement} - created HTML tab-content element
*/
addContentItem: function () {
var popupDiv = this.popup.container;
return createElement(DIV, {
className: PREFIX + 'tab-item-content'
}, null, popupDiv);
},
/**
* Add click event to each tab
* @private
* @param {number} disableTab
* Disable tab when 0
*/
switchTabs: function (disableTab) {
var _self = this, popupDiv = this.popup.container, tabs = popupDiv.querySelectorAll('.' + PREFIX + 'tab-item'), dataParam;
tabs.forEach(function (tab, i) {
dataParam = tab.getAttribute(PREFIX + 'data-tab-type');
if (dataParam === 'edit' && disableTab === 0) {
return;
}
['click', 'touchstart'].forEach(function (eventName) {
addEvent(tab, eventName, function () {
// reset class on other elements
_self.tabs.deselectAll.call(_self);
_self.tabs.selectTab.call(_self, this, i);
});
});
});
},
/**
* Set tab as visible
* @private
* @param {globals.Element} - current tab
* @param {number} - Index of tab in menu
*/
selectTab: function (tab, index) {
var allTabs = this.popup.container
.querySelectorAll('.' + PREFIX + 'tab-item-content');
tab.className += ' ' + PREFIX + 'tab-item-active';
allTabs[index].className += ' ' + PREFIX + 'tab-item-show';
},
/**
* Set all tabs as invisible.
* @private
*/
deselectAll: function () {
var popupDiv = this.popup.container, tabs = popupDiv
.querySelectorAll('.' + PREFIX + 'tab-item'), tabsContent = popupDiv
.querySelectorAll('.' + PREFIX + 'tab-item-content'), i;
for (i = 0; i < tabs.length; i++) {
tabs[i].classList.remove(PREFIX + 'tab-item-active');
tabsContent[i].classList.remove(PREFIX + 'tab-item-show');
}
}
}
};
addEvent(NavigationBindings, 'showPopup', function (config) {
if (!this.popup) {
// Add popup to main container
this.popup = new H.Popup(this.chart.container, (this.chart.options.navigation.iconsURL ||
(this.chart.options.stockTools &&
this.chart.options.stockTools.gui.iconsURL) ||
'https://code.highcharts.com/8.2.0/gfx/stock-icons/'));
}
this.popup.showForm(config.formType, this.chart, config.options, config.onSubmit);
});
addEvent(NavigationBindings, 'closePopup', function () {
if (this.popup) {
this.popup.closePopup();
}
});
| {
"pile_set_name": "Github"
} |
"""
Tests of ModelAdmin system checks logic.
"""
from django.contrib.contenttypes.fields import GenericForeignKey
from django.contrib.contenttypes.models import ContentType
from django.db import models
class Album(models.Model):
title = models.CharField(max_length=150)
class Song(models.Model):
title = models.CharField(max_length=150)
album = models.ForeignKey(Album, models.CASCADE)
original_release = models.DateField(editable=False)
class Meta:
ordering = ('title',)
def __str__(self):
return self.title
def readonly_method_on_model(self):
# does nothing
pass
class TwoAlbumFKAndAnE(models.Model):
album1 = models.ForeignKey(Album, models.CASCADE, related_name="album1_set")
album2 = models.ForeignKey(Album, models.CASCADE, related_name="album2_set")
e = models.CharField(max_length=1)
class Author(models.Model):
name = models.CharField(max_length=100)
class Book(models.Model):
name = models.CharField(max_length=100)
subtitle = models.CharField(max_length=100)
price = models.FloatField()
authors = models.ManyToManyField(Author, through='AuthorsBooks')
class AuthorsBooks(models.Model):
author = models.ForeignKey(Author, models.CASCADE)
book = models.ForeignKey(Book, models.CASCADE)
featured = models.BooleanField()
class State(models.Model):
name = models.CharField(max_length=15)
class City(models.Model):
state = models.ForeignKey(State, models.CASCADE)
class Influence(models.Model):
name = models.TextField()
content_type = models.ForeignKey(ContentType, models.CASCADE)
object_id = models.PositiveIntegerField()
content_object = GenericForeignKey('content_type', 'object_id')
| {
"pile_set_name": "Github"
} |
{
"version": 1,
"storageDriverName": "ontap-san-economy",
"managementLIF": "10.0.0.1",
"svm": "trident_svm_eco",
"username": "cluster-admin",
"password": "password",
"defaults": {
"spaceAllocation": "false",
"encryption": "false"
},
"labels":{"store":"san_economy_store"},
"region": "us_east_1",
"storage": [
{
"labels":{"app":"oracledb", "cost":"30"},
"zone":"us_east_1a",
"defaults": {
"spaceAllocation": "true",
"encryption": "true"
}
},
{
"labels":{"app":"postgresdb", "cost":"20"},
"zone":"us_east_1b",
"defaults": {
"spaceAllocation": "false",
"encryption": "true"
}
},
{
"labels":{"app":"mysqldb", "cost":"10"},
"zone":"us_east_1c",
"defaults": {
"spaceAllocation": "true",
"encryption": "false"
}
}
]
}
| {
"pile_set_name": "Github"
} |
<map id="Graphical Class Hierarchy" name="Graphical Class Hierarchy">
<area shape="rect" id="node1" href="$classargs_1_1_matcher.html" title="args::Matcher" alt="" coords="5,5,108,31"/>
</map>
| {
"pile_set_name": "Github"
} |
class Intltool < Formula
desc "String tool"
homepage "https://wiki.freedesktop.org/www/Software/intltool"
url "https://launchpad.net/intltool/trunk/0.51.0/+download/intltool-0.51.0.tar.gz"
sha256 "67c74d94196b153b774ab9f89b2fa6c6ba79352407037c8c14d5aeb334e959cd"
bottle do
cellar :any_skip_relocation
sha256 "14bb0680842b8b392cb1a5f5baf142e99a54a538d1a587f6d1158785b276ffc6" => :el_capitan
sha256 "da6c24f1cc40fdf6ae286ec003ecd779d0f866fe850e36f5e5953786fa45a561" => :yosemite
sha256 "5deeef3625d52f71d633e7510396d0028ec7b7ccf40c78b5d254bdf4214e6363" => :mavericks
sha256 "739e17a9f4e75913118a8ef0fd2a7ad7d645769cc61aeb1d6bcf760fe4bd48a7" => :mountain_lion
end
def install
system "./configure", "--prefix=#{prefix}",
"--disable-silent-rules"
system "make", "install"
end
test do
system bin/"intltool-extract", "--help"
end
end
| {
"pile_set_name": "Github"
} |
# Sample Programs in Racket
Welcome to Sample Programs in Racket!
## Sample Programs
- [Hello World in Racket](https://therenegadecoder.com/code/hello-world-in-racket/)
- [Fibonacci in Racket](https://github.com/TheRenegadeCoder/sample-programs/issues/1852)
- [Factorial in Racket](https://github.com/TheRenegadeCoder/sample-programs/issues/1853)
## Fun Facts
- Debut: 1994
- Developer: PLT Inc.
- License: LGPL
## References
- [Racket Wiki](https://en.wikipedia.org/wiki/Racket_(programming_language))
- [Racket Docs](https://racket-lang.org/)
| {
"pile_set_name": "Github"
} |
GLIBC_PROVIDES dnl See aclocal.m4 in the top level source directory.
# Local configure fragment for sysdeps/unix/sysv/linux/s390/s390-64.
LIBC_SLIBDIR_RTLDDIR([lib64], [lib])
| {
"pile_set_name": "Github"
} |
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// https://developers.google.com/protocol-buffers/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// This header declares the namespace google::protobuf::protobuf_unittest in order to expose
// any problems with the generated class names. We use this header to ensure
// unittest.cc will declare the namespace prior to other includes, while obeying
// normal include ordering.
//
// When generating a class name of "foo.Bar" we must ensure we prefix the class
// name with "::", in case the namespace google::protobuf::foo exists. We intentionally
// trigger that case here by declaring google::protobuf::protobuf_unittest.
//
// See ClassName in helpers.h for more details.
#ifndef GOOGLE_PROTOBUF_COMPILER_CPP_UNITTEST_H__
#define GOOGLE_PROTOBUF_COMPILER_CPP_UNITTEST_H__
namespace google {
namespace protobuf {
namespace protobuf_unittest {}
} // namespace protobuf
} // namespace google
#endif // GOOGLE_PROTOBUF_COMPILER_CPP_UNITTEST_H__
| {
"pile_set_name": "Github"
} |
'use strict'
var semver = require('semver')
var debug = require('debug')('opbeat')
var shimmer = require('../shimmer')
module.exports = function (ws, agent, version) {
if (!semver.satisfies(version, '^1.0.0 || ^2.0.0 || ^3.0.0 || ^4.0.0')) {
debug('ws version %s not supported - aborting...', version)
return ws
}
debug('shimming ws.prototype.send function')
shimmer.wrap(ws.prototype, 'send', wrapSend)
return ws
function wrapSend (orig) {
return function wrappedSend () {
var trace = agent.buildTrace()
var id = trace && trace.transaction.id
debug('intercepted call to ws.prototype.send %o', { id: id })
if (!trace) return orig.apply(this, arguments)
var args = [].slice.call(arguments)
var cb = args[args.length - 1]
if (typeof cb === 'function') {
args[args.length - 1] = done
} else {
cb = null
args.push(done)
}
trace.start('Send WebSocket Message', 'websocket.send')
return orig.apply(this, args)
function done () {
trace.end()
if (cb) cb.apply(this, arguments)
}
}
}
}
| {
"pile_set_name": "Github"
} |
๏ปฟ"Filed out from Dolphin Smalltalk 7"!
Link variableSubclass: #Process
instanceVariableNames: 'suspendedFrame priority myList callbackDepth _unused6 _unused7 fpControl threadSync thread exceptionEnvironment _alreadyPrinted _reserved1 debugger name _reserved2'
classVariableNames: 'DefaultFpControl DefaultMaxStack DefaultStack'
poolDictionaries: ''
classInstanceVariableNames: ''!
Process guid: (GUID fromString: '{87b4c64e-026e-11d3-9fd7-00a0cc3e4a32}')!
Process addClassConstant: 'DefaultFpControl' value: 16r80007!
Process addClassConstant: 'DefaultStack' value: 16r1!
Process comment: 'A Process represents an individual thread of execution in the image.
Note that the name "Process" is historic - a Smalltalk Process is much more similar to a "thread" than a true process, since all Processes share the same execution context (the image). Dolphin''s processes do not map directly onto native threads, but are "green" threads. The multi-threading system is implemented internally by the VM and image, with all "green" threads running within a single Win32 thread. This means that a call to a long running (or blocking) external API call will block the entire system, so a facility is provided to "overlap" such calls. This is done by marking the external method with the "overlap" annotation, in which case the VM will perform the call on a separate native thread. For the duration of the overlapped operation the calling Process is blocked, but other Processes in the image will continue to run.
A Process can in any of the following states:
- active The Process is actually running. Usually you will only be able to catch the main UI process in this state.
- debug The Process is currently being debugged.
- ready The Process is ready to run, but currently suspended on one of the Processors priority queues.
- suspended The Process has been suspended (see #suspend), and will not run again until sent #resume.
Note that a suspended process with no active references will be garbage collected.
- waiting The Process is waiting on a <Semaphore>, i.e. it has sent #wait to a Semaphore with no excess signals.
A Process remains waiting on a Semaphore until it reaches the front of that Semaphores queue of
waiting Processes and the Semaphore is sent a #signal message.
- dead The Process has been terminated, or has run to completion.
A Process in any state other than #dead is considered alertable, and may be sent an interrupt by the VM at any time. See<ProcessorScheduler> for more details.
In general it is not a good idea to manipulate the contents of a live process directly (e.g. in an Inspector). For performance reasons the VM tends to assume that a Process'' state is consistent, and it does not perform much error checking. Hence it is quite easy to crash the system by modification of instance variables and the stack. It is quite safe to view the contents, but if a live Process is inspected you may find that the snapshot is invalidated by the stack growing and shrinking to meet requirements, which could cause errors in the inspector when trying to access non-existant stack slots.
Instance Variables:
suspendedFrame <Integer> address of suspendedFrame when in states ready, waiting, or suspended, otherwise nil.
priority <Integer> priority level (see ProcessorScheduler).
myList <LinkedList> on which the process is currently queued if in states ready or waiting, otherwise nil.
callbackDepth <Integer> number of callbacks which have not yet been returned from (i.e. nested depth).
primitiveFailureCode <Integer> code reported by last primitive failure.
primitiveFailureData <Object> argument supplied by last primitive failure. Value depends on primitive and failure reason.
fpControl <Integer> floating point control flags. See Intel/CRT docs.
threadSync <Semaphore> used for overlapped call synchronisationby the VM.
thread Pointer to overlapped call control block. For VM use only.
exceptionEnvironment List of active exception frames <ExceptionHandler> in LIFO order.
_alreadyPrinted <IdentitySet> of objects which have already printed in a recursive #printOn:
_reserved1 Reserved for future use.
debugger <debugEventHandler> associated with the Process, if any. Used as a destination for debug events.
name The <Object> ''name'' of the process. Usually a <String> or <CompiledMethod>.
_reserved2 Reserved for future use.
Class Variables:
DefaultFpControl <Integer> default floating point control flags to initialize fpControl instance variable.
DefaultMaxStack <Integer> maximum stack depth (size up to which a Process may grow - virtual memory reserved).
DefaultStack <Integer> initial stack depth (initial virtual memory committed).'!
!Process categoriesForClass!Kernel-Processes! !
!Process methodsFor!
_alreadyPrinted
^_alreadyPrinted!
at: anInteger ifAbsent: exceptionBlock
"Answer an <Object> which is the element of the receiver
at the specified <SmallInteger> index. If the index is out of bounds
answer the result of evaluating the <niladicValuable> exceptionBlock."
^(anInteger > 0 and: [anInteger <= self size])
ifTrue: [self at: anInteger]
ifFalse: [exceptionBlock value]!
at: anInteger put: anObject
"Replace the receivers indexed instance variable at the argument, index, with the argument, value. Answer value."
"Primitive Failure Reasons:
InvalidParameter1 - index is not a SmallInteger
OutOfBounds - index out of bounds (not in the range 1..receiver's indexable size)"
<primitive: 176>
^self
_primitiveError: _failureCode
at: anInteger
put: anObject!
basicAt: anInteger put: anObject
"Private - Replace the receivers indexed instance variable at the argument, index, with the argument, value. Answer value.
MUST not be reimplemented (except by classes whose instances have special representations such as SmallInteger)."
"Primitive Failure Reasons:
InvalidParameter1 - index is not a SmallInteger
OutOfBounds - index out of bounds (not in the range 1..receiver's indexable size)"
<primitive: 176>
^self
_primitiveError: _failureCode
at: anInteger
put: anObject!
basicSuspendedFrame
"Private - Answer the SmallInteger pointer into the stack of the suspended frame. If nil then
the process has terminated (or is not yet initialized)."
^suspendedFrame!
callbackDepth
"Private - Answer the depth of outstanding callbacks from the VM in the receivers stack.
An example of a callback is an entry from the Smalltalk window procedure to
View>>dispatchMessage:. Recursive callbacks (callbacks which occur during the
processing of another callback, e.g. sending a Win32 message in the handler for
another Win32 message) will increase the callback depth to a figure greater than one.
The Main (user interface) process will always have a callback depth >= 1 when
examined.
Whether a Process' stack contains callbacks affects the way it must be unwound
on termination, or when handling an exception, since the callbacks from the
VM must themselves be properly unwound, not just the Smalltalk stack."
^callbackDepth!
canDebug
"Answer whether the receiver can be debugged (this requires that a debugger
be available)."
^self respondsTo: #debuggerClass!
debugger
"Private - Answer the object which is currently claiming to be the 'debugger' on this
process. This object will receiver debug events as and when they occur in the receiver
(it need not be an actual <Debugger>). The answer will be nil if there is no debugger."
^debugger!
debugger: anObject
"Private - anObject is claiming to be the debugger for the receiver, so save it so
that it can later be sent debug events which occur in the receiver. Any
existing debugger is disconnected."
debugger := anObject!
errno
"Answer the value of the C runtime 'errno' global variable saved on completion of the last
overlapped call made from the receiver."
^CRTLibrary nonblocking errno!
exceptionEnvironment
"Private - Answer the receiver's exception environment (a LIFO stack of ExceptionHandlers).
A linked list of ExceptionHandlers is maintained to expedite the search for handlers
when an exception occurs."
^exceptionEnvironment!
exceptionEnvironment: anExceptionHandler
"Private - Set the receiver's exception environment to be the argument,
anExceptionHandler. N.B. Use with care, the previous exception environment
should be linked to the new exception environment."
exceptionEnvironment := anExceptionHandler!
finalize
"Private - Ensure the receiver is properly terminated.
This method should only be invoked if the process dies because there
are no outstanding references to it. If normally terminated, then
it will not be finalized."
self terminate!
fpControl
"Answer the current floating point control word for the receiver. This is an <integer>
combination of flags from the CRT FP control word enumerations:
_DN_xxx - Denormal control (mask _MCW_DN)
_EM_xxx - Exception masking (mask _MCW_EM)
_IC_xxx - Infinity control (mask _MCW_IC)set
_PC_xxx - Precision control (mask _MCW_PC)
_RC_xxx - Rounding control (mask _MCW_RC)
See the CRT documentation on MSDN for further details."
^fpControl!
fpControl: anInteger
fpControl := anInteger!
frameAtAddress: spInteger
"Private - Answer a frame representing the real stack frame at the specified SP (a
SmallInteger address/2 in the receiver), or nil if the address is not within this process."
^self frameAtIndex: (self indexOfSP: spInteger)!
frameAtIndex: anInteger
"Private - Answer a StackFrame represent a real frame in the receiver at the specified index,
or nil if the index is out of bounds."
^self frameClass process: self index: anInteger!
frameClass
"Private - Answer the class of object to use to represent the receiver's activation records"
^StackFrame!
id
"Answer an id which is unique for the lifetime of the process within
this particular session. Should the process be terminated in the session
then the id may be re-used, i.e. this is really only useful to help with debugging."
^self yourAddress bitShift: -16!
indexOfSP: anInteger
"Private - Answer the index into the receiver of the VM stack pointer value, anInteger (which is a pointer, bitshifted right one position, although this is an implementation
detail which may be changed)."
<primitive: 175>
^((anInteger bitShift: -1) - (self yourAddress bitShift: -2)) - self class instSize + 1!
interruptWith: aBlock
"Private - Interrupt the receiver with the specified block. The block is evaluated regardless of
the receiver's current state (unless dead). On completion of the block, the receiver resumes whatever
it was doing before, including waiting on a Semaphore, etc."
"Implementation Note: aBlock is evaluated with asynchronous process switching disabled!!"
^self queueInterrupt: Processor genericInterrupt with: aBlock!
isActive
"Answer whether the receiver is the current active process."
^Processor activeProcess == self
!
isAlive
"Answer whether the receiver is either ready, waiting, or active."
^self isActive or: [self suspendingList notNil] !
isAlive: aSemaphore
"Private - Answer whether the receiver is either ready, waiting on the specified
Semaphore, or active."
| state |
state := self state.
^state == #ready
or: [state == #running or: [state == #waiting and: [self suspendingList == aSemaphore]]]!
isDead
^suspendedFrame isNil!
isDebuggee
"Private - Answer whether the receiver is currently being debugged."
^debugger notNil!
isInCallback
"Private - Answer whether the receiver is processing a callback from the VM.
Whether a Process' stack contains callbacks affects the way it must be unwound
on termination, or when handling an exception, since the callbacks from the
VM must themselves be properly unwound (and in the same order in which they
were made), not just the Smalltalk stack."
^self callbackDepth > 0!
isMain
"Answer whether the receiver is the main user I/F process (i.e. it
manages the input queue)."
^SessionManager inputState main == self
!
isReady
"Answer whether the receiver is Ready to run but inactive"
^self state == #ready !
isSuspended
"Answer whether the receiver is Suspended/Terminated."
^self state == #suspended
!
isTerminated
"Answer whether the receiver has Terminated."
^self state == #dead
!
isWaiting
"Answer whether the receiver is waiting on a Semaphore."
^self state == #waiting !
kill
"Terminate the receiver with extreme prejudice. Any outstanding unwind blocks
will not be run. It is necessary, however, to correctly maintain the VM's callback stack,
so all outstanding callbacks are unwound. Finally, the receiver is put to sleep, permanently.
N.B. This should not be sent to a process which is not the active process if it has callbacks."
self isDead ifTrue: [^self].
self isActive
ifTrue: [self shutdown]
ifFalse:
["As the receiver is not active, we queue an interrupt which will
cause the VM to activate the receiver (even if Waiting or Suspended)."
self queueInterrupt: Processor killInterrupt]!
lastError
"Answer the value of the Win32 error code (i.e. the result of GetLastError()) run in the
context of the overlapped external call thread associated with the receiver."
^KernelLibrary default threadGetLastError!
name
"Answer the 'name' of the Process. This is usually defined by the creator of the process.
The default name is the home method (which allows access to the source of the forking block,
even for immediate expressions). The name need not be a String (all Objects respond to #displayString)"
^name!
name: anObject
"Set the name of the Process to the argument, anObject (see #name)"
name := anObject!
primTerminate
"Private - Transition the receiver from its current state to the Terminated state. Once terminated, a Process cannot (easily) be resumed or restarted."
"Primitive Failure Reasons:
AlreadyComplete - The process is suspended (processes can only be terminated from within their own running context)
ThreadIsTerminating - The process is already on the pending terminations list (i.e. waiting for its associated OS thread to terminate)
Retry - The receiver is the last running process, so it cannot be terminated until another process has been started (an Idle Panic interrupt will also be generated). Assuming correct recovery after the idle panic, a second attempt at termination should succeed."
"Implementation Note: This primitive is approximately equivalent to:
self suspendUnconditionally.
suspendedFrame := nil
except that the primitive can correctly terminate any process, even the active process. The
active process cannot terminate itself correctly in this way in Smalltalk without the
assistance of another process, because as soon as it suspends itself, it will obviously stop
running, and so will be unable to nil out its suspended context. It is considered that the
use of a simple primitive to terminate processes is both less error prone, and consumes less
resources, than the alternative of dedicating another process to this task."
<primitive: 91>
^_failureCode == _PrimitiveFailureCode.ThreadIsTerminating or:
[_failureCode == _PrimitiveFailureCode.Retry
ifTrue: [false "Please try again"]
ifFalse: [self primitiveFailed: _failureCode]]!
printOn: aStream
"Append a short debug description of the receiver to aStream."
aStream
basicPrint: self;
nextPut: $(;
print: self name;
nextPutAll: ', id: ';
print: self id;
nextPutAll: ', priority: ';
print: self priority;
nextPutAll: ', state: ';
print: self state;
nextPut: $)!
priority
"Answer the receiver's priority (see ProcessorScheduler)"
^priority
!
priority: anInteger
"Set the receiver's priority to anInteger and Answer the previous priority. Note that
if the receiver is the currently active process, the new priority is lower, and there
are higher-priority processes ready to run, the active process will be preempted.
If the receiver is not the active process, and its priority is increased above that of
the active process, then the active process will be preempted.
Primitive failure reasons:
InvalidParameter1 - anInteger is not a SmallInteger.
IntegerOutOfRange - anInteger is not in the range of permissible priorities (1..highest priority)."
<primitive: 92>
^(_failureCode == _PrimitiveFailureCode.InvalidParameter1
or: [_failureCode == _PrimitiveFailureCode.IntegerOutOfRange])
ifTrue: [self error: ('Invalid Process priority <1p>' expandMacrosWith: anInteger)]
ifFalse: [self primitiveFailed: _failureCode]!
queueInterrupt: anInteger
"Queue an interrupt with the specified number for the receiver (which can be in any resumable state)
and a nil argument."
^self queueInterrupt: anInteger with: nil!
queueInterrupt: anInteger with: anObject
"Queue an interrupt with the specified number for the receiver (which can be in any resumable state).
The argument is passed to the interrupted process and can be of any type as necessary.
Primitive failure reasons:
InvalidParameter1 - anInteger is not a SmallInteger.
IllegalStateChange - the receiver is dead (i.e. not runnable)."
<primitive: 98>
^self primitiveFailed: _failureCode!
resetFloatingPoint
CRTLibrary default
_clearfp;
_control87: fpControl
mask: ##(CRTConstants._MCW_DN | CRTConstants._MCW_EM | CRTConstants._MCW_IC | CRTConstants._MCW_PC
| CRTConstants._MCW_RC)!
resume
"Change the state of the receiver from Suspended to Ready (by placing it at the end of the Processor's queue for the receiver's priority). Fail if the receiver is already waiting in a queue (in a Semaphore or the Processor). See #resume: for further details (sending this message is equivalent to sending #resume: with nil as the argument)."
<primitive: 87>
^self primitiveFailed: _failureCode!
resume: suspendingListOrNil
"Change the state of the receiver from Suspended to Ready/Waiting by placing it at the end of the Processor's queue for the receiver's priority if suspendingListOrNil is nil, otherwise returning it to the queue associated with suspendingListOrNil. Fail if the receiver is already waiting in a queue (in a Semaphore or the Processor) - i.e. it is only appropriate to send this message to previously #suspend'd Processes, it is not the means by which to start currently Waiting or Ready processes (which have to wait either for the Semaphore on which they are Waiting to be signalled, or their turn to run after higher priority processes, and in a round robin fashion with respect to Processes of the same priority if they are Ready to run)."
"Primitive failure reasons:
IllegalStateChange - the receiver is not suspended on a scheduler or semaphore list.
AssertionFailure - the receiver has been terminated (or not properly initialized)."
<primitive: 87>
^self primitiveFailed: _failureCode!
resumeUnconditionally
"Change the state of the receiver to Ready to run regardless of its current state (unless terminated)."
<primitive: 87>
myList isNil ifTrue: [^self primitiveFailed: _failureCode]!
setFpControl: flagsInteger mask: maskInteger
"Set the current floating point control word for the receiver. If the receiver is the
current active process, then the processor control word is updated. Once set the VM will
maintain isolated fp state for each Process. The mask should be one or more of:
_MCW_DN - Denormal control (flags _DN_xxx)
_MCW_EM - Exception masking (flags _EM_xxx)
_MCW_IC - Infinity control (flags _IC_xxx)
_MCW_PC - Precision control (flags _PC_xxx)
_MCW_RC - Rounding control (mask _RC_xxx)
Note that you can unmask some FP exceptions that are masked by default such as _EM_DENORMAL
and _EM_INEXACT, it is unwise to do so for anything other than short well tested blocks of code as
this may cause any Floating point code in external libraries that is not written to expect these
exceptions (e.g. in Windows controls) to fail in unexpected ways. Unmasking _EM_INEXACT, in
particular, will quickly kill a development image."
| current |
current := fpControl.
fpControl := (current bitAnd: maskInteger bitInvert) bitOr: (flagsInteger bitAnd: maskInteger).
self isActive
ifTrue:
["Set it whether or not it is different from the current control value as some external code could have changed it."
self resetFloatingPoint].
^current!
setLaunchBlock: aBlockClosure
"Private - Initialize the receiver and install aBlockClosure as the launch frame of the
receiver (which must be a new process). The VM needs a correctly established frame in order
to start running a process."
| baseFrame |
_alreadyPrinted := IdentitySet new.
callbackDepth := priority := 0.
fpControl := Processor activeProcess fpControl ?? DefaultFpControl.
self beFinalizable.
self at: 1 put: aBlockClosure receiver.
"Note that we must allow space for the block's stack temps"
baseFrame := self frameClass new setProcess: self index: 2 + aBlockClosure localCount.
baseFrame
basicSender: 0;
basicIP: aBlockClosure initialIP + MemoryManager current objectHeaderSize - 1;
sp: baseFrame frameSize + 1;
method: aBlockClosure method;
environment: aBlockClosure.
baseFrame bp: 2.
self suspendedFrame: baseFrame!
setPriority: anInteger
priority := anInteger!
shutdown
"Private - Terminate the receiver with extreme prejudice. Any outstanding unwind blocks
will not be run. It is necessary, however, to correctly maintain the VM's callback stack,
so all outstanding callbacks ARE unwound. Finally, the receiver is put to sleep, permanently.
N.B. This should not be sent to a process which is not the active process if it has callbacks.
Sending this method directly is not recommended (send either #kill or #terminate instead)."
"Inform any debugger so that it can close.
You will not be able to debug past this point."
debugger notNil ifTrue: [debugger perform: #onTerminate].
"Unwind any outstanding callbacks."
Processor unwindCallbacks.
self beUnfinalizable.
[self primTerminate == true] whileFalse!
size
"Answer the number of indexed variables in the receiver (0 for non-indexable objects,
as the named instance variables are not included)."
"Implementation Note: Access thisContext to get the process size saved down as the
processes dynamically change size to accomodate their stack. Normally the process
size is only recorded from the SP on process switches, when thisContext is accessed,
on GC's, on invocations of the #allReferences primitive, and on image save."
thisContext.
^super size!
spOfIndex: anInteger
"Private - Answer a VM stack pointer value (SmallInteger) for the specified index of the
receiver."
| sp |
sp := (self yourAddress bitShift: -1) + ((anInteger + self class instSize - 1) * 2).
"The result must always be a SmallInteger, or the VM will not interpret the stack pointer correctly and may crash,
this means the SP value can be negative when interpreted as a signed value"
^(16r40000000 + sp bitAnd: 16r7FFFFFFF) + -16r40000000!
stackTrace: anInteger
"Private - Answer a <readableString> containing a stack trace to the depth specified by the <integer>
argument."
^self topFrame stackTrace: anInteger!
state
"Private - Answer a symbol identifying the receiver's state."
^self isActive
ifTrue: [#running]
ifFalse:
["The state may change, so minimize chance of getting
it wrong by storing suspendingList in a temporary"
| list |
list := self suspendingList.
list isNil
ifTrue:
[self isDebuggee
ifTrue: [#debug]
ifFalse: [self basicSuspendedFrame isNil ifTrue: [#dead] ifFalse: [#suspended]]]
ifFalse: [(list isKindOf: Semaphore) ifTrue: [#waiting] ifFalse: [#ready]]]!
stbSaveOn: anSTBOutFiler
"Save out a binary representation of the receiver to anSTBOutFiler.
Processes cannot be saved and restored correctly so output them as
nil by default"
anSTBOutFiler saveObject: self as: nil.!
suspend
"Transition the receiver from Running (if active), Waiting (if waiting on a Semaphore) or Ready (if waiting to be scheduled by the Processor) states to the Suspended state (i.e. not runnable). If the receiver is the activeProcess, suspend it and schedule another, otherwise remove the receiver from the list of Ready processes in the Processor, or the list of Waiting processes in a Semaphore, and nil out its suspending list backpointer. The receiver may be transitioned back to the Ready state at any time by sending it #resume (but remember that resuming a Process that was waiting on a Semaphore when it was suspended may upset process synchronisation because it will not return to the Semaphores waiting list).
Report an error if the receiver is already Suspended (which is recognised by a null backpointer, as this indicates that the process is not waiting in a list).
Suspended processes have a 'nil' suspending list, are not the active process, and have a non-zero suspendedFrame address (which distinguishes them from terminated processes). If the process is the last runnable process, then answer false, otherwise answer the receiver (when resumed)."
"Primitive failure results:
AlreadyComplete - the process is already suspended.
Retry - the process is the active process and could not be suspended because it is the only runnable process remaining.
ThreadIsTerminating - the process is pending termination"
<primitive: 88>
^_failureCode == _PrimitiveFailureCode.Retry
ifTrue: [false]
ifFalse: [self primitiveFailed: _failureCode]!
suspendedFrame
"Private - Answer a stack frame for the receiver's suspended context, nil if the receiver is dead."
| frameAddress |
frameAddress := self basicSuspendedFrame.
^frameAddress isNil ifFalse: [self frameAtAddress: frameAddress]!
suspendedFrame: aStackFrameOrIndex
"Private - Set the suspended frame index of the receiver."
suspendedFrame := self spOfIndex: aStackFrameOrIndex asInteger!
suspendingList
"Private - Answer the list (semaphore or Processor queue) on which the receiver has been
suspended. A Process which has been suspended, or which is currently active,
will answer nil."
^myList!
suspendUnconditionally
"As #suspend, but fails silently attempts at suspending processes which are already Suspended.
Answers the receiver.
Primitive failure results:
Completed - the process is already suspended.
Retry - the process is the active process and could not be suspended because it is the only runnable process remaining.
ThreadIsTerminating - the process is pending termination
The Completed and Retry failure codes are ignored. Any other failure code is unexpected, and will result in an exception being raised."
<primitive: 88>
^_failureCode == _PrimitiveFailureCode.Retry
ifTrue: [false]
ifFalse: [_failureCode == _PrimitiveFailureCode.Completed ifTrue: [self] ifFalse: [self primitiveFailed: _failureCode]]!
terminate
"Transition the receiver from its current state to the Terminated state. Once Terminated,
a Process cannot be resumed or restarted.
Implementation note: In order to ensure that all unwind blocks (see BlockClosure>>andFinally:
and BlockClosure>>ifCurtailed:) are run, termination is achieved by raising a ProcessTermination
exception which is caught and handled by the launch block of the receiver (see
BlockClosure>>newProcess). The launch block handler for ProcessTermination #return:'s, dropping
all later stack frames, and thus causing any unwind blocks to be executed. As its last action the launch
block sends #shutdown message to the Process for final cleanup."
self isDead ifTrue: [^self].
self isActive
ifTrue:
[ProcessTermination signalWith: self.
"Won't get this far unless the process hasn't completed its initialization,
and established a based handler block for the ProcessTermination signal."
self shutdown]
ifFalse:
["Exceptions can only be raised in active processes (and a process must be active
to terminate itself), so as the receiver is not active, we must queue an interrupt
which will cause the VM to activate the receiver (even if Waiting or Suspended)."
self queueInterrupt: Processor terminateInterrupt]!
threadSync
^threadSync!
topFrame
"Private - Answer a frame representing the top activation record of the receiver's stack.
We deliberately answer a frame for the sender if the receiver is the active
process, as the current context will be invalidated immediately this method
returns. Of course that frame will also be invalidated should the sender
subsequently return too."
^self isActive
ifTrue: [(self frameAtAddress: thisContext) sender]
ifFalse: [self suspendedFrame]! !
!Process categoriesFor: #_alreadyPrinted!accessing!private! !
!Process categoriesFor: #at:ifAbsent:!accessing!public! !
!Process categoriesFor: #at:put:!accessing!public! !
!Process categoriesFor: #basicAt:put:!accessing!private! !
!Process categoriesFor: #basicSuspendedFrame!private!stack frames! !
!Process categoriesFor: #callbackDepth!accessing!private! !
!Process categoriesFor: #canDebug!development!public!testing! !
!Process categoriesFor: #debugger!accessing!development!private! !
!Process categoriesFor: #debugger:!accessing!development!private! !
!Process categoriesFor: #errno!accessing!public! !
!Process categoriesFor: #exceptionEnvironment!accessing!debugger-step over!public! !
!Process categoriesFor: #exceptionEnvironment:!accessing!debugger-step over!private! !
!Process categoriesFor: #finalize!finalizing!private! !
!Process categoriesFor: #fpControl!accessing!public! !
!Process categoriesFor: #fpControl:!accessing!private! !
!Process categoriesFor: #frameAtAddress:!private!stack frames! !
!Process categoriesFor: #frameAtIndex:!private!stack frames! !
!Process categoriesFor: #frameClass!private!stack frames! !
!Process categoriesFor: #id!accessing!public! !
!Process categoriesFor: #indexOfSP:!private!stack frames! !
!Process categoriesFor: #interruptWith:!interrupts!private! !
!Process categoriesFor: #isActive!public!states-testing! !
!Process categoriesFor: #isAlive!public!states-testing! !
!Process categoriesFor: #isAlive:!private!states-testing! !
!Process categoriesFor: #isDead!public!states-testing! !
!Process categoriesFor: #isDebuggee!private!states-testing! !
!Process categoriesFor: #isInCallback!private!testing! !
!Process categoriesFor: #isMain!public!testing! !
!Process categoriesFor: #isReady!public!states-testing! !
!Process categoriesFor: #isSuspended!public!states-testing! !
!Process categoriesFor: #isTerminated!public!states-testing! !
!Process categoriesFor: #isWaiting!public!states-testing! !
!Process categoriesFor: #kill!public!states-changing! !
!Process categoriesFor: #lastError!accessing!public! !
!Process categoriesFor: #name!accessing!public! !
!Process categoriesFor: #name:!accessing!public! !
!Process categoriesFor: #primTerminate!private!states-changing! !
!Process categoriesFor: #printOn:!printing!public! !
!Process categoriesFor: #priority!accessing!public! !
!Process categoriesFor: #priority:!accessing!public! !
!Process categoriesFor: #queueInterrupt:!interrupts!public! !
!Process categoriesFor: #queueInterrupt:with:!interrupts!public! !
!Process categoriesFor: #resetFloatingPoint!helpers!private! !
!Process categoriesFor: #resume!public!states-changing! !
!Process categoriesFor: #resume:!public!states-changing! !
!Process categoriesFor: #resumeUnconditionally!public!states-changing! !
!Process categoriesFor: #setFpControl:mask:!accessing!public! !
!Process categoriesFor: #setLaunchBlock:!initializing!private! !
!Process categoriesFor: #setPriority:!accessing!private! !
!Process categoriesFor: #shutdown!private!states-changing! !
!Process categoriesFor: #size!accessing!public! !
!Process categoriesFor: #spOfIndex:!private!stack frames! !
!Process categoriesFor: #stackTrace:!helpers!private! !
!Process categoriesFor: #state!private!states-changing! !
!Process categoriesFor: #stbSaveOn:!binary filing!public! !
!Process categoriesFor: #suspend!public!states-changing! !
!Process categoriesFor: #suspendedFrame!private!stack frames! !
!Process categoriesFor: #suspendedFrame:!private!stack frames! !
!Process categoriesFor: #suspendingList!accessing!private! !
!Process categoriesFor: #suspendUnconditionally!public!states-changing! !
!Process categoriesFor: #terminate!public!states-changing! !
!Process categoriesFor: #threadSync!accessing!private! !
!Process categoriesFor: #topFrame!private!stack frames! !
!Process class methodsFor!
forContext: aBlockClosure priority: priorityInteger maxStack: slotsInteger
"Private - Answer a suspended instance of the receiver that will execute the block,
aBlockClosure, at the priority, anInteger, reserving slotsInteger as the maximum stack size.
N.B. There are certain requirements which must be met by the launch block, aBlockClosure,
if the new process is to die quietly without causing a GPF:
1) It must be a zero argument BlockClosure (not just any old niladic valuable)
2) It must have a null home stack frame (i.e. its home context is marked as having
already returned).
3) It must catch ProcessTermination notifications, and proceed through to its
shutdown code (e.g. [...] on: ProcessTermination do: [:pt | pt return]).
4) It must send #shutdown to the active process so that it is properly terminated.
5) It must perform a ^-return as its last action.
Items (2) and (5) ensure that any attempt to drop off the bottom of the process stack
is trapped by the VM and results in a 'Context Expiry' walkback rather than an
unrecoverable GPF."
^(self new: DefaultStack max: slotsInteger ?? DefaultMaxStack)
setLaunchBlock: aBlockClosure;
priority: priorityInteger;
yourself!
initialize
"Initialize the class variables of the receiver:
DefaultStack - The initial stack size of new Processes. This should be relatively
small so as not to waste space, and to reduce instantiation overhead,
but not so small that it causes a stack fault and growth. A default
value which corresponds to less than one OS page (normally 4k bytes,
or 1024 object pointers) will be rounded up to one OS page. The
actual stack size will be slightly less than the number of pointers
which fit on one OS page, because the VM adjusts it to account for
Process' fixed instance variables, and overhead.
DefaultMaxStack - The maximum size to which the stack of new Processes can grow before
the VM signals a stack overflow. Processes grow by a number of pages each time
a stack overflow occurs, from the initial size, up to this maximum.
This value should be large enough to allow useful work to be done by
recursive methods, but not so large that programming errors go
undetected, It is unlikely that a stack need be large than 65536,
and for those instances, specific instantiation is recommended.
DefaultFpControl - Default floating point control word - see msdn documentation for the
CRT function _controlfp_s().
Evaluate me to initialize:
Process initialize
"
self addClassConstant: 'DefaultStack' value: 1. "Let the VM work out the minimum size (will be at least one OS page)"
DefaultMaxStack := 64 * 1024. "Grow to 64K slots (256Kb) before overflow."
"See FloatingPointException for an explanation of the default FP exception mask"
self addClassConstant: 'DefaultFpControl'
value: CRTConstants._RC_NEAR | CRTConstants._IC_PROJECTIVE | CRTConstants._DN_SAVE
| CRTConstants._PC_64
| (CRTConstants._MCW_EM maskClear: CRTConstants._EM_ZERODIVIDE | CRTConstants._EM_INVALID)!
new
"Processes should be created by sending one of the #fork family of messages to a block."
^self shouldNotImplement! !
!Process class categoriesFor: #forContext:priority:maxStack:!instance creation!private! !
!Process class categoriesFor: #initialize!development!initializing!public! !
!Process class categoriesFor: #new!instance creation!public! !
| {
"pile_set_name": "Github"
} |
/*
* Copyright (C) 2013-2015 RoboVM AB
*
* 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.robovm.apple.mapkit;
/*<imports>*/
import java.io.*;
import java.nio.*;
import java.util.*;
import org.robovm.objc.*;
import org.robovm.objc.annotation.*;
import org.robovm.objc.block.*;
import org.robovm.rt.*;
import org.robovm.rt.annotation.*;
import org.robovm.rt.bro.*;
import org.robovm.rt.bro.annotation.*;
import org.robovm.rt.bro.ptr.*;
import org.robovm.apple.foundation.*;
import org.robovm.apple.coregraphics.*;
import org.robovm.apple.corelocation.*;
import org.robovm.apple.uikit.*;
import org.robovm.apple.dispatch.*;
/*</imports>*/
/*<javadoc>*/
/*</javadoc>*/
/*<annotations>*/@Library("MapKit") @NativeClass/*</annotations>*/
/*<visibility>*/public/*</visibility>*/ class /*<name>*/MKMultiPoint/*</name>*/
extends /*<extends>*/MKShape/*</extends>*/
/*<implements>*/implements MKGeoJSONObject/*</implements>*/ {
/*<ptr>*/public static class MKMultiPointPtr extends Ptr<MKMultiPoint, MKMultiPointPtr> {}/*</ptr>*/
/*<bind>*/static { ObjCRuntime.bind(MKMultiPoint.class); }/*</bind>*/
/*<constants>*//*</constants>*/
/*<constructors>*/
public MKMultiPoint() {}
@Deprecated protected MKMultiPoint(long handle) { super(handle); }
protected MKMultiPoint(Handle h, long handle) { super(h, handle); }
protected MKMultiPoint(SkipInit skipInit) { super(skipInit); }
/*</constructors>*/
/*<properties>*/
@Property(selector = "pointCount")
public native @MachineSizedUInt long getPointCount();
/*</properties>*/
/*<members>*//*</members>*/
public MKMapPoint[] getPoints() {
return getPoints0().toArray((int) getPointCount());
}
public CLLocationCoordinate2D[] getCoordinates(@ByVal NSRange range) {
CLLocationCoordinate2D coords = Struct.allocate(CLLocationCoordinate2D.class, (int)range.getLength());
getCoordinates0(coords, range);
return coords.toArray((int) range.getLength());
}
/*<methods>*/
@Method(selector = "points")
protected native MKMapPoint getPoints0();
@Method(selector = "getCoordinates:range:")
protected native void getCoordinates0(CLLocationCoordinate2D coords, @ByVal NSRange range);
/*</methods>*/
}
| {
"pile_set_name": "Github"
} |
{
"credit": "Made with Blockbench",
"ambientocclusion": false,
"textures": {
"particle": "block/redstone_torch"
},
"elements": [
{
"from": [7, 0, 7],
"to": [9, 10, 9],
"shade": false,
"faces": {
"north": {"uv": [7, 6, 9, 16], "texture": "#particle"},
"east": {"uv": [7, 6, 9, 16], "texture": "#particle"},
"south": {"uv": [7, 6, 9, 16], "texture": "#particle"},
"west": {"uv": [7, 6, 9, 16], "texture": "#particle"},
"up": {"uv": [7, 6, 9, 8], "texture": "#particle"},
"down": {"uv": [7, 14, 9, 16], "texture": "#particle"}
}
}
],
"display": {
"thirdperson_righthand": {
"translation": [-0.75, 4.75, 1.25],
"scale": [0.6, 0.6, 0.6]
},
"thirdperson_lefthand": {
"translation": [-0.75, 4.75, 1.25],
"scale": [0.6, 0.6, 0.6]
},
"firstperson_righthand": {
"rotation": [0, -90, 25],
"translation": [1.13, 3.2, 1.13],
"scale": [0.68, 0.68, 0.68]
},
"firstperson_lefthand": {
"rotation": [0, 90, -25],
"translation": [1.13, 3.2, 1.13],
"scale": [0.68, 0.68, 0.68]
},
"ground": {
"translation": [0, 2, 0],
"scale": [0.5, 0.5, 0.5]
},
"gui": {
"rotation": [30, 225, 0],
"translation": [0, 2.5, 0]
},
"head": {
"translation": [0, 14.25, 0]
},
"fixed": {
"translation": [0, 3, -1]
}
}
} | {
"pile_set_name": "Github"
} |
# Copyright 2008-2020 pydicom authors. See LICENSE file for details.
"""Compatibility functions for previous Python 2 support"""
# Python 2 only - warn and mark this as deprecated.
import warnings
warnings.warn(
"Starting in pydicom 3.0, the compat module (used for Python 2)"
" will be removed",
DeprecationWarning
)
# Text types
text_type = str
string_types = (str, )
char_types = (str, bytes)
number_types = (int, )
int_type = int
| {
"pile_set_name": "Github"
} |
fileFormatVersion: 2
guid: 15ad3dc0ff22d7748af5e82ef5503d32
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
| {
"pile_set_name": "Github"
} |
//===----------------------------------------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
// UNSUPPORTED: libcpp-has-no-threads
// <future>
// class error_condition
// error_condition make_error_condition(future_errc e);
#include <future>
#include <cassert>
#include "test_macros.h"
int main(int, char**)
{
{
const std::error_condition ec1 =
std::make_error_condition(std::future_errc::future_already_retrieved);
assert(ec1.value() ==
static_cast<int>(std::future_errc::future_already_retrieved));
assert(ec1.category() == std::future_category());
}
return 0;
}
| {
"pile_set_name": "Github"
} |
<?xml version="1.0"?>
<ZopeData>
<record id="1" aka="AAAAAAAAAAE=">
<pickle>
<global name="ERP5 Form" module="erp5.portal_type"/>
</pickle>
<pickle>
<dictionary>
<item>
<key> <string>_bind_names</string> </key>
<value>
<object>
<klass>
<global name="NameAssignments" module="Shared.DC.Scripts.Bindings"/>
</klass>
<tuple/>
<state>
<dictionary>
<item>
<key> <string>_asgns</string> </key>
<value>
<dictionary/>
</value>
</item>
</dictionary>
</state>
</object>
</value>
</item>
<item>
<key> <string>_objects</string> </key>
<value>
<tuple/>
</value>
</item>
<item>
<key> <string>action</string> </key>
<value> <string>Base_edit</string> </value>
</item>
<item>
<key> <string>description</string> </key>
<value> <string></string> </value>
</item>
<item>
<key> <string>edit_order</string> </key>
<value>
<list/>
</value>
</item>
<item>
<key> <string>encoding</string> </key>
<value> <string>UTF-8</string> </value>
</item>
<item>
<key> <string>enctype</string> </key>
<value> <string></string> </value>
</item>
<item>
<key> <string>group_list</string> </key>
<value>
<list>
<string>left</string>
<string>right</string>
<string>center</string>
<string>bottom</string>
<string>hidden</string>
</list>
</value>
</item>
<item>
<key> <string>groups</string> </key>
<value>
<dictionary>
<item>
<key> <string>bottom</string> </key>
<value>
<list>
<string>subscriber_listbox</string>
</list>
</value>
</item>
<item>
<key> <string>center</string> </key>
<value>
<list/>
</value>
</item>
<item>
<key> <string>hidden</string> </key>
<value>
<list/>
</value>
</item>
<item>
<key> <string>left</string> </key>
<value>
<list>
<string>my_title</string>
<string>my_source_reference</string>
<string>my_url_string</string>
<string>my_source_title</string>
<string>my_conduit_module_id</string>
<string>my_list_method_id</string>
<string>my_xml_binding_generator_method_id</string>
<string>my_gid_generator_method_id</string>
<string>my_synchronization_id_generator_method_id</string>
<string>my_content_type</string>
<string>my_authentication_type</string>
<string>my_authentication_format</string>
</list>
</value>
</item>
<item>
<key> <string>right</string> </key>
<value>
<list>
<string>my_is_synchronized_with_erp5_portal</string>
<string>my_is_activity_enabled</string>
<string>my_translated_portal_type</string>
<string>my_translated_validation_state_title</string>
</list>
</value>
</item>
</dictionary>
</value>
</item>
<item>
<key> <string>id</string> </key>
<value> <string>SyncMLPublication_view</string> </value>
</item>
<item>
<key> <string>method</string> </key>
<value> <string>POST</string> </value>
</item>
<item>
<key> <string>name</string> </key>
<value> <string>SyncMLPublication_view</string> </value>
</item>
<item>
<key> <string>pt</string> </key>
<value> <string>form_view</string> </value>
</item>
<item>
<key> <string>row_length</string> </key>
<value> <int>4</int> </value>
</item>
<item>
<key> <string>stored_encoding</string> </key>
<value> <string>UTF-8</string> </value>
</item>
<item>
<key> <string>title</string> </key>
<value> <string>SyncML Publication</string> </value>
</item>
<item>
<key> <string>unicode_mode</string> </key>
<value> <int>0</int> </value>
</item>
<item>
<key> <string>update_action</string> </key>
<value> <string></string> </value>
</item>
<item>
<key> <string>update_action_title</string> </key>
<value> <string></string> </value>
</item>
</dictionary>
</pickle>
</record>
</ZopeData>
| {
"pile_set_name": "Github"
} |
/* eslint-disable react/no-danger */
import React from 'react'
import type { IndexSpecification } from 'mongodb'
import { IColumn, getTheme } from '@fluentui/react'
import bytes from 'bytes'
import { formatNumber, formatDate } from '@/utils/formatter'
import { IndexFeatures } from './IndexFeatures'
import { IndexInfo } from './IndexInfo'
export function IndexCell(props: {
item: IndexSpecification
column: IColumn
size?: number
accesses?: { ops: number; since: Date }
}) {
const theme = getTheme()
switch (props.column.key) {
case 'name': {
return (
<span style={{ color: theme.palette.neutralPrimary }}>
{props.item.name}
</span>
)
}
case 'size': {
return props.size !== undefined ? <>{bytes(props.size)}</> : null
}
case 'ops': {
return props.accesses ? <>{formatNumber(props.accesses.ops)}</> : null
}
case 'since': {
return props.accesses ? (
<time>{formatDate(props.accesses.since)}</time>
) : null
}
case 'keys': {
return <IndexInfo value={props.item} />
}
case 'features': {
return <IndexFeatures value={props.item} />
}
default: {
return null
}
}
}
| {
"pile_set_name": "Github"
} |
/* Copyright 2019 Braden Farmer
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.farmerbb.taskbar.service;
import com.farmerbb.taskbar.ui.DashboardController;
import com.farmerbb.taskbar.ui.UIHostService;
import com.farmerbb.taskbar.ui.UIController;
public class DashboardService extends UIHostService {
@Override
public UIController newController() {
return new DashboardController(this);
}
} | {
"pile_set_name": "Github"
} |
[
{admin_menu_hierarchy, ["admin", "hierarchy", name], controller_admin, [{template,"admin_menu_hierarchy.tpl"}, seo_noindex]}
].
| {
"pile_set_name": "Github"
} |
class Foo {
def foo = {
abstract sealed class Animal
case class Goat(age: Int) extends Animal
case class Horse(age: Int) extends Animal
val x: Animal = Goat(1)
x match {
case Goat(_) => println("a goat")
}
}
} | {
"pile_set_name": "Github"
} |
{- ----------------------------------------------------------------------------------------
what : kind signatures
expected: ok
---------------------------------------------------------------------------------------- -}
module KindSig1 where
data Eq1 a b = Eq1 (forall f . f a -> f b)
Eq2 :: * -> * -> *
data Eq2 a b = Eq2 (forall f . f a -> f b)
main :: IO ()
main = return ()
| {
"pile_set_name": "Github"
} |
# ===========================================================================
# http://www.gnu.org/software/autoconf-archive/ax_compare_version.html
# ===========================================================================
#
# SYNOPSIS
#
# AX_COMPARE_VERSION(VERSION_A, OP, VERSION_B, [ACTION-IF-TRUE], [ACTION-IF-FALSE])
#
# DESCRIPTION
#
# This macro compares two version strings. Due to the various number of
# minor-version numbers that can exist, and the fact that string
# comparisons are not compatible with numeric comparisons, this is not
# necessarily trivial to do in a autoconf script. This macro makes doing
# these comparisons easy.
#
# The six basic comparisons are available, as well as checking equality
# limited to a certain number of minor-version levels.
#
# The operator OP determines what type of comparison to do, and can be one
# of:
#
# eq - equal (test A == B)
# ne - not equal (test A != B)
# le - less than or equal (test A <= B)
# ge - greater than or equal (test A >= B)
# lt - less than (test A < B)
# gt - greater than (test A > B)
#
# Additionally, the eq and ne operator can have a number after it to limit
# the test to that number of minor versions.
#
# eq0 - equal up to the length of the shorter version
# ne0 - not equal up to the length of the shorter version
# eqN - equal up to N sub-version levels
# neN - not equal up to N sub-version levels
#
# When the condition is true, shell commands ACTION-IF-TRUE are run,
# otherwise shell commands ACTION-IF-FALSE are run. The environment
# variable 'ax_compare_version' is always set to either 'true' or 'false'
# as well.
#
# Examples:
#
# AX_COMPARE_VERSION([3.15.7],[lt],[3.15.8])
# AX_COMPARE_VERSION([3.15],[lt],[3.15.8])
#
# would both be true.
#
# AX_COMPARE_VERSION([3.15.7],[eq],[3.15.8])
# AX_COMPARE_VERSION([3.15],[gt],[3.15.8])
#
# would both be false.
#
# AX_COMPARE_VERSION([3.15.7],[eq2],[3.15.8])
#
# would be true because it is only comparing two minor versions.
#
# AX_COMPARE_VERSION([3.15.7],[eq0],[3.15])
#
# would be true because it is only comparing the lesser number of minor
# versions of the two values.
#
# Note: The characters that separate the version numbers do not matter. An
# empty string is the same as version 0. OP is evaluated by autoconf, not
# configure, so must be a string, not a variable.
#
# The author would like to acknowledge Guido Draheim whose advice about
# the m4_case and m4_ifvaln functions make this macro only include the
# portions necessary to perform the specific comparison specified by the
# OP argument in the final configure script.
#
# LICENSE
#
# Copyright (c) 2008 Tim Toolan <[email protected]>
#
# Copying and distribution of this file, with or without modification, are
# permitted in any medium without royalty provided the copyright notice
# and this notice are preserved. This file is offered as-is, without any
# warranty.
#serial 11
dnl #########################################################################
AC_DEFUN([AX_COMPARE_VERSION], [
AC_REQUIRE([AC_PROG_AWK])
# Used to indicate true or false condition
ax_compare_version=false
# Convert the two version strings to be compared into a format that
# allows a simple string comparison. The end result is that a version
# string of the form 1.12.5-r617 will be converted to the form
# 0001001200050617. In other words, each number is zero padded to four
# digits, and non digits are removed.
AS_VAR_PUSHDEF([A],[ax_compare_version_A])
A=`echo "$1" | sed -e 's/\([[0-9]]*\)/Z\1Z/g' \
-e 's/Z\([[0-9]]\)Z/Z0\1Z/g' \
-e 's/Z\([[0-9]][[0-9]]\)Z/Z0\1Z/g' \
-e 's/Z\([[0-9]][[0-9]][[0-9]]\)Z/Z0\1Z/g' \
-e 's/[[^0-9]]//g'`
AS_VAR_PUSHDEF([B],[ax_compare_version_B])
B=`echo "$3" | sed -e 's/\([[0-9]]*\)/Z\1Z/g' \
-e 's/Z\([[0-9]]\)Z/Z0\1Z/g' \
-e 's/Z\([[0-9]][[0-9]]\)Z/Z0\1Z/g' \
-e 's/Z\([[0-9]][[0-9]][[0-9]]\)Z/Z0\1Z/g' \
-e 's/[[^0-9]]//g'`
dnl # In the case of le, ge, lt, and gt, the strings are sorted as necessary
dnl # then the first line is used to determine if the condition is true.
dnl # The sed right after the echo is to remove any indented white space.
m4_case(m4_tolower($2),
[lt],[
ax_compare_version=`echo "x$A
x$B" | sed 's/^ *//' | sort -r | sed "s/x${A}/false/;s/x${B}/true/;1q"`
],
[gt],[
ax_compare_version=`echo "x$A
x$B" | sed 's/^ *//' | sort | sed "s/x${A}/false/;s/x${B}/true/;1q"`
],
[le],[
ax_compare_version=`echo "x$A
x$B" | sed 's/^ *//' | sort | sed "s/x${A}/true/;s/x${B}/false/;1q"`
],
[ge],[
ax_compare_version=`echo "x$A
x$B" | sed 's/^ *//' | sort -r | sed "s/x${A}/true/;s/x${B}/false/;1q"`
],[
dnl Split the operator from the subversion count if present.
m4_bmatch(m4_substr($2,2),
[0],[
# A count of zero means use the length of the shorter version.
# Determine the number of characters in A and B.
ax_compare_version_len_A=`echo "$A" | $AWK '{print(length)}'`
ax_compare_version_len_B=`echo "$B" | $AWK '{print(length)}'`
# Set A to no more than B's length and B to no more than A's length.
A=`echo "$A" | sed "s/\(.\{$ax_compare_version_len_B\}\).*/\1/"`
B=`echo "$B" | sed "s/\(.\{$ax_compare_version_len_A\}\).*/\1/"`
],
[[0-9]+],[
# A count greater than zero means use only that many subversions
A=`echo "$A" | sed "s/\(\([[0-9]]\{4\}\)\{m4_substr($2,2)\}\).*/\1/"`
B=`echo "$B" | sed "s/\(\([[0-9]]\{4\}\)\{m4_substr($2,2)\}\).*/\1/"`
],
[.+],[
AC_WARNING(
[illegal OP numeric parameter: $2])
],[])
# Pad zeros at end of numbers to make same length.
ax_compare_version_tmp_A="$A`echo $B | sed 's/./0/g'`"
B="$B`echo $A | sed 's/./0/g'`"
A="$ax_compare_version_tmp_A"
# Check for equality or inequality as necessary.
m4_case(m4_tolower(m4_substr($2,0,2)),
[eq],[
test "x$A" = "x$B" && ax_compare_version=true
],
[ne],[
test "x$A" != "x$B" && ax_compare_version=true
],[
AC_WARNING([illegal OP parameter: $2])
])
])
AS_VAR_POPDEF([A])dnl
AS_VAR_POPDEF([B])dnl
dnl # Execute ACTION-IF-TRUE / ACTION-IF-FALSE.
if test "$ax_compare_version" = "true" ; then
m4_ifvaln([$4],[$4],[:])dnl
m4_ifvaln([$5],[else $5])dnl
fi
]) dnl AX_COMPARE_VERSION
| {
"pile_set_name": "Github"
} |
# Copyright: Ankitects Pty Ltd and contributors
# -*- coding: utf-8 -*-
# License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
from __future__ import annotations
from copy import deepcopy
from dataclasses import dataclass
import aqt
from anki.errors import DeckRenameError
from anki.lang import _, ngettext
from anki.rsbackend import TR, DeckTreeNode
from anki.utils import ids2str
from aqt import AnkiQt, gui_hooks
from aqt.qt import *
from aqt.sound import av_player
from aqt.toolbar import BottomBar
from aqt.utils import askUser, getOnlyText, openLink, shortcut, showWarning, tr
class DeckBrowserBottomBar:
def __init__(self, deck_browser: DeckBrowser):
self.deck_browser = deck_browser
@dataclass
class DeckBrowserContent:
"""Stores sections of HTML content that the deck browser will be
populated with.
Attributes:
tree {str} -- HTML of the deck tree section
stats {str} -- HTML of the stats section
"""
tree: str
stats: str
@dataclass
class RenderDeckNodeContext:
current_deck_id: int
class DeckBrowser:
_dueTree: DeckTreeNode
def __init__(self, mw: AnkiQt) -> None:
self.mw = mw
self.web = mw.web
self.bottom = BottomBar(mw, mw.bottomWeb)
self.scrollPos = QPoint(0, 0)
def show(self):
av_player.stop_and_clear_queue()
self.web.set_bridge_command(self._linkHandler, self)
self._renderPage()
# redraw top bar for theme change
self.mw.toolbar.redraw()
def refresh(self):
self._renderPage()
# Event handlers
##########################################################################
def _linkHandler(self, url):
if ":" in url:
(cmd, arg) = url.split(":")
else:
cmd = url
if cmd == "open":
self._selDeck(arg)
elif cmd == "opts":
self._showOptions(arg)
elif cmd == "shared":
self._onShared()
elif cmd == "import":
self.mw.onImport()
elif cmd == "create":
deck = getOnlyText(_("Name for deck:"))
if deck:
self.mw.col.decks.id(deck)
gui_hooks.sidebar_should_refresh_decks()
self.refresh()
elif cmd == "drag":
draggedDeckDid, ontoDeckDid = arg.split(",")
self._dragDeckOnto(draggedDeckDid, ontoDeckDid)
elif cmd == "collapse":
self._collapse(int(arg))
return False
def _selDeck(self, did):
self.mw.col.decks.select(did)
self.mw.onOverview()
# HTML generation
##########################################################################
_body = """
<center>
<table cellspacing=0 cellpading=3>
%(tree)s
</table>
<br>
%(stats)s
</center>
"""
def _renderPage(self, reuse=False):
if not reuse:
self._dueTree = self.mw.col.sched.deck_due_tree()
self.__renderPage(None)
return
self.web.evalWithCallback("window.pageYOffset", self.__renderPage)
def __renderPage(self, offset):
content = DeckBrowserContent(
tree=self._renderDeckTree(self._dueTree),
stats=self._renderStats(),
)
gui_hooks.deck_browser_will_render_content(self, content)
self.web.stdHtml(
self._body % content.__dict__,
css=["deckbrowser.css"],
js=["jquery.js", "jquery-ui.js", "deckbrowser.js"],
context=self,
)
self.web.key = "deckBrowser"
self._drawButtons()
if offset is not None:
self._scrollToOffset(offset)
gui_hooks.deck_browser_did_render(self)
def _scrollToOffset(self, offset):
self.web.eval("$(function() { window.scrollTo(0, %d, 'instant'); });" % offset)
def _renderStats(self):
return self.mw.col.studied_today()
def _renderDeckTree(self, top: DeckTreeNode) -> str:
buf = """
<tr><th colspan=5 align=start>%s</th><th class=count>%s</th>
<th class=count>%s</th><th class=optscol></th></tr>""" % (
_("Deck"),
tr(TR.STATISTICS_DUE_COUNT),
_("New"),
)
buf += self._topLevelDragRow()
ctx = RenderDeckNodeContext(current_deck_id=self.mw.col.conf["curDeck"])
for child in top.children:
buf += self._render_deck_node(child, ctx)
return buf
def _render_deck_node(self, node: DeckTreeNode, ctx: RenderDeckNodeContext) -> str:
if node.collapsed:
prefix = "+"
else:
prefix = "-"
due = node.review_count + node.learn_count
def indent():
return " " * 6 * (node.level - 1)
if node.deck_id == ctx.current_deck_id:
klass = "deck current"
else:
klass = "deck"
buf = "<tr class='%s' id='%d'>" % (klass, node.deck_id)
# deck link
if node.children:
collapse = (
"<a class=collapse href=# onclick='return pycmd(\"collapse:%d\")'>%s</a>"
% (node.deck_id, prefix)
)
else:
collapse = "<span class=collapse></span>"
if node.filtered:
extraclass = "filtered"
else:
extraclass = ""
buf += """
<td class=decktd colspan=5>%s%s<a class="deck %s"
href=# onclick="return pycmd('open:%d')">%s</a></td>""" % (
indent(),
collapse,
extraclass,
node.deck_id,
node.name,
)
# due counts
def nonzeroColour(cnt, klass):
if not cnt:
klass = "zero-count"
return f'<span class="{klass}">{cnt}</span>'
buf += "<td align=right>%s</td><td align=right>%s</td>" % (
nonzeroColour(due, "review-count"),
nonzeroColour(node.new_count, "new-count"),
)
# options
buf += (
"<td align=center class=opts><a onclick='return pycmd(\"opts:%d\");'>"
"<img src='/_anki/imgs/gears.svg' class=gears></a></td></tr>" % node.deck_id
)
# children
if not node.collapsed:
for child in node.children:
buf += self._render_deck_node(child, ctx)
return buf
def _topLevelDragRow(self):
return "<tr class='top-level-drag-row'><td colspan='6'> </td></tr>"
# Options
##########################################################################
def _showOptions(self, did: str) -> None:
m = QMenu(self.mw)
a = m.addAction(_("Rename"))
qconnect(a.triggered, lambda b, did=did: self._rename(int(did)))
a = m.addAction(_("Options"))
qconnect(a.triggered, lambda b, did=did: self._options(did))
a = m.addAction(_("Export"))
qconnect(a.triggered, lambda b, did=did: self._export(did))
a = m.addAction(_("Delete"))
qconnect(a.triggered, lambda b, did=did: self._delete(int(did)))
gui_hooks.deck_browser_will_show_options_menu(m, int(did))
m.exec_(QCursor.pos())
def _export(self, did):
self.mw.onExport(did=did)
def _rename(self, did: int) -> None:
self.mw.checkpoint(_("Rename Deck"))
deck = self.mw.col.decks.get(did)
oldName = deck["name"]
newName = getOnlyText(_("New deck name:"), default=oldName)
newName = newName.replace('"', "")
if not newName or newName == oldName:
return
try:
self.mw.col.decks.rename(deck, newName)
gui_hooks.sidebar_should_refresh_decks()
except DeckRenameError as e:
return showWarning(e.description)
self.show()
def _options(self, did):
# select the deck first, because the dyn deck conf assumes the deck
# we're editing is the current one
self.mw.col.decks.select(did)
self.mw.onDeckConf()
def _collapse(self, did: int) -> None:
self.mw.col.decks.collapse(did)
node = self.mw.col.decks.find_deck_in_tree(self._dueTree, did)
if node:
node.collapsed = not node.collapsed
self._renderPage(reuse=True)
def _dragDeckOnto(self, draggedDeckDid, ontoDeckDid):
try:
self.mw.col.decks.renameForDragAndDrop(draggedDeckDid, ontoDeckDid)
gui_hooks.sidebar_should_refresh_decks()
except DeckRenameError as e:
return showWarning(e.description)
self.show()
def _delete(self, did):
self.mw.checkpoint(_("Delete Deck"))
deck = self.mw.col.decks.get(did)
if not deck["dyn"]:
dids = [did] + [r[1] for r in self.mw.col.decks.children(did)]
cnt = self.mw.col.db.scalar(
"select count() from cards where did in {0} or "
"odid in {0}".format(ids2str(dids))
)
if cnt:
extra = ngettext(" It has %d card.", " It has %d cards.", cnt) % cnt
else:
extra = None
if (
deck["dyn"]
or not extra
or askUser(
(_("Are you sure you wish to delete %s?") % deck["name"]) + extra
)
):
self.mw.progress.start()
self.mw.col.decks.rem(did, True)
self.mw.progress.finish()
self.show()
# Top buttons
######################################################################
drawLinks = [
["", "shared", _("Get Shared")],
["", "create", _("Create Deck")],
["Ctrl+Shift+I", "import", _("Import File")],
]
def _drawButtons(self):
buf = ""
drawLinks = deepcopy(self.drawLinks)
for b in drawLinks:
if b[0]:
b[0] = _("Shortcut key: %s") % shortcut(b[0])
buf += """
<button title='%s' onclick='pycmd(\"%s\");'>%s</button>""" % tuple(
b
)
self.bottom.draw(
buf=buf,
link_handler=self._linkHandler,
web_context=DeckBrowserBottomBar(self),
)
def _onShared(self):
openLink(aqt.appShared + "decks/")
| {
"pile_set_name": "Github"
} |
#ifndef BOOST_MPL_LIST_LIST0_HPP_INCLUDED
#define BOOST_MPL_LIST_LIST0_HPP_INCLUDED
// Copyright Aleksey Gurtovoy 2000-2004
//
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//
// See http://www.boost.org/libs/mpl for documentation.
// $Id$
// $Date$
// $Revision$
#include <boost/mpl/long.hpp>
#include <boost/mpl/aux_/na.hpp>
#include <boost/mpl/list/aux_/push_front.hpp>
#include <boost/mpl/list/aux_/pop_front.hpp>
#include <boost/mpl/list/aux_/push_back.hpp>
#include <boost/mpl/list/aux_/front.hpp>
#include <boost/mpl/list/aux_/clear.hpp>
#include <boost/mpl/list/aux_/O1_size.hpp>
#include <boost/mpl/list/aux_/size.hpp>
#include <boost/mpl/list/aux_/empty.hpp>
#include <boost/mpl/list/aux_/begin_end.hpp>
#include <boost/mpl/list/aux_/item.hpp>
namespace boost { namespace mpl {
template< typename Dummy = na > struct list0;
template<> struct list0<na>
: l_end
{
typedef l_end type;
};
}}
#endif // BOOST_MPL_LIST_LIST0_HPP_INCLUDED
| {
"pile_set_name": "Github"
} |
DEFINED_PHASES=compile install preinst prepare setup unpack
DEPEND=app-arch/unzip >=dev-java/java-config-2.2.0-r3
DESCRIPTION=Java GUI for managing BibTeX and other bibliographies
EAPI=6
HOMEPAGE=http://www.jabref.org/
IUSE=elibc_FreeBSD
KEYWORDS=~amd64 ~x86
LICENSE=MIT
RDEPEND=dev-java/openjdk:8[javafx] virtual/jre:1.8 >=dev-java/java-config-2.2.0-r3
SLOT=0
SRC_URI=https://github.com/JabRef/jabref/releases/download/v4.0/JabRef-4.0.jar
_eclasses_=desktop 7fd20552ce4cc97e8acb132a499a7dd8 eapi7-ver f9ec87e93172b25ce65a85303dc06964 edos2unix 33e347e171066657f91f8b0c72ec8773 epatch ed88001f77c6dd0d5f09e45c1a5b480e estack 686eaab303305a908fd57b2fd7617800 eutils 2d5b3f4b315094768576b6799e4f926e java-pkg-2 c4e6af2574fd1dc79b43a6e27af4b5fb java-utils-2 ec7a89849c84f93e9c6db27812923888 l10n 8cdd85e169b835d518bc2fd59f780d8e ltprune db8b7ce9d0e663594bcb4a4e72131a79 multilib 98584e405e2b0264d37e8f728327fed1 preserve-libs ef207dc62baddfddfd39a164d9797648 toolchain-funcs 605c126bed8d87e4378d5ff1645330cb vcs-clean 2a0f74a496fa2b1552c4f3398258b7bf versionator 2352c3fc97241f6a02042773c8287748 wrapper 4251d4c84c25f59094fd557e0063a974
_md5_=365cea59e062e6f5e4483e27a5137e7c
| {
"pile_set_name": "Github"
} |
/*
* Copyright 1994-2002 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*/
/*
* Solaris-dependent types for Green threads
*/
#ifndef _JAVASOFT_SOLARIS_TYPES_MD_H_
#define _JAVASOFT_SOLARIS_TYPES_MD_H_
#include <sys/types.h>
#include <sys/stat.h>
#ifdef __linux__
#include <stdint.h>
#define HAVE_INTPTR_T
#define _UINT64_T
#endif
#define int8_t char
/* Fix for varargs differences on PowerPC */
#if defined(__powerpc__)
#define VARGS(x) (x)
#else
#define VARGS(x) (&x)
#endif /* __powerpc__ */
#if defined(__alpha__)
#define PTR_IS_64 1
#define LONG_IS_64 1
#else
#define PTR_IS_32 1
#endif
/* don't redefine typedef's on Solaris 2.6 or Later */
#if !defined(_ILP32) && !defined(_LP64)
#ifndef HAVE_INTPTR_T
#ifdef LONG_IS_64
typedef long intptr_t;
typedef unsigned long uintptr_t;
#else
typedef int intptr_t;
typedef unsigned int uintptr_t;
#endif /* LONG_IS_64 */
#endif /* don't HAVE_INTPTR_T */
#ifndef _UINT64_T
#define _UINT64_T
#ifdef LONG_IS_64
typedef unsigned long uint64_t;
#else
typedef unsigned long long uint64_t;
#endif
#define _UINT32_T
#ifndef uint32_t /* [sbb] scaffolding */
typedef unsigned int uint32_t;
#endif /* [sbb] scaffolding */
#if defined(__linux__)
typedef unsigned int uint_t;
#endif
#endif
#ifndef __BIT_TYPES_DEFINED__
/* that should get Linux, at least */
#ifndef _INT64_T
#define _INT64_T
#ifdef LONG_IS_64
typedef long int64_t;
#else
typedef long long int64_t;
#endif
#define _INT32_T
#ifndef int32_t /* [sbb] scaffolding */
typedef int int32_t;
#endif /* [sbb] scaffolding */
#if defined(__linux__)
typedef int int_t;
#endif
#endif
#endif /* __BIT_TYPES_DEFINED__ */
#endif /* !defined(_ILP32) && !defined(_LP64) */
/* use these macros when the compiler supports the long long type */
#define ll_high(a) ((uint32_t)(((uint64_t)(a))>>32))
#define ll_low(a) ((uint32_t)(a))
#define int2ll(a) ((int64_t)(a))
#define ll2int(a) ((int)(a))
#define ll_add(a, b) ((int64_t)(a) + (int64_t)(b))
#define ll_and(a, b) ((int64_t)(a) & (int64_t)(b))
#define ll_div(a, b) ((int64_t)(a) / (int64_t)(b))
#define ll_mul(a, b) ((int64_t)(a) * (int64_t)(b))
#define ll_neg(a) (-(a))
#define ll_not(a) (~(uint64_t)(a))
#define ll_or(a, b) ((uint64_t)(a) | (b))
#define ll_shl(a, n) ((uint64_t)(a) << (n))
#define ll_shr(a, n) ((int64_t)(a) >> (n))
#define ll_sub(a, b) ((uint64_t)(a) - (b))
#define ll_ushr(a, n) ((uint64_t)(a) >>(n))
#define ll_xor(a, b) ((int64_t)(a) ^ (int64_t)(b))
#define uint2ll(a) ((uint64_t)(a))
#define ll_rem(a,b) ((int64_t)(a) % (int64_t)(b))
extern int32_t float2l(float f);
extern int32_t double2l(double d);
extern int64_t float2ll(float f);
extern int64_t double2ll(double d);
#define ll2float(a) ((float) (a))
#define ll2double(a) ((double) (a))
/* Useful on machines where jlong and jdouble have different endianness. */
#define ll2double_bits(a) ((void) 0)
/* comparison operators */
#define ll_ltz(ll) ((ll)<0)
#define ll_gez(ll) ((ll)>=0)
#define ll_eqz(a) ((a) == 0)
#define ll_nez(a) ((a) != 0)
#define ll_eq(a, b) ((a) == (b))
#define ll_ne(a,b) ((a) != (b))
#define ll_ge(a,b) ((a) >= (b))
#define ll_le(a,b) ((a) <= (b))
#define ll_lt(a,b) ((a) < (b))
#define ll_gt(a,b) ((a) > (b))
#define ll_zero_const ((int64_t) 0)
#define ll_one_const ((int64_t) 1)
extern void ll2str(int64_t a, char *s, char *limit);
#define ll2ptr(a) ((void*)(uintptr_t)(a))
#define ptr2ll(a) ((int64_t)(uintptr_t)(a))
#ifdef ppc
#define HAVE_ALIGNED_DOUBLES
#define HAVE_ALIGNED_LONGLONGS
#endif
/* printf format modifier for printing pointers */
#ifdef _LP64
#define FORMAT64_MODIFIER "l"
#else
#define FORMAT64_MODIFIER "ll"
#endif
#endif /* !_JAVASOFT_SOLARIS_TYPES_MD_H_ */
| {
"pile_set_name": "Github"
} |
@import url("base.css");
/* common styles */
@import url("../common/domButtons.css");
@import url("../common/transitions.css");
/* widget styles */
@import url("Accordion.css");
@import url("Button.css");
@import url("Carousel.css");
@import url("CheckBox.css");
@import url("ComboBox.css");
@import url("FixedSplitter.css");
@import url("GridLayout.css");
@import url("IconContainer.css");
@import url("IconMenu.css");
@import url("Opener.css");
@import url("PageIndicator.css");
@import url("ProgressBar.css");
@import url("RadioButton.css");
@import url("ScrollablePane.css");
@import url("SearchBox.css");
@import url("SimpleDialog.css");
@import url("Slider.css");
@import url("SpinWheel.css");
@import url("TabBar.css");
@import url("TextArea.css");
@import url("ToggleButton.css");
@import url("ValuePicker.css");
@import url("FormLayout.css");
| {
"pile_set_name": "Github"
} |
#
# Set primary media language Cron job
#
FROM dockermediacloud/cron-base:latest
# Copy sources
COPY src/ /opt/mediacloud/src/cron-set-media-primary-language/
ENV PERL5LIB="/opt/mediacloud/src/cron-set-media-primary-language/perl:${PERL5LIB}" \
PYTHONPATH="/opt/mediacloud/src/cron-set-media-primary-language/python:${PYTHONPATH}"
# Copy Cron script
COPY bin /opt/mediacloud/bin
# Add Cron job
ADD crontab /etc/cron.d/set_media_primary_language
RUN chmod 0644 /etc/cron.d/set_media_primary_language
# CMD is set in "cron-base"
| {
"pile_set_name": "Github"
} |
'use strict';
var GetIntrinsic = require('../GetIntrinsic');
var $Array = GetIntrinsic('%Array%');
var $species = GetIntrinsic('%Symbol.species%', true);
var $TypeError = GetIntrinsic('%TypeError%');
var Get = require('./Get');
var IsArray = require('./IsArray');
var IsConstructor = require('./IsConstructor');
var IsInteger = require('./IsInteger');
var Type = require('./Type');
// https://ecma-international.org/ecma-262/6.0/#sec-arrayspeciescreate
module.exports = function ArraySpeciesCreate(originalArray, length) {
if (!IsInteger(length) || length < 0) {
throw new $TypeError('Assertion failed: length must be an integer >= 0');
}
var len = length === 0 ? 0 : length;
var C;
var isArray = IsArray(originalArray);
if (isArray) {
C = Get(originalArray, 'constructor');
// TODO: figure out how to make a cross-realm normal Array, a same-realm Array
// if (IsConstructor(C)) {
// if C is another realm's Array, C = undefined
// Object.getPrototypeOf(Object.getPrototypeOf(Object.getPrototypeOf(Array))) === null ?
// }
if ($species && Type(C) === 'Object') {
C = Get(C, $species);
if (C === null) {
C = void 0;
}
}
}
if (typeof C === 'undefined') {
return $Array(len);
}
if (!IsConstructor(C)) {
throw new $TypeError('C must be a constructor');
}
return new C(len); // Construct(C, len);
};
| {
"pile_set_name": "Github"
} |
#!/usr/bin/env bash
if echo $SHELLOPTS | grep -q xtrace; then
export SHELLOPTS
fi
if test $(basename $0) = adb-tty; then
IS_TTY_IO=true my-adb "$@"
else
IS_TTY_IO=false my-adb "$@"
fi
| {
"pile_set_name": "Github"
} |
๏ปฟ/**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#pragma once
#include <aws/redshift/Redshift_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSStreamFwd.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <aws/redshift/model/UsageLimitFeatureType.h>
#include <aws/redshift/model/UsageLimitLimitType.h>
#include <aws/redshift/model/UsageLimitPeriod.h>
#include <aws/redshift/model/UsageLimitBreachAction.h>
#include <aws/core/utils/memory/stl/AWSVector.h>
#include <aws/redshift/model/ResponseMetadata.h>
#include <aws/redshift/model/Tag.h>
#include <utility>
namespace Aws
{
namespace Utils
{
namespace Xml
{
class XmlNode;
} // namespace Xml
} // namespace Utils
namespace Redshift
{
namespace Model
{
/**
* <p>Describes a usage limit object for a cluster. </p><p><h3>See Also:</h3> <a
* href="http://docs.aws.amazon.com/goto/WebAPI/redshift-2012-12-01/UsageLimit">AWS
* API Reference</a></p>
*/
class AWS_REDSHIFT_API UsageLimit
{
public:
UsageLimit();
UsageLimit(const Aws::Utils::Xml::XmlNode& xmlNode);
UsageLimit& operator=(const Aws::Utils::Xml::XmlNode& xmlNode);
void OutputToStream(Aws::OStream& ostream, const char* location, unsigned index, const char* locationValue) const;
void OutputToStream(Aws::OStream& oStream, const char* location) const;
/**
* <p>The identifier of the usage limit.</p>
*/
inline const Aws::String& GetUsageLimitId() const{ return m_usageLimitId; }
/**
* <p>The identifier of the usage limit.</p>
*/
inline bool UsageLimitIdHasBeenSet() const { return m_usageLimitIdHasBeenSet; }
/**
* <p>The identifier of the usage limit.</p>
*/
inline void SetUsageLimitId(const Aws::String& value) { m_usageLimitIdHasBeenSet = true; m_usageLimitId = value; }
/**
* <p>The identifier of the usage limit.</p>
*/
inline void SetUsageLimitId(Aws::String&& value) { m_usageLimitIdHasBeenSet = true; m_usageLimitId = std::move(value); }
/**
* <p>The identifier of the usage limit.</p>
*/
inline void SetUsageLimitId(const char* value) { m_usageLimitIdHasBeenSet = true; m_usageLimitId.assign(value); }
/**
* <p>The identifier of the usage limit.</p>
*/
inline UsageLimit& WithUsageLimitId(const Aws::String& value) { SetUsageLimitId(value); return *this;}
/**
* <p>The identifier of the usage limit.</p>
*/
inline UsageLimit& WithUsageLimitId(Aws::String&& value) { SetUsageLimitId(std::move(value)); return *this;}
/**
* <p>The identifier of the usage limit.</p>
*/
inline UsageLimit& WithUsageLimitId(const char* value) { SetUsageLimitId(value); return *this;}
/**
* <p>The identifier of the cluster with a usage limit.</p>
*/
inline const Aws::String& GetClusterIdentifier() const{ return m_clusterIdentifier; }
/**
* <p>The identifier of the cluster with a usage limit.</p>
*/
inline bool ClusterIdentifierHasBeenSet() const { return m_clusterIdentifierHasBeenSet; }
/**
* <p>The identifier of the cluster with a usage limit.</p>
*/
inline void SetClusterIdentifier(const Aws::String& value) { m_clusterIdentifierHasBeenSet = true; m_clusterIdentifier = value; }
/**
* <p>The identifier of the cluster with a usage limit.</p>
*/
inline void SetClusterIdentifier(Aws::String&& value) { m_clusterIdentifierHasBeenSet = true; m_clusterIdentifier = std::move(value); }
/**
* <p>The identifier of the cluster with a usage limit.</p>
*/
inline void SetClusterIdentifier(const char* value) { m_clusterIdentifierHasBeenSet = true; m_clusterIdentifier.assign(value); }
/**
* <p>The identifier of the cluster with a usage limit.</p>
*/
inline UsageLimit& WithClusterIdentifier(const Aws::String& value) { SetClusterIdentifier(value); return *this;}
/**
* <p>The identifier of the cluster with a usage limit.</p>
*/
inline UsageLimit& WithClusterIdentifier(Aws::String&& value) { SetClusterIdentifier(std::move(value)); return *this;}
/**
* <p>The identifier of the cluster with a usage limit.</p>
*/
inline UsageLimit& WithClusterIdentifier(const char* value) { SetClusterIdentifier(value); return *this;}
/**
* <p>The Amazon Redshift feature to which the limit applies.</p>
*/
inline const UsageLimitFeatureType& GetFeatureType() const{ return m_featureType; }
/**
* <p>The Amazon Redshift feature to which the limit applies.</p>
*/
inline bool FeatureTypeHasBeenSet() const { return m_featureTypeHasBeenSet; }
/**
* <p>The Amazon Redshift feature to which the limit applies.</p>
*/
inline void SetFeatureType(const UsageLimitFeatureType& value) { m_featureTypeHasBeenSet = true; m_featureType = value; }
/**
* <p>The Amazon Redshift feature to which the limit applies.</p>
*/
inline void SetFeatureType(UsageLimitFeatureType&& value) { m_featureTypeHasBeenSet = true; m_featureType = std::move(value); }
/**
* <p>The Amazon Redshift feature to which the limit applies.</p>
*/
inline UsageLimit& WithFeatureType(const UsageLimitFeatureType& value) { SetFeatureType(value); return *this;}
/**
* <p>The Amazon Redshift feature to which the limit applies.</p>
*/
inline UsageLimit& WithFeatureType(UsageLimitFeatureType&& value) { SetFeatureType(std::move(value)); return *this;}
/**
* <p>The type of limit. Depending on the feature type, this can be based on a time
* duration or data size.</p>
*/
inline const UsageLimitLimitType& GetLimitType() const{ return m_limitType; }
/**
* <p>The type of limit. Depending on the feature type, this can be based on a time
* duration or data size.</p>
*/
inline bool LimitTypeHasBeenSet() const { return m_limitTypeHasBeenSet; }
/**
* <p>The type of limit. Depending on the feature type, this can be based on a time
* duration or data size.</p>
*/
inline void SetLimitType(const UsageLimitLimitType& value) { m_limitTypeHasBeenSet = true; m_limitType = value; }
/**
* <p>The type of limit. Depending on the feature type, this can be based on a time
* duration or data size.</p>
*/
inline void SetLimitType(UsageLimitLimitType&& value) { m_limitTypeHasBeenSet = true; m_limitType = std::move(value); }
/**
* <p>The type of limit. Depending on the feature type, this can be based on a time
* duration or data size.</p>
*/
inline UsageLimit& WithLimitType(const UsageLimitLimitType& value) { SetLimitType(value); return *this;}
/**
* <p>The type of limit. Depending on the feature type, this can be based on a time
* duration or data size.</p>
*/
inline UsageLimit& WithLimitType(UsageLimitLimitType&& value) { SetLimitType(std::move(value)); return *this;}
/**
* <p>The limit amount. If time-based, this amount is in minutes. If data-based,
* this amount is in terabytes (TB).</p>
*/
inline long long GetAmount() const{ return m_amount; }
/**
* <p>The limit amount. If time-based, this amount is in minutes. If data-based,
* this amount is in terabytes (TB).</p>
*/
inline bool AmountHasBeenSet() const { return m_amountHasBeenSet; }
/**
* <p>The limit amount. If time-based, this amount is in minutes. If data-based,
* this amount is in terabytes (TB).</p>
*/
inline void SetAmount(long long value) { m_amountHasBeenSet = true; m_amount = value; }
/**
* <p>The limit amount. If time-based, this amount is in minutes. If data-based,
* this amount is in terabytes (TB).</p>
*/
inline UsageLimit& WithAmount(long long value) { SetAmount(value); return *this;}
/**
* <p>The time period that the amount applies to. A <code>weekly</code> period
* begins on Sunday. The default is <code>monthly</code>. </p>
*/
inline const UsageLimitPeriod& GetPeriod() const{ return m_period; }
/**
* <p>The time period that the amount applies to. A <code>weekly</code> period
* begins on Sunday. The default is <code>monthly</code>. </p>
*/
inline bool PeriodHasBeenSet() const { return m_periodHasBeenSet; }
/**
* <p>The time period that the amount applies to. A <code>weekly</code> period
* begins on Sunday. The default is <code>monthly</code>. </p>
*/
inline void SetPeriod(const UsageLimitPeriod& value) { m_periodHasBeenSet = true; m_period = value; }
/**
* <p>The time period that the amount applies to. A <code>weekly</code> period
* begins on Sunday. The default is <code>monthly</code>. </p>
*/
inline void SetPeriod(UsageLimitPeriod&& value) { m_periodHasBeenSet = true; m_period = std::move(value); }
/**
* <p>The time period that the amount applies to. A <code>weekly</code> period
* begins on Sunday. The default is <code>monthly</code>. </p>
*/
inline UsageLimit& WithPeriod(const UsageLimitPeriod& value) { SetPeriod(value); return *this;}
/**
* <p>The time period that the amount applies to. A <code>weekly</code> period
* begins on Sunday. The default is <code>monthly</code>. </p>
*/
inline UsageLimit& WithPeriod(UsageLimitPeriod&& value) { SetPeriod(std::move(value)); return *this;}
/**
* <p>The action that Amazon Redshift takes when the limit is reached. Possible
* values are: </p> <ul> <li> <p> <b>log</b> - To log an event in a system table.
* The default is log.</p> </li> <li> <p> <b>emit-metric</b> - To emit CloudWatch
* metrics.</p> </li> <li> <p> <b>disable</b> - To disable the feature until the
* next usage period begins.</p> </li> </ul>
*/
inline const UsageLimitBreachAction& GetBreachAction() const{ return m_breachAction; }
/**
* <p>The action that Amazon Redshift takes when the limit is reached. Possible
* values are: </p> <ul> <li> <p> <b>log</b> - To log an event in a system table.
* The default is log.</p> </li> <li> <p> <b>emit-metric</b> - To emit CloudWatch
* metrics.</p> </li> <li> <p> <b>disable</b> - To disable the feature until the
* next usage period begins.</p> </li> </ul>
*/
inline bool BreachActionHasBeenSet() const { return m_breachActionHasBeenSet; }
/**
* <p>The action that Amazon Redshift takes when the limit is reached. Possible
* values are: </p> <ul> <li> <p> <b>log</b> - To log an event in a system table.
* The default is log.</p> </li> <li> <p> <b>emit-metric</b> - To emit CloudWatch
* metrics.</p> </li> <li> <p> <b>disable</b> - To disable the feature until the
* next usage period begins.</p> </li> </ul>
*/
inline void SetBreachAction(const UsageLimitBreachAction& value) { m_breachActionHasBeenSet = true; m_breachAction = value; }
/**
* <p>The action that Amazon Redshift takes when the limit is reached. Possible
* values are: </p> <ul> <li> <p> <b>log</b> - To log an event in a system table.
* The default is log.</p> </li> <li> <p> <b>emit-metric</b> - To emit CloudWatch
* metrics.</p> </li> <li> <p> <b>disable</b> - To disable the feature until the
* next usage period begins.</p> </li> </ul>
*/
inline void SetBreachAction(UsageLimitBreachAction&& value) { m_breachActionHasBeenSet = true; m_breachAction = std::move(value); }
/**
* <p>The action that Amazon Redshift takes when the limit is reached. Possible
* values are: </p> <ul> <li> <p> <b>log</b> - To log an event in a system table.
* The default is log.</p> </li> <li> <p> <b>emit-metric</b> - To emit CloudWatch
* metrics.</p> </li> <li> <p> <b>disable</b> - To disable the feature until the
* next usage period begins.</p> </li> </ul>
*/
inline UsageLimit& WithBreachAction(const UsageLimitBreachAction& value) { SetBreachAction(value); return *this;}
/**
* <p>The action that Amazon Redshift takes when the limit is reached. Possible
* values are: </p> <ul> <li> <p> <b>log</b> - To log an event in a system table.
* The default is log.</p> </li> <li> <p> <b>emit-metric</b> - To emit CloudWatch
* metrics.</p> </li> <li> <p> <b>disable</b> - To disable the feature until the
* next usage period begins.</p> </li> </ul>
*/
inline UsageLimit& WithBreachAction(UsageLimitBreachAction&& value) { SetBreachAction(std::move(value)); return *this;}
/**
* <p>A list of tag instances.</p>
*/
inline const Aws::Vector<Tag>& GetTags() const{ return m_tags; }
/**
* <p>A list of tag instances.</p>
*/
inline bool TagsHasBeenSet() const { return m_tagsHasBeenSet; }
/**
* <p>A list of tag instances.</p>
*/
inline void SetTags(const Aws::Vector<Tag>& value) { m_tagsHasBeenSet = true; m_tags = value; }
/**
* <p>A list of tag instances.</p>
*/
inline void SetTags(Aws::Vector<Tag>&& value) { m_tagsHasBeenSet = true; m_tags = std::move(value); }
/**
* <p>A list of tag instances.</p>
*/
inline UsageLimit& WithTags(const Aws::Vector<Tag>& value) { SetTags(value); return *this;}
/**
* <p>A list of tag instances.</p>
*/
inline UsageLimit& WithTags(Aws::Vector<Tag>&& value) { SetTags(std::move(value)); return *this;}
/**
* <p>A list of tag instances.</p>
*/
inline UsageLimit& AddTags(const Tag& value) { m_tagsHasBeenSet = true; m_tags.push_back(value); return *this; }
/**
* <p>A list of tag instances.</p>
*/
inline UsageLimit& AddTags(Tag&& value) { m_tagsHasBeenSet = true; m_tags.push_back(std::move(value)); return *this; }
inline const ResponseMetadata& GetResponseMetadata() const{ return m_responseMetadata; }
inline bool ResponseMetadataHasBeenSet() const { return m_responseMetadataHasBeenSet; }
inline void SetResponseMetadata(const ResponseMetadata& value) { m_responseMetadataHasBeenSet = true; m_responseMetadata = value; }
inline void SetResponseMetadata(ResponseMetadata&& value) { m_responseMetadataHasBeenSet = true; m_responseMetadata = std::move(value); }
inline UsageLimit& WithResponseMetadata(const ResponseMetadata& value) { SetResponseMetadata(value); return *this;}
inline UsageLimit& WithResponseMetadata(ResponseMetadata&& value) { SetResponseMetadata(std::move(value)); return *this;}
private:
Aws::String m_usageLimitId;
bool m_usageLimitIdHasBeenSet;
Aws::String m_clusterIdentifier;
bool m_clusterIdentifierHasBeenSet;
UsageLimitFeatureType m_featureType;
bool m_featureTypeHasBeenSet;
UsageLimitLimitType m_limitType;
bool m_limitTypeHasBeenSet;
long long m_amount;
bool m_amountHasBeenSet;
UsageLimitPeriod m_period;
bool m_periodHasBeenSet;
UsageLimitBreachAction m_breachAction;
bool m_breachActionHasBeenSet;
Aws::Vector<Tag> m_tags;
bool m_tagsHasBeenSet;
ResponseMetadata m_responseMetadata;
bool m_responseMetadataHasBeenSet;
};
} // namespace Model
} // namespace Redshift
} // namespace Aws
| {
"pile_set_name": "Github"
} |
<ui version="4.0" >
<class>Dialog</class>
<widget class="QDialog" name="Dialog" >
<property name="geometry" >
<rect>
<x>0</x>
<y>0</y>
<width>480</width>
<height>640</height>
</rect>
</property>
<property name="windowTitle" >
<string>Dialog</string>
</property>
<widget class="QDialogButtonBox" name="buttonBox" >
<property name="geometry" >
<rect>
<x>390</x>
<y>10</y>
<width>81</width>
<height>621</height>
</rect>
</property>
<property name="orientation" >
<enum>Qt::Vertical</enum>
</property>
<property name="standardButtons" >
<set>QDialogButtonBox::Cancel|QDialogButtonBox::Ok</set>
</property>
</widget>
</widget>
<resources/>
<connections>
<connection>
<sender>buttonBox</sender>
<signal>accepted()</signal>
<receiver>Dialog</receiver>
<slot>accept()</slot>
<hints>
<hint type="sourcelabel" >
<x>248</x>
<y>254</y>
</hint>
<hint type="destinationlabel" >
<x>157</x>
<y>274</y>
</hint>
</hints>
</connection>
<connection>
<sender>buttonBox</sender>
<signal>rejected()</signal>
<receiver>Dialog</receiver>
<slot>reject()</slot>
<hints>
<hint type="sourcelabel" >
<x>316</x>
<y>260</y>
</hint>
<hint type="destinationlabel" >
<x>286</x>
<y>274</y>
</hint>
</hints>
</connection>
</connections>
</ui>
| {
"pile_set_name": "Github"
} |
/**
* Copyright (c) 2011-2019 libbitcoin developers (see AUTHORS)
*
* This file is part of libbitcoin.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef LIBBITCOIN_SYSTEM_RESUBSCRIBER_IPP
#define LIBBITCOIN_SYSTEM_RESUBSCRIBER_IPP
#include <functional>
#include <memory>
#include <string>
#include <utility>
#include <bitcoin/system/utility/assert.hpp>
#include <bitcoin/system/utility/dispatcher.hpp>
#include <bitcoin/system/utility/thread.hpp>
#include <bitcoin/system/utility/threadpool.hpp>
////#include <bitcoin/system/utility/track.hpp>
namespace libbitcoin {
namespace system {
template <typename... Args>
resubscriber<Args...>::resubscriber(threadpool& pool,
const std::string& class_name)
: stopped_(true), dispatch_(pool, class_name)
/*, track<resubscriber<Args...>>(class_name)*/
{
}
template <typename... Args>
resubscriber<Args...>::~resubscriber()
{
BITCOIN_ASSERT_MSG(subscriptions_.empty(), "resubscriber not cleared");
}
template <typename... Args>
void resubscriber<Args...>::start()
{
// Critical Section
///////////////////////////////////////////////////////////////////////////
subscribe_mutex_.lock_upgrade();
if (stopped_)
{
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
subscribe_mutex_.unlock_upgrade_and_lock();
stopped_ = false;
subscribe_mutex_.unlock();
//---------------------------------------------------------------------
return;
}
subscribe_mutex_.unlock_upgrade();
///////////////////////////////////////////////////////////////////////////
}
template <typename... Args>
void resubscriber<Args...>::stop()
{
// Critical Section
///////////////////////////////////////////////////////////////////////////
subscribe_mutex_.lock_upgrade();
if (!stopped_)
{
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
subscribe_mutex_.unlock_upgrade_and_lock();
stopped_ = true;
subscribe_mutex_.unlock();
//---------------------------------------------------------------------
return;
}
subscribe_mutex_.unlock_upgrade();
///////////////////////////////////////////////////////////////////////////
}
template <typename... Args>
void resubscriber<Args...>::subscribe(handler&& notify, Args... stopped_args)
{
// Critical Section
///////////////////////////////////////////////////////////////////////////
subscribe_mutex_.lock_upgrade();
if (!stopped_)
{
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
subscribe_mutex_.unlock_upgrade_and_lock();
subscriptions_.push_back(std::forward<handler>(notify));
subscribe_mutex_.unlock();
//---------------------------------------------------------------------
return;
}
subscribe_mutex_.unlock_upgrade();
///////////////////////////////////////////////////////////////////////////
notify(stopped_args...);
}
template <typename... Args>
void resubscriber<Args...>::invoke(Args... args)
{
do_invoke(args...);
}
template <typename... Args>
void resubscriber<Args...>::relay(Args... args)
{
// This enqueues work while maintaining order.
dispatch_.ordered(&resubscriber<Args...>::do_invoke,
this->shared_from_this(), args...);
}
// private
template <typename... Args>
void resubscriber<Args...>::do_invoke(Args... args)
{
// Critical Section (prevent concurrent handler execution)
///////////////////////////////////////////////////////////////////////////
unique_lock lock(invoke_mutex_);
// Critical Section (protect stop)
///////////////////////////////////////////////////////////////////////////
subscribe_mutex_.lock();
// Move subscribers from the member list to a temporary list.
list subscriptions;
std::swap(subscriptions, subscriptions_);
subscribe_mutex_.unlock();
///////////////////////////////////////////////////////////////////////////
// Subscriptions may be created while this loop is executing.
// Invoke subscribers from temporary list and resubscribe as indicated.
for (const auto& handler: subscriptions)
{
//!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
// DEADLOCK RISK, handler must not return to invoke.
//!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
if (handler(args...))
{
// Critical Section
///////////////////////////////////////////////////////////////////
subscribe_mutex_.lock_upgrade();
if (stopped_)
{
subscribe_mutex_.unlock_upgrade();
//-------------------------------------------------------------
continue;
}
subscribe_mutex_.unlock_upgrade_and_lock();
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
subscriptions_.push_back(handler);
subscribe_mutex_.unlock();
///////////////////////////////////////////////////////////////////
}
}
///////////////////////////////////////////////////////////////////////////
}
} // namespace system
} // namespace libbitcoin
#endif
| {
"pile_set_name": "Github"
} |
package me.lake.librestreaming.sample.hardfilter;
import android.opengl.GLES11Ext;
import android.opengl.GLES20;
import java.nio.FloatBuffer;
import me.lake.librestreaming.filter.hardvideofilter.BaseHardVideoFilter;
import me.lake.librestreaming.filter.hardvideofilter.OriginalHardVideoFilter;
import me.lake.librestreaming.tools.GLESTools;
/**
* Created by lake on 03/06/16.
* modified base on gpuimage:GPUImage3x3TextureSamplingFilter
*/
public class Base3x3SamplingHardVideoFilter extends BaseHardVideoFilter {
protected String vertexShader_filter = "" +
"attribute vec4 aCamPosition;\n" +
"attribute vec2 aCamTextureCoord;\n" +
"varying vec2 vCamTextureCoord;\n" +
"uniform highp float texelWidth; \n" +
"uniform highp float texelHeight; \n" +
"\n" +
"varying vec2 leftTextureCoordinate;\n" +
"varying vec2 rightTextureCoordinate;\n" +
"\n" +
"varying vec2 topTextureCoordinate;\n" +
"varying vec2 topLeftTextureCoordinate;\n" +
"varying vec2 topRightTextureCoordinate;\n" +
"\n" +
"varying vec2 bottomTextureCoordinate;\n" +
"varying vec2 bottomLeftTextureCoordinate;\n" +
"varying vec2 bottomRightTextureCoordinate;\n" +
"\n" +
"void main()\n" +
"{\n" +
" gl_Position = aCamPosition;\n" +
"\n" +
" vec2 widthStep = vec2(texelWidth, 0.0);\n" +
" vec2 heightStep = vec2(0.0, texelHeight);\n" +
" vec2 widthHeightStep = vec2(texelWidth, texelHeight);\n" +
" vec2 widthNegativeHeightStep = vec2(texelWidth, -texelHeight);\n" +
"\n" +
" vCamTextureCoord = aCamTextureCoord.xy;\n" +
" leftTextureCoordinate = aCamTextureCoord.xy - widthStep;\n" +
" rightTextureCoordinate = aCamTextureCoord.xy + widthStep;\n" +
"\n" +
" topTextureCoordinate = aCamTextureCoord.xy - heightStep;\n" +
" topLeftTextureCoordinate = aCamTextureCoord.xy - widthHeightStep;\n" +
" topRightTextureCoordinate = aCamTextureCoord.xy + widthNegativeHeightStep;\n" +
"\n" +
" bottomTextureCoordinate = aCamTextureCoord.xy + heightStep;\n" +
" bottomLeftTextureCoordinate = aCamTextureCoord.xy - widthNegativeHeightStep;\n" +
" bottomRightTextureCoordinate = aCamTextureCoord.xy + widthHeightStep;\n" +
"}";
protected String fragmentshader_filter;
protected int glProgram;
protected int glTextureLoc;
protected int glCamPostionLoc;
protected int glCamTextureCoordLoc;
private int mUniformTexelWidthLocation;
private int mUniformTexelHeightLocation;
private float mTexelWidth;
private float mTexelHeight;
private float mLineSize = 1.0f;
public Base3x3SamplingHardVideoFilter(String vertexShaderCode, String fragmentShaderCode) {
if (vertexShaderCode != null) {
vertexShader_filter = vertexShaderCode;
}
if (fragmentShaderCode != null) {
fragmentshader_filter = fragmentShaderCode;
}
}
@Override
public void onInit(int VWidth, int VHeight) {
super.onInit(VWidth, VHeight);
glProgram = GLESTools.createProgram(vertexShader_filter, fragmentshader_filter);
GLES20.glUseProgram(glProgram);
glTextureLoc = GLES20.glGetUniformLocation(glProgram, "uCamTexture");
glCamPostionLoc = GLES20.glGetAttribLocation(glProgram, "aCamPosition");
glCamTextureCoordLoc = GLES20.glGetAttribLocation(glProgram, "aCamTextureCoord");
mUniformTexelWidthLocation = GLES20.glGetUniformLocation(glProgram, "texelWidth");
mUniformTexelHeightLocation = GLES20.glGetUniformLocation(glProgram, "texelHeight");
mTexelWidth = mLineSize / SIZE_WIDTH;
mTexelHeight = mLineSize / SIZE_HEIGHT;
}
@Override
public void onDraw(int cameraTexture, int targetFrameBuffer, FloatBuffer shapeBuffer, FloatBuffer textrueBuffer) {
GLES20.glBindFramebuffer(GLES20.GL_FRAMEBUFFER, targetFrameBuffer);
GLES20.glUseProgram(glProgram);
GLES20.glActiveTexture(GLES20.GL_TEXTURE0);
GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, cameraTexture);
GLES20.glUniform1f(mUniformTexelWidthLocation, mTexelWidth);
GLES20.glUniform1f(mUniformTexelHeightLocation, mTexelHeight);
GLES20.glUniform1i(glTextureLoc, 0);
GLES20.glEnableVertexAttribArray(glCamPostionLoc);
GLES20.glEnableVertexAttribArray(glCamTextureCoordLoc);
shapeBuffer.position(0);
GLES20.glVertexAttribPointer(glCamPostionLoc, 2,
GLES20.GL_FLOAT, false,
2 * 4, shapeBuffer);
textrueBuffer.position(0);
GLES20.glVertexAttribPointer(glCamTextureCoordLoc, 2,
GLES20.GL_FLOAT, false,
2 * 4, textrueBuffer);
GLES20.glViewport(0, 0, SIZE_WIDTH, SIZE_HEIGHT);
GLES20.glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT);
GLES20.glDrawElements(GLES20.GL_TRIANGLES, drawIndecesBuffer.limit(), GLES20.GL_UNSIGNED_SHORT, drawIndecesBuffer);
GLES20.glFinish();
GLES20.glDisableVertexAttribArray(glCamPostionLoc);
GLES20.glDisableVertexAttribArray(glCamTextureCoordLoc);
GLES20.glBindTexture(GLES11Ext.GL_TEXTURE_EXTERNAL_OES, 0);
GLES20.glUseProgram(0);
GLES20.glBindFramebuffer(GLES20.GL_FRAMEBUFFER, 0);
}
@Override
public void onDestroy() {
super.onDestroy();
GLES20.glDeleteProgram(glProgram);
}
}
| {
"pile_set_name": "Github"
} |
{
"name": "Clicky",
"author": "Brendan Coles <[email protected]>",
"version": "0.1",
"description": "Clicky - Real Time Web Analytics",
"website": "https://www.getclicky.com/",
"matches": [
{
"regexp": "(?i-mx:<script[^>]+src=[\"'](https?:)?\\/\\/static\\.getclicky\\.com)"
}
]
}
| {
"pile_set_name": "Github"
} |
"use strict";
var dial = require("../libs/dialClient.js"),
utils = require("../libs/utils.js"),
Q = require("q");
const argv = require("yargs")
.usage("\nUsage: node " + __filename.slice(__dirname.length + 1) + "[options]")
.option("host", {
describe: "IP address of host on which DIAL server under test is running",
type: "string",
demand: true
})
.option("application", {
alias: "app",
describe: "Application to test",
type: "string",
demand: true
})
.help("help").alias("help", "h").argv;
function test() {
var host = argv.host;
var app = argv.application;
var payload = "key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&"
+ "key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&"
+ "key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&"
+ "key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&"
+ "key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&"
+ "key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&"
+ "key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&"
+ "key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&"
+ "key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&"
+ "key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&"
+ "key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&"
+ "key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&"
+ "key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&"
+ "key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&"
+ "key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&"
+ "key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&"
+ "key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&"
+ "key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&"
+ "key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&"
+ "key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&"
+ "key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&"
+ "key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&"
+ "key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&"
+ "key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&"
+ "key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&"
+ "key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&"
+ "key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&"
+ "key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&"
+ "key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&"
+ "key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&"
+ "key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&"
+ "key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&"
+ "key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value&key=value";
return new Q()
.then(function () {
utils.printTestInfo(__filename.slice(__dirname.length + 1), "Try to launch " + app + " application with excess payload and ensure DIAL server returns response code 413");
})
.then(dial.launchApplication.bind(null, host, app, payload))
.then(function (response) {
if(response.statusCode !== 413) {
return Q.reject(new Error("Tried to launch " + app + " with excess payload. Expected statusCode: 413 but got " + response.statusCode));
}
})
.then(function () {
utils.printTestSuccess()
})
.fail(function handleError(err) {
utils.printTestFailure(err);
});
}
module.exports.test = test;
if (require.main === module) {
test()
.done();
}
| {
"pile_set_name": "Github"
} |
<!doctype html>
<html>
<body>
hello world
</body>
</html>
| {
"pile_set_name": "Github"
} |
/*M///////////////////////////////////////////////////////////////////////////////////////
//
// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
// By downloading, copying, installing or using the software you agree to this license.
// If you do not agree to this license, do not download, install,
// copy or use the software.
//
//
// License Agreement
// For Open Source Computer Vision Library
//
// Copyright (C) 2013, OpenCV Foundation, all rights reserved.
// Copyright (C) 2017, Intel Corporation, all rights reserved.
// Third party copyrights are property of their respective owners.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistribution's of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistribution's 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.
//
// * The name of the copyright holders may not 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 Intel Corporation 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.
//
//M*/
#include "../precomp.hpp"
#include "layers_common.hpp"
#include "../op_cuda.hpp"
#include "../op_inf_engine.hpp"
#ifdef HAVE_DNN_NGRAPH
#include "../ie_ngraph.hpp"
#if INF_ENGINE_VER_MAJOR_GT(INF_ENGINE_RELEASE_2020_4)
#include <ngraph/op/prior_box.hpp>
#include <ngraph/op/prior_box_clustered.hpp>
#else
#include <ngraph/op/experimental/layers/prior_box.hpp>
#include <ngraph/op/experimental/layers/prior_box_clustered.hpp>
#endif
#endif
#include "../op_vkcom.hpp"
#include <float.h>
#include <algorithm>
#include <cmath>
#ifdef HAVE_OPENCL
#include "opencl_kernels_dnn.hpp"
#endif
#ifdef HAVE_CUDA
#include "../cuda4dnn/primitives/prior_box.hpp"
using namespace cv::dnn::cuda4dnn;
#endif
namespace cv
{
namespace dnn
{
class PriorBoxLayerImpl CV_FINAL : public PriorBoxLayer
{
public:
static bool getParameterDict(const LayerParams ¶ms,
const std::string ¶meterName,
DictValue& result)
{
if (!params.has(parameterName))
{
return false;
}
result = params.get(parameterName);
return true;
}
template<typename T>
T getParameter(const LayerParams ¶ms,
const std::string ¶meterName,
const size_t &idx=0,
const bool required=true,
const T& defaultValue=T())
{
DictValue dictValue;
bool success = getParameterDict(params, parameterName, dictValue);
if(!success)
{
if(required)
{
std::string message = _layerName;
message += " layer parameter does not contain ";
message += parameterName;
message += " parameter.";
CV_Error(Error::StsBadArg, message);
}
else
{
return defaultValue;
}
}
return dictValue.get<T>(idx);
}
void getAspectRatios(const LayerParams ¶ms)
{
DictValue aspectRatioParameter;
bool aspectRatioRetieved = getParameterDict(params, "aspect_ratio", aspectRatioParameter);
if (!aspectRatioRetieved)
return;
for (int i = 0; i < aspectRatioParameter.size(); ++i)
{
float aspectRatio = aspectRatioParameter.get<float>(i);
bool alreadyExists = fabs(aspectRatio - 1.f) < 1e-6f;
for (size_t j = 0; j < _aspectRatios.size() && !alreadyExists; ++j)
{
alreadyExists = fabs(aspectRatio - _aspectRatios[j]) < 1e-6;
}
if (!alreadyExists)
{
_aspectRatios.push_back(aspectRatio);
if (_flip)
{
_aspectRatios.push_back(1./aspectRatio);
}
}
}
}
static void getParams(const std::string& name, const LayerParams ¶ms,
std::vector<float>* values)
{
DictValue dict;
if (getParameterDict(params, name, dict))
{
values->resize(dict.size());
for (int i = 0; i < dict.size(); ++i)
{
(*values)[i] = dict.get<float>(i);
}
}
else
values->clear();
}
void getVariance(const LayerParams ¶ms)
{
DictValue varianceParameter;
bool varianceParameterRetrieved = getParameterDict(params, "variance", varianceParameter);
CV_Assert(varianceParameterRetrieved);
int varianceSize = varianceParameter.size();
if (varianceSize > 1)
{
// Must and only provide 4 variance.
CV_Assert(varianceSize == 4);
for (int i = 0; i < varianceSize; ++i)
{
float variance = varianceParameter.get<float>(i);
CV_Assert(variance > 0);
_variance.push_back(variance);
}
}
else
{
if (varianceSize == 1)
{
float variance = varianceParameter.get<float>(0);
CV_Assert(variance > 0);
_variance.push_back(variance);
}
else
{
// Set default to 0.1.
_variance.push_back(0.1f);
}
}
}
PriorBoxLayerImpl(const LayerParams ¶ms)
{
setParamsFrom(params);
_flip = getParameter<bool>(params, "flip", 0, false, true);
_clip = getParameter<bool>(params, "clip", 0, false, true);
_bboxesNormalized = getParameter<bool>(params, "normalized_bbox", 0, false, true);
getParams("min_size", params, &_minSize);
getAspectRatios(params);
getVariance(params);
if (params.has("max_size"))
{
getParams("max_size", params, &_maxSize);
CV_Assert(_minSize.size() == _maxSize.size());
for (int i = 0; i < _maxSize.size(); i++)
CV_Assert(_minSize[i] < _maxSize[i]);
}
std::vector<float> widths, heights;
getParams("width", params, &widths);
getParams("height", params, &heights);
_explicitSizes = !widths.empty();
CV_Assert(widths.size() == heights.size());
if (_explicitSizes)
{
CV_Assert(_aspectRatios.empty());
CV_Assert(!params.has("min_size"));
CV_Assert(!params.has("max_size"));
_boxWidths = widths;
_boxHeights = heights;
}
else
{
CV_Assert(!_minSize.empty());
for (int i = 0; i < _minSize.size(); ++i)
{
float minSize = _minSize[i];
CV_Assert(minSize > 0);
_boxWidths.push_back(minSize);
_boxHeights.push_back(minSize);
if (_maxSize.size() > 0)
{
float size = sqrt(minSize * _maxSize[i]);
_boxWidths.push_back(size);
_boxHeights.push_back(size);
}
// rest of priors
for (size_t r = 0; r < _aspectRatios.size(); ++r)
{
float arSqrt = sqrt(_aspectRatios[r]);
_boxWidths.push_back(minSize * arSqrt);
_boxHeights.push_back(minSize / arSqrt);
}
}
}
CV_Assert(_boxWidths.size() == _boxHeights.size());
_numPriors = _boxWidths.size();
if (params.has("step_h") || params.has("step_w")) {
CV_Assert(!params.has("step"));
_stepY = getParameter<float>(params, "step_h");
CV_Assert(_stepY > 0.);
_stepX = getParameter<float>(params, "step_w");
CV_Assert(_stepX > 0.);
} else if (params.has("step")) {
const float step = getParameter<float>(params, "step");
CV_Assert(step > 0);
_stepY = step;
_stepX = step;
} else {
_stepY = 0;
_stepX = 0;
}
if (params.has("offset_h") || params.has("offset_w"))
{
CV_Assert_N(!params.has("offset"), params.has("offset_h"), params.has("offset_w"));
getParams("offset_h", params, &_offsetsY);
getParams("offset_w", params, &_offsetsX);
CV_Assert(_offsetsX.size() == _offsetsY.size());
_numPriors *= std::max((size_t)1, 2 * (_offsetsX.size() - 1));
}
else
{
float offset = getParameter<float>(params, "offset", 0, false, 0.5);
_offsetsX.assign(1, offset);
_offsetsY.assign(1, offset);
}
}
virtual bool supportBackend(int backendId) CV_OVERRIDE
{
#ifdef HAVE_DNN_NGRAPH
if (backendId == DNN_BACKEND_INFERENCE_ENGINE_NGRAPH)
return _explicitSizes || _stepX == _stepY;
#endif
return backendId == DNN_BACKEND_OPENCV ||
backendId == DNN_BACKEND_CUDA ||
(backendId == DNN_BACKEND_INFERENCE_ENGINE_NN_BUILDER_2019 && haveInfEngine() &&
( _explicitSizes || (_minSize.size() == 1 && _maxSize.size() <= 1)))
|| (backendId == DNN_BACKEND_VKCOM && haveVulkan());
}
bool getMemoryShapes(const std::vector<MatShape> &inputs,
const int requiredOutputs,
std::vector<MatShape> &outputs,
std::vector<MatShape> &internals) const CV_OVERRIDE
{
CV_Assert(!inputs.empty());
int layerHeight = inputs[0][2];
int layerWidth = inputs[0][3];
// Since all images in a batch has same height and width, we only need to
// generate one set of priors which can be shared across all images.
size_t outNum = 1;
// 2 channels. First channel stores the mean of each prior coordinate.
// Second channel stores the variance of each prior coordinate.
size_t outChannels = 2;
outputs.resize(1, shape(outNum, outChannels,
layerHeight * layerWidth * _numPriors * 4));
return false;
}
void finalize(InputArrayOfArrays inputs_arr, OutputArrayOfArrays) CV_OVERRIDE
{
std::vector<Mat> inputs;
inputs_arr.getMatVector(inputs);
CV_CheckGT(inputs.size(), (size_t)1, "");
CV_CheckEQ(inputs[0].dims, 4, ""); CV_CheckEQ(inputs[1].dims, 4, "");
int layerWidth = inputs[0].size[3];
int layerHeight = inputs[0].size[2];
int imageWidth = inputs[1].size[3];
int imageHeight = inputs[1].size[2];
_stepY = _stepY == 0 ? (static_cast<float>(imageHeight) / layerHeight) : _stepY;
_stepX = _stepX == 0 ? (static_cast<float>(imageWidth) / layerWidth) : _stepX;
}
#ifdef HAVE_OPENCL
bool forward_ocl(InputArrayOfArrays inps, OutputArrayOfArrays outs, OutputArrayOfArrays internals)
{
std::vector<UMat> inputs;
std::vector<UMat> outputs;
bool use_half = (inps.depth() == CV_16S);
inps.getUMatVector(inputs);
outs.getUMatVector(outputs);
int _layerWidth = inputs[0].size[3];
int _layerHeight = inputs[0].size[2];
int _imageWidth = inputs[1].size[3];
int _imageHeight = inputs[1].size[2];
if (umat_offsetsX.empty())
{
Mat offsetsX(1, _offsetsX.size(), CV_32FC1, &_offsetsX[0]);
Mat offsetsY(1, _offsetsY.size(), CV_32FC1, &_offsetsY[0]);
Mat variance(1, _variance.size(), CV_32FC1, &_variance[0]);
Mat widths(1, _boxWidths.size(), CV_32FC1, &_boxWidths[0]);
Mat heights(1, _boxHeights.size(), CV_32FC1, &_boxHeights[0]);
offsetsX.copyTo(umat_offsetsX);
offsetsY.copyTo(umat_offsetsY);
variance.copyTo(umat_variance);
widths.copyTo(umat_widths);
heights.copyTo(umat_heights);
}
String opts;
if (use_half)
opts = "-DDtype=half -DDtype4=half4 -Dconvert_T=convert_half4";
else
opts = "-DDtype=float -DDtype4=float4 -Dconvert_T=convert_float4";
size_t nthreads = _layerHeight * _layerWidth;
ocl::Kernel kernel("prior_box", ocl::dnn::prior_box_oclsrc, opts);
kernel.set(0, (int)nthreads);
kernel.set(1, (float)_stepX);
kernel.set(2, (float)_stepY);
kernel.set(3, ocl::KernelArg::PtrReadOnly(umat_offsetsX));
kernel.set(4, ocl::KernelArg::PtrReadOnly(umat_offsetsY));
kernel.set(5, (int)_offsetsX.size());
kernel.set(6, ocl::KernelArg::PtrReadOnly(umat_widths));
kernel.set(7, ocl::KernelArg::PtrReadOnly(umat_heights));
kernel.set(8, (int)_boxWidths.size());
kernel.set(9, ocl::KernelArg::PtrWriteOnly(outputs[0]));
kernel.set(10, (int)_layerHeight);
kernel.set(11, (int)_layerWidth);
kernel.set(12, (int)_imageHeight);
kernel.set(13, (int)_imageWidth);
kernel.run(1, &nthreads, NULL, false);
// clip the prior's coordinate such that it is within [0, 1]
if (_clip)
{
ocl::Kernel kernel("clip", ocl::dnn::prior_box_oclsrc, opts);
size_t nthreads = _layerHeight * _layerWidth * _numPriors * 4;
if (!kernel.args((int)nthreads, ocl::KernelArg::PtrReadWrite(outputs[0]))
.run(1, &nthreads, NULL, false))
return false;
}
// set the variance.
{
ocl::Kernel kernel("set_variance", ocl::dnn::prior_box_oclsrc, opts);
int offset = total(shape(outputs[0]), 2);
size_t nthreads = _layerHeight * _layerWidth * _numPriors;
kernel.set(0, (int)nthreads);
kernel.set(1, (int)offset);
kernel.set(2, (int)_variance.size());
kernel.set(3, ocl::KernelArg::PtrReadOnly(umat_variance));
kernel.set(4, ocl::KernelArg::PtrWriteOnly(outputs[0]));
if (!kernel.run(1, &nthreads, NULL, false))
return false;
}
return true;
}
#endif
void forward(InputArrayOfArrays inputs_arr, OutputArrayOfArrays outputs_arr, OutputArrayOfArrays internals_arr) CV_OVERRIDE
{
CV_TRACE_FUNCTION();
CV_TRACE_ARG_VALUE(name, "name", name.c_str());
CV_OCL_RUN(IS_DNN_OPENCL_TARGET(preferableTarget),
forward_ocl(inputs_arr, outputs_arr, internals_arr))
if (inputs_arr.depth() == CV_16S)
{
forward_fallback(inputs_arr, outputs_arr, internals_arr);
return;
}
std::vector<Mat> inputs, outputs;
inputs_arr.getMatVector(inputs);
outputs_arr.getMatVector(outputs);
CV_Assert(inputs.size() == 2);
int _layerWidth = inputs[0].size[3];
int _layerHeight = inputs[0].size[2];
int _imageWidth = inputs[1].size[3];
int _imageHeight = inputs[1].size[2];
float* outputPtr = outputs[0].ptr<float>();
float _boxWidth, _boxHeight;
for (size_t h = 0; h < _layerHeight; ++h)
{
for (size_t w = 0; w < _layerWidth; ++w)
{
for (size_t i = 0; i < _boxWidths.size(); ++i)
{
_boxWidth = _boxWidths[i];
_boxHeight = _boxHeights[i];
for (int j = 0; j < _offsetsX.size(); ++j)
{
float center_x = (w + _offsetsX[j]) * _stepX;
float center_y = (h + _offsetsY[j]) * _stepY;
outputPtr = addPrior(center_x, center_y, _boxWidth, _boxHeight, _imageWidth,
_imageHeight, _bboxesNormalized, outputPtr);
}
}
}
}
// clip the prior's coordinate such that it is within [0, 1]
if (_clip)
{
int _outChannelSize = _layerHeight * _layerWidth * _numPriors * 4;
outputPtr = outputs[0].ptr<float>();
for (size_t d = 0; d < _outChannelSize; ++d)
{
outputPtr[d] = std::min<float>(std::max<float>(outputPtr[d], 0.), 1.);
}
}
// set the variance.
outputPtr = outputs[0].ptr<float>(0, 1);
if(_variance.size() == 1)
{
Mat secondChannel(1, outputs[0].size[2], CV_32F, outputPtr);
secondChannel.setTo(Scalar::all(_variance[0]));
}
else
{
int count = 0;
for (size_t h = 0; h < _layerHeight; ++h)
{
for (size_t w = 0; w < _layerWidth; ++w)
{
for (size_t i = 0; i < _numPriors; ++i)
{
for (int j = 0; j < 4; ++j)
{
outputPtr[count] = _variance[j];
++count;
}
}
}
}
}
}
#ifdef HAVE_DNN_IE_NN_BUILDER_2019
virtual Ptr<BackendNode> initInfEngine(const std::vector<Ptr<BackendWrapper> >&) CV_OVERRIDE
{
if (_explicitSizes)
{
InferenceEngine::Builder::PriorBoxClusteredLayer ieLayer(name);
ieLayer.setSteps({_stepY, _stepX});
CV_CheckEQ(_offsetsX.size(), (size_t)1, ""); CV_CheckEQ(_offsetsY.size(), (size_t)1, ""); CV_CheckEQ(_offsetsX[0], _offsetsY[0], "");
ieLayer.setOffset(_offsetsX[0]);
ieLayer.setClip(_clip);
ieLayer.setFlip(false); // We already flipped aspect ratios.
InferenceEngine::Builder::Layer l = ieLayer;
CV_Assert_N(!_boxWidths.empty(), !_boxHeights.empty(), !_variance.empty());
CV_Assert(_boxWidths.size() == _boxHeights.size());
l.getParameters()["width"] = _boxWidths;
l.getParameters()["height"] = _boxHeights;
l.getParameters()["variance"] = _variance;
return Ptr<BackendNode>(new InfEngineBackendNode(l));
}
else
{
InferenceEngine::Builder::PriorBoxLayer ieLayer(name);
CV_Assert(!_explicitSizes);
ieLayer.setMinSize(_minSize[0]);
if (!_maxSize.empty())
ieLayer.setMaxSize(_maxSize[0]);
CV_CheckEQ(_offsetsX.size(), (size_t)1, ""); CV_CheckEQ(_offsetsY.size(), (size_t)1, ""); CV_CheckEQ(_offsetsX[0], _offsetsY[0], "");
ieLayer.setOffset(_offsetsX[0]);
ieLayer.setClip(_clip);
ieLayer.setFlip(false); // We already flipped aspect ratios.
InferenceEngine::Builder::Layer l = ieLayer;
if (_stepX == _stepY)
{
l.getParameters()["step"] = _stepX;
l.getParameters()["step_h"] = 0.0f;
l.getParameters()["step_w"] = 0.0f;
}
else
{
l.getParameters()["step"] = 0.0f;
l.getParameters()["step_h"] = _stepY;
l.getParameters()["step_w"] = _stepX;
}
if (!_aspectRatios.empty())
{
l.getParameters()["aspect_ratio"] = _aspectRatios;
}
CV_Assert(!_variance.empty());
l.getParameters()["variance"] = _variance;
return Ptr<BackendNode>(new InfEngineBackendNode(l));
}
}
#endif // HAVE_DNN_IE_NN_BUILDER_2019
#ifdef HAVE_DNN_NGRAPH
virtual Ptr<BackendNode> initNgraph(const std::vector<Ptr<BackendWrapper> >& inputs, const std::vector<Ptr<BackendNode> >& nodes) CV_OVERRIDE
{
CV_Assert(nodes.size() == 2);
auto layer = nodes[0].dynamicCast<InfEngineNgraphNode>()->node;
auto image = nodes[1].dynamicCast<InfEngineNgraphNode>()->node;
auto layer_shape = std::make_shared<ngraph::op::ShapeOf>(layer);
auto image_shape = std::make_shared<ngraph::op::ShapeOf>(image);
auto lower_bounds = std::make_shared<ngraph::op::Constant>(ngraph::element::i64, ngraph::Shape{1}, std::vector<int64_t>{2});
auto upper_bounds = std::make_shared<ngraph::op::Constant>(ngraph::element::i64, ngraph::Shape{1}, std::vector<int64_t>{4});
auto strides = std::make_shared<ngraph::op::Constant>(ngraph::element::i64, ngraph::Shape{1}, std::vector<int64_t>{1});
auto slice_layer = std::make_shared<ngraph::op::v1::StridedSlice>(layer_shape,
lower_bounds, upper_bounds, strides, std::vector<int64_t>{}, std::vector<int64_t>{});
auto slice_image = std::make_shared<ngraph::op::v1::StridedSlice>(image_shape,
lower_bounds, upper_bounds, strides, std::vector<int64_t>{}, std::vector<int64_t>{});
if (_explicitSizes)
{
CV_Assert_N(!_boxWidths.empty(), !_boxHeights.empty(), !_variance.empty());
CV_Assert(_boxWidths.size() == _boxHeights.size());
ngraph::op::PriorBoxClusteredAttrs attrs;
attrs.widths = _boxWidths;
attrs.heights = _boxHeights;
attrs.clip = _clip;
CV_CheckEQ(_offsetsX.size(), (size_t)1, ""); CV_CheckEQ(_offsetsY.size(), (size_t)1, ""); CV_CheckEQ(_offsetsX[0], _offsetsY[0], "");
attrs.offset = _offsetsX[0];
attrs.step_heights = _stepY;
attrs.step_widths = _stepX;
attrs.variances = _variance;
auto priorBox = std::make_shared<ngraph::op::PriorBoxClustered>(slice_layer, slice_image, attrs);
auto axis = std::make_shared<ngraph::op::Constant>(ngraph::element::i64, ngraph::Shape{1}, std::vector<int64_t>{0});
auto unsqueeze = std::make_shared<ngraph::op::Unsqueeze>(priorBox, axis);
return Ptr<BackendNode>(new InfEngineNgraphNode(unsqueeze));
}
else
{
ngraph::op::PriorBoxAttrs attrs;
attrs.min_size = _minSize;
attrs.max_size = _maxSize;
// doesn't work with empty aspectRatio
attrs.aspect_ratio = !_aspectRatios.empty()? _aspectRatios : std::vector<float>{1.0f};
attrs.clip = _clip;
attrs.flip = false;
attrs.variance = _variance;
CV_CheckEQ(_offsetsX.size(), (size_t)1, ""); CV_CheckEQ(_offsetsY.size(), (size_t)1, ""); CV_CheckEQ(_offsetsX[0], _offsetsY[0], "");
attrs.offset = _offsetsX[0];
attrs.step = _stepX;
attrs.scale_all_sizes = !_aspectRatios.empty();
auto priorBox = std::make_shared<ngraph::op::PriorBox>(slice_layer, slice_image, attrs);
auto axis = std::make_shared<ngraph::op::Constant>(ngraph::element::i64, ngraph::Shape{1}, std::vector<int64_t>{0});
auto unsqueeze = std::make_shared<ngraph::op::Unsqueeze>(priorBox, axis);
return Ptr<BackendNode>(new InfEngineNgraphNode(unsqueeze));
}
}
#endif // HAVE_DNN_NGRAPH
#ifdef HAVE_CUDA
Ptr<BackendNode> initCUDA(
void *context_,
const std::vector<Ptr<BackendWrapper>>& inputs,
const std::vector<Ptr<BackendWrapper>>& outputs
) override
{
auto context = reinterpret_cast<csl::CSLContext*>(context_);
auto feature_map_wrapper = inputs[0].dynamicCast<CUDABackendWrapper>();
auto feature_map_shape = feature_map_wrapper->getShape();
auto image_wrapper = inputs[1].dynamicCast<CUDABackendWrapper>();
auto image_shape = image_wrapper->getShape();
PriorBoxConfiguration config;
config.feature_map_width = feature_map_shape.rbegin()[0];
config.feature_map_height = feature_map_shape.rbegin()[1];
config.image_width = image_shape.rbegin()[0];
config.image_height = image_shape.rbegin()[1];
config.num_priors = _numPriors;
config.box_widths = _boxWidths;
config.box_heights = _boxHeights;
config.offsets_x = _offsetsX;
config.offsets_y = _offsetsY;
config.stepX = _stepX;
config.stepY = _stepY;
config.variance = _variance;
config.clip = _clip;
config.normalize = _bboxesNormalized;
return make_cuda_node<cuda4dnn::PriorBoxOp>(preferableTarget, std::move(context->stream), config);
}
#endif
#ifdef HAVE_VULKAN
virtual Ptr<BackendNode> initVkCom(const std::vector<Ptr<BackendWrapper> > &input) CV_OVERRIDE
{
std::shared_ptr<vkcom::OpBase> op(new vkcom::OpPriorBox(_stepX, _stepY,
_clip, _numPriors,
_variance, _offsetsX,
_offsetsY, _boxWidths,
_boxHeights));
return Ptr<BackendNode>(new VkComBackendNode(input, op));
}
#endif // HAVE_VULKAN
virtual int64 getFLOPS(const std::vector<MatShape> &inputs,
const std::vector<MatShape> &outputs) const CV_OVERRIDE
{
CV_UNUSED(outputs); // suppress unused variable warning
long flops = 0;
for (int i = 0; i < inputs.size(); i++)
{
flops += total(inputs[i], 2) * _numPriors * 4;
}
return flops;
}
private:
std::vector<float> _minSize;
std::vector<float> _maxSize;
float _stepX, _stepY;
std::vector<float> _aspectRatios;
std::vector<float> _variance;
std::vector<float> _offsetsX;
std::vector<float> _offsetsY;
// Precomputed final widths and heights based on aspect ratios or explicit sizes.
std::vector<float> _boxWidths;
std::vector<float> _boxHeights;
#ifdef HAVE_OPENCL
UMat umat_offsetsX;
UMat umat_offsetsY;
UMat umat_widths;
UMat umat_heights;
UMat umat_variance;
#endif
bool _flip;
bool _clip;
bool _explicitSizes;
bool _bboxesNormalized;
size_t _numPriors;
static const size_t _numAxes = 4;
static const std::string _layerName;
static float* addPrior(float center_x, float center_y, float width, float height,
float imgWidth, float imgHeight, bool normalized, float* dst)
{
if (normalized)
{
dst[0] = (center_x - width * 0.5f) / imgWidth; // xmin
dst[1] = (center_y - height * 0.5f) / imgHeight; // ymin
dst[2] = (center_x + width * 0.5f) / imgWidth; // xmax
dst[3] = (center_y + height * 0.5f) / imgHeight; // ymax
}
else
{
dst[0] = center_x - width * 0.5f; // xmin
dst[1] = center_y - height * 0.5f; // ymin
dst[2] = center_x + width * 0.5f - 1.0f; // xmax
dst[3] = center_y + height * 0.5f - 1.0f; // ymax
}
return dst + 4;
}
};
const std::string PriorBoxLayerImpl::_layerName = std::string("PriorBox");
Ptr<PriorBoxLayer> PriorBoxLayer::create(const LayerParams ¶ms)
{
return Ptr<PriorBoxLayer>(new PriorBoxLayerImpl(params));
}
}
}
| {
"pile_set_name": "Github"
} |
/*
* Copyright (C) 2018 - present Instructure, Inc.
*
* This file is part of Canvas.
*
* Canvas is free software: you can redistribute it and/or modify it under
* the terms of the GNU Affero General Public License as published by the Free
* Software Foundation, version 3 of the License.
*
* Canvas is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
* A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
* details.
*
* You should have received a copy of the GNU Affero General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import React from 'react'
import {bool, func, number} from 'prop-types'
import I18n from 'i18n!assignments_2'
import {OverrideShape} from '../../assignmentData'
import {ToggleGroup} from '@instructure/ui-toggle-details'
import {View} from '@instructure/ui-layout'
import OverrideSummary from './OverrideSummary'
import OverrideDetail from './OverrideDetail'
export default class Override extends React.Component {
static propTypes = {
override: OverrideShape.isRequired,
onChangeOverride: func.isRequired,
onValidate: func.isRequired,
invalidMessage: func.isRequired,
index: number.isRequired, // offset of this override in the assignment
readOnly: bool
}
static defaultProps = {
readOnly: false
}
constructor(props) {
super(props)
this.state = {
expanded: false
}
}
handleChangeOverride = (path, value) => {
return this.props.onChangeOverride(this.props.index, path, value)
}
handleValidate = (path, value) => {
return this.props.onValidate(this.props.index, path, value)
}
invalidMessage = path => {
return this.props.invalidMessage(this.props.index, path)
}
handleToggle = (_event, expanded) => {
this.setState({expanded})
}
render() {
return (
<View as="div" margin="0 0 small 0" data-testid="Override">
<ToggleGroup
expanded={this.state.expanded}
onToggle={this.handleToggle}
toggleLabel={
this.state.expanded ? I18n.t('Click to hide details') : I18n.t('Click to show details')
}
summary={<OverrideSummary override={this.props.override} />}
background="default"
>
<OverrideDetail
override={this.props.override}
onChangeOverride={this.handleChangeOverride}
onValidate={this.handleValidate}
invalidMessage={this.invalidMessage}
readOnly={this.props.readOnly}
/>
</ToggleGroup>
</View>
)
}
}
| {
"pile_set_name": "Github"
} |
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\Process\Pipes;
/**
* PipesInterface manages descriptors and pipes for the use of proc_open.
*
* @author Romain Neutron <[email protected]>
*
* @internal
*/
interface PipesInterface
{
const CHUNK_SIZE = 16384;
/**
* Returns an array of descriptors for the use of proc_open.
*
* @return array
*/
public function getDescriptors();
/**
* Returns an array of filenames indexed by their related stream in case these pipes use temporary files.
*
* @return string[]
*/
public function getFiles();
/**
* Reads data in file handles and pipes.
*
* @param bool $blocking Whether to use blocking calls or not
* @param bool $close Whether to close pipes if they've reached EOF
*
* @return string[] An array of read data indexed by their fd
*/
public function readAndWrite($blocking, $close = false);
/**
* Returns if the current state has open file handles or pipes.
*
* @return bool
*/
public function areOpen();
/**
* Returns if pipes are able to read output.
*
* @return bool
*/
public function haveReadSupport();
/**
* Closes file handles and pipes.
*/
public function close();
}
| {
"pile_set_name": "Github"
} |
&GLOBAL
PROJECT ch4-gapw-1-distributed
PRINT_LEVEL LOW
RUN_TYPE LINEAR_RESPONSE
&END GLOBAL
&FORCE_EVAL
&DFT
BASIS_SET_FILE_NAME EMSL_BASIS_SETS
POTENTIAL_FILE_NAME POTENTIAL
&MGRID
CUTOFF 100
&RS_GRID
DISTRIBUTION_TYPE DISTRIBUTED
&END RS_GRID
&END MGRID
&QS
METHOD GAPW
&END QS
&SCF
MAX_SCF 5
SCF_GUESS ATOMIC
&END SCF
&XC
&XC_FUNCTIONAL BLYP
&END XC_FUNCTIONAL
&END XC
&END DFT
&PROPERTIES
&LINRES
&LOCALIZE
&END
MAX_ITER 10
PRECONDITIONER FULL_ALL
&CURRENT
GAUGE R_AND_STEP_FUNCTION
&END CURRENT
&NMR
&PRINT
&CHI_TENSOR
&END CHI_TENSOR
&END PRINT
&END
&END
&END
&SUBSYS
&CELL
ABC 5.0 5.0 5.0
&END CELL
&COORD
C -0.000367 0.000000 0.000481
H 0.638760 -0.000080 0.888272
H 0.207743 0.893069 -0.597225
H 0.207729 -0.892972 -0.597375
H -1.052031 -0.000017 0.303441
&END COORD
&KIND H
BASIS_SET 3-21G*
POTENTIAL ALL
&END KIND
&KIND C
BASIS_SET 3-21G*
POTENTIAL ALL
&END KIND
&END SUBSYS
&END FORCE_EVAL
| {
"pile_set_name": "Github"
} |
/*
* OMAP thermal definitions
*
* Copyright (C) 2012 Texas Instruments Incorporated - http://www.ti.com/
* Contact:
* Eduardo Valentin <[email protected]>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* version 2 as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA
*
*/
#ifndef __TI_THERMAL_H
#define __TI_THERMAL_H
#include "ti-bandgap.h"
/* PCB sensor calculation constants */
#define OMAP_GRADIENT_SLOPE_W_PCB_4430 0
#define OMAP_GRADIENT_CONST_W_PCB_4430 20000
#define OMAP_GRADIENT_SLOPE_W_PCB_4460 1142
#define OMAP_GRADIENT_CONST_W_PCB_4460 -393
#define OMAP_GRADIENT_SLOPE_W_PCB_4470 1063
#define OMAP_GRADIENT_CONST_W_PCB_4470 -477
#define OMAP_GRADIENT_SLOPE_W_PCB_5430_CPU 100
#define OMAP_GRADIENT_CONST_W_PCB_5430_CPU 484
#define OMAP_GRADIENT_SLOPE_W_PCB_5430_GPU 464
#define OMAP_GRADIENT_CONST_W_PCB_5430_GPU -5102
#define DRA752_GRADIENT_SLOPE_W_PCB 0
#define DRA752_GRADIENT_CONST_W_PCB 2000
/* trip points of interest in milicelsius (at hotspot level) */
#define OMAP_TRIP_COLD 100000
#define OMAP_TRIP_HOT 110000
#define OMAP_TRIP_SHUTDOWN 125000
#define OMAP_TRIP_NUMBER 2
#define OMAP_TRIP_STEP \
((OMAP_TRIP_SHUTDOWN - OMAP_TRIP_HOT) / (OMAP_TRIP_NUMBER - 1))
/* Update rates */
#define FAST_TEMP_MONITORING_RATE 250
/* helper macros */
/**
* ti_thermal_get_trip_value - returns trip temperature based on index
* @i: trip index
*/
#define ti_thermal_get_trip_value(i) \
(OMAP_TRIP_HOT + ((i) * OMAP_TRIP_STEP))
/**
* ti_thermal_is_valid_trip - check for trip index
* @i: trip index
*/
#define ti_thermal_is_valid_trip(trip) \
((trip) >= 0 && (trip) < OMAP_TRIP_NUMBER)
#ifdef CONFIG_TI_THERMAL
int ti_thermal_expose_sensor(struct ti_bandgap *bgp, int id, char *domain);
int ti_thermal_remove_sensor(struct ti_bandgap *bgp, int id);
int ti_thermal_report_sensor_temperature(struct ti_bandgap *bgp, int id);
int ti_thermal_register_cpu_cooling(struct ti_bandgap *bgp, int id);
int ti_thermal_unregister_cpu_cooling(struct ti_bandgap *bgp, int id);
#else
static inline
int ti_thermal_expose_sensor(struct ti_bandgap *bgp, int id, char *domain)
{
return 0;
}
static inline
int ti_thermal_remove_sensor(struct ti_bandgap *bgp, int id)
{
return 0;
}
static inline
int ti_thermal_report_sensor_temperature(struct ti_bandgap *bgp, int id)
{
return 0;
}
static inline
int ti_thermal_register_cpu_cooling(struct ti_bandgap *bgp, int id)
{
return 0;
}
static inline
int ti_thermal_unregister_cpu_cooling(struct ti_bandgap *bgp, int id)
{
return 0;
}
#endif
#endif
| {
"pile_set_name": "Github"
} |
# phpsocket.io
A server side alternative implementation of [socket.io](https://github.com/socketio/socket.io) in PHP based on [Workerman](https://github.com/walkor/Workerman).<br>
# Notice
Only support socket.io v1.3.0 or greater. <br>
This project is just translate socket.io by [workerman](https://github.com/walkor/Workerman).<br>
More api just see http://socket.io/docs/server-api/
# Install
composer require workerman/phpsocket.io
# Examples
## Simple chat
start.php
```php
use Workerman\Worker;
use PHPSocketIO\SocketIO;
require_once __DIR__ . '/vendor/autoload.php';
// Listen port 2021 for socket.io client
$io = new SocketIO(2021);
$io->on('connection', function ($socket) use ($io) {
$socket->on('chat message', function ($msg) use ($io) {
$io->emit('chat message', $msg);
});
});
Worker::runAll();
```
## Another chat demo
https://github.com/walkor/phpsocket.io/blob/master/examples/chat/start_io.php
```php
use Workerman\Worker;
use PHPSocketIO\SocketIO;
require_once __DIR__ . '/vendor/autoload.php';
// Listen port 2020 for socket.io client
$io = new SocketIO(2020);
$io->on('connection', function ($socket) {
$socket->addedUser = false;
// When the client emits 'new message', this listens and executes
$socket->on('new message', function ($data) use ($socket) {
// We tell the client to execute 'new message'
$socket->broadcast->emit('new message', array(
'username' => $socket->username,
'message' => $data
));
});
// When the client emits 'add user', this listens and executes
$socket->on('add user', function ($username) use ($socket) {
global $usernames, $numUsers;
// We store the username in the socket session for this client
$socket->username = $username;
// Add the client's username to the global list
$usernames[$username] = $username;
++$numUsers;
$socket->addedUser = true;
$socket->emit('login', array(
'numUsers' => $numUsers
));
// echo globally (all clients) that a person has connected
$socket->broadcast->emit('user joined', array(
'username' => $socket->username,
'numUsers' => $numUsers
));
});
// When the client emits 'typing', we broadcast it to others
$socket->on('typing', function () use ($socket) {
$socket->broadcast->emit('typing', array(
'username' => $socket->username
));
});
// When the client emits 'stop typing', we broadcast it to others
$socket->on('stop typing', function () use ($socket) {
$socket->broadcast->emit('stop typing', array(
'username' => $socket->username
));
});
// When the user disconnects, perform this
$socket->on('disconnect', function () use ($socket) {
global $usernames, $numUsers;
// Remove the username from global usernames list
if ($socket->addedUser) {
unset($usernames[$socket->username]);
--$numUsers;
// echo globally that this client has left
$socket->broadcast->emit('user left', array(
'username' => $socket->username,
'numUsers' => $numUsers
));
}
});
});
Worker::runAll();
```
## Enable SSL for https
**```(phpsocket.io>=1.1.1 && workerman>=3.3.7 required)```**
start.php
```php
<?php
use Workerman\Worker;
use PHPSocketIO\SocketIO;
require_once __DIR__ . '/vendor/autoload.php';
// SSL context
$context = array(
'ssl' => array(
'local_cert' => '/your/path/of/server.pem',
'local_pk' => '/your/path/of/server.key',
'verify_peer' => false
)
);
$io = new SocketIO(2021, $context);
$io->on('connection', function ($connection) use ($io) {
echo "New connection coming\n";
});
Worker::runAll();
```
# ๆๅ
[ไธญๆๆๅ](https://github.com/walkor/phpsocket.io/tree/master/docs/zh)
# Livedemo
[chat demo](http://www.workerman.net/demos/phpsocketio-chat/)
# Run chat example
cd examples/chat
## Start
```php start.php start``` for debug mode
```php start.php start -d ``` for daemon mode
## Stop
```php start.php stop```
## Status
```php start.php status```
# License
MIT
| {
"pile_set_name": "Github"
} |
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>SchemeUserState</key>
<dict>
<key>BlurMenu.xcscheme</key>
<dict>
<key>orderHint</key>
<integer>0</integer>
</dict>
</dict>
<key>SuppressBuildableAutocreation</key>
<dict>
<key>411C361718A2C70600E9934E</key>
<dict>
<key>primary</key>
<true/>
</dict>
<key>411C363818A2C70700E9934E</key>
<dict>
<key>primary</key>
<true/>
</dict>
</dict>
</dict>
</plist>
| {
"pile_set_name": "Github"
} |
// ----------------------------------------------------------------------- //
//
// MODULE : SoundDB.h
//
// PURPOSE : Definition of Sound database
//
// CREATED : 02/23/04
//
// (c) 1999-2004 Monolith Productions, Inc. All Rights Reserved
//
// ----------------------------------------------------------------------- //
#ifndef __SOUNDDB_H__
#define __SOUNDDB_H__
//
// Includes...
//
#include "GameDatabaseMgr.h"
//
// Defines...
//
const char* const SndDB_fOuterRadius = "OuterRadius";
//struct used to encapsulate sound initialization information retrieved from database
struct SoundRecord
{
SoundRecord::SoundRecord() :
m_fInnerRad ( 0.0f ),
m_fOuterRad ( 0.0f ),
m_fPitch ( 0.0f ),
m_fPlayChance ( 0.0f ),
m_nVolume ( 0 ),
m_ePriority ( SOUNDPRIORITY_MISC_LOW ),
m_nFlags ( 0 ),
m_fMinDelay ( 0.0f ),
m_fMaxDelay ( 0.0f ),
m_fDopplerFactor ( 1.0f ),
m_nMixChannel ( PLAYSOUND_MIX_DEFAULT ),
m_fSoundSwitchRad ( 0.0f ),
m_bShouldTestSwitchRadius (false)
{
}
float m_fInnerRad; // Inner sound radius
float m_fOuterRad; // Outer sound radius
float m_fPitch; // The pitch of the sound
float m_fPlayChance; // The chance that a sound will play
uint8 m_nVolume; // The volume of the sound
SoundPriority m_ePriority; // The priority of the sound
uint32 m_nFlags; // Sound flags
bool m_bLipSync; // Will lip sync if able
float m_fMinDelay; // min delay before playing this sound again
float m_fMaxDelay; // max delay before playing this sound again
float m_fDopplerFactor; // amount to adjust the doppler by
int16 m_nMixChannel; // output channel for mixer
float m_fSoundSwitchRad; // Radius where it will switch sound files, if applicable
bool m_bShouldTestSwitchRadius; // true if there's a switch radius value to test.
};
//struct containing a weighted list of sound files for random selection
class CSoundSet
{
public:
CSoundSet();
virtual ~CSoundSet() {};
void Init(HRECORD hRecord);
const char* GetRandomFile();
const char* GetRandomNotDirtyFile();
const char* GetRandomAltFile();
HRECORD GetRecord() {return m_hRecord;}
private:
void ClearDirty();
HRECORD m_hRecord;
typedef std::vector<bool, LTAllocator<bool, LT_MEM_TYPE_GAMECODE> > boolArray;
typedef std::vector<uint32, LTAllocator<uint32, LT_MEM_TYPE_GAMECODE> > uint32Array;
uint32Array m_vecWeights;
boolArray m_vecDirty;
uint32 m_nTotalWeight;
uint32Array m_vecAltWeights;
boolArray m_vecAltDirty;
uint32 m_nAltTotalWeight;
};
typedef std::vector<CSoundSet, LTAllocator<CSoundSet, LT_MEM_TYPE_GAMECODE> > SoundSetArray;
class CSoundDB;
extern CSoundDB* g_pSoundDB;
class CSoundDB : public CGameDatabaseMgr
{
DECLARE_SINGLETON( CSoundDB );
public : // Methods...
bool Init( const char *szDatabaseFile = DB_Default_File );
void Term();
HCATEGORY GetSoundCategory() { return m_hSoundCat; }
uint32 GetNumSoundRecords();
HRECORD GetSoundDBRecord(uint32 nIndex);
HRECORD GetSoundDBRecord(const char* pName);
HRECORD GetCharacterSoundDBRecord(HRECORD hModel, const char* pName);
//fills in sound record, returns false if record does not exist
bool FillSoundRecord(HRECORD hSR, SoundRecord& sr);
const char* GetRandomSoundFileNotDirty(HRECORD hSR);
const char* GetRandomSoundFileWeighted(HRECORD hSR);
const char* GetRandomAltSoundFileWeighted(HRECORD hSR);
private : // Members...
bool InitSoundSets();
HCATEGORY m_hSoundCat;
HCATEGORY m_hCharacterSoundCat;
SoundSetArray m_vecSoundSets;
};
////////////////////////////////////////////////////////////////////////////
//
// CSoundDBPlugin is used to help facilitate populating the WorldEdit object
// properties that use SoundDB
//
////////////////////////////////////////////////////////////////////////////
#ifdef _SERVERBUILD
#include "iobjectplugin.h"
class CSoundDBPlugin : public IObjectPlugin
{
private:
CSoundDBPlugin();
CSoundDBPlugin( const CSoundDBPlugin &other );
CSoundDBPlugin& operator=( const CSoundDBPlugin &other );
~CSoundDBPlugin();
public:
NO_INLINE static CSoundDBPlugin& Instance() { static CSoundDBPlugin sPlugin; return sPlugin; }
virtual LTRESULT PreHook_EditStringList(
const char* szRezPath,
const char* szPropName,
char** aszStrings,
uint32* pcStrings,
const uint32 cMaxStrings,
const uint32 cMaxStringLength);
protected :
};
#endif // _SERVERBUILD
#endif // __SOUNDDB_H__
| {
"pile_set_name": "Github"
} |
//
// ZoomTool.h
// Seashore
//
// Created by robert engels on 1/24/19.
//
#import "AbstractTool.h"
#import "ZoomOptions.h"
NS_ASSUME_NONNULL_BEGIN
@interface ZoomTool : AbstractTool
{
ZoomOptions *options;
}
@end
NS_ASSUME_NONNULL_END
| {
"pile_set_name": "Github"
} |
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright (c) 2017 Oracle and/or its affiliates. All rights reserved.
*
* The contents of this file are subject to the terms of either the GNU
* General Public License Version 2 only ("GPL") or the Common Development
* and Distribution License("CDDL") (collectively, the "License"). You
* may not use this file except in compliance with the License. You can
* obtain a copy of the License at
* https://glassfish.dev.java.net/public/CDDL+GPL_1_1.html
* or packager/legal/LICENSE.txt. See the License for the specific
* language governing permissions and limitations under the License.
*
* When distributing the software, include this License Header Notice in each
* file and include the License file at packager/legal/LICENSE.txt.
*
* GPL Classpath Exception:
* Oracle designates this particular file as subject to the "Classpath"
* exception as provided by Oracle in the GPL Version 2 section of the License
* file that accompanied this code.
*
* Modifications:
* If applicable, add the following below the License Header, with the fields
* enclosed by brackets [] replaced by your own identifying information:
* "Portions Copyright [year] [name of copyright owner]"
*
* Contributor(s):
* If you wish your version of this file to be governed by only the CDDL or
* only the GPL Version 2, indicate your decision by adding "[Contributor]
* elects to include this software in this distribution under the [CDDL or GPL
* Version 2] license." If you don't indicate a single choice of license, a
* recipient has the option to distribute your version of this file under
* either the CDDL, the GPL Version 2 or to extend the choice of license to
* its licensees as provided above. However, if you add GPL Version 2 code
* and therefore, elected the GPL Version 2 license, then the option applies
* only if the new code is made subject to such option by the copyright
* holder.
*/
package org.glassfish.hk2.xml.test.unordered;
import org.glassfish.hk2.api.ServiceLocator;
import org.glassfish.hk2.xml.test.utilities.Utilities;
import org.junit.Test;
/**
* Tests that files with unordered children can be read
* @author jwells
*
*/
public class UnorderedTest {
/**
* Shows we can read an unordered xml file streaming
* @throws Exception
*/
@Test
// @org.junit.Ignore
public void testStreamingUnordered() throws Exception {
ServiceLocator locator = Utilities.createDomLocator();
UnorderedCommons.testUnorderedUnmarshal(locator, getClass().getClassLoader());
}
/**
* Shows we can read an unordered xml file jaxb
* @throws Exception
*/
@Test
// @org.junit.Ignore
public void testStreamingJaxb() throws Exception {
ServiceLocator locator = Utilities.createLocator();
UnorderedCommons.testUnorderedUnmarshal(locator, getClass().getClassLoader());
}
}
| {
"pile_set_name": "Github"
} |
{
"variants": {
"type=bottom": { "model": "quark:block/basalt_slab" },
"type=top": { "model": "quark:block/basalt_slab_top" },
"type=double": { "model": "quark:block/basalt" }
}
}
| {
"pile_set_name": "Github"
} |
[gcr.io/google-containers/serve-hostname-arm](https://hub.docker.com/r/anjia0532/google-containers.serve-hostname-arm/tags/)
-----
[gcr.io/google-containers/serve-hostname-arm:1.5](https://hub.docker.com/r/anjia0532/google-containers.serve-hostname-arm/tags/)
| {
"pile_set_name": "Github"
} |
<?php
/**
* Phanbook : Delightfully simple forum software
*
* Licensed under The BSD License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice.
*
* @link http://phanbook.com Phanbook Project
* @since 1.0.0
* @license https://github.com/phanbook/phanbook/blob/master/LICENSE.txt
*/
namespace Phanbook\Cli\Tasks;
use Phalcon\Cli\Task;
use Phanbook\Cli\Library\Output;
/**
* \Phanbook\Cli\Tasks\TestsTask
*
* @property \Phanbook\Mail\Mail mail
* @package Phanbook\Cli\Tasks
*/
class TestsTask extends Task
{
public function test1Action()
{
Output::stdout('Hello World!');
}
public function mainAction()
{
Output::stdout("Main Action");
}
public function test2Action($paramArray)
{
Output::stdout('First param: ' . $paramArray[0]);
Output::stdout('Second param: ' . $paramArray[1]);
}
public function renderAction()
{
echo $this->mail->renderTest();
}
}
| {
"pile_set_name": "Github"
} |
/*
* MouseMoveListener.java
*
* Version 1.0
*
* 20 May 2013
*/
package com.bixly.pastevid.util.view;
import java.awt.Container;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import javax.swing.JComponent;
import javax.swing.JFrame;
/**
*
* @author Jorge
*/
public class MouseMoveListener implements MouseListener, MouseMotionListener {
private JComponent target;
private Point start_drag;
private Point start_loc;
private boolean isLocked = false;
private boolean isSnapped = true;
private Rectangle snapArea = null;
public MouseMoveListener(JComponent target) {
this.target = target;
}
public static JFrame getFrame(Container target) {
if (target instanceof JFrame) {
return (JFrame) target;
}
return getFrame(target.getParent());
}
Point getScreenLocation(MouseEvent e) {
Point cursor = e.getPoint();
Point target_location = this.target.getLocationOnScreen();
return new Point((int) (target_location.getX() + cursor.getX()),
(int) (target_location.getY() + cursor.getY()));
}
public void mouseClicked(MouseEvent e) {
}
public void mouseEntered(MouseEvent e) {
((JFrame) target.getParent().getParent().getParent().getParent()).setState(JFrame.NORMAL);
}
public void mouseExited(MouseEvent e) {
}
public void mousePressed(MouseEvent e) {
this.start_drag = this.getScreenLocation(e);
this.start_loc = MouseMoveListener.getFrame(this.target).getLocation();
}
public void mouseReleased(MouseEvent e) {
}
public void mouseDragged(MouseEvent e) {
Point current = this.getScreenLocation(e);
double distance = this.start_drag.distance(current);
double threshold = 50;
if(distance >= threshold){
this.setLocked(false);
}
if(!this.isLocked){
Point offset = new Point((int) current.getX() - (int) start_drag.getX(),
(int) current.getY() - (int) start_drag.getY());
JFrame frame = MouseMoveListener.getFrame(target);
Point new_location = new Point(
(int) (this.start_loc.getX() + offset.getX()), (int) (this.start_loc.getY() + offset.getY()));
Point newLocationFrameCenter = new Point(new_location.x + frame.getWidth() / 2,
new_location.y + frame.getHeight() / 2);
if (this.snapArea != null && this.snapArea.contains(newLocationFrameCenter)) {
frame.setLocation(this.snapArea.x, this.snapArea.y);
this.setLocked(true);
this.isSnapped = true;
} else {
this.isSnapped = false;
frame.setLocation(new_location);
}
}
}
public void mouseMoved(MouseEvent e) {
}
public void setLocked(boolean isLocked){
this.isLocked = isLocked;
}
public boolean isLocked(){
return this.isLocked;
}
/**
* Sets the snap area of this listener. If set to null, then snapping
* will be disabled.
*
* @param snapArea
*/
public void setSnapArea(Rectangle snapArea){
this.snapArea = snapArea;
}
public boolean isSnapped(){
return this.isSnapped;
}
public void setSnapped(boolean isSnapped){
this.isSnapped = isSnapped;
}
}
| {
"pile_set_name": "Github"
} |
// RUN: %clang_cc1 -fsyntax-only -fopenmp -x c++ -std=c++11 -fexceptions -fcxx-exceptions -verify %s
// RUN: %clang_cc1 -fsyntax-only -fopenmp-simd -x c++ -std=c++11 -fexceptions -fcxx-exceptions -verify %s
class S {
int a;
S() : a(0) {} // expected-note {{implicitly declared private here}}
public:
S(int v) : a(v) {}
S(const S &s) : a(s.a) {}
};
static int sii;
// expected-note@+1 {{defined as threadprivate or thread local}}
#pragma omp threadprivate(sii)
static int globalii;
int test_iteration_spaces() {
const int N = 100;
float a[N], b[N], c[N];
int ii, jj, kk;
float fii;
double dii;
#pragma omp target
#pragma omp teams distribute simd
for (int i = 0; i < 10; i += 1) {
c[i] = a[i] + b[i];
}
#pragma omp target
#pragma omp teams distribute simd
for (char i = 0; i < 10; i++) {
c[i] = a[i] + b[i];
}
#pragma omp target
#pragma omp teams distribute simd
for (char i = 0; i < 10; i += '\1') {
c[i] = a[i] + b[i];
}
#pragma omp target
#pragma omp teams distribute simd
for (long long i = 0; i < 10; i++) {
c[i] = a[i] + b[i];
}
#pragma omp target
#pragma omp teams distribute simd
// expected-error@+1 {{expression must have integral or unscoped enumeration type, not 'double'}}
for (long long i = 0; i < 10; i += 1.5) {
c[i] = a[i] + b[i];
}
#pragma omp target
#pragma omp teams distribute simd
for (long long i = 0; i < 'z'; i += 1u) {
c[i] = a[i] + b[i];
}
#pragma omp target
#pragma omp teams distribute simd
// expected-error@+1 {{variable must be of integer or random access iterator type}}
for (float fi = 0; fi < 10.0; fi++) {
c[(int)fi] = a[(int)fi] + b[(int)fi];
}
#pragma omp target
#pragma omp teams distribute simd
// expected-error@+1 {{variable must be of integer or random access iterator type}}
for (double fi = 0; fi < 10.0; fi++) {
c[(int)fi] = a[(int)fi] + b[(int)fi];
}
#pragma omp target
#pragma omp teams distribute simd
// expected-error@+1 {{initialization clause of OpenMP for loop is not in canonical form ('var = init' or 'T var = init')}}
for (int &ref = ii; ref < 10; ref++) {
}
#pragma omp target
#pragma omp teams distribute simd
// expected-error@+1 {{initialization clause of OpenMP for loop is not in canonical form ('var = init' or 'T var = init')}}
for (int i; i < 10; i++)
c[i] = a[i];
#pragma omp target
#pragma omp teams distribute simd
// expected-error@+1 {{initialization clause of OpenMP for loop is not in canonical form ('var = init' or 'T var = init')}}
for (int i = 0, j = 0; i < 10; ++i)
c[i] = a[i];
#pragma omp target
#pragma omp teams distribute simd
// expected-error@+1 {{initialization clause of OpenMP for loop is not in canonical form ('var = init' or 'T var = init')}}
for (; ii < 10; ++ii)
c[ii] = a[ii];
#pragma omp target
#pragma omp teams distribute simd
// expected-warning@+2 {{expression result unused}}
// expected-error@+1 {{initialization clause of OpenMP for loop is not in canonical form ('var = init' or 'T var = init')}}
for (ii + 1; ii < 10; ++ii)
c[ii] = a[ii];
#pragma omp target
#pragma omp teams distribute simd
// expected-error@+1 {{initialization clause of OpenMP for loop is not in canonical form ('var = init' or 'T var = init')}}
for (c[ii] = 0; ii < 10; ++ii)
c[ii] = a[ii];
#pragma omp target
#pragma omp teams distribute simd
// Ok to skip parenthesises.
for (((ii)) = 0; ii < 10; ++ii)
c[ii] = a[ii];
#pragma omp target
#pragma omp teams distribute simd
// expected-error@+1 {{condition of OpenMP for loop must be a relational comparison ('<', '<=', '>', or '>=') of loop variable 'i'}}
for (int i = 0; i; i++)
c[i] = a[i];
#pragma omp target
#pragma omp teams distribute simd
// expected-error@+2 {{condition of OpenMP for loop must be a relational comparison ('<', '<=', '>', or '>=') of loop variable 'i'}}
// expected-error@+1 {{increment clause of OpenMP for loop must perform simple addition or subtraction on loop variable 'i'}}
for (int i = 0; jj < kk; ii++)
c[i] = a[i];
#pragma omp target
#pragma omp teams distribute simd
// expected-error@+1 {{condition of OpenMP for loop must be a relational comparison ('<', '<=', '>', or '>=') of loop variable 'i'}}
for (int i = 0; !!i; i++)
c[i] = a[i];
#pragma omp target
#pragma omp teams distribute simd
// expected-error@+1 {{condition of OpenMP for loop must be a relational comparison ('<', '<=', '>', or '>=') of loop variable 'i'}}
for (int i = 0; i != 1; i++)
c[i] = a[i];
#pragma omp target
#pragma omp teams distribute simd
// expected-error@+1 {{condition of OpenMP for loop must be a relational comparison ('<', '<=', '>', or '>=') of loop variable 'i'}}
for (int i = 0;; i++)
c[i] = a[i];
// Ok.
#pragma omp target
#pragma omp teams distribute simd
for (int i = 11; i > 10; i--)
c[i] = a[i];
// Ok.
#pragma omp target
#pragma omp teams distribute simd
for (int i = 0; i < 10; ++i)
c[i] = a[i];
// Ok.
#pragma omp target
#pragma omp teams distribute simd
for (ii = 0; ii < 10; ++ii)
c[ii] = a[ii];
#pragma omp target
#pragma omp teams distribute simd
// expected-error@+1 {{increment clause of OpenMP for loop must perform simple addition or subtraction on loop variable 'ii'}}
for (ii = 0; ii < 10; ++jj)
c[ii] = a[jj];
#pragma omp target
#pragma omp teams distribute simd
// expected-error@+1 {{increment clause of OpenMP for loop must perform simple addition or subtraction on loop variable 'ii'}}
for (ii = 0; ii < 10; ++++ii)
c[ii] = a[ii];
// Ok but undefined behavior (in general, cannot check that incr
// is really loop-invariant).
#pragma omp target
#pragma omp teams distribute simd
for (ii = 0; ii < 10; ii = ii + ii)
c[ii] = a[ii];
#pragma omp target
#pragma omp teams distribute simd
// expected-error@+1 {{expression must have integral or unscoped enumeration type, not 'float'}}
for (ii = 0; ii < 10; ii = ii + 1.0f)
c[ii] = a[ii];
// Ok - step was converted to integer type.
#pragma omp target
#pragma omp teams distribute simd
for (ii = 0; ii < 10; ii = ii + (int)1.1f)
c[ii] = a[ii];
#pragma omp target
#pragma omp teams distribute simd
// expected-error@+1 {{increment clause of OpenMP for loop must perform simple addition or subtraction on loop variable 'ii'}}
for (ii = 0; ii < 10; jj = ii + 2)
c[ii] = a[ii];
#pragma omp target
#pragma omp teams distribute simd
// expected-warning@+2 {{relational comparison result unused}}
// expected-error@+1 {{increment clause of OpenMP for loop must perform simple addition or subtraction on loop variable 'ii'}}
for (ii = 0; ii<10; jj> kk + 2)
c[ii] = a[ii];
#pragma omp target
#pragma omp teams distribute simd
// expected-error@+1 {{increment clause of OpenMP for loop must perform simple addition or subtraction on loop variable 'ii'}}
for (ii = 0; ii < 10;)
c[ii] = a[ii];
#pragma omp target
#pragma omp teams distribute simd
// expected-warning@+2 {{expression result unused}}
// expected-error@+1 {{increment clause of OpenMP for loop must perform simple addition or subtraction on loop variable 'ii'}}
for (ii = 0; ii < 10; !ii)
c[ii] = a[ii];
#pragma omp target
#pragma omp teams distribute simd
// expected-error@+1 {{increment clause of OpenMP for loop must perform simple addition or subtraction on loop variable 'ii'}}
for (ii = 0; ii < 10; ii ? ++ii : ++jj)
c[ii] = a[ii];
#pragma omp target
#pragma omp teams distribute simd
// expected-error@+1 {{increment clause of OpenMP for loop must perform simple addition or subtraction on loop variable 'ii'}}
for (ii = 0; ii < 10; ii = ii < 10)
c[ii] = a[ii];
#pragma omp target
#pragma omp teams distribute simd
// expected-note@+2 {{loop step is expected to be positive due to this condition}}
// expected-error@+1 {{increment expression must cause 'ii' to increase on each iteration of OpenMP for loop}}
for (ii = 0; ii < 10; ii = ii + 0)
c[ii] = a[ii];
#pragma omp target
#pragma omp teams distribute simd
// expected-note@+2 {{loop step is expected to be positive due to this condition}}
// expected-error@+1 {{increment expression must cause 'ii' to increase on each iteration of OpenMP for loop}}
for (ii = 0; ii < 10; ii = ii + (int)(0.8 - 0.45))
c[ii] = a[ii];
#pragma omp target
#pragma omp teams distribute simd
// expected-note@+2 {{loop step is expected to be positive due to this condition}}
// expected-error@+1 {{increment expression must cause 'ii' to increase on each iteration of OpenMP for loop}}
for (ii = 0; (ii) < 10; ii -= 25)
c[ii] = a[ii];
#pragma omp target
#pragma omp teams distribute simd
// expected-note@+2 {{loop step is expected to be positive due to this condition}}
// expected-error@+1 {{increment expression must cause 'ii' to increase on each iteration of OpenMP for loop}}
for (ii = 0; (ii < 10); ii -= 0)
c[ii] = a[ii];
#pragma omp target
#pragma omp teams distribute simd
// expected-note@+2 {{loop step is expected to be negative due to this condition}}
// expected-error@+1 {{increment expression must cause 'ii' to decrease on each iteration of OpenMP for loop}}
for (ii = 0; ii > 10; (ii += 0))
c[ii] = a[ii];
#pragma omp target
#pragma omp teams distribute simd
// expected-note@+2 {{loop step is expected to be positive due to this condition}}
// expected-error@+1 {{increment expression must cause 'ii' to increase on each iteration of OpenMP for loop}}
for (ii = 0; ii < 10; (ii) = (1 - 1) + (ii))
c[ii] = a[ii];
#pragma omp target
#pragma omp teams distribute simd
// expected-note@+2 {{loop step is expected to be negative due to this condition}}
// expected-error@+1 {{increment expression must cause 'ii' to decrease on each iteration of OpenMP for loop}}
for ((ii = 0); ii > 10; (ii -= 0))
c[ii] = a[ii];
#pragma omp target
#pragma omp teams distribute simd
// expected-note@+2 {{loop step is expected to be positive due to this condition}}
// expected-error@+1 {{increment expression must cause 'ii' to increase on each iteration of OpenMP for loop}}
for (ii = 0; (ii < 10); (ii -= 0))
c[ii] = a[ii];
#pragma omp target
#pragma omp teams distribute simd firstprivate(ii) // expected-note {{defined as firstprivate}}
// expected-error@+1 {{loop iteration variable in the associated loop of 'omp teams distribute simd' directive may not be firstprivate, predetermined as linear}}
for (ii = 0; ii < 10; ii++)
c[ii] = a[ii];
#pragma omp target
#pragma omp teams distribute simd private(ii) // expected-note {{defined as private}}
// expected-error@+1 {{loop iteration variable in the associated loop of 'omp teams distribute simd' directive may not be private, predetermined as linear}}
for (ii = 0; ii < 10; ii++)
c[ii] = a[ii];
#pragma omp target
#pragma omp teams distribute simd lastprivate(ii) // expected-note {{defined as lastprivate}}
// expected-error@+1 {{loop iteration variable in the associated loop of 'omp teams distribute simd' directive may not be lastprivate, predetermined as linear}}
for (ii = 0; ii < 10; ii++)
c[ii] = a[ii];
#pragma omp target
#pragma omp teams distribute simd
// expected-error@+1 {{loop iteration variable in the associated loop of 'omp teams distribute simd' directive may not be threadprivate or thread local, predetermined as linear}}
for (sii = 0; sii < 10; sii++)
c[sii] = a[sii];
{
#pragma omp target
#pragma omp teams distribute simd collapse(2)
for (ii = 0; ii < 10; ii += 1)
for (globalii = 0; globalii < 10; globalii += 1)
c[globalii] += a[globalii] + ii;
}
#pragma omp target
#pragma omp teams distribute simd
// expected-error@+1 {{statement after '#pragma omp teams distribute simd' must be a for loop}}
for (auto &item : a) {
item = item + 1;
}
#pragma omp target
#pragma omp teams distribute simd
// expected-note@+2 {{loop step is expected to be positive due to this condition}}
// expected-error@+1 {{increment expression must cause 'i' to increase on each iteration of OpenMP for loop}}
for (unsigned i = 9; i < 10; i--) {
c[i] = a[i] + b[i];
}
int(*lb)[4] = nullptr;
#pragma omp target
#pragma omp teams distribute simd
for (int(*p)[4] = lb; p < lb + 8; ++p) {
}
#pragma omp target
#pragma omp teams distribute simd
// expected-warning@+1 {{initialization clause of OpenMP for loop is not in canonical form ('var = init' or 'T var = init')}}
for (int a{0}; a < 10; ++a) {
}
return 0;
}
// Iterators allowed in openmp for-loops.
namespace std {
struct random_access_iterator_tag {};
template <class Iter>
struct iterator_traits {
typedef typename Iter::difference_type difference_type;
typedef typename Iter::iterator_category iterator_category;
};
template <class Iter>
typename iterator_traits<Iter>::difference_type
distance(Iter first, Iter last) { return first - last; }
}
class Iter0 {
public:
Iter0() {}
Iter0(const Iter0 &) {}
Iter0 operator++() { return *this; }
Iter0 operator--() { return *this; }
bool operator<(Iter0 a) { return true; }
};
// expected-note@+2 {{candidate function not viable: no known conversion from 'GoodIter' to 'Iter0' for 1st argument}}
// expected-note@+1 2 {{candidate function not viable: no known conversion from 'Iter1' to 'Iter0' for 1st argument}}
int operator-(Iter0 a, Iter0 b) { return 0; }
class Iter1 {
public:
Iter1(float f = 0.0f, double d = 0.0) {}
Iter1(const Iter1 &) {}
Iter1 operator++() { return *this; }
Iter1 operator--() { return *this; }
bool operator<(Iter1 a) { return true; }
bool operator>=(Iter1 a) { return false; }
};
class GoodIter {
public:
GoodIter() {}
GoodIter(const GoodIter &) {}
GoodIter(int fst, int snd) {}
GoodIter &operator=(const GoodIter &that) { return *this; }
GoodIter &operator=(const Iter0 &that) { return *this; }
GoodIter &operator+=(int x) { return *this; }
explicit GoodIter(void *) {}
GoodIter operator++() { return *this; }
GoodIter operator--() { return *this; }
bool operator!() { return true; }
bool operator<(GoodIter a) { return true; }
bool operator<=(GoodIter a) { return true; }
bool operator>=(GoodIter a) { return false; }
typedef int difference_type;
typedef std::random_access_iterator_tag iterator_category;
};
// expected-note@+2 {{candidate function not viable: no known conversion from 'const Iter0' to 'GoodIter' for 2nd argument}}
// expected-note@+1 2 {{candidate function not viable: no known conversion from 'Iter1' to 'GoodIter' for 1st argument}}
int operator-(GoodIter a, GoodIter b) { return 0; }
// expected-note@+1 3 {{candidate function not viable: requires single argument 'a', but 2 arguments were provided}}
GoodIter operator-(GoodIter a) { return a; }
// expected-note@+2 {{candidate function not viable: no known conversion from 'const Iter0' to 'int' for 2nd argument}}
// expected-note@+1 2 {{candidate function not viable: no known conversion from 'Iter1' to 'GoodIter' for 1st argument}}
GoodIter operator-(GoodIter a, int v) { return GoodIter(); }
// expected-note@+1 2 {{candidate function not viable: no known conversion from 'Iter0' to 'GoodIter' for 1st argument}}
GoodIter operator+(GoodIter a, int v) { return GoodIter(); }
// expected-note@+2 {{candidate function not viable: no known conversion from 'GoodIter' to 'int' for 1st argument}}
// expected-note@+1 2 {{candidate function not viable: no known conversion from 'Iter1' to 'int' for 1st argument}}
GoodIter operator-(int v, GoodIter a) { return GoodIter(); }
// expected-note@+1 2 {{candidate function not viable: no known conversion from 'Iter0' to 'int' for 1st argument}}
GoodIter operator+(int v, GoodIter a) { return GoodIter(); }
int test_with_random_access_iterator() {
GoodIter begin, end;
Iter0 begin0, end0;
#pragma omp target
#pragma omp teams distribute simd
for (GoodIter I = begin; I < end; ++I)
++I;
#pragma omp target
#pragma omp teams distribute simd
// expected-error@+1 {{initialization clause of OpenMP for loop is not in canonical form ('var = init' or 'T var = init')}}
for (GoodIter &I = begin; I < end; ++I)
++I;
#pragma omp target
#pragma omp teams distribute simd
for (GoodIter I = begin; I >= end; --I)
++I;
#pragma omp target
#pragma omp teams distribute simd
// expected-warning@+1 {{initialization clause of OpenMP for loop is not in canonical form ('var = init' or 'T var = init')}}
for (GoodIter I(begin); I < end; ++I)
++I;
#pragma omp target
#pragma omp teams distribute simd
// expected-warning@+1 {{initialization clause of OpenMP for loop is not in canonical form ('var = init' or 'T var = init')}}
for (GoodIter I(nullptr); I < end; ++I)
++I;
#pragma omp target
#pragma omp teams distribute simd
// expected-warning@+1 {{initialization clause of OpenMP for loop is not in canonical form ('var = init' or 'T var = init')}}
for (GoodIter I(0); I < end; ++I)
++I;
#pragma omp target
#pragma omp teams distribute simd
// expected-warning@+1 {{initialization clause of OpenMP for loop is not in canonical form ('var = init' or 'T var = init')}}
for (GoodIter I(1, 2); I < end; ++I)
++I;
#pragma omp target
#pragma omp teams distribute simd
for (begin = GoodIter(0); begin < end; ++begin)
++begin;
#pragma omp target
#pragma omp teams distribute simd
// expected-error@+2 {{invalid operands to binary expression ('GoodIter' and 'const Iter0')}}
// expected-error@+1 {{could not calculate number of iterations calling 'operator-' with upper and lower loop bounds}}
for (begin = begin0; begin < end; ++begin)
++begin;
#pragma omp target
#pragma omp teams distribute simd
// expected-error@+1 {{initialization clause of OpenMP for loop is not in canonical form ('var = init' or 'T var = init')}}
for (++begin; begin < end; ++begin)
++begin;
#pragma omp target
#pragma omp teams distribute simd
for (begin = end; begin < end; ++begin)
++begin;
#pragma omp target
#pragma omp teams distribute simd
// expected-error@+1 {{condition of OpenMP for loop must be a relational comparison ('<', '<=', '>', or '>=') of loop variable 'I'}}
for (GoodIter I = begin; I - I; ++I)
++I;
#pragma omp target
#pragma omp teams distribute simd
// expected-error@+1 {{condition of OpenMP for loop must be a relational comparison ('<', '<=', '>', or '>=') of loop variable 'I'}}
for (GoodIter I = begin; begin < end; ++I)
++I;
#pragma omp target
#pragma omp teams distribute simd
// expected-error@+1 {{condition of OpenMP for loop must be a relational comparison ('<', '<=', '>', or '>=') of loop variable 'I'}}
for (GoodIter I = begin; !I; ++I)
++I;
#pragma omp target
#pragma omp teams distribute simd
// expected-note@+2 {{loop step is expected to be negative due to this condition}}
// expected-error@+1 {{increment expression must cause 'I' to decrease on each iteration of OpenMP for loop}}
for (GoodIter I = begin; I >= end; I = I + 1)
++I;
#pragma omp target
#pragma omp teams distribute simd
for (GoodIter I = begin; I >= end; I = I - 1)
++I;
#pragma omp target
#pragma omp teams distribute simd
// expected-error@+1 {{increment clause of OpenMP for loop must perform simple addition or subtraction on loop variable 'I'}}
for (GoodIter I = begin; I >= end; I = -I)
++I;
#pragma omp target
#pragma omp teams distribute simd
// expected-note@+2 {{loop step is expected to be negative due to this condition}}
// expected-error@+1 {{increment expression must cause 'I' to decrease on each iteration of OpenMP for loop}}
for (GoodIter I = begin; I >= end; I = 2 + I)
++I;
#pragma omp target
#pragma omp teams distribute simd
// expected-error@+1 {{increment clause of OpenMP for loop must perform simple addition or subtraction on loop variable 'I'}}
for (GoodIter I = begin; I >= end; I = 2 - I)
++I;
#pragma omp target
#pragma omp teams distribute simd
// expected-error@+1 {{invalid operands to binary expression ('Iter0' and 'int')}}
for (Iter0 I = begin0; I < end0; ++I)
++I;
#pragma omp target
#pragma omp teams distribute simd
// Initializer is constructor without params.
// expected-error@+2 {{invalid operands to binary expression ('Iter0' and 'int')}}
// expected-warning@+1 {{initialization clause of OpenMP for loop is not in canonical form ('var = init' or 'T var = init')}}
for (Iter0 I; I < end0; ++I)
++I;
Iter1 begin1, end1;
#pragma omp target
#pragma omp teams distribute simd
// expected-error@+2 {{invalid operands to binary expression ('Iter1' and 'Iter1')}}
// expected-error@+1 {{could not calculate number of iterations calling 'operator-' with upper and lower loop bounds}}
for (Iter1 I = begin1; I < end1; ++I)
++I;
#pragma omp target
#pragma omp teams distribute simd
// expected-note@+2 {{loop step is expected to be negative due to this condition}}
// expected-error@+1 {{increment expression must cause 'I' to decrease on each iteration of OpenMP for loop}}
for (Iter1 I = begin1; I >= end1; ++I)
++I;
#pragma omp target
#pragma omp teams distribute simd
// expected-error@+4 {{invalid operands to binary expression ('Iter1' and 'float')}}
// expected-error@+3 {{could not calculate number of iterations calling 'operator-' with upper and lower loop bounds}}
// Initializer is constructor with all default params.
// expected-warning@+1 {{initialization clause of OpenMP for loop is not in canonical form ('var = init' or 'T var = init')}}
for (Iter1 I; I < end1; ++I) {
}
return 0;
}
template <typename IT, int ST>
class TC {
public:
int dotest_lt(IT begin, IT end) {
#pragma omp target
#pragma omp teams distribute simd
// expected-note@+2 {{loop step is expected to be positive due to this condition}}
// expected-error@+1 {{increment expression must cause 'I' to increase on each iteration of OpenMP for loop}}
for (IT I = begin; I < end; I = I + ST) {
++I;
}
#pragma omp target
#pragma omp teams distribute simd
// expected-note@+2 {{loop step is expected to be positive due to this condition}}
// expected-error@+1 {{increment expression must cause 'I' to increase on each iteration of OpenMP for loop}}
for (IT I = begin; I <= end; I += ST) {
++I;
}
#pragma omp target
#pragma omp teams distribute simd
for (IT I = begin; I < end; ++I) {
++I;
}
}
static IT step() {
return IT(ST);
}
};
template <typename IT, int ST = 0>
int dotest_gt(IT begin, IT end) {
#pragma omp target
#pragma omp teams distribute simd
// expected-note@+2 2 {{loop step is expected to be negative due to this condition}}
// expected-error@+1 2 {{increment expression must cause 'I' to decrease on each iteration of OpenMP for loop}}
for (IT I = begin; I >= end; I = I + ST) {
++I;
}
#pragma omp target
#pragma omp teams distribute simd
// expected-note@+2 2 {{loop step is expected to be negative due to this condition}}
// expected-error@+1 2 {{increment expression must cause 'I' to decrease on each iteration of OpenMP for loop}}
for (IT I = begin; I >= end; I += ST) {
++I;
}
#pragma omp target
#pragma omp teams distribute simd
// expected-note@+2 {{loop step is expected to be negative due to this condition}}
// expected-error@+1 {{increment expression must cause 'I' to decrease on each iteration of OpenMP for loop}}
for (IT I = begin; I >= end; ++I) {
++I;
}
#pragma omp target
#pragma omp teams distribute simd
for (IT I = begin; I < end; I += TC<int, ST>::step()) {
++I;
}
}
void test_with_template() {
GoodIter begin, end;
TC<GoodIter, 100> t1;
TC<GoodIter, -100> t2;
t1.dotest_lt(begin, end);
t2.dotest_lt(begin, end); // expected-note {{in instantiation of member function 'TC<GoodIter, -100>::dotest_lt' requested here}}
dotest_gt(begin, end); // expected-note {{in instantiation of function template specialization 'dotest_gt<GoodIter, 0>' requested here}}
dotest_gt<unsigned, 10>(0, 100); // expected-note {{in instantiation of function template specialization 'dotest_gt<unsigned int, 10>' requested here}}
}
void test_loop_break() {
const int N = 100;
float a[N], b[N], c[N];
#pragma omp target
#pragma omp teams distribute simd
for (int i = 0; i < 10; i++) {
c[i] = a[i] + b[i];
for (int j = 0; j < 10; ++j) {
if (a[i] > b[j])
break; // OK in nested loop
}
switch (i) {
case 1:
b[i]++;
break;
default:
break;
}
if (c[i] > 10)
break; // expected-error {{'break' statement cannot be used in OpenMP for loop}}
if (c[i] > 11)
break; // expected-error {{'break' statement cannot be used in OpenMP for loop}}
}
#pragma omp target
#pragma omp teams distribute simd
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 10; j++) {
c[i] = a[i] + b[i];
if (c[i] > 10) {
if (c[i] < 20) {
break; // OK
}
}
}
}
}
void test_loop_eh() {
const int N = 100;
float a[N], b[N], c[N];
#pragma omp target
#pragma omp teams distribute simd
for (int i = 0; i < 10; i++) {
c[i] = a[i] + b[i];
try { // expected-error {{'try' statement cannot be used in OpenMP simd region}}
for (int j = 0; j < 10; ++j) {
if (a[i] > b[j])
throw a[i]; // expected-error {{throw' statement cannot be used in OpenMP simd region}}
}
throw a[i]; // expected-error {{throw' statement cannot be used in OpenMP simd region}}
} catch (float f) {
if (f > 0.1)
throw a[i]; // expected-error {{throw' statement cannot be used in OpenMP simd region}}
return; // expected-error {{cannot return from OpenMP region}}
}
switch (i) {
case 1:
b[i]++;
break;
default:
break;
}
for (int j = 0; j < 10; j++) {
if (c[i] > 10)
throw c[i]; // expected-error {{throw' statement cannot be used in OpenMP simd region}}
}
}
if (c[9] > 10)
throw c[9]; // OK
#pragma omp target
#pragma omp teams distribute simd
for (int i = 0; i < 10; ++i) {
struct S {
void g() { throw 0; }
};
}
}
void test_loop_firstprivate_lastprivate() {
S s(4);
// expected-error@+2 {{lastprivate variable cannot be firstprivate}} expected-note@+2 {{defined as lastprivate}}
#pragma omp target
#pragma omp teams distribute simd lastprivate(s) firstprivate(s) // expected-error {{calling a private constructor of class 'S'}} expected-warning {{Non-trivial type 'S' is mapped, only trivial types are guaranteed to be mapped correctly}}
for (int i = 0; i < 16; ++i)
;
}
void test_ordered() {
#pragma omp target
#pragma omp teams distribute simd ordered // expected-error {{unexpected OpenMP clause 'ordered' in directive '#pragma omp teams distribute simd'}}
for (int i = 0; i < 16; ++i)
;
}
void test_nowait() {
#pragma omp target
// expected-error@+1 2 {{unexpected OpenMP clause 'nowait' in directive '#pragma omp teams distribute simd'}}
#pragma omp teams distribute simd nowait nowait // expected-error {{directive '#pragma omp teams distribute simd' cannot contain more than one 'nowait' clause}}
for (int i = 0; i < 16; ++i)
;
}
| {
"pile_set_name": "Github"
} |
/**
* Copyright 2016 Google Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
@import '_elements';
$border-radius: 3px;
$schedule-bar-radius: 10px;
$color-white: #fff;
$color-medium-grey: rgba(0, 0, 0, .7);
$color-light-grey: rgba(0, 0, 0, .54);
$content-padding: 70px;
$content-padding-mobile: 16px;
:host([inline]) #busSchedule {
// Overrides for paper-dialog
position: absolute !important;
top: 0 !important;
left: 0 !important;
right: 0 !important;
padding: 0 !important;
margin: 0 !important;
height: 100% !important;
width: 100% !important;
max-height: 100% !important;
max-width: 100% !important;
z-index: 1 !important;
box-shadow: none !important;
}
#busSchedule {
border-radius: $border-radius;
font-size: 16px;
height: 90%;
max-width: $tablet-breakpoint-min;
width: 80%;
}
@media (max-width: $phone-breakpoint-max) {
#busSchedule {
height: 100%;
left: 0 !important;
margin: 0;
max-width: 100%;
top: 0 !important;
width: 100%;
position: fixed !important;
}
}
.bus-schedule-header {
margin: 0;
padding: 0;
z-index: 1; // Keeps dropdown menu in front of schedule content.
}
.bus-schedule-banner {
border-radius: $border-radius $border-radius 0 0;
margin: 0;
padding: 24px 24px 0 24px;
@media (max-width: $phone-breakpoint-max) {
padding: 16px 16px 0 16px;
}
}
.bus-schedule-nav {
margin: 0 33px;
&.-disabled {
opacity: 0.54;
pointer-events: none;
}
}
.schedule-scrollable {
margin: 0;
padding: 0;
}
.bus-schedule-content {
border-radius: 0 0 $border-radius $border-radius;
padding: 24px $content-padding 72px $content-padding;
@media (max-width: $phone-breakpoint-max) {
padding: 20px $content-padding-mobile 72px $content-padding-mobile;
}
}
.-error {
color: $color-text-error;
}
.bus-schedule-close {
margin: -8px 0 0 -8px;
}
.route-fields {
padding: 0 12px;
}
.route-field {
border-radius: $border-radius;
margin: 0 0 12px 0;
padding: 2px 8px 2px 16px;
}
.route-label {
font-size: 14px;
opacity: 0.54;
padding-right: 4px;
&.-disabled {
display: none;
}
}
.schedule-swap-button {
margin-top: 10px;
}
.bus-schedule-table {
position: relative;
width: 100%;
.shuttle-start,
.shuttle-end {
color: $color-medium-grey;
display: block;
position: relative;
.shuttle-bar {
display: block;
height: 20px;
position: absolute;
top: -26px;
width: 100%;
}
&:after {
border-radius: 50%;
content: '';
display: block;
height: 12px;
position: absolute;
top: -22px;
width: 12px;
}
}
.shuttle-start {
.shuttle-bar {
border-radius: $schedule-bar-radius 0 0 $schedule-bar-radius;
}
&:after {
background: $color-white;
left: 4px;
z-index: 1;
}
}
.shuttle-end {
text-align: right;
.shuttle-bar {
border-radius: 0 $schedule-bar-radius $schedule-bar-radius 0;
}
&:after {
background: $color-light-grey;
right: 4px;
}
}
.shuttle-duration {
color: $color-light-grey;
display: block;
font-size: 12px;
font-weight: 500;
left: 0;
line-height: 20px;
margin: -26px 0 0 0;
position: absolute;
text-align: center;
width: 100%;
}
.bg-dark .shuttle-duration {
color: $color-white;
}
.schedule-headers {
color: $color-light-grey;
font-size: 14px;
font-weight: 500;
margin-bottom: 22px;
}
.shuttle-start-header {
text-align: left;
}
.shuttle-end-header {
flex: auto;
text-align: right;
}
.shuttle-duration-header {
width: 0;
}
ol {
margin: 0;
padding: 0;
}
li {
color: #000;
&:before {
background: #eceff1;
border-radius: $schedule-bar-radius;
content: '';
height: 20px;
position: absolute;
width: 100%;
}
}
.shuttle-cell {
margin-bottom: 18px;
padding: 26px 0 0 0;
&.shuttle-start-cell {
flex: 0 0 1px;
}
&.shuttle-end-cell {
flex: auto;
color: #333;
}
&.shuttle-duration-cell {
width: 0;
}
}
}
.bus-schedule-loop-container {
margin: 24px 0 18px -28px;
padding: 0 0 2em 0;
position: relative;
@media (max-width: $phone-breakpoint-max) {
margin-left: -6px;
}
}
.bus-schedule-loop-list-container {
position: relative;
ol {
list-style: none;
margin: 0;
padding: 0 0 0 80px;
position: relative;
}
li {
font-weight: 500;
margin: 0 0 42px 0;
position: relative;
&:last-of-type {
margin-bottom: 18px;
}
&:before {
background: $color-white;
border-radius: 50%;
content: '';
display: block;
height: 12px;
left: -32px;
margin: -6px 0 0 0;
position: absolute;
top: 50%;
width: 12px;
}
}
}
.loop-bar {
border-radius: 10px;
bottom: 3px;
display: block;
left: 44px;
position: absolute;
top: 3px;
width: 20px;
}
.loop-pickup {
margin-bottom: 12px;
}
.loop-depart {
bottom: 0;
left: 0;
position: absolute;
}
.loop-time {
color: $color-medium-grey;
display: block;
float: left;
margin: 0 16px 0 0;
text-align: right;
width: 64px;
}
.loop-type {
color: $color-light-grey;
font-size: 13px;
}
.-bordered {
border-bottom: 1px solid $color-bluegrey-100;
margin: 0 (-$content-padding) 24px (-$content-padding);
padding: 0 $content-padding 18px $content-padding;
@media (max-width: $phone-breakpoint-max) {
margin: 0 (-$content-padding-mobile) 24px (-$content-padding-mobile);
padding: 0 $content-padding-mobile 18px $content-padding-mobile;
}
}
| {
"pile_set_name": "Github"
} |
{ stdenv
, lib
, fetchFromGitHub
, python3
, wrapQtAppsHook
}:
python3.pkgs.buildPythonApplication rec {
pname = "maestral-qt";
version = "1.1.0";
disabled = python3.pkgs.pythonOlder "3.6";
src = fetchFromGitHub {
owner = "SamSchott";
repo = "maestral-qt";
rev = "v${version}";
sha256 = "0clzzwwbrynfbvawhaaa4mp2qi8smng31mmz0is166z6g67bwdl6";
};
propagatedBuildInputs = with python3.pkgs; [
bugsnag
click
markdown2
maestral
pyqt5
];
nativeBuildInputs = [ wrapQtAppsHook ];
makeWrapperArgs = [
# Firstly, add all necessary QT variables
"\${qtWrapperArgs[@]}"
# Add the installed directories to the python path so the daemon can find them
"--prefix" "PYTHONPATH" ":" "${stdenv.lib.concatStringsSep ":" (map (p: p + "/lib/${python3.libPrefix}/site-packages") (python3.pkgs.requiredPythonModules python3.pkgs.maestral.propagatedBuildInputs))}"
"--prefix" "PYTHONPATH" ":" "${python3.pkgs.maestral}/lib/${python3.libPrefix}/site-packages"
];
# no tests
doCheck = false;
meta = with lib; {
description = "GUI front-end for maestral (an open-source Dropbox client) for Linux";
license = licenses.mit;
maintainers = with maintainers; [ peterhoeg ];
platforms = platforms.linux;
inherit (src.meta) homepage;
};
}
| {
"pile_set_name": "Github"
} |
/*
This file is for the Gao-Mateer FFT
sse http://www.math.clemson.edu/~sgao/papers/GM10.pdf
*/
#include "fft.h"
#include "vec.h"
/* input: in, polynomial in bitsliced form */
/* output: in, result of applying the radix conversions on in */
static void radix_conversions(uint64_t *in) {
int i, j, k;
const uint64_t mask[5][2] = {
{0x8888888888888888, 0x4444444444444444},
{0xC0C0C0C0C0C0C0C0, 0x3030303030303030},
{0xF000F000F000F000, 0x0F000F000F000F00},
{0xFF000000FF000000, 0x00FF000000FF0000},
{0xFFFF000000000000, 0x0000FFFF00000000}
};
const uint64_t s[5][GFBITS] = {
#include "scalars.inc"
};
//
for (j = 0; j <= 4; j++) {
for (i = 0; i < GFBITS; i++) {
for (k = 4; k >= j; k--) {
in[i] ^= (in[i] & mask[k][0]) >> (1 << k);
in[i] ^= (in[i] & mask[k][1]) >> (1 << k);
}
}
PQCLEAN_MCELIECE348864_VEC_vec_mul(in, in, s[j]); // scaling
}
}
/* input: in, result of applying the radix conversions to the input polynomial */
/* output: out, evaluation results (by applying the FFT butterflies) */
static void butterflies(uint64_t out[][ GFBITS ], const uint64_t *in) {
int i, j, k, s, b;
uint64_t tmp[ GFBITS ];
uint64_t consts[ 63 ][ GFBITS ] = {
#include "consts.inc"
};
const vec powers[ 64 ][ GFBITS ] = {
#include "powers.inc"
};
uint64_t consts_ptr = 0;
const unsigned char reversal[64] = {
0, 32, 16, 48, 8, 40, 24, 56,
4, 36, 20, 52, 12, 44, 28, 60,
2, 34, 18, 50, 10, 42, 26, 58,
6, 38, 22, 54, 14, 46, 30, 62,
1, 33, 17, 49, 9, 41, 25, 57,
5, 37, 21, 53, 13, 45, 29, 61,
3, 35, 19, 51, 11, 43, 27, 59,
7, 39, 23, 55, 15, 47, 31, 63
};
// boradcast
for (j = 0; j < 64; j++) {
for (i = 0; i < GFBITS; i++) {
out[j][i] = (in[i] >> reversal[j]) & 1;
out[j][i] = -out[j][i];
}
}
// butterflies
for (i = 0; i <= 5; i++) {
s = 1 << i;
for (j = 0; j < 64; j += 2 * s) {
for (k = j; k < j + s; k++) {
PQCLEAN_MCELIECE348864_VEC_vec_mul(tmp, out[k + s], consts[ consts_ptr + (k - j) ]);
for (b = 0; b < GFBITS; b++) {
out[k][b] ^= tmp[b];
}
for (b = 0; b < GFBITS; b++) {
out[k + s][b] ^= out[k][b];
}
}
}
consts_ptr += ((uint64_t)1 << i);
}
//
// adding the part contributed by x^64
for (i = 0; i < 64; i++) {
for (b = 0; b < GFBITS; b++) {
out[i][b] ^= powers[i][b];
}
}
}
void PQCLEAN_MCELIECE348864_VEC_fft(vec out[][ GFBITS ], vec *in) {
radix_conversions(in);
butterflies(out, in);
}
| {
"pile_set_name": "Github"
} |
#
# Copyright ยฉ 2012 - 2020 Michal ฤihaล <[email protected]>
#
# This file is part of Weblate <https://weblate.org/>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
#
"""Tests for XLIFF rich string."""
from django.test import TestCase
from translate.storage.placeables.strelem import StringElem
from translate.storage.xliff import xlifffile
from weblate.trans.tests.utils import get_test_file
from weblate.trans.util import rich_to_xliff_string, xliff_string_to_rich
TEST_X = get_test_file("placeholder-x.xliff")
TEST_MRK = get_test_file("placeholder-mrk.xliff")
class XliffPlaceholdersTest(TestCase):
def test_bidirectional_xliff_string(self):
cases = [
'foo <x id="INTERPOLATION" equiv-text="{{ angular }}"/> bar',
"",
"hello world",
"hello <p>world</p>",
]
for string in cases:
rich = xliff_string_to_rich(string)
self.assertTrue(isinstance(rich, list))
self.assertTrue(isinstance(rich[0], StringElem))
final_string = rich_to_xliff_string(rich)
self.assertEqual(string, final_string)
def test_xliff_roundtrip(self):
with open(TEST_X, "rb") as handle:
source = handle.read()
store = xlifffile.parsestring(source)
string = rich_to_xliff_string(store.units[0].rich_source)
self.assertEqual(
'T: <x id="INTERPOLATION" equiv-text="{{ angular }}"/>', string
)
store.units[0].rich_source = xliff_string_to_rich(string)
self.assertEqual(source, bytes(store))
def test_xliff_roundtrip_unknown(self):
with open(TEST_MRK, "rb") as handle:
source = handle.read()
store = xlifffile.parsestring(source)
string = rich_to_xliff_string(store.units[0].rich_source)
self.assertEqual('T: <mrk mtype="protected">%s</mrk>', string)
store.units[0].rich_source = xliff_string_to_rich(string)
self.assertEqual(source, bytes(store))
| {
"pile_set_name": "Github"
} |
# Generated by h2py from /usr/include/netinet/in.h
# Included from netinet/in_f.h
def IN_CLASSA(i): return (((int)(i) & 0x80000000) == 0)
IN_CLASSA_NET = 0xff000000
IN_CLASSA_NSHIFT = 24
IN_CLASSA_HOST = 0x00ffffff
IN_CLASSA_MAX = 128
def IN_CLASSB(i): return (((int)(i) & 0xc0000000) == 0x80000000)
IN_CLASSB_NET = 0xffff0000
IN_CLASSB_NSHIFT = 16
IN_CLASSB_HOST = 0x0000ffff
IN_CLASSB_MAX = 65536
def IN_CLASSC(i): return (((int)(i) & 0xe0000000) == 0xc0000000)
IN_CLASSC_NET = 0xffffff00
IN_CLASSC_NSHIFT = 8
IN_CLASSC_HOST = 0x000000ff
def IN_CLASSD(i): return (((int)(i) & 0xf0000000) == 0xe0000000)
IN_CLASSD_NET = 0xf0000000
IN_CLASSD_NSHIFT = 28
IN_CLASSD_HOST = 0x0fffffff
def IN_MULTICAST(i): return IN_CLASSD(i)
def IN_EXPERIMENTAL(i): return (((int)(i) & 0xe0000000) == 0xe0000000)
def IN_BADCLASS(i): return (((int)(i) & 0xf0000000) == 0xf0000000)
INADDR_ANY = 0x00000000
INADDR_LOOPBACK = 0x7f000001
INADDR_BROADCAST = 0xffffffff
INADDR_NONE = 0xffffffff
IN_LOOPBACKNET = 127
INADDR_UNSPEC_GROUP = 0xe0000000
INADDR_ALLHOSTS_GROUP = 0xe0000001
INADDR_ALLRTRS_GROUP = 0xe0000002
INADDR_MAX_LOCAL_GROUP = 0xe00000ff
# Included from netinet/in6.h
# Included from sys/types.h
def quad_low(x): return x.val[0]
ADT_EMASKSIZE = 8
SHRT_MIN = -32768
SHRT_MAX = 32767
INT_MIN = (-2147483647-1)
INT_MAX = 2147483647
LONG_MIN = (-2147483647-1)
LONG_MAX = 2147483647
OFF32_MAX = LONG_MAX
ISTAT_ASSERTED = 0
ISTAT_ASSUMED = 1
ISTAT_NONE = 2
OFF_MAX = OFF32_MAX
CLOCK_MAX = LONG_MAX
P_MYID = (-1)
P_MYHOSTID = (-1)
# Included from sys/select.h
FD_SETSIZE = 4096
NBBY = 8
NULL = 0
# Included from sys/bitypes.h
# Included from netinet/in6_f.h
def IN6_IS_ADDR_UNSPECIFIED(a): return IN6_ADDR_EQUAL_L(a, 0, 0, 0, 0)
def IN6_SET_ADDR_UNSPECIFIED(a): return IN6_ADDR_COPY_L(a, 0, 0, 0, 0)
def IN6_IS_ADDR_ANY(a): return IN6_ADDR_EQUAL_L(a, 0, 0, 0, 0)
def IN6_SET_ADDR_ANY(a): return IN6_ADDR_COPY_L(a, 0, 0, 0, 0)
def IN6_IS_ADDR_LOOPBACK(a): return IN6_ADDR_EQUAL_L(a, 0, 0, 0, 0x01000000)
def IN6_SET_ADDR_LOOPBACK(a): return IN6_ADDR_COPY_L(a, 0, 0, 0, 0x01000000)
IN6_MC_FLAG_PERMANENT = 0x0
IN6_MC_FLAG_TRANSIENT = 0x1
IN6_MC_SCOPE_NODELOCAL = 0x1
IN6_MC_SCOPE_LINKLOCAL = 0x2
IN6_MC_SCOPE_SITELOCAL = 0x5
IN6_MC_SCOPE_ORGLOCAL = 0x8
IN6_MC_SCOPE_GLOBAL = 0xE
def IN6_IS_ADDR_MC_NODELOCAL(a): return \
def IN6_IS_ADDR_MC_LINKLOCAL(a): return \
def IN6_IS_ADDR_MC_SITELOCAL(a): return \
def IN6_IS_ADDR_MC_ORGLOCAL(a): return \
def IN6_IS_ADDR_MC_GLOBAL(a): return \
# Included from sys/convsa.h
__NETLIB_UW211_SVR4 = 1
__NETLIB_UW211_XPG4 = 2
__NETLIB_GEMINI_SVR4 = 3
__NETLIB_GEMINI_XPG4 = 4
__NETLIB_FP1_SVR4 = 5
__NETLIB_FP1_XPG4 = 6
__NETLIB_BASE_VERSION__ = __NETLIB_UW211_SVR4
__NETLIB_VERSION__ = __NETLIB_FP1_SVR4
__NETLIB_VERSION__ = __NETLIB_FP1_XPG4
__NETLIB_VERSION__ = __NETLIB_GEMINI_SVR4
__NETLIB_VERSION__ = __NETLIB_GEMINI_XPG4
__NETLIB_VERSION__ = __NETLIB_UW211_SVR4
__NETLIB_VERSION__ = __NETLIB_UW211_XPG4
__NETLIB_VERSION__ = __NETLIB_FP1_XPG4
# Included from sys/byteorder.h
LITTLE_ENDIAN = 1234
BIG_ENDIAN = 4321
PDP_ENDIAN = 3412
# Included from sys/byteorder_f.h
BYTE_ORDER = LITTLE_ENDIAN
def htonl(hl): return __htonl(hl)
def ntohl(nl): return __ntohl(nl)
def htons(hs): return __htons(hs)
def ntohs(ns): return __ntohs(ns)
def ntohl(x): return (x)
def ntohs(x): return (x)
def htonl(x): return (x)
def htons(x): return (x)
def __NETLIB_VERSION_IS_XPG4(version): return (((version) % 2) == 0)
def __NETLIB_VERSION_HAS_SALEN(version): return ((version) >= __NETLIB_GEMINI_SVR4)
def __NETLIB_VERSION_IS_IKS(version): return ((version) >= __NETLIB_FP1_SVR4)
def SA_FAMILY_GET(sa): return \
INET6_ADDRSTRLEN = 46
IPV6_UNICAST_HOPS = 3
IPV6_ADDRFORM = 24
IPV6_MULTICAST_HOPS = 25
IPV6_MULTICAST_IF = 26
IPV6_MULTICAST_LOOP = 27
IPV6_ADD_MEMBERSHIP = 28
IPV6_DROP_MEMBERSHIP = 29
# Included from sys/insrem.h
def LIST_INIT(head): return \
def LIST_INIT(head): return \
def remque(a): return REMQUE(a)
# Included from sys/socket.h
# Included from sys/uio.h
SHUT_RD = 0
SHUT_WR = 1
SHUT_RDWR = 2
# Included from sys/netconfig.h
# Included from sys/cdefs.h
def __P(protos): return protos
def __STRING(x): return #x
def __P(protos): return ()
def __STRING(x): return "x"
NETCONFIG = "/etc/netconfig"
NETPATH = "NETPATH"
NC_TPI_CLTS = 1
NC_TPI_COTS = 2
NC_TPI_COTS_ORD = 3
NC_TPI_RAW = 4
NC_NOFLAG = 00
NC_VISIBLE = 0o1
NC_BROADCAST = 0o2
NC_NOPROTOFMLY = "-"
NC_LOOPBACK = "loopback"
NC_INET = "inet"
NC_INET6 = "inet6"
NC_IMPLINK = "implink"
NC_PUP = "pup"
NC_CHAOS = "chaos"
NC_NS = "ns"
NC_NBS = "nbs"
NC_ECMA = "ecma"
NC_DATAKIT = "datakit"
NC_CCITT = "ccitt"
NC_SNA = "sna"
NC_DECNET = "decnet"
NC_DLI = "dli"
NC_LAT = "lat"
NC_HYLINK = "hylink"
NC_APPLETALK = "appletalk"
NC_NIT = "nit"
NC_IEEE802 = "ieee802"
NC_OSI = "osi"
NC_X25 = "x25"
NC_OSINET = "osinet"
NC_GOSIP = "gosip"
NC_NETWARE = "netware"
NC_NOPROTO = "-"
NC_TCP = "tcp"
NC_UDP = "udp"
NC_ICMP = "icmp"
NC_IPX = "ipx"
NC_SPX = "spx"
NC_TPI_CLTS = 1
NC_TPI_COTS = 2
NC_TPI_COTS_ORD = 3
NC_TPI_RAW = 4
SOCK_STREAM = 2
SOCK_DGRAM = 1
SOCK_RAW = 4
SOCK_RDM = 5
SOCK_SEQPACKET = 6
SO_DEBUG = 0x0001
SO_ACCEPTCONN = 0x0002
SO_REUSEADDR = 0x0004
SO_KEEPALIVE = 0x0008
SO_DONTROUTE = 0x0010
SO_BROADCAST = 0x0020
SO_USELOOPBACK = 0x0040
SO_LINGER = 0x0080
SO_OOBINLINE = 0x0100
SO_ORDREL = 0x0200
SO_IMASOCKET = 0x0400
SO_MGMT = 0x0800
SO_REUSEPORT = 0x1000
SO_LISTENING = 0x2000
SO_RDWR = 0x4000
SO_SEMA = 0x8000
SO_DONTLINGER = (~SO_LINGER)
SO_SNDBUF = 0x1001
SO_RCVBUF = 0x1002
SO_SNDLOWAT = 0x1003
SO_RCVLOWAT = 0x1004
SO_SNDTIMEO = 0x1005
SO_RCVTIMEO = 0x1006
SO_ERROR = 0x1007
SO_TYPE = 0x1008
SO_PROTOTYPE = 0x1009
SO_ALLRAW = 0x100a
SOL_SOCKET = 0xffff
AF_UNSPEC = 0
AF_UNIX = 1
AF_LOCAL = AF_UNIX
AF_INET = 2
AF_IMPLINK = 3
AF_PUP = 4
AF_CHAOS = 5
AF_NS = 6
AF_NBS = 7
AF_ECMA = 8
AF_DATAKIT = 9
AF_CCITT = 10
AF_SNA = 11
AF_DECnet = 12
AF_DLI = 13
AF_LAT = 14
AF_HYLINK = 15
AF_APPLETALK = 16
AF_NIT = 17
AF_802 = 18
AF_OSI = 19
AF_ISO = AF_OSI
AF_X25 = 20
AF_OSINET = 21
AF_GOSIP = 22
AF_YNET = 23
AF_ROUTE = 24
AF_LINK = 25
pseudo_AF_XTP = 26
AF_INET6 = 27
AF_MAX = 27
AF_INET_BSWAP = 0x0200
PF_UNSPEC = AF_UNSPEC
PF_UNIX = AF_UNIX
PF_LOCAL = AF_LOCAL
PF_INET = AF_INET
PF_IMPLINK = AF_IMPLINK
PF_PUP = AF_PUP
PF_CHAOS = AF_CHAOS
PF_NS = AF_NS
PF_NBS = AF_NBS
PF_ECMA = AF_ECMA
PF_DATAKIT = AF_DATAKIT
PF_CCITT = AF_CCITT
PF_SNA = AF_SNA
PF_DECnet = AF_DECnet
PF_DLI = AF_DLI
PF_LAT = AF_LAT
PF_HYLINK = AF_HYLINK
PF_APPLETALK = AF_APPLETALK
PF_NIT = AF_NIT
PF_802 = AF_802
PF_OSI = AF_OSI
PF_ISO = PF_OSI
PF_X25 = AF_X25
PF_OSINET = AF_OSINET
PF_GOSIP = AF_GOSIP
PF_YNET = AF_YNET
PF_ROUTE = AF_ROUTE
PF_LINK = AF_LINK
pseudo_PF_XTP = pseudo_AF_XTP
PF_INET6 = AF_INET6
PF_MAX = AF_MAX
SOMAXCONN = 5
SCM_RIGHTS = 1
MSG_OOB = 0x1
MSG_PEEK = 0x2
MSG_DONTROUTE = 0x4
MSG_CTRUNC = 0x8
MSG_TRUNC = 0x10
MSG_EOR = 0x30
MSG_WAITALL = 0x20
MSG_MAXIOVLEN = 16
def OPTLEN(x): return ((((x) + sizeof(int) - 1) / sizeof(int)) * sizeof(int))
GIARG = 0x1
CONTI = 0x2
GITAB = 0x4
SOCKETSYS = 88
SOCKETSYS = 83
SO_ACCEPT = 1
SO_BIND = 2
SO_CONNECT = 3
SO_GETPEERNAME = 4
SO_GETSOCKNAME = 5
SO_GETSOCKOPT = 6
SO_LISTEN = 7
SO_RECV = 8
SO_RECVFROM = 9
SO_SEND = 10
SO_SENDTO = 11
SO_SETSOCKOPT = 12
SO_SHUTDOWN = 13
SO_SOCKET = 14
SO_SOCKPOLL = 15
SO_GETIPDOMAIN = 16
SO_SETIPDOMAIN = 17
SO_ADJTIME = 18
# Included from sys/stream.h
# Included from sys/cred.h
# Included from sys/ksynch.h
# Included from sys/dl.h
SIGNBIT = 0x80000000
# Included from sys/ipl.h
# Included from sys/disp_p.h
# Included from sys/trap.h
DIVERR = 0
SGLSTP = 1
NMIFLT = 2
BPTFLT = 3
INTOFLT = 4
BOUNDFLT = 5
INVOPFLT = 6
NOEXTFLT = 7
DBLFLT = 8
EXTOVRFLT = 9
INVTSSFLT = 10
SEGNPFLT = 11
STKFLT = 12
GPFLT = 13
PGFLT = 14
EXTERRFLT = 16
ALIGNFLT = 17
MCEFLT = 18
USERFLT = 0x100
TRP_PREEMPT = 0x200
TRP_UNUSED = 0x201
PF_ERR_MASK = 0x01
PF_ERR_PAGE = 0
PF_ERR_PROT = 1
PF_ERR_WRITE = 2
PF_ERR_USER = 4
EVT_STRSCHED = 0x04
EVT_GLOBCALLOUT = 0x08
EVT_LCLCALLOUT = 0x10
EVT_SOFTINTMASK = (EVT_STRSCHED|EVT_GLOBCALLOUT|EVT_LCLCALLOUT)
PL0 = 0
PL1 = 1
PL2 = 2
PL3 = 3
PL4 = 4
PL5 = 5
PL6 = 6
PLHI = 8
PL7 = PLHI
PLBASE = PL0
PLTIMEOUT = PL1
PLDISK = PL5
PLSTR = PL6
PLTTY = PLSTR
PLMIN = PL0
PLMIN = PL1
MAX_INTR_LEVELS = 10
MAX_INTR_NESTING = 50
STRSCHED = EVT_STRSCHED
GLOBALSOFTINT = EVT_GLOBCALLOUT
LOCALSOFTINT = EVT_LCLCALLOUT
# Included from sys/ksynch_p.h
def GET_TIME(timep): return \
LK_THRESHOLD = 500000
# Included from sys/list.h
# Included from sys/listasm.h
def remque_null(e): return \
def LS_ISEMPTY(listp): return \
LK_BASIC = 0x1
LK_SLEEP = 0x2
LK_NOSTATS = 0x4
def CYCLES_SINCE(c): return CYCLES_BETWEEN((c), CYCLES())
LSB_NLKDS = 92
EVT_RUNRUN = 0x01
EVT_KPRUNRUN = 0x02
SP_UNLOCKED = 0
SP_LOCKED = 1
KS_LOCKTEST = 0x01
KS_MPSTATS = 0x02
KS_DEINITED = 0x04
KS_NVLTTRACE = 0x08
RWS_READ = (ord('r'))
RWS_WRITE = (ord('w'))
RWS_UNLOCKED = (ord('u'))
RWS_BUSY = (ord('b'))
def SLEEP_LOCKOWNED(lkp): return \
def SLEEP_DISOWN(lkp): return \
KS_NOPRMPT = 0x00000001
__KS_LOCKTEST = KS_LOCKTEST
__KS_LOCKTEST = 0
__KS_MPSTATS = KS_MPSTATS
__KS_MPSTATS = 0
__KS_NVLTTRACE = KS_NVLTTRACE
__KS_NVLTTRACE = 0
KSFLAGS = (__KS_LOCKTEST|__KS_MPSTATS|__KS_NVLTTRACE)
KSVUNIPROC = 1
KSVMPDEBUG = 2
KSVMPNODEBUG = 3
KSVFLAG = KSVUNIPROC
KSVFLAG = KSVMPDEBUG
KSVFLAG = KSVMPNODEBUG
# Included from sys/ksinline.h
_A_SP_LOCKED = 1
_A_SP_UNLOCKED = 0
_A_INVPL = -1
def _ATOMIC_INT_INCR(atomic_intp): return \
def _ATOMIC_INT_DECR(atomic_intp): return \
def ATOMIC_INT_READ(atomic_intp): return _ATOMIC_INT_READ(atomic_intp)
def ATOMIC_INT_INCR(atomic_intp): return _ATOMIC_INT_INCR(atomic_intp)
def ATOMIC_INT_DECR(atomic_intp): return _ATOMIC_INT_DECR(atomic_intp)
def FSPIN_INIT(lp): return
def FSPIN_LOCK(l): return DISABLE()
def FSPIN_TRYLOCK(l): return (DISABLE(), B_TRUE)
def FSPIN_UNLOCK(l): return ENABLE()
def LOCK_DEINIT(lp): return
def LOCK_DEALLOC(lp): return
def LOCK_OWNED(lp): return (B_TRUE)
def RW_DEINIT(lp): return
def RW_DEALLOC(lp): return
def RW_OWNED(lp): return (B_TRUE)
def IS_LOCKED(lockp): return B_FALSE
def LOCK_PLMIN(lockp): return \
def TRYLOCK_PLMIN(lockp): return LOCK_PLMIN(lockp)
def LOCK_SH_PLMIN(lockp): return LOCK_PLMIN(lockp)
def RW_RDLOCK_PLMIN(lockp): return LOCK_PLMIN(lockp)
def RW_WRLOCK_PLMIN(lockp): return LOCK_PLMIN(lockp)
def LOCK_DEINIT(l): return
def LOCK_PLMIN(lockp): return LOCK((lockp), PLMIN)
def TRYLOCK_PLMIN(lockp): return TRYLOCK((lockp), PLMIN)
def LOCK_SH_PLMIN(lockp): return LOCK_SH((lockp), PLMIN)
def RW_RDLOCK_PLMIN(lockp): return RW_RDLOCK((lockp), PLMIN)
def RW_WRLOCK_PLMIN(lockp): return RW_WRLOCK((lockp), PLMIN)
def FSPIN_IS_LOCKED(fsp): return B_FALSE
def SPIN_IS_LOCKED(lockp): return B_FALSE
def FSPIN_OWNED(l): return (B_TRUE)
CR_MLDREAL = 0x00000001
CR_RDUMP = 0x00000002
def crhold(credp): return crholdn((credp), 1)
def crfree(credp): return crfreen((credp), 1)
# Included from sys/strmdep.h
def str_aligned(X): return (((uint)(X) & (sizeof(int) - 1)) == 0)
# Included from sys/engine.h
# Included from sys/clock.h
# Included from sys/time.h
DST_NONE = 0
DST_USA = 1
DST_AUST = 2
DST_WET = 3
DST_MET = 4
DST_EET = 5
DST_CAN = 6
DST_GB = 7
DST_RUM = 8
DST_TUR = 9
DST_AUSTALT = 10
ITIMER_REAL = 0
ITIMER_VIRTUAL = 1
ITIMER_PROF = 2
FD_SETSIZE = 4096
FD_NBBY = 8
# Included from time.h
NULL = 0
CLOCKS_PER_SEC = 1000000
# Included from sys/clock_p.h
CGBITS = 4
IDBITS = 28
def toid_unpackcg(idval): return (((idval) >> IDBITS) & 0xf)
def toid_unpackid(idval): return ((idval) & 0xfffffff)
def toid_unpackcg(idval): return 0
def toid_unpackid(idval): return (idval)
NCALLOUT_HASH = 1024
CALLOUT_MAXVAL = 0x7fffffff
TO_PERIODIC = 0x80000000
TO_IMMEDIATE = 0x80000000
SEC = 1
MILLISEC = 1000
MICROSEC = 1000000
NANOSEC = 1000000000
SECHR = (60*60)
SECDAY = (24*SECHR)
SECYR = (365*SECDAY)
def TIME_OWNED_R(cgnum): return (B_TRUE)
LOOPSECONDS = 1800
LOOPMICROSECONDS = (LOOPSECONDS * MICROSEC)
def TICKS_SINCE(t): return TICKS_BETWEEN(t, TICKS())
MAXRQS = 2
E_OFFLINE = 0x01
E_BAD = 0x02
E_SHUTDOWN = 0x04
E_DRIVER = 0x08
E_DEFAULTKEEP = 0x100
E_DRIVERBOUND = 0x200
E_EXCLUSIVE = 0x400
E_CGLEADER = 0x800
E_NOWAY = (E_OFFLINE|E_BAD|E_SHUTDOWN)
E_BOUND = 0x01
E_GLOBAL = 0x00
E_UNAVAIL = -1
ENGINE_ONLINE = 1
def PROCESSOR_UNMAP(e): return ((e) - engine)
BOOTENG = 0
QMOVED = 0x0001
QWANTR = 0x0002
QWANTW = 0x0004
QFULL = 0x0008
QREADR = 0x0010
QUSE = 0x0020
QNOENB = 0x0040
QUP = 0x0080
QBACK = 0x0100
QINTER = 0x0200
QPROCSON = 0x0400
QTOENAB = 0x0800
QFREEZE = 0x1000
QBOUND = 0x2000
QDEFCNT = 0x4000
QENAB = 0x0001
QSVCBUSY = 0x0002
STRM_PUTCNT_TABLES = 31
def STRM_MYENG_PUTCNT(sdp): return STRM_PUTCNT(l.eng_num, sdp)
QB_FULL = 0x01
QB_WANTW = 0x02
QB_BACK = 0x04
NBAND = 256
DB_WASDUPED = 0x1
DB_2PIECE = 0x2
STRLEAKHASHSZ = 1021
MSGMARK = 0x01
MSGNOLOOP = 0x02
MSGDELIM = 0x04
MSGNOGET = 0x08
MSGLOG = 0x10
M_DATA = 0x00
M_PROTO = 0x01
M_BREAK = 0x08
M_PASSFP = 0x09
M_SIG = 0x0b
M_DELAY = 0x0c
M_CTL = 0x0d
M_IOCTL = 0x0e
M_SETOPTS = 0x10
M_RSE = 0x11
M_TRAIL = 0x12
M_IOCACK = 0x81
M_IOCNAK = 0x82
M_PCPROTO = 0x83
M_PCSIG = 0x84
M_READ = 0x85
M_FLUSH = 0x86
M_STOP = 0x87
M_START = 0x88
M_HANGUP = 0x89
M_ERROR = 0x8a
M_COPYIN = 0x8b
M_COPYOUT = 0x8c
M_IOCDATA = 0x8d
M_PCRSE = 0x8e
M_STOPI = 0x8f
M_STARTI = 0x90
M_PCCTL = 0x91
M_PCSETOPTS = 0x92
QNORM = 0x00
QPCTL = 0x80
STRCANON = 0x01
RECOPY = 0x02
SO_ALL = 0x003f
SO_READOPT = 0x0001
SO_WROFF = 0x0002
SO_MINPSZ = 0x0004
SO_MAXPSZ = 0x0008
SO_HIWAT = 0x0010
SO_LOWAT = 0x0020
SO_MREADON = 0x0040
SO_MREADOFF = 0x0080
SO_NDELON = 0x0100
SO_NDELOFF = 0x0200
SO_ISTTY = 0x0400
SO_ISNTTY = 0x0800
SO_TOSTOP = 0x1000
SO_TONSTOP = 0x2000
SO_BAND = 0x4000
SO_DELIM = 0x8000
SO_NODELIM = 0x010000
SO_STRHOLD = 0x020000
SO_LOOP = 0x040000
DRVOPEN = 0x0
MODOPEN = 0x1
CLONEOPEN = 0x2
OPENFAIL = -1
BPRI_LO = 1
BPRI_MED = 2
BPRI_HI = 3
INFPSZ = -1
FLUSHALL = 1
FLUSHDATA = 0
STRHIGH = 5120
STRLOW = 1024
MAXIOCBSZ = 1024
def straln(a): return (caddr_t)((int)(a) & ~(sizeof(int)-1))
IPM_ID = 200
ICMPM_ID = 201
TCPM_ID = 202
UDPM_ID = 203
ARPM_ID = 204
APPM_ID = 205
RIPM_ID = 206
PPPM_ID = 207
AHDLCM_ID = 208
MHDLCRIPM_ID = 209
HDLCM_ID = 210
PPCID_ID = 211
IGMPM_ID = 212
IPIPM_ID = 213
IPPROTO_IP = 0
IPPROTO_HOPOPTS = 0
IPPROTO_ICMP = 1
IPPROTO_IGMP = 2
IPPROTO_GGP = 3
IPPROTO_IPIP = 4
IPPROTO_TCP = 6
IPPROTO_EGP = 8
IPPROTO_PUP = 12
IPPROTO_UDP = 17
IPPROTO_IDP = 22
IPPROTO_TP = 29
IPPROTO_IPV6 = 41
IPPROTO_ROUTING = 43
IPPROTO_FRAGMENT = 44
IPPROTO_ESP = 50
IPPROTO_AH = 51
IPPROTO_ICMPV6 = 58
IPPROTO_NONE = 59
IPPROTO_DSTOPTS = 60
IPPROTO_HELLO = 63
IPPROTO_ND = 77
IPPROTO_EON = 80
IPPROTO_RAW = 255
IPPROTO_MAX = 256
IPPORT_ECHO = 7
IPPORT_DISCARD = 9
IPPORT_SYSTAT = 11
IPPORT_DAYTIME = 13
IPPORT_NETSTAT = 15
IPPORT_FTP = 21
IPPORT_TELNET = 23
IPPORT_SMTP = 25
IPPORT_TIMESERVER = 37
IPPORT_NAMESERVER = 42
IPPORT_WHOIS = 43
IPPORT_MTP = 57
IPPORT_TFTP = 69
IPPORT_RJE = 77
IPPORT_FINGER = 79
IPPORT_TTYLINK = 87
IPPORT_SUPDUP = 95
IPPORT_EXECSERVER = 512
IPPORT_LOGINSERVER = 513
IPPORT_CMDSERVER = 514
IPPORT_EFSSERVER = 520
IPPORT_BIFFUDP = 512
IPPORT_WHOSERVER = 513
IPPORT_ROUTESERVER = 520
IPPORT_RESERVED = 1024
IPPORT_USERRESERVED = 65535
IPPORT_RESERVED_LOW = 512
IPPORT_RESERVED_HIGH = 1023
IPPORT_USERRESERVED_LOW = 32768
IPPORT_USERRESERVED_HIGH = 65535
INET_ADDRSTRLEN = 16
IP_OPTIONS = 1
IP_TOS = 2
IP_TTL = 3
IP_HDRINCL = 4
IP_RECVOPTS = 5
IP_RECVRETOPTS = 6
IP_RECVDSTADDR = 7
IP_RETOPTS = 8
IP_MULTICAST_IF = 9
IP_MULTICAST_LOOP = 10
IP_ADD_MEMBERSHIP = 11
IP_DROP_MEMBERSHIP = 12
IP_BROADCAST_IF = 14
IP_RECVIFINDEX = 15
IP_MULTICAST_TTL = 16
MRT_INIT = 17
MRT_DONE = 18
MRT_ADD_VIF = 19
MRT_DEL_VIF = 20
MRT_ADD_MFC = 21
MRT_DEL_MFC = 22
MRT_VERSION = 23
IP_DEFAULT_MULTICAST_TTL = 1
IP_DEFAULT_MULTICAST_LOOP = 1
IP_MAX_MEMBERSHIPS = 20
INADDR_UNSPEC_GROUP = 0xe0000000
INADDR_ALLHOSTS_GROUP = 0xe0000001
INADDR_ALLRTRS_GROUP = 0xe0000002
INADDR_MAX_LOCAL_GROUP = 0xe00000ff
# Included from netinet/in_mp.h
# Included from netinet/in_mp_ddi.h
# Included from sys/inline.h
IP_HIER_BASE = (20)
def ASSERT_LOCK(x): return
def ASSERT_WRLOCK(x): return
def ASSERT_UNLOCK(x): return
def CANPUT(q): return canput((q))
def CANPUTNEXT(q): return canputnext((q))
INET_DEBUG = 1
| {
"pile_set_name": "Github"
} |
๏ปฟ// *********************************************************************
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License
// *********************************************************************
using System;
using Microsoft.StreamProcessing.Internal.Collections;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace SimpleTesting
{
[TestClass]
public class RemovableEndPointHeapTest : TestWithConfigSettingsAndMemoryLeakDetection
{
[TestMethod, TestCategory("Gated")]
public void TestRemovableEndPointHeap()
{
SimpleRemovableEndPointHeapTest();
RandomRemovableEndPointHeapTest(1000, 10, 100);
RandomRemovableEndPointHeapTest(100, 10, 1000000);
BugReproTest();
}
private static void BugReproTest()
{
var heap = new RemovableEndPointHeap();
int index1 = heap.Insert(1, 1);
int index2 = heap.Insert(2, 2);
heap.Remove(index1);
heap.Insert(3, 3);
heap.Remove(index2);
Assert.IsTrue(heap.TryGetNext(out long time, out int value));
Assert.AreEqual(3L, time);
Assert.AreEqual(3, value);
Assert.IsTrue(heap.IsEmpty);
}
private static void SimpleRemovableEndPointHeapTest()
{
var heap = new RemovableEndPointHeap();
int index1 = heap.Insert(5, 1000);
heap.Remove(index1);
Assert.IsTrue(heap.IsEmpty);
Assert.AreEqual(0, heap.Count);
Assert.IsFalse(heap.TryPeekNext(out _, out _));
Assert.IsFalse(heap.TryGetNext(out _, out _));
Assert.IsFalse(heap.TryGetNextExclusive(100, out _, out _));
Assert.IsFalse(heap.TryGetNextInclusive(100, out _, out _));
index1 = heap.Insert(6, 100);
int index2 = heap.Insert(7, 200);
heap.Remove(index2);
Assert.IsFalse(heap.IsEmpty);
Assert.AreEqual(1, heap.Count);
Assert.IsFalse(heap.TryGetNextExclusive(1, out _, out _));
Assert.IsFalse(heap.TryGetNextInclusive(1, out _, out _));
Assert.IsTrue(heap.TryPeekNext(out var time, out var value));
Assert.AreEqual(6, time);
Assert.AreEqual(100, value);
heap.Remove(index1);
Assert.IsTrue(heap.IsEmpty);
index1 = heap.Insert(8, 100);
index2 = heap.Insert(9, 200);
heap.Remove(index1);
Assert.IsFalse(heap.IsEmpty);
Assert.AreEqual(1, heap.Count);
Assert.IsFalse(heap.TryGetNextExclusive(1, out _, out _));
Assert.IsFalse(heap.TryGetNextInclusive(1, out _, out _));
Assert.IsTrue(heap.TryPeekNext(out time, out value));
Assert.AreEqual(9, time);
Assert.AreEqual(200, value);
heap.Remove(index2);
Assert.IsTrue(heap.IsEmpty);
heap.Insert(3, 1001);
heap.Insert(5, 1002);
heap.Insert(4, 1003);
Assert.IsFalse(heap.TryGetNextInclusive(2, out _, out _));
Assert.IsTrue(heap.TryGetNextInclusive(3, out time, out value));
Assert.AreEqual(3, time);
Assert.AreEqual(1001, value);
Assert.IsFalse(heap.TryGetNextExclusive(4, out _, out _));
Assert.IsTrue(heap.TryGetNextExclusive(5, out time, out value));
Assert.AreEqual(4, time);
Assert.AreEqual(1003, value);
Assert.IsTrue(heap.TryGetNextInclusive(100, out time, out value));
Assert.AreEqual(5, time);
Assert.AreEqual(1002, value);
Assert.IsTrue(heap.IsEmpty);
}
private static void RandomRemovableEndPointHeapTest(int size, int minValue, int maxValue)
{
var heap = new RemovableEndPointHeap();
var rand = new Random();
var input = new int[size];
var indexes = new int[size];
for (int j = 0; j < size; j++)
{
int value = rand.Next(minValue, maxValue);
indexes[j] = heap.Insert(value, value);
input[j] = value;
}
Assert.AreEqual(size, heap.Count);
for (int j = size / 2; j < size; j++)
{
heap.Remove(indexes[j]);
}
Assert.AreEqual(size / 2, heap.Count);
Array.Sort(input, 0, size / 2);
for (int j = 0; j < size / 2; j++)
{
Assert.IsTrue(heap.TryGetNext(out long time, out int value));
Assert.AreEqual(input[j], time);
Assert.AreEqual(input[j], value);
}
Assert.IsTrue(heap.IsEmpty);
}
}
}
| {
"pile_set_name": "Github"
} |
<!--
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.
-->
# "Cookbook" Examples
This directory holds simple "cookbook" examples, which show how to define
commonly-used data analysis patterns that you would likely incorporate into a
larger Apache Beam pipeline. They include:
<ul>
<li><a href="https://github.com/apache/beam/blob/master/examples/java/src/main/java/org/apache/beam/examples/cookbook/BigQueryTornadoes.java">BigQueryTornadoes</a>
— An example that reads the public samples of weather data from Google
BigQuery, counts the number of tornadoes that occur in each month, and
writes the results to BigQuery. Demonstrates reading/writing BigQuery,
counting a <code>PCollection</code>, and user-defined <code>PTransforms</code>.</li>
<li><a href="https://github.com/apache/beam/blob/master/examples/java/src/main/java/org/apache/beam/examples/cookbook/CombinePerKeyExamples.java">CombinePerKeyExamples</a>
— An example that reads the public "Shakespeare" data, and for
each word in the dataset that exceeds a given length, generates a string
containing the list of play names in which that word appears.
Demonstrates the <code>Combine.perKey</code>
transform, which lets you combine the values in a key-grouped
<code>PCollection</code>.
</li>
<li><a href="https://github.com/apache/beam/blob/master/examples/java/src/main/java/org/apache/beam/examples/cookbook/DistinctExample.java">DistinctExample</a>
— An example that uses Shakespeare's plays as plain text files, and
removes duplicate lines across all the files. Demonstrates the
<code>Distinct</code>, <code>TextIO.Read</code>,
and <code>TextIO.Write</code> transforms, and how to wire transforms together.
</li>
<li><a href="https://github.com/apache/beam/blob/master/examples/java/src/main/java/org/apache/beam/examples/cookbook/FilterExamples.java">FilterExamples</a>
— An example that shows different approaches to filtering, including
selection and projection. It also shows how to dynamically set parameters
by defining and using new pipeline options, and use how to use a value derived
by a pipeline. Demonstrates the <code>Mean</code> transform,
<code>Options</code> configuration, and using pipeline-derived data as a side
input.
</li>
<li><a href="https://github.com/apache/beam/blob/master/examples/java/src/main/java/org/apache/beam/examples/cookbook/JoinExamples.java">JoinExamples</a>
— An example that shows how to join two collections. It uses a
sample of the <a href="http://goo.gl/OB6oin">GDELT "world event"
data</a>, joining the event <code>action</code> country code against a table
that maps country codes to country names. Demonstrates the <code>Join</code>
operation, and using multiple input sources.
</li>
<li><a href="https://github.com/apache/beam/blob/master/examples/java/src/main/java/org/apache/beam/examples/cookbook/MaxPerKeyExamples.java">MaxPerKeyExamples</a>
— An example that reads the public samples of weather data from BigQuery,
and finds the maximum temperature (<code>mean_temp</code>) for each month.
Demonstrates the <code>Max</code> statistical combination transform, and how to
find the max-per-key group.
</li>
</ul>
See the [documentation](http://beam.apache.org/get-started/quickstart/) and the [Examples
README](../../../../../../../../README.md) for
information about how to run these examples.
| {
"pile_set_name": "Github"
} |
# [745. Prefix and Suffix Search](https://leetcode.com/problems/prefix-and-suffix-search/)
## ้ข็ฎ
Given manyย `words`,ย `words[i]`ย has weightย `i`.
Design a classย `WordFilter`ย that supports one function,ย `WordFilter.f(String prefix, String suffix)`. It will return the word with givenย `prefix`ย andย `suffix`ย with maximum weight. If no word exists, return -1.
**Examples:**
Input:
WordFilter(["apple"])
WordFilter.f("a", "e") // returns 0
WordFilter.f("b", "") // returns -1
**Note:**
1. `words`ย has length in rangeย `[1, 15000]`.
2. For each test case, up toย `words.length`ย queriesย `WordFilter.f`ย may be made.
3. `words[i]`ย has length in rangeย `[1, 10]`.
4. `prefix, suffix`ย have lengths in rangeย `[0, 10]`.
5. `words[i]`ย andย `prefix, suffix`ย queries consist of lowercase letters only.
## ้ข็ฎๅคงๆ
็ปๅฎๅคไธชย words๏ผwords[i]ย ็ๆ้ไธบย iย ใ่ฎพ่ฎกไธไธช็ฑปย WordFilterย ๅฎ็ฐๅฝๆฐWordFilter.f(String prefix, String suffix)ใ่ฟไธชๅฝๆฐๅฐ่ฟๅๅ
ทๆๅ็ผย prefixย ๅๅ็ผsuffixย ็่ฏ็ๆๅคงๆ้ใๅฆๆๆฒกๆ่ฟๆ ท็่ฏ๏ผ่ฟๅ -1ใ
## ่งฃ้ขๆ่ทฏ
- ่ฆๆฑๅฎ็ฐไธไธช `WordFilter` ๏ผๅฎๅ
ทๆๅญ็ฌฆไธฒๅน้
็ๅ่ฝ๏ผๅฏไปฅๅน้
ๅบๅ็ผๅๅ็ผ้ฝๆปก่ถณๆกไปถ็ๅญ็ฌฆไธฒไธๆ ๏ผๅฆๆๆพๅพๅฐ๏ผ่ฟๅไธๆ ๏ผๅฆๆๆพไธๅฐ๏ผๅ่ฟๅ -1 ใ
- ่ฟไธ้ขๆ 2 ็ง่งฃ้ขๆ่ทฏใ็ฌฌไธ็งๆฏๅ
ๆ่ฟไธช `WordFilter` ็ปๆ้้ข็ๅญ็ฌฆไธฒๅ
จ้จ้ขๅค็ไธ้๏ผๅฐๅฎ็ๅ็ผ๏ผๅ็ผ็ๆๆ็ปๅ้ฝๆไธพๅบๆฅๆพๅจ map ไธญ๏ผไนๅๅน้
็ๆถๅๅช้่ฆๆ็
ง่ชๅทฑๅฎไน็่งๅๆฅๆพ key ๅฐฑๅฏไปฅไบใๅๅงๅๆถ้ดๅคๆๅบฆ `O(N * L^2)`๏ผๆฅๆพๆถ้ดๅคๆๅบฆ `O(1)`๏ผ็ฉบ้ดๅคๆๅบฆ `O(N * L^2)`ใๅ
ถไธญ `N` ๆฏ่พๅ
ฅ็ๅญ็ฌฆไธฒๆฐ็ป็้ฟๅบฆ๏ผ`L` ๆฏ่พๅ
ฅๅญ็ฌฆไธฒๆฐ็ปไธญๅญ็ฌฆไธฒ็ๆๅคง้ฟๅบฆใ็ฌฌไบ็งๆ่ทฏๆฏ็ดๆฅ้ๅๅญ็ฌฆไธฒๆฏไธชไธๆ ๏ผไพๆฌก็จๅญ็ฌฆไธฒ็ๅ็ผๅน้
ๆนๆณๅๅ็ผๅน้
ๆนๆณ๏ผไพๆฌกๅน้
ใๅๅงๅๆถ้ดๅคๆๅบฆ `O(1)`๏ผๆฅๆพๆถ้ดๅคๆๅบฆ `O(N * L)`๏ผ็ฉบ้ดๅคๆๅบฆ `O(1)`ใๅ
ถไธญ `N` ๆฏ่พๅ
ฅ็ๅญ็ฌฆไธฒๆฐ็ป็้ฟๅบฆ๏ผ`L` ๆฏ่พๅ
ฅๅญ็ฌฆไธฒๆฐ็ปไธญๅญ็ฌฆไธฒ็ๆๅคง้ฟๅบฆใ
| {
"pile_set_name": "Github"
} |
<?php
/**
* Write an Exportable migration index file as a part of the build process.
*
* This script uses the LibreSignage build from dist/ so you must call
* this script late in the build process.
*/
// Setup DOCUMENT_ROOT to point to 'dist/public/'.
$_SERVER['DOCUMENT_ROOT'] = getcwd().'/dist/public';
require_once($_SERVER['DOCUMENT_ROOT'].'/../common/php/Config.php');
use libresignage\common\php\Config;
use libresignage\common\php\exportable\migration\MigrationIndex;
// Write the migration index.
echo "Generating Exportable migration index...\n";
$num = MigrationIndex::write(
Config::config('LIBRESIGNAGE_ROOT').'/common/php/exportable/migration/index.json',
Config::config('LIBRESIGNAGE_ROOT').'/common/php/exportable/migration/defs'
);
echo "Wrote an index with $num classes.\n";
| {
"pile_set_name": "Github"
} |
Importing a CSS file into another CSS file
Property names require American English
Use `SVG` for icons
Autohiding scrollbars for **IE**
Multiple borders with pseudo elements | {
"pile_set_name": "Github"
} |
/* FluidSynth - A Software Synthesizer
*
* Copyright (C) 2003 Peter Hanappe and others.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free
* Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301, USA
*/
/*
* Josh Green <[email protected]>
* 2009-05-28
*/
#include "fluid_ringbuffer.h"
#include "fluid_sys.h"
/**
* Create a lock free queue with a fixed maximum count and size of elements.
* @param count Count of elements in queue (fixed max number of queued elements)
* @return New lock free queue or NULL if out of memory (error message logged)
*
* Lockless FIFO queues don't use any locking mechanisms and can therefore be
* advantageous in certain situations, such as passing data between a lower
* priority thread and a higher "real time" thread, without potential lock
* contention which could stall the high priority thread. Note that there may
* only be one producer thread and one consumer thread.
*/
fluid_ringbuffer_t *
new_fluid_ringbuffer(int count, int elementsize)
{
fluid_ringbuffer_t *queue;
fluid_return_val_if_fail(count > 0, NULL);
queue = FLUID_NEW(fluid_ringbuffer_t);
if(!queue)
{
FLUID_LOG(FLUID_ERR, "Out of memory");
return NULL;
}
queue->array = FLUID_MALLOC(elementsize * count);
if(!queue->array)
{
FLUID_LOG(FLUID_ERR, "Out of memory");
delete_fluid_ringbuffer(queue);
return NULL;
}
/* Clear array, in case dynamic pointer reclaiming is being done */
FLUID_MEMSET(queue->array, 0, elementsize * count);
queue->totalcount = count;
queue->elementsize = elementsize;
fluid_atomic_int_set(&queue->count, 0);
queue->in = 0;
queue->out = 0;
return (queue);
}
/**
* Free an event queue.
* @param queue Lockless queue instance
*
* Care must be taken when freeing a queue, to ensure that the consumer and
* producer threads will no longer access it.
*/
void
delete_fluid_ringbuffer(fluid_ringbuffer_t *queue)
{
fluid_return_if_fail(queue != NULL);
FLUID_FREE(queue->array);
FLUID_FREE(queue);
}
| {
"pile_set_name": "Github"
} |
/* Original source Farseer Physics Engine:
* Copyright (c) 2014 Ian Qvist, http://farseerphysics.codeplex.com
* Microsoft Permissive License (Ms-PL) v1.1
*/
/*
* Farseer Physics Engine:
* Copyright (c) 2012 Ian Qvist
*
* Original source Box2D:
* Copyright (c) 2006-2011 Erin Catto http://www.box2d.org
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/
using tainicom.Aether.Physics2D.Collision;
using tainicom.Aether.Physics2D.Dynamics;
using tainicom.Aether.Physics2D.Dynamics.Contacts;
using tainicom.Aether.Physics2D.Samples.Testbed.Framework;
using Microsoft.Xna.Framework;
namespace tainicom.Aether.Physics2D.Samples.Testbed.Tests
{
public class ConveyorBeltTest : Test
{
private Fixture _platform;
ConveyorBeltTest()
{
// Ground
{
Body ground = World.CreateBody();
ground.CreateEdge(new Vector2(-20.0f, 0.0f), new Vector2(20.0f, 0.0f));
}
// Platform
{
Body body = World.CreateBody(new Vector2(-5, 5));
_platform = body.CreateRectangle(20, 1f, 1, Vector2.Zero);
_platform.Friction = 0.8f;
}
// Boxes
for (int i = 0; i < 5; ++i)
{
Body body = World.CreateRectangle(1f, 1f, 20, new Vector2(-10.0f + 2.0f * i, 7.0f));
body.BodyType = BodyType.Dynamic;
}
}
protected override void PreSolve(Contact contact, ref Manifold oldManifold)
{
base.PreSolve(contact, ref oldManifold);
Fixture fixtureA = contact.FixtureA;
Fixture fixtureB = contact.FixtureB;
if (fixtureA == _platform)
{
contact.TangentSpeed = 5.0f;
}
if (fixtureB == _platform)
{
contact.TangentSpeed = -5.0f;
}
}
internal static Test Create()
{
return new ConveyorBeltTest();
}
}
} | {
"pile_set_name": "Github"
} |
Phil Callaway, who has achieved notoriety for his humorous writing and speaking, was born July 26, 1961 in Three Hills, Alberta, Canada .
| {
"pile_set_name": "Github"
} |
// SPDX-License-Identifier: GPL-2.0
/**
* sni_ave.c - Socionext UniPhier AVE ethernet driver
* Copyright 2014 Panasonic Corporation
* Copyright 2015-2017 Socionext Inc.
*/
#include <linux/bitops.h>
#include <linux/clk.h>
#include <linux/etherdevice.h>
#include <linux/interrupt.h>
#include <linux/io.h>
#include <linux/iopoll.h>
#include <linux/mii.h>
#include <linux/module.h>
#include <linux/netdevice.h>
#include <linux/of_net.h>
#include <linux/of_mdio.h>
#include <linux/of_platform.h>
#include <linux/phy.h>
#include <linux/reset.h>
#include <linux/types.h>
#include <linux/u64_stats_sync.h>
/* General Register Group */
#define AVE_IDR 0x000 /* ID */
#define AVE_VR 0x004 /* Version */
#define AVE_GRR 0x008 /* Global Reset */
#define AVE_CFGR 0x00c /* Configuration */
/* Interrupt Register Group */
#define AVE_GIMR 0x100 /* Global Interrupt Mask */
#define AVE_GISR 0x104 /* Global Interrupt Status */
/* MAC Register Group */
#define AVE_TXCR 0x200 /* TX Setup */
#define AVE_RXCR 0x204 /* RX Setup */
#define AVE_RXMAC1R 0x208 /* MAC address (lower) */
#define AVE_RXMAC2R 0x20c /* MAC address (upper) */
#define AVE_MDIOCTR 0x214 /* MDIO Control */
#define AVE_MDIOAR 0x218 /* MDIO Address */
#define AVE_MDIOWDR 0x21c /* MDIO Data */
#define AVE_MDIOSR 0x220 /* MDIO Status */
#define AVE_MDIORDR 0x224 /* MDIO Rd Data */
/* Descriptor Control Register Group */
#define AVE_DESCC 0x300 /* Descriptor Control */
#define AVE_TXDC 0x304 /* TX Descriptor Configuration */
#define AVE_RXDC0 0x308 /* RX Descriptor Ring0 Configuration */
#define AVE_IIRQC 0x34c /* Interval IRQ Control */
/* Packet Filter Register Group */
#define AVE_PKTF_BASE 0x800 /* PF Base Address */
#define AVE_PFMBYTE_BASE 0xd00 /* PF Mask Byte Base Address */
#define AVE_PFMBIT_BASE 0xe00 /* PF Mask Bit Base Address */
#define AVE_PFSEL_BASE 0xf00 /* PF Selector Base Address */
#define AVE_PFEN 0xffc /* Packet Filter Enable */
#define AVE_PKTF(ent) (AVE_PKTF_BASE + (ent) * 0x40)
#define AVE_PFMBYTE(ent) (AVE_PFMBYTE_BASE + (ent) * 8)
#define AVE_PFMBIT(ent) (AVE_PFMBIT_BASE + (ent) * 4)
#define AVE_PFSEL(ent) (AVE_PFSEL_BASE + (ent) * 4)
/* 64bit descriptor memory */
#define AVE_DESC_SIZE_64 12 /* Descriptor Size */
#define AVE_TXDM_64 0x1000 /* Tx Descriptor Memory */
#define AVE_RXDM_64 0x1c00 /* Rx Descriptor Memory */
#define AVE_TXDM_SIZE_64 0x0ba0 /* Tx Descriptor Memory Size 3KB */
#define AVE_RXDM_SIZE_64 0x6000 /* Rx Descriptor Memory Size 24KB */
/* 32bit descriptor memory */
#define AVE_DESC_SIZE_32 8 /* Descriptor Size */
#define AVE_TXDM_32 0x1000 /* Tx Descriptor Memory */
#define AVE_RXDM_32 0x1800 /* Rx Descriptor Memory */
#define AVE_TXDM_SIZE_32 0x07c0 /* Tx Descriptor Memory Size 2KB */
#define AVE_RXDM_SIZE_32 0x4000 /* Rx Descriptor Memory Size 16KB */
/* RMII Bridge Register Group */
#define AVE_RSTCTRL 0x8028 /* Reset control */
#define AVE_RSTCTRL_RMIIRST BIT(16)
#define AVE_LINKSEL 0x8034 /* Link speed setting */
#define AVE_LINKSEL_100M BIT(0)
/* AVE_GRR */
#define AVE_GRR_RXFFR BIT(5) /* Reset RxFIFO */
#define AVE_GRR_PHYRST BIT(4) /* Reset external PHY */
#define AVE_GRR_GRST BIT(0) /* Reset all MAC */
/* AVE_CFGR */
#define AVE_CFGR_FLE BIT(31) /* Filter Function */
#define AVE_CFGR_CHE BIT(30) /* Checksum Function */
#define AVE_CFGR_MII BIT(27) /* Func mode (1:MII/RMII, 0:RGMII) */
#define AVE_CFGR_IPFCEN BIT(24) /* IP fragment sum Enable */
/* AVE_GISR (common with GIMR) */
#define AVE_GI_PHY BIT(24) /* PHY interrupt */
#define AVE_GI_TX BIT(16) /* Tx complete */
#define AVE_GI_RXERR BIT(8) /* Receive frame more than max size */
#define AVE_GI_RXOVF BIT(7) /* Overflow at the RxFIFO */
#define AVE_GI_RXDROP BIT(6) /* Drop packet */
#define AVE_GI_RXIINT BIT(5) /* Interval interrupt */
/* AVE_TXCR */
#define AVE_TXCR_FLOCTR BIT(18) /* Flow control */
#define AVE_TXCR_TXSPD_1G BIT(17)
#define AVE_TXCR_TXSPD_100 BIT(16)
/* AVE_RXCR */
#define AVE_RXCR_RXEN BIT(30) /* Rx enable */
#define AVE_RXCR_FDUPEN BIT(22) /* Interface mode */
#define AVE_RXCR_FLOCTR BIT(21) /* Flow control */
#define AVE_RXCR_AFEN BIT(19) /* MAC address filter */
#define AVE_RXCR_DRPEN BIT(18) /* Drop pause frame */
#define AVE_RXCR_MPSIZ_MASK GENMASK(10, 0)
/* AVE_MDIOCTR */
#define AVE_MDIOCTR_RREQ BIT(3) /* Read request */
#define AVE_MDIOCTR_WREQ BIT(2) /* Write request */
/* AVE_MDIOSR */
#define AVE_MDIOSR_STS BIT(0) /* access status */
/* AVE_DESCC */
#define AVE_DESCC_STATUS_MASK GENMASK(31, 16)
#define AVE_DESCC_RD0 BIT(8) /* Enable Rx descriptor Ring0 */
#define AVE_DESCC_RDSTP BIT(4) /* Pause Rx descriptor */
#define AVE_DESCC_TD BIT(0) /* Enable Tx descriptor */
/* AVE_TXDC */
#define AVE_TXDC_SIZE GENMASK(27, 16) /* Size of Tx descriptor */
#define AVE_TXDC_ADDR GENMASK(11, 0) /* Start address */
#define AVE_TXDC_ADDR_START 0
/* AVE_RXDC0 */
#define AVE_RXDC0_SIZE GENMASK(30, 16) /* Size of Rx descriptor */
#define AVE_RXDC0_ADDR GENMASK(14, 0) /* Start address */
#define AVE_RXDC0_ADDR_START 0
/* AVE_IIRQC */
#define AVE_IIRQC_EN0 BIT(27) /* Enable interval interrupt Ring0 */
#define AVE_IIRQC_BSCK GENMASK(15, 0) /* Interval count unit */
/* Command status for descriptor */
#define AVE_STS_OWN BIT(31) /* Descriptor ownership */
#define AVE_STS_INTR BIT(29) /* Request for interrupt */
#define AVE_STS_OK BIT(27) /* Normal transmit */
/* TX */
#define AVE_STS_NOCSUM BIT(28) /* No use HW checksum */
#define AVE_STS_1ST BIT(26) /* Head of buffer chain */
#define AVE_STS_LAST BIT(25) /* Tail of buffer chain */
#define AVE_STS_OWC BIT(21) /* Out of window,Late Collision */
#define AVE_STS_EC BIT(20) /* Excess collision occurred */
#define AVE_STS_PKTLEN_TX_MASK GENMASK(15, 0)
/* RX */
#define AVE_STS_CSSV BIT(21) /* Checksum check performed */
#define AVE_STS_CSER BIT(20) /* Checksum error detected */
#define AVE_STS_PKTLEN_RX_MASK GENMASK(10, 0)
/* Packet filter */
#define AVE_PFMBYTE_MASK0 (GENMASK(31, 8) | GENMASK(5, 0))
#define AVE_PFMBYTE_MASK1 GENMASK(25, 0)
#define AVE_PFMBIT_MASK GENMASK(15, 0)
#define AVE_PF_SIZE 17 /* Number of all packet filter */
#define AVE_PF_MULTICAST_SIZE 7 /* Number of multicast filter */
#define AVE_PFNUM_FILTER 0 /* No.0 */
#define AVE_PFNUM_UNICAST 1 /* No.1 */
#define AVE_PFNUM_BROADCAST 2 /* No.2 */
#define AVE_PFNUM_MULTICAST 11 /* No.11-17 */
/* NETIF Message control */
#define AVE_DEFAULT_MSG_ENABLE (NETIF_MSG_DRV | \
NETIF_MSG_PROBE | \
NETIF_MSG_LINK | \
NETIF_MSG_TIMER | \
NETIF_MSG_IFDOWN | \
NETIF_MSG_IFUP | \
NETIF_MSG_RX_ERR | \
NETIF_MSG_TX_ERR)
/* Parameter for descriptor */
#define AVE_NR_TXDESC 32 /* Tx descriptor */
#define AVE_NR_RXDESC 64 /* Rx descriptor */
#define AVE_DESC_OFS_CMDSTS 0
#define AVE_DESC_OFS_ADDRL 4
#define AVE_DESC_OFS_ADDRU 8
/* Parameter for ethernet frame */
#define AVE_MAX_ETHFRAME 1518
/* Parameter for interrupt */
#define AVE_INTM_COUNT 20
#define AVE_FORCE_TXINTCNT 1
#define IS_DESC_64BIT(p) ((p)->data->is_desc_64bit)
enum desc_id {
AVE_DESCID_RX,
AVE_DESCID_TX,
};
enum desc_state {
AVE_DESC_RX_PERMIT,
AVE_DESC_RX_SUSPEND,
AVE_DESC_START,
AVE_DESC_STOP,
};
struct ave_desc {
struct sk_buff *skbs;
dma_addr_t skbs_dma;
size_t skbs_dmalen;
};
struct ave_desc_info {
u32 ndesc; /* number of descriptor */
u32 daddr; /* start address of descriptor */
u32 proc_idx; /* index of processing packet */
u32 done_idx; /* index of processed packet */
struct ave_desc *desc; /* skb info related descriptor */
};
struct ave_soc_data {
bool is_desc_64bit;
};
struct ave_stats {
struct u64_stats_sync syncp;
u64 packets;
u64 bytes;
u64 errors;
u64 dropped;
u64 collisions;
u64 fifo_errors;
};
struct ave_private {
void __iomem *base;
int irq;
int phy_id;
unsigned int desc_size;
u32 msg_enable;
struct clk *clk;
struct reset_control *rst;
phy_interface_t phy_mode;
struct phy_device *phydev;
struct mii_bus *mdio;
/* stats */
struct ave_stats stats_rx;
struct ave_stats stats_tx;
/* NAPI support */
struct net_device *ndev;
struct napi_struct napi_rx;
struct napi_struct napi_tx;
/* descriptor */
struct ave_desc_info rx;
struct ave_desc_info tx;
/* flow control */
int pause_auto;
int pause_rx;
int pause_tx;
const struct ave_soc_data *data;
};
static u32 ave_desc_read(struct net_device *ndev, enum desc_id id, int entry,
int offset)
{
struct ave_private *priv = netdev_priv(ndev);
u32 addr;
addr = ((id == AVE_DESCID_TX) ? priv->tx.daddr : priv->rx.daddr)
+ entry * priv->desc_size + offset;
return readl(priv->base + addr);
}
static u32 ave_desc_read_cmdsts(struct net_device *ndev, enum desc_id id,
int entry)
{
return ave_desc_read(ndev, id, entry, AVE_DESC_OFS_CMDSTS);
}
static void ave_desc_write(struct net_device *ndev, enum desc_id id,
int entry, int offset, u32 val)
{
struct ave_private *priv = netdev_priv(ndev);
u32 addr;
addr = ((id == AVE_DESCID_TX) ? priv->tx.daddr : priv->rx.daddr)
+ entry * priv->desc_size + offset;
writel(val, priv->base + addr);
}
static void ave_desc_write_cmdsts(struct net_device *ndev, enum desc_id id,
int entry, u32 val)
{
ave_desc_write(ndev, id, entry, AVE_DESC_OFS_CMDSTS, val);
}
static void ave_desc_write_addr(struct net_device *ndev, enum desc_id id,
int entry, dma_addr_t paddr)
{
struct ave_private *priv = netdev_priv(ndev);
ave_desc_write(ndev, id, entry, AVE_DESC_OFS_ADDRL,
lower_32_bits(paddr));
if (IS_DESC_64BIT(priv))
ave_desc_write(ndev, id,
entry, AVE_DESC_OFS_ADDRU,
upper_32_bits(paddr));
}
static u32 ave_irq_disable_all(struct net_device *ndev)
{
struct ave_private *priv = netdev_priv(ndev);
u32 ret;
ret = readl(priv->base + AVE_GIMR);
writel(0, priv->base + AVE_GIMR);
return ret;
}
static void ave_irq_restore(struct net_device *ndev, u32 val)
{
struct ave_private *priv = netdev_priv(ndev);
writel(val, priv->base + AVE_GIMR);
}
static void ave_irq_enable(struct net_device *ndev, u32 bitflag)
{
struct ave_private *priv = netdev_priv(ndev);
writel(readl(priv->base + AVE_GIMR) | bitflag, priv->base + AVE_GIMR);
writel(bitflag, priv->base + AVE_GISR);
}
static void ave_hw_write_macaddr(struct net_device *ndev,
const unsigned char *mac_addr,
int reg1, int reg2)
{
struct ave_private *priv = netdev_priv(ndev);
writel(mac_addr[0] | mac_addr[1] << 8 |
mac_addr[2] << 16 | mac_addr[3] << 24, priv->base + reg1);
writel(mac_addr[4] | mac_addr[5] << 8, priv->base + reg2);
}
static void ave_hw_read_version(struct net_device *ndev, char *buf, int len)
{
struct ave_private *priv = netdev_priv(ndev);
u32 major, minor, vr;
vr = readl(priv->base + AVE_VR);
major = (vr & GENMASK(15, 8)) >> 8;
minor = (vr & GENMASK(7, 0));
snprintf(buf, len, "v%u.%u", major, minor);
}
static void ave_ethtool_get_drvinfo(struct net_device *ndev,
struct ethtool_drvinfo *info)
{
struct device *dev = ndev->dev.parent;
strlcpy(info->driver, dev->driver->name, sizeof(info->driver));
strlcpy(info->bus_info, dev_name(dev), sizeof(info->bus_info));
ave_hw_read_version(ndev, info->fw_version, sizeof(info->fw_version));
}
static u32 ave_ethtool_get_msglevel(struct net_device *ndev)
{
struct ave_private *priv = netdev_priv(ndev);
return priv->msg_enable;
}
static void ave_ethtool_set_msglevel(struct net_device *ndev, u32 val)
{
struct ave_private *priv = netdev_priv(ndev);
priv->msg_enable = val;
}
static void ave_ethtool_get_wol(struct net_device *ndev,
struct ethtool_wolinfo *wol)
{
wol->supported = 0;
wol->wolopts = 0;
if (ndev->phydev)
phy_ethtool_get_wol(ndev->phydev, wol);
}
static int ave_ethtool_set_wol(struct net_device *ndev,
struct ethtool_wolinfo *wol)
{
int ret;
if (!ndev->phydev ||
(wol->wolopts & (WAKE_ARP | WAKE_MAGICSECURE)))
return -EOPNOTSUPP;
ret = phy_ethtool_set_wol(ndev->phydev, wol);
if (!ret)
device_set_wakeup_enable(&ndev->dev, !!wol->wolopts);
return ret;
}
static void ave_ethtool_get_pauseparam(struct net_device *ndev,
struct ethtool_pauseparam *pause)
{
struct ave_private *priv = netdev_priv(ndev);
pause->autoneg = priv->pause_auto;
pause->rx_pause = priv->pause_rx;
pause->tx_pause = priv->pause_tx;
}
static int ave_ethtool_set_pauseparam(struct net_device *ndev,
struct ethtool_pauseparam *pause)
{
struct ave_private *priv = netdev_priv(ndev);
struct phy_device *phydev = ndev->phydev;
if (!phydev)
return -EINVAL;
priv->pause_auto = pause->autoneg;
priv->pause_rx = pause->rx_pause;
priv->pause_tx = pause->tx_pause;
phydev->advertising &= ~(ADVERTISED_Pause | ADVERTISED_Asym_Pause);
if (pause->rx_pause)
phydev->advertising |= ADVERTISED_Pause | ADVERTISED_Asym_Pause;
if (pause->tx_pause)
phydev->advertising ^= ADVERTISED_Asym_Pause;
if (pause->autoneg) {
if (netif_running(ndev))
phy_start_aneg(phydev);
}
return 0;
}
static const struct ethtool_ops ave_ethtool_ops = {
.get_link_ksettings = phy_ethtool_get_link_ksettings,
.set_link_ksettings = phy_ethtool_set_link_ksettings,
.get_drvinfo = ave_ethtool_get_drvinfo,
.nway_reset = phy_ethtool_nway_reset,
.get_link = ethtool_op_get_link,
.get_msglevel = ave_ethtool_get_msglevel,
.set_msglevel = ave_ethtool_set_msglevel,
.get_wol = ave_ethtool_get_wol,
.set_wol = ave_ethtool_set_wol,
.get_pauseparam = ave_ethtool_get_pauseparam,
.set_pauseparam = ave_ethtool_set_pauseparam,
};
static int ave_mdiobus_read(struct mii_bus *bus, int phyid, int regnum)
{
struct net_device *ndev = bus->priv;
struct ave_private *priv;
u32 mdioctl, mdiosr;
int ret;
priv = netdev_priv(ndev);
/* write address */
writel((phyid << 8) | regnum, priv->base + AVE_MDIOAR);
/* read request */
mdioctl = readl(priv->base + AVE_MDIOCTR);
writel((mdioctl | AVE_MDIOCTR_RREQ) & ~AVE_MDIOCTR_WREQ,
priv->base + AVE_MDIOCTR);
ret = readl_poll_timeout(priv->base + AVE_MDIOSR, mdiosr,
!(mdiosr & AVE_MDIOSR_STS), 20, 2000);
if (ret) {
netdev_err(ndev, "failed to read (phy:%d reg:%x)\n",
phyid, regnum);
return ret;
}
return readl(priv->base + AVE_MDIORDR) & GENMASK(15, 0);
}
static int ave_mdiobus_write(struct mii_bus *bus, int phyid, int regnum,
u16 val)
{
struct net_device *ndev = bus->priv;
struct ave_private *priv;
u32 mdioctl, mdiosr;
int ret;
priv = netdev_priv(ndev);
/* write address */
writel((phyid << 8) | regnum, priv->base + AVE_MDIOAR);
/* write data */
writel(val, priv->base + AVE_MDIOWDR);
/* write request */
mdioctl = readl(priv->base + AVE_MDIOCTR);
writel((mdioctl | AVE_MDIOCTR_WREQ) & ~AVE_MDIOCTR_RREQ,
priv->base + AVE_MDIOCTR);
ret = readl_poll_timeout(priv->base + AVE_MDIOSR, mdiosr,
!(mdiosr & AVE_MDIOSR_STS), 20, 2000);
if (ret)
netdev_err(ndev, "failed to write (phy:%d reg:%x)\n",
phyid, regnum);
return ret;
}
static int ave_dma_map(struct net_device *ndev, struct ave_desc *desc,
void *ptr, size_t len, enum dma_data_direction dir,
dma_addr_t *paddr)
{
dma_addr_t map_addr;
map_addr = dma_map_single(ndev->dev.parent, ptr, len, dir);
if (unlikely(dma_mapping_error(ndev->dev.parent, map_addr)))
return -ENOMEM;
desc->skbs_dma = map_addr;
desc->skbs_dmalen = len;
*paddr = map_addr;
return 0;
}
static void ave_dma_unmap(struct net_device *ndev, struct ave_desc *desc,
enum dma_data_direction dir)
{
if (!desc->skbs_dma)
return;
dma_unmap_single(ndev->dev.parent,
desc->skbs_dma, desc->skbs_dmalen, dir);
desc->skbs_dma = 0;
}
/* Prepare Rx descriptor and memory */
static int ave_rxdesc_prepare(struct net_device *ndev, int entry)
{
struct ave_private *priv = netdev_priv(ndev);
struct sk_buff *skb;
dma_addr_t paddr;
int ret;
skb = priv->rx.desc[entry].skbs;
if (!skb) {
skb = netdev_alloc_skb_ip_align(ndev,
AVE_MAX_ETHFRAME);
if (!skb) {
netdev_err(ndev, "can't allocate skb for Rx\n");
return -ENOMEM;
}
}
/* set disable to cmdsts */
ave_desc_write_cmdsts(ndev, AVE_DESCID_RX, entry,
AVE_STS_INTR | AVE_STS_OWN);
/* map Rx buffer
* Rx buffer set to the Rx descriptor has two restrictions:
* - Rx buffer address is 4 byte aligned.
* - Rx buffer begins with 2 byte headroom, and data will be put from
* (buffer + 2).
* To satisfy this, specify the address to put back the buffer
* pointer advanced by NET_IP_ALIGN by netdev_alloc_skb_ip_align(),
* and expand the map size by NET_IP_ALIGN.
*/
ret = ave_dma_map(ndev, &priv->rx.desc[entry],
skb->data - NET_IP_ALIGN,
AVE_MAX_ETHFRAME + NET_IP_ALIGN,
DMA_FROM_DEVICE, &paddr);
if (ret) {
netdev_err(ndev, "can't map skb for Rx\n");
dev_kfree_skb_any(skb);
return ret;
}
priv->rx.desc[entry].skbs = skb;
/* set buffer pointer */
ave_desc_write_addr(ndev, AVE_DESCID_RX, entry, paddr);
/* set enable to cmdsts */
ave_desc_write_cmdsts(ndev, AVE_DESCID_RX, entry,
AVE_STS_INTR | AVE_MAX_ETHFRAME);
return ret;
}
/* Switch state of descriptor */
static int ave_desc_switch(struct net_device *ndev, enum desc_state state)
{
struct ave_private *priv = netdev_priv(ndev);
int ret = 0;
u32 val;
switch (state) {
case AVE_DESC_START:
writel(AVE_DESCC_TD | AVE_DESCC_RD0, priv->base + AVE_DESCC);
break;
case AVE_DESC_STOP:
writel(0, priv->base + AVE_DESCC);
if (readl_poll_timeout(priv->base + AVE_DESCC, val, !val,
150, 15000)) {
netdev_err(ndev, "can't stop descriptor\n");
ret = -EBUSY;
}
break;
case AVE_DESC_RX_SUSPEND:
val = readl(priv->base + AVE_DESCC);
val |= AVE_DESCC_RDSTP;
val &= ~AVE_DESCC_STATUS_MASK;
writel(val, priv->base + AVE_DESCC);
if (readl_poll_timeout(priv->base + AVE_DESCC, val,
val & (AVE_DESCC_RDSTP << 16),
150, 150000)) {
netdev_err(ndev, "can't suspend descriptor\n");
ret = -EBUSY;
}
break;
case AVE_DESC_RX_PERMIT:
val = readl(priv->base + AVE_DESCC);
val &= ~AVE_DESCC_RDSTP;
val &= ~AVE_DESCC_STATUS_MASK;
writel(val, priv->base + AVE_DESCC);
break;
default:
ret = -EINVAL;
break;
}
return ret;
}
static int ave_tx_complete(struct net_device *ndev)
{
struct ave_private *priv = netdev_priv(ndev);
u32 proc_idx, done_idx, ndesc, cmdsts;
unsigned int nr_freebuf = 0;
unsigned int tx_packets = 0;
unsigned int tx_bytes = 0;
proc_idx = priv->tx.proc_idx;
done_idx = priv->tx.done_idx;
ndesc = priv->tx.ndesc;
/* free pre-stored skb from done_idx to proc_idx */
while (proc_idx != done_idx) {
cmdsts = ave_desc_read_cmdsts(ndev, AVE_DESCID_TX, done_idx);
/* do nothing if owner is HW (==1 for Tx) */
if (cmdsts & AVE_STS_OWN)
break;
/* check Tx status and updates statistics */
if (cmdsts & AVE_STS_OK) {
tx_bytes += cmdsts & AVE_STS_PKTLEN_TX_MASK;
/* success */
if (cmdsts & AVE_STS_LAST)
tx_packets++;
} else {
/* error */
if (cmdsts & AVE_STS_LAST) {
priv->stats_tx.errors++;
if (cmdsts & (AVE_STS_OWC | AVE_STS_EC))
priv->stats_tx.collisions++;
}
}
/* release skb */
if (priv->tx.desc[done_idx].skbs) {
ave_dma_unmap(ndev, &priv->tx.desc[done_idx],
DMA_TO_DEVICE);
dev_consume_skb_any(priv->tx.desc[done_idx].skbs);
priv->tx.desc[done_idx].skbs = NULL;
nr_freebuf++;
}
done_idx = (done_idx + 1) % ndesc;
}
priv->tx.done_idx = done_idx;
/* update stats */
u64_stats_update_begin(&priv->stats_tx.syncp);
priv->stats_tx.packets += tx_packets;
priv->stats_tx.bytes += tx_bytes;
u64_stats_update_end(&priv->stats_tx.syncp);
/* wake queue for freeing buffer */
if (unlikely(netif_queue_stopped(ndev)) && nr_freebuf)
netif_wake_queue(ndev);
return nr_freebuf;
}
static int ave_rx_receive(struct net_device *ndev, int num)
{
struct ave_private *priv = netdev_priv(ndev);
unsigned int rx_packets = 0;
unsigned int rx_bytes = 0;
u32 proc_idx, done_idx;
struct sk_buff *skb;
unsigned int pktlen;
int restpkt, npkts;
u32 ndesc, cmdsts;
proc_idx = priv->rx.proc_idx;
done_idx = priv->rx.done_idx;
ndesc = priv->rx.ndesc;
restpkt = ((proc_idx + ndesc - 1) - done_idx) % ndesc;
for (npkts = 0; npkts < num; npkts++) {
/* we can't receive more packet, so fill desc quickly */
if (--restpkt < 0)
break;
cmdsts = ave_desc_read_cmdsts(ndev, AVE_DESCID_RX, proc_idx);
/* do nothing if owner is HW (==0 for Rx) */
if (!(cmdsts & AVE_STS_OWN))
break;
if (!(cmdsts & AVE_STS_OK)) {
priv->stats_rx.errors++;
proc_idx = (proc_idx + 1) % ndesc;
continue;
}
pktlen = cmdsts & AVE_STS_PKTLEN_RX_MASK;
/* get skbuff for rx */
skb = priv->rx.desc[proc_idx].skbs;
priv->rx.desc[proc_idx].skbs = NULL;
ave_dma_unmap(ndev, &priv->rx.desc[proc_idx], DMA_FROM_DEVICE);
skb->dev = ndev;
skb_put(skb, pktlen);
skb->protocol = eth_type_trans(skb, ndev);
if ((cmdsts & AVE_STS_CSSV) && (!(cmdsts & AVE_STS_CSER)))
skb->ip_summed = CHECKSUM_UNNECESSARY;
rx_packets++;
rx_bytes += pktlen;
netif_receive_skb(skb);
proc_idx = (proc_idx + 1) % ndesc;
}
priv->rx.proc_idx = proc_idx;
/* update stats */
u64_stats_update_begin(&priv->stats_rx.syncp);
priv->stats_rx.packets += rx_packets;
priv->stats_rx.bytes += rx_bytes;
u64_stats_update_end(&priv->stats_rx.syncp);
/* refill the Rx buffers */
while (proc_idx != done_idx) {
if (ave_rxdesc_prepare(ndev, done_idx))
break;
done_idx = (done_idx + 1) % ndesc;
}
priv->rx.done_idx = done_idx;
return npkts;
}
static int ave_napi_poll_rx(struct napi_struct *napi, int budget)
{
struct ave_private *priv;
struct net_device *ndev;
int num;
priv = container_of(napi, struct ave_private, napi_rx);
ndev = priv->ndev;
num = ave_rx_receive(ndev, budget);
if (num < budget) {
napi_complete_done(napi, num);
/* enable Rx interrupt when NAPI finishes */
ave_irq_enable(ndev, AVE_GI_RXIINT);
}
return num;
}
static int ave_napi_poll_tx(struct napi_struct *napi, int budget)
{
struct ave_private *priv;
struct net_device *ndev;
int num;
priv = container_of(napi, struct ave_private, napi_tx);
ndev = priv->ndev;
num = ave_tx_complete(ndev);
napi_complete(napi);
/* enable Tx interrupt when NAPI finishes */
ave_irq_enable(ndev, AVE_GI_TX);
return num;
}
static void ave_global_reset(struct net_device *ndev)
{
struct ave_private *priv = netdev_priv(ndev);
u32 val;
/* set config register */
val = AVE_CFGR_FLE | AVE_CFGR_IPFCEN | AVE_CFGR_CHE;
if (!phy_interface_mode_is_rgmii(priv->phy_mode))
val |= AVE_CFGR_MII;
writel(val, priv->base + AVE_CFGR);
/* reset RMII register */
val = readl(priv->base + AVE_RSTCTRL);
val &= ~AVE_RSTCTRL_RMIIRST;
writel(val, priv->base + AVE_RSTCTRL);
/* assert reset */
writel(AVE_GRR_GRST | AVE_GRR_PHYRST, priv->base + AVE_GRR);
msleep(20);
/* 1st, negate PHY reset only */
writel(AVE_GRR_GRST, priv->base + AVE_GRR);
msleep(40);
/* negate reset */
writel(0, priv->base + AVE_GRR);
msleep(40);
/* negate RMII register */
val = readl(priv->base + AVE_RSTCTRL);
val |= AVE_RSTCTRL_RMIIRST;
writel(val, priv->base + AVE_RSTCTRL);
ave_irq_disable_all(ndev);
}
static void ave_rxfifo_reset(struct net_device *ndev)
{
struct ave_private *priv = netdev_priv(ndev);
u32 rxcr_org;
/* save and disable MAC receive op */
rxcr_org = readl(priv->base + AVE_RXCR);
writel(rxcr_org & (~AVE_RXCR_RXEN), priv->base + AVE_RXCR);
/* suspend Rx descriptor */
ave_desc_switch(ndev, AVE_DESC_RX_SUSPEND);
/* receive all packets before descriptor starts */
ave_rx_receive(ndev, priv->rx.ndesc);
/* assert reset */
writel(AVE_GRR_RXFFR, priv->base + AVE_GRR);
usleep_range(40, 50);
/* negate reset */
writel(0, priv->base + AVE_GRR);
usleep_range(10, 20);
/* negate interrupt status */
writel(AVE_GI_RXOVF, priv->base + AVE_GISR);
/* permit descriptor */
ave_desc_switch(ndev, AVE_DESC_RX_PERMIT);
/* restore MAC reccieve op */
writel(rxcr_org, priv->base + AVE_RXCR);
}
static irqreturn_t ave_irq_handler(int irq, void *netdev)
{
struct net_device *ndev = (struct net_device *)netdev;
struct ave_private *priv = netdev_priv(ndev);
u32 gimr_val, gisr_val;
gimr_val = ave_irq_disable_all(ndev);
/* get interrupt status */
gisr_val = readl(priv->base + AVE_GISR);
/* PHY */
if (gisr_val & AVE_GI_PHY)
writel(AVE_GI_PHY, priv->base + AVE_GISR);
/* check exceeding packet */
if (gisr_val & AVE_GI_RXERR) {
writel(AVE_GI_RXERR, priv->base + AVE_GISR);
netdev_err(ndev, "receive a packet exceeding frame buffer\n");
}
gisr_val &= gimr_val;
if (!gisr_val)
goto exit_isr;
/* RxFIFO overflow */
if (gisr_val & AVE_GI_RXOVF) {
priv->stats_rx.fifo_errors++;
ave_rxfifo_reset(ndev);
goto exit_isr;
}
/* Rx drop */
if (gisr_val & AVE_GI_RXDROP) {
priv->stats_rx.dropped++;
writel(AVE_GI_RXDROP, priv->base + AVE_GISR);
}
/* Rx interval */
if (gisr_val & AVE_GI_RXIINT) {
napi_schedule(&priv->napi_rx);
/* still force to disable Rx interrupt until NAPI finishes */
gimr_val &= ~AVE_GI_RXIINT;
}
/* Tx completed */
if (gisr_val & AVE_GI_TX) {
napi_schedule(&priv->napi_tx);
/* still force to disable Tx interrupt until NAPI finishes */
gimr_val &= ~AVE_GI_TX;
}
exit_isr:
ave_irq_restore(ndev, gimr_val);
return IRQ_HANDLED;
}
static int ave_pfsel_start(struct net_device *ndev, unsigned int entry)
{
struct ave_private *priv = netdev_priv(ndev);
u32 val;
if (WARN_ON(entry > AVE_PF_SIZE))
return -EINVAL;
val = readl(priv->base + AVE_PFEN);
writel(val | BIT(entry), priv->base + AVE_PFEN);
return 0;
}
static int ave_pfsel_stop(struct net_device *ndev, unsigned int entry)
{
struct ave_private *priv = netdev_priv(ndev);
u32 val;
if (WARN_ON(entry > AVE_PF_SIZE))
return -EINVAL;
val = readl(priv->base + AVE_PFEN);
writel(val & ~BIT(entry), priv->base + AVE_PFEN);
return 0;
}
static int ave_pfsel_set_macaddr(struct net_device *ndev,
unsigned int entry,
const unsigned char *mac_addr,
unsigned int set_size)
{
struct ave_private *priv = netdev_priv(ndev);
if (WARN_ON(entry > AVE_PF_SIZE))
return -EINVAL;
if (WARN_ON(set_size > 6))
return -EINVAL;
ave_pfsel_stop(ndev, entry);
/* set MAC address for the filter */
ave_hw_write_macaddr(ndev, mac_addr,
AVE_PKTF(entry), AVE_PKTF(entry) + 4);
/* set byte mask */
writel(GENMASK(31, set_size) & AVE_PFMBYTE_MASK0,
priv->base + AVE_PFMBYTE(entry));
writel(AVE_PFMBYTE_MASK1, priv->base + AVE_PFMBYTE(entry) + 4);
/* set bit mask filter */
writel(AVE_PFMBIT_MASK, priv->base + AVE_PFMBIT(entry));
/* set selector to ring 0 */
writel(0, priv->base + AVE_PFSEL(entry));
/* restart filter */
ave_pfsel_start(ndev, entry);
return 0;
}
static void ave_pfsel_set_promisc(struct net_device *ndev,
unsigned int entry, u32 rxring)
{
struct ave_private *priv = netdev_priv(ndev);
if (WARN_ON(entry > AVE_PF_SIZE))
return;
ave_pfsel_stop(ndev, entry);
/* set byte mask */
writel(AVE_PFMBYTE_MASK0, priv->base + AVE_PFMBYTE(entry));
writel(AVE_PFMBYTE_MASK1, priv->base + AVE_PFMBYTE(entry) + 4);
/* set bit mask filter */
writel(AVE_PFMBIT_MASK, priv->base + AVE_PFMBIT(entry));
/* set selector to rxring */
writel(rxring, priv->base + AVE_PFSEL(entry));
ave_pfsel_start(ndev, entry);
}
static void ave_pfsel_init(struct net_device *ndev)
{
unsigned char bcast_mac[ETH_ALEN];
int i;
eth_broadcast_addr(bcast_mac);
for (i = 0; i < AVE_PF_SIZE; i++)
ave_pfsel_stop(ndev, i);
/* promiscious entry, select ring 0 */
ave_pfsel_set_promisc(ndev, AVE_PFNUM_FILTER, 0);
/* unicast entry */
ave_pfsel_set_macaddr(ndev, AVE_PFNUM_UNICAST, ndev->dev_addr, 6);
/* broadcast entry */
ave_pfsel_set_macaddr(ndev, AVE_PFNUM_BROADCAST, bcast_mac, 6);
}
static void ave_phy_adjust_link(struct net_device *ndev)
{
struct ave_private *priv = netdev_priv(ndev);
struct phy_device *phydev = ndev->phydev;
u32 val, txcr, rxcr, rxcr_org;
u16 rmt_adv = 0, lcl_adv = 0;
u8 cap;
/* set RGMII speed */
val = readl(priv->base + AVE_TXCR);
val &= ~(AVE_TXCR_TXSPD_100 | AVE_TXCR_TXSPD_1G);
if (phy_interface_is_rgmii(phydev) && phydev->speed == SPEED_1000)
val |= AVE_TXCR_TXSPD_1G;
else if (phydev->speed == SPEED_100)
val |= AVE_TXCR_TXSPD_100;
writel(val, priv->base + AVE_TXCR);
/* set RMII speed (100M/10M only) */
if (!phy_interface_is_rgmii(phydev)) {
val = readl(priv->base + AVE_LINKSEL);
if (phydev->speed == SPEED_10)
val &= ~AVE_LINKSEL_100M;
else
val |= AVE_LINKSEL_100M;
writel(val, priv->base + AVE_LINKSEL);
}
/* check current RXCR/TXCR */
rxcr = readl(priv->base + AVE_RXCR);
txcr = readl(priv->base + AVE_TXCR);
rxcr_org = rxcr;
if (phydev->duplex) {
rxcr |= AVE_RXCR_FDUPEN;
if (phydev->pause)
rmt_adv |= LPA_PAUSE_CAP;
if (phydev->asym_pause)
rmt_adv |= LPA_PAUSE_ASYM;
if (phydev->advertising & ADVERTISED_Pause)
lcl_adv |= ADVERTISE_PAUSE_CAP;
if (phydev->advertising & ADVERTISED_Asym_Pause)
lcl_adv |= ADVERTISE_PAUSE_ASYM;
cap = mii_resolve_flowctrl_fdx(lcl_adv, rmt_adv);
if (cap & FLOW_CTRL_TX)
txcr |= AVE_TXCR_FLOCTR;
else
txcr &= ~AVE_TXCR_FLOCTR;
if (cap & FLOW_CTRL_RX)
rxcr |= AVE_RXCR_FLOCTR;
else
rxcr &= ~AVE_RXCR_FLOCTR;
} else {
rxcr &= ~AVE_RXCR_FDUPEN;
rxcr &= ~AVE_RXCR_FLOCTR;
txcr &= ~AVE_TXCR_FLOCTR;
}
if (rxcr_org != rxcr) {
/* disable Rx mac */
writel(rxcr & ~AVE_RXCR_RXEN, priv->base + AVE_RXCR);
/* change and enable TX/Rx mac */
writel(txcr, priv->base + AVE_TXCR);
writel(rxcr, priv->base + AVE_RXCR);
}
phy_print_status(phydev);
}
static void ave_macaddr_init(struct net_device *ndev)
{
ave_hw_write_macaddr(ndev, ndev->dev_addr, AVE_RXMAC1R, AVE_RXMAC2R);
/* pfsel unicast entry */
ave_pfsel_set_macaddr(ndev, AVE_PFNUM_UNICAST, ndev->dev_addr, 6);
}
static int ave_init(struct net_device *ndev)
{
struct ethtool_wolinfo wol = { .cmd = ETHTOOL_GWOL };
struct ave_private *priv = netdev_priv(ndev);
struct device *dev = ndev->dev.parent;
struct device_node *np = dev->of_node;
struct device_node *mdio_np;
struct phy_device *phydev;
int ret;
/* enable clk because of hw access until ndo_open */
ret = clk_prepare_enable(priv->clk);
if (ret) {
dev_err(dev, "can't enable clock\n");
return ret;
}
ret = reset_control_deassert(priv->rst);
if (ret) {
dev_err(dev, "can't deassert reset\n");
goto out_clk_disable;
}
ave_global_reset(ndev);
mdio_np = of_get_child_by_name(np, "mdio");
if (!mdio_np) {
dev_err(dev, "mdio node not found\n");
ret = -EINVAL;
goto out_reset_assert;
}
ret = of_mdiobus_register(priv->mdio, mdio_np);
of_node_put(mdio_np);
if (ret) {
dev_err(dev, "failed to register mdiobus\n");
goto out_reset_assert;
}
phydev = of_phy_get_and_connect(ndev, np, ave_phy_adjust_link);
if (!phydev) {
dev_err(dev, "could not attach to PHY\n");
ret = -ENODEV;
goto out_mdio_unregister;
}
priv->phydev = phydev;
phy_ethtool_get_wol(phydev, &wol);
device_set_wakeup_capable(&ndev->dev, !!wol.supported);
if (!phy_interface_is_rgmii(phydev)) {
phydev->supported &= ~PHY_GBIT_FEATURES;
phydev->supported |= PHY_BASIC_FEATURES;
}
phydev->supported |= SUPPORTED_Pause | SUPPORTED_Asym_Pause;
phy_attached_info(phydev);
return 0;
out_mdio_unregister:
mdiobus_unregister(priv->mdio);
out_reset_assert:
reset_control_assert(priv->rst);
out_clk_disable:
clk_disable_unprepare(priv->clk);
return ret;
}
static void ave_uninit(struct net_device *ndev)
{
struct ave_private *priv = netdev_priv(ndev);
phy_disconnect(priv->phydev);
mdiobus_unregister(priv->mdio);
/* disable clk because of hw access after ndo_stop */
reset_control_assert(priv->rst);
clk_disable_unprepare(priv->clk);
}
static int ave_open(struct net_device *ndev)
{
struct ave_private *priv = netdev_priv(ndev);
int entry;
int ret;
u32 val;
ret = request_irq(priv->irq, ave_irq_handler, IRQF_SHARED, ndev->name,
ndev);
if (ret)
return ret;
priv->tx.desc = kcalloc(priv->tx.ndesc, sizeof(*priv->tx.desc),
GFP_KERNEL);
if (!priv->tx.desc) {
ret = -ENOMEM;
goto out_free_irq;
}
priv->rx.desc = kcalloc(priv->rx.ndesc, sizeof(*priv->rx.desc),
GFP_KERNEL);
if (!priv->rx.desc) {
kfree(priv->tx.desc);
ret = -ENOMEM;
goto out_free_irq;
}
/* initialize Tx work and descriptor */
priv->tx.proc_idx = 0;
priv->tx.done_idx = 0;
for (entry = 0; entry < priv->tx.ndesc; entry++) {
ave_desc_write_cmdsts(ndev, AVE_DESCID_TX, entry, 0);
ave_desc_write_addr(ndev, AVE_DESCID_TX, entry, 0);
}
writel(AVE_TXDC_ADDR_START |
(((priv->tx.ndesc * priv->desc_size) << 16) & AVE_TXDC_SIZE),
priv->base + AVE_TXDC);
/* initialize Rx work and descriptor */
priv->rx.proc_idx = 0;
priv->rx.done_idx = 0;
for (entry = 0; entry < priv->rx.ndesc; entry++) {
if (ave_rxdesc_prepare(ndev, entry))
break;
}
writel(AVE_RXDC0_ADDR_START |
(((priv->rx.ndesc * priv->desc_size) << 16) & AVE_RXDC0_SIZE),
priv->base + AVE_RXDC0);
ave_desc_switch(ndev, AVE_DESC_START);
ave_pfsel_init(ndev);
ave_macaddr_init(ndev);
/* set Rx configuration */
/* full duplex, enable pause drop, enalbe flow control */
val = AVE_RXCR_RXEN | AVE_RXCR_FDUPEN | AVE_RXCR_DRPEN |
AVE_RXCR_FLOCTR | (AVE_MAX_ETHFRAME & AVE_RXCR_MPSIZ_MASK);
writel(val, priv->base + AVE_RXCR);
/* set Tx configuration */
/* enable flow control, disable loopback */
writel(AVE_TXCR_FLOCTR, priv->base + AVE_TXCR);
/* enable timer, clear EN,INTM, and mask interval unit(BSCK) */
val = readl(priv->base + AVE_IIRQC) & AVE_IIRQC_BSCK;
val |= AVE_IIRQC_EN0 | (AVE_INTM_COUNT << 16);
writel(val, priv->base + AVE_IIRQC);
val = AVE_GI_RXIINT | AVE_GI_RXOVF | AVE_GI_TX | AVE_GI_RXDROP;
ave_irq_restore(ndev, val);
napi_enable(&priv->napi_rx);
napi_enable(&priv->napi_tx);
phy_start(ndev->phydev);
phy_start_aneg(ndev->phydev);
netif_start_queue(ndev);
return 0;
out_free_irq:
disable_irq(priv->irq);
free_irq(priv->irq, ndev);
return ret;
}
static int ave_stop(struct net_device *ndev)
{
struct ave_private *priv = netdev_priv(ndev);
int entry;
ave_irq_disable_all(ndev);
disable_irq(priv->irq);
free_irq(priv->irq, ndev);
netif_tx_disable(ndev);
phy_stop(ndev->phydev);
napi_disable(&priv->napi_tx);
napi_disable(&priv->napi_rx);
ave_desc_switch(ndev, AVE_DESC_STOP);
/* free Tx buffer */
for (entry = 0; entry < priv->tx.ndesc; entry++) {
if (!priv->tx.desc[entry].skbs)
continue;
ave_dma_unmap(ndev, &priv->tx.desc[entry], DMA_TO_DEVICE);
dev_kfree_skb_any(priv->tx.desc[entry].skbs);
priv->tx.desc[entry].skbs = NULL;
}
priv->tx.proc_idx = 0;
priv->tx.done_idx = 0;
/* free Rx buffer */
for (entry = 0; entry < priv->rx.ndesc; entry++) {
if (!priv->rx.desc[entry].skbs)
continue;
ave_dma_unmap(ndev, &priv->rx.desc[entry], DMA_FROM_DEVICE);
dev_kfree_skb_any(priv->rx.desc[entry].skbs);
priv->rx.desc[entry].skbs = NULL;
}
priv->rx.proc_idx = 0;
priv->rx.done_idx = 0;
kfree(priv->tx.desc);
kfree(priv->rx.desc);
return 0;
}
static int ave_start_xmit(struct sk_buff *skb, struct net_device *ndev)
{
struct ave_private *priv = netdev_priv(ndev);
u32 proc_idx, done_idx, ndesc, cmdsts;
int ret, freepkt;
dma_addr_t paddr;
proc_idx = priv->tx.proc_idx;
done_idx = priv->tx.done_idx;
ndesc = priv->tx.ndesc;
freepkt = ((done_idx + ndesc - 1) - proc_idx) % ndesc;
/* stop queue when not enough entry */
if (unlikely(freepkt < 1)) {
netif_stop_queue(ndev);
return NETDEV_TX_BUSY;
}
/* add padding for short packet */
if (skb_put_padto(skb, ETH_ZLEN)) {
priv->stats_tx.dropped++;
return NETDEV_TX_OK;
}
/* map Tx buffer
* Tx buffer set to the Tx descriptor doesn't have any restriction.
*/
ret = ave_dma_map(ndev, &priv->tx.desc[proc_idx],
skb->data, skb->len, DMA_TO_DEVICE, &paddr);
if (ret) {
dev_kfree_skb_any(skb);
priv->stats_tx.dropped++;
return NETDEV_TX_OK;
}
priv->tx.desc[proc_idx].skbs = skb;
ave_desc_write_addr(ndev, AVE_DESCID_TX, proc_idx, paddr);
cmdsts = AVE_STS_OWN | AVE_STS_1ST | AVE_STS_LAST |
(skb->len & AVE_STS_PKTLEN_TX_MASK);
/* set interrupt per AVE_FORCE_TXINTCNT or when queue is stopped */
if (!(proc_idx % AVE_FORCE_TXINTCNT) || netif_queue_stopped(ndev))
cmdsts |= AVE_STS_INTR;
/* disable checksum calculation when skb doesn't calurate checksum */
if (skb->ip_summed == CHECKSUM_NONE ||
skb->ip_summed == CHECKSUM_UNNECESSARY)
cmdsts |= AVE_STS_NOCSUM;
ave_desc_write_cmdsts(ndev, AVE_DESCID_TX, proc_idx, cmdsts);
priv->tx.proc_idx = (proc_idx + 1) % ndesc;
return NETDEV_TX_OK;
}
static int ave_ioctl(struct net_device *ndev, struct ifreq *ifr, int cmd)
{
return phy_mii_ioctl(ndev->phydev, ifr, cmd);
}
static const u8 v4multi_macadr[] = { 0x01, 0x00, 0x00, 0x00, 0x00, 0x00 };
static const u8 v6multi_macadr[] = { 0x33, 0x00, 0x00, 0x00, 0x00, 0x00 };
static void ave_set_rx_mode(struct net_device *ndev)
{
struct ave_private *priv = netdev_priv(ndev);
struct netdev_hw_addr *hw_adr;
int count, mc_cnt;
u32 val;
/* MAC addr filter enable for promiscious mode */
mc_cnt = netdev_mc_count(ndev);
val = readl(priv->base + AVE_RXCR);
if (ndev->flags & IFF_PROMISC || !mc_cnt)
val &= ~AVE_RXCR_AFEN;
else
val |= AVE_RXCR_AFEN;
writel(val, priv->base + AVE_RXCR);
/* set all multicast address */
if ((ndev->flags & IFF_ALLMULTI) || mc_cnt > AVE_PF_MULTICAST_SIZE) {
ave_pfsel_set_macaddr(ndev, AVE_PFNUM_MULTICAST,
v4multi_macadr, 1);
ave_pfsel_set_macaddr(ndev, AVE_PFNUM_MULTICAST + 1,
v6multi_macadr, 1);
} else {
/* stop all multicast filter */
for (count = 0; count < AVE_PF_MULTICAST_SIZE; count++)
ave_pfsel_stop(ndev, AVE_PFNUM_MULTICAST + count);
/* set multicast addresses */
count = 0;
netdev_for_each_mc_addr(hw_adr, ndev) {
if (count == mc_cnt)
break;
ave_pfsel_set_macaddr(ndev, AVE_PFNUM_MULTICAST + count,
hw_adr->addr, 6);
count++;
}
}
}
static void ave_get_stats64(struct net_device *ndev,
struct rtnl_link_stats64 *stats)
{
struct ave_private *priv = netdev_priv(ndev);
unsigned int start;
do {
start = u64_stats_fetch_begin_irq(&priv->stats_rx.syncp);
stats->rx_packets = priv->stats_rx.packets;
stats->rx_bytes = priv->stats_rx.bytes;
} while (u64_stats_fetch_retry_irq(&priv->stats_rx.syncp, start));
do {
start = u64_stats_fetch_begin_irq(&priv->stats_tx.syncp);
stats->tx_packets = priv->stats_tx.packets;
stats->tx_bytes = priv->stats_tx.bytes;
} while (u64_stats_fetch_retry_irq(&priv->stats_tx.syncp, start));
stats->rx_errors = priv->stats_rx.errors;
stats->tx_errors = priv->stats_tx.errors;
stats->rx_dropped = priv->stats_rx.dropped;
stats->tx_dropped = priv->stats_tx.dropped;
stats->rx_fifo_errors = priv->stats_rx.fifo_errors;
stats->collisions = priv->stats_tx.collisions;
}
static int ave_set_mac_address(struct net_device *ndev, void *p)
{
int ret = eth_mac_addr(ndev, p);
if (ret)
return ret;
ave_macaddr_init(ndev);
return 0;
}
static const struct net_device_ops ave_netdev_ops = {
.ndo_init = ave_init,
.ndo_uninit = ave_uninit,
.ndo_open = ave_open,
.ndo_stop = ave_stop,
.ndo_start_xmit = ave_start_xmit,
.ndo_do_ioctl = ave_ioctl,
.ndo_set_rx_mode = ave_set_rx_mode,
.ndo_get_stats64 = ave_get_stats64,
.ndo_set_mac_address = ave_set_mac_address,
};
static int ave_probe(struct platform_device *pdev)
{
const struct ave_soc_data *data;
struct device *dev = &pdev->dev;
char buf[ETHTOOL_FWVERS_LEN];
phy_interface_t phy_mode;
struct ave_private *priv;
struct net_device *ndev;
struct device_node *np;
struct resource *res;
const void *mac_addr;
void __iomem *base;
u64 dma_mask;
int irq, ret;
u32 ave_id;
data = of_device_get_match_data(dev);
if (WARN_ON(!data))
return -EINVAL;
np = dev->of_node;
phy_mode = of_get_phy_mode(np);
if (phy_mode < 0) {
dev_err(dev, "phy-mode not found\n");
return -EINVAL;
}
if ((!phy_interface_mode_is_rgmii(phy_mode)) &&
phy_mode != PHY_INTERFACE_MODE_RMII &&
phy_mode != PHY_INTERFACE_MODE_MII) {
dev_err(dev, "phy-mode is invalid\n");
return -EINVAL;
}
irq = platform_get_irq(pdev, 0);
if (irq < 0) {
dev_err(dev, "IRQ not found\n");
return irq;
}
res = platform_get_resource(pdev, IORESOURCE_MEM, 0);
base = devm_ioremap_resource(dev, res);
if (IS_ERR(base))
return PTR_ERR(base);
ndev = alloc_etherdev(sizeof(struct ave_private));
if (!ndev) {
dev_err(dev, "can't allocate ethernet device\n");
return -ENOMEM;
}
ndev->netdev_ops = &ave_netdev_ops;
ndev->ethtool_ops = &ave_ethtool_ops;
SET_NETDEV_DEV(ndev, dev);
ndev->features |= (NETIF_F_IP_CSUM | NETIF_F_RXCSUM);
ndev->hw_features |= (NETIF_F_IP_CSUM | NETIF_F_RXCSUM);
ndev->max_mtu = AVE_MAX_ETHFRAME - (ETH_HLEN + ETH_FCS_LEN);
mac_addr = of_get_mac_address(np);
if (mac_addr)
ether_addr_copy(ndev->dev_addr, mac_addr);
/* if the mac address is invalid, use random mac address */
if (!is_valid_ether_addr(ndev->dev_addr)) {
eth_hw_addr_random(ndev);
dev_warn(dev, "Using random MAC address: %pM\n",
ndev->dev_addr);
}
priv = netdev_priv(ndev);
priv->base = base;
priv->irq = irq;
priv->ndev = ndev;
priv->msg_enable = netif_msg_init(-1, AVE_DEFAULT_MSG_ENABLE);
priv->phy_mode = phy_mode;
priv->data = data;
if (IS_DESC_64BIT(priv)) {
priv->desc_size = AVE_DESC_SIZE_64;
priv->tx.daddr = AVE_TXDM_64;
priv->rx.daddr = AVE_RXDM_64;
dma_mask = DMA_BIT_MASK(64);
} else {
priv->desc_size = AVE_DESC_SIZE_32;
priv->tx.daddr = AVE_TXDM_32;
priv->rx.daddr = AVE_RXDM_32;
dma_mask = DMA_BIT_MASK(32);
}
ret = dma_set_mask(dev, dma_mask);
if (ret)
goto out_free_netdev;
priv->tx.ndesc = AVE_NR_TXDESC;
priv->rx.ndesc = AVE_NR_RXDESC;
u64_stats_init(&priv->stats_tx.syncp);
u64_stats_init(&priv->stats_rx.syncp);
priv->clk = devm_clk_get(dev, NULL);
if (IS_ERR(priv->clk)) {
ret = PTR_ERR(priv->clk);
goto out_free_netdev;
}
priv->rst = devm_reset_control_get_optional_shared(dev, NULL);
if (IS_ERR(priv->rst)) {
ret = PTR_ERR(priv->rst);
goto out_free_netdev;
}
priv->mdio = devm_mdiobus_alloc(dev);
if (!priv->mdio) {
ret = -ENOMEM;
goto out_free_netdev;
}
priv->mdio->priv = ndev;
priv->mdio->parent = dev;
priv->mdio->read = ave_mdiobus_read;
priv->mdio->write = ave_mdiobus_write;
priv->mdio->name = "uniphier-mdio";
snprintf(priv->mdio->id, MII_BUS_ID_SIZE, "%s-%x",
pdev->name, pdev->id);
/* Register as a NAPI supported driver */
netif_napi_add(ndev, &priv->napi_rx, ave_napi_poll_rx, priv->rx.ndesc);
netif_tx_napi_add(ndev, &priv->napi_tx, ave_napi_poll_tx,
priv->tx.ndesc);
platform_set_drvdata(pdev, ndev);
ret = register_netdev(ndev);
if (ret) {
dev_err(dev, "failed to register netdevice\n");
goto out_del_napi;
}
/* get ID and version */
ave_id = readl(priv->base + AVE_IDR);
ave_hw_read_version(ndev, buf, sizeof(buf));
dev_info(dev, "Socionext %c%c%c%c Ethernet IP %s (irq=%d, phy=%s)\n",
(ave_id >> 24) & 0xff, (ave_id >> 16) & 0xff,
(ave_id >> 8) & 0xff, (ave_id >> 0) & 0xff,
buf, priv->irq, phy_modes(phy_mode));
return 0;
out_del_napi:
netif_napi_del(&priv->napi_rx);
netif_napi_del(&priv->napi_tx);
out_free_netdev:
free_netdev(ndev);
return ret;
}
static int ave_remove(struct platform_device *pdev)
{
struct net_device *ndev = platform_get_drvdata(pdev);
struct ave_private *priv = netdev_priv(ndev);
unregister_netdev(ndev);
netif_napi_del(&priv->napi_rx);
netif_napi_del(&priv->napi_tx);
free_netdev(ndev);
return 0;
}
static const struct ave_soc_data ave_pro4_data = {
.is_desc_64bit = false,
};
static const struct ave_soc_data ave_pxs2_data = {
.is_desc_64bit = false,
};
static const struct ave_soc_data ave_ld11_data = {
.is_desc_64bit = false,
};
static const struct ave_soc_data ave_ld20_data = {
.is_desc_64bit = true,
};
static const struct of_device_id of_ave_match[] = {
{
.compatible = "socionext,uniphier-pro4-ave4",
.data = &ave_pro4_data,
},
{
.compatible = "socionext,uniphier-pxs2-ave4",
.data = &ave_pxs2_data,
},
{
.compatible = "socionext,uniphier-ld11-ave4",
.data = &ave_ld11_data,
},
{
.compatible = "socionext,uniphier-ld20-ave4",
.data = &ave_ld20_data,
},
{ /* Sentinel */ }
};
MODULE_DEVICE_TABLE(of, of_ave_match);
static struct platform_driver ave_driver = {
.probe = ave_probe,
.remove = ave_remove,
.driver = {
.name = "ave",
.of_match_table = of_ave_match,
},
};
module_platform_driver(ave_driver);
MODULE_DESCRIPTION("Socionext UniPhier AVE ethernet driver");
MODULE_LICENSE("GPL v2");
| {
"pile_set_name": "Github"
} |
๏ปฟ
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Threading.Tasks;
using Blazui.Component;
namespace Blazui.ClientRenderWithSeo.Client.Demo.Table
{
public class AutoGenerateColumnTestData
{
[TableColumn(Text = "ๆถ้ด", Format = "yyyy-MM-dd")]
public DateTime Time { get; set; }
[TableColumn(Text = "ๅงๅ")]
public string Name { get; set; }
[TableColumn(Text = "ๅฐๅ")]
public string Address { get; set; }
[TableColumn(Text = "ๆฏ/ๅฆ")]
public bool Yes { get; set; }
}
}
| {
"pile_set_name": "Github"
} |
// Copyright Aleksey Gurtovoy 2000-2004
// Copyright Jaap Suter 2003
//
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//
// Preprocessed version of "boost/mpl/bitxor.hpp" header
// -- DO NOT modify by hand!
namespace boost { namespace mpl {
template<
typename Tag1
, typename Tag2
>
struct bitxor_impl
: if_c<
( BOOST_MPL_AUX_NESTED_VALUE_WKND(int, Tag1)
> BOOST_MPL_AUX_NESTED_VALUE_WKND(int, Tag2)
)
, aux::cast2nd_impl< bitxor_impl< Tag1,Tag1 >,Tag1, Tag2 >
, aux::cast1st_impl< bitxor_impl< Tag2,Tag2 >,Tag1, Tag2 >
>::type
{
};
/// for Digital Mars C++/compilers with no CTPS/TTP support
template<> struct bitxor_impl< na,na >
{
template< typename U1, typename U2 > struct apply
{
typedef apply type;
BOOST_STATIC_CONSTANT(int, value = 0);
};
};
template< typename Tag > struct bitxor_impl< na,Tag >
{
template< typename U1, typename U2 > struct apply
{
typedef apply type;
BOOST_STATIC_CONSTANT(int, value = 0);
};
};
template< typename Tag > struct bitxor_impl< Tag,na >
{
template< typename U1, typename U2 > struct apply
{
typedef apply type;
BOOST_STATIC_CONSTANT(int, value = 0);
};
};
template< typename T > struct bitxor_tag
{
typedef typename T::tag type;
};
template<
typename BOOST_MPL_AUX_NA_PARAM(N1)
, typename BOOST_MPL_AUX_NA_PARAM(N2)
, typename N3 = na, typename N4 = na, typename N5 = na
>
struct bitxor_
: bitxor_< bitxor_< bitxor_< bitxor_< N1,N2 >, N3>, N4>, N5>
{
BOOST_MPL_AUX_LAMBDA_SUPPORT(
5
, bitxor_
, ( N1, N2, N3, N4, N5 )
)
};
template<
typename N1, typename N2, typename N3, typename N4
>
struct bitxor_< N1,N2,N3,N4,na >
: bitxor_< bitxor_< bitxor_< N1,N2 >, N3>, N4>
{
BOOST_MPL_AUX_LAMBDA_SUPPORT_SPEC(
5
, bitxor_
, ( N1, N2, N3, N4, na )
)
};
template<
typename N1, typename N2, typename N3
>
struct bitxor_< N1,N2,N3,na,na >
: bitxor_< bitxor_< N1,N2 >, N3>
{
BOOST_MPL_AUX_LAMBDA_SUPPORT_SPEC(
5
, bitxor_
, ( N1, N2, N3, na, na )
)
};
template<
typename N1, typename N2
>
struct bitxor_< N1,N2,na,na,na >
: bitxor_impl<
typename bitxor_tag<N1>::type
, typename bitxor_tag<N2>::type
>::template apply< N1,N2 >::type
{
BOOST_MPL_AUX_LAMBDA_SUPPORT_SPEC(
5
, bitxor_
, ( N1, N2, na, na, na )
)
};
BOOST_MPL_AUX_NA_SPEC2(2, 5, bitxor_)
}}
namespace boost { namespace mpl {
template<>
struct bitxor_impl< integral_c_tag,integral_c_tag >
{
template< typename N1, typename N2 > struct apply
: integral_c<
typename aux::largest_int<
typename N1::value_type
, typename N2::value_type
>::type
, ( BOOST_MPL_AUX_VALUE_WKND(N1)::value
^ BOOST_MPL_AUX_VALUE_WKND(N2)::value
)
>
{
};
};
}}
| {
"pile_set_name": "Github"
} |
๏ปฟ<!DOCTYPE html>
<html lang="en" prefix="og: http://ogp.me/ns#">
<head>
<meta charset="UTF-8">
<title>Practice: ไฝใ - Lesson 8 | Genki Study Resources - 2nd Edition</title>
<meta name="title" content="Practice: ไฝใ - Lesson 8 | Genki Study Resources - 2nd Edition">
<meta name="twitter:title" content="Practice: ไฝใ - Lesson 8 | Genki Study Resources - 2nd Edition">
<meta property="og:title" content="Practice: ไฝใ - Lesson 8 | Genki Study Resources - 2nd Edition">
<meta name="description" content="You went to a party but did nothing there. Make sentences using the cues.">
<meta property="og:description" content="You went to a party but did nothing there. Make sentences using the cues.">
<link rel="shortcut icon" type="image/x-icon" href="../../../resources/images/genkico.ico">
<meta name="keywords" content="Genki I, page 204, problem VIII-A, japanese, quizzes, exercises, 2nd Edition" lang="en">
<meta name="language" content="en">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta property="og:site_name" content="sethclydesdale.github.io">
<meta property="og:url" content="https://sethclydesdale.github.io/genki-study-resources/lessons/lesson-8/grammar-12/">
<meta property="og:type" content="website">
<meta property="og:image" content="https://sethclydesdale.github.io/genki-study-resources/resources/images/genki-thumb.png">
<meta name="twitter:card" content="summary">
<meta name="twitter:creator" content="@SethC1995">
<link rel="stylesheet" href="../../../resources/css/stylesheet.min.css">
<script src="../../../resources/javascript/head.min.js"></script>
<script src="../../../resources/javascript/ga.js" async></script>
</head>
<body>
<header>
<h1><a href="../../../" id="home-link" class="edition-icon second-ed">Genki Study Resources</a></h1>
<a id="fork-me" href="https://github.com/SethClydesdale/genki-study-resources">Fork Me</a>
</header>
<div id="content">
<div id="exercise" class="content-block">
<div id="quiz-result"></div>
<div id="quiz-zone" class="clear"></div>
<div id="quiz-timer" class="center"></div>
</div>
</div>
<footer class="clear">
<ul class="footer-left">
<li><a href="../../../" id="footer-home">Home</a></li>
<li><a href="../../../privacy/">Privacy</a></li>
<li><a href="../../../report/">Report a Bug</a></li>
<li><a href="../../../help/">Help</a></li>
<li><a href="../../../donate/">Donate</a></li>
</ul>
<ul class="footer-right">
<li>Created by <a href="https://github.com/SethClydesdale">Seth Clydesdale</a> and the <a href="https://github.com/SethClydesdale/genki-study-resources/graphs/contributors">GitHub Community</a></li>
</ul>
</footer>
<script src="../../../resources/javascript/dragula.min.js"></script>
<script src="../../../resources/javascript/easytimer.min.js"></script>
<script src="../../../resources/javascript/exercises/2nd-ed.min.js"></script>
<script src="../../../resources/javascript/genki.min.js"></script>
<script src="../../../resources/javascript/all.min.js"></script>
<script>Genki.generateQuiz({
type : 'multi',
info : 'You went to a party but did nothing there. Make sentences using the cues.',
quizlet : [
{
question : 'ใใผใใฃใผใซ่กใใพใใใใ(eat)',
answers : [
'Aใใผใใฃใผใซ่กใใพใใใใไฝใ้ฃในใพใใใงใใใ',
'ใใผใใฃใผใซ่กใใพใใใใไฝใ้ฃในใพใใใงใใใ',
'ใใผใใฃใผใซ่กใใพใใใใไฝใ้ฃในใพใใใงใใใ'
]
},
{
question : 'ใใผใใฃใผใซ่กใใพใใใใ(drink)',
answers : [
'Aใใผใใฃใผใซ่กใใพใใใใไฝใ้ฃฒใฟใพใใใงใใใ',
'ใใผใใฃใผใซ่กใใพใใใใไฝใ้ฃฒใฟใพใใใงใใใ',
'ใใผใใฃใผใซ่กใใพใใใใไฝใ้ฃฒใฟใพใใใงใใใ'
]
},
{
question : 'ใซใฉใชใฑใใใใพใใใใ(sing)',
answers : [
'Aใซใฉใชใฑใใใใพใใใใไฝใๆญใใพใใใงใใใ',
'ใซใฉใชใฑใใใใพใใใใไฝใๆญใใพใใใงใใใ',
'ใซใฉใชใฑใใใใพใใใใไฝใๆญใใพใใใงใใใ'
]
},
{
question : 'ใใฌใใใใใพใใใใ(watch)',
answers : [
'Aใใฌใใใใใพใใใใไฝใ่ฆใพใใใงใใใ',
'ใใฌใใใใใพใใใใไฝใ่ฆใพใใใงใใใ',
'ใใฌใใใใใพใใใใไฝใ่ฆใพใใใงใใใ'
]
},
{
question : 'ใซใกใฉใๆใฃใฆใใพใใใใ(take)',
answers : [
'Aใซใกใฉใๆใฃใฆใใพใใใใไฝใๆฎใใพใใใงใใใ',
'ใซใกใฉใๆใฃใฆใใพใใใใไฝใๆฎใใพใใใงใใใ',
'ใซใกใฉใๆใฃใฆใใพใใใใไฝใๆฎใใพใใใงใใใ'
]
},
{
question : 'ใใฟใใใซไผใใพใใใใ(talk)',
answers : [
'Aใใฟใใใซไผใใพใใใใไฝใ่ฉฑใใพใใใงใใใ',
'ใใฟใใใซไผใใพใใใใไฝใ่ฉฑใใพใใใงใใใ',
'ใใฟใใใซไผใใพใใใใไฝใ่ฉฑใใพใใใงใใใ'
]
},
{
question : 'ใใผใใฃใผใซ่กใใพใใใใ(do)',
answers : [
'Aใใผใใฃใผใซ่กใใพใใใใไฝใใใพใใใงใใใ',
'ใใผใใฃใผใซ่กใใพใใใใไฝใใใพใใใงใใใ',
'ใใผใใฃใผใซ่กใใพใใใใไฝใใใพใใใงใใใ'
]
}
]
});</script>
</body>
</html> | {
"pile_set_name": "Github"
} |
#!/usr/bin/perl
$file = $ARGV[0];
open(IN,$file) || die print "Failed to open file: $file : $!";
read(IN,$buffer,1);
read(IN,$buffer2,1);
if (ord($buffer) != 0x41 && ord($buffer2) != 0x50) {
print "bad header ". $buffer ." ".$buffer2. "\n";
exit;
}
read(IN,$buffer,1);
if (ord($buffer) != 2) {
print "bad version";
exit;
}
# spare
read(IN,$buffer,1);
$a = 0;
while (read(IN,$buffer,1)) {
$pos = (tell(IN) - 1);
$size = ((ord($buffer) & 63));
read(IN,$buffer,1);
if (ord($buffer) == 0xff) {
printf("end sentinel at %u\n", $pos);
last;
}
printf("%04x: key %u size %d\n ", $pos, ord($buffer), $size + 1);
for ($i = 0; $i <= ($size); $i++) {
read(IN,$buffer,1);
printf(" %02x", ord($buffer));
}
print "\n";
}
close IN; | {
"pile_set_name": "Github"
} |
{
"kind": "Template",
"apiVersion": "v1",
"metadata": {
"name": "mariadb-ephemeral",
"creationTimestamp": null,
"annotations": {
"description": "MariaDB database service, without persistent storage. For more information about using this template, including OpenShift considerations, see https://github.com/sclorg/mariadb-container/blob/master/10.3/root/usr/share/container-scripts/mysql/README.md.\n\nWARNING: Any data stored will be lost upon pod destruction. Only use this template for testing",
"iconClass": "icon-mariadb",
"openshift.io/display-name": "MariaDB (Ephemeral)",
"openshift.io/documentation-url": "https://github.com/sclorg/mariadb-container/blob/master/10.3/root/usr/share/container-scripts/mysql/README.md",
"openshift.io/long-description": "This template provides a standalone MariaDB server with a database created. The database is not stored on persistent storage, so any restart of the service will result in all data being lost. The database name, username, and password are chosen via parameters when provisioning this service.",
"openshift.io/provider-display-name": "Red Hat, Inc.",
"openshift.io/support-url": "https://access.redhat.com",
"tags": "database,mariadb"
}
},
"message": "The following service(s) have been created in your project: ${DATABASE_SERVICE_NAME}.\n\n Username: ${MYSQL_USER}\n Password: ${MYSQL_PASSWORD}\n Database Name: ${MYSQL_DATABASE}\n Connection URL: mysql://${DATABASE_SERVICE_NAME}:3306/\n\nFor more information about using this template, including OpenShift considerations, see https://github.com/sclorg/mariadb-container/blob/master/10.3/root/usr/share/container-scripts/mysql/README.md.",
"objects": [
{
"apiVersion": "v1",
"kind": "Secret",
"metadata": {
"annotations": {
"template.openshift.io/expose-database_name": "{.data['database-name']}",
"template.openshift.io/expose-password": "{.data['database-password']}",
"template.openshift.io/expose-root_password": "{.data['database-root-password']}",
"template.openshift.io/expose-username": "{.data['database-user']}"
},
"name": "${DATABASE_SERVICE_NAME}"
},
"stringData": {
"database-name": "${MYSQL_DATABASE}",
"database-password": "${MYSQL_PASSWORD}",
"database-root-password": "${MYSQL_ROOT_PASSWORD}",
"database-user": "${MYSQL_USER}"
}
},
{
"apiVersion": "v1",
"kind": "Service",
"metadata": {
"annotations": {
"template.openshift.io/expose-uri": "mysql://{.spec.clusterIP}:{.spec.ports[?(.name==\"mariadb\")].port}"
},
"name": "${DATABASE_SERVICE_NAME}"
},
"spec": {
"ports": [
{
"name": "mariadb",
"port": 3306
}
],
"selector": {
"name": "${DATABASE_SERVICE_NAME}"
}
}
},
{
"apiVersion": "v1",
"kind": "DeploymentConfig",
"metadata": {
"annotations": {
"template.alpha.openshift.io/wait-for-ready": "true"
},
"name": "${DATABASE_SERVICE_NAME}"
},
"spec": {
"replicas": 1,
"selector": {
"name": "${DATABASE_SERVICE_NAME}"
},
"strategy": {
"type": "Recreate"
},
"template": {
"metadata": {
"labels": {
"name": "${DATABASE_SERVICE_NAME}"
}
},
"spec": {
"containers": [
{
"env": [
{
"name": "MYSQL_USER",
"valueFrom": {
"secretKeyRef": {
"key": "database-user",
"name": "${DATABASE_SERVICE_NAME}"
}
}
},
{
"name": "MYSQL_PASSWORD",
"valueFrom": {
"secretKeyRef": {
"key": "database-password",
"name": "${DATABASE_SERVICE_NAME}"
}
}
},
{
"name": "MYSQL_ROOT_PASSWORD",
"valueFrom": {
"secretKeyRef": {
"key": "database-root-password",
"name": "${DATABASE_SERVICE_NAME}"
}
}
},
{
"name": "MYSQL_DATABASE",
"valueFrom": {
"secretKeyRef": {
"key": "database-name",
"name": "${DATABASE_SERVICE_NAME}"
}
}
}
],
"image": " ",
"imagePullPolicy": "IfNotPresent",
"livenessProbe": {
"exec": {
"command": [
"/bin/sh",
"-i",
"-c",
"MYSQL_PWD=\"$MYSQL_PASSWORD\" mysqladmin -u $MYSQL_USER ping"
]
},
"initialDelaySeconds": 30,
"timeoutSeconds": 1
},
"name": "mariadb",
"ports": [
{
"containerPort": 3306
}
],
"readinessProbe": {
"exec": {
"command": [
"/bin/sh",
"-i",
"-c",
"MYSQL_PWD=\"$MYSQL_PASSWORD\" mysqladmin -u $MYSQL_USER ping"
]
},
"initialDelaySeconds": 5,
"timeoutSeconds": 1
},
"resources": {
"limits": {
"memory": "${MEMORY_LIMIT}"
}
},
"volumeMounts": [
{
"mountPath": "/var/lib/mysql/data",
"name": "${DATABASE_SERVICE_NAME}-data"
}
]
}
],
"volumes": [
{
"emptyDir": {
"medium": ""
},
"name": "${DATABASE_SERVICE_NAME}-data"
}
]
}
},
"triggers": [
{
"imageChangeParams": {
"automatic": true,
"containerNames": [
"mariadb"
],
"from": {
"kind": "ImageStreamTag",
"name": "mariadb:${MARIADB_VERSION}",
"namespace": "${NAMESPACE}"
}
},
"type": "ImageChange"
},
{
"type": "ConfigChange"
}
]
}
}
],
"parameters": [
{
"name": "MEMORY_LIMIT",
"displayName": "Memory Limit",
"description": "Maximum amount of memory the container can use.",
"value": "512Mi",
"required": true
},
{
"name": "NAMESPACE",
"displayName": "Namespace",
"description": "The OpenShift Namespace where the ImageStream resides.",
"value": "openshift"
},
{
"name": "DATABASE_SERVICE_NAME",
"displayName": "Database Service Name",
"description": "The name of the OpenShift Service exposed for the database.",
"value": "mariadb",
"required": true
},
{
"name": "MYSQL_USER",
"displayName": "MariaDB Connection Username",
"description": "Username for MariaDB user that will be used for accessing the database.",
"generate": "expression",
"from": "user[A-Z0-9]{3}",
"required": true
},
{
"name": "MYSQL_PASSWORD",
"displayName": "MariaDB Connection Password",
"description": "Password for the MariaDB connection user.",
"generate": "expression",
"from": "[a-zA-Z0-9]{16}",
"required": true
},
{
"name": "MYSQL_ROOT_PASSWORD",
"displayName": "MariaDB root Password",
"description": "Password for the MariaDB root user.",
"generate": "expression",
"from": "[a-zA-Z0-9]{16}",
"required": true
},
{
"name": "MYSQL_DATABASE",
"displayName": "MariaDB Database Name",
"description": "Name of the MariaDB database accessed.",
"value": "sampledb",
"required": true
},
{
"name": "MARIADB_VERSION",
"displayName": "Version of MariaDB Image",
"description": "Version of MariaDB image to be used (10.3-el7, 10.3-el8, or latest).",
"value": "10.3-el8",
"required": true
}
],
"labels": {
"template": "mariadb-ephemeral-template"
}
} | {
"pile_set_name": "Github"
} |
// Copyright 2020 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.androidbrowserhelper.playbilling.provider;
import android.app.Activity;
import com.android.billingclient.api.SkuDetails;
import com.android.billingclient.api.SkuDetailsResponseListener;
import java.util.List;
/**
* Wraps communication with Play Billing to provide a simpler interface and allowing mocking in
* tests.
*/
interface BillingWrapper {
/**
* Callbacks for connection state and for purchase flow completion.
*/
interface Listener {
/** Will be called when connected to the Play Billing client. */
void onConnected();
/** Will be called when the Play Billing client disconnects. */
void onDisconnected();
/** Will be called after a call to {@link #launchPaymentFlow} that returns {@code true}. */
void onPurchaseFlowComplete(int result);
}
/** Connect to the Play Billing client. */
void connect();
/**
* Get {@link SkuDetails} objects for the provided SKUs.
*/
void querySkuDetails(List<String> skus, SkuDetailsResponseListener callback);
/**
* Launches the Payment Flow. If it returns {@code true},
* {@link Listener#onPurchaseFlowComplete} should be called.
*/
boolean launchPaymentFlow(Activity activity, SkuDetails sku);
}
| {
"pile_set_name": "Github"
} |
import * as lpn from 'google-libphonenumber';
/*
We use "control: any" instead of "control: FormControl" to silence:
"Property 'nativeElement' does not exist on type 'FormControl'".
This happens because I've expanded control with nativeElement via
'NativeElementInjectorDirective' to get an access to the element.
More about this approach and reasons for this:
https://github.com/angular/angular/issues/18025
https://stackoverflow.com/a/54075119/1617590
*/
export const phoneNumberValidator = (control: any) => {
if (!control.value) {
return;
}
// Find <input> inside injected nativeElement and get its "id".
const el: HTMLElement = control.nativeElement as HTMLElement;
const inputBox: HTMLInputElement = el
? el.querySelector('input[type="tel"]')
: undefined;
if (inputBox) {
const id = inputBox.id;
const isCheckValidation = inputBox.getAttribute('validation');
if (isCheckValidation === 'true') {
const isRequired = control.errors && control.errors.required === true;
const error = { validatePhoneNumber: { valid: false } };
inputBox.setCustomValidity('Invalid field.');
let number: lpn.PhoneNumber;
try {
number = lpn.PhoneNumberUtil.getInstance().parse(
control.value.number,
control.value.countryCode
);
} catch (e) {
if (isRequired === true) {
return error;
} else {
inputBox.setCustomValidity('');
}
}
if (control.value) {
if (!number) {
return error;
} else {
if (
!lpn.PhoneNumberUtil.getInstance().isValidNumberForRegion(
number,
control.value.countryCode
)
) {
return error;
} else {
inputBox.setCustomValidity('');
}
}
}
} else if (isCheckValidation === 'false') {
inputBox.setCustomValidity('');
control.clearValidators();
}
}
return;
};
| {
"pile_set_name": "Github"
} |
/*
* Copyright (C) 2004-2020 ZNC, see the NOTICE file for details.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
//! @author [email protected]
//
// The encryption here was designed to be compatible with mircryption's CBC
// mode.
//
// Latest tested against:
// MircryptionSuite - Mircryption ver 1.19.01 (dll v1.15.01 , mirc v7.32) CBC
// loaded and ready.
//
// TODO:
//
// 1) Encrypt key storage file
// 2) Some way of notifying the user that the current channel is in "encryption
// mode" verses plain text
// 3) Temporarily disable a target (nick/chan)
//
// NOTE: This module is currently NOT intended to secure you from your shell
// admin.
// The keys are currently stored in plain text, so anyone with access to
// your account (or root) can obtain them.
// It is strongly suggested that you enable SSL between ZNC and your
// client otherwise the encryption stops at ZNC and gets sent to your
// client in plain text.
//
#include <openssl/bn.h>
#include <openssl/dh.h>
#include <znc/Chan.h>
#include <znc/IRCNetwork.h>
#include <znc/SHA256.h>
#include <znc/User.h>
#define REQUIRESSL 1
// To be removed in future versions
#define NICK_PREFIX_OLD_KEY "[nick-prefix]"
#define NICK_PREFIX_KEY "@nick-prefix@"
class CCryptMod : public CModule {
private:
/*
* As used in other implementations like KVIrc, fish10, Quassel, FiSH-irssi,
* ... all the way back to the original located at
* http://mircryption.sourceforge.net/Extras/McpsFishDH.zip
*/
static constexpr const char* m_sPrime1080 =
"FBE1022E23D213E8ACFA9AE8B9DFADA3EA6B7AC7A7B7E95AB5EB2DF858921FEADE95E6"
"AC7BE7DE6ADBAB8A783E7AF7A7FA6A2B7BEB1E72EAE2B72F9FA2BFB2A2EFBEFAC868BA"
"DB3E828FA8BADFADA3E4CC1BE7E8AFE85E9698A783EB68FA07A77AB6AD7BEB618ACF9C"
"A2897EB28A6189EFA07AB99A8A7FA9AE299EFA7BA66DEAFEFBEFBF0B7D8B";
/* Generate our keys once and reuse, just like ssh keys */
std::unique_ptr<DH, decltype(&DH_free)> m_pDH;
CString m_sPrivKey;
CString m_sPubKey;
#if OPENSSL_VERSION_NUMBER < 0X10100000L || defined(LIBRESSL_VERSION_NUMBER)
static int DH_set0_pqg(DH* dh, BIGNUM* p, BIGNUM* q, BIGNUM* g) {
/* If the fields p and g in dh are nullptr, the corresponding input
* parameters MUST be non-nullptr. q may remain nullptr.
*/
if (dh == nullptr || (dh->p == nullptr && p == nullptr) ||
(dh->g == nullptr && g == nullptr))
return 0;
if (p != nullptr) {
BN_free(dh->p);
dh->p = p;
}
if (g != nullptr) {
BN_free(dh->g);
dh->g = g;
}
if (q != nullptr) {
BN_free(dh->q);
dh->q = q;
dh->length = BN_num_bits(q);
}
return 1;
}
static void DH_get0_key(const DH* dh, const BIGNUM** pub_key,
const BIGNUM** priv_key) {
if (dh != nullptr) {
if (pub_key != nullptr) *pub_key = dh->pub_key;
if (priv_key != nullptr) *priv_key = dh->priv_key;
}
}
#endif
bool DH1080_gen() {
/* Generate our keys on first call */
if (m_sPrivKey.empty() || m_sPubKey.empty()) {
int len;
const BIGNUM* bPrivKey = nullptr;
const BIGNUM* bPubKey = nullptr;
BIGNUM* bPrime = nullptr;
BIGNUM* bGen = nullptr;
if (!BN_hex2bn(&bPrime, m_sPrime1080) || !BN_dec2bn(&bGen, "2") ||
!DH_set0_pqg(m_pDH.get(), bPrime, nullptr, bGen) ||
!DH_generate_key(m_pDH.get())) {
/* one of them failed */
if (bPrime != nullptr) BN_clear_free(bPrime);
if (bGen != nullptr) BN_clear_free(bGen);
return false;
}
/* Get our keys */
DH_get0_key(m_pDH.get(), &bPubKey, &bPrivKey);
/* Get our private key */
len = BN_num_bytes(bPrivKey);
m_sPrivKey.resize(len);
BN_bn2bin(bPrivKey, (unsigned char*)m_sPrivKey.data());
m_sPrivKey.Base64Encode();
/* Get our public key */
len = BN_num_bytes(bPubKey);
m_sPubKey.resize(len);
BN_bn2bin(bPubKey, (unsigned char*)m_sPubKey.data());
m_sPubKey.Base64Encode();
}
return true;
}
bool DH1080_comp(CString& sOtherPubKey, CString& sSecretKey) {
long len;
unsigned char* key = nullptr;
BIGNUM* bOtherPubKey = nullptr;
/* Prepare other public key */
len = sOtherPubKey.Base64Decode();
bOtherPubKey =
BN_bin2bn((unsigned char*)sOtherPubKey.data(), len, nullptr);
/* Generate secret key */
key = (unsigned char*)calloc(DH_size(m_pDH.get()), 1);
if ((len = DH_compute_key(key, bOtherPubKey, m_pDH.get())) == -1) {
sSecretKey = "";
if (bOtherPubKey != nullptr) BN_clear_free(bOtherPubKey);
if (key != nullptr) free(key);
return false;
}
/* Get our secret key */
sSecretKey.resize(SHA256_DIGEST_SIZE);
sha256(key, len, (unsigned char*)sSecretKey.data());
sSecretKey.Base64Encode();
sSecretKey.TrimRight("=");
if (bOtherPubKey != nullptr) BN_clear_free(bOtherPubKey);
if (key != nullptr) free(key);
return true;
}
CString NickPrefix() {
MCString::iterator it = FindNV(NICK_PREFIX_KEY);
/*
* Check for different Prefixes to not confuse modules with nicknames
* Also check for overlap for rare cases like:
* SP = "*"; NP = "*s"; "tatus" sends an encrypted message appearing at
* "*status"
*/
CString sStatusPrefix = GetUser()->GetStatusPrefix();
if (it != EndNV()) {
size_t sp = sStatusPrefix.size();
size_t np = it->second.size();
int min = std::min(sp, np);
if (min == 0 || sStatusPrefix.CaseCmp(it->second, min) != 0)
return it->second;
}
return sStatusPrefix.StartsWith("*") ? "." : "*";
}
public:
/* MODCONSTRUCTOR(CLASS) is of form "CLASS(...) : CModule(...)" */
MODCONSTRUCTOR(CCryptMod), m_pDH(DH_new(), DH_free) {
AddHelpCommand();
AddCommand("DelKey", t_d("<#chan|Nick>"),
t_d("Remove a key for nick or channel"),
[=](const CString& sLine) { OnDelKeyCommand(sLine); });
AddCommand("SetKey", t_d("<#chan|Nick> <Key>"),
t_d("Set a key for nick or channel"),
[=](const CString& sLine) { OnSetKeyCommand(sLine); });
AddCommand("ListKeys", "", t_d("List all keys"),
[=](const CString& sLine) { OnListKeysCommand(sLine); });
AddCommand("KeyX", t_d("<Nick>"),
t_d("Start a DH1080 key exchange with nick"),
[=](const CString& sLine) { OnKeyXCommand(sLine); });
AddCommand(
"GetNickPrefix", "", t_d("Get the nick prefix"),
[=](const CString& sLine) { OnGetNickPrefixCommand(sLine); });
AddCommand(
"SetNickPrefix", t_d("[Prefix]"),
t_d("Set the nick prefix, with no argument it's disabled."),
[=](const CString& sLine) { OnSetNickPrefixCommand(sLine); });
}
bool OnLoad(const CString& sArgsi, CString& sMessage) override {
MCString::iterator it = FindNV(NICK_PREFIX_KEY);
if (it == EndNV()) {
/* Don't have the new prefix key yet */
it = FindNV(NICK_PREFIX_OLD_KEY);
if (it != EndNV()) {
SetNV(NICK_PREFIX_KEY, it->second);
DelNV(NICK_PREFIX_OLD_KEY);
}
}
return true;
}
EModRet OnUserTextMessage(CTextMessage& Message) override {
FilterOutgoing(Message);
return CONTINUE;
}
EModRet OnUserNoticeMessage(CNoticeMessage& Message) override {
FilterOutgoing(Message);
return CONTINUE;
}
EModRet OnUserActionMessage(CActionMessage& Message) override {
FilterOutgoing(Message);
return CONTINUE;
}
EModRet OnUserTopicMessage(CTopicMessage& Message) override {
FilterOutgoing(Message);
return CONTINUE;
}
EModRet OnPrivMsg(CNick& Nick, CString& sMessage) override {
FilterIncoming(Nick.GetNick(), Nick, sMessage);
return CONTINUE;
}
EModRet OnPrivNotice(CNick& Nick, CString& sMessage) override {
CString sCommand = sMessage.Token(0);
CString sOtherPubKey = sMessage.Token(1);
if ((sCommand.Equals("DH1080_INIT") ||
sCommand.Equals("DH1080_INIT_CBC")) &&
!sOtherPubKey.empty()) {
CString sSecretKey;
CString sTail = sMessage.Token(2); /* For fish10 */
/* remove trailing A */
if (sOtherPubKey.TrimSuffix("A") && DH1080_gen() &&
DH1080_comp(sOtherPubKey, sSecretKey)) {
PutModule(
t_f("Received DH1080 public key from {1}, sending mine...")(
Nick.GetNick()));
PutIRC("NOTICE " + Nick.GetNick() + " :DH1080_FINISH " +
m_sPubKey + "A" + (sTail.empty() ? "" : (" " + sTail)));
SetNV(Nick.GetNick().AsLower(), sSecretKey);
PutModule(t_f("Key for {1} successfully set.")(Nick.GetNick()));
return HALT;
}
PutModule(t_f("Error in {1} with {2}: {3}")(
sCommand, Nick.GetNick(),
(sSecretKey.empty() ? t_s("no secret key computed")
: sSecretKey)));
return CONTINUE;
} else if (sCommand.Equals("DH1080_FINISH") && !sOtherPubKey.empty()) {
/*
* In theory we could get a DH1080_FINISH without us having sent a
* DH1080_INIT first, but then to have any use for the other user,
* they'd already have our pub key
*/
CString sSecretKey;
/* remove trailing A */
if (sOtherPubKey.TrimSuffix("A") && DH1080_gen() &&
DH1080_comp(sOtherPubKey, sSecretKey)) {
SetNV(Nick.GetNick().AsLower(), sSecretKey);
PutModule(t_f("Key for {1} successfully set.")(Nick.GetNick()));
return HALT;
}
PutModule(t_f("Error in {1} with {2}: {3}")(
sCommand, Nick.GetNick(),
(sSecretKey.empty() ? t_s("no secret key computed")
: sSecretKey)));
return CONTINUE;
}
FilterIncoming(Nick.GetNick(), Nick, sMessage);
return CONTINUE;
}
EModRet OnPrivAction(CNick& Nick, CString& sMessage) override {
FilterIncoming(Nick.GetNick(), Nick, sMessage);
return CONTINUE;
}
EModRet OnChanMsg(CNick& Nick, CChan& Channel, CString& sMessage) override {
FilterIncoming(Channel.GetName(), Nick, sMessage);
return CONTINUE;
}
EModRet OnChanNotice(CNick& Nick, CChan& Channel,
CString& sMessage) override {
FilterIncoming(Channel.GetName(), Nick, sMessage);
return CONTINUE;
}
EModRet OnChanAction(CNick& Nick, CChan& Channel,
CString& sMessage) override {
FilterIncoming(Channel.GetName(), Nick, sMessage);
return CONTINUE;
}
EModRet OnTopic(CNick& Nick, CChan& Channel, CString& sMessage) override {
FilterIncoming(Channel.GetName(), Nick, sMessage);
return CONTINUE;
}
EModRet OnNumericMessage(CNumericMessage& Message) override {
if (Message.GetCode() != 332) {
return CONTINUE;
}
CChan* pChan = GetNetwork()->FindChan(Message.GetParam(1));
if (pChan) {
CNick* Nick = pChan->FindNick(Message.GetParam(0));
CString sTopic = Message.GetParam(2);
FilterIncoming(pChan->GetName(), *Nick, sTopic);
Message.SetParam(2, sTopic);
}
return CONTINUE;
}
template <typename T>
void FilterOutgoing(T& Msg) {
CString sTarget = Msg.GetTarget();
sTarget.TrimPrefix(NickPrefix());
Msg.SetTarget(sTarget);
CString sMessage = Msg.GetText();
if (sMessage.TrimPrefix("``")) {
return;
}
MCString::iterator it = FindNV(sTarget.AsLower());
if (it != EndNV()) {
sMessage = MakeIvec() + sMessage;
sMessage.Encrypt(it->second);
sMessage.Base64Encode();
Msg.SetText("+OK *" + sMessage);
}
}
void FilterIncoming(const CString& sTarget, CNick& Nick,
CString& sMessage) {
if (sMessage.TrimPrefix("+OK *")) {
MCString::iterator it = FindNV(sTarget.AsLower());
if (it != EndNV()) {
sMessage.Base64Decode();
sMessage.Decrypt(it->second);
sMessage.LeftChomp(8);
sMessage = sMessage.c_str();
Nick.SetNick(NickPrefix() + Nick.GetNick());
}
}
}
void OnDelKeyCommand(const CString& sCommand) {
CString sTarget = sCommand.Token(1);
if (!sTarget.empty()) {
if (DelNV(sTarget.AsLower())) {
PutModule(t_f("Target [{1}] deleted")(sTarget));
} else {
PutModule(t_f("Target [{1}] not found")(sTarget));
}
} else {
PutModule(t_s("Usage DelKey <#chan|Nick>"));
}
}
void OnSetKeyCommand(const CString& sCommand) {
CString sTarget = sCommand.Token(1);
CString sKey = sCommand.Token(2, true);
// Strip "cbc:" from beginning of string incase someone pastes directly
// from mircryption
sKey.TrimPrefix("cbc:");
if (!sKey.empty()) {
SetNV(sTarget.AsLower(), sKey);
PutModule(
t_f("Set encryption key for [{1}] to [{2}]")(sTarget, sKey));
} else {
PutModule(t_s("Usage: SetKey <#chan|Nick> <Key>"));
}
}
void OnKeyXCommand(const CString& sCommand) {
CString sTarget = sCommand.Token(1);
if (!sTarget.empty()) {
if (DH1080_gen()) {
PutIRC("NOTICE " + sTarget + " :DH1080_INIT " + m_sPubKey +
"A");
PutModule(t_f("Sent my DH1080 public key to {1}, waiting for reply ...")(sTarget));
} else {
PutModule(t_s("Error generating our keys, nothing sent."));
}
} else {
PutModule(t_s("Usage: KeyX <Nick>"));
}
}
void OnGetNickPrefixCommand(const CString& sCommand) {
CString sPrefix = NickPrefix();
if (sPrefix.empty()) {
PutModule(t_s("Nick Prefix disabled."));
} else {
PutModule(t_f("Nick Prefix: {1}")(sPrefix));
}
}
void OnSetNickPrefixCommand(const CString& sCommand) {
CString sPrefix = sCommand.Token(1);
if (sPrefix.StartsWith(":")) {
PutModule(
t_s("You cannot use :, even followed by other symbols, as Nick "
"Prefix."));
} else {
CString sStatusPrefix = GetUser()->GetStatusPrefix();
size_t sp = sStatusPrefix.size();
size_t np = sPrefix.size();
int min = std::min(sp, np);
if (min > 0 && sStatusPrefix.CaseCmp(sPrefix, min) == 0)
PutModule(
t_f("Overlap with Status Prefix ({1}), this Nick Prefix "
"will not be used!")(sStatusPrefix));
else {
SetNV(NICK_PREFIX_KEY, sPrefix);
if (sPrefix.empty())
PutModule(t_s("Disabling Nick Prefix."));
else
PutModule(t_f("Setting Nick Prefix to {1}")(sPrefix));
}
}
}
void OnListKeysCommand(const CString& sCommand) {
CTable Table;
Table.AddColumn(t_s("Target", "listkeys"));
Table.AddColumn(t_s("Key", "listkeys"));
Table.SetStyle(CTable::ListStyle);
for (MCString::iterator it = BeginNV(); it != EndNV(); ++it) {
if (!it->first.Equals(NICK_PREFIX_KEY)) {
Table.AddRow();
Table.SetCell(t_s("Target", "listkeys"), it->first);
Table.SetCell(t_s("Key", "listkeys"), it->second);
}
}
if (Table.empty())
PutModule(t_s("You have no encryption keys set."));
else
PutModule(Table);
}
CString MakeIvec() {
CString sRet;
time_t t;
time(&t);
int r = rand();
sRet.append((char*)&t, 4);
sRet.append((char*)&r, 4);
return sRet;
}
};
template <>
void TModInfo<CCryptMod>(CModInfo& Info) {
Info.SetWikiPage("crypt");
}
NETWORKMODULEDEFS(CCryptMod, t_s("Encryption for channel/private messages"))
| {
"pile_set_name": "Github"
} |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
//
// TIFF Codec class testing unit
//
// Authors:
// Jordi Mas i Hern?ndez ([email protected])
// Sebastien Pouliot <[email protected]>
//
// Copyright (C) 2006, 2007 Novell, Inc (http://www.novell.com)
//
// 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.
//
using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using Xunit;
namespace MonoTests.System.Drawing.Imaging
{
public class TiffCodecTest
{
/* Checks bitmap features on a known 32bbp bitmap */
[ConditionalFact(Helpers.IsDrawingSupported)]
public void Bitmap32bitsFeatures()
{
string sInFile = Helpers.GetTestBitmapPath("almogaver32bits.tif");
using (Bitmap bmp = new Bitmap(sInFile))
{
GraphicsUnit unit = GraphicsUnit.World;
RectangleF rect = bmp.GetBounds(ref unit);
// MS reports 24 bpp while we report 32 bpp
// Assert.Equal (PixelFormat.Format24bppRgb, bmp.PixelFormat);
Assert.Equal(173, bmp.Width);
Assert.Equal(183, bmp.Height);
Assert.Equal(0, rect.X);
Assert.Equal(0, rect.Y);
Assert.Equal(173, rect.Width);
Assert.Equal(183, rect.Height);
Assert.Equal(173, bmp.Size.Width);
Assert.Equal(183, bmp.Size.Height);
}
}
/* Checks bitmap features on a known 32bbp bitmap */
[ConditionalFact(Helpers.IsDrawingSupported)]
[ActiveIssue("https://github.com/dotnet/runtime/issues/22221", TestPlatforms.AnyUnix)]
public void Bitmap32bitsPixelFormat()
{
string sInFile = Helpers.GetTestBitmapPath("almogaver32bits.tif");
using (Bitmap bmp = new Bitmap(sInFile))
{
// GDI+ reports 24 bpp while libgdiplus reports 32 bpp
Assert.Equal (PixelFormat.Format24bppRgb, bmp.PixelFormat);
}
}
[ConditionalFact(Helpers.IsDrawingSupported)]
public void Bitmap32bitsPixels()
{
string sInFile = Helpers.GetTestBitmapPath("almogaver32bits.tif");
using (Bitmap bmp = new Bitmap(sInFile))
{
// sampling values from a well known bitmap
Assert.Equal(-1579559, bmp.GetPixel(0, 0).ToArgb());
Assert.Equal(-1645353, bmp.GetPixel(0, 32).ToArgb());
Assert.Equal(-461332, bmp.GetPixel(0, 64).ToArgb());
Assert.Equal(-330005, bmp.GetPixel(0, 96).ToArgb());
Assert.Equal(-2237489, bmp.GetPixel(0, 128).ToArgb());
Assert.Equal(-1251105, bmp.GetPixel(0, 160).ToArgb());
Assert.Equal(-3024947, bmp.GetPixel(32, 0).ToArgb());
Assert.Equal(-2699070, bmp.GetPixel(32, 32).ToArgb());
Assert.Equal(-2366734, bmp.GetPixel(32, 64).ToArgb());
Assert.Equal(-4538413, bmp.GetPixel(32, 96).ToArgb());
Assert.Equal(-6116681, bmp.GetPixel(32, 128).ToArgb());
Assert.Equal(-7369076, bmp.GetPixel(32, 160).ToArgb());
Assert.Equal(-13024729, bmp.GetPixel(64, 0).ToArgb());
Assert.Equal(-7174020, bmp.GetPixel(64, 32).ToArgb());
Assert.Equal(-51, bmp.GetPixel(64, 64).ToArgb());
Assert.Equal(-16053503, bmp.GetPixel(64, 96).ToArgb());
Assert.Equal(-8224431, bmp.GetPixel(64, 128).ToArgb());
Assert.Equal(-16579326, bmp.GetPixel(64, 160).ToArgb());
Assert.Equal(-2502457, bmp.GetPixel(96, 0).ToArgb());
Assert.Equal(-9078395, bmp.GetPixel(96, 32).ToArgb());
Assert.Equal(-12696508, bmp.GetPixel(96, 64).ToArgb());
Assert.Equal(-70772, bmp.GetPixel(96, 96).ToArgb());
Assert.Equal(-4346279, bmp.GetPixel(96, 128).ToArgb());
Assert.Equal(-11583193, bmp.GetPixel(96, 160).ToArgb());
Assert.Equal(-724763, bmp.GetPixel(128, 0).ToArgb());
Assert.Equal(-7238268, bmp.GetPixel(128, 32).ToArgb());
Assert.Equal(-2169612, bmp.GetPixel(128, 64).ToArgb());
Assert.Equal(-3683883, bmp.GetPixel(128, 96).ToArgb());
Assert.Equal(-12892867, bmp.GetPixel(128, 128).ToArgb());
Assert.Equal(-3750464, bmp.GetPixel(128, 160).ToArgb());
Assert.Equal(-3222844, bmp.GetPixel(160, 0).ToArgb());
Assert.Equal(-65806, bmp.GetPixel(160, 32).ToArgb());
Assert.Equal(-2961726, bmp.GetPixel(160, 64).ToArgb());
Assert.Equal(-2435382, bmp.GetPixel(160, 96).ToArgb());
Assert.Equal(-2501944, bmp.GetPixel(160, 128).ToArgb());
Assert.Equal(-9211799, bmp.GetPixel(160, 160).ToArgb());
}
}
[ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsDrawingSupported), nameof(PlatformDetection.IsNotArm64Process))] // [ActiveIssue("https://github.com/dotnet/runtime/issues/28859")]
public void Bitmap32bitsData()
{
string sInFile = Helpers.GetTestBitmapPath("almogaver32bits.tif");
using (Bitmap bmp = new Bitmap(sInFile))
{
BitmapData data = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height), ImageLockMode.ReadOnly, PixelFormat.Format24bppRgb);
try
{
Assert.Equal(bmp.Height, data.Height);
Assert.Equal(bmp.Width, data.Width);
Assert.Equal(PixelFormat.Format24bppRgb, data.PixelFormat);
Assert.Equal(520, data.Stride);
Assert.Equal(183, data.Height);
unsafe
{
byte* scan = (byte*)data.Scan0;
// sampling values from a well known bitmap
Assert.Equal(217, *(scan + 0));
Assert.Equal(192, *(scan + 1009));
Assert.Equal(210, *(scan + 2018));
Assert.Equal(196, *(scan + 3027));
Assert.Equal(216, *(scan + 4036));
Assert.Equal(215, *(scan + 5045));
Assert.Equal(218, *(scan + 6054));
Assert.Equal(218, *(scan + 7063));
Assert.Equal(95, *(scan + 8072));
Assert.Equal(9, *(scan + 9081));
Assert.Equal(247, *(scan + 10090));
Assert.Equal(161, *(scan + 11099));
Assert.Equal(130, *(scan + 12108));
Assert.Equal(131, *(scan + 13117));
Assert.Equal(175, *(scan + 14126));
Assert.Equal(217, *(scan + 15135));
Assert.Equal(201, *(scan + 16144));
Assert.Equal(183, *(scan + 17153));
Assert.Equal(236, *(scan + 18162));
Assert.Equal(242, *(scan + 19171));
Assert.Equal(125, *(scan + 20180));
Assert.Equal(193, *(scan + 21189));
Assert.Equal(227, *(scan + 22198));
Assert.Equal(44, *(scan + 23207));
Assert.Equal(230, *(scan + 24216));
Assert.Equal(224, *(scan + 25225));
Assert.Equal(164, *(scan + 26234));
Assert.Equal(43, *(scan + 27243));
Assert.Equal(200, *(scan + 28252));
Assert.Equal(255, *(scan + 29261));
Assert.Equal(226, *(scan + 30270));
Assert.Equal(230, *(scan + 31279));
Assert.Equal(178, *(scan + 32288));
Assert.Equal(224, *(scan + 33297));
Assert.Equal(233, *(scan + 34306));
Assert.Equal(212, *(scan + 35315));
Assert.Equal(153, *(scan + 36324));
Assert.Equal(143, *(scan + 37333));
Assert.Equal(215, *(scan + 38342));
Assert.Equal(116, *(scan + 39351));
Assert.Equal(26, *(scan + 40360));
Assert.Equal(28, *(scan + 41369));
Assert.Equal(75, *(scan + 42378));
Assert.Equal(50, *(scan + 43387));
Assert.Equal(244, *(scan + 44396));
Assert.Equal(191, *(scan + 45405));
Assert.Equal(200, *(scan + 46414));
Assert.Equal(197, *(scan + 47423));
Assert.Equal(232, *(scan + 48432));
Assert.Equal(186, *(scan + 49441));
Assert.Equal(210, *(scan + 50450));
Assert.Equal(215, *(scan + 51459));
Assert.Equal(155, *(scan + 52468));
Assert.Equal(56, *(scan + 53477));
Assert.Equal(149, *(scan + 54486));
Assert.Equal(137, *(scan + 55495));
Assert.Equal(141, *(scan + 56504));
Assert.Equal(36, *(scan + 57513));
Assert.Equal(39, *(scan + 58522));
Assert.Equal(25, *(scan + 59531));
Assert.Equal(44, *(scan + 60540));
Assert.Equal(12, *(scan + 61549));
Assert.Equal(161, *(scan + 62558));
Assert.Equal(179, *(scan + 63567));
Assert.Equal(181, *(scan + 64576));
Assert.Equal(165, *(scan + 65585));
Assert.Equal(182, *(scan + 66594));
Assert.Equal(186, *(scan + 67603));
Assert.Equal(201, *(scan + 68612));
Assert.Equal(49, *(scan + 69621));
Assert.Equal(161, *(scan + 70630));
Assert.Equal(140, *(scan + 71639));
Assert.Equal(2, *(scan + 72648));
Assert.Equal(15, *(scan + 73657));
Assert.Equal(33, *(scan + 74666));
Assert.Equal(17, *(scan + 75675));
Assert.Equal(0, *(scan + 76684));
Assert.Equal(47, *(scan + 77693));
Assert.Equal(4, *(scan + 78702));
Assert.Equal(142, *(scan + 79711));
Assert.Equal(151, *(scan + 80720));
Assert.Equal(124, *(scan + 81729));
Assert.Equal(81, *(scan + 82738));
Assert.Equal(214, *(scan + 83747));
Assert.Equal(217, *(scan + 84756));
Assert.Equal(30, *(scan + 85765));
Assert.Equal(185, *(scan + 86774));
Assert.Equal(200, *(scan + 87783));
Assert.Equal(37, *(scan + 88792));
Assert.Equal(2, *(scan + 89801));
Assert.Equal(41, *(scan + 90810));
Assert.Equal(16, *(scan + 91819));
Assert.Equal(0, *(scan + 92828));
Assert.Equal(146, *(scan + 93837));
Assert.Equal(163, *(scan + 94846));
}
}
finally
{
bmp.UnlockBits(data);
}
}
}
private void Save(PixelFormat original, PixelFormat expected, bool colorCheck)
{
string sOutFile = $"linerect-{expected}.tif";
// Save
Bitmap bmp = new Bitmap(100, 100, original);
Graphics gr = Graphics.FromImage(bmp);
using (Pen p = new Pen(Color.BlueViolet, 2))
{
gr.DrawLine(p, 10.0F, 10.0F, 90.0F, 90.0F);
gr.DrawRectangle(p, 10.0F, 10.0F, 80.0F, 80.0F);
}
try
{
bmp.Save(sOutFile, ImageFormat.Tiff);
// Load
using (Bitmap bmpLoad = new Bitmap(sOutFile))
{
Assert.Equal(expected, bmpLoad.PixelFormat);
if (colorCheck)
{
Color color = bmpLoad.GetPixel(10, 10);
Assert.Equal(Color.FromArgb(255, 138, 43, 226), color);
}
}
}
finally
{
gr.Dispose();
bmp.Dispose();
try
{
File.Delete(sOutFile);
}
catch
{
}
}
}
[ConditionalFact(Helpers.RecentGdiplusIsAvailable)]
public void Save_24bppRgb()
{
Save(PixelFormat.Format24bppRgb, PixelFormat.Format24bppRgb, true);
}
[ConditionalFact(Helpers.RecentGdiplusIsAvailable)]
public void Save_32bppRgb()
{
Save(PixelFormat.Format32bppRgb, PixelFormat.Format32bppArgb, true);
}
[ConditionalFact(Helpers.RecentGdiplusIsAvailable)]
public void Save_32bppArgb()
{
Save(PixelFormat.Format32bppArgb, PixelFormat.Format32bppArgb, true);
}
[ConditionalFact(Helpers.RecentGdiplusIsAvailable)]
public void Save_32bppPArgb()
{
Save(PixelFormat.Format32bppPArgb, PixelFormat.Format32bppArgb, true);
}
}
}
| {
"pile_set_name": "Github"
} |
/*
Package neurosky contains the Gobot adaptor and driver for the Neurosky Mindwave Mobile EEG.
Installing:
go get gobot.io/x/gobot/platforms/neurosky
Example:
package main
import (
"fmt"
"gobot.io/x/gobot"
"gobot.io/x/gobot/platforms/neurosky"
)
func main() {
adaptor := neurosky.NewAdaptor("/dev/rfcomm0")
neuro := neurosky.NewDriver(adaptor)
work := func() {
neuro.On(neuro.Event("extended"), func(data interface{}) {
fmt.Println("Extended", data)
})
neuro.On(neuro.Event("signal"), func(data interface{}) {
fmt.Println("Signal", data)
})
neuro.On(neuro.Event("attention"), func(data interface{}) {
fmt.Println("Attention", data)
})
neuro.On(neuro.Event("meditation"), func(data interface{}) {
fmt.Println("Meditation", data)
})
neuro.On(neuro.Event("blink"), func(data interface{}) {
fmt.Println("Blink", data)
})
neuro.On(neuro.Event("wave"), func(data interface{}) {
fmt.Println("Wave", data)
})
neuro.On(neuro.Event("eeg"), func(data interface{}) {
eeg := data.(neurosky.EEGData)
fmt.Println("Delta", eeg.Delta)
fmt.Println("Theta", eeg.Theta)
fmt.Println("LoAlpha", eeg.LoAlpha)
fmt.Println("HiAlpha", eeg.HiAlpha)
fmt.Println("LoBeta", eeg.LoBeta)
fmt.Println("HiBeta", eeg.HiBeta)
fmt.Println("LoGamma", eeg.LoGamma)
fmt.Println("MidGamma", eeg.MidGamma)
fmt.Println("\n")
})
}
robot := gobot.NewRobot("brainBot",
[]gobot.Connection{adaptor},
[]gobot.Device{neuro},
work,
)
robot.Start()
}
For further information refer to neuroky README:
https://github.com/hybridgroup/gobot/blob/master/platforms/neurosky/README.md
*/
package neurosky // import "gobot.io/x/gobot/platforms/neurosky"
| {
"pile_set_name": "Github"
} |
name 'esri-tomcat'
maintainer 'Esri'
maintainer_email '[email protected]'
license 'Apache 2.0'
description 'Installs/Configures esri-tomcat'
long_description IO.read(File.join(File.dirname(__FILE__), 'README.md'))
version '0.1.7'
chef_version '>= 13'
depends 'tomcat', '>= 3.2.0'
depends 'openssl', '~> 8.5'
%w(ubuntu redhat centos).each do |os|
supports os
end
issues_url 'https://github.com/Esri/arcgis-cookbook/issues' if respond_to?(:issues_url)
source_url 'https://github.com/Esri/arcgis-cookbook' if respond_to?(:source_url)
| {
"pile_set_name": "Github"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.