repo_name
stringlengths 4
116
| path
stringlengths 3
942
| size
stringlengths 1
7
| content
stringlengths 3
1.05M
| license
stringclasses 15
values |
---|---|---|---|---|
slannigan/computed_input_errors
|
addon/mixins/has-property.js
|
1005
|
import Ember from 'ember';
import HasIdMixin from '../mixins/has-id';
const { computed, Mixin, assert, defineProperty } = Ember;
/*
A mixin that enriches a component that is attached to a model property.
The property name by default is taken from the formComponent, computed unless explictly
defined in the `property` variable.
This mixin also binds a property named `errors` to the model's `model.errors.@propertyName` array
*/
export default Mixin.create(HasIdMixin, {
property: undefined,
propertyName: computed('property', 'formComponent.property', {
get() {
if (this.get('property')) {
return this.get('property');
} else if (this.get('formComponent.property')) {
return this.get('formComponent.property');
} else {
return assert(false, 'Property could not be found.');
}
}
}),
init() {
this._super(...arguments);
defineProperty(this, 'errors', computed.alias((`model.errors.${this.get('propertyName')}`)));
}
});
|
apache-2.0
|
edge-code/edge-inspect-extension
|
htmlContent/inspect-howto-dialog.html
|
798
|
<div class="inspect-howto-dialog template modal hide">
<div class="modal-header">
<a href="#" class="close">×</a>
<h1 class="dialog-title">{{Strings.PRODUCT_NAME}}</h1>
</div>
<div class="modal-body">
<p class="dialog-message">{{Strings.HOWTO_INTRO}}</p>
<div class="inspect-howto-diagram"></div>
<ol class="dialog-message">
<li>{{Strings.HOWTO_INSTRUCTIONS_1}}</li>
<li>{{Strings.HOWTO_INSTRUCTIONS_2}}</li>
<li>{{Strings.HOWTO_INSTRUCTIONS_3}}</li>
</ol>
</div>
<div class="modal-footer">
<span class="inspect-needhelp">{{{Strings.INSPECT_needhelp}}}</span>
<a href="#" class="dialog-button btn primary" data-button-id="ok">{{Strings.DIALOG_DONE}}</a>
</div>
</div>
|
apache-2.0
|
gamingrobot/ginux
|
ops/root_predeploy.sh
|
99
|
#!/bin/bash
echo "I am the predeploy script that on the ginux-dev as root"
killall vzcontrol
exit 0
|
apache-2.0
|
sryza/spark
|
core/src/main/scala/org/apache/spark/rdd/DoubleRDDFunctions.scala
|
8788
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.spark.rdd
import org.apache.spark.{TaskContext, Logging}
import org.apache.spark.partial.BoundedDouble
import org.apache.spark.partial.MeanEvaluator
import org.apache.spark.partial.PartialResult
import org.apache.spark.partial.SumEvaluator
import org.apache.spark.util.StatCounter
/**
* Extra functions available on RDDs of Doubles through an implicit conversion.
* Import `org.apache.spark.SparkContext._` at the top of your program to use these functions.
*/
class DoubleRDDFunctions(self: RDD[Double]) extends Logging with Serializable {
/** Add up the elements in this RDD. */
def sum(): Double = {
self.reduce(_ + _)
}
/**
* Return a [[org.apache.spark.util.StatCounter]] object that captures the mean, variance and
* count of the RDD's elements in one operation.
*/
def stats(): StatCounter = {
self.mapPartitions(nums => Iterator(StatCounter(nums))).reduce((a, b) => a.merge(b))
}
/** Compute the mean of this RDD's elements. */
def mean(): Double = stats().mean
/** Compute the variance of this RDD's elements. */
def variance(): Double = stats().variance
/** Compute the standard deviation of this RDD's elements. */
def stdev(): Double = stats().stdev
/**
* Compute the sample standard deviation of this RDD's elements (which corrects for bias in
* estimating the standard deviation by dividing by N-1 instead of N).
*/
def sampleStdev(): Double = stats().sampleStdev
/**
* Compute the sample variance of this RDD's elements (which corrects for bias in
* estimating the variance by dividing by N-1 instead of N).
*/
def sampleVariance(): Double = stats().sampleVariance
/** (Experimental) Approximate operation to return the mean within a timeout. */
def meanApprox(timeout: Long, confidence: Double = 0.95): PartialResult[BoundedDouble] = {
val processPartition = (ctx: TaskContext, ns: Iterator[Double]) => StatCounter(ns)
val evaluator = new MeanEvaluator(self.partitions.size, confidence)
self.context.runApproximateJob(self, processPartition, evaluator, timeout)
}
/** (Experimental) Approximate operation to return the sum within a timeout. */
def sumApprox(timeout: Long, confidence: Double = 0.95): PartialResult[BoundedDouble] = {
val processPartition = (ctx: TaskContext, ns: Iterator[Double]) => StatCounter(ns)
val evaluator = new SumEvaluator(self.partitions.size, confidence)
self.context.runApproximateJob(self, processPartition, evaluator, timeout)
}
/**
* Compute a histogram of the data using bucketCount number of buckets evenly
* spaced between the minimum and maximum of the RDD. For example if the min
* value is 0 and the max is 100 and there are two buckets the resulting
* buckets will be [0, 50) [50, 100]. bucketCount must be at least 1
* If the RDD contains infinity, NaN throws an exception
* If the elements in RDD do not vary (max == min) always returns a single bucket.
*/
def histogram(bucketCount: Int): Pair[Array[Double], Array[Long]] = {
// Compute the minimum and the maxium
val (max: Double, min: Double) = self.mapPartitions { items =>
Iterator(items.foldRight(Double.NegativeInfinity,
Double.PositiveInfinity)((e: Double, x: Pair[Double, Double]) =>
(x._1.max(e), x._2.min(e))))
}.reduce { (maxmin1, maxmin2) =>
(maxmin1._1.max(maxmin2._1), maxmin1._2.min(maxmin2._2))
}
if (min.isNaN || max.isNaN || max.isInfinity || min.isInfinity ) {
throw new UnsupportedOperationException(
"Histogram on either an empty RDD or RDD containing +/-infinity or NaN")
}
val increment = (max-min)/bucketCount.toDouble
val range = if (increment != 0) {
Range.Double.inclusive(min, max, increment)
} else {
List(min, min)
}
val buckets = range.toArray
(buckets, histogram(buckets, true))
}
/**
* Compute a histogram using the provided buckets. The buckets are all open
* to the left except for the last which is closed
* e.g. for the array
* [1, 10, 20, 50] the buckets are [1, 10) [10, 20) [20, 50]
* e.g 1<=x<10 , 10<=x<20, 20<=x<50
* And on the input of 1 and 50 we would have a histogram of 1, 0, 0
*
* Note: if your histogram is evenly spaced (e.g. [0, 10, 20, 30]) this can be switched
* from an O(log n) inseration to O(1) per element. (where n = # buckets) if you set evenBuckets
* to true.
* buckets must be sorted and not contain any duplicates.
* buckets array must be at least two elements
* All NaN entries are treated the same. If you have a NaN bucket it must be
* the maximum value of the last position and all NaN entries will be counted
* in that bucket.
*/
def histogram(buckets: Array[Double], evenBuckets: Boolean = false): Array[Long] = {
if (buckets.length < 2) {
throw new IllegalArgumentException("buckets array must have at least two elements")
}
// The histogramPartition function computes the partail histogram for a given
// partition. The provided bucketFunction determines which bucket in the array
// to increment or returns None if there is no bucket. This is done so we can
// specialize for uniformly distributed buckets and save the O(log n) binary
// search cost.
def histogramPartition(bucketFunction: (Double) => Option[Int])(iter: Iterator[Double]):
Iterator[Array[Long]] = {
val counters = new Array[Long](buckets.length - 1)
while (iter.hasNext) {
bucketFunction(iter.next()) match {
case Some(x: Int) => {counters(x) += 1}
case _ => {}
}
}
Iterator(counters)
}
// Merge the counters.
def mergeCounters(a1: Array[Long], a2: Array[Long]): Array[Long] = {
a1.indices.foreach(i => a1(i) += a2(i))
a1
}
// Basic bucket function. This works using Java's built in Array
// binary search. Takes log(size(buckets))
def basicBucketFunction(e: Double): Option[Int] = {
val location = java.util.Arrays.binarySearch(buckets, e)
if (location < 0) {
// If the location is less than 0 then the insertion point in the array
// to keep it sorted is -location-1
val insertionPoint = -location-1
// If we have to insert before the first element or after the last one
// its out of bounds.
// We do this rather than buckets.lengthCompare(insertionPoint)
// because Array[Double] fails to override it (for now).
if (insertionPoint > 0 && insertionPoint < buckets.length) {
Some(insertionPoint-1)
} else {
None
}
} else if (location < buckets.length - 1) {
// Exact match, just insert here
Some(location)
} else {
// Exact match to the last element
Some(location - 1)
}
}
// Determine the bucket function in constant time. Requires that buckets are evenly spaced
def fastBucketFunction(min: Double, increment: Double, count: Int)(e: Double): Option[Int] = {
// If our input is not a number unless the increment is also NaN then we fail fast
if (e.isNaN()) {
return None
}
val bucketNumber = (e - min)/(increment)
// We do this rather than buckets.lengthCompare(bucketNumber)
// because Array[Double] fails to override it (for now).
if (bucketNumber > count || bucketNumber < 0) {
None
} else {
Some(bucketNumber.toInt.min(count - 1))
}
}
// Decide which bucket function to pass to histogramPartition. We decide here
// rather than having a general function so that the decission need only be made
// once rather than once per shard
val bucketFunction = if (evenBuckets) {
fastBucketFunction(buckets(0), buckets(1)-buckets(0), buckets.length-1) _
} else {
basicBucketFunction _
}
self.mapPartitions(histogramPartition(bucketFunction)).reduce(mergeCounters)
}
}
|
apache-2.0
|
mdoering/backbone
|
life/Fungi/Basidiomycota/Agaricomycetes/Agaricales/Cortinariaceae/Cortinarius/Cortinarius dalecarlicus/README.md
|
337
|
# Cortinarius dalecarlicus Brandrud SPECIES
#### Status
ACCEPTED
#### According to
Index Fungorum
#### Published in
in Brandrud, Lindström, Marklund, Melot & Muskos, Cortinarius (Sweden), Flora Photographica vol. <b>2</b> [Swedish version by Brandrud] 33 (1992)
#### Original name
Cortinarius dalecarlicus Brandrud
### Remarks
null
|
apache-2.0
|
mdoering/backbone
|
life/Plantae/Pteridophyta/Polypodiopsida/Hymenophyllales/Hymenophyllaceae/Microgonium/Microgonium craspedoneurum/README.md
|
192
|
# Microgonium craspedoneurum (Copel.) Copel. SPECIES
#### Status
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null
|
apache-2.0
|
mdoering/backbone
|
life/Fungi/Basidiomycota/Pucciniomycetes/Septobasidiales/Septobasidiaceae/Septobasidium/Septobasidium sabal-minor/README.md
|
232
|
# Septobasidium sabal-minor Couch SPECIES
#### Status
ACCEPTED
#### According to
Index Fungorum
#### Published in
J. Elisha Mitchell scient. Soc. 51: 19 (1935)
#### Original name
Septobasidium sabal-minor Couch
### Remarks
null
|
apache-2.0
|
mdoering/backbone
|
life/Plantae/Magnoliophyta/Magnoliopsida/Fabales/Fabaceae/Crotalaria/Crotalaria eremaea/Crotalaria eremaea eremaea/README.md
|
203
|
# Crotalaria eremaea subsp. eremaea F.Muell. SUBSPECIES
#### Status
ACCEPTED
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null
|
apache-2.0
|
mdoering/backbone
|
life/Plantae/Magnoliophyta/Magnoliopsida/Asterales/Asteraceae/Cirsium phulchokiense/README.md
|
178
|
# Cirsium phulchokiense Kitam. SPECIES
#### Status
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null
|
apache-2.0
|
mdoering/backbone
|
life/Plantae/Magnoliophyta/Magnoliopsida/Rosales/Moraceae/Ipo/Ipo bennettii/README.md
|
170
|
# Ipo bennettii Kuntze SPECIES
#### Status
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null
|
apache-2.0
|
mdoering/backbone
|
life/Plantae/Chlorophyta/Chlorophyceae/Chlorococcales/Chlorococcaceae/Bracteacoccus/Bracteacoccus anomalus/README.md
|
204
|
# Bracteacoccus anomalus (E.J. James) R.C. Starr SPECIES
#### Status
ACCEPTED
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null
|
apache-2.0
|
mdoering/backbone
|
life/Plantae/Magnoliophyta/Liliopsida/Poales/Restionaceae/Desmocladus/README.md
|
172
|
# Desmocladus Nees GENUS
#### Status
ACCEPTED
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null
|
apache-2.0
|
mdoering/backbone
|
life/Plantae/Magnoliophyta/Magnoliopsida/Fabales/Polygalaceae/Polygala/Polygala westii/README.md
|
171
|
# Polygala westii Exell SPECIES
#### Status
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null
|
apache-2.0
|
mdoering/backbone
|
life/Plantae/Magnoliophyta/Magnoliopsida/Caryophyllales/Cactaceae/Sclerocactus/Sclerocactus erectocentrus/ Syn. Echinomastus acunensis/README.md
|
215
|
# Echinomastus acunensis W.T. Marsh. SPECIES
#### Status
SYNONYM
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
Saguaroland Bull. 7:33. 1953
#### Original name
null
### Remarks
null
|
apache-2.0
|
mdoering/backbone
|
life/Plantae/Magnoliophyta/Magnoliopsida/Gentianales/Apocynaceae/Asclepias/Asclepias scheryi/README.md
|
175
|
# Asclepias scheryi Woodson SPECIES
#### Status
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null
|
apache-2.0
|
mdoering/backbone
|
life/Plantae/Magnoliophyta/Magnoliopsida/Fabales/Fabaceae/Desmodium/Desmodium rubrum/ Syn. Ornithopus rubrum/README.md
|
180
|
# Ornithopus rubrum Lour. SPECIES
#### Status
SYNONYM
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null
|
apache-2.0
|
mdoering/backbone
|
life/Fungi/Ascomycota/Lecanoromycetes/Umbilicariales/Umbilicariaceae/Umbilicaria/Umbilicaria pennsylvanica/Umbilicaria pennsylvanica pertusa/README.md
|
201
|
# Umbilicaria pennsylvanica f. pertusa (Rass.) Rass. FORM
#### Status
ACCEPTED
#### According to
Index Fungorum
#### Published in
null
#### Original name
Umbilicaria pertusa Rass.
### Remarks
null
|
apache-2.0
|
mdoering/backbone
|
life/Fungi/Ascomycota/Sordariomycetes/Xylariales/Xylariaceae/Sphaeria/Sphaeria thoracella/README.md
|
181
|
# Sphaeria thoracella Rostr. SPECIES
#### Status
ACCEPTED
#### According to
Index Fungorum
#### Published in
null
#### Original name
Sphaeria thoracella Rostr.
### Remarks
null
|
apache-2.0
|
fchu/hadoop-0.20.205
|
docs/api/org/apache/hadoop/fs/class-use/FSOutputSummer.html
|
5974
|
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!--NewPage-->
<HTML>
<HEAD>
<!-- Generated by javadoc (build 1.6.0_23) on Fri Oct 07 06:23:09 UTC 2011 -->
<TITLE>
Uses of Class org.apache.hadoop.fs.FSOutputSummer (Hadoop 0.20.205.0 API)
</TITLE>
<META NAME="date" CONTENT="2011-10-07">
<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../stylesheet.css" TITLE="Style">
<SCRIPT type="text/javascript">
function windowTitle()
{
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Uses of Class org.apache.hadoop.fs.FSOutputSummer (Hadoop 0.20.205.0 API)";
}
}
</SCRIPT>
<NOSCRIPT>
</NOSCRIPT>
</HEAD>
<BODY BGCOLOR="white" onload="windowTitle();">
<HR>
<!-- ========= START OF TOP NAVBAR ======= -->
<A NAME="navbar_top"><!-- --></A>
<A HREF="#skip-navbar_top" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_top_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../org/apache/hadoop/fs/FSOutputSummer.html" title="class in org.apache.hadoop.fs"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
PREV
NEXT</FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../index.html?org/apache/hadoop/fs//class-useFSOutputSummer.html" target="_top"><B>FRAMES</B></A>
<A HREF="FSOutputSummer.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!--
if(window==top) {
document.writeln('<A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_top"></A>
<!-- ========= END OF TOP NAVBAR ========= -->
<HR>
<CENTER>
<H2>
<B>Uses of Class<br>org.apache.hadoop.fs.FSOutputSummer</B></H2>
</CENTER>
No usage of org.apache.hadoop.fs.FSOutputSummer
<P>
<HR>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<A NAME="navbar_bottom"><!-- --></A>
<A HREF="#skip-navbar_bottom" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_bottom_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../org/apache/hadoop/fs/FSOutputSummer.html" title="class in org.apache.hadoop.fs"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
PREV
NEXT</FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../index.html?org/apache/hadoop/fs//class-useFSOutputSummer.html" target="_top"><B>FRAMES</B></A>
<A HREF="FSOutputSummer.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!--
if(window==top) {
document.writeln('<A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_bottom"></A>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<HR>
Copyright © 2009 The Apache Software Foundation
</BODY>
</HTML>
|
apache-2.0
|
riganti/dotvvm-samples-academy
|
src/DotvvmAcademy.Meta/MetaMemberInfoVisitor.cs
|
2764
|
using DotvvmAcademy.Meta.Syntax;
using System;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
namespace DotvvmAcademy.Meta
{
internal class MetaMemberInfoVisitor : MemberInfoVisitor<NameNode>
{
public override NameNode DefaultVisit(MemberInfo info)
{
throw new NotSupportedException($"MemberInfo of type \"{info.GetType()}\" is not supported.");
}
public override NameNode VisitConstructor(ConstructorInfo info)
{
return VisitMember(info);
}
public override NameNode VisitEvent(EventInfo info)
{
return VisitMember(info);
}
public override NameNode VisitField(FieldInfo info)
{
return VisitMember(info);
}
public override NameNode VisitMethod(MethodInfo info)
{
return VisitMember(info);
}
public override NameNode VisitProperty(PropertyInfo info)
{
return VisitMember(info);
}
public override NameNode VisitType(Type info)
{
if (info.IsConstructedGenericType)
{
var arguments = info.GetGenericArguments()
.Select(a => Visit(a));
return NameFactory.ConstructedType(Visit(info.GetGenericTypeDefinition()), arguments);
}
else if (info.IsNested)
{
return NameFactory.NestedType(Visit(info.DeclaringType), info.Name, info.GetGenericArguments().Length);
}
else if (info.IsPointer)
{
return NameFactory.PointerType(Visit(info.GetElementType()));
}
else if (info.IsArray)
{
return NameFactory.ArrayType(Visit(info.GetElementType()), info.GetArrayRank());
}
else
{
if (info.Namespace == null)
{
return NameFactory.Simple(info.Name);
}
else
{
return NameFactory.Qualified(VisitNamespace(info.Namespace), NameFactory.Simple(info.Name));
}
}
}
private NameNode VisitNamespace(string @namespace)
{
var segments = @namespace.Split('.');
NameNode result = NameFactory.Identifier(segments[0]);
for (int i = 1; i < segments.Length; i++)
{
result = NameFactory.Qualified(result, segments[i]);
}
return result;
}
private NameNode VisitMember(MemberInfo info)
{
return NameFactory.Member(Visit(info.DeclaringType), info.Name);
}
}
}
|
apache-2.0
|
lerwine/PowerShell-Modules
|
src/NetworkUtility/UriPathSegmentList.cs
|
21377
|
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Linq;
using System.Management.Automation;
using System.Text;
using System.Threading;
namespace NetworkUtility
{
#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member
public class UriPathSegmentList : IList<string>, IList, INotifyPropertyChanged, INotifyCollectionChanged, IEquatable<UriPathSegmentList>, IComparable<UriPathSegmentList>, IComparable
{
private static StringComparer _comparer = StringComparer.InvariantCultureIgnoreCase;
private object _syncRoot = new object();
private List<string> _segments = null;
private List<char> _separators = new List<char>();
private int _count = 0;
private string _fullPath = "";
private string _encodedFullPath = "";
public event PropertyChangedEventHandler PropertyChanged;
public event NotifyCollectionChangedEventHandler CollectionChanged;
public string FullPath
{
get
{
Monitor.Enter(_syncRoot);
try { return _fullPath; }
finally { Monitor.Exit(_syncRoot); }
}
}
public string EncodedFullPath
{
get
{
Monitor.Enter(_syncRoot);
try { return _encodedFullPath; }
finally { Monitor.Exit(_syncRoot); }
}
}
public bool IsEmpty
{
get
{
Monitor.Enter(_syncRoot);
try { return _segments == null; }
finally { Monitor.Exit(_syncRoot); }
}
}
public bool IsPathRooted
{
get
{
Monitor.Enter(_syncRoot);
try { return _segments != null && _separators.Count == _segments.Count; }
finally { Monitor.Exit(_syncRoot); }
}
set
{
Monitor.Enter(_syncRoot);
try
{
if (value)
{
if (_separators == null)
_separators = new List<char>();
else if (_separators.Count < _segments.Count)
_separators.Insert(0, _separators.DefaultIfEmpty('/').First());
}
else if (_separators != null)
{
if (_separators.Count == 0)
_separators = null;
else
_separators.RemoveAt(0);
}
}
finally { Monitor.Exit(_syncRoot); }
}
}
public string this[int index]
{
get
{
Monitor.Enter(_syncRoot);
try { return _segments[index]; }
finally { Monitor.Exit(_syncRoot); }
}
set
{
string oldValue;
Monitor.Enter(_syncRoot);
try
{
if (value == null)
throw new ArgumentNullException();
if (_segments[index] == value)
return;
oldValue = _segments[index];
_segments[index] = value;
}
finally { Monitor.Exit(_syncRoot); }
UpdateFullPath(() => RaiseCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Replace, value, oldValue, index)));
}
}
object IList.this[int index]
{
get { return this[index]; }
set
{
object obj = value;
if (obj != null && obj is PSObject)
obj = (obj as PSObject).BaseObject;
this[index] = (string)obj;
}
}
public int Count
{
get
{
Monitor.Enter(_syncRoot);
try { return _count; }
finally { Monitor.Exit(_syncRoot); }
}
}
bool ICollection<string>.IsReadOnly { get { return false; } }
bool IList.IsReadOnly { get { return false; } }
bool IList.IsFixedSize { get { return false; } }
object ICollection.SyncRoot { get { return _syncRoot; } }
bool ICollection.IsSynchronized { get { return true; } }
public static string EscapePathSegment(string value)
{
if (String.IsNullOrEmpty(value))
return "";
StringBuilder sb = new StringBuilder();
foreach (char c in value)
{
switch (c)
{
case '%':
sb.Append("%25");
break;
case '\\':
sb.Append("%5C");
break;
case '#':
sb.Append("%23");
break;
case '/':
sb.Append("%2F");
break;
case ':':
sb.Append("%3A");
break;
case '?':
sb.Append("%3F");
break;
default:
if (c < ' ' || c > 126)
sb.Append(Uri.HexEscape(c));
else
sb.Append(c);
break;
}
}
return sb.ToString();
}
public static string EncodePathSegment(string value)
{
if (String.IsNullOrEmpty(value))
return "";
StringBuilder sb = new StringBuilder();
foreach (char c in value)
{
switch (c)
{
case ' ':
sb.Append("%20");
break;
case '"':
sb.Append("%22");
break;
case '%':
sb.Append("%25");
break;
case '<':
sb.Append("%3C");
break;
case '>':
sb.Append("%3E");
break;
case '\\':
sb.Append("%5C");
break;
case '^':
sb.Append("%5E");
break;
case '`':
sb.Append("%60");
break;
case '{':
sb.Append("%7B");
break;
case '|':
sb.Append("%7C");
break;
case '}':
sb.Append("%7D");
break;
case '#':
sb.Append("%23");
break;
case '+':
sb.Append("%2B");
break;
case '/':
sb.Append("%2F");
break;
case ':':
sb.Append("%3A");
break;
case '?':
sb.Append("%3F");
break;
default:
if (c < ' ' || c > 126)
sb.Append(Uri.HexEscape(c));
else
sb.Append(c);
break;
}
}
return sb.ToString();
}
private void EnsureCount(Action action)
{
try { action(); }
finally { EnsureCount(); }
}
private void EnsureCount()
{
Monitor.Enter(_syncRoot);
try
{
if (_count == _segments.Count)
return;
_count = _segments.Count;
}
finally { Monitor.Exit(_syncRoot); }
RaisePropertyChanged("Count");
}
private void UpdateFullPath(Action action)
{
try { action(); }
finally { UpdateFullPath(); }
}
private void UpdateFullPath()
{
string encodedFullPath, escapedFullPath;
Monitor.Enter(_syncRoot);
try
{
if (_segments.Count == 0)
{
encodedFullPath = "";
escapedFullPath = "";
}
else
{
StringBuilder encoded = new StringBuilder();
StringBuilder escaped = new StringBuilder();
if (_segments.Count == _separators.Count)
{
for (int i = 0; i < _segments.Count; i++)
{
char c = _separators[i];
encoded.Append(c);
escaped.Append(c);
string s = _segments[i];
encoded.Append(EncodePathSegment(s));
escaped.Append(EscapePathSegment(s));
}
}
else
{
encoded.Append(EncodePathSegment(_segments[0]));
for (int i = 1; i < _segments.Count; i++)
{
char c = _separators[i - 1];
encoded.Append(c);
encoded.Append(c);
string s = _segments[i];
encoded.Append(EncodePathSegment(s));
escaped.Append(EscapePathSegment(s));
}
}
encodedFullPath = encoded.ToString();
escapedFullPath = escaped.ToString();
}
if (_encodedFullPath == encodedFullPath)
encodedFullPath = null;
else
_encodedFullPath = encodedFullPath;
if (_fullPath == escapedFullPath)
escapedFullPath = null;
else
_fullPath = escapedFullPath;
}
finally { Monitor.Exit(_syncRoot); }
if (escapedFullPath != null)
RaisePropertyChanged("FullPath");
if (encodedFullPath != null)
RaisePropertyChanged("EncodedFullPath");
}
protected virtual void OnPropertyChanged(PropertyChangedEventArgs args) { }
protected void RaisePropertyChanged(string propertyName)
{
PropertyChangedEventArgs args = new PropertyChangedEventArgs(propertyName);
try { OnPropertyChanged(args); }
finally
{
PropertyChangedEventHandler propertyChanged = PropertyChanged;
if (propertyChanged != null)
propertyChanged(this, args);
}
}
protected virtual void OnCollectionChanged(NotifyCollectionChangedEventArgs args) { }
private void RaiseCollectionChanged(NotifyCollectionChangedEventArgs args)
{
try { OnCollectionChanged(args); }
finally
{
NotifyCollectionChangedEventHandler collectionChanged = CollectionChanged;
if (collectionChanged != null)
collectionChanged(this, args);
}
}
public int Add(string item)
{
if (item == null)
throw new ArgumentNullException("item");
Monitor.Enter(_syncRoot);
int index;
try
{
index = _segments.Count;
if (_separators == null)
_separators = new List<char>();
else
_separators.Add(_separators.DefaultIfEmpty('/').Last());
_segments.Add(item);
}
finally { Monitor.Exit(_syncRoot); }
EnsureCount();
UpdateFullPath();
return index;
}
void ICollection<string>.Add(string item) { Add(item); }
int IList.Add(object value)
{
object obj = value;
if (obj != null && obj is PSObject)
obj = (obj as PSObject).BaseObject;
return Add((string)obj);
}
public void Clear()
{
Monitor.Enter(_syncRoot);
try
{
if (_segments.Count == 0)
return;
if (_separators.Count == _segments.Count)
_separators.Clear();
else
_separators = null;
_segments.Clear();
}
finally { Monitor.Exit(_syncRoot); }
EnsureCount();
UpdateFullPath();
}
public bool Contains(string item)
{
if (item == null)
return false;
Monitor.Enter(_syncRoot);
try
{
if (_segments.Count == 0)
return false;
for (int i = 0; i < _segments.Count; i++)
{
if (_comparer.Equals(_segments[i], item))
return true;
}
}
finally { Monitor.Exit(_syncRoot); }
return false;
}
bool IList.Contains(object value)
{
object obj = value;
if (obj != null && obj is PSObject)
obj = (obj as PSObject).BaseObject;
return Contains(obj as string);
}
public void CopyTo(string[] array, int arrayIndex)
{
Monitor.Enter(_syncRoot);
try { _segments.CopyTo(array, arrayIndex); }
finally { Monitor.Exit(_syncRoot); }
}
void ICollection.CopyTo(Array array, int index)
{
Monitor.Enter(_syncRoot);
try { _segments.ToArray().CopyTo(array, index); }
finally { Monitor.Exit(_syncRoot); }
}
public IEnumerator<string> GetEnumerator() { return _segments.GetEnumerator(); }
public char? GetSeparator(int index)
{
Monitor.Enter(_syncRoot);
try
{
if (index < 0 || index >= _segments.Count)
throw new ArgumentOutOfRangeException("index");
if (_separators != null && _separators.Count == _segments.Count)
return _separators[index];
if (index == 0)
return null;
return _separators[index - 1];
}
finally { Monitor.Exit(_syncRoot); }
}
public int IndexOf(string item)
{
if (item == null)
return -1;
Monitor.Enter(_syncRoot);
try
{
if (_segments.Count == 0)
return -1;
int index = _segments.IndexOf(item);
if (index < 0)
{
for (int i = 0; i < _segments.Count; i++)
{
if (_comparer.Equals(_segments[i], item))
return i;
}
}
return index;
}
finally { Monitor.Exit(_syncRoot); }
}
int IList.IndexOf(object value)
{
object obj = value;
if (obj != null && obj is PSObject)
obj = (obj as PSObject).BaseObject;
return IndexOf(obj as string);
}
public void Insert(int index, string item)
{
if (item == null)
throw new ArgumentNullException("item");
Monitor.Enter(_syncRoot);
try
{
if (index < 0 || index > _segments.Count)
throw new ArgumentOutOfRangeException("index");
if (index == _segments.Count)
{
_segments.Add(item);
if (_separators == null)
_separators = new List<char>();
else
_separators.Add(_separators.DefaultIfEmpty('/').Last());
}
else
{
if (_separators.Count == _segments.Count)
_separators.Insert(index, _separators[index]);
else if (index == _separators.Count)
_separators.Add(_separators.DefaultIfEmpty('/').Last());
else if (index == 0)
_separators.Insert(0, _separators.DefaultIfEmpty('/').First());
else
_separators.Insert(index - 1, _separators[index - 1]);
_segments.Insert(index, item);
}
}
finally { Monitor.Exit(_syncRoot); }
EnsureCount();
UpdateFullPath();
}
void IList.Insert(int index, object value)
{
object obj = value;
if (obj != null && obj is PSObject)
obj = (obj as PSObject).BaseObject;
Insert(index, (string)obj);
}
public bool Remove(string item)
{
if (item == null)
return false;
Monitor.Enter(_syncRoot);
try
{
int index = IndexOf(item);
if (index < 0)
return false;
if (_segments.Count == _separators.Count)
_separators.RemoveAt(index);
else
_separators.RemoveAt((index > 0) ? index - 1 : 0);
_segments.RemoveAt(index);
}
finally { Monitor.Exit(_syncRoot); }
EnsureCount();
UpdateFullPath();
return true;
}
void IList.Remove(object value)
{
object obj = value;
if (obj != null && obj is PSObject)
obj = (obj as PSObject).BaseObject;
Remove(obj as string);
}
public void RemoveAt(int index)
{
Monitor.Enter(_syncRoot);
try
{
if (index < 0 || index >= _segments.Count)
throw new ArgumentOutOfRangeException("index");
if (_segments.Count == _separators.Count)
_separators.RemoveAt(index);
else
_separators.RemoveAt((index > 0) ? index - 1 : 0);
_segments.RemoveAt(index);
}
finally { Monitor.Exit(_syncRoot); }
EnsureCount();
UpdateFullPath();
}
public void SetSeparator(int index, char separator)
{
if (!(separator == ':' || separator == '/' || separator == '\\'))
throw new ArgumentException("Invalid separator character", "separator");
Monitor.Enter(_syncRoot);
try
{
if (index < 0 || index >= _segments.Count)
throw new ArgumentOutOfRangeException("index");
if (_separators.Count == _segments.Count)
_separators[index] = separator;
else if (index == 0)
_separators.Insert(0, separator);
else
_separators[index - 1] = separator;
}
finally { Monitor.Exit(_syncRoot); }
UpdateFullPath();
}
IEnumerator IEnumerable.GetEnumerator() { return _segments.ToArray().GetEnumerator(); }
#warning Not implemented
public int CompareTo(UriPathSegmentList other)
{
throw new NotImplementedException();
}
public int CompareTo(object obj) { return CompareTo(obj as UriPathSegmentList); }
public bool Equals(UriPathSegmentList other)
{
throw new NotImplementedException();
}
public override bool Equals(object obj) { return Equals(obj as UriPathSegmentList); }
public override int GetHashCode() { return ToString().GetHashCode(); }
public override string ToString()
{
Monitor.Enter(_syncRoot);
try
{
throw new NotImplementedException();
}
finally { Monitor.Exit(_syncRoot); }
}
}
#pragma warning restore CS1591 // Missing XML comment for publicly visible type or member
}
|
apache-2.0
|
dev-comp/botservice
|
botservice-ejb/src/main/java/botservice/schedule/MsgToUserResender.java
|
2890
|
package botservice.schedule;
import botservice.model.system.UserLogEntity;
import botservice.model.system.UserLogEntity_;
import botservice.properties.BotServiceProperty;
import botservice.properties.BotServicePropertyConst;
import botservice.service.SystemService;
import botservice.service.common.BaseParam;
import botservice.serviceException.ServiceException;
import botservice.serviceException.ServiceExceptionObject;
import botservice.util.BotMsgDirectionType;
import botservice.util.BotMsgTransportStatus;
import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.ejb.*;
import javax.enterprise.event.Event;
import javax.inject.Inject;
import java.io.Serializable;
import java.util.List;
/**
* Бин, вызываемый по расписанию и пытающийся доставить те сообщения в очередь ботам (конечным пользователям),
* которые по каким-либо причинам не удалось доставить сразу
*/
@Singleton
@Startup
public class MsgToUserResender implements Serializable {
@Resource
private TimerService timerService;
@Inject
SystemService systemService;
@Inject
@ServiceException
Event<ServiceExceptionObject> serviceExceptionEvent;
@Inject
@BotServiceProperty(name = BotServicePropertyConst.MSG_TO_USER_RESEND_TIMEAUT)
private int msgToUserResendTimeOut;
@PostConstruct
public void init(){
timerService.createIntervalTimer(0L, msgToUserResendTimeOut*1000,
new TimerConfig(this, false));
}
@Timeout
public void resendMsgToClntApp(Timer timer){
if (timer.getInfo() instanceof MsgToUserResender){
List<UserLogEntity> userLogEntityList = systemService.getEntityListByCriteria(UserLogEntity.class,
new BaseParam(UserLogEntity_.directionType, BotMsgDirectionType.TO_USER),
new BaseParam(UserLogEntity_.transportStatus, BotMsgTransportStatus.DEFERRED));
for(UserLogEntity userLogEntity: userLogEntityList){
try {
systemService.sendMessageToBotQueue(userLogEntity.getMsgBody(), userLogEntity.getUserKeyEntity());
userLogEntity.setTransportStatus(BotMsgTransportStatus.DELIVERED);
systemService.mergeEntity(userLogEntity);
} catch (Exception e){
serviceExceptionEvent.fire(new ServiceExceptionObject(
"Ошибка при попытке повторной отправки сообщения в очередь бота: " +
userLogEntity.getUserKeyEntity().getBotEntity().getName(), e));
}
}
}
}
}
|
apache-2.0
|
vincentk/unit16-z
|
src/main/java/com/unit16/z/indexed/DSL.java
|
3250
|
package com.unit16.z.indexed;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.function.Function;
import java.util.function.Predicate;
import com.google.common.collect.Iterators;
import com.google.common.collect.Lists;
import com.google.common.collect.UnmodifiableIterator;
public abstract class DSL<B>
implements Indexed<B>, Iterable<B>
{
private static final class ListBacked<C>
extends DSL<C>
{
private final List<C> _list;
ListBacked(List<C> i)
{
_list = i;
}
ListBacked(DSL<C> i)
{
_list = new ArrayList<>(i.size());
for (C c : i) { _list.add(c); }
}
@Override public C get(int i) { return _list.get(i); }
@Override public int size() { return _list.size(); }
@Override public Iterator<C> iterator() { return _list.iterator(); }
@Override public String toString() { return getClass().getSimpleName() + ": " + _list.toString(); }
}
private static final class IndexedBacked<C>
extends DSL<C>
{
private final Indexed<C> _i;
IndexedBacked(Indexed<C> i) {
_i = i;
}
@Override
public C get(int i) { return _i.get(i); }
@Override
public int size() { return _i.size(); }
@Override
public Iterator<C> iterator() {
return new UnmodifiableIterator<C>() {
private int _j = 0;
@Override
public boolean hasNext() { return _j < size(); }
@Override
public C next() { _j++; return get(_j - 1);}
};
}
}
public static <C> DSL<C> from(List<C> c)
{
return new ListBacked<>(c);
}
public static <C> DSL<C> from(Indexed<C> c)
{
return (c instanceof DSL) ? (DSL<C>) c : new IndexedBacked<>(c);
}
public final <C> DSL<C> map(Function<? super B, ? extends C> f)
{
return new OnResultOf<>(this, f);
}
public final DSL<B> head(final int max)
{
final Indexed<B> w = this;
return new IndexedBacked<>(new Indexed<B>(){
@Override
public B get(int i) { return w.get(i); }
@Override
public int size() { return max; }});
}
public final DSL<B> tail(final int min)
{
final Indexed<B> w = this;
return new IndexedBacked<>(new Indexed<B>(){
@Override
public B get(int i) { return w.get(i + min); }
@Override
public int size() { return w.size() - min; }});
}
public final DSL<B> filter(Predicate<? super B> p)
{
if (size() > 0)
{
final Iterator<B> i = Iterators.filter(this.iterator(), x -> p.test(x));
if (i.hasNext())
{
return new ListBacked<>(Lists.newArrayList(i));
}
}
return new Empty<>();
}
public final DSL<B> strict()
{
return new ListBacked<>(this);
}
public final DSL<B> append(Indexed<B> snd)
{
return new Concat<>(this, snd);
}
private static final class Concat<C>
extends DSL<C>
{
private final DSL<C> fst_;
private final DSL<C> snd_;
private final int sf;
private final int ss;
Concat(Indexed<C> fst, Indexed<C> snd) {
fst_ = from(fst);
snd_ = from(snd);
sf = fst_.size();
ss = snd_.size();
}
@Override
public C get(int i) {
return i < sf ? fst_.get(i) : snd_.get(i - sf);
}
@Override
public int size() { return sf + ss; }
@Override
public Iterator<C> iterator() {
return Iterators.concat(fst_.iterator(), snd_.iterator()); }
}
}
|
apache-2.0
|
mdoering/backbone
|
life/Plantae/Magnoliophyta/Magnoliopsida/Ranunculales/Menispermaceae/Cissampelos/Cissampelos subtriangularis/README.md
|
188
|
# Cissampelos subtriangularis A.St.-Hil. SPECIES
#### Status
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null
|
apache-2.0
|
Datahjelpen/PEAK
|
resources/views/item/taxonomy/content-main.blade.php
|
206
|
<h1>This is an taxonomy</h1>
<ul>
<li>id: {{ $taxonomy->id }}</li>
<li>slug: {{ $taxonomy->slug }}</li>
<li>hierarchical: {{ $taxonomy->hierarchical }}</li>
{{ dump($taxonomy->terms) }}
</ul>
|
apache-2.0
|
CSGOpenSource/elasticsearch-net
|
src/Nest/Indices/AliasManagement/GetAlias/GetAliasResponse.cs
|
2661
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using Elasticsearch.Net;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace Nest
{
[JsonConverter(typeof(GetAliasResponseConverter))]
public interface IGetAliasResponse : IResponse
{
IReadOnlyDictionary<string, IReadOnlyList<AliasDefinition>> Indices { get; }
/// <summary>
/// An additional error message if an error occurs.
/// </summary>
/// <remarks>Applies to Elasticsearch 5.5.0+</remarks>
string Error { get; }
int? StatusCode { get; }
}
public class GetAliasResponse : ResponseBase, IGetAliasResponse
{
public IReadOnlyDictionary<string, IReadOnlyList<AliasDefinition>> Indices { get; internal set; } = EmptyReadOnly<string, IReadOnlyList<AliasDefinition>>.Dictionary;
public override bool IsValid => this.Indices.Count > 0;
public string Error { get; internal set; }
public int? StatusCode { get; internal set; }
}
internal class GetAliasResponseConverter : JsonConverter
{
public override bool CanWrite => false;
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
throw new NotSupportedException();
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
var j = JObject.Load(reader);
var errorProperty =j.Property("error");
string error = null;
if (errorProperty?.Value?.Type == JTokenType.String)
{
error = errorProperty.Value.Value<string>();
errorProperty.Remove();
}
var statusProperty =j.Property("status");
int? statusCode = null;
if (statusProperty?.Value?.Type == JTokenType.Integer)
{
statusCode = statusProperty.Value.Value<int>();
statusProperty.Remove();
}
//Read the remaining properties as aliases
var dict = serializer.Deserialize<Dictionary<string, Dictionary<string, Dictionary<string, AliasDefinition>>>>(j.CreateReader());
var indices = new Dictionary<string, IReadOnlyList<AliasDefinition>>();
foreach (var kv in dict)
{
var indexDict = kv.Key;
var aliases = new List<AliasDefinition>();
if (kv.Value != null && kv.Value.ContainsKey("aliases"))
{
var aliasDict = kv.Value["aliases"];
if (aliasDict != null)
aliases = aliasDict.Select(kva =>
{
var alias = kva.Value;
alias.Name = kva.Key;
return alias;
}).ToList();
}
indices.Add(indexDict, aliases);
}
return new GetAliasResponse { Indices = indices, Error = error, StatusCode = statusCode};
}
public override bool CanConvert(Type objectType) => true;
}
}
|
apache-2.0
|
LiberatorUSA/GUCEF
|
platform/gucefCORE/include/gucefCORE_CIniParser.h
|
5608
|
/*
* gucefCORE: GUCEF module providing O/S abstraction and generic solutions
* Copyright (C) 2002 - 2007. Dinand Vanvelzen
*
* 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#ifndef GUCEF_CORE_CINIPARSER_H
#define GUCEF_CORE_CINIPARSER_H
/*-------------------------------------------------------------------------//
// //
// INCLUDES //
// //
//-------------------------------------------------------------------------*/
#include <vector>
#ifndef GUCEF_CORE_CDATANODE_H
#include "CDataNode.h"
#define GUCEF_CORE_CDATANODE_H
#endif /* GUCEF_CORE_CDATANODE_H ? */
#ifndef GUCEF_CORE_CSTRING_H
#include "gucefCORE_CString.h"
#define GUCEF_CORE_CSTRING_H
#endif /* GUCEF_CORE_CSTRING_H ? */
#ifndef GUCEF_CORE_CVALUELIST_H
#include "CValueList.h"
#define GUCEF_CORE_CVALUELIST_H
#endif /* GUCEF_CORE_CVALUELIST_H ? */
#ifndef GUCEF_CORE_CIOACCESS_H
#include "CIOAccess.h"
#define GUCEF_CORE_CIOACCESS_H
#endif /* GUCEF_CORE_CIOACCESS_H ? */
#ifndef GUCEF_CORE_MACROS_H
#include "gucefCORE_macros.h" /* often used gucef macros */
#define GUCEF_CORE_MACROS_H
#endif /* GUCEF_CORE_MACROS_H ? */
/*-------------------------------------------------------------------------//
// //
// NAMESPACE //
// //
//-------------------------------------------------------------------------*/
namespace GUCEF {
namespace CORE {
/*-------------------------------------------------------------------------//
// //
// CLASSES //
// //
//-------------------------------------------------------------------------*/
class GUCEF_CORE_PUBLIC_CPP CIniParser
{
public:
struct SIniSection
{
CString sectionName;
CValueList sectionData;
};
typedef struct SIniSection TIniSection;
typedef std::vector< TIniSection > TIniData;
CIniParser( void );
CIniParser( const CIniParser& src );
virtual ~CIniParser();
CIniParser& operator=( const CIniParser& src );
bool SaveTo( CDataNode& rootNode ) const;
bool SaveTo( CIOAccess& fileAccess ) const;
bool SaveTo( CString& outputIniString ) const;
bool LoadFrom( const CDataNode& rootNode );
bool LoadFrom( CIOAccess& fileAccess );
bool LoadFrom( const CString& iniText );
void Clear( void );
TIniData& GetData( void );
const TIniData& GetData( void ) const;
private:
bool LoadFrom( const CDataNode& node ,
TIniSection* currentSection ,
bool& foundASection );
static bool IsCharIndexWithinQuotes( const CString& testString ,
UInt32 charIndex ,
Int32& quotationStartIndex ,
Int32& quotationEndIndex );
static Int32 FindIndexOfNonQuotedEquals( const CString& testString );
static CString StripQuotation( const CString& testString );
static bool HasChildWithValueOrAttribs( const CDataNode& node );
private:
TIniData m_iniData;
};
/*-------------------------------------------------------------------------//
// //
// NAMESPACE //
// //
//-------------------------------------------------------------------------*/
}; /* namespace CORE */
}; /* namespace GUCEF */
/*-------------------------------------------------------------------------*/
#endif /* GUCEF_CORE_CINIPARSER_H */
/*-------------------------------------------------------------------------//
// //
// Info & Changes //
// //
//-------------------------------------------------------------------------//
- 21-09-2005 :
- initial version
---------------------------------------------------------------------------*/
|
apache-2.0
|
mdoering/backbone
|
life/Plantae/Magnoliophyta/Magnoliopsida/Fabales/Fabaceae/Arachis/Arachis pseudovillosa/ Syn. Arachis prostrata pseudovillosa/README.md
|
209
|
# Arachis prostrata var. pseudovillosa Chodat & Hassl. VARIETY
#### Status
SYNONYM
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null
|
apache-2.0
|
resin-io-library/base-images
|
balena-base-images/golang/parallella/alpine/3.12/1.17.7/run/Dockerfile
|
2467
|
# AUTOGENERATED FILE
FROM balenalib/parallella-alpine:3.12-run
ENV GO_VERSION 1.17.7
# set up nsswitch.conf for Go's "netgo" implementation
# - https://github.com/golang/go/blob/go1.9.1/src/net/conf.go#L194-L275
# - docker run --rm debian:stretch grep '^hosts:' /etc/nsswitch.conf
RUN [ ! -e /etc/nsswitch.conf ] && echo 'hosts: files dns' > /etc/nsswitch.conf
# gcc for cgo
RUN apk add --no-cache git gcc ca-certificates
RUN fetchDeps='curl' \
&& set -x \
&& apk add --no-cache $fetchDeps \
&& mkdir -p /usr/local/go \
&& curl -SLO "http://resin-packages.s3.amazonaws.com/golang/v$GO_VERSION/go$GO_VERSION.linux-alpine-armv7hf.tar.gz" \
&& echo "052ef9c11ea2788e3c6c242c4b4a4beb9c461a96bab367315bfef515694633d7 go$GO_VERSION.linux-alpine-armv7hf.tar.gz" | sha256sum -c - \
&& tar -xzf "go$GO_VERSION.linux-alpine-armv7hf.tar.gz" -C /usr/local/go --strip-components=1 \
&& rm -f go$GO_VERSION.linux-alpine-armv7hf.tar.gz
ENV GOROOT /usr/local/go
ENV GOPATH /go
ENV PATH $GOPATH/bin:/usr/local/go/bin:$PATH
RUN mkdir -p "$GOPATH/src" "$GOPATH/bin" && chmod -R 777 "$GOPATH"
WORKDIR $GOPATH
CMD ["echo","'No CMD command was set in Dockerfile! Details about CMD command could be found in Dockerfile Guide section in our Docs. Here's the link: https://balena.io/docs"]
RUN curl -SLO "https://raw.githubusercontent.com/balena-io-library/base-images/613d8e9ca8540f29a43fddf658db56a8d826fffe/scripts/assets/tests/[email protected]" \
&& echo "Running test-stack@golang" \
&& chmod +x [email protected] \
&& bash [email protected] \
&& rm -rf [email protected]
RUN [ ! -d /.balena/messages ] && mkdir -p /.balena/messages; echo $'Here are a few details about this Docker image (For more information please visit https://www.balena.io/docs/reference/base-images/base-images/): \nArchitecture: ARM v7 \nOS: Alpine Linux 3.12 \nVariant: run variant \nDefault variable(s): UDEV=off \nThe following software stack is preinstalled: \nGo v1.17.7 \nExtra features: \n- Easy way to install packages with `install_packages <package-name>` command \n- Run anywhere with cross-build feature (for ARM only) \n- Keep the container idling with `balena-idle` command \n- Show base image details with `balena-info` command' > /.balena/messages/image-info
RUN echo $'#!/bin/bash\nbalena-info\nbusybox ln -sf /bin/busybox /bin/sh\n/bin/sh "$@"' > /bin/sh-shim \
&& chmod +x /bin/sh-shim \
&& ln -f /bin/sh /bin/sh.real \
&& ln -f /bin/sh-shim /bin/sh
|
apache-2.0
|
perka/flatpack-java
|
demo-client/src/test/java/com/getperka/flatpack/demo/client/ClientSmokeTest.java
|
8420
|
/*
* #%L
* FlatPack Demonstration Client
* %%
* Copyright (C) 2012 Perka Inc.
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
package com.getperka.flatpack.demo.client;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.net.HttpURLConnection;
import java.nio.charset.Charset;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.UUID;
import javax.ws.rs.core.UriBuilder;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import com.getperka.flatpack.Configuration;
import com.getperka.flatpack.FlatPack;
import com.getperka.flatpack.FlatPackEntity;
import com.getperka.flatpack.client.StatusCodeException;
import com.getperka.flatpack.demo.server.DemoServer;
/**
* Contains a variety of smoke tests to demonstrate various facets of the FlatPack stack.
*/
public class ClientSmokeTest {
private static final int PORT = 8111;
/**
* Spin up an instance of the demo server.
*/
@BeforeClass
public static void beforeClass() {
assertTrue(new DemoServer().start(PORT));
}
private ClientApi api;
private Random random;
/**
* Creates an instance of the ClientApi.
*/
@Before
public void before() throws IOException {
random = new Random(0);
Configuration config = new Configuration()
.addTypeSource(ClientTypeSource.get());
api = new ClientApi(FlatPack.create(config));
api.setServerBase(UriBuilder.fromUri("http://localhost").port(PORT).build());
api.setVerbose(true);
assertEquals(204, api.resetPost().execute().getResponseCode());
}
/**
* Demonstrates ConstraintViolation handling. ConstraintViolations are returned as a simple
* {@code string:string} map in the FlatPackEntity's {@code error} block. The goal is to provide
* enough context for user interfaces to present the error message in a useful way, without
* assuming that the client is a Java app.
*/
@Test
public void testConstraintViolation() throws IOException {
Product p = makeProduct();
p.setPrice(BigDecimal.valueOf(-1));
FlatPackEntity<?> entity = null;
try {
api.productsPut(Collections.singletonList(p))
.queryParameter("isAdmin", "true")
.execute();
fail("Should have seen StatusCodeException");
} catch (StatusCodeException e) {
// The 400 status code is returned by the service method.
assertEquals(400, e.getStatusCode());
/*
* If the server returned a valid flatpack-encoded response, it can be retrieved from the
* StatusCodeException. Otherwise, this method will return null.
*/
entity = e.getEntity();
}
// Pull out the error messages
Map<String, String> errors = entity.getExtraErrors();
assertNotNull(errors);
assertEquals(1, errors.size());
Map.Entry<String, String> entry = errors.entrySet().iterator().next();
assertEquals("price", entry.getKey());
assertEquals("must be greater than or equal to 0", entry.getValue());
}
/**
* Demonstrates how generated client API will present a non-FlatPack resource (as an
* HttpUrlConnection).
*/
@Test
public void testNonFlatpackEndpoint() throws IOException {
// The query parameters are added as a builder-style pattern
HttpURLConnection conn = api.helloGet().withName("ClientSmokeTest").execute();
assertEquals(200, conn.getResponseCode());
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(),
Charset.forName("UTF8")));
assertEquals("Hello ClientSmokeTest!", reader.readLine());
}
/**
* Demonstrates the use of roles to restrict property setters.
*/
@Test
public void testRolePropertyAccess() throws IOException {
// Create a Product
Product p = new Product();
UUID uuid = p.getUuid();
p.setName("Product");
p.setNotes("Some notes");
p.setPrice(BigDecimal.valueOf(42));
api.productsPut(Collections.singletonList(p))
.queryParameter("isAdmin", "true")
.execute();
// Try to update it with a non-admin request
p = new Product();
p.setUuid(uuid);
p.setPrice(BigDecimal.valueOf(1));
api.productsPut(Collections.singletonList(p)).execute();
// Verify that nothing changed, as nobody
List<Product> products = api.productsGet().execute().getValue();
assertEquals(1, products.size());
p = products.get(0);
// Same UUID
assertEquals(uuid, p.getUuid());
// Unchanged price
assertEquals(BigDecimal.valueOf(42), p.getPrice());
// Can't see the notes
assertNull(p.getNotes());
// Now try the update again, as an admin
p = new Product();
p.setUuid(uuid);
p.setPrice(BigDecimal.valueOf(99));
api.productsPut(Collections.singletonList(p))
.queryParameter("isAdmin", "true")
.execute();
// Verify the changes, as nobody
products = api.productsGet().execute().getValue();
assertEquals(1, products.size());
p = products.get(0);
// Same UUID
assertEquals(uuid, p.getUuid());
// Unchanged price
assertEquals(BigDecimal.valueOf(99), p.getPrice());
}
/**
* Demonstrates a couple of round-trips to the server.
*/
@Test
public void testSimpleGetAndPut() throws IOException {
List<Product> products = api.productsGet().execute().getValue();
assertEquals(0, products.size());
// A server error would be reported as a StatusCodeException, a subclass of IOException
api.productsPut(Arrays.asList(makeProduct(), makeProduct()))
.queryParameter("isAdmin", "true")
.execute();
/*
* The object returned from productsGet() is an endpoint-specific interface that may contain
* additional fluid setters for declared query parameters. It also provides access to some
* request internals, including the FlatPackEntity that will be sent as part of the request.
* This allows callers to further customize outgoing requests, in the above case to add the
* isAdmin query parameter that interacts with the DummyAuthenticator. The call to execute()
* triggers payload serialization and execution of the HTTP request. This returns a
* FlatPackEntity describing the response, and getValue() returns the primary value object
* contained in the payload.
*/
FlatPackEntity<List<Product>> entity = api.productsGet().execute();
assertTrue(entity.getExtraErrors().toString(), entity.getExtraErrors().isEmpty());
assertTrue(entity.getExtraWarnings().toString(), entity.getExtraWarnings().isEmpty());
products = entity.getValue();
assertEquals(2, products.size());
assertEquals(BigDecimal.valueOf(360), products.get(0).getPrice());
assertEquals(BigDecimal.valueOf(948), products.get(1).getPrice());
assertTrue(products.get(0).wasPersistent());
assertTrue(products.get(1).wasPersistent());
// Try to update one of the objects
Product p = products.get(0);
p.setPrice(BigDecimal.valueOf(99));
assertEquals(Collections.singleton("price"), p.dirtyPropertyNames());
api.productsPut(Collections.singletonList(p)).queryParameter("isAdmin", "true").execute();
// Re-fetch and verify update
products = api.productsGet().execute().getValue();
assertEquals(99, products.get(0).getPrice().intValue());
assertTrue(products.get(0).dirtyPropertyNames().isEmpty());
}
private Product makeProduct() {
Product p = new Product();
p.setName("ClientSmokeTest");
p.setPrice(BigDecimal.valueOf(random.nextInt(1000)));
return p;
}
}
|
apache-2.0
|
olympiag3/olypy
|
olymap/templates/master_gate_report.html
|
1024
|
<HTML>
<HEAD>
<script src="sorttable.js"></script><TITLE>Olympia Master Gate Report</TITLE>
</HEAD>
<BODY>
<H3>Olympia Master Gate Report</H3>
<h5>(Click on table headers to sort)</h5>
<table border="1" style="border-collapse: collapse" class="sortable">
<tr><th>Kind</th><th>Start</th><th>Destination</th></tr>
{% for entry in loc %}
<tr>
<td>{{ entry.kind }}</td>
{% if entry.road %}
{% if entry.road.from %}
<td>{{ entry.road.from.name }} [<a href="{{ entry.road.from.oid }}.html">{{ entry.road.from.oid }}</a>]</td>
{% else %}
<td> </td>
{% endif %}
{% if entry.road.from %}
<td>{{ entry.road.to.name }} [<a href="{{ entry.road.to.oid }}.html">{{ entry.road.to.oid }}</a>]</td>
{% else %}
<td> </td>
{% endif %}
{% else %}
<td> </td>
<td> </td>
{% endif %}
</tr>
{% endfor %}
</table>
</BODY>
</HTML>
|
apache-2.0
|
portdirect/harbor
|
docker/marina/marina-freeipa/README.md
|
514
|
# port/marina-freeipa
### Release Info
[](http://microbadger.com/images/port/marina-freeipa "Image info @ microbadger.com")
[](http://microbadger.com/images/port/marina-freeipa "Image info @ microbadger.com")
[](http://microbadger.com/images/port/marina-freeipa "Image info @ microbadger.com")
|
apache-2.0
|
shivanshu21/docker-volume-vsphere
|
esx_service/utils/vmdk_utils.py
|
19851
|
#!/usr/bin/env python
# Copyright 2016 VMware, 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.
# Utility functions for dealing with VMDKs and datastores
import os
import os.path
import glob
import re
import logging
import fnmatch
from pyVim import vmconfig
from pyVmomi import vim
import pyVim
from pyVim.invt import GetVmFolder, FindChild
from error_code import *
import threadutils
import vmdk_ops
import auth_data_const
import auth
import auth_api
import log_config
from error_code import *
# datastores should not change during 'vmdkops_admin' run,
# so using global to avoid multiple scans of /vmfs/volumes
datastores = None
# we assume files smaller that that to be descriptor files
MAX_DESCR_SIZE = 5000
# regexp for finding "snapshot" (aka delta disk) descriptor names
SNAP_NAME_REGEXP = r"^.*-[0-9]{6}$" # used for names without .vmdk suffix
SNAP_VMDK_REGEXP = r"^.*-[0-9]{6}\.vmdk$" # used for file names
# regexp for finding 'special' vmdk files (they are created by ESXi)
SPECIAL_FILES_REGEXP = r"\A.*-(delta|ctk|digest|flat)\.vmdk$"
# glob expression to match end of 'delta' (aka snapshots) file names.
SNAP_SUFFIX_GLOB = "-[0-9][0-9][0-9][0-9][0-9][0-9].vmdk"
# regexp for finding datastore path "[datastore] path/to/file.vmdk" from full vmdk path
DATASTORE_PATH_REGEXP = r"^/vmfs/volumes/([^/]+)/(.*\.vmdk)$"
# lsof command
LSOF_CMD = "/bin/vmkvsitools lsof"
# Number of times and sleep time to retry on IOError EBUSY
VMDK_RETRY_COUNT = 5
VMDK_RETRY_SLEEP = 1
# root for all the volumes
VOLUME_ROOT = "/vmfs/volumes/"
# For managing resource locks.
lockManager = threadutils.LockManager()
def init_datastoreCache(force=False):
"""
Initializes the datastore cache with the list of datastores accessible
from local ESX host. force=True will force it to ignore current cache
and force init
"""
with lockManager.get_lock("init_datastoreCache"):
global datastores
logging.debug("init_datastoreCache: %s", datastores)
if datastores and not force:
return
si = vmdk_ops.get_si()
# We are connected to ESX so childEntity[0] is current DC/Host
ds_objects = si.content.rootFolder.childEntity[0].datastoreFolder.childEntity
tmp_ds = []
for datastore in ds_objects:
dockvols_path, err = vmdk_ops.get_vol_path(datastore.info.name)
if err:
logging.error(" datastore %s is being ignored as the dockvol path can't be created on it", datastore.info.name)
continue
tmp_ds.append((datastore.info.name,
datastore.info.url,
dockvols_path))
datastores = tmp_ds
def validate_datastore(datastore):
"""
Checks if the datastore is part of datastoreCache.
If not it will update the datastore cache and check if datastore
is a part of the updated cache.
"""
init_datastoreCache()
if datastore in [i[0] for i in datastores]:
return True
else:
init_datastoreCache(force=True)
if datastore in [i[0] for i in datastores]:
return True
return False
def get_datastores():
"""
Returns a list of (name, url, dockvol_path), with an element per datastore
where:
'name' is datastore name (e.g. 'vsanDatastore') ,
'url' is datastore URL (e.g. '/vmfs/volumes/vsan:572904f8c031435f-3513e0db551fcc82')
'dockvol-path; is a full path to 'dockvols' folder on datastore
"""
init_datastoreCache()
return datastores
def get_volumes(tenant_re):
""" Return dicts of docker volumes, their datastore and their paths
"""
# Assume we have two tenants "tenant1" and "tenant2"
# volumes for "tenant1" are in /vmfs/volumes/datastore1/dockervol/tenant1
# volumes for "tenant2" are in /vmfs/volumes/datastore1/dockervol/tenant2
# volumes does not belongs to any tenants are under /vmfs/volumes/dockervol
# tenant_re = None : only return volumes which do not belong to a tenant
# tenant_re = "tenant1" : only return volumes which belongs to tenant1
# tenant_re = "tenant*" : return volumes which belong to tenant1 or tenant2
# tenant_re = "*" : return all volumes under /vmfs/volumes/datastore1/dockervol
logging.debug("get_volumes: tenant_pattern(%s)", tenant_re)
volumes = []
for (datastore, url, path) in get_datastores():
logging.debug("get_volumes: %s %s %s", datastore, url, path)
if not tenant_re:
for file_name in list_vmdks(path):
# path : docker_vol path
volumes.append({'path': path,
'filename': file_name,
'datastore': datastore})
else:
for root, dirs, files in os.walk(path):
# walkthough all files under docker_vol path
# root is the current directory which is traversing
# root = /vmfs/volumes/datastore1/dockervol/tenant1_uuid
# path = /vmfs/volumes/datastore1/dockervol
# sub_dir get the string "/tenant1_uuid"
# sub_dir_name is "tenant1_uuid"
# call get_tenant_name with "tenant1_uuid" to find corresponding
# tenant_name which will be used to match
# pattern specified by tenant_re
logging.debug("get_volumes: path=%s root=%s", path, root)
sub_dir = root.replace(path, "")
sub_dir_name = sub_dir[1:]
# sub_dir_name is the tenant uuid
error_info, tenant_name = auth_api.get_tenant_name(sub_dir_name)
if not error_info:
logging.debug("get_volumes: path=%s root=%s sub_dir_name=%s tenant_name=%s",
path, root, sub_dir_name, tenant_name)
if fnmatch.fnmatch(tenant_name, tenant_re):
for file_name in list_vmdks(root):
volumes.append({'path': root,
'filename': file_name,
'datastore': datastore,
'tenant': tenant_name})
else:
# cannot find this tenant, this tenant was removed
# mark those volumes created by "orphan" tenant
logging.debug("get_volumes: cannot find tenant_name for tenant_uuid=%s", sub_dir_name)
logging.debug("get_volumes: path=%s root=%s sub_dir_name=%s",
path, root, sub_dir_name)
# return orphan volumes only in case when volumes from any tenants are asked
if tenant_re == "*":
for file_name in list_vmdks(root):
volumes.append({'path': root,
'filename': file_name,
'datastore': datastore,
'tenant' : auth_data_const.ORPHAN_TENANT})
logging.debug("volumes %s", volumes)
return volumes
def get_vmdk_path(path, vol_name):
"""
If the volume-related VMDK exists, returns full path to the latest
VMDK disk in the disk chain, be it volume-NNNNNN.vmdk or volume.vmdk.
If the disk does not exists, returns full path to the disk for create().
"""
# Get a delta disk list, and if it's empty - return the full path for volume
# VMDK base file.
# Note: we rely on NEVER allowing '-NNNNNN' in end of a volume name and on
# the fact that ESXi always creates deltadisks as <name>-NNNNNN.vmdk (N is a
# digit, and there are exactly 6 digits there) for delta disks
#
# see vmdk_ops.py:parse_vol_name() which enforces the volume name rules.
delta_disks = glob.glob("{0}/{1}{2}".format(path, vol_name, SNAP_SUFFIX_GLOB))
if not delta_disks:
return os.path.join(path, "{0}.vmdk".format(vol_name))
# this funky code gets the name of the latest delta disk:
latest = sorted([(vmdk, os.stat(vmdk).st_ctime) for vmdk in delta_disks], key=lambda d: d[1], reverse=True)[0][0]
logging.debug("The latest delta disk is %s. All delta disks: %s", latest, delta_disks)
return latest
def get_datastore_path(vmdk_path):
"""Returns a string datastore path "[datastore] path/to/file.vmdk"
from a full vmdk path.
"""
match = re.search(DATASTORE_PATH_REGEXP, vmdk_path)
datastore, path = match.groups()
return "[{0}] {1}".format(datastore, path)
def get_datastore_from_vmdk_path(vmdk_path):
"""Returns a string representing the datastore from a full vmdk path.
"""
match = re.search(DATASTORE_PATH_REGEXP, vmdk_path)
datastore, path = match.groups()
return datastore
def get_volname_from_vmdk_path(vmdk_path):
"""Returns the volume name from a full vmdk path.
"""
match = re.search(DATASTORE_PATH_REGEXP, vmdk_path)
_, path = match.groups()
vmdk = path.split("/")[-1]
return strip_vmdk_extension(vmdk)
def list_vmdks(path, volname="", show_snapshots=False):
""" Return a list of VMDKs in a given path. Filters out non-descriptor
files and delta disks.
Params:
path - where the VMDKs are looked for
volname - if passed, only files related to this VMDKs will be returned. Useful when
doing volume snapshot inspect
show_snapshots - if set to True, all VMDKs (including delta files) will be returned
"""
# dockvols may not exists on a datastore - this is normal.
if not os.path.exists(path):
return []
logging.debug("list_vmdks: dockvol existed on datastore")
vmdks = [f for f in os.listdir(path) if vmdk_is_a_descriptor(path, f)]
if volname:
vmdks = [f for f in vmdks if f.startswith(volname)]
if not show_snapshots:
expr = re.compile(SNAP_VMDK_REGEXP)
vmdks = [f for f in vmdks if not expr.match(f)]
logging.debug("vmdks %s", vmdks)
return vmdks
def vmdk_is_a_descriptor(path, file_name):
"""
Is the file a vmdk descriptor file? We assume any file that ends in .vmdk,
does not have -delta or -flat or -digest or -ctk at the end of filename,
and has a size less than MAX_DESCR_SIZE is a descriptor file.
"""
name = file_name.lower()
# filter out all files with wrong extention
# also filter out -delta, -flat, -digest and -ctk VMDK files
if not name.endswith('.vmdk') or re.match(SPECIAL_FILES_REGEXP, name):
return False
# Check the size. It's a cheap(ish) way to check for descriptor,
# without actually checking the file content and risking lock conflicts
try:
if os.stat(os.path.join(path, file_name)).st_size > MAX_DESCR_SIZE:
return False
except OSError:
pass # if file does not exist, assume it's small enough
return True
def strip_vmdk_extension(filename):
""" Remove the .vmdk file extension from a string """
return filename.replace(".vmdk", "")
def get_vm_uuid_by_name(vm_name):
""" Returns vm_uuid for given vm_name, or None """
si = vmdk_ops.get_si()
try:
vm = FindChild(GetVmFolder(), vm_name)
return vm.config.uuid
except:
return None
def get_vm_name_by_uuid(vm_uuid):
""" Returns vm_name for given vm_uuid, or None """
si = vmdk_ops.get_si()
try:
return vmdk_ops.vm_uuid2name(vm_uuid)
except:
return None
def get_vm_config_path(vm_name):
"""Returns vm_uuid for given vm_name, or None """
si = vmdk_ops.get_si()
try:
vm = FindChild(GetVmFolder(), vm_name)
config_path = vm.summary.config.vmPathName
except:
return None
# config path has the format like this "[datastore1] test_vm1/test_vm1/test_vm1.vmx"
datastore, path = config_path.split()
datastore = datastore[1:-1]
datastore_path = os.path.join("/vmfs/volumes/", datastore)
# datastore_path has the format like this /vmfs/volumes/datastore_name
vm_config_path = os.path.join(datastore_path, path)
return vm_config_path
def get_attached_volume_path(vm, volname, datastore):
"""
Returns full path for docker volume "volname", residing on "datastore" and attached to "VM"
Files a warning and returns None if the volume is not attached
"""
# Find the attached disk with backing matching "[datastore] dockvols/[.*]/volname[-ddddddd]?.vmdk"
# SInce we don't know the vmgroup (the path after dockvols), we'll just pick the first match (and yell if
# there is more than one match)
# Yes, it is super redundant - we will find VM, scan disks and find a matching one here, then return the path
# and it will likely be used to do the same steps - find VM, scan the disks, etc.. It's a hack and it's a corner
# case, so we'll live with this
# Note that if VM is moved to a different vmgroup in flight, we may fail here and it's fine.
# Note that if there is a volume with the same name in 2 different vmgroup folders and both are attached
# and VM is moved between the groups we may end up returning the wrong volume but not possible, as the user
# would need to change VMgroup in-flight and admin tool would block it when volumes are attached.
if not datastore:
# we rely on datastore always being a part of volume name passed to detach.
# if this contract breaks, or we are called from somewhere else - bail out
logging.error("get_attached_volume_path internal error - empty datastore")
return None
# look for '[datastore] dockvols/tenant/volume.vmdk' name
# and account for delta disks (e.g. volume-000001.vmdk)
prog = re.compile('\[%s\] %s/[^/]+/%s(-[0-9]{6})?\.vmdk$' %
(datastore, vmdk_ops.DOCK_VOLS_DIR, volname))
attached = [d for d in vm.config.hardware.device \
if isinstance(d, vim.VirtualDisk) and \
isinstance(d.backing, vim.VirtualDisk.FlatVer2BackingInfo) and \
prog.match(d.backing.fileName)]
if len(attached) == 0:
logging.error("Can't find device attached to '%s' for volume '%s' on [%s].",
vm.config.name, volname, datastore)
return None
if len(attached) > 1:
logging.warning("More than 1 device attached to '%s' for volume '%s' on [%s].",
vm.config.name, volname, datastore)
path = find_dvs_volume(attached[0])
logging.warning("Found path: %s", path)
return path
def find_dvs_volume(dev):
"""
If the @param dev (type is vim.vm.device) a vDVS managed volume, return its vmdk path
"""
# if device is not a virtual disk, skip this device
if type(dev) != vim.vm.device.VirtualDisk:
return False
# Filename format is as follows:
# "[<datastore name>] <parent-directory>/tenant/<vmdk-descriptor-name>"
# Trim the datastore name and keep disk path.
datastore_name, disk_path = dev.backing.fileName.rsplit("]", 1)
logging.info("backing disk name is %s", disk_path)
# name formatting to remove unwanted characters
datastore_name = datastore_name[1:]
disk_path = disk_path.lstrip()
# find the dockvols dir on current datastore and resolve symlinks if any
dvol_dir_path = os.path.realpath(os.path.join(VOLUME_ROOT,
datastore_name, vmdk_ops.DOCK_VOLS_DIR))
dvol_dir = os.path.basename(dvol_dir_path)
if disk_path.startswith(dvol_dir):
# returning the vmdk path for vDVS volume
return os.path.join(VOLUME_ROOT, datastore_name, disk_path)
return None
def check_volumes_mounted(vm_list):
"""
Return error_info if any vm in @param vm_list have docker volume mounted
"""
for vm_id, _ in vm_list:
vm = vmdk_ops.findVmByUuid(vm_id)
if vm:
for d in vm.config.hardware.device:
if find_dvs_volume(d):
error_info = generate_error_info(ErrorCode.VM_WITH_MOUNTED_VOLUMES,
vm.config.name)
return error_info
else:
error_info = generate_error_info(ErrorCode.VM_NOT_FOUND, vm_id)
return error_info
return None
def log_volume_lsof(vol_name):
"""Log volume open file descriptors"""
rc, out = vmdk_ops.RunCommand(LSOF_CMD)
if rc != 0:
logging.error("Error running lsof for %s: %s", vol_name, out)
return
for line in out.splitlines():
# Make sure we only match the lines pertaining to that volume files.
if re.search(r".*/vmfs/volumes/.*{0}.*".format(vol_name), line):
cartel, name, ftype, fd, desc = line.split()
msg = "cartel={0}, name={1}, type={2}, fd={3}, desc={4}".format(
cartel, name, ftype, fd, desc)
logging.info("Volume open descriptor: %s", msg)
def get_datastore_objects():
""" return all datastore objects """
si = vmdk_ops.get_si()
return si.content.rootFolder.childEntity[0].datastore
def get_datastore_url(datastore_name):
""" return datastore url for given datastore name """
# Return datastore url for datastore name "_VM_DS""
if datastore_name == auth_data_const.VM_DS:
return auth_data_const.VM_DS_URL
# Return datastore url for datastore name "_ALL_DS""
if datastore_name == auth_data_const.ALL_DS:
return auth_data_const.ALL_DS_URL
# validate_datastore will refresh the cache if datastore_name is not in cache
if not validate_datastore(datastore_name):
return None
# Query datastore URL from VIM API
# get_datastores() return a list of tuple
# each tuple has format like (datastore_name, datastore_url, dockvol_path)
res = [d[1] for d in get_datastores() if d[0] == datastore_name]
return res[0]
def get_datastore_name(datastore_url):
""" return datastore name for given datastore url """
# Return datastore name for datastore url "_VM_DS_URL""
if datastore_url == auth_data_const.VM_DS_URL:
return auth_data_const.VM_DS
# Return datastore name for datastore url "_ALL_DS_URL""
if datastore_url == auth_data_const.ALL_DS_URL:
return auth_data_const.ALL_DS
# Query datastore name from VIM API
# get_datastores() return a list of tuple
# each tuple has format like (datastore_name, datastore_url, dockvol_path)
res = [d[0] for d in get_datastores() if d[1] == datastore_url]
logging.debug("get_datastore_name: res=%s", res)
return res[0] if res else None
def get_datastore_url_from_config_path(config_path):
"""Returns datastore url in config_path """
# path can be /vmfs/volumes/<datastore_url_name>/...
# or /vmfs/volumes/datastore_name/...
# so extract datastore_url_name:
config_ds_url = os.path.join("/vmfs/volumes/",
os.path.realpath(config_path).split("/")[3])
logging.debug("get_datastore_url_from_config_path: config_path=%s config_ds_url=%s"
% (config_path, config_ds_url))
return config_ds_url
def main():
log_config.configure()
if __name__ == "__main__":
main()
|
apache-2.0
|
info-appmart/OthersMethods
|
src/com/example/testconnectionappmart/Service.java
|
3650
|
package com.example.testconnectionappmart;
public class Service {
private int id;
private String discountEndDt;
private String discountPrice;
private String logoImagePath;
private String discountAmount;
private String saveType;
private String appmartPrice;
private String serviceName;
private String appName;
private String exp;
private String price;
private String serviceId;
private String cntCycle;
private String saleType;
private String discountStartDt;
private String policy;
private String developId;
private String discountRate;
private String dayCycle;
private String setlType;
private String monthCycle;
//constructor
//constructor
public Service(){}
public Service(String serviceId){
this.serviceId= serviceId;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getServiceId() {
return serviceId;
}
public void setServiceId(String serviceId) {
this.serviceId = serviceId;
}
public String getDiscountEndDt() {
return discountEndDt;
}
public void setDiscountEndDt(String discountEndDt) {
this.discountEndDt = discountEndDt;
}
public String getDiscountPrice() {
return discountPrice;
}
public void setDiscountPrice(String discountPrice) {
this.discountPrice = discountPrice;
}
public String getLogoImagePath() {
return logoImagePath;
}
public void setLogoImagePath(String logoImagePath) {
this.logoImagePath = logoImagePath;
}
public String getDiscountAmount() {
return discountAmount;
}
public void setDiscountAmount(String discountAmount) {
this.discountAmount = discountAmount;
}
public String getSaveType() {
return saveType;
}
public void setSaveType(String saveType) {
this.saveType = saveType;
}
public String getAppmartPrice() {
return appmartPrice;
}
public void setAppmartPrice(String appmartPrice) {
this.appmartPrice = appmartPrice;
}
public String getServiceName() {
return serviceName;
}
public void setServiceName(String serviceName) {
this.serviceName = serviceName;
}
public String getAppName() {
return appName;
}
public void setAppName(String appName) {
this.appName = appName;
}
public String getExp() {
return exp;
}
public void setExp(String exp) {
this.exp = exp;
}
public String getPrice() {
return price;
}
public void setPrice(String price) {
this.price = price;
}
public String getCntCycle() {
return cntCycle;
}
public void setCntCycle(String cntCycle) {
this.cntCycle = cntCycle;
}
public String getSaleType() {
return saleType;
}
public void setSaleType(String saleType) {
this.saleType = saleType;
}
public String getDiscountStartDt() {
return discountStartDt;
}
public void setDiscountStartDt(String discountStartDt) {
this.discountStartDt = discountStartDt;
}
public String getPolicy() {
return policy;
}
public void setPolicy(String policy) {
this.policy = policy;
}
public String getDevelopId() {
return developId;
}
public void setDevelopId(String developId) {
this.developId = developId;
}
public String getDiscountRate() {
return discountRate;
}
public void setDiscountRate(String discountRate) {
this.discountRate = discountRate;
}
public String getDayCycle() {
return dayCycle;
}
public void setDayCycle(String dayCycle) {
this.dayCycle = dayCycle;
}
public String getSetlType() {
return setlType;
}
public void setSetlType(String setlType) {
this.setlType = setlType;
}
public String getMonthCycle() {
return monthCycle;
}
public void setMonthCycle(String monthCycle) {
this.monthCycle = monthCycle;
}
}
|
apache-2.0
|
fusepoolP3/p3-silk
|
silk-workbench-outdated/src/main/scala/de/fuberlin/wiwiss/silk/workbench/lift/snippet/Branding.scala
|
1390
|
package de.fuberlin.wiwiss.silk.workbench.lift.snippet
/*
* 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 net.liftweb.util._
import Helpers._
import java.util.Properties
import java.io.{FileNotFoundException, FileReader, File}
class Branding {
var workbenchName = "Silk Workbench"
try {
var configPath = scala.util.Properties.propOrElse("SILK_WORKBENCH_CONFIG_PATH", "")
if (configPath.equals("") && !configPath.endsWith(File.separator)){
configPath += File.separator
}
val configFile = new File(configPath + "config.properties");
val properties = new Properties()
properties.load(new FileReader(configFile))
if(properties.getProperty("workbenchName") != null) workbenchName = properties.getProperty("workbenchName")
} catch {
case _ : FileNotFoundException =>
{
}
}
def render = "*" #> workbenchName
}
|
apache-2.0
|
AnimeROM/android_package_AnimeManager
|
src/com/animerom/filemanager/commands/shell/ChangePermissionsCommand.java
|
2364
|
package com.animerom.filemanager.commands.shell;
import com.animerom.filemanager.commands.ChangePermissionsExecutable;
import com.animerom.filemanager.console.CommandNotFoundException;
import com.animerom.filemanager.console.ExecutionException;
import com.animerom.filemanager.console.InsufficientPermissionsException;
import com.animerom.filemanager.model.MountPoint;
import com.animerom.filemanager.model.Permissions;
import com.animerom.filemanager.util.MountPointHelper;
import java.text.ParseException;
/**
* A class for change the permissions of an object.
*
* {@link "http://unixhelp.ed.ac.uk/CGI/man-cgi?chmod"}
*/
public class ChangePermissionsCommand
extends SyncResultProgram implements ChangePermissionsExecutable {
private static final String ID = "chmod"; //$NON-NLS-1$
private Boolean mRet;
private final String mFileName;
/**
* Constructor of <code>ChangePermissionsCommand</code>.
*
* @param fileName The name of the file or directory to be moved
* @param newPermissions The new permissions to apply to the object
* @throws InvalidCommandDefinitionException If the command has an invalid definition
*/
public ChangePermissionsCommand(
String fileName, Permissions newPermissions) throws InvalidCommandDefinitionException {
super(ID, newPermissions.toOctalString(), fileName);
this.mFileName = fileName;
}
/**
* {@inheritDoc}
*/
@Override
public void parse(String in, String err) throws ParseException {
//Release the return object
this.mRet = Boolean.TRUE;
}
/**
* {@inheritDoc}
*/
@Override
public Boolean getResult() {
return this.mRet;
}
/**
* {@inheritDoc}
*/
@Override
public void checkExitCode(int exitCode)
throws InsufficientPermissionsException, CommandNotFoundException, ExecutionException {
if (exitCode != 0) {
throw new ExecutionException("exitcode != 0"); //$NON-NLS-1$
}
}
/**
* {@inheritDoc}
*/
@Override
public MountPoint getSrcWritableMountPoint() {
return null;
}
/**
* {@inheritDoc}
*/
@Override
public MountPoint getDstWritableMountPoint() {
return MountPointHelper.getMountPointFromDirectory(this.mFileName);
}
}
|
apache-2.0
|
Getsidecar/googleads-php-lib
|
examples/Dfp/v201702/ProposalService/UpdateProposals.php
|
2856
|
<?php
/**
* This example updates a proposal's notes. To determine which proposals exist,
* run GetAllProposals.php.
*
* PHP version 5
*
* Copyright 2014, 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 GoogleApiAdsDfp
* @subpackage v201702
* @category WebServices
* @copyright 2014, Google Inc. All Rights Reserved.
* @license http://www.apache.org/licenses/LICENSE-2.0 Apache License,
* Version 2.0
*/
error_reporting(E_STRICT | E_ALL);
// You can set the include path to src directory or reference
// DfpUser.php directly via require_once.
// $path = '/path/to/dfp_api_php_lib/src';
$path = dirname(__FILE__) . '/../../../../src';
set_include_path(get_include_path() . PATH_SEPARATOR . $path);
require_once 'Google/Api/Ads/Dfp/Lib/DfpUser.php';
require_once 'Google/Api/Ads/Dfp/Util/v201702/StatementBuilder.php';
require_once dirname(__FILE__) . '/../../../Common/ExampleUtils.php';
// Set the ID of the proposal to update.
$proposalId = 'INSERT_PROPOSAL_ID_HERE';
try {
// Get DfpUser from credentials in "../auth.ini"
// relative to the DfpUser.php file's directory.
$user = new DfpUser();
// Log SOAP XML request and response.
$user->LogDefaults();
// Get the ProposalService.
$proposalService = $user->GetService('ProposalService', 'v201702');
// Create a statement to select a single proposal by ID.
$statementBuilder = new StatementBuilder();
$statementBuilder->Where('id = :id')
->OrderBy('id ASC')
->Limit(1)
->WithBindVariableValue('id', $proposalId);
// Get the proposal.
$page = $proposalService->getProposalsByStatement(
$statementBuilder->ToStatement());
$proposal = $page->results[0];
// Update the proposal's notes.
$proposal->internalNotes = 'Proposal needs further review before approval.';
// Update the proposal on the server.
$proposals = $proposalService->updateProposals(array($proposal));
foreach ($proposals as $updatedProposal) {
printf("Proposal with ID %d and name '%s' was updated.\n",
$updatedProposal->id, $updatedProposal->name);
}
} catch (OAuth2Exception $e) {
ExampleUtils::CheckForOAuth2Errors($e);
} catch (ValidationException $e) {
ExampleUtils::CheckForOAuth2Errors($e);
} catch (Exception $e) {
printf("%s\n", $e->getMessage());
}
|
apache-2.0
|
rostam/gradoop
|
gradoop-flink/src/test/java/org/gradoop/flink/model/impl/operators/matching/single/cypher/common/functions/ReverseEdgeEmbeddingTest.java
|
1568
|
/*
* Copyright © 2014 - 2019 Leipzig University (Database Research Group)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gradoop.flink.model.impl.operators.matching.single.cypher.common.functions;
import org.gradoop.common.model.impl.id.GradoopId;
import org.gradoop.flink.model.impl.operators.matching.single.cypher.functions.ReverseEdgeEmbedding;
import org.gradoop.flink.model.impl.operators.matching.single.cypher.pojos.Embedding;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class ReverseEdgeEmbeddingTest {
@Test
public void testReversingAnEdgeEmbedding() throws Exception {
GradoopId a = GradoopId.get();
GradoopId e = GradoopId.get();
GradoopId b = GradoopId.get();
Embedding edge = new Embedding();
edge.add(a);
edge.add(e);
edge.add(b);
ReverseEdgeEmbedding op = new ReverseEdgeEmbedding();
Embedding reversed = op.map(edge);
assertEquals(b, reversed.getId(0));
assertEquals(e, reversed.getId(1));
assertEquals(a, reversed.getId(2));
}
}
|
apache-2.0
|
Weasyl/weasyl
|
weasyl/templates/help/folder-options.html
|
4513
|
$:{TITLE("Folder Options", "Help", "/help")}
<div class="content">
<div class="constrained">
<h3>Using Weasyl's Folder Options</h3>
<div class="formatted-content">
<p>Weasyl has the ability to customize how folders that you create inside your submissions gallery work! To do this, you must be logged in, and create at least one folder in <a href="/manage/folders">Submission Folders</a>.</p>
<p>Once you have done this, a new section will appear on your Submissions Folders page named <strong>Edit Folder Options</strong>. For example, here we've created the folder <em>Really Neat Stuff</em>.
<figure class="help-image">
<img src="${resource_path('img/help/help-folder-options1.png')}" alt="Selection of a folder whose options should be edited">
</figure>
<p>You'll be able to select <em>Really Neat Stuff</em> as a link, and be taken to Weasyl's Folder Options. This is what it looks like:</p>
<figure class="help-image">
<img src="${resource_path('img/help/help-folder-options2.png')}" alt="Weasyl’s Folder Options page">
</figure>
</div>
<a href="#featured-submissions" class="faq-permalink">Link</a>
<h3 id="featured-submissions">Using Folders to Set Featured Submissions</h3>
<div class="formatted-content">
<p>After setting up a submissions folder, you can enable the <strong>featured submissions</strong> option on it. When you do, your options will look like this:</p>
<figure class="help-image">
<img src="${resource_path('img/help/help-folder-options3.png')}" alt="Setting the “this is a featured submissions folder’ option">
</figure>
<p>On Weasyl, if you do not have <strong>any</strong> folders enabled with this option, <a href="/~">your profile page</a> will prominently display the most recent image you've uploaded, with the header <strong>Most Recent</strong>.</p>
<p>When one or more folders has the above option checked, Weasyl will replace the <em>Most Recent</em> image on your profile with <strong>Featured Submission</strong>.</p>
<p>Weasyl chooses an image at random from among Featured Submission folders, to display as your featured submission, and does this with each visit to your profile page.</p>
<p>If you really want one single submission to <strong>always</strong> be shown as your featured submission, we recommend creating a folder with that submission inside it, and enabling only that folder with the Featured Submission option.</p>
</div>
<a href="#scraps-folder" class="faq-permalink">Link</a>
<h3 id="scraps-folder">Creating a "Scraps" Folder</h3>
<div class="formatted-content">
<p>Many people like to have a folder where works created in it are not shown on their profile or submissions pages (or on Weasyl's front page), but <strong>do</strong> want their followers notified when they're uploaded. Typically Internet art sites call these "Scraps" folders. If you'd like your own, select a folder and set the following options, and you're done!</p>
<figure class="help-image">
<img src="${resource_path('img/help/help-folder-options4.png')}" alt="Setting the “will not appear on Weasyl’s front page” and “will not appear on your profile or submissions pages” options">
</figure>
</div>
<a href="#spamming-followers" class="faq-permalink">Link</a>
<h3 id="spamming-followers">Avoiding "Spamming" Followers With Mass Uploads</h3>
<div class="formatted-content">
<p>If you plan to upload a lot of submissions, but don't want to "spam your followers with notifications", Weasyl lets you do this too! Create a folder, and set the following option on it:</p>
<figure class="help-image">
<img src="${resource_path('img/help/help-folder-options5.png')}" alt="Setting the ‘Do not generate “new submission” notifications to your followers’ option">
</figure>
<p>You're ready to submit works into this folder, quietly! Once you're done, all you need to do is remove this option and followers will once again get notifications when you create new submissions in this folder.</p>
<p><strong>Advanced:</strong> If you <em>really</em> want to be clever, you can go to <a href="/manage/folders">Submission Folders</a> once you're done with your "quiet" uploads, and delete the folder. This will move all of the submissions you've just "quietly" added directly into your "top" folder.</p>
</div>
</div>
</div>
|
apache-2.0
|
moosbusch/xbLIDO
|
src/net/opengis/gml/MultiSurfaceDomainType.java
|
8916
|
/*
* Copyright 2013 Gunnar Kappei.
*
* 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 net.opengis.gml;
/**
* An XML MultiSurfaceDomainType(@http://www.opengis.net/gml).
*
* This is a complex type.
*/
public interface MultiSurfaceDomainType extends net.opengis.gml.DomainSetType
{
public static final org.apache.xmlbeans.SchemaType type = (org.apache.xmlbeans.SchemaType)
org.apache.xmlbeans.XmlBeans.typeSystemForClassLoader(MultiSurfaceDomainType.class.getClassLoader(), "schemaorg_apache_xmlbeans.system.s6E28D279B6C224D74769DB8B98AF1665").resolveHandle("multisurfacedomaintype70a9type");
/**
* Gets the "MultiSurface" element
*/
net.opengis.gml.MultiSurfaceType getMultiSurface();
/**
* True if has "MultiSurface" element
*/
boolean isSetMultiSurface();
/**
* Sets the "MultiSurface" element
*/
void setMultiSurface(net.opengis.gml.MultiSurfaceType multiSurface);
/**
* Appends and returns a new empty "MultiSurface" element
*/
net.opengis.gml.MultiSurfaceType addNewMultiSurface();
/**
* Unsets the "MultiSurface" element
*/
void unsetMultiSurface();
/**
* A factory class with static methods for creating instances
* of this type.
*/
public static final class Factory
{
public static net.opengis.gml.MultiSurfaceDomainType newInstance() {
return (net.opengis.gml.MultiSurfaceDomainType) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().newInstance( type, null ); }
public static net.opengis.gml.MultiSurfaceDomainType newInstance(org.apache.xmlbeans.XmlOptions options) {
return (net.opengis.gml.MultiSurfaceDomainType) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().newInstance( type, options ); }
/** @param xmlAsString the string value to parse */
public static net.opengis.gml.MultiSurfaceDomainType parse(java.lang.String xmlAsString) throws org.apache.xmlbeans.XmlException {
return (net.opengis.gml.MultiSurfaceDomainType) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( xmlAsString, type, null ); }
public static net.opengis.gml.MultiSurfaceDomainType parse(java.lang.String xmlAsString, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException {
return (net.opengis.gml.MultiSurfaceDomainType) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( xmlAsString, type, options ); }
/** @param file the file from which to load an xml document */
public static net.opengis.gml.MultiSurfaceDomainType parse(java.io.File file) throws org.apache.xmlbeans.XmlException, java.io.IOException {
return (net.opengis.gml.MultiSurfaceDomainType) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( file, type, null ); }
public static net.opengis.gml.MultiSurfaceDomainType parse(java.io.File file, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException {
return (net.opengis.gml.MultiSurfaceDomainType) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( file, type, options ); }
public static net.opengis.gml.MultiSurfaceDomainType parse(java.net.URL u) throws org.apache.xmlbeans.XmlException, java.io.IOException {
return (net.opengis.gml.MultiSurfaceDomainType) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( u, type, null ); }
public static net.opengis.gml.MultiSurfaceDomainType parse(java.net.URL u, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException {
return (net.opengis.gml.MultiSurfaceDomainType) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( u, type, options ); }
public static net.opengis.gml.MultiSurfaceDomainType parse(java.io.InputStream is) throws org.apache.xmlbeans.XmlException, java.io.IOException {
return (net.opengis.gml.MultiSurfaceDomainType) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( is, type, null ); }
public static net.opengis.gml.MultiSurfaceDomainType parse(java.io.InputStream is, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException {
return (net.opengis.gml.MultiSurfaceDomainType) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( is, type, options ); }
public static net.opengis.gml.MultiSurfaceDomainType parse(java.io.Reader r) throws org.apache.xmlbeans.XmlException, java.io.IOException {
return (net.opengis.gml.MultiSurfaceDomainType) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( r, type, null ); }
public static net.opengis.gml.MultiSurfaceDomainType parse(java.io.Reader r, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException {
return (net.opengis.gml.MultiSurfaceDomainType) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( r, type, options ); }
public static net.opengis.gml.MultiSurfaceDomainType parse(javax.xml.stream.XMLStreamReader sr) throws org.apache.xmlbeans.XmlException {
return (net.opengis.gml.MultiSurfaceDomainType) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( sr, type, null ); }
public static net.opengis.gml.MultiSurfaceDomainType parse(javax.xml.stream.XMLStreamReader sr, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException {
return (net.opengis.gml.MultiSurfaceDomainType) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( sr, type, options ); }
public static net.opengis.gml.MultiSurfaceDomainType parse(org.w3c.dom.Node node) throws org.apache.xmlbeans.XmlException {
return (net.opengis.gml.MultiSurfaceDomainType) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( node, type, null ); }
public static net.opengis.gml.MultiSurfaceDomainType parse(org.w3c.dom.Node node, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException {
return (net.opengis.gml.MultiSurfaceDomainType) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( node, type, options ); }
/** @deprecated {@link org.apache.xmlbeans.xml.stream.XMLInputStream} */
@Deprecated
public static net.opengis.gml.MultiSurfaceDomainType parse(org.apache.xmlbeans.xml.stream.XMLInputStream xis) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException {
return (net.opengis.gml.MultiSurfaceDomainType) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( xis, type, null ); }
/** @deprecated {@link org.apache.xmlbeans.xml.stream.XMLInputStream} */
@Deprecated
public static net.opengis.gml.MultiSurfaceDomainType parse(org.apache.xmlbeans.xml.stream.XMLInputStream xis, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException {
return (net.opengis.gml.MultiSurfaceDomainType) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( xis, type, options ); }
/** @deprecated {@link org.apache.xmlbeans.xml.stream.XMLInputStream} */
@Deprecated
public static org.apache.xmlbeans.xml.stream.XMLInputStream newValidatingXMLInputStream(org.apache.xmlbeans.xml.stream.XMLInputStream xis) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException {
return org.apache.xmlbeans.XmlBeans.getContextTypeLoader().newValidatingXMLInputStream( xis, type, null ); }
/** @deprecated {@link org.apache.xmlbeans.xml.stream.XMLInputStream} */
@Deprecated
public static org.apache.xmlbeans.xml.stream.XMLInputStream newValidatingXMLInputStream(org.apache.xmlbeans.xml.stream.XMLInputStream xis, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException {
return org.apache.xmlbeans.XmlBeans.getContextTypeLoader().newValidatingXMLInputStream( xis, type, options ); }
private Factory() { } // No instance of this class allowed
}
}
|
apache-2.0
|
mmmsplay10/QuizUpWinner
|
quizup/o/ฯ.java
|
2925
|
package o;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.util.TypedValue;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView.LayoutParams;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import com.quizup.core.QuizApplication;
import com.quizup.core.activities.WallpaperActivity;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
public final class ฯ extends BaseAdapter
{
public ArrayList<Υ> ˊ;
private WallpaperActivity ˋ;
private Bitmap ˎ;
private int ˏ;
public ฯ(WallpaperActivity paramWallpaperActivity)
{
this.ˋ = paramWallpaperActivity;
this.ˊ = ϟ.ˊ(QuizApplication.ᐝ());
this.ˏ = ((int)TypedValue.applyDimension(1, 120.0F, Resources.getSystem().getDisplayMetrics()));
Υ localΥ = new Υ(paramWallpaperActivity);
localΥ.ˊ = "file://wallpaper:pattern_1:purple";
this.ˎ = ϟ.ˊ(paramWallpaperActivity, localΥ, this.ˏ);
}
public final int getCount()
{
return this.ˊ.size();
}
public final long getItemId(int paramInt)
{
return 0L;
}
public final View getView(int paramInt, View paramView, ViewGroup paramViewGroup)
{
ImageView localImageView2;
if (paramView == null)
{
ImageView localImageView1 = new ImageView(this.ˋ);
localImageView2 = localImageView1;
localImageView1.setLayoutParams(new AbsListView.LayoutParams(this.ˏ, this.ˏ));
}
else
{
localImageView2 = (ImageView)paramView;
}
int i;
if (((Υ)this.ˊ.get(paramInt)).ˋ == null)
i = 1;
else
i = 0;
if (i != 0)
{
Υ localΥ = (Υ)this.ˊ.get(paramInt);
ImageView localImageView3 = localImageView2;
if (localImageView3 != null)
{
Drawable localDrawable = localImageView3.getDrawable();
if ((localDrawable instanceof ฯ.if))
{
localʇ1 = (ʇ)((ฯ.if)localDrawable).ˊ.get();
break label140;
}
}
ʇ localʇ1 = null;
label140: ʇ localʇ2 = localʇ1;
if (localʇ1 != null)
if (localʇ2.ˊ.equals(localΥ))
{
localʇ2.cancel(true);
}
else
{
j = 0;
break label181;
}
int j = 1;
label181: if (j != 0)
{
ʇ localʇ3 = new ʇ(this.ˋ, localImageView3, localΥ, this.ˏ);
localImageView3.setImageDrawable(new ฯ.if(this.ˋ.getResources(), this.ˎ, localʇ3));
localʇ3.execute(new Void[0]);
}
return localImageView2;
}
localImageView2.setImageBitmap(((Υ)this.ˊ.get(paramInt)).ˋ);
return localImageView2;
}
}
/* Location: /Users/vikas/Documents/Mhacks_Real_app/classes-dex2jar.jar
* Qualified Name: o.ฯ
* JD-Core Version: 0.6.2
*/
|
apache-2.0
|
d-ulyanov/log4php-graylog2
|
src/main/php/layouts/LoggerLayoutGelf.php
|
8053
|
<?php
/**
* 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.
*/
/**
* This layout outputs events in a JSON-encoded GELF format.
*
* This class was originally contributed by Dmitry Ulyanov.
*
* ## Configurable parameters: ##
*
* - **host** - Server on which logs are collected.
* - **shortMessageLength** - Maximum length of short message.
* - **locationInfo** - If set to true, adds the file name and line number at
* which the log statement originated. Slightly slower, defaults to false.
*
* @package log4php
* @subpackage layouts
* @since 2.4.0
* @license http://www.apache.org/licenses/LICENSE-2.0 Apache License, Version 2.0
* @link http://logging.apache.org/log4php/docs/layouts/html.html Layout documentation
* @link http://github.com/d-ulyanov/log4php-graylog2 Dmitry Ulyanov's original submission.
* @link http://graylog2.org/about/gelf GELF documentation.
*/
class LoggerLayoutGelf extends LoggerLayout {
/**
* GELF log levels according to syslog priority
*/
const LEVEL_EMERGENCY = 0;
const LEVEL_ALERT = 1;
const LEVEL_CRITICAL = 2;
const LEVEL_ERROR = 3;
const LEVEL_WARNING = 4;
const LEVEL_NOTICE = 5;
const LEVEL_INFO = 6;
const LEVEL_DEBUG = 7;
/**
* Version of Graylog2 GELF protocol (1.1 since 11/2013)
*/
const GELF_PROTOCOL_VERSION = '1.1';
/**
* Whether to log location information (file and line number).
* @var boolean
*/
protected $locationInfo = false;
/**
* Maximum length of short message
* @var int
*/
protected $shortMessageLength = 255;
/**
* Server on which logs are collected
* @var string
*/
protected $host;
/**
* Maps log4php levels to equivalent Gelf levels
* @var array
*/
protected $levelMap = array(
LoggerLevel::TRACE => self::LEVEL_DEBUG,
LoggerLevel::DEBUG => self::LEVEL_DEBUG,
LoggerLevel::INFO => self::LEVEL_INFO,
LoggerLevel::WARN => self::LEVEL_WARNING,
LoggerLevel::ERROR => self::LEVEL_ERROR,
LoggerLevel::FATAL => self::LEVEL_CRITICAL,
);
public function activateOptions() {
if (!$this->getHost()) {
$this->setHost(gethostname());
}
return parent::activateOptions();
}
/**
* @param LoggerLoggingEvent $event
* @return string
*/
public function format(LoggerLoggingEvent $event) {
$messageAsArray = array(
// Basic fields
'version' => self::GELF_PROTOCOL_VERSION,
'host' => $this->getHost(),
'short_message' => $this->getShortMessage($event),
'full_message' => $this->getFullMessage($event),
'timestamp' => $event->getTimeStamp(),
'level' => $this->getGelfLevel($event->getLevel()),
// Additional fields
'_facility' => $event->getLoggerName(),
'_thread' => $event->getThreadName(),
);
if ($this->getLocationInfo()) {
$messageAsArray += $this->getEventLocationFields($event);
}
$messageAsArray += $this->getEventMDCFields($event);
return json_encode($messageAsArray);
}
/**
* Returns event location information as array
* @param LoggerLoggingEvent $event
* @return array
*/
public function getEventLocationFields(LoggerLoggingEvent $event) {
$locInfo = $event->getLocationInformation();
return array(
'_file' => $locInfo->getFileName(),
'_line' => $locInfo->getLineNumber(),
'_class' => $locInfo->getClassName(),
'_method' => $locInfo->getMethodName()
);
}
/**
* Returns event MDC data as array
* @param LoggerLoggingEvent $event
* @return array
*/
public function getEventMDCFields(LoggerLoggingEvent $event) {
$fields = array();
foreach ($event->getMDCMap() as $key => $value) {
$fieldName = "_".$key;
if ($this->isAdditionalFieldNameValid($fieldName)) {
$fields[$fieldName] = $value;
}
}
return $fields;
}
/**
* Checks is field name valid according to Gelf specification
* @param string $fieldName
* @return bool
*/
public function isAdditionalFieldNameValid($fieldName) {
return (preg_match("@^_[\w\.\-]*$@", $fieldName) AND $fieldName != '_id');
}
/**
* Sets the 'locationInfo' parameter.
* @param boolean $locationInfo
*/
public function setLocationInfo($locationInfo) {
$this->setBoolean('locationInfo', $locationInfo);
}
/**
* Returns the value of the 'locationInfo' parameter.
* @return boolean
*/
public function getLocationInfo() {
return $this->locationInfo;
}
/**
* @param LoggerLoggingEvent $event
* @return string
*/
public function getShortMessage(LoggerLoggingEvent $event) {
$shortMessage = mb_substr($event->getRenderedMessage(), 0, $this->getShortMessageLength());
return $this->cleanNonUtfSymbols($shortMessage);
}
/**
* @param LoggerLoggingEvent $event
* @return string
*/
public function getFullMessage(LoggerLoggingEvent $event) {
return $this->cleanNonUtfSymbols(
$event->getRenderedMessage()
);
}
/**
* @param LoggerLevel $level
* @return int
*/
public function getGelfLevel(LoggerLevel $level) {
$int = $level->toInt();
if (isset($this->levelMap[$int])) {
return $this->levelMap[$int];
} else {
return self::LEVEL_ALERT;
}
}
/**
* @param int $shortMessageLength
*/
public function setShortMessageLength($shortMessageLength) {
$this->setPositiveInteger('shortMessageLength', $shortMessageLength);
}
/**
* @return int
*/
public function getShortMessageLength() {
return $this->shortMessageLength;
}
/**
* @param string $host
*/
public function setHost($host) {
$this->setString('host', $host);
}
/**
* @return string
*/
public function getHost() {
return $this->host;
}
/**
* @param string $message
* @return string
*/
protected function cleanNonUtfSymbols($message) {
/**
* Reject overly long 2 byte sequences, as well as characters
* above U+10000 and replace with ?
*/
$message = preg_replace(
'/[\x00-\x08\x10\x0B\x0C\x0E-\x19\x7F]'.
'|[\x00-\x7F][\x80-\xBF]+'.
'|([\xC0\xC1]|[\xF0-\xFF])[\x80-\xBF]*'.
'|[\xC2-\xDF]((?![\x80-\xBF])|[\x80-\xBF]{2,})'.
'|[\xE0-\xEF](([\x80-\xBF](?![\x80-\xBF]))|(?![\x80-\xBF]{2})|[\x80-\xBF]{3,})/S',
'?',
$message
);
/**
* Reject overly long 3 byte sequences and UTF-16 surrogates
* and replace with ?
*/
$message = preg_replace(
'/\xE0[\x80-\x9F][\x80-\xBF]'.
'|\xED[\xA0-\xBF][\x80-\xBF]/S',
'?',
$message
);
return $message;
}
}
|
apache-2.0
|
ycaihua/omicron
|
omicron-core/src/main/java/com/datagre/apps/omicron/core/dto/OmicronConfigNotification.java
|
476
|
package com.datagre.apps.omicron.core.dto;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;
/**
* Created by zengxiaobo on 2017/3/24.
*/
@Data
@NoArgsConstructor
@ToString
public class OmicronConfigNotification {
private String namespaceName;
private long notificationId;
public OmicronConfigNotification(String namespaceName, long notificationId) {
this.namespaceName = namespaceName;
this.notificationId = notificationId;
}
}
|
apache-2.0
|
Bigpoint/monolog-creator
|
src/MonologCreator/Processor/ExtraFieldProcessor.php
|
1014
|
<?php
namespace MonologCreator\Processor;
/**
* Class ExtraFieldProcessor
*
* Allows adding additional high-level or special fields to the log output.
*
* @package MonologCreator\Processor
* @author Sebastian Götze <[email protected]>
*/
class ExtraFieldProcessor implements \Monolog\Processor\ProcessorInterface
{
/**
* Array to hold additional fields
*
* @var array
*/
private $extraFields = array();
public function __construct(array $extraFields = array())
{
$this->extraFields = $extraFields;
}
/**
* Invoke processor
*
* Adds fields to record before returning it.
*
* @param array $record
* @return array
*/
public function __invoke(array $record)
{
if (false === \is_array($record['extra'])) {
$record['extra'] = array();
}
// Add fields to record
$record['extra'] = \array_merge($record['extra'], $this->extraFields);
return $record;
}
}
|
apache-2.0
|
envoyproxy/envoy-wasm
|
source/common/router/upstream_request.cc
|
22548
|
#include "common/router/upstream_request.h"
#include <chrono>
#include <cstdint>
#include <functional>
#include <memory>
#include <string>
#include "envoy/event/dispatcher.h"
#include "envoy/event/timer.h"
#include "envoy/grpc/status.h"
#include "envoy/http/conn_pool.h"
#include "envoy/runtime/runtime.h"
#include "envoy/upstream/cluster_manager.h"
#include "envoy/upstream/upstream.h"
#include "common/common/assert.h"
#include "common/common/empty_string.h"
#include "common/common/enum_to_int.h"
#include "common/common/scope_tracker.h"
#include "common/common/utility.h"
#include "common/grpc/common.h"
#include "common/http/codes.h"
#include "common/http/header_map_impl.h"
#include "common/http/headers.h"
#include "common/http/message_impl.h"
#include "common/http/utility.h"
#include "common/network/application_protocol.h"
#include "common/network/transport_socket_options_impl.h"
#include "common/network/upstream_server_name.h"
#include "common/network/upstream_subject_alt_names.h"
#include "common/router/config_impl.h"
#include "common/router/debug_config.h"
#include "common/router/router.h"
#include "common/stream_info/uint32_accessor_impl.h"
#include "common/tracing/http_tracer_impl.h"
#include "extensions/common/proxy_protocol/proxy_protocol_header.h"
#include "extensions/filters/http/well_known_names.h"
namespace Envoy {
namespace Router {
UpstreamRequest::UpstreamRequest(RouterFilterInterface& parent,
std::unique_ptr<GenericConnPool>&& conn_pool)
: parent_(parent), conn_pool_(std::move(conn_pool)), grpc_rq_success_deferred_(false),
stream_info_(parent_.callbacks()->dispatcher().timeSource()),
start_time_(parent_.callbacks()->dispatcher().timeSource().monotonicTime()),
calling_encode_headers_(false), upstream_canary_(false), decode_complete_(false),
encode_complete_(false), encode_trailers_(false), retried_(false), awaiting_headers_(true),
outlier_detection_timeout_recorded_(false),
create_per_try_timeout_on_request_complete_(false), paused_for_connect_(false),
record_timeout_budget_(parent_.cluster()->timeoutBudgetStats().has_value()) {
if (parent_.config().start_child_span_) {
span_ = parent_.callbacks()->activeSpan().spawnChild(
parent_.callbacks()->tracingConfig(), "router " + parent.cluster()->name() + " egress",
parent.timeSource().systemTime());
if (parent.attemptCount() != 1) {
// This is a retry request, add this metadata to span.
span_->setTag(Tracing::Tags::get().RetryCount, std::to_string(parent.attemptCount() - 1));
}
}
stream_info_.healthCheck(parent_.callbacks()->streamInfo().healthCheck());
if (conn_pool_->protocol().has_value()) {
stream_info_.protocol(conn_pool_->protocol().value());
}
}
UpstreamRequest::~UpstreamRequest() {
if (span_ != nullptr) {
Tracing::HttpTracerUtility::finalizeUpstreamSpan(*span_, upstream_headers_.get(),
upstream_trailers_.get(), stream_info_,
Tracing::EgressConfig::get());
}
if (per_try_timeout_ != nullptr) {
// Allows for testing.
per_try_timeout_->disableTimer();
}
if (max_stream_duration_timer_ != nullptr) {
max_stream_duration_timer_->disableTimer();
}
clearRequestEncoder();
// If desired, fire the per-try histogram when the UpstreamRequest
// completes.
if (record_timeout_budget_) {
Event::Dispatcher& dispatcher = parent_.callbacks()->dispatcher();
const MonotonicTime end_time = dispatcher.timeSource().monotonicTime();
const std::chrono::milliseconds response_time =
std::chrono::duration_cast<std::chrono::milliseconds>(end_time - start_time_);
Upstream::ClusterTimeoutBudgetStatsOptRef tb_stats = parent_.cluster()->timeoutBudgetStats();
tb_stats->get().upstream_rq_timeout_budget_per_try_percent_used_.recordValue(
FilterUtility::percentageOfTimeout(response_time, parent_.timeout().per_try_timeout_));
}
stream_info_.setUpstreamTiming(upstream_timing_);
stream_info_.onRequestComplete();
for (const auto& upstream_log : parent_.config().upstream_logs_) {
upstream_log->log(parent_.downstreamHeaders(), upstream_headers_.get(),
upstream_trailers_.get(), stream_info_);
}
while (downstream_data_disabled_ != 0) {
parent_.callbacks()->onDecoderFilterBelowWriteBufferLowWatermark();
parent_.cluster()->stats().upstream_flow_control_drained_total_.inc();
--downstream_data_disabled_;
}
}
void UpstreamRequest::decode100ContinueHeaders(Http::ResponseHeaderMapPtr&& headers) {
ScopeTrackerScopeState scope(&parent_.callbacks()->scope(), parent_.callbacks()->dispatcher());
ASSERT(100 == Http::Utility::getResponseStatus(*headers));
parent_.onUpstream100ContinueHeaders(std::move(headers), *this);
}
void UpstreamRequest::decodeHeaders(Http::ResponseHeaderMapPtr&& headers, bool end_stream) {
ScopeTrackerScopeState scope(&parent_.callbacks()->scope(), parent_.callbacks()->dispatcher());
// We drop 1xx other than 101 on the floor; 101 upgrade headers need to be passed to the client as
// part of the final response. 100-continue headers are handled in onUpstream100ContinueHeaders.
//
// We could in principle handle other headers here, but this might result in the double invocation
// of decodeHeaders() (once for informational, again for non-informational), which is likely an
// easy to miss corner case in the filter and HCM contract.
//
// This filtering is done early in upstream request, unlike 100 coalescing which is performed in
// the router filter, since the filtering only depends on the state of a single upstream, and we
// don't want to confuse accounting such as onFirstUpstreamRxByteReceived() with informational
// headers.
const uint64_t response_code = Http::Utility::getResponseStatus(*headers);
if (Http::CodeUtility::is1xx(response_code) &&
response_code != enumToInt(Http::Code::SwitchingProtocols)) {
return;
}
// TODO(rodaine): This is actually measuring after the headers are parsed and not the first
// byte.
upstream_timing_.onFirstUpstreamRxByteReceived(parent_.callbacks()->dispatcher().timeSource());
maybeEndDecode(end_stream);
awaiting_headers_ = false;
if (!parent_.config().upstream_logs_.empty()) {
upstream_headers_ = Http::createHeaderMap<Http::ResponseHeaderMapImpl>(*headers);
}
stream_info_.response_code_ = static_cast<uint32_t>(response_code);
if (paused_for_connect_ && response_code == 200) {
encodeBodyAndTrailers();
paused_for_connect_ = false;
}
parent_.onUpstreamHeaders(response_code, std::move(headers), *this, end_stream);
}
void UpstreamRequest::decodeData(Buffer::Instance& data, bool end_stream) {
ScopeTrackerScopeState scope(&parent_.callbacks()->scope(), parent_.callbacks()->dispatcher());
maybeEndDecode(end_stream);
stream_info_.addBytesReceived(data.length());
parent_.onUpstreamData(data, *this, end_stream);
}
void UpstreamRequest::decodeTrailers(Http::ResponseTrailerMapPtr&& trailers) {
ScopeTrackerScopeState scope(&parent_.callbacks()->scope(), parent_.callbacks()->dispatcher());
maybeEndDecode(true);
if (!parent_.config().upstream_logs_.empty()) {
upstream_trailers_ = Http::createHeaderMap<Http::ResponseTrailerMapImpl>(*trailers);
}
parent_.onUpstreamTrailers(std::move(trailers), *this);
}
const RouteEntry& UpstreamRequest::routeEntry() const { return *parent_.routeEntry(); }
const Network::Connection& UpstreamRequest::connection() const {
return *parent_.callbacks()->connection();
}
void UpstreamRequest::decodeMetadata(Http::MetadataMapPtr&& metadata_map) {
parent_.onUpstreamMetadata(std::move(metadata_map));
}
void UpstreamRequest::maybeEndDecode(bool end_stream) {
if (end_stream) {
upstream_timing_.onLastUpstreamRxByteReceived(parent_.callbacks()->dispatcher().timeSource());
decode_complete_ = true;
}
}
void UpstreamRequest::onUpstreamHostSelected(Upstream::HostDescriptionConstSharedPtr host) {
stream_info_.onUpstreamHostSelected(host);
upstream_host_ = host;
parent_.callbacks()->streamInfo().onUpstreamHostSelected(host);
parent_.onUpstreamHostSelected(host);
}
void UpstreamRequest::encodeHeaders(bool end_stream) {
ASSERT(!encode_complete_);
encode_complete_ = end_stream;
conn_pool_->newStream(this);
}
void UpstreamRequest::encodeData(Buffer::Instance& data, bool end_stream) {
ASSERT(!encode_complete_);
encode_complete_ = end_stream;
if (!upstream_ || paused_for_connect_) {
ENVOY_STREAM_LOG(trace, "buffering {} bytes", *parent_.callbacks(), data.length());
if (!buffered_request_body_) {
buffered_request_body_ = std::make_unique<Buffer::WatermarkBuffer>(
[this]() -> void { this->enableDataFromDownstreamForFlowControl(); },
[this]() -> void { this->disableDataFromDownstreamForFlowControl(); },
[]() -> void { /* TODO(adisuissa): Handle overflow watermark */ });
buffered_request_body_->setWatermarks(parent_.callbacks()->decoderBufferLimit());
}
buffered_request_body_->move(data);
} else {
ASSERT(downstream_metadata_map_vector_.empty());
ENVOY_STREAM_LOG(trace, "proxying {} bytes", *parent_.callbacks(), data.length());
stream_info_.addBytesSent(data.length());
upstream_->encodeData(data, end_stream);
if (end_stream) {
upstream_timing_.onLastUpstreamTxByteSent(parent_.callbacks()->dispatcher().timeSource());
}
}
}
void UpstreamRequest::encodeTrailers(const Http::RequestTrailerMap& trailers) {
ASSERT(!encode_complete_);
encode_complete_ = true;
encode_trailers_ = true;
if (!upstream_) {
ENVOY_STREAM_LOG(trace, "buffering trailers", *parent_.callbacks());
} else {
ASSERT(downstream_metadata_map_vector_.empty());
ENVOY_STREAM_LOG(trace, "proxying trailers", *parent_.callbacks());
upstream_->encodeTrailers(trailers);
upstream_timing_.onLastUpstreamTxByteSent(parent_.callbacks()->dispatcher().timeSource());
}
}
void UpstreamRequest::encodeMetadata(Http::MetadataMapPtr&& metadata_map_ptr) {
if (!upstream_) {
ENVOY_STREAM_LOG(trace, "upstream_ not ready. Store metadata_map to encode later: {}",
*parent_.callbacks(), *metadata_map_ptr);
downstream_metadata_map_vector_.emplace_back(std::move(metadata_map_ptr));
} else {
ENVOY_STREAM_LOG(trace, "Encode metadata: {}", *parent_.callbacks(), *metadata_map_ptr);
Http::MetadataMapVector metadata_map_vector;
metadata_map_vector.emplace_back(std::move(metadata_map_ptr));
upstream_->encodeMetadata(metadata_map_vector);
}
}
void UpstreamRequest::onResetStream(Http::StreamResetReason reason,
absl::string_view transport_failure_reason) {
ScopeTrackerScopeState scope(&parent_.callbacks()->scope(), parent_.callbacks()->dispatcher());
if (span_ != nullptr) {
// Add tags about reset.
span_->setTag(Tracing::Tags::get().Error, Tracing::Tags::get().True);
span_->setTag(Tracing::Tags::get().ErrorReason, Http::Utility::resetReasonToString(reason));
}
clearRequestEncoder();
awaiting_headers_ = false;
if (!calling_encode_headers_) {
stream_info_.setResponseFlag(Filter::streamResetReasonToResponseFlag(reason));
parent_.onUpstreamReset(reason, transport_failure_reason, *this);
} else {
deferred_reset_reason_ = reason;
}
}
void UpstreamRequest::resetStream() {
// Don't reset the stream if we're already done with it.
if (encode_complete_ && decode_complete_) {
return;
}
if (span_ != nullptr) {
// Add tags about the cancellation.
span_->setTag(Tracing::Tags::get().Canceled, Tracing::Tags::get().True);
}
if (conn_pool_->cancelAnyPendingStream()) {
ENVOY_STREAM_LOG(debug, "canceled pool request", *parent_.callbacks());
ASSERT(!upstream_);
}
if (upstream_) {
ENVOY_STREAM_LOG(debug, "resetting pool request", *parent_.callbacks());
upstream_->resetStream();
clearRequestEncoder();
}
}
void UpstreamRequest::setupPerTryTimeout() {
ASSERT(!per_try_timeout_);
if (parent_.timeout().per_try_timeout_.count() > 0) {
per_try_timeout_ =
parent_.callbacks()->dispatcher().createTimer([this]() -> void { onPerTryTimeout(); });
per_try_timeout_->enableTimer(parent_.timeout().per_try_timeout_);
}
}
void UpstreamRequest::onPerTryTimeout() {
// If we've sent anything downstream, ignore the per try timeout and let the response continue
// up to the global timeout
if (!parent_.downstreamResponseStarted()) {
ENVOY_STREAM_LOG(debug, "upstream per try timeout", *parent_.callbacks());
stream_info_.setResponseFlag(StreamInfo::ResponseFlag::UpstreamRequestTimeout);
parent_.onPerTryTimeout(*this);
} else {
ENVOY_STREAM_LOG(debug,
"ignored upstream per try timeout due to already started downstream response",
*parent_.callbacks());
}
}
void UpstreamRequest::onPoolFailure(ConnectionPool::PoolFailureReason reason,
absl::string_view transport_failure_reason,
Upstream::HostDescriptionConstSharedPtr host) {
Http::StreamResetReason reset_reason = Http::StreamResetReason::ConnectionFailure;
switch (reason) {
case ConnectionPool::PoolFailureReason::Overflow:
reset_reason = Http::StreamResetReason::Overflow;
break;
case ConnectionPool::PoolFailureReason::RemoteConnectionFailure:
FALLTHRU;
case ConnectionPool::PoolFailureReason::LocalConnectionFailure:
reset_reason = Http::StreamResetReason::ConnectionFailure;
break;
case ConnectionPool::PoolFailureReason::Timeout:
reset_reason = Http::StreamResetReason::LocalReset;
}
// Mimic an upstream reset.
onUpstreamHostSelected(host);
onResetStream(reset_reason, transport_failure_reason);
}
void UpstreamRequest::onPoolReady(
std::unique_ptr<GenericUpstream>&& upstream, Upstream::HostDescriptionConstSharedPtr host,
const Network::Address::InstanceConstSharedPtr& upstream_local_address,
const StreamInfo::StreamInfo& info) {
// This may be called under an existing ScopeTrackerScopeState but it will unwind correctly.
ScopeTrackerScopeState scope(&parent_.callbacks()->scope(), parent_.callbacks()->dispatcher());
ENVOY_STREAM_LOG(debug, "pool ready", *parent_.callbacks());
upstream_ = std::move(upstream);
if (parent_.requestVcluster()) {
// The cluster increases its upstream_rq_total_ counter right before firing this onPoolReady
// callback. Hence, the upstream request increases the virtual cluster's upstream_rq_total_ stat
// here.
parent_.requestVcluster()->stats().upstream_rq_total_.inc();
}
host->outlierDetector().putResult(Upstream::Outlier::Result::LocalOriginConnectSuccess);
onUpstreamHostSelected(host);
stream_info_.setUpstreamFilterState(std::make_shared<StreamInfo::FilterStateImpl>(
info.filterState().parent()->parent(), StreamInfo::FilterState::LifeSpan::Request));
stream_info_.setUpstreamLocalAddress(upstream_local_address);
parent_.callbacks()->streamInfo().setUpstreamLocalAddress(upstream_local_address);
stream_info_.setUpstreamSslConnection(info.downstreamSslConnection());
parent_.callbacks()->streamInfo().setUpstreamSslConnection(info.downstreamSslConnection());
if (parent_.downstreamEndStream()) {
setupPerTryTimeout();
} else {
create_per_try_timeout_on_request_complete_ = true;
}
// Make sure the connection manager will inform the downstream watermark manager when the
// downstream buffers are overrun. This may result in immediate watermark callbacks referencing
// the encoder.
parent_.callbacks()->addDownstreamWatermarkCallbacks(downstream_watermark_manager_);
calling_encode_headers_ = true;
auto* headers = parent_.downstreamHeaders();
if (parent_.routeEntry()->autoHostRewrite() && !host->hostname().empty()) {
parent_.downstreamHeaders()->setHost(host->hostname());
}
if (span_ != nullptr) {
span_->injectContext(*parent_.downstreamHeaders());
}
upstream_timing_.onFirstUpstreamTxByteSent(parent_.callbacks()->dispatcher().timeSource());
// Make sure that when we are forwarding CONNECT payload we do not do so until
// the upstream has accepted the CONNECT request.
if (conn_pool_->protocol().has_value() &&
headers->getMethodValue() == Http::Headers::get().MethodValues.Connect) {
paused_for_connect_ = true;
}
if (upstream_host_->cluster().commonHttpProtocolOptions().has_max_stream_duration()) {
const auto max_stream_duration = std::chrono::milliseconds(DurationUtil::durationToMilliseconds(
upstream_host_->cluster().commonHttpProtocolOptions().max_stream_duration()));
if (max_stream_duration.count()) {
max_stream_duration_timer_ = parent_.callbacks()->dispatcher().createTimer(
[this]() -> void { onStreamMaxDurationReached(); });
max_stream_duration_timer_->enableTimer(max_stream_duration);
}
}
upstream_->encodeHeaders(*parent_.downstreamHeaders(), shouldSendEndStream());
calling_encode_headers_ = false;
if (!paused_for_connect_) {
encodeBodyAndTrailers();
}
}
void UpstreamRequest::encodeBodyAndTrailers() {
// It is possible to get reset in the middle of an encodeHeaders() call. This happens for
// example in the HTTP/2 codec if the frame cannot be encoded for some reason. This should never
// happen but it's unclear if we have covered all cases so protect against it and test for it.
// One specific example of a case where this happens is if we try to encode a total header size
// that is too big in HTTP/2 (64K currently).
if (deferred_reset_reason_) {
onResetStream(deferred_reset_reason_.value(), absl::string_view());
} else {
// Encode metadata after headers and before any other frame type.
if (!downstream_metadata_map_vector_.empty()) {
ENVOY_STREAM_LOG(debug, "Send metadata onPoolReady. {}", *parent_.callbacks(),
downstream_metadata_map_vector_);
upstream_->encodeMetadata(downstream_metadata_map_vector_);
downstream_metadata_map_vector_.clear();
if (shouldSendEndStream()) {
Buffer::OwnedImpl empty_data("");
upstream_->encodeData(empty_data, true);
}
}
if (buffered_request_body_) {
stream_info_.addBytesSent(buffered_request_body_->length());
upstream_->encodeData(*buffered_request_body_, encode_complete_ && !encode_trailers_);
}
if (encode_trailers_) {
upstream_->encodeTrailers(*parent_.downstreamTrailers());
}
if (encode_complete_) {
upstream_timing_.onLastUpstreamTxByteSent(parent_.callbacks()->dispatcher().timeSource());
}
}
}
void UpstreamRequest::onStreamMaxDurationReached() {
upstream_host_->cluster().stats().upstream_rq_max_duration_reached_.inc();
// The upstream had closed then try to retry along with retry policy.
parent_.onStreamMaxDurationReached(*this);
}
void UpstreamRequest::clearRequestEncoder() {
// Before clearing the encoder, unsubscribe from callbacks.
if (upstream_) {
parent_.callbacks()->removeDownstreamWatermarkCallbacks(downstream_watermark_manager_);
}
upstream_.reset();
}
void UpstreamRequest::DownstreamWatermarkManager::onAboveWriteBufferHighWatermark() {
ASSERT(parent_.upstream_);
// There are two states we should get this callback in: 1) the watermark was
// hit due to writes from a different filter instance over a shared
// downstream connection, or 2) the watermark was hit due to THIS filter
// instance writing back the "winning" upstream request. In either case we
// can disable reads from upstream.
ASSERT(!parent_.parent_.finalUpstreamRequest() ||
&parent_ == parent_.parent_.finalUpstreamRequest());
// The downstream connection is overrun. Pause reads from upstream.
// If there are multiple calls to readDisable either the codec (H2) or the underlying
// Network::Connection (H1) will handle reference counting.
parent_.parent_.cluster()->stats().upstream_flow_control_paused_reading_total_.inc();
parent_.upstream_->readDisable(true);
}
void UpstreamRequest::DownstreamWatermarkManager::onBelowWriteBufferLowWatermark() {
ASSERT(parent_.upstream_);
// One source of connection blockage has buffer available. Pass this on to the stream, which
// will resume reads if this was the last remaining high watermark.
parent_.parent_.cluster()->stats().upstream_flow_control_resumed_reading_total_.inc();
parent_.upstream_->readDisable(false);
}
void UpstreamRequest::disableDataFromDownstreamForFlowControl() {
// If there is only one upstream request, we can be assured that
// disabling reads will not slow down other upstream requests. If we've
// already seen the full downstream request (downstream_end_stream_) then
// disabling reads is a noop.
// This assert condition must be true because
// parent_.upstreamRequests().size() can only be greater than 1 in the
// case of a per-try-timeout with hedge_on_per_try_timeout enabled, and
// the per try timeout timer is started only after downstream_end_stream_
// is true.
ASSERT(parent_.upstreamRequests().size() == 1 || parent_.downstreamEndStream());
parent_.cluster()->stats().upstream_flow_control_backed_up_total_.inc();
parent_.callbacks()->onDecoderFilterAboveWriteBufferHighWatermark();
++downstream_data_disabled_;
}
void UpstreamRequest::enableDataFromDownstreamForFlowControl() {
// If there is only one upstream request, we can be assured that
// disabling reads will not overflow any write buffers in other upstream
// requests. If we've already seen the full downstream request
// (downstream_end_stream_) then enabling reads is a noop.
// This assert condition must be true because
// parent_.upstreamRequests().size() can only be greater than 1 in the
// case of a per-try-timeout with hedge_on_per_try_timeout enabled, and
// the per try timeout timer is started only after downstream_end_stream_
// is true.
ASSERT(parent_.upstreamRequests().size() == 1 || parent_.downstreamEndStream());
parent_.cluster()->stats().upstream_flow_control_drained_total_.inc();
parent_.callbacks()->onDecoderFilterBelowWriteBufferLowWatermark();
ASSERT(downstream_data_disabled_ != 0);
if (downstream_data_disabled_ > 0) {
--downstream_data_disabled_;
}
}
} // namespace Router
} // namespace Envoy
|
apache-2.0
|
bozimmerman/CoffeeMud
|
com/planet_ink/coffee_mud/Abilities/Spells/Spell_Erase.java
|
3338
|
package com.planet_ink.coffee_mud.Abilities.Spells;
import com.planet_ink.coffee_mud.core.interfaces.*;
import com.planet_ink.coffee_mud.core.*;
import com.planet_ink.coffee_mud.core.collections.*;
import com.planet_ink.coffee_mud.Abilities.interfaces.*;
import com.planet_ink.coffee_mud.Areas.interfaces.*;
import com.planet_ink.coffee_mud.Behaviors.interfaces.*;
import com.planet_ink.coffee_mud.CharClasses.interfaces.*;
import com.planet_ink.coffee_mud.Commands.interfaces.*;
import com.planet_ink.coffee_mud.Common.interfaces.*;
import com.planet_ink.coffee_mud.Exits.interfaces.*;
import com.planet_ink.coffee_mud.Items.interfaces.*;
import com.planet_ink.coffee_mud.Libraries.interfaces.*;
import com.planet_ink.coffee_mud.Locales.interfaces.*;
import com.planet_ink.coffee_mud.MOBS.interfaces.*;
import com.planet_ink.coffee_mud.Races.interfaces.*;
import java.util.*;
/*
Copyright 2001-2022 Bo Zimmerman
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.
*/
public class Spell_Erase extends Spell
{
@Override
public String ID()
{
return "Spell_Erase";
}
private final static String localizedName = CMLib.lang().L("Erase Scroll");
@Override
public String name()
{
return localizedName;
}
@Override
protected int canTargetCode()
{
return CAN_ITEMS;
}
@Override
public int classificationCode()
{
return Ability.ACODE_SPELL|Ability.DOMAIN_ALTERATION;
}
@Override
public int abstractQuality()
{
return Ability.QUALITY_INDIFFERENT;
}
@Override
public boolean invoke(final MOB mob, final List<String> commands, final Physical givenTarget, final boolean auto, final int asLevel)
{
if((commands.size()<1)&&(givenTarget==null))
{
mob.tell(L("Erase what?."));
return false;
}
final Item target=getTarget(mob,mob.location(),givenTarget,commands,Wearable.FILTER_ANY);
if(target==null)
return false;
if(!(target instanceof Scroll)&&(!target.isReadable()))
{
mob.tell(L("You can't erase that."));
return false;
}
if(!super.invoke(mob,commands,givenTarget,auto,asLevel))
return false;
final boolean success=proficiencyCheck(mob,0,auto);
if(success)
{
final CMMsg msg=CMClass.getMsg(mob,target,this,verbalCastCode(mob,target,auto),auto?L("The words on <T-NAME> fade."):L("^S<S-NAME> whisper(s), and then rub(s) on <T-NAMESELF>, making the words fade.^?"));
if(mob.location().okMessage(mob,msg))
{
mob.location().send(mob,msg);
if(target instanceof Scroll)
((Scroll)target).setSpellList("");
else
target.setReadableText("");
}
}
else
beneficialWordsFizzle(mob,target,L("<S-NAME> whisper(s), and then rub(s) on <T-NAMESELF>, but nothing happens."));
// return whether it worked
return success;
}
}
|
apache-2.0
|
TremoloSecurity/OpenUnison
|
unison/unison-applications-gitlab/src/main/java/com/tremolosecurity/unison/gitlab/provisioning/targets/GitlabUserProvider.java
|
21837
|
/*******************************************************************************
* Copyright 2020 Tremolo Security, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*******************************************************************************/
package com.tremolosecurity.unison.gitlab.provisioning.targets;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.http.Header;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.CookieSpecs;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.BasicHttpClientConnectionManager;
import org.apache.http.message.BasicHeader;
import org.apache.http.util.EntityUtils;
import org.apache.logging.log4j.Logger;
import org.gitlab4j.api.GitLabApi;
import org.gitlab4j.api.GitLabApiException;
import org.gitlab4j.api.GroupApi;
import org.gitlab4j.api.UserApi;
import org.gitlab4j.api.models.AccessLevel;
import org.gitlab4j.api.models.Group;
import org.gitlab4j.api.models.Identity;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import com.tremolosecurity.config.util.ConfigManager;
import com.tremolosecurity.provisioning.core.ProvisioningException;
import com.tremolosecurity.provisioning.core.User;
import com.tremolosecurity.provisioning.core.UserStoreProviderWithAddGroup;
import com.tremolosecurity.provisioning.core.Workflow;
import com.tremolosecurity.provisioning.util.GenPasswd;
import com.tremolosecurity.provisioning.core.ProvisioningUtil.ActionType;
import com.tremolosecurity.saml.Attribute;
public class GitlabUserProvider implements UserStoreProviderWithAddGroup {
static Logger logger = org.apache.logging.log4j.LogManager.getLogger(GitlabUserProvider.class.getName());
ConfigManager cfgMgr;
String name;
String token;
String url;
GitLabApi gitLabApi;
UserApi userApi;
GroupApi groupApi;
BeanUtils beanUtils = new BeanUtils();
public static final String GITLAB_IDENTITIES = "com.tremolosecurity.unison.gitlab.itentities";
public static final String GITLAB_GROUP_ENTITLEMENTS = "com.tremolosecurity.unison.gitlab.group-entitlements";
@Override
public void createUser(User user, Set<String> attributes, Map<String, Object> request)
throws ProvisioningException {
int approvalID = 0;
if (request.containsKey("APPROVAL_ID")) {
approvalID = (Integer) request.get("APPROVAL_ID");
}
Workflow workflow = (Workflow) request.get("WORKFLOW");
org.gitlab4j.api.models.User newUser = new org.gitlab4j.api.models.User();
newUser.setUsername(user.getUserID());
for (String attrName : attributes) {
Attribute attr = user.getAttribs().get(attrName);
if (attr != null) {
try {
this.beanUtils.setProperty(newUser, attrName, attr.getValues().get(0));
} catch (IllegalAccessException | InvocationTargetException e) {
throw new ProvisioningException("Could not set " + attrName + " for " + user.getUserID(),e);
}
}
}
try {
this.userApi.createUser(newUser, new GenPasswd(50).getPassword(), false);
} catch (GitLabApiException e) {
throw new ProvisioningException("Could not create user",e);
}
newUser = this.findUserByName(user.getUserID());
int numTries = 0;
while (newUser == null) {
if (numTries > 10) {
throw new ProvisioningException("User " + user.getUserID() + " never created");
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
}
newUser = this.findUserByName(user.getUserID());
numTries++;
}
this.cfgMgr.getProvisioningEngine().logAction(this.name,true, ActionType.Add, approvalID, workflow, "id", newUser.getId().toString());
for (String attrName : attributes) {
Attribute attr = user.getAttribs().get(attrName);
if (attr != null) {
this.cfgMgr.getProvisioningEngine().logAction(this.name,false, ActionType.Add, approvalID, workflow, attrName, attr.getValues().get(0));
}
}
List<GitlabFedIdentity> ids = (List<GitlabFedIdentity>) request.get(GitlabUserProvider.GITLAB_IDENTITIES);
if (ids != null) {
ArrayList<Header> defheaders = new ArrayList<Header>();
defheaders.add(new BasicHeader("Private-Token", this.token));
BasicHttpClientConnectionManager bhcm = new BasicHttpClientConnectionManager(
cfgMgr.getHttpClientSocketRegistry());
RequestConfig rc = RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD).setRedirectsEnabled(false)
.build();
CloseableHttpClient http = HttpClients.custom()
.setConnectionManager(bhcm)
.setDefaultHeaders(defheaders)
.setDefaultRequestConfig(rc)
.build();
try {
for (GitlabFedIdentity id : ids) {
HttpPut getmembers = new HttpPut(new StringBuilder().append(this.url).append("/api/v4/users/").append(newUser.getId()).append("?provider=").append(id.getProvider()).append("&extern_uid=").append(URLEncoder.encode(user.getUserID(), "UTF-8")).toString());
CloseableHttpResponse resp = http.execute(getmembers);
if (resp.getStatusLine().getStatusCode() != 200) {
throw new IOException("Invalid response " + resp.getStatusLine().getStatusCode());
}
this.cfgMgr.getProvisioningEngine().logAction(this.name,false, ActionType.Add, approvalID, workflow, "identity-provider", id.getProvider());
this.cfgMgr.getProvisioningEngine().logAction(this.name,false, ActionType.Add, approvalID, workflow, "identity-externid", id.getExternalUid());
}
} catch (IOException e) {
throw new ProvisioningException("Could not set identity",e);
} finally {
try {
http.close();
} catch (IOException e) {
}
bhcm.close();
}
}
HashMap<String,Integer> groupmap = (HashMap<String, Integer>) request.get(GitlabUserProvider.GITLAB_GROUP_ENTITLEMENTS);
if (groupmap == null) {
groupmap = new HashMap<String, Integer>();
}
for (String group : user.getGroups()) {
try {
Group groupObj = this.findGroupByName(group);
if (groupObj == null) {
logger.warn("Group " + group + " does not exist");
} else {
int accessLevel = AccessLevel.DEVELOPER.ordinal();
if (groupmap.containsKey(group)) {
accessLevel = groupmap.get(group);
}
this.groupApi.addMember(groupObj.getId(), newUser.getId(), accessLevel);
this.cfgMgr.getProvisioningEngine().logAction(this.name,false, ActionType.Add, approvalID, workflow, "group", group);
}
} catch (GitLabApiException e) {
throw new ProvisioningException("Could not find group " + group,e);
}
}
}
@Override
public void setUserPassword(User user, Map<String, Object> request) throws ProvisioningException {
// TODO Auto-generated method stub
}
@Override
public void syncUser(User user, boolean addOnly, Set<String> attributes, Map<String, Object> request)
throws ProvisioningException {
List<GitlabFedIdentity> ids = (List<GitlabFedIdentity>) request.get(GitlabUserProvider.GITLAB_IDENTITIES);
int approvalID = 0;
if (request.containsKey("APPROVAL_ID")) {
approvalID = (Integer) request.get("APPROVAL_ID");
}
Workflow workflow = (Workflow) request.get("WORKFLOW");
User fromGitlab = this.findUser(user.getUserID(), attributes, request);
if (fromGitlab == null) {
this.createUser(user, attributes, request);
return;
}
List<GitlabFedIdentity> idsFromGitlab = (List<GitlabFedIdentity>) request.get(GitlabUserProvider.GITLAB_IDENTITIES);
HashMap<String,String> toSet = new HashMap<String,String>();
HashSet<String> toDelete = new HashSet<String>();
for (String attrName : attributes) {
Attribute attrFromGitlab = fromGitlab.getAttribs().get(attrName);
Attribute attrIn = user.getAttribs().get(attrName);
if ((attrIn != null && attrFromGitlab == null) || (attrIn != null && attrFromGitlab != null && ! attrIn.getValues().get(0).equals(attrFromGitlab.getValues().get(0)))) {
toSet.put(attrName,attrIn.getValues().get(0));
} else if (! addOnly) {
if (attrIn == null && attrFromGitlab != null) {
toDelete.add(attrName);
}
}
}
org.gitlab4j.api.models.User toSave = this.findUserByName(user.getUserID());
for (String attrName : toSet.keySet()) {
try {
this.beanUtils.setProperty(toSave, attrName, toSet.get(attrName));
} catch (IllegalAccessException | InvocationTargetException e) {
throw new ProvisioningException("Could not update user " + user.getUserID(),e);
}
}
for (String attrName : toDelete) {
try {
this.beanUtils.setProperty(toSave, attrName, "");
} catch (IllegalAccessException | InvocationTargetException e) {
throw new ProvisioningException("Could not update user " + user.getUserID(),e);
}
}
if (ids != null) {
ArrayList<Header> defheaders = new ArrayList<Header>();
defheaders.add(new BasicHeader("Private-Token", this.token));
BasicHttpClientConnectionManager bhcm = new BasicHttpClientConnectionManager(
cfgMgr.getHttpClientSocketRegistry());
RequestConfig rc = RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD).setRedirectsEnabled(false)
.build();
CloseableHttpClient http = HttpClients.custom()
.setConnectionManager(bhcm)
.setDefaultHeaders(defheaders)
.setDefaultRequestConfig(rc)
.build();
try {
for (GitlabFedIdentity id : ids) {
boolean found = false;
for (GitlabFedIdentity idfromgl : idsFromGitlab) {
if (id.getExternalUid().equals(idfromgl.getExternalUid()) && id.getProvider().equals(idfromgl.getProvider()) ) {
found = true;
break;
}
}
if (! found) {
HttpPut getmembers = new HttpPut(new StringBuilder().append(this.url).append("/api/v4/users/").append(toSave.getId()).append("?provider=").append(id.getProvider()).append("&extern_uid=").append(URLEncoder.encode(user.getUserID(), "UTF-8")).toString());
CloseableHttpResponse resp = http.execute(getmembers);
if (resp.getStatusLine().getStatusCode() != 200) {
throw new IOException("Invalid response " + resp.getStatusLine().getStatusCode());
}
this.cfgMgr.getProvisioningEngine().logAction(this.name,false, ActionType.Add, approvalID, workflow, "identity-provider", id.getProvider());
this.cfgMgr.getProvisioningEngine().logAction(this.name,false, ActionType.Add, approvalID, workflow, "identity-externid", id.getExternalUid());
}
}
} catch (IOException e) {
throw new ProvisioningException("Could not set identity",e);
} finally {
try {
http.close();
} catch (IOException e) {
}
bhcm.close();
}
}
try {
this.userApi.updateUser(toSave, null);
} catch (GitLabApiException e) {
throw new ProvisioningException("Could not save user " + user.getUserID(),e);
}
for (String attrName : toSet.keySet()) {
this.cfgMgr.getProvisioningEngine().logAction(this.name,false, ActionType.Replace, approvalID, workflow, attrName, toSet.get(attrName));
}
for (String attrName : toDelete) {
this.cfgMgr.getProvisioningEngine().logAction(this.name,false, ActionType.Replace, approvalID, workflow, attrName, "");
}
HashMap<String,Integer> groupmap = (HashMap<String, Integer>) request.get(GitlabUserProvider.GITLAB_GROUP_ENTITLEMENTS);
if (groupmap == null) {
groupmap = new HashMap<String, Integer>();
}
for (String inGroup : user.getGroups()) {
if (! fromGitlab.getGroups().contains(inGroup)) {
try {
Group groupObj = this.findGroupByName(inGroup);
if (groupObj == null) {
logger.warn("Group " + inGroup + " does not exist");
} else {
int accessLevel = AccessLevel.DEVELOPER.ordinal();
if (groupmap.containsKey(inGroup)) {
accessLevel = groupmap.get(inGroup);
}
this.groupApi.addMember(groupObj.getId(), toSave.getId(), accessLevel);
this.cfgMgr.getProvisioningEngine().logAction(this.name,false, ActionType.Add, approvalID, workflow, "group", inGroup);
}
} catch (GitLabApiException e) {
if (e.getMessage().equalsIgnoreCase("Member already exists")) {
continue;
} else {
throw new ProvisioningException("Could not find group " + inGroup,e);
}
}
}
}
if (! addOnly) {
for (String groupFromGitlab : fromGitlab.getGroups()) {
if (! user.getGroups().contains(groupFromGitlab)) {
try {
Group groupObj = this.findGroupByName(groupFromGitlab);
if (groupObj == null) {
logger.warn("Group " + groupFromGitlab + " does not exist");
} else {
this.groupApi.removeMember(groupObj.getId(), toSave.getId());
this.cfgMgr.getProvisioningEngine().logAction(this.name,false, ActionType.Delete, approvalID, workflow, "group", groupFromGitlab);
}
} catch (GitLabApiException e) {
throw new ProvisioningException("Could not find group " + groupFromGitlab);
}
}
}
}
}
@Override
public void deleteUser(User user, Map<String, Object> request) throws ProvisioningException {
int approvalID = 0;
if (request.containsKey("APPROVAL_ID")) {
approvalID = (Integer) request.get("APPROVAL_ID");
}
Workflow workflow = (Workflow) request.get("WORKFLOW");
org.gitlab4j.api.models.User fromGitlab = this.findUserByName(user.getUserID());
if (fromGitlab == null) {
return;
}
try {
this.userApi.deleteUser(fromGitlab.getId(),false);
} catch (GitLabApiException e) {
throw new ProvisioningException("Could not delete " + user.getUserID(),e);
}
this.cfgMgr.getProvisioningEngine().logAction(this.name,true, ActionType.Delete, approvalID, workflow, "id", fromGitlab.getId().toString());
}
@Override
public User findUser(String userID, Set<String> attributes, Map<String, Object> request)
throws ProvisioningException {
org.gitlab4j.api.models.User fromGitlab = findUserByName(userID);
if (fromGitlab == null) {
return null;
}
User forUnison = new User(userID);
for (String attrName : attributes) {
try {
String val = beanUtils.getProperty(fromGitlab, attrName);
if (val != null) {
Attribute attr = new Attribute(attrName,val);
forUnison.getAttribs().put(attrName, attr);
}
} catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
throw new ProvisioningException("Couldn't load attribute " + attrName,e);
}
}
if (fromGitlab.getIdentities() != null) {
ArrayList<GitlabFedIdentity> ids = new ArrayList<GitlabFedIdentity>();
for (Identity fedid : fromGitlab.getIdentities()) {
GitlabFedIdentity id = new GitlabFedIdentity();
id.setExternalUid(fedid.getExternUid());
id.setProvider(fedid.getProvider());
ids.add(id);
}
request.put(GitlabUserProvider.GITLAB_IDENTITIES,ids);
}
ArrayList<Header> defheaders = new ArrayList<Header>();
defheaders.add(new BasicHeader("Private-Token", this.token));
BasicHttpClientConnectionManager bhcm = new BasicHttpClientConnectionManager(
cfgMgr.getHttpClientSocketRegistry());
RequestConfig rc = RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD).setRedirectsEnabled(false)
.build();
CloseableHttpClient http = HttpClients.custom()
.setConnectionManager(bhcm)
.setDefaultHeaders(defheaders)
.setDefaultRequestConfig(rc)
.build();
try {
HttpGet getmembers = new HttpGet(new StringBuilder().append(this.url).append("/api/v4/users/").append(fromGitlab.getId()).append("/memberships").toString());
CloseableHttpResponse resp = http.execute(getmembers);
if (resp.getStatusLine().getStatusCode() != 200) {
throw new IOException("Invalid response " + resp.getStatusLine().getStatusCode());
}
String json = EntityUtils.toString(resp.getEntity());
JSONArray members = (JSONArray) new JSONParser().parse(json);
for (Object o : members) {
JSONObject member = (JSONObject) o;
String sourceType = (String) member.get("source_type");
String sourceName = (String) member.get("source_name");
if (sourceType.equalsIgnoreCase("Namespace")) {
forUnison.getGroups().add(sourceName);
}
}
} catch (IOException | ParseException e) {
throw new ProvisioningException("Could not get group memebers",e);
} finally {
try {
http.close();
} catch (IOException e) {
}
bhcm.close();
}
return forUnison;
}
private org.gitlab4j.api.models.User findUserByName(String userID) throws ProvisioningException {
org.gitlab4j.api.models.User fromGitlab;
try {
List<org.gitlab4j.api.models.User> users = this.userApi.findUsers(userID);
if (users.size() == 0) {
return null;
} else if (users.size() > 1) {
int count = 0;
org.gitlab4j.api.models.User foundUser = null;
for (org.gitlab4j.api.models.User user : users) {
if (user.getUsername().equals(userID)) {
count++;
foundUser = user;
}
}
if (count > 1) {
throw new ProvisioningException(userID + " maps to multiple users");
} else if (count == 0) {
return null;
} else {
return foundUser;
}
} else {
fromGitlab = users.get(0);
}
} catch (GitLabApiException e) {
throw new ProvisioningException("Could not load user",e);
}
return fromGitlab;
}
@Override
public void init(Map<String, Attribute> cfg, ConfigManager cfgMgr, String name) throws ProvisioningException {
this.token = cfg.get("token").getValues().get(0);
this.url = cfg.get("url").getValues().get(0);
this.name = name;
this.gitLabApi = new GitLabApi(this.url, this.token);
this.userApi = new UserApi(this.gitLabApi);
this.groupApi = new GroupApi(this.gitLabApi);
this.cfgMgr = cfgMgr;
}
@Override
public void addGroup(String name, Map<String, String> additionalAttributes, User user, Map<String, Object> request)
throws ProvisioningException {
if (this.isGroupExists(name, null, request)) {
return;
}
int approvalID = 0;
if (request.containsKey("APPROVAL_ID")) {
approvalID = (Integer) request.get("APPROVAL_ID");
}
Workflow workflow = (Workflow) request.get("WORKFLOW");
Group groupToCreate = new Group();
groupToCreate.setName(name);
groupToCreate.setPath(name);
for (String prop : additionalAttributes.keySet()) {
try {
this.beanUtils.setProperty(groupToCreate, prop, additionalAttributes.get(prop));
} catch (IllegalAccessException | InvocationTargetException e) {
throw new ProvisioningException("Could not set properties",e);
}
}
try {
this.groupApi.addGroup(groupToCreate);
} catch (GitLabApiException e) {
throw new ProvisioningException("Could not create group " + name,e);
}
this.cfgMgr.getProvisioningEngine().logAction(this.name,true, ActionType.Add, approvalID, workflow, "group-object", name);
}
@Override
public void deleteGroup(String name, User user, Map<String, Object> request) throws ProvisioningException {
if (! this.isGroupExists(name, null, request)) {
return;
}
int approvalID = 0;
if (request.containsKey("APPROVAL_ID")) {
approvalID = (Integer) request.get("APPROVAL_ID");
}
Workflow workflow = (Workflow) request.get("WORKFLOW");
try {
this.groupApi.deleteGroup(name);
} catch (GitLabApiException e) {
throw new ProvisioningException("Could not delete group " + name,e);
}
this.cfgMgr.getProvisioningEngine().logAction(this.name,true, ActionType.Delete, approvalID, workflow, "group-object", name);
}
@Override
public boolean isGroupExists(String name, User user, Map<String, Object> request) throws ProvisioningException {
try {
Group group = this.findGroupByName(name);
return group != null;
} catch (GitLabApiException e) {
throw new ProvisioningException("Could not search for groups",e);
}
}
public Group findGroupByName(String name) throws GitLabApiException {
List<Group> groups = this.groupApi.getGroups(name);
for (Group group : groups) {
if (group.getName().equalsIgnoreCase(name)) {
return group;
}
}
return null;
}
public GitLabApi getApi() {
return this.gitLabApi;
}
public String getName() {
return this.name;
}
@Override
public void shutdown() throws ProvisioningException {
this.gitLabApi.close();
}
}
|
apache-2.0
|
smuldr/xtime-android
|
app/src/androidTest/java/com/xebia/xtime/test/shared/model/WorkTypeTest.java
|
1185
|
package com.xebia.xtime.test.shared.model;
import android.os.Parcel;
import com.xebia.xtime.shared.model.WorkType;
import junit.framework.TestCase;
public class WorkTypeTest extends TestCase {
private WorkType mWorkType;
@Override
protected void setUp() throws Exception {
super.setUp();
mWorkType = new WorkType("id", "name");
}
public void testEquals() {
assertTrue(mWorkType.equals(new WorkType("id", "name")));
assertFalse(mWorkType.equals(new WorkType("not id", "name")));
assertFalse(mWorkType.equals(new WorkType("id", "not name")));
}
public void testParcelable() {
Parcel in = Parcel.obtain();
Parcel out = Parcel.obtain();
WorkType result = null;
try {
in.writeParcelable(mWorkType, 0);
byte[] bytes = in.marshall();
out.unmarshall(bytes, 0, bytes.length);
out.setDataPosition(0);
result = out.readParcelable(WorkType.class.getClassLoader());
} finally {
in.recycle();
out.recycle();
}
assertNotNull(result);
assertEquals(mWorkType, result);
}
}
|
apache-2.0
|
gserv/serv
|
serv-wx/src/main/java/com/github/gserv/serv/wx/message/XmlMessageParseException.java
|
700
|
package com.github.gserv.serv.wx.message;
/**
* 消息解析异常
*
* @author shiying
*
*/
public class XmlMessageParseException extends RuntimeException {
/**
*
*/
private static final long serialVersionUID = 6648701329524322380L;
public XmlMessageParseException() {
super();
// TODO Auto-generated constructor stub
}
public XmlMessageParseException(String arg0, Throwable arg1) {
super(arg0, arg1);
// TODO Auto-generated constructor stub
}
public XmlMessageParseException(String arg0) {
super(arg0);
// TODO Auto-generated constructor stub
}
public XmlMessageParseException(Throwable arg0) {
super(arg0);
// TODO Auto-generated constructor stub
}
}
|
apache-2.0
|
support-project/knowledge
|
src/main/resources/org/support/project/knowledge/markdown/sample_markdown_ja.md
|
4447
|
# Markdown sample
- ここに書かれているMarkdownのテキストが、下のDispley sampleに表示されるので、
Markdownがどのように表示されるかのイメージが湧くと思います
## 見出し -> 「#」
- 「#」はタイトル
- 「#」の後に、スペースを1つあけて、タイトルの文字を書く
- 「#」の個数で大きさが変わる(個数が多くなるほど小さくなる)
# タイトル1
## タイトル2
### タイトル3
#### タイトル4
## 箇条書き -> 「-」
- 「-」は箇条書き
- 「-」の後に、スペースを1つあけて、箇条書きの内容を書く
- 「-」の前に、スペースを3つ置くと、インデントされて表示される
- このように階層構造で表示される
## 箇条書き(番号付き) -> 「1.」
1. 「1.」は箇条書き(番号付き)
1. 「1.」の後に、スペースを1つあけて、箇条書きの内容を書く
1. 番号が付くこと以外「-」と同じ
## 強調 -> 「2つの*(アスタリスク)」
- 文の中の強調したい部分を「2つの*(アスタリスク)」で囲むと強調する
- 例えば **こんなふうに** 強調される
## 罫線 -> 「3つ以上の*(アスタリスク)」
- 罫線を入れたい場合、「3つ以上の*(アスタリスク)」のみを記載する
***
- 上に罫線が表示される
## リンク
- リンクを入れたい部分に、[リンクの名前](リンク先のURL) を記載する
- [Knowledge](https://information-knowledge.support-project.org)
## コードを表示
- コードを表示したい部分は「`(バッククオート)」で囲みます
```ruby
require 'redcarpet'
markdown = Redcarpet.new("Hello World!")
puts markdown.to_html
```
## 拡張Markdown syntax
- WebSiteの紹介を入れたい部分に[oembed WebSiteURL]を記載する
- GitHub
- [oembed https://github.com/support-project/knowledge]
- SlideShare
- [oembed http://www.slideshare.net/koda3/knowledge-information]
- GoogleMap
- [oembed https://www.google.com/maps/embed?pb=!1m18!1m12!1m3!1d12966.919088372344!2d139.72177695!3d35.6590289!2m3!1f0!2f0!3f0!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0x0%3A0x5bfe0248594cc802!2z5YWt5pys5pyo44OS44Or44K6!5e0!3m2!1sja!2sjp!4v1482300583922]
- 絵文字
- `:` と `:` の間にキーを入れることで絵文字を表示します
- `people nature objects places symbols` のリンクで絵文字の一覧を表示するので、そこから選択することも可能です
- :+1: :smile:
- 他の記事へのリンク
- `#` の後に記事のIDを入力すると、他の記事へのリンクになる
- `#` を入力すると、リンク先の記事の選択肢が表示される
- #1 ← 記事「1」へのリンク
- LaTeX形式で数式(ブロック表示)
- `$$`で囲むと数式をブロック表示します
- $$ e^{i\theta} = \cos\theta + i\sin\theta $$
- LaTeX形式で数式(インライン表示)
- `$` で囲むとインライン表示
- 有名なオイラーの公式は,$e^{i\theta}=\cos\theta+i\sin\theta$ です.
- LaTeX形式で数式(コードブロック)
- コードブロック \`\`\`math の中は、直接数式を記載します(上記の'$'が必要無し)
- `\\` が改行
```math
数式1:
E = mc^2
\\
数式2:
\sum_{n=1}^\infty \frac{1}{n^2} = \frac{\pi^2}{6}
\\
有名なオイラーの公式は,e^{i\theta}=\cos\theta+i\sin\theta です.
```
## 画像を記事内に挿入
- 画像をアップロードすると、「画像を表示」ボタンを押せるようになり、それを押すと画像が表示される
- 画像の表示は以下のような形式で記載する
- ``
- 
## 画像を記事内に挿入(クリップボードにコピーした画像を直接アップロード)
- テキストの編集エリアに、直接貼り付けることが可能です
## スライドを記事内に挿入
- スライド(PDF)をアップロードすると、「スライドショー」ボタンを押せるようになり、それを押すとスライドショー表示ができる
## さらに詳しく
- [GitHub Flavored Markdown](https://help.github.com/articles/github-flavored-markdown/) が参考になります
|
apache-2.0
|
ethereumproject/etherjar
|
etherjar-abi/src/main/java/io/emeraldpay/etherjar/abi/UFixedType.java
|
3629
|
/*
* Copyright (c) 2020 EmeraldPay Inc, All Rights Reserved.
* Copyright (c) 2016-2017 Infinitape 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 io.emeraldpay.etherjar.abi;
import java.math.BigDecimal;
import java.util.Collections;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.function.Function;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class UFixedType extends DecimalType {
public final static UFixedType DEFAULT = new UFixedType();
final static Map<Integer, UFixedType> CACHED_INSTANCES =
Stream.of(8, 16, 32, 64, 128).collect(Collectors.collectingAndThen(
Collectors.toMap(Function.identity(), UFixedType::new), Collections::unmodifiableMap));
final static String NAME_PREFIX = "ufixed";
final static Pattern NAME_PATTERN = Pattern.compile("ufixed((\\d{1,3})x(\\d{1,3}))?");
/**
* Try to parse a {@link UFixedType} string representation (either canonical form or not).
*
* @param str a string
* @return a {@link UFixedType} instance is packed as {@link Optional} value,
* or {@link Optional#empty()} instead
* @throws NullPointerException if a {@code str} is {@code null}
* @throws IllegalArgumentException if a {@link IntType} has invalid input
* @see #getCanonicalName()
*/
public static Optional<UFixedType> from(String str) {
if (!str.startsWith(NAME_PREFIX))
return Optional.empty();
Matcher matcher = NAME_PATTERN.matcher(str);
if (!matcher.matches())
throw new IllegalArgumentException("Wrong 'ufixed' type format: " + str);
if (Objects.isNull(matcher.group(1)))
return Optional.of(DEFAULT);
int mBits = Integer.parseInt(matcher.group(2));
int nBits = Integer.parseInt(matcher.group(3));
return Optional.of(mBits == nBits && CACHED_INSTANCES.containsKey(mBits) ?
CACHED_INSTANCES.get(mBits) : new UFixedType(mBits, nBits));
}
private final BigDecimal minValue;
private final BigDecimal maxValue;
private final NumericType numericType;
public UFixedType() {
this(128, 128);
}
public UFixedType(int bits) {
this(bits, bits);
}
public UFixedType(int mBits, int nBits) {
super(mBits, nBits);
numericType = new UIntType(mBits + nBits);
minValue = new BigDecimal(
numericType.getMinValue().shiftRight(nBits));
maxValue = new BigDecimal(
numericType.getMaxValue().shiftRight(nBits));
}
@Override
public BigDecimal getMinValue() {
return minValue;
}
@Override
public BigDecimal getMaxValue() {
return maxValue;
}
@Override
public NumericType getNumericType() {
return numericType;
}
@Override
public String getCanonicalName() {
return String.format("ufixed%dx%d", getMBits(), getNBits());
}
}
|
apache-2.0
|
injitools/cms-Inji
|
system/modules/Ecommerce/appControllers/content/view.php
|
3001
|
<?php
/**
* @var \Ecommerce\Item $item ;
*/
?>
<div class="ecommerce">
<div class="row">
<div class="col-md-3 item-sidebar">
<div class="sidebar-block">
<div class="items">
<?php $this->widget('Ecommerce\categorys'); ?>
</div>
</div>
</div>
<div class="col-md-9">
<div class="detail_item content">
<div class="row">
<div class="col-sm-5">
<img src="<?= Statics::file($item->image ? $item->image->path : false, '350x800'); ?>"
class="img-responsive"/>
</div>
<div class="col-sm-7">
<h1><?= $item->name(); ?></h1>
<ul class="item-options">
<?php
foreach ($item->options as $param) {
if (!$param->item_option_view || !$param->value) {
continue;
}
if ($param->item_option_type == 'select') {
if (empty($param->option->items[$param->value])) {
continue;
}
$value = $param->option->items[$param->value]->value;
} else {
$value = $param->value;
}
$paramName = $param->item_option_name;
echo "<li>{$paramName}: {$value} {$param->item_option_postfix}</li>";
}
?>
</ul>
<div class="item-actions">
<div class="item-price">
<span class="item-price-caption">Цена: </span>
<span class="item-price-amount"><?= number_format($item->getPrice()->price, 2, '.', ' '); ?></span>
<span class="item-price-currency">руб</span>
</div>
<div class="btn btn-primary item-addtocart"
onclick="inji.Ecommerce.Cart.addItem(<?= $item->getPrice()->id; ?>, 1);">
<i class="glyphicon glyphicon-shopping-cart"></i> Добавить в корзину
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-xs-12">
<div class="item-description">
<?= $item->description; ?>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
|
apache-2.0
|
ivannaranjo/google-cloud-visualstudio
|
GoogleCloudExtension/GoogleCloudExtension/CloudExplorerSources/Gae/VersionItem.cs
|
3463
|
// 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.
using Google.Apis.Appengine.v1.Data;
using GoogleCloudExtension.Utils;
namespace GoogleCloudExtension.CloudExplorerSources.Gae
{
/// <summary>
/// This class represents a GAE service in the Properties Window.
/// </summary>
internal class VersionItem : PropertyWindowItemBase
{
private readonly Version _version;
public VersionItem(Version version) : base(className: Resources.CloudExplorerGaeVersionCategory, componentName: version.Id)
{
_version = version;
}
[LocalizedCategory(nameof(Resources.CloudExplorerGaeVersionCategory))]
public string Name => _version.Name;
[LocalizedCategory(nameof(Resources.CloudExplorerGaeVersionCategory))]
public string Id => _version.Id;
[LocalizedCategory(nameof(Resources.CloudExplorerGaeVersionCategory))]
public string Status => _version.ServingStatus;
[LocalizedCategory(nameof(Resources.CloudExplorerGaeVersionCategory))]
public string Deployer => _version.CreatedBy;
[LocalizedCategory(nameof(Resources.CloudExplorerGaeVersionCategory))]
public string Url => _version.VersionUrl;
[LocalizedCategory(nameof(Resources.CloudExplorerGaeVersionCategory))]
public string Runtime => _version.Runtime;
[LocalizedCategory(nameof(Resources.CloudExplorerGaeVersionCategory))]
public string Environment => _version.Env;
[LocalizedDisplayName(nameof(Resources.CloudExplorerGaeVersionInstanceClassDisplayName))]
[LocalizedCategory(nameof(Resources.CloudExplorerGaeVersionCategory))]
public string InstanceClass => _version.InstanceClass;
[LocalizedDisplayName(nameof(Resources.CloudExplorerGaeVersionCreationTimeDisplayName))]
[LocalizedCategory(nameof(Resources.CloudExplorerGaeVersionCategory))]
public string CreationTime => _version.CreateTime;
[LocalizedDisplayName(nameof(Resources.CloudExplorerGaeVersionVirtualMachineDisplayName))]
[LocalizedCategory(nameof(Resources.CloudExplorerGaeVersionCategory))]
public bool? VirtualMachine => _version.Vm;
[LocalizedCategory(nameof(Resources.CloudExplorerGaeVersionResourcesCategory))]
public double? CPU => _version.Resources?.Cpu;
[LocalizedDisplayName(nameof(Resources.CloudExplorerGaeVersionResoucesDiskDisplayName))]
[LocalizedCategory(nameof(Resources.CloudExplorerGaeVersionResourcesCategory))]
public double? Disk => _version.Resources?.DiskGb;
[LocalizedDisplayName(nameof(Resources.CloudExplorerGaeVersionResoucesMemoryDisplayName))]
[LocalizedCategory(nameof(Resources.CloudExplorerGaeVersionResourcesCategory))]
public double? Memory => _version.Resources?.MemoryGb;
public override string ToString() => _version.Id;
}
}
|
apache-2.0
|
treason258/TreLibrary
|
LovelyReaderAS/appbase/src/main/java/com/app/base/common/calculation/Space.java
|
560
|
/**
*
*/
package com.app.base.common.calculation;
/**
* 用来定义两个点之间的距离.
*
* @author [email protected]
*/
public class Space {
/**
* x,y轴需要增加或增小的距离.
*/
public float x_space = 0, y_space = 0;
/**
*
*/
public Space() {
super();
}
/**
* 构造Space对象.
* @param x_space x轴需要增加或增小的距离.
* @param y_space y轴需要增加或增小的距离.
*/
public Space(float x_space, float y_space) {
super();
this.x_space = x_space;
this.y_space = y_space;
}
}
|
apache-2.0
|
d3estudio/asics-access
|
web/app/assets/javascripts/controllers/admin/reportCtrl.js
|
1736
|
angular.module('asics').controller('ReportCtrl', [
'$mdToast',
'$scope',
'$interval',
'admin',
'$stateParams',
function ($mdToast, $scope, $interval, admin, $stateParams) {
$scope.strings = {};
$scope.language = $stateParams.language;
$scope.country_count = [];
$scope.available_dates = [];
$scope.current_date = [];
angular.copy(adminReportStrings[$scope.language], $scope.strings);
function get_reports(day) {
admin.getReport(day)
.then(readReportInformation)
.catch(errorToast);
}
createDateList();
setCurrentDate();
function createDateList() {
for (var day = 3; day < 22; day++) {
$scope.available_dates.push({
date: day
});
}
}
function setCurrentDate() {
var d = new Date();
var day = d.getDate();
$scope.current_date = $.grep($scope.available_dates, function(e){ return e.date == day })[0];
}
function readReportInformation(result) {
angular.copy(result.country_count, $scope.country_count);
}
$scope.$watch('current_date', function () {
get_reports($scope.current_date.date)
});
function errorToast(error) {
var toast = $mdToast.simple()
.textContent(error)
.position('top right')
.hideDelay(3000)
.theme('error-toast');
$mdToast.show(toast);
}
}
]);
var adminReportStrings = {
EN: {
date: "Day",
title: "Visitors list",
description: "Select the date to look up the number of visitors per country on that day."
},
PT: {
date: "Dia",
title: "Lista de visitantes",
description: "Selecione a data para pesquisar o número de visitantes por país no dia."
}
};
|
apache-2.0
|
mimacom/maven-liferay-plugin
|
mimacom-liferay-adapter/mimacom-liferay-adapter-6.1.10/src/main/java/org/mimacom/commons/liferay/adapter6110/LiferayToolsImpl.java
|
3832
|
package org.mimacom.commons.liferay.adapter6110;
/*
* Copyright (c) 2014 mimacom a.g.
*
* 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 java.io.File;
import org.mimacom.commons.liferay.adapter.LiferayTools;
import com.liferay.portal.kernel.log.Log;
import com.liferay.portal.kernel.log.LogFactory;
import com.liferay.portal.kernel.log.LogFactoryUtil;
import com.liferay.portal.kernel.util.FileUtil;
import com.liferay.portal.kernel.util.HtmlUtil;
import com.liferay.portal.kernel.util.ServerDetector;
import com.liferay.portal.kernel.xml.SAXReaderUtil;
import com.liferay.portal.util.FileImpl;
import com.liferay.portal.util.HtmlImpl;
import com.liferay.portal.util.PortalImpl;
import com.liferay.portal.util.PortalUtil;
import com.liferay.portal.xml.SAXReaderImpl;
public class LiferayToolsImpl implements LiferayTools {
public LiferayToolsImpl() {
}
static void addExtraContent(String appServerType, StringBuilder content) {
if (ServerDetector.WEBSPHERE_ID.equals(appServerType)) {
content.append("<context-param>");
content
.append("<param-name>com.ibm.websphere.portletcontainer.PortletDeploymentEnabled</param-name>");
content.append("<param-value>false</param-value>");
content.append("</context-param>");
}
}
public String getVersion() {
return "6.1.10";
}
public void initLiferay() {
new FileUtil().setFile(new FileImpl());
new SAXReaderUtil().setSAXReader(new SAXReaderImpl());
new PortalUtil().setPortal(new PortalImpl());
new HtmlUtil().setHtml(new HtmlImpl());
}
public void mergeCss(File basedir) {
// TODO stni
// create the merged css uncompressed and compressed
// String cssPath = new File(basedir, "css").getAbsolutePath();
// String unpacked = cssPath + "/everything_unpacked.css";
// new CSSBuilder(cssPath, unpacked);
// YUICompressor.main(new String[] { "--type", "css", "-o", cssPath +
// "/everything_packed.css", unpacked });
}
public void initLog(final org.apache.maven.plugin.logging.Log log) {
LogFactoryUtil.setLogFactory(new LogFactory() {
public Log getLog(String name) {
return new MavenLiferayLog(name, log);
}
public Log getLog(Class<?> c) {
return new MavenLiferayLog(c.getSimpleName(), log);
}
});
}
public void deployLayout(String serverType, File sourceDir)
throws Exception {
new StandaloneLayoutDeployer(serverType).deployFile(sourceDir,null);
}
public void deployPortlet(String version, String serverType, File sourceDir)
throws Exception {
new StandalonePortletDeployer(version, serverType).deployFile(
sourceDir, null);
}
public void deployTheme(String serverType, File sourceDir) throws Exception {
new StandaloneThemeDeployer(serverType).deployFile(sourceDir,null);
}
public void deployHook(String serverType, File sourceDir) throws Exception {
new StandaloneHookDeployer(serverType).deployFile(sourceDir,null);
}
public void buildService(String arg0, String arg1, String arg2,
String arg3, String arg4, String arg5, String arg6, String arg7,
String arg8, String arg9, String arg10, String arg11, String arg12,
String arg13, String arg14, String arg15, String arg16,
String arg17, String arg18, String arg19, boolean arg20,
String arg21, String arg22, String arg23, String arg24) {
// TODO Auto-generated method stub
}
}
|
apache-2.0
|
fredzannarbor/pagekicker-community
|
scripts/includes/text-extraction-from-html.sh
|
219
|
# extract text
$JAVA_BIN -jar $scriptpath"lib/tika-app.jar" -t tmp/$uuid/tmp.cumulative.html > tmp/$uuid/cumulative.txt
echo "completed text extraction from html to tmp/$uuid/cumulative.txt" | tee --append $sfb_log
|
apache-2.0
|
KyoSherlock/SherlockMidi
|
sherlockmidi/src/main/java/cn/sherlock/com/sun/media/sound/ModelConnectionBlock.java
|
4417
|
/*
* Copyright 2007 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.
*/
package cn.sherlock.com.sun.media.sound;
/**
* Connection blocks are used to connect source variable
* to a destination variable.
* For example Note On velocity can be connected to output gain.
* In DLS this is called articulator and in SoundFonts (SF2) a modulator.
*
* @author Karl Helgason
*/
public class ModelConnectionBlock {
//
// source1 * source2 * scale -> destination
//
private final static ModelSource[] no_sources = new ModelSource[0];
private ModelSource[] sources = no_sources;
private double scale = 1;
private ModelDestination destination;
public ModelConnectionBlock() {
}
public ModelConnectionBlock(double scale, ModelDestination destination) {
this.scale = scale;
this.destination = destination;
}
public ModelConnectionBlock(ModelSource source,
ModelDestination destination) {
if (source != null) {
this.sources = new ModelSource[1];
this.sources[0] = source;
}
this.destination = destination;
}
public ModelConnectionBlock(ModelSource source, double scale,
ModelDestination destination) {
if (source != null) {
this.sources = new ModelSource[1];
this.sources[0] = source;
}
this.scale = scale;
this.destination = destination;
}
public ModelConnectionBlock(ModelSource source, ModelSource control,
ModelDestination destination) {
if (source != null) {
if (control == null) {
this.sources = new ModelSource[1];
this.sources[0] = source;
} else {
this.sources = new ModelSource[2];
this.sources[0] = source;
this.sources[1] = control;
}
}
this.destination = destination;
}
public ModelConnectionBlock(ModelSource source, ModelSource control,
double scale, ModelDestination destination) {
if (source != null) {
if (control == null) {
this.sources = new ModelSource[1];
this.sources[0] = source;
} else {
this.sources = new ModelSource[2];
this.sources[0] = source;
this.sources[1] = control;
}
}
this.scale = scale;
this.destination = destination;
}
public ModelDestination getDestination() {
return destination;
}
public void setDestination(ModelDestination destination) {
this.destination = destination;
}
public double getScale() {
return scale;
}
public void setScale(double scale) {
this.scale = scale;
}
public ModelSource[] getSources() {
return sources;
}
public void setSources(ModelSource[] source) {
this.sources = source;
}
public void addSource(ModelSource source) {
ModelSource[] oldsources = sources;
sources = new ModelSource[oldsources.length + 1];
for (int i = 0; i < oldsources.length; i++) {
sources[i] = oldsources[i];
}
sources[sources.length - 1] = source;
}
}
|
apache-2.0
|
alibaba/nacos
|
common/src/main/java/com/alibaba/nacos/common/http/client/handler/AbstractResponseHandler.java
|
2256
|
/*
* Copyright 1999-2018 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.common.http.client.handler;
import com.alibaba.nacos.common.http.HttpRestResult;
import com.alibaba.nacos.common.http.client.response.HttpClientResponse;
import com.alibaba.nacos.common.http.param.Header;
import com.alibaba.nacos.common.utils.IoUtils;
import org.apache.http.HttpStatus;
import java.lang.reflect.Type;
/**
* Abstract response handler.
*
* @author mai.jh
*/
public abstract class AbstractResponseHandler<T> implements ResponseHandler<T> {
private Type responseType;
@Override
public final void setResponseType(Type responseType) {
this.responseType = responseType;
}
@Override
public final HttpRestResult<T> handle(HttpClientResponse response) throws Exception {
if (HttpStatus.SC_OK != response.getStatusCode()) {
return handleError(response);
}
return convertResult(response, this.responseType);
}
private HttpRestResult<T> handleError(HttpClientResponse response) throws Exception {
Header headers = response.getHeaders();
String message = IoUtils.toString(response.getBody(), headers.getCharset());
return new HttpRestResult<T>(headers, response.getStatusCode(), null, message);
}
/**
* Abstract convertResult method, Different types of converters for expansion.
*
* @param response http client response
* @param responseType responseType
* @return HttpRestResult
* @throws Exception ex
*/
public abstract HttpRestResult<T> convertResult(HttpClientResponse response, Type responseType) throws Exception;
}
|
apache-2.0
|
hanhlh/hadoop-0.20.2_FatBTree
|
src/hdfs/org/apache/hadoop/hdfs/server/namenodeFBT/rule/CompleteFileRule.java
|
1272
|
/**
*
*/
package org.apache.hadoop.hdfs.server.namenodeFBT.rule;
import org.apache.hadoop.hdfs.server.namenodeFBT.FBTDirectory;
import org.apache.hadoop.hdfs.server.namenodeFBT.NameNodeFBTProcessor;
import org.apache.hadoop.hdfs.server.namenodeFBT.NodeVisitor;
import org.apache.hadoop.hdfs.server.namenodeFBT.NodeVisitorFactory;
import org.apache.hadoop.hdfs.server.namenodeFBT.utils.StringUtility;
/**
* @author hanhlh
*
*/
public class CompleteFileRule extends AbstractRule{
public CompleteFileRule(RuleManager manager) {
super(manager);
}
@Override
protected Class[] events() {
return new Class[] { CompleteFileRequest.class };
}
@Override
protected void action(RuleEvent event) {
StringUtility.debugSpace("CompleteFileRule action");
CompleteFileRequest request = (CompleteFileRequest) event;
FBTDirectory directory =
(FBTDirectory) NameNodeFBTProcessor.
lookup(request.getDirectoryName());
NodeVisitorFactory visitorFactory = directory.getNodeVisitorFactory();
NodeVisitor visitor = visitorFactory.createCompleteFileVisitor();
visitor.setRequest(request);
visitor.run();
_manager.dispatch(visitor.getResponse());
}
}
|
apache-2.0
|
rabitarochan/play-angularhelper
|
core/src/main/scala/com/github/rabitarochan/play2/angularhelper/JsType.scala
|
2399
|
package com.github.rabitarochan.play2.angularhelper
import play.api.libs.json._
import scala.util.matching.Regex
sealed trait JsType {
def parse(key: String, kvs: Seq[(String, String)]): JsValue
}
case class JsBooleanType(default: Boolean) extends JsType {
def parse(key: String, kvs: Seq[(String, String)]): JsValue = {
kvs.find(_._1 == key) match {
case Some((_, v)) => JsBoolean(v.toBoolean)
case None => JsBoolean(default)
}
}
}
case class JsNumberType(default: Int) extends JsType {
def parse(key: String, kvs: Seq[(String, String)]): JsValue = {
kvs.find(_._1 == key) match {
case Some((_, value)) => JsNumber(BigDecimal(value))
case None => JsNumber(default)
}
}
}
case class JsStringType(default: String) extends JsType {
def parse(key: String, kvs: Seq[(String, String)]): JsValue = {
kvs.find(_._1 == key) match {
case Some((_, v)) => JsString(v)
case None => JsString(default)
}
}
}
case class JsObjectType(properties: (String, JsType)*) extends JsType {
def parse(key: String, kvs: Seq[(String, String)]): JsValue = {
kvs.filter(_._1.startsWith(key + ".")) match {
case Nil => JsObject(properties.map(x => x._1 -> x._2.parse(x._1, Nil)))
case xs => {
JsObject(
properties.map { property =>
val (pkey, ptype) = property
pkey -> ptype.parse(pkey, xs.map(x => (x._1.substring((key + ".").length), x._2)))
}
)
}
}
}
}
case class JsArrayType(innerJsType: JsType) extends JsType {
def parse(key: String, kvs: Seq[(String, String)]): JsValue = {
kvs.filter(p => isMatch(key, p._1)) match {
case Nil => JsArray(Nil)
case xs => {
JsArray(
xs.groupBy(t => getGroupKey(key, t._1))
.toSeq
.sortBy(_._1)
.map(p =>
innerJsType.parse("", p._2.map(t => removeKey(key, t._1) -> t._2)))
)
}
}
}
private def isMatch(key: String, s: String): Boolean = {
arrayRegex(key).findPrefixMatchOf(s).isDefined
}
private def getGroupKey(key: String, s: String): String = {
arrayRegex(key).findPrefixOf(s).get
}
private def removeKey(key: String, s: String): String = {
arrayRegex(key).replaceFirstIn(s, "")
}
private def arrayRegex(key: String): Regex = s"${key}\\[[0-9]+\\]".r
}
|
apache-2.0
|
hajdam/deltahex-netbeans
|
src/org/exbin/framework/editor/text/panel/TextFontOptionsPanel.java
|
15094
|
/*
* Copyright (C) ExBin Project
*
* This application or 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 3 of the License,
* or (at your option) any later version.
*
* This application or 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 this application. If not, see <http://www.gnu.org/licenses/>.
*/
package org.exbin.framework.editor.text.panel;
import java.awt.Font;
import java.awt.event.ItemEvent;
import java.awt.font.TextAttribute;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.ResourceBundle;
import java.util.prefs.Preferences;
import org.exbin.framework.gui.options.api.OptionsPanel;
import org.exbin.framework.gui.options.api.OptionsPanel.ModifiedOptionListener;
import org.exbin.framework.gui.options.api.OptionsPanel.PathItem;
/**
* Text font options panel.
*
* @version 0.2.0 2017/01/04
* @author ExBin Project (http://exbin.org)
*/
public class TextFontOptionsPanel extends javax.swing.JPanel implements OptionsPanel {
public static final String PREFERENCES_TEXT_FONT_DEFAULT = "textFont.default";
public static final String PREFERENCES_TEXT_FONT_FAMILY = "textFont.family";
public static final String PREFERENCES_TEXT_FONT_SIZE = "textFont.size";
public static final String PREFERENCES_TEXT_FONT_UNDERLINE = "textFont.underline";
public static final String PREFERENCES_TEXT_FONT_STRIKETHROUGH = "textFont.strikethrough";
public static final String PREFERENCES_TEXT_FONT_STRONG = "textFont.strong";
public static final String PREFERENCES_TEXT_FONT_ITALIC = "textFont.italic";
public static final String PREFERENCES_TEXT_FONT_SUBSCRIPT = "textFont.subscript";
public static final String PREFERENCES_TEXT_FONT_SUPERSCRIPT = "textFont.superscript";
private ModifiedOptionListener modifiedOptionListener;
private FontChangeAction fontChangeAction;
private final ResourceBundle resourceBundle;
private final TextFontPanelApi frame;
private Font font;
public TextFontOptionsPanel(TextFontPanelApi frame) {
this.frame = frame;
resourceBundle = java.util.ResourceBundle.getBundle("org/exbin/framework/editor/text/panel/resources/TextFontOptionsPanel");
initComponents();
}
@Override
public void setEnabled(boolean enabled) {
super.setEnabled(enabled);
fontPreviewLabel.setEnabled(enabled);
fillDefaultFontButton.setEnabled(enabled);
fillCurrentFontButton.setEnabled(enabled);
changeFontButton.setEnabled(enabled);
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jColorChooser1 = new javax.swing.JColorChooser();
defaultFontCheckBox = new javax.swing.JCheckBox();
fillDefaultFontButton = new javax.swing.JButton();
changeFontButton = new javax.swing.JButton();
fontPreviewLabel = new javax.swing.JLabel();
fillCurrentFontButton = new javax.swing.JButton();
jColorChooser1.setName("jColorChooser1"); // NOI18N
setName("Form"); // NOI18N
defaultFontCheckBox.setSelected(true);
defaultFontCheckBox.setText(resourceBundle.getString("TextFontOptionsPanel.defaultFontCheckBox.text")); // NOI18N
defaultFontCheckBox.setName("defaultFontCheckBox"); // NOI18N
defaultFontCheckBox.addItemListener(new java.awt.event.ItemListener() {
public void itemStateChanged(java.awt.event.ItemEvent evt) {
defaultFontCheckBoxItemStateChanged(evt);
}
});
fillDefaultFontButton.setText(resourceBundle.getString("TextFontOptionsPanel.fillDefaultFontButton.text")); // NOI18N
fillDefaultFontButton.setEnabled(false);
fillDefaultFontButton.setName("fillDefaultFontButton"); // NOI18N
fillDefaultFontButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
fillDefaultFontButtonActionPerformed(evt);
}
});
changeFontButton.setText(resourceBundle.getString("TextFontOptionsPanel.changeFontButton.text")); // NOI18N
changeFontButton.setEnabled(false);
changeFontButton.setName("changeFontButton"); // NOI18N
changeFontButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
changeFontButtonActionPerformed(evt);
}
});
fontPreviewLabel.setBackground(java.awt.Color.white);
fontPreviewLabel.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
fontPreviewLabel.setText(resourceBundle.getString("TextFontOptionsPanel.fontPreviewLabel.text")); // NOI18N
fontPreviewLabel.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
fontPreviewLabel.setEnabled(false);
fontPreviewLabel.setName("fontPreviewLabel"); // NOI18N
fontPreviewLabel.setOpaque(true);
fillCurrentFontButton.setText(resourceBundle.getString("TextFontOptionsPanel.fillCurrentFontButton.text")); // NOI18N
fillCurrentFontButton.setEnabled(false);
fillCurrentFontButton.setName("fillCurrentFontButton"); // NOI18N
fillCurrentFontButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
fillCurrentFontButtonActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(fontPreviewLabel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(defaultFontCheckBox, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(layout.createSequentialGroup()
.addComponent(changeFontButton)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(fillDefaultFontButton)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(fillCurrentFontButton)
.addGap(0, 0, Short.MAX_VALUE)))
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(defaultFontCheckBox)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(fontPreviewLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 39, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(changeFontButton)
.addComponent(fillDefaultFontButton)
.addComponent(fillCurrentFontButton))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
}// </editor-fold>//GEN-END:initComponents
private void defaultFontCheckBoxItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_defaultFontCheckBoxItemStateChanged
boolean selected = evt.getStateChange() != ItemEvent.SELECTED;
fontPreviewLabel.setEnabled(selected);
fillDefaultFontButton.setEnabled(selected);
fillCurrentFontButton.setEnabled(selected);
changeFontButton.setEnabled(selected);
setModified(true);
}//GEN-LAST:event_defaultFontCheckBoxItemStateChanged
private void fillDefaultFontButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_fillDefaultFontButtonActionPerformed
fontPreviewLabel.setFont(frame.getDefaultFont());
setModified(true);
}//GEN-LAST:event_fillDefaultFontButtonActionPerformed
private void changeFontButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_changeFontButtonActionPerformed
if (fontChangeAction != null) {
Font resultFont = fontChangeAction.changeFont(fontPreviewLabel.getFont());
if (resultFont != null) {
fontPreviewLabel.setFont(resultFont);
setModified(true);
}
}
}//GEN-LAST:event_changeFontButtonActionPerformed
private void fillCurrentFontButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_fillCurrentFontButtonActionPerformed
fontPreviewLabel.setFont(frame.getCurrentFont());
setModified(true);
}//GEN-LAST:event_fillCurrentFontButtonActionPerformed
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton changeFontButton;
private javax.swing.JCheckBox defaultFontCheckBox;
private javax.swing.JButton fillCurrentFontButton;
private javax.swing.JButton fillDefaultFontButton;
private javax.swing.JLabel fontPreviewLabel;
private javax.swing.JColorChooser jColorChooser1;
// End of variables declaration//GEN-END:variables
@Override
public List<OptionsPanel.PathItem> getPath() {
ArrayList<OptionsPanel.PathItem> path = new ArrayList<>();
path.add(new PathItem("apperance", ""));
path.add(new PathItem("font", resourceBundle.getString("options.Path.0")));
return path;
}
@Override
public void loadFromPreferences(Preferences preferences) {
Boolean defaultColor = Boolean.valueOf(preferences.get(PREFERENCES_TEXT_FONT_DEFAULT, Boolean.toString(true)));
defaultFontCheckBox.setSelected(defaultColor);
setEnabled(!defaultColor);
String value;
Map<TextAttribute, Object> attribs = new HashMap<>();
value = preferences.get(PREFERENCES_TEXT_FONT_FAMILY, null);
if (value != null) {
attribs.put(TextAttribute.FAMILY, value);
}
value = preferences.get(PREFERENCES_TEXT_FONT_SIZE, null);
if (value != null) {
attribs.put(TextAttribute.SIZE, new Integer(value).floatValue());
}
if (Boolean.valueOf(preferences.get(PREFERENCES_TEXT_FONT_UNDERLINE, null))) {
attribs.put(TextAttribute.UNDERLINE, TextAttribute.UNDERLINE_LOW_ONE_PIXEL);
}
if (Boolean.valueOf(preferences.get(PREFERENCES_TEXT_FONT_STRIKETHROUGH, null))) {
attribs.put(TextAttribute.STRIKETHROUGH, TextAttribute.STRIKETHROUGH_ON);
}
if (Boolean.valueOf(preferences.get(PREFERENCES_TEXT_FONT_STRONG, null))) {
attribs.put(TextAttribute.WEIGHT, TextAttribute.WEIGHT_BOLD);
}
if (Boolean.valueOf(preferences.get(PREFERENCES_TEXT_FONT_ITALIC, null))) {
attribs.put(TextAttribute.POSTURE, TextAttribute.POSTURE_OBLIQUE);
}
if (Boolean.valueOf(preferences.get(PREFERENCES_TEXT_FONT_SUBSCRIPT, null))) {
attribs.put(TextAttribute.SUPERSCRIPT, TextAttribute.SUPERSCRIPT_SUB);
}
if (Boolean.valueOf(preferences.get(PREFERENCES_TEXT_FONT_SUPERSCRIPT, null))) {
attribs.put(TextAttribute.SUPERSCRIPT, TextAttribute.SUPERSCRIPT_SUPER);
}
font = frame.getDefaultFont().deriveFont(attribs);
fontPreviewLabel.setFont(font);
}
@Override
public void saveToPreferences(Preferences preferences) {
preferences.put(PREFERENCES_TEXT_FONT_DEFAULT, Boolean.toString(defaultFontCheckBox.isSelected()));
Map<TextAttribute, ?> attribs = font.getAttributes();
String value = (String) attribs.get(TextAttribute.FAMILY);
if (value != null) {
preferences.put(PREFERENCES_TEXT_FONT_FAMILY, value);
} else {
preferences.remove(PREFERENCES_TEXT_FONT_FAMILY);
}
Float fontSize = (Float) attribs.get(TextAttribute.SIZE);
if (fontSize != null) {
preferences.put(PREFERENCES_TEXT_FONT_SIZE, Integer.toString((int) (float) fontSize));
} else {
preferences.remove(PREFERENCES_TEXT_FONT_SIZE);
}
preferences.put(PREFERENCES_TEXT_FONT_UNDERLINE, Boolean.toString(TextAttribute.UNDERLINE_LOW_ONE_PIXEL.equals(attribs.get(TextAttribute.UNDERLINE))));
preferences.put(PREFERENCES_TEXT_FONT_STRIKETHROUGH, Boolean.toString(TextAttribute.STRIKETHROUGH_ON.equals(attribs.get(TextAttribute.STRIKETHROUGH))));
preferences.put(PREFERENCES_TEXT_FONT_STRONG, Boolean.toString(TextAttribute.WEIGHT_BOLD.equals(attribs.get(TextAttribute.WEIGHT))));
preferences.put(PREFERENCES_TEXT_FONT_ITALIC, Boolean.toString(TextAttribute.POSTURE_OBLIQUE.equals(attribs.get(TextAttribute.POSTURE))));
preferences.put(PREFERENCES_TEXT_FONT_SUBSCRIPT, Boolean.toString(TextAttribute.SUPERSCRIPT_SUB.equals(attribs.get(TextAttribute.SUPERSCRIPT))));
preferences.put(PREFERENCES_TEXT_FONT_SUPERSCRIPT, Boolean.toString(TextAttribute.SUPERSCRIPT_SUPER.equals(attribs.get(TextAttribute.SUPERSCRIPT))));
}
@Override
public void applyPreferencesChanges() {
if (defaultFontCheckBox.isSelected()) {
frame.setCurrentFont(frame.getDefaultFont());
} else {
frame.setCurrentFont(font);
}
}
private void setModified(boolean b) {
if (modifiedOptionListener != null) {
modifiedOptionListener.wasModified();
}
}
@Override
public void setModifiedOptionListener(ModifiedOptionListener listener) {
modifiedOptionListener = listener;
}
public void setFontChangeAction(FontChangeAction fontChangeAction) {
this.fontChangeAction = fontChangeAction;
}
public static interface FontChangeAction {
Font changeFont(Font currentFont);
}
}
|
apache-2.0
|
Tendors/phpshell
|
protected/modules/Crypt/install.php
|
1294
|
<?
$error = false;
if (isset($_POST['action'])) {
switch ($_POST['action']) {
case 'crypt_set_key':
$_SESSION['core']['install']['crypt']['key'] = $_POST['key'];
break;
}
}
ob_start();
?>
<!DOCTYPE html>
<html lang="en-US">
<head>
<title>Install Crypt</title>
<meta charset="UTF-8">
<meta name="robots" content="none">
</head>
<body>
<h1>Install Crypt</h1>
<?
if (!$error) {
if (!isset($_SESSION['core']['install']['crypt']['key'])) {
$error = true;
?>
<form method="post">
<input type="hidden" name="action" value="crypt_set_key">
<label for="key">Key</label>
<br>
<input type="text" name="key" value="<?= str_pad(bin2hex(openssl_random_pseudo_bytes(16)), 32, "\0") ?>">
<br><br>
<input type="submit" value="Next">
</form>
<?
}
}
?>
</body>
</html>
<?
$content = ob_get_contents();
ob_end_clean();
if ($error) {
echo $content;
exit;
}
// Install module
$data->extractTo(ROOT);
if (!APP::Module('Registry')->Get('module_crypt_key')) {
APP::Module('Registry')->Add('module_crypt_key', $_SESSION['core']['install']['crypt']['key']);
}
|
apache-2.0
|
DeLaSalleUniversity-Manila/forkhub-Janelaaa
|
app/src/main/java/com/janela/mobile/ui/gist/CreateGistActivity.java
|
4694
|
/*
* Copyright 2012 GitHub Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.janela.mobile.ui.gist;
import static android.content.Intent.FLAG_ACTIVITY_CLEAR_TOP;
import static android.content.Intent.FLAG_ACTIVITY_SINGLE_TOP;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.ActionBar;
import android.text.Editable;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.CheckBox;
import android.widget.EditText;
import com.janela.mobile.R;
import com.janela.mobile.ui.BaseActivity;
import com.janela.mobile.ui.TextWatcherAdapter;
import com.janela.mobile.util.ShareUtils;
import org.eclipse.egit.github.core.Gist;
/**
* Activity to share a text selection as a public or private Gist
*/
public class CreateGistActivity extends BaseActivity {
private EditText descriptionText;
private EditText nameText;
private EditText contentText;
private CheckBox publicCheckBox;
private MenuItem createItem;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.gist_create);
descriptionText = finder.find(R.id.et_gist_description);
nameText = finder.find(R.id.et_gist_name);
contentText = finder.find(R.id.et_gist_content);
publicCheckBox = finder.find(R.id.cb_public);
ActionBar actionBar = getSupportActionBar();
actionBar.setTitle(R.string.new_gist);
actionBar.setIcon(R.drawable.action_gist);
actionBar.setDisplayHomeAsUpEnabled(true);
String text = ShareUtils.getBody(getIntent());
if (!TextUtils.isEmpty(text))
contentText.setText(text);
String subject = ShareUtils.getSubject(getIntent());
if (!TextUtils.isEmpty(subject))
descriptionText.setText(subject);
contentText.addTextChangedListener(new TextWatcherAdapter() {
@Override
public void afterTextChanged(Editable s) {
updateCreateMenu(s);
}
});
updateCreateMenu();
}
private void updateCreateMenu() {
if (contentText != null)
updateCreateMenu(contentText.getText());
}
private void updateCreateMenu(CharSequence text) {
if (createItem != null)
createItem.setEnabled(!TextUtils.isEmpty(text));
}
@Override
public boolean onCreateOptionsMenu(Menu options) {
getMenuInflater().inflate(R.menu.gist_create, options);
createItem = options.findItem(R.id.m_apply);
updateCreateMenu();
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.m_apply:
createGist();
return true;
case android.R.id.home:
finish();
Intent intent = new Intent(this, GistsActivity.class);
intent.addFlags(FLAG_ACTIVITY_CLEAR_TOP | FLAG_ACTIVITY_SINGLE_TOP);
startActivity(intent);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private void createGist() {
final boolean isPublic = publicCheckBox.isChecked();
String enteredDescription = descriptionText.getText().toString().trim();
final String description = enteredDescription.length() > 0 ? enteredDescription
: getString(R.string.gist_description_hint);
String enteredName = nameText.getText().toString().trim();
final String name = enteredName.length() > 0 ? enteredName
: getString(R.string.gist_file_name_hint);
final String content = contentText.getText().toString();
new CreateGistTask(this, description, isPublic, name, content) {
@Override
protected void onSuccess(Gist gist) throws Exception {
super.onSuccess(gist);
startActivity(GistsViewActivity.createIntent(gist));
setResult(RESULT_OK);
finish();
}
}.create();
}
}
|
apache-2.0
|
Alacant/Rawr-RG
|
Rawr.Base/CustomControls/ExtendedToolTipLabel.cs
|
1292
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
namespace Rawr.CustomControls
{
public partial class ExtendedToolTipLabel : Label
{
private ToolTip _ToolTip;
private string _ToolTipText;
public ExtendedToolTipLabel()
{
InitializeComponent();
_ToolTip = new ToolTip();
this.MouseLeave += new EventHandler(ExtendedToolTipLabel_MouseLeave);
this.MouseHover += new EventHandler(ExtendedToolTipLabel_MouseHover);
}
void ExtendedToolTipLabel_MouseHover(object sender, EventArgs e)
{
if (!String.IsNullOrEmpty(_ToolTipText))
{
int x = PointToClient(MousePosition).X + 10;
_ToolTip.Show(_ToolTipText, this, new Point(x, -10));
}
}
public string ToolTipText
{
get { return _ToolTipText; }
set { _ToolTipText = value; }
}
void ExtendedToolTipLabel_MouseLeave(object sender, EventArgs e)
{
if (!String.IsNullOrEmpty(_ToolTipText))
{
_ToolTip.Hide(this);
}
}
}
}
|
apache-2.0
|
oehme/analysing-gradle-performance
|
my-app/src/test/java/org/gradle/test/performance/mediummonolithicjavaproject/p388/Test7764.java
|
2111
|
package org.gradle.test.performance.mediummonolithicjavaproject.p388;
import org.junit.Test;
import static org.junit.Assert.*;
public class Test7764 {
Production7764 objectUnderTest = new Production7764();
@Test
public void testProperty0() {
String value = "value";
objectUnderTest.setProperty0(value);
assertEquals(value, objectUnderTest.getProperty0());
}
@Test
public void testProperty1() {
String value = "value";
objectUnderTest.setProperty1(value);
assertEquals(value, objectUnderTest.getProperty1());
}
@Test
public void testProperty2() {
String value = "value";
objectUnderTest.setProperty2(value);
assertEquals(value, objectUnderTest.getProperty2());
}
@Test
public void testProperty3() {
String value = "value";
objectUnderTest.setProperty3(value);
assertEquals(value, objectUnderTest.getProperty3());
}
@Test
public void testProperty4() {
String value = "value";
objectUnderTest.setProperty4(value);
assertEquals(value, objectUnderTest.getProperty4());
}
@Test
public void testProperty5() {
String value = "value";
objectUnderTest.setProperty5(value);
assertEquals(value, objectUnderTest.getProperty5());
}
@Test
public void testProperty6() {
String value = "value";
objectUnderTest.setProperty6(value);
assertEquals(value, objectUnderTest.getProperty6());
}
@Test
public void testProperty7() {
String value = "value";
objectUnderTest.setProperty7(value);
assertEquals(value, objectUnderTest.getProperty7());
}
@Test
public void testProperty8() {
String value = "value";
objectUnderTest.setProperty8(value);
assertEquals(value, objectUnderTest.getProperty8());
}
@Test
public void testProperty9() {
String value = "value";
objectUnderTest.setProperty9(value);
assertEquals(value, objectUnderTest.getProperty9());
}
}
|
apache-2.0
|
Hexworks/zircon
|
docs/2020.2.0-RELEASE-KOTLIN/zircon.core/zircon.core/org.hexworks.zircon.api.uievent/-key-code/-d-e-a-d_-m-a-c-r-o-n/is-unknown.html
|
3693
|
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1" charset="UTF-8">
<title>isUnknown</title>
<link href="../../../../images/logo-icon.svg" rel="icon" type="image/svg">
<script>var pathToRoot = "../../../../";</script>
<script type="text/javascript" src="../../../../scripts/sourceset_dependencies.js" async="async"></script>
<link href="../../../../styles/style.css" rel="Stylesheet">
<link href="../../../../styles/logo-styles.css" rel="Stylesheet">
<link href="../../../../styles/jetbrains-mono.css" rel="Stylesheet">
<link href="../../../../styles/main.css" rel="Stylesheet">
<script type="text/javascript" src="../../../../scripts/clipboard.js" async="async"></script>
<script type="text/javascript" src="../../../../scripts/navigation-loader.js" async="async"></script>
<script type="text/javascript" src="../../../../scripts/platform-content-handler.js" async="async"></script>
<script type="text/javascript" src="../../../../scripts/main.js" async="async"></script>
</head>
<body>
<div id="container">
<div id="leftColumn">
<div id="logo"></div>
<div id="paneSearch"></div>
<div id="sideMenu"></div>
</div>
<div id="main">
<div id="leftToggler"><span class="icon-toggler"></span></div>
<script type="text/javascript" src="../../../../scripts/pages.js"></script>
<script type="text/javascript" src="../../../../scripts/main.js"></script>
<div class="main-content" id="content" pageIds="org.hexworks.zircon.api.uievent/KeyCode.DEAD_MACRON/isUnknown/#/PointingToDeclaration//-828656838">
<div class="navigation-wrapper" id="navigation-wrapper">
<div class="breadcrumbs"><a href="../../../index.html">zircon.core</a>/<a href="../../index.html">org.hexworks.zircon.api.uievent</a>/<a href="../index.html">KeyCode</a>/<a href="index.html">DEAD_MACRON</a>/<a href="is-unknown.html">isUnknown</a></div>
<div class="pull-right d-flex">
<div class="filter-section" id="filter-section"><button class="platform-tag platform-selector common-like" data-active="" data-filter=":zircon.core:dokkaHtml/commonMain">common</button></div>
<div id="searchBar"></div>
</div>
</div>
<div class="cover ">
<h1 class="cover"><span>is</span><wbr></wbr><span>Unknown</span></h1>
</div>
<div class="divergent-group" data-filterable-current=":zircon.core:dokkaHtml/commonMain" data-filterable-set=":zircon.core:dokkaHtml/commonMain"><div class="with-platform-tags"><span class="pull-right"></span></div>
<div>
<div class="platform-hinted " data-platform-hinted="data-platform-hinted"><div class="content sourceset-depenent-content" data-active="" data-togglable=":zircon.core:dokkaHtml/commonMain"><div class="symbol monospace">val <a href="is-unknown.html">isUnknown</a>: <a href="https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-boolean/index.html">Boolean</a><span class="top-right-position"><span class="copy-icon"></span><div class="copy-popup-wrapper popup-to-left"><span class="copy-popup-icon"></span><span>Content copied to clipboard</span></div></span></div></div></div>
</div>
<p class="paragraph">Tells whether this is the <a href="../index.html">UNKNOWN</a>.</p></div>
</div>
<div class="footer"><span class="go-to-top-icon"><a href="#content"></a></span><span>© 2020 Copyright</span><span class="pull-right"><span>Sponsored and developed by dokka</span><a href="https://github.com/Kotlin/dokka"><span class="padded-icon"></span></a></span></div>
</div>
</div>
</body>
</html>
|
apache-2.0
|
dlp-keynote/LCR2000-nHD-PEM
|
GUI/Temperature.h
|
2792
|
/*
* Copyright (C) {2017} Keynote Photonics - www.keynotephotonics.com
*
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Redistribution and use of source is not permitted with out
* written authorizitaion.
*
* 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 Keynote Photonics 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.
*
*/
#ifndef TEMPERATURE_H
#define TEMPERATURE_H
#define Temp1 0
#define Temp2 10
#define Temp3 15
#define Temp4 20
#define Temp5 25
#define Temp6 30
#define Temp7 35
#define Temp8 40
#define Temp9 45
#define TempA 50
#define TempB 55
#define TempC 60
#define TempD 65
#define TempE 70
#define TempF 80
#define TempG 90
#define TempH 100
#define TempI 125
#define T_DAC_0 1023
#define T_DAC_1 645
#define T_DAC_2 623
#define T_DAC_3 597
#define T_DAC_4 568
#define T_DAC_5 535
#define T_DAC_6 500
#define T_DAC_7 464
#define T_DAC_8 426
#define T_DAC_9 388
#define T_DAC_A 350
#define T_DAC_B 314
#define T_DAC_C 280
#define T_DAC_D 248
#define T_DAC_E 193
#define T_DAC_F 148
#define T_DAC_G 113
#define T_DAC_H 58
#define T_Scale1 64.5
#define T_Scale2 41.53
#define T_Scale3 29.85
#define T_Scale4 22.72
#define T_Scale5 17.833
#define T_Scale6 14.28
#define T_Scale7 11.6
#define T_Scale8 9.47
#define T_Scale9 7.76
#define T_ScaleA 6.36
#define T_ScaleB 5.23
#define T_ScaleC 4.30
#define T_ScaleD 3.54
#define T_ScaleE 2.41
#define T_ScaleF 1.64
#define T_ScaleG 1.13
#define T_ScaleH 0.464
#endif // TEMPERATURE_H
|
apache-2.0
|
spindance/serviced-precomp
|
volume/rsync/rsync_unit_test.go
|
2090
|
// Copyright 2015 The Serviced 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.
// +build unit
package rsync
import (
"fmt"
"testing"
"github.com/control-center/serviced/volume"
"github.com/stretchr/testify/assert"
)
type ParseDFTest struct {
label string
inlabel string
inbytes []byte
out []volume.Usage
outmsg string
err error
errmsg string
}
var parsedftests = []ParseDFTest{
{
label: "output from df",
inlabel: "volumelabel",
inbytes: []byte(`Filesystem 1B-blocks Used Avail
/dev/sdb1 1901233012736 172685119488 1631947202560`),
out: []volume.Usage{
{Label: "volumelabel on /dev/sdb1", Type: "Total Bytes", Value: 1901233012736},
{Label: "volumelabel on /dev/sdb1", Type: "Used Bytes", Value: 172685119488},
{Label: "volumelabel on /dev/sdb1", Type: "Available Bytes", Value: 1631947202560},
},
outmsg: "output did not match expectation",
err: nil,
errmsg: "error was not nil",
},
{
label: "empty input handled gracefully",
inlabel: "volumelabel",
inbytes: []byte{},
out: []volume.Usage{},
outmsg: "output did not match expectation",
err: nil,
errmsg: "error was not nil",
},
}
func TestStub(t *testing.T) {
assert.True(t, true, "Test environment set up properly.")
}
func TestParseDF(t *testing.T) {
for _, tc := range parsedftests {
result, err := parseDFCommand(tc.inlabel, tc.inbytes)
assert.Equal(t, err, tc.err, fmt.Sprintf("%s: %s", tc.label, tc.errmsg))
assert.Equal(t, result, tc.out, fmt.Sprintf("%s: %s", tc.label, tc.outmsg))
}
}
|
apache-2.0
|
litsec/eidas-opensaml
|
docs/javadoc/opensaml4/2.0.0/se/litsec/eidas/opensaml/config/package-tree.html
|
6449
|
<!DOCTYPE HTML>
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (11.0.1) on Mon Jan 18 16:59:34 CET 2021 -->
<title>se.litsec.eidas.opensaml.config Class Hierarchy (eIDAS extension for OpenSAML 4.x - 2.0.0)</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta name="dc.created" content="2021-01-18">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">
<link rel="stylesheet" type="text/css" href="../../../../../jquery/jquery-ui.css" title="Style">
<script type="text/javascript" src="../../../../../script.js"></script>
<script type="text/javascript" src="../../../../../jquery/jszip/dist/jszip.min.js"></script>
<script type="text/javascript" src="../../../../../jquery/jszip-utils/dist/jszip-utils.min.js"></script>
<!--[if IE]>
<script type="text/javascript" src="../../../../../jquery/jszip-utils/dist/jszip-utils-ie.min.js"></script>
<![endif]-->
<script type="text/javascript" src="../../../../../jquery/jquery-3.3.1.js"></script>
<script type="text/javascript" src="../../../../../jquery/jquery-migrate-3.0.1.js"></script>
<script type="text/javascript" src="../../../../../jquery/jquery-ui.js"></script>
</head>
<body>
<script type="text/javascript"><!--
try {
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="se.litsec.eidas.opensaml.config Class Hierarchy (eIDAS extension for OpenSAML 4.x - 2.0.0)";
}
}
catch(err) {
}
//-->
var pathtoroot = "../../../../../";
var useModuleDirectories = true;
loadScripts(document, 'script');</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<header role="banner">
<nav role="navigation">
<div class="fixedNav">
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a id="navbar.top">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div>
<a id="navbar.top.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../index.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li>Class</li>
<li>Use</li>
<li class="navBarCell1Rev">Tree</li>
<li><a href="../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../../allclasses.html">All Classes</a></li>
</ul>
<ul class="navListSearch">
<li><label for="search">SEARCH:</label>
<input type="text" id="search" value="search" disabled="disabled">
<input type="reset" id="reset" value="reset" disabled="disabled">
</li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
</div>
<a id="skip.navbar.top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
</div>
<div class="navPadding"> </div>
<script type="text/javascript"><!--
$('.navPadding').css('padding-top', $('.fixedNav').css("height"));
//-->
</script>
</nav>
</header>
<main role="main">
<div class="header">
<h1 class="title">Hierarchy For Package se.litsec.eidas.opensaml.config</h1>
<span class="packageHierarchyLabel">Package Hierarchies:</span>
<ul class="horizontal">
<li><a href="../../../../../overview-tree.html">All Packages</a></li>
</ul>
</div>
<div class="contentContainer">
<section role="region">
<h2 title="Class Hierarchy">Class Hierarchy</h2>
<ul>
<li class="circle">java.lang.<a href="https://docs.oracle.com/en/java/javase/11/docs/api/java/lang/Object.html?is-external=true" title="class or interface in java.lang" class="externalLink"><span class="typeNameLink">Object</span></a>
<ul>
<li class="circle">org.opensaml.core.xml.config.<a href="https://build.shibboleth.net/nexus/content/sites/site/java-opensaml/4.0.1/apidocs/org/opensaml/core/xml/config/AbstractXMLObjectProviderInitializer.html?is-external=true" title="class or interface in org.opensaml.core.xml.config" class="externalLink"><span class="typeNameLink">AbstractXMLObjectProviderInitializer</span></a> (implements org.opensaml.core.config.<a href="https://build.shibboleth.net/nexus/content/sites/site/java-opensaml/4.0.1/apidocs/org/opensaml/core/config/Initializer.html?is-external=true" title="class or interface in org.opensaml.core.config" class="externalLink">Initializer</a>)
<ul>
<li class="circle">se.litsec.eidas.opensaml.config.<a href="XMLObjectProviderInitializer.html" title="class in se.litsec.eidas.opensaml.config"><span class="typeNameLink">XMLObjectProviderInitializer</span></a></li>
</ul>
</li>
</ul>
</li>
</ul>
</section>
</div>
</main>
<footer role="contentinfo">
<nav role="navigation">
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a id="navbar.bottom">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div>
<a id="navbar.bottom.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../index.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li>Class</li>
<li>Use</li>
<li class="navBarCell1Rev">Tree</li>
<li><a href="../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../../allclasses.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
</div>
<a id="skip.navbar.bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
</nav>
<p class="legalCopy"><small>Copyright © 2021 <a href="http://www.litsec.se">Litsec AB</a>. All rights reserved.</small></p>
</footer>
</body>
</html>
|
apache-2.0
|
krook/nginx-php-container-cluster
|
scripts/docker/code-php-cli/Dockerfile
|
1320
|
ARG PHP_CLI_VERSION=latest
ARG REGISTRY_NAMESPACE=orod
FROM registry.ng.bluemix.net/${REGISTRY_NAMESPACE}/config-php-cli:${PHP_CLI_VERSION}
ARG DRUSH_VERSION
RUN apt-get update -y && apt-get upgrade -y
# Worker name and index (TODO: where to set this?)
ENV WORKER_NAME="send-emails" \
WORKER_INDEX="1"
# Register the COMPOSER_HOME environment variable.
ENV COMPOSER_HOME=/root/.composer
# Add global binary directory to PATH.
ENV PATH /root/.composer/vendor/bin:$PATH
# Allow Composer to be run as root.
ENV COMPOSER_ALLOW_SUPERUSER=1
RUN curl -sS https://getcomposer.org/installer | \
php -- --install-dir=/usr/bin/ --filename=composer
COPY tmp/composer.json ./
# COPY tmp/code/composer.lock ./
RUN composer install --no-scripts --no-autoloader
COPY . ./
RUN composer global require drush/drush:8.x
ADD tmp/composer.json /root/drush/
ADD tmp/composer.lock /root/drush/
# Add Drush specific scripts
ADD tmp/drush/ /root/drush/
RUN chmod +x /root/drush/*.sh
# Add database connection info
ADD tmp/sites/default/ /root/drush/sites/default/
# Prep a backup directory
RUN mkdir /root/backups/
WORKDIR /root/drush/
# Change this to be a Drush command?
# This container is more here to just exec into rather than run something headless
CMD php $WORKER_NAME/$WORKER_NAME.php WORKER_INDEX=$WORKER_INDEX
|
apache-2.0
|
McLeodMoores/starling
|
projects/engine/src/main/java/com/opengamma/engine/fudgemsg/ValuePropertiesFudgeBuilder.java
|
4577
|
/**
* Copyright (C) 2009 - present by OpenGamma Inc. and the OpenGamma group of companies
*
* Please see distribution for license.
*/
package com.opengamma.engine.fudgemsg;
import java.util.ArrayList;
import java.util.List;
import org.fudgemsg.FudgeField;
import org.fudgemsg.FudgeMsg;
import org.fudgemsg.MutableFudgeMsg;
import org.fudgemsg.mapping.FudgeBuilder;
import org.fudgemsg.mapping.FudgeDeserializer;
import org.fudgemsg.mapping.FudgeSerializer;
import org.fudgemsg.mapping.GenericFudgeBuilderFor;
import org.fudgemsg.wire.types.FudgeWireType;
import com.opengamma.engine.value.ValueProperties;
/**
* Fudge message builder for {@link ValueProperties}. Messages can take the form:
* <ul>
* <li>The empty property set is an empty message.
* <li>A simple property set has a field named {@code with} that contains a sub-message. This in turn contains a field per property - the name of
* the field is the name of the property. This is either a:
* <ul>
* <li>Simple string value
* <li>An indicator indicating a wild-card property value
* <li>A sub-message containing un-named fields with each possible value of the property.
* </ul>
* If the property is optional, the sub-message form is used with a field named {@code optional}. If the field is an optional wild-card the sub-message
* form is used which contains only the {@code optional} field.
* <li>The infinite property set ({@link ValueProperties#all}) has a field named {@code without} that contains an empty sub-message.
* <li>The near-infinite property set has a field named {@code without} that contains a field for each of absent entries, the string value of each field
* is the property name.
* </ul>
*/
@GenericFudgeBuilderFor(ValueProperties.class)
public class ValuePropertiesFudgeBuilder implements FudgeBuilder<ValueProperties> {
// TODO: The message format described above is not particularly efficient or convenient, but kept for compatibility
/**
* Field name for the sub-message containing property values.
*/
public static final String WITH_FIELD = "with";
/**
* Field name for the sub-message representing the infinite or near-infinite property set.
*/
public static final String WITHOUT_FIELD = "without";
/**
* Field name for the 'optional' flag.
*/
public static final String OPTIONAL_FIELD = "optional";
@Override
public MutableFudgeMsg buildMessage(final FudgeSerializer serializer, final ValueProperties object) {
final MutableFudgeMsg message = serializer.newMessage();
object.toFudgeMsg(message);
return message;
}
@Override
public ValueProperties buildObject(final FudgeDeserializer deserializer, final FudgeMsg message) {
if (message.isEmpty()) {
return ValueProperties.none();
}
FudgeMsg subMsg = message.getMessage(WITHOUT_FIELD);
if (subMsg != null) {
if (subMsg.isEmpty()) {
// Infinite
return ValueProperties.all();
}
// Near-infinite
final ValueProperties.Builder builder = ValueProperties.all().copy();
for (final FudgeField field : subMsg) {
if (field.getType().getTypeId() == FudgeWireType.STRING_TYPE_ID) {
builder.withoutAny((String) field.getValue());
}
}
return builder.get();
}
subMsg = message.getMessage(WITH_FIELD);
if (subMsg == null) {
return ValueProperties.none();
}
final ValueProperties.Builder builder = ValueProperties.builder();
for (final FudgeField field : subMsg) {
final String propertyName = field.getName();
switch (field.getType().getTypeId()) {
case FudgeWireType.INDICATOR_TYPE_ID:
builder.withAny(propertyName);
break;
case FudgeWireType.STRING_TYPE_ID:
builder.with(propertyName, (String) field.getValue());
break;
case FudgeWireType.SUB_MESSAGE_TYPE_ID: {
final FudgeMsg subMsg2 = (FudgeMsg) field.getValue();
final List<String> values = new ArrayList<>(subMsg2.getNumFields());
for (final FudgeField field2 : subMsg2) {
switch (field2.getType().getTypeId()) {
case FudgeWireType.INDICATOR_TYPE_ID:
builder.withOptional(propertyName);
break;
case FudgeWireType.STRING_TYPE_ID:
values.add((String) field2.getValue());
break;
}
}
if (!values.isEmpty()) {
builder.with(propertyName, values);
}
break;
}
}
}
return builder.get();
}
}
|
apache-2.0
|
AdaptiveMe/adaptive-arp-javascript
|
adaptive-arp-js/src_units/ServiceResultCallback.d.ts
|
5079
|
/// <reference path="BaseCallback.d.ts" />
/// <reference path="CommonUtil.d.ts" />
/// <reference path="IServiceResultCallback.d.ts" />
/// <reference path="IServiceResultCallbackError.d.ts" />
/// <reference path="IServiceResultCallbackWarning.d.ts" />
/// <reference path="ServiceResponse.d.ts" />
/**
--| ADAPTIVE RUNTIME PLATFORM |----------------------------------------------------------------------------------------
(C) Copyright 2013-2015 Carlos Lozano Diez t/a Adaptive.me <http://adaptive.me>.
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 appli-
-cable 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.
Original author:
* Carlos Lozano Diez
<http://github.com/carloslozano>
<http://twitter.com/adaptivecoder>
<mailto:[email protected]>
Contributors:
* Ferran Vila Conesa
<http://github.com/fnva>
<http://twitter.com/ferran_vila>
<mailto:[email protected]>
* See source code files for contributors.
Release:
* @version v2.2.15
-------------------------------------------| aut inveniam viam aut faciam |--------------------------------------------
*/
declare module Adaptive {
/**
Interface for Managing the Services operations
Auto-generated implementation of IServiceResultCallback specification.
*/
/**
@property {Adaptive.Dictionary} registeredServiceResultCallback
@member Adaptive
@private
ServiceResultCallback control dictionary.
*/
var registeredServiceResultCallback: Dictionary<IServiceResultCallback>;
/**
@method
@private
@member Adaptive
@param {number} id
@param {Adaptive.IServiceResultCallbackError} error
*/
function handleServiceResultCallbackError(id: number, error: IServiceResultCallbackError): void;
/**
@method
@private
@member Adaptive
@param {number} id
@param {Adaptive.ServiceResponse} response
*/
function handleServiceResultCallbackResult(id: number, response: ServiceResponse): void;
/**
@method
@private
@member Adaptive
@param {number} id
@param {Adaptive.ServiceResponse} response
@param {Adaptive.IServiceResultCallbackWarning} warning
*/
function handleServiceResultCallbackWarning(id: number, response: ServiceResponse, warning: IServiceResultCallbackWarning): void;
/**
@class Adaptive.ServiceResultCallback
@extends Adaptive.BaseCallback
*/
class ServiceResultCallback extends BaseCallback implements IServiceResultCallback {
/**
@private
@property
*/
onErrorFunction: (error: IServiceResultCallbackError) => void;
/**
@private
@property
*/
onResultFunction: (response: ServiceResponse) => void;
/**
@private
@property
*/
onWarningFunction: (response: ServiceResponse, warning: IServiceResultCallbackWarning) => void;
/**
@method constructor
Constructor with anonymous handler functions for callback.
@param {Function} onErrorFunction Function receiving parameters of type: Adaptive.IServiceResultCallbackError
@param {Function} onResultFunction Function receiving parameters of type: Adaptive.ServiceResponse
@param {Function} onWarningFunction Function receiving parameters of type: Adaptive.ServiceResponse, Adaptive.IServiceResultCallbackWarning
*/
constructor(onErrorFunction: (error: IServiceResultCallbackError) => void, onResultFunction: (response: ServiceResponse) => void, onWarningFunction: (response: ServiceResponse, warning: IServiceResultCallbackWarning) => void);
/**
@method
This method is called on Error
@param {Adaptive.IServiceResultCallbackError} error error returned by the platform
@since v2.0
*/
onError(error: IServiceResultCallbackError): void;
/**
@method
This method is called on Result
@param {Adaptive.ServiceResponse} response response data
@since v2.0
*/
onResult(response: ServiceResponse): void;
/**
@method
This method is called on Warning
@param {Adaptive.ServiceResponse} response response data
@param {Adaptive.IServiceResultCallbackWarning} warning warning returned by the platform
@since v2.0
*/
onWarning(response: ServiceResponse, warning: IServiceResultCallbackWarning): void;
}
}
|
apache-2.0
|
fernandoj92/mvca-parkinson
|
voltric-ltm-analysis/src/main/java/voltric/io/data/arff/ArffFolderReader.java
|
110
|
package voltric.io.data.arff;
/**
* Created by Fernando on 2/15/2017.
*/
public class ArffFolderReader {
}
|
apache-2.0
|
gravitee-io/gravitee-management-webui
|
src/management/api/proxy/backend/endpoint/group.controller.ts
|
5282
|
/*
* Copyright (C) 2015 The Gravitee team (http://gravitee.io)
*
* 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 { StateParams, StateService } from '@uirouter/core';
import _ = require('lodash');
import { ApiService } from '../../../../../services/api.service';
import NotificationService from '../../../../../services/notification.service';
class ApiEndpointGroupController {
private api: any;
private group: any;
private initialGroups: any;
private discovery: any;
private creation = false;
private serviceDiscoveryJsonSchemaForm: string[];
private types: any[];
private serviceDiscoveryJsonSchema: any;
private serviceDiscoveryConfigurationForm: any;
constructor(
private ApiService: ApiService,
private NotificationService: NotificationService,
private ServiceDiscoveryService,
private $scope,
private $rootScope: ng.IRootScopeService,
private resolvedServicesDiscovery,
private $state: StateService,
private $stateParams: StateParams,
private $timeout,
) {
'ngInject';
}
$onInit() {
this.api = this.$scope.$parent.apiCtrl.api;
this.group = _.find(this.api.proxy.groups, { name: this.$stateParams.groupName });
this.$scope.duplicateEndpointNames = false;
// Creation mode
if (!this.group) {
this.group = {};
this.creation = true;
}
this.serviceDiscoveryJsonSchemaForm = ['*'];
this.types = this.resolvedServicesDiscovery.data;
this.discovery = this.group.services && this.group.services.discovery;
this.discovery = this.discovery || { enabled: false, configuration: {} };
this.initialGroups = _.cloneDeep(this.api.proxy.groups);
this.$scope.lbs = [
{
name: 'Round-Robin',
value: 'ROUND_ROBIN',
},
{
name: 'Random',
value: 'RANDOM',
},
{
name: 'Weighted Round-Robin',
value: 'WEIGHTED_ROUND_ROBIN',
},
{
name: 'Weighted Random',
value: 'WEIGHTED_RANDOM',
},
];
if (!this.group.load_balancing) {
this.group.load_balancing = {
type: this.$scope.lbs[0].value,
};
}
this.retrievePluginSchema();
}
onTypeChange() {
this.discovery.configuration = {};
this.retrievePluginSchema();
}
retrievePluginSchema() {
if (this.discovery.provider !== undefined) {
this.ServiceDiscoveryService.getSchema(this.discovery.provider).then(
({ data }) => {
this.serviceDiscoveryJsonSchema = data;
},
(response) => {
if (response.status === 404) {
this.serviceDiscoveryJsonSchema = {};
return {
schema: {},
};
} else {
// todo manage errors
this.NotificationService.showError('Unexpected error while loading service discovery schema for ' + this.discovery.provider);
}
},
);
}
}
update(api) {
// include discovery service
this.group.services = {
discovery: this.discovery,
};
if (!_.includes(api.proxy.groups, this.group)) {
if (!api.proxy.groups) {
api.proxy.groups = [this.group];
} else {
api.proxy.groups.push(this.group);
}
}
if (this.group.ssl.trustAll) {
delete this.group.ssl.trustStore;
}
if (this.group.ssl.trustStore && (!this.group.ssl.trustStore.type || this.group.ssl.trustStore.type === '')) {
delete this.group.ssl.trustStore;
}
if (this.group.ssl.keyStore && (!this.group.ssl.keyStore.type || this.group.ssl.keyStore.type === '')) {
delete this.group.ssl.keyStore;
}
if (this.group.headers.length > 0) {
this.group.headers = _.mapValues(_.keyBy(this.group.headers, 'name'), 'value');
} else {
delete this.group.headers;
}
this.ApiService.update(api).then((updatedApi) => {
this.api = updatedApi.data;
this.api.etag = updatedApi.headers('etag');
this.onApiUpdate();
this.initialGroups = _.cloneDeep(api.proxy.groups);
});
}
onApiUpdate() {
this.$rootScope.$broadcast('apiChangeSuccess', { api: this.api });
this.NotificationService.show('Group configuration saved');
this.$state.go('management.apis.detail.proxy.endpoints');
}
reset() {
this.$scope.duplicateEndpointNames = false;
this.$state.reload();
}
backToEndpointsConfiguration() {
this.reset();
this.api.proxy.groups = _.cloneDeep(this.initialGroups);
this.$state.go('management.apis.detail.proxy.endpoints');
}
checkEndpointNameUniqueness() {
this.$scope.duplicateEndpointNames = this.ApiService.isEndpointNameAlreadyUsed(this.api, this.group.name, this.creation);
}
}
export default ApiEndpointGroupController;
|
apache-2.0
|
droolsjbpm/optaplanner
|
optaplanner-core/src/main/java/org/optaplanner/core/impl/solver/scope/SolverScope.java
|
9712
|
/*
* Copyright 2020 Red Hat, Inc. and/or its affiliates.
*
* 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.optaplanner.core.impl.solver.scope;
import java.util.List;
import java.util.Random;
import java.util.concurrent.Semaphore;
import org.optaplanner.core.api.domain.solution.PlanningSolution;
import org.optaplanner.core.api.score.Score;
import org.optaplanner.core.api.solver.Solver;
import org.optaplanner.core.impl.domain.solution.descriptor.SolutionDescriptor;
import org.optaplanner.core.impl.phase.scope.AbstractPhaseScope;
import org.optaplanner.core.impl.score.definition.ScoreDefinition;
import org.optaplanner.core.impl.score.director.InnerScoreDirector;
import org.optaplanner.core.impl.solver.termination.Termination;
import org.optaplanner.core.impl.solver.thread.ChildThreadType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @param <Solution_> the solution type, the class with the {@link PlanningSolution} annotation
*/
public class SolverScope<Solution_> {
protected final transient Logger logger = LoggerFactory.getLogger(getClass());
protected int startingSolverCount;
protected Random workingRandom;
protected InnerScoreDirector<Solution_, ?> scoreDirector;
/**
* Used for capping CPU power usage in multithreaded scenarios.
*/
protected Semaphore runnableThreadSemaphore = null;
protected volatile Long startingSystemTimeMillis;
protected volatile Long endingSystemTimeMillis;
protected long childThreadsScoreCalculationCount = 0;
protected Score startingInitializedScore;
protected volatile Solution_ bestSolution;
protected volatile Score bestScore;
protected Long bestSolutionTimeMillis;
// ************************************************************************
// Constructors and simple getters/setters
// ************************************************************************
public int getStartingSolverCount() {
return startingSolverCount;
}
public void setStartingSolverCount(int startingSolverCount) {
this.startingSolverCount = startingSolverCount;
}
public Random getWorkingRandom() {
return workingRandom;
}
public void setWorkingRandom(Random workingRandom) {
this.workingRandom = workingRandom;
}
public InnerScoreDirector<Solution_, ?> getScoreDirector() {
return scoreDirector;
}
public void setScoreDirector(InnerScoreDirector<Solution_, ?> scoreDirector) {
this.scoreDirector = scoreDirector;
}
public void setRunnableThreadSemaphore(Semaphore runnableThreadSemaphore) {
this.runnableThreadSemaphore = runnableThreadSemaphore;
}
public Long getStartingSystemTimeMillis() {
return startingSystemTimeMillis;
}
public Long getEndingSystemTimeMillis() {
return endingSystemTimeMillis;
}
public SolutionDescriptor<Solution_> getSolutionDescriptor() {
return scoreDirector.getSolutionDescriptor();
}
public ScoreDefinition getScoreDefinition() {
return scoreDirector.getScoreDefinition();
}
public Solution_ getWorkingSolution() {
return scoreDirector.getWorkingSolution();
}
public int getWorkingEntityCount() {
return scoreDirector.getWorkingEntityCount();
}
public List<Object> getWorkingEntityList() {
return scoreDirector.getWorkingEntityList();
}
public int getWorkingValueCount() {
return scoreDirector.getWorkingValueCount();
}
public Score calculateScore() {
return scoreDirector.calculateScore();
}
public void assertScoreFromScratch(Solution_ solution) {
scoreDirector.getScoreDirectorFactory().assertScoreFromScratch(solution);
}
public Score getStartingInitializedScore() {
return startingInitializedScore;
}
public void setStartingInitializedScore(Score startingInitializedScore) {
this.startingInitializedScore = startingInitializedScore;
}
public void addChildThreadsScoreCalculationCount(long addition) {
childThreadsScoreCalculationCount += addition;
}
public long getScoreCalculationCount() {
return scoreDirector.getCalculationCount() + childThreadsScoreCalculationCount;
}
public Solution_ getBestSolution() {
return bestSolution;
}
/**
* The {@link PlanningSolution best solution} must never be the same instance
* as the {@link PlanningSolution working solution}, it should be a (un)changed clone.
*
* @param bestSolution never null
*/
public void setBestSolution(Solution_ bestSolution) {
this.bestSolution = bestSolution;
}
public Score getBestScore() {
return bestScore;
}
public void setBestScore(Score bestScore) {
this.bestScore = bestScore;
}
public Long getBestSolutionTimeMillis() {
return bestSolutionTimeMillis;
}
public void setBestSolutionTimeMillis(Long bestSolutionTimeMillis) {
this.bestSolutionTimeMillis = bestSolutionTimeMillis;
}
// ************************************************************************
// Calculated methods
// ************************************************************************
public void startingNow() {
startingSystemTimeMillis = System.currentTimeMillis();
endingSystemTimeMillis = null;
}
public Long getBestSolutionTimeMillisSpent() {
return bestSolutionTimeMillis - startingSystemTimeMillis;
}
public void endingNow() {
endingSystemTimeMillis = System.currentTimeMillis();
}
public boolean isBestSolutionInitialized() {
return bestScore.isSolutionInitialized();
}
public long calculateTimeMillisSpentUpToNow() {
long now = System.currentTimeMillis();
return now - startingSystemTimeMillis;
}
public long getTimeMillisSpent() {
return endingSystemTimeMillis - startingSystemTimeMillis;
}
/**
* @return at least 0, per second
*/
public long getScoreCalculationSpeed() {
long timeMillisSpent = getTimeMillisSpent();
// Avoid divide by zero exception on a fast CPU
return getScoreCalculationCount() * 1000L / (timeMillisSpent == 0L ? 1L : timeMillisSpent);
}
public void setWorkingSolutionFromBestSolution() {
// The workingSolution must never be the same instance as the bestSolution.
scoreDirector.setWorkingSolution(scoreDirector.cloneSolution(bestSolution));
}
public SolverScope<Solution_> createChildThreadSolverScope(ChildThreadType childThreadType) {
SolverScope<Solution_> childThreadSolverScope = new SolverScope<>();
childThreadSolverScope.startingSolverCount = startingSolverCount;
// TODO FIXME use RandomFactory
// Experiments show that this trick to attain reproducibility doesn't break uniform distribution
childThreadSolverScope.workingRandom = new Random(workingRandom.nextLong());
childThreadSolverScope.scoreDirector = scoreDirector.createChildThreadScoreDirector(childThreadType);
childThreadSolverScope.startingSystemTimeMillis = startingSystemTimeMillis;
childThreadSolverScope.endingSystemTimeMillis = null;
childThreadSolverScope.startingInitializedScore = null;
childThreadSolverScope.bestSolution = null;
childThreadSolverScope.bestScore = null;
childThreadSolverScope.bestSolutionTimeMillis = null;
return childThreadSolverScope;
}
public void initializeYielding() {
if (runnableThreadSemaphore != null) {
try {
runnableThreadSemaphore.acquire();
} catch (InterruptedException e) {
// TODO it will take a while before the BasicPlumbingTermination is called
// The BasicPlumbingTermination will terminate the solver.
Thread.currentThread().interrupt();
}
}
}
/**
* Similar to {@link Thread#yield()}, but allows capping the number of active solver threads
* at less than the CPU processor count, so other threads (for example servlet threads that handle REST calls)
* and other processes (such as SSH) have access to uncontested CPUs and don't suffer any latency.
* <p>
* Needs to be called <b>before</b> {@link Termination#isPhaseTerminated(AbstractPhaseScope)},
* so the decision to start a new iteration is after any yield waiting time has been consumed
* (so {@link Solver#terminateEarly()} reacts immediately).
*/
public void checkYielding() {
if (runnableThreadSemaphore != null) {
runnableThreadSemaphore.release();
try {
runnableThreadSemaphore.acquire();
} catch (InterruptedException e) {
// The BasicPlumbingTermination will terminate the solver.
Thread.currentThread().interrupt();
}
}
}
public void destroyYielding() {
if (runnableThreadSemaphore != null) {
runnableThreadSemaphore.release();
}
}
}
|
apache-2.0
|
omacarena/novaburst.flowcolab
|
app/modules/account/account.service.client/src/main/org/flowcolab/account/service/client/dto/account/AccountCreateRequest.java
|
2219
|
package org.flowcolab.account.service.client.dto.account;
import org.flowcolab.account.service.client.dto.person.PersonCreateRequest;
import org.hibernate.validator.constraints.Email;
import org.hibernate.validator.constraints.NotEmpty;
import javax.validation.constraints.AssertTrue;
import javax.validation.constraints.NotNull;
public class AccountCreateRequest {
@NotNull
@NotEmpty
private String username;
@NotNull
@NotEmpty
private String password;
@NotNull
@NotEmpty
@Email
private String email;
@AssertTrue
private Boolean isTermsAccepted;
@NotNull
private PersonCreateRequest person;
public AccountCreateRequest() {
}
public AccountCreateRequest(String username,
String password,
String email,
Boolean isTermsAccepted,
PersonCreateRequest person) {
this.username = username;
this.password = password;
this.email = email;
this.isTermsAccepted = isTermsAccepted;
this.person = person;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public Boolean getIsTermsAccepted() {
return isTermsAccepted;
}
public void setIsTermsAccepted(Boolean isTermsAccepted) {
this.isTermsAccepted = isTermsAccepted;
}
public PersonCreateRequest getPerson() {
return person;
}
public void setPerson(PersonCreateRequest person) {
this.person = person;
}
@Override
public String toString() {
return "AccountCreateRequest{" +
"username='" + username + '\'' +
", email='" + email + '\'' +
", isTermsAccepted=" + isTermsAccepted +
'}';
}
}
|
apache-2.0
|
mdoering/backbone
|
life/Plantae/Magnoliophyta/Magnoliopsida/Boraginales/Boraginaceae/Cordia/Cordia warneckei/README.md
|
195
|
# Cordia warneckei Gürke ex Baker & C.H.Wright SPECIES
#### Status
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null
|
apache-2.0
|
charles-cooper/idylfin
|
src/com/opengamma/analytics/financial/credit/creditdefaultswap/pricing/PresentValueLegacyCreditDefaultSwap.java
|
24342
|
/**
* Copyright (C) 2012 - present by OpenGamma Inc. and the OpenGamma group of companies
*
* Please see distribution for license.
*/
package com.opengamma.analytics.financial.credit.creditdefaultswap.pricing;
import javax.time.calendar.ZonedDateTime;
import com.opengamma.analytics.financial.credit.BuySellProtection;
import com.opengamma.analytics.financial.credit.PriceType;
import com.opengamma.analytics.financial.credit.cds.ISDACurve;
import com.opengamma.analytics.financial.credit.creditdefaultswap.definition.LegacyCreditDefaultSwapDefinition;
import com.opengamma.analytics.financial.credit.hazardratemodel.HazardRateCurve;
import com.opengamma.analytics.financial.credit.schedulegeneration.GenerateCreditDefaultSwapIntegrationSchedule;
import com.opengamma.analytics.financial.credit.schedulegeneration.GenerateCreditDefaultSwapPremiumLegSchedule;
import com.opengamma.analytics.util.time.TimeCalculator;
import com.opengamma.financial.convention.daycount.DayCount;
import com.opengamma.financial.convention.daycount.DayCountFactory;
import com.opengamma.util.ArgumentChecker;
/**
* Class containing methods for the valuation of a vanilla Legacy CDS
*/
public class PresentValueLegacyCreditDefaultSwap {
// -------------------------------------------------------------------------------------------------
private static final DayCount ACT_365 = DayCountFactory.INSTANCE.getDayCount("ACT/365");
// Set the number of partitions to divide the timeline up into for the valuation of the contingent leg
private static final int DEFAULT_N_POINTS = 30;
private final int _numberOfIntegrationSteps;
public PresentValueLegacyCreditDefaultSwap() {
this(DEFAULT_N_POINTS);
}
public PresentValueLegacyCreditDefaultSwap(int numberOfIntegrationPoints) {
_numberOfIntegrationSteps = numberOfIntegrationPoints;
}
// -------------------------------------------------------------------------------------------------
// TODO : Lots of ongoing work to do in this class - Work In Progress
// TODO : Add a method to calc both the legs in one method (useful for performance reasons e.g. not computing survival probabilities and discount factors twice)
// TODO : If valuationDate = adjustedMatDate - 1day have to be more careful in how the contingent leg integral is calculated
// TODO : Fix the bug when val date is very close to mat date
// TODO : Need to add the code for when the settlement date > 0 business days (just a discount factor)
// TODO : Replace the while with a binary search function
// TODO : Should build the cashflow schedules outside of the leg valuation routines to avoid repitition of calculations
// TODO : Eventually replace the ISDACurve with a YieldCurve object (currently using ISDACurve built by RiskCare as this allows exact comparison with the ISDA model)
// TODO : Replace the accrued schedule double with a ZonedDateTime object to make it consistent with other calculations
// TODO : Tidy up the calculatePremiumLeg, valueFeeLegAccrualOnDefault and methods
// TODO : Add the calculation for the settlement and stepin discount factors
// -------------------------------------------------------------------------------------------------
// Public method for computing the PV of a CDS based on an input CDS contract (with a hazard rate curve calibrated to market observed data)
public double getPresentValueCreditDefaultSwap(LegacyCreditDefaultSwapDefinition cds, ISDACurve yieldCurve, HazardRateCurve hazardRateCurve) {
// -------------------------------------------------------------
// Check input CDS, YieldCurve and SurvivalCurve objects are not null
ArgumentChecker.notNull(cds, "LegacyCreditDefaultSwapDefinition");
ArgumentChecker.notNull(yieldCurve, "YieldCurve");
ArgumentChecker.notNull(hazardRateCurve, "HazardRateCurve");
// -------------------------------------------------------------
// Calculate the value of the premium leg (including accrued if required)
double presentValuePremiumLeg = calculatePremiumLeg(cds, yieldCurve, hazardRateCurve);
// Calculate the value of the contingent leg
double presentValueContingentLeg = calculateContingentLeg(cds, yieldCurve, hazardRateCurve);
// Calculate the PV of the CDS (assumes we are buying protection i.e. paying the premium leg, receiving the contingent leg)
double presentValue = -(cds.getParSpread() / 10000.0) * presentValuePremiumLeg + presentValueContingentLeg;
// -------------------------------------------------------------
// If we require the clean price, then calculate the accrued interest and add this to the PV
if (cds.getPriceType() == PriceType.CLEAN) {
presentValue += calculateAccruedInterest(cds, yieldCurve, hazardRateCurve);
}
// If we are selling protection, then reverse the direction of the premium and contingent leg cashflows
if (cds.getBuySellProtection() == BuySellProtection.SELL) {
presentValue = -1 * presentValue;
}
// -------------------------------------------------------------
return presentValue;
}
//-------------------------------------------------------------------------------------------------
// Public method to calculate the par spread of a CDS at contract inception (with a hazard rate curve calibrated to market observed data)
public double getParSpreadCreditDefaultSwap(LegacyCreditDefaultSwapDefinition cds, ISDACurve yieldCurve, HazardRateCurve hazardRateCurve) {
// -------------------------------------------------------------
// Check input CDS, YieldCurve and SurvivalCurve objects are not null
ArgumentChecker.notNull(cds, "CDS field");
ArgumentChecker.notNull(yieldCurve, "YieldCurve field");
ArgumentChecker.notNull(hazardRateCurve, "HazardRateCurve field");
// -------------------------------------------------------------
double parSpread = 0.0;
// -------------------------------------------------------------
// Construct a cashflow schedule object
final GenerateCreditDefaultSwapPremiumLegSchedule cashflowSchedule = new GenerateCreditDefaultSwapPremiumLegSchedule();
// Check if the valuationDate equals the adjusted effective date (have to do this after the schedule is constructed)
ArgumentChecker.isTrue(cds.getValuationDate().equals(cashflowSchedule.getAdjustedEffectiveDate(cds)), "Valuation Date should equal the adjusted effective date when computing par spreads");
// -------------------------------------------------------------
// Calculate the value of the premium leg
double presentValuePremiumLeg = calculatePremiumLeg(cds, yieldCurve, hazardRateCurve);
// Calculate the value of the contingent leg
double presentValueContingentLeg = calculateContingentLeg(cds, yieldCurve, hazardRateCurve);
// -------------------------------------------------------------
// Calculate the par spread (NOTE : Returned value is in bps)
if (Double.doubleToLongBits(presentValuePremiumLeg) == 0.0) {
throw new IllegalStateException("Warning : The premium leg has a PV of zero - par spread cannot be computed");
} else {
parSpread = 10000.0 * presentValueContingentLeg / presentValuePremiumLeg;
}
// -------------------------------------------------------------
return parSpread;
}
// -------------------------------------------------------------------------------------------------
// Method to calculate the value of the premium leg of a CDS (with a hazard rate curve calibrated to market observed data)
// The code for the accrued calc has just been lifted from RiskCare's implementation for now because it exactly reproduces the ISDA model - will replace with a better model in due course
private double calculatePremiumLeg(LegacyCreditDefaultSwapDefinition cds, ISDACurve yieldCurve, HazardRateCurve hazardRateCurve) {
// -------------------------------------------------------------
// Local variable definitions
int startIndex = 0;
int endIndex = 0;
double presentValuePremiumLeg = 0.0;
double presentValueAccruedInterest = 0.0;
// -------------------------------------------------------------
// Construct a cashflow schedule object for the premium leg
final GenerateCreditDefaultSwapPremiumLegSchedule cashflowSchedule = new GenerateCreditDefaultSwapPremiumLegSchedule();
// Build the premium leg cashflow schedule from the contract specification
ZonedDateTime[] premiumLegSchedule = cashflowSchedule.constructCreditDefaultSwapPremiumLegSchedule(cds);
// Construct a schedule object for the accrued leg (this is not a cashflow schedule per se, but a set of time nodes for evaluating the accrued payment integral)
GenerateCreditDefaultSwapIntegrationSchedule accruedSchedule = new GenerateCreditDefaultSwapIntegrationSchedule();
// Build the integration schedule for the calculation of the accrued leg
double[] accruedLegIntegrationSchedule = accruedSchedule.constructCreditDefaultSwapAccruedLegIntegrationSchedule(cds, yieldCurve, hazardRateCurve);
// Calculate the stepin time with the appropriate offset
double offsetStepinTime = accruedSchedule.calculateCreditDefaultSwapOffsetStepinTime(cds, ACT_365);
// -------------------------------------------------------------
// Get the date on which we want to calculate the MtM
ZonedDateTime valuationDate = cds.getValuationDate();
// Get the (adjusted) maturity date of the trade
ZonedDateTime adjustedMaturityDate = cashflowSchedule.getAdjustedMaturityDate(cds);
// -------------------------------------------------------------
// If the valuationDate is after the adjusted maturity date then throw an exception (differs from check in ctor because of the adjusted maturity date)
ArgumentChecker.isTrue(!valuationDate.isAfter(adjustedMaturityDate), "Valuation date {} must be on or before the adjusted maturity date {}", valuationDate, adjustedMaturityDate);
// If the valuation date is exactly the adjusted maturity date then simply return zero
if (valuationDate.equals(adjustedMaturityDate)) {
return 0.0;
}
// -------------------------------------------------------------
// Determine where in the cashflow schedule the valuationDate is
int startCashflowIndex = getCashflowIndex(cds, premiumLegSchedule, 1, 1);
// -------------------------------------------------------------
// Calculate the value of the remaining premium and accrual payments (due after valuationDate)
for (int i = startCashflowIndex; i < premiumLegSchedule.length; i++) {
// Get the beginning and end dates of the current coupon
ZonedDateTime accrualStart = premiumLegSchedule[i - 1];
ZonedDateTime accrualEnd = premiumLegSchedule[i];
// -------------------------------------------------------------
// Calculate the time between the valuation date (time at which survival probability is unity) and the current cashflow
double t = TimeCalculator.getTimeBetween(valuationDate, accrualEnd, ACT_365);
// Calculate the discount factor at time t
double discountFactor = yieldCurve.getDiscountFactor(t);
// -------------------------------------------------------------
// If protection starts at the beginning of the period ...
if (cds.getProtectionStart()) {
// ... Roll all but the last date back by 1/365 of a year
if (i < premiumLegSchedule.length - 1) {
t -= cds.getProtectionOffset();
}
// This is a bit of a hack - need a more elegant way of dealing with the timing nuances
if (i == 1) {
accrualStart = accrualStart.minusDays(1);
}
// ... Roll the final maturity date forward by one day
if (i == premiumLegSchedule.length - 1) {
accrualEnd = accrualEnd.plusDays(1);
}
}
// -------------------------------------------------------------
// Compute the daycount fraction for the current accrual period
double dcf = cds.getDayCountFractionConvention().getDayCountFraction(accrualStart, accrualEnd);
// Calculate the survival probability at the modified time t
double survivalProbability = hazardRateCurve.getSurvivalProbability(t);
// Add this discounted cashflow to the running total for the value of the premium leg
presentValuePremiumLeg += dcf * discountFactor * survivalProbability;
// -------------------------------------------------------------
// Now calculate the accrued leg component if required (need to re-write this code)
if (cds.getIncludeAccruedPremium()) {
double stepinDiscountFactor = 1.0;
startIndex = endIndex;
while (accruedLegIntegrationSchedule[endIndex] < t) {
++endIndex;
}
presentValueAccruedInterest += valueFeeLegAccrualOnDefault(dcf, accruedLegIntegrationSchedule, yieldCurve, hazardRateCurve, startIndex, endIndex,
offsetStepinTime, stepinDiscountFactor);
}
// -------------------------------------------------------------
}
// -------------------------------------------------------------
return cds.getNotional() * (presentValuePremiumLeg + presentValueAccruedInterest);
// -------------------------------------------------------------
}
//-------------------------------------------------------------------------------------------------
// Need to re-write this code completely!!
private double valueFeeLegAccrualOnDefault(final double amount, final double[] timeline, final ISDACurve yieldCurve, final HazardRateCurve hazardRateCurve, final int startIndex,
final int endIndex, final double stepinTime, final double stepinDiscountFactor) {
final double[] timePoints = timeline; //timeline.getTimePoints();
final double startTime = timePoints[startIndex];
final double endTime = timePoints[endIndex];
final double subStartTime = stepinTime > startTime ? stepinTime : startTime;
final double accrualRate = amount / (endTime - startTime);
double t0, t1, dt, survival0, survival1, discount0, discount1;
double lambda, fwdRate, lambdaFwdRate, valueForTimeStep, value;
t0 = subStartTime - startTime + 0.5 * (1.0 / 365.0); //HALF_DAY_ACT_365F;
survival0 = hazardRateCurve.getSurvivalProbability(subStartTime);
double PRICING_TIME = 0.0;
discount0 = startTime < stepinTime || startTime < PRICING_TIME ? stepinDiscountFactor : yieldCurve.getDiscountFactor(timePoints[startIndex]); //discountFactors[startIndex];
value = 0.0;
for (int i = startIndex + 1; i <= endIndex; ++i) {
if (timePoints[i] <= stepinTime) {
continue;
}
t1 = timePoints[i] - startTime + 0.5 * (1.0 / 365.0); //HALF_DAY_ACT_365F;
dt = t1 - t0;
survival1 = hazardRateCurve.getSurvivalProbability(timePoints[i]);
discount1 = yieldCurve.getDiscountFactor(timePoints[i]); //discountFactors[i];
lambda = Math.log(survival0 / survival1) / dt;
fwdRate = Math.log(discount0 / discount1) / dt;
lambdaFwdRate = lambda + fwdRate + 1.0e-50;
valueForTimeStep = lambda * accrualRate * survival0 * discount0
* (((t0 + 1.0 / lambdaFwdRate) / lambdaFwdRate) - ((t1 + 1.0 / lambdaFwdRate) / lambdaFwdRate) * survival1 / survival0 * discount1 / discount0);
value += valueForTimeStep;
t0 = t1;
survival0 = survival1;
discount0 = discount1;
}
return value;
}
// -------------------------------------------------------------------------------------------------
// If the cleanPrice flag is TRUE then this function is called to calculate the accrued interest between valuationDate and the previous coupon date
private double calculateAccruedInterest(LegacyCreditDefaultSwapDefinition cds, ISDACurve yieldCurve, HazardRateCurve hazardRateCurve) {
// Construct a cashflow schedule object
final GenerateCreditDefaultSwapPremiumLegSchedule cashflowSchedule = new GenerateCreditDefaultSwapPremiumLegSchedule();
// Build the premium leg cashflow schedule from the contract specification
ZonedDateTime[] premiumLegSchedule = cashflowSchedule.constructCreditDefaultSwapPremiumLegSchedule(cds);
// Assume the stepin date is the valuation date + 1 day (this is not business day adjusted)
ZonedDateTime stepinDate = cds.getValuationDate().plusDays(1);
// Determine where in the premium leg cashflow schedule the current valuation date is
int startCashflowIndex = getCashflowIndex(cds, premiumLegSchedule, 0, 1);
// Get the date of the last coupon before the current valuation date
ZonedDateTime previousPeriod = premiumLegSchedule[startCashflowIndex - 1];
// Compute the amount of time between previousPeriod and stepinDate
double dcf = cds.getDayCountFractionConvention().getDayCountFraction(previousPeriod, stepinDate);
// Calculate the accrued interest gained in this period of time
double accruedInterest = (cds.getParSpread() / 10000.0) * dcf * cds.getNotional();
return accruedInterest;
}
// -------------------------------------------------------------------------------------------------
// Method to determine where in the premium leg cashflow schedule the valuation date is
private int getCashflowIndex(LegacyCreditDefaultSwapDefinition cds, ZonedDateTime[] premiumLegSchedule, final int startIndex, final int deltaDays) {
int counter = startIndex;
// Determine where in the cashflow schedule the valuationDate is
while (!cds.getValuationDate().isBefore(premiumLegSchedule[counter].minusDays(deltaDays))) {
counter++;
}
return counter;
}
// -------------------------------------------------------------------------------------------------
// Method to calculate the contingent leg (replicates the calculation in the ISDA model)
private double calculateContingentLeg(LegacyCreditDefaultSwapDefinition cds, ISDACurve yieldCurve, HazardRateCurve hazardRateCurve) {
// -------------------------------------------------------------
// Local variable definitions
double presentValueContingentLeg = 0.0;
// -------------------------------------------------------------
// Construct an integration schedule object for the contingent leg
GenerateCreditDefaultSwapIntegrationSchedule contingentLegSchedule = new GenerateCreditDefaultSwapIntegrationSchedule();
// Build the integration schedule for the calculation of the contingent leg
double[] contingentLegIntegrationSchedule = contingentLegSchedule.constructCreditDefaultSwapContingentLegIntegrationSchedule(cds, yieldCurve, hazardRateCurve);
// -------------------------------------------------------------
// Get the survival probability at the first point in the integration schedule
double survivalProbability = hazardRateCurve.getSurvivalProbability(contingentLegIntegrationSchedule[0]);
// Get the discount factor at the first point in the integration schedule
double discountFactor = yieldCurve.getDiscountFactor(contingentLegIntegrationSchedule[0]);
// -------------------------------------------------------------
// Loop over each of the points in the integration schedule
for (int i = 1; i < contingentLegIntegrationSchedule.length; ++i) {
// Calculate the time between adjacent points in the integration schedule
double deltat = contingentLegIntegrationSchedule[i] - contingentLegIntegrationSchedule[i - 1];
// Set the probability of survival up to the previous point in the integration schedule
double survivalProbabilityPrevious = survivalProbability;
// Set the discount factor up to the previous point in the integration schedule
double discountFactorPrevious = discountFactor;
// Get the survival probability at this point in the integration schedule
survivalProbability = hazardRateCurve.getSurvivalProbability(contingentLegIntegrationSchedule[i]);
// Get the discount factor at this point in the integration schedule
discountFactor = yieldCurve.getDiscountFactor(contingentLegIntegrationSchedule[i]);
// Calculate the forward hazard rate over the interval deltat (assumes the hazard rate is constant over this period)
double hazardRate = Math.log(survivalProbabilityPrevious / survivalProbability) / deltat;
// Calculate the forward interest rate over the interval deltat (assumes the interest rate is constant over this period)
double interestRate = Math.log(discountFactorPrevious / discountFactor) / deltat;
// Calculate the contribution of the interval deltat to the overall contingent leg integral
presentValueContingentLeg += (hazardRate / (hazardRate + interestRate)) * (1.0 - Math.exp(-(hazardRate + interestRate) * deltat)) * survivalProbabilityPrevious * discountFactorPrevious;
}
// -------------------------------------------------------------
return cds.getNotional() * (1 - cds.getRecoveryRate()) * presentValueContingentLeg;
}
// -------------------------------------------------------------------------------------------------
// Method to calculate the value of the contingent leg of a CDS (with a hazard rate curve calibrated to market observed data) - Currently not used but this is a more elegant calc than ISDA
private double calculateContingentLegOld(LegacyCreditDefaultSwapDefinition cds, ISDACurve yieldCurve, HazardRateCurve hazardRateCurve) {
// -------------------------------------------------------------
// Construct a schedule generation object (to access the adjusted maturity date method)
GenerateCreditDefaultSwapPremiumLegSchedule cashflowSchedule = new GenerateCreditDefaultSwapPremiumLegSchedule();
// Get the date when protection begins
ZonedDateTime valuationDate = cds.getValuationDate();
// Get the date when protection ends
ZonedDateTime adjustedMaturityDate = cashflowSchedule.getAdjustedMaturityDate(cds);
// -------------------------------------------------------------
// If the valuationDate is after the adjusted maturity date then throw an exception (differs from check in ctor because of the adjusted maturity date)
ArgumentChecker.isTrue(!valuationDate.isAfter(adjustedMaturityDate), "Valuation date {} must be on or before the adjusted maturity date {}", valuationDate, adjustedMaturityDate);
// If the valuation date is exactly the adjusted maturity date then simply return zero
if (valuationDate.equals(adjustedMaturityDate)) {
return 0.0;
}
// -------------------------------------------------------------
double presentValueContingentLeg = 0.0;
// -------------------------------------------------------------
// Calculate the partition of the time axis for the calculation of the integral in the contingent leg
// The period of time for which protection is provided
double protectionPeriod = TimeCalculator.getTimeBetween(valuationDate, adjustedMaturityDate.plusDays(1), /*cds.getDayCountFractionConvention()*/ACT_365);
// Given the protection period, how many partitions should it be divided into
int numberOfPartitions = (int) (_numberOfIntegrationSteps * protectionPeriod + 0.5);
// The size of the time increments in the calculation of the integral
double epsilon = protectionPeriod / numberOfPartitions;
// -------------------------------------------------------------
// Calculate the integral for the contingent leg (note the limits of the loop)
for (int k = 1; k <= numberOfPartitions; k++) {
double t = k * epsilon;
double tPrevious = (k - 1) * epsilon;
double discountFactor = yieldCurve.getDiscountFactor(t);
double survivalProbability = hazardRateCurve.getSurvivalProbability(t);
double survivalProbabilityPrevious = hazardRateCurve.getSurvivalProbability(tPrevious);
presentValueContingentLeg += discountFactor * (survivalProbabilityPrevious - survivalProbability);
}
// -------------------------------------------------------------
return cds.getNotional() * (1.0 - cds.getRecoveryRate()) * presentValueContingentLeg;
}
// -------------------------------------------------------------------------------------------------
}
|
apache-2.0
|
archana-khanal/twu-biblioteca-archanakhanal
|
test/com/twu/biblioteca/MockMenuOption.java
|
61
|
package com.twu.biblioteca;
public class MockMenuOption {
}
|
apache-2.0
|
zhou18520786640/zhou18520786640.github.io
|
2016/03/12/使用TableView布局UI控件/index.html
|
16801
|
<!doctype html>
<html class="theme-next muse use-motion">
<head>
<meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
<link href="/vendors/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css"/>
<link href="//fonts.googleapis.com/css?family=Lato:300,400,700,400italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
<link href="/vendors/font-awesome/css/font-awesome.min.css?v=4.4.0" rel="stylesheet" type="text/css" />
<link href="/css/main.css?v=0.5.0" rel="stylesheet" type="text/css" />
<meta name="keywords" content="iOS," />
<link rel="shortcut icon" type="image/x-icon" href="/favicon.ico?v=0.5.0" />
<meta name="description" content="场景考虑一个电子商品app的商品展示页面。需要展示一个商品三部分的信息。分别是商品的领券入口,商品的优惠信息。商品是一个海淘商品。这三部分信息分别
初版">
<meta property="og:type" content="article">
<meta property="og:title" content="使用TableView布局UI控件">
<meta property="og:url" content="http://yoursite.com/2016/03/12/使用TableView布局UI控件/index.html">
<meta property="og:site_name" content="周明的技术博客">
<meta property="og:description" content="场景考虑一个电子商品app的商品展示页面。需要展示一个商品三部分的信息。分别是商品的领券入口,商品的优惠信息。商品是一个海淘商品。这三部分信息分别
初版">
<meta property="og:image" content="http://pic2.ooopic.com/11/39/38/20bOOOPIC97.jpg">
<meta property="og:updated_time" content="2016-03-11T16:45:34.000Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="使用TableView布局UI控件">
<meta name="twitter:description" content="场景考虑一个电子商品app的商品展示页面。需要展示一个商品三部分的信息。分别是商品的领券入口,商品的优惠信息。商品是一个海淘商品。这三部分信息分别
初版">
<meta name="twitter:image" content="http://pic2.ooopic.com/11/39/38/20bOOOPIC97.jpg">
<script type="text/javascript" id="hexo.configuration">
var NexT = window.NexT || {};
var CONFIG = {
scheme: 'Muse',
sidebar: {"position":"left","display":"post"},
fancybox: true,
motion: true,
duoshuo: {
userId: 0,
author: '博主'
}
};
</script>
<title> 使用TableView布局UI控件 | 周明的技术博客 </title>
</head>
<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">
<div class="container one-collumn sidebar-position-left page-post-detail ">
<div class="headband"></div>
<header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
<div class="header-inner"><div class="site-meta ">
<div class="custom-logo-site-title">
<a href="/" class="brand" rel="start">
<span class="logo-line-before"><i></i></span>
<span class="site-title">周明的技术博客</span>
<span class="logo-line-after"><i></i></span>
</a>
</div>
<p class="site-subtitle">记录技术成长之路</p>
</div>
<div class="site-nav-toggle">
<button>
<span class="btn-bar"></span>
<span class="btn-bar"></span>
<span class="btn-bar"></span>
</button>
</div>
<nav class="site-nav">
<ul id="menu" class="menu ">
<li class="menu-item menu-item-home">
<a href="/" rel="section">
<i class="menu-item-icon fa fa-home fa-fw"></i> <br />
首页
</a>
</li>
<li class="menu-item menu-item-archives">
<a href="/archives" rel="section">
<i class="menu-item-icon fa fa-archive fa-fw"></i> <br />
归档
</a>
</li>
<li class="menu-item menu-item-tags">
<a href="/tags" rel="section">
<i class="menu-item-icon fa fa-tags fa-fw"></i> <br />
标签
</a>
</li>
</ul>
</nav>
</div>
</header>
<main id="main" class="main">
<div class="main-inner">
<div class="content-wrap">
<div id="content" class="content">
<div id="posts" class="posts-expand">
<article class="post post-type-normal " itemscope itemtype="http://schema.org/Article">
<header class="post-header">
<h1 class="post-title" itemprop="name headline">
使用TableView布局UI控件
</h1>
<div class="post-meta">
<span class="post-time">
<span class="post-meta-item-icon">
<i class="fa fa-calendar-o"></i>
</span>
<span class="post-meta-item-text">发表于</span>
<time itemprop="dateCreated" datetime="2016-03-12T00:32:54+08:00" content="2016-03-12">
2016-03-12
</time>
</span>
</div>
</header>
<div class="post-body" itemprop="articleBody">
<p><img src="http://pic2.ooopic.com/11/39/38/20bOOOPIC97.jpg" alt="image"></p>
<h3 id="场景"><a href="#场景" class="headerlink" title="场景"></a>场景</h3><p>考虑一个电子商品app的商品展示页面。需要展示一个商品三部分的信息。分别是商品的领券入口,商品的优惠信息。商品是一个海淘商品。这三部分信息分别</p>
<h3 id="初版"><a href="#初版" class="headerlink" title="初版"></a>初版</h3>
</div>
<div>
</div>
<footer class="post-footer">
<div class="post-tags">
<a href="/tags/iOS/" rel="tag">#iOS</a>
</div>
<div class="post-nav">
<div class="post-nav-next post-nav-item">
<a href="/2016/03/05/oc设计模式之简单工厂模式/" rel="next" title="OC设计模式之简单工厂模式">
<i class="fa fa-chevron-left"></i> OC设计模式之简单工厂模式
</a>
</div>
<div class="post-nav-prev post-nav-item">
<a href="/2016/03/12/hexo-github部署静态blog/" rel="prev" title="hexo github部署静态blog">
hexo github部署静态blog <i class="fa fa-chevron-right"></i>
</a>
</div>
</div>
</footer>
</article>
<div class="post-spread">
</div>
</div>
</div>
<div class="comments" id="comments">
</div>
</div>
<div class="sidebar-toggle">
<div class="sidebar-toggle-line-wrap">
<span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
<span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
<span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
</div>
</div>
<aside id="sidebar" class="sidebar">
<div class="sidebar-inner">
<ul class="sidebar-nav motion-element">
<li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap" >
文章目录
</li>
<li class="sidebar-nav-overview" data-target="site-overview">
站点概览
</li>
</ul>
<section class="site-overview sidebar-panel ">
<div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
<img class="site-author-image" itemprop="image"
src="http://www.xxdm.com/uploads/allimg/131219/2_131219164520_1.jpg"
alt="Jeff Zhou" />
<p class="site-author-name" itemprop="name">Jeff Zhou</p>
<p class="site-description motion-element" itemprop="description"></p>
</div>
<nav class="site-state motion-element">
<div class="site-state-item site-state-posts">
<a href="/archives">
<span class="site-state-item-count">44</span>
<span class="site-state-item-name">日志</span>
</a>
</div>
<div class="site-state-item site-state-tags">
<a href="/tags">
<span class="site-state-item-count">4</span>
<span class="site-state-item-name">标签</span>
</a>
</div>
</nav>
<div class="links-of-author motion-element">
</div>
<div class="links-of-author motion-element">
</div>
</section>
<section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
<div class="post-toc-indicator-top post-toc-indicator">
<i class="fa fa-angle-double-up"></i>
</div>
<div class="post-toc">
<div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-3"><a class="nav-link" href="#场景"><span class="nav-number">1.</span> <span class="nav-text">场景</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#初版"><span class="nav-number">2.</span> <span class="nav-text">初版</span></a></li></ol></div>
</div>
<div class="post-toc-indicator-bottom post-toc-indicator">
<i class="fa fa-angle-double-down"></i>
</div>
</section>
</div>
</aside>
</div>
</main>
<footer id="footer" class="footer">
<div class="footer-inner">
<div class="copyright" >
©
<span itemprop="copyrightYear">2016</span>
<span class="with-love">
<i class="fa fa-heart"></i>
</span>
<span class="author" itemprop="copyrightHolder">Jeff Zhou</span>
</div>
<div class="powered-by">
由 <a class="theme-link" href="http://hexo.io">Hexo</a> 强力驱动
</div>
<div class="theme-info">
主题 -
<a class="theme-link" href="https://github.com/iissnan/hexo-theme-next">
NexT.Muse
</a>
</div>
</div>
</footer>
<div class="back-to-top"></div>
</div>
<script type="text/javascript">
if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
window.Promise = null;
}
</script>
<script type="text/javascript" src="/vendors/jquery/index.js?v=2.1.3"></script>
<script type="text/javascript" src="/vendors/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
<script type="text/javascript" src="/vendors/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
<script type="text/javascript" src="/vendors/velocity/velocity.min.js"></script>
<script type="text/javascript" src="/vendors/velocity/velocity.ui.min.js"></script>
<script type="text/javascript" src="/vendors/fancybox/source/jquery.fancybox.pack.js"></script>
<script type="text/javascript" src="/js/src/utils.js?v=0.5.0"></script>
<script type="text/javascript" src="/js/src/motion.js?v=0.5.0"></script>
<script type="text/javascript" src="/js/src/scrollspy.js?v=0.5.0"></script>
<script type="text/javascript" id="sidebar.toc.highlight">
$(document).ready(function () {
var tocSelector = '.post-toc';
var $tocSelector = $(tocSelector);
var activeCurrentSelector = '.active-current';
$tocSelector
.on('activate.bs.scrollspy', function () {
var $currentActiveElement = $(tocSelector + ' .active').last();
removeCurrentActiveClass();
$currentActiveElement.addClass('active-current');
$tocSelector[0].scrollTop = $currentActiveElement.position().top;
})
.on('clear.bs.scrollspy', function () {
removeCurrentActiveClass();
});
function removeCurrentActiveClass () {
$(tocSelector + ' ' + activeCurrentSelector)
.removeClass(activeCurrentSelector.substring(1));
}
function processTOC () {
getTOCMaxHeight();
toggleTOCOverflowIndicators();
}
function getTOCMaxHeight () {
var height = $('.sidebar').height() -
$tocSelector.position().top -
$('.post-toc-indicator-bottom').height();
$tocSelector.css('height', height);
return height;
}
function toggleTOCOverflowIndicators () {
tocOverflowIndicator(
'.post-toc-indicator-top',
$tocSelector.scrollTop() > 0 ? 'show' : 'hide'
);
tocOverflowIndicator(
'.post-toc-indicator-bottom',
$tocSelector.scrollTop() >= $tocSelector.find('ol').height() - $tocSelector.height() ? 'hide' : 'show'
)
}
$(document).on('sidebar.motion.complete', function () {
processTOC();
});
$('body').scrollspy({ target: tocSelector });
$(window).on('resize', function () {
if ( $('.sidebar').hasClass('sidebar-active') ) {
processTOC();
}
});
onScroll($tocSelector);
function onScroll (element) {
element.on('mousewheel DOMMouseScroll', function (event) {
var oe = event.originalEvent;
var delta = oe.wheelDelta || -oe.detail;
this.scrollTop += ( delta < 0 ? 1 : -1 ) * 30;
event.preventDefault();
toggleTOCOverflowIndicators();
});
}
function tocOverflowIndicator (indicator, action) {
var $indicator = $(indicator);
var opacity = action === 'show' ? 1 : 0;
$indicator.velocity ?
$indicator.velocity('stop').velocity({
opacity: opacity
}, { duration: 100 }) :
$indicator.stop().animate({
opacity: opacity
}, 100);
}
});
</script>
<script type="text/javascript" id="sidebar.nav">
$(document).ready(function () {
var html = $('html');
var TAB_ANIMATE_DURATION = 200;
var hasVelocity = $.isFunction(html.velocity);
$('.sidebar-nav li').on('click', function () {
var item = $(this);
var activeTabClassName = 'sidebar-nav-active';
var activePanelClassName = 'sidebar-panel-active';
if (item.hasClass(activeTabClassName)) {
return;
}
var currentTarget = $('.' + activePanelClassName);
var target = $('.' + item.data('target'));
hasVelocity ?
currentTarget.velocity('transition.slideUpOut', TAB_ANIMATE_DURATION, function () {
target
.velocity('stop')
.velocity('transition.slideDownIn', TAB_ANIMATE_DURATION)
.addClass(activePanelClassName);
}) :
currentTarget.animate({ opacity: 0 }, TAB_ANIMATE_DURATION, function () {
currentTarget.hide();
target
.stop()
.css({'opacity': 0, 'display': 'block'})
.animate({ opacity: 1 }, TAB_ANIMATE_DURATION, function () {
currentTarget.removeClass(activePanelClassName);
target.addClass(activePanelClassName);
});
});
item.siblings().removeClass(activeTabClassName);
item.addClass(activeTabClassName);
});
$('.post-toc a').on('click', function (e) {
e.preventDefault();
var targetSelector = NexT.utils.escapeSelector(this.getAttribute('href'));
var offset = $(targetSelector).offset().top;
hasVelocity ?
html.velocity('stop').velocity('scroll', {
offset: offset + 'px',
mobileHA: false
}) :
$('html, body').stop().animate({
scrollTop: offset
}, 500);
});
// Expand sidebar on post detail page by default, when post has a toc.
NexT.motion.middleWares.sidebar = function () {
var $tocContent = $('.post-toc-content');
if (CONFIG.scheme !== 'Pisces' && (CONFIG.sidebar.display === 'post' || CONFIG.sidebar.display === 'always')) {
if ($tocContent.length > 0 && $tocContent.html().trim().length > 0) {
NexT.utils.displaySidebar();
}
}
};
});
</script>
<script type="text/javascript" src="/js/src/bootstrap.js?v=0.5.0"></script>
</body>
</html>
|
apache-2.0
|
xiaohaoyong/www.jzfupin.cn
|
core/library/global.function.php
|
10008
|
<?php
if (!defined('IN_IAEWEB')) exit();
/**
* 图片路径自动补全
*/
function image($url)
{
if (empty($url) || strlen($url) < 4) return SITE_PATH.'data/upload/nopic.gif';
if (substr($url, 0, 7) == 'http://') return $url;
if (strpos($url, SITE_PATH) !== false && SITE_PATH != '/') return $url;
if (substr($url, 0, 1) == '/') $url = substr($url, 1);
return SITE_PATH.$url;
}
/**
* 缩略图片
*/
function thumb($img, $width = 200, $height = 200)
{
if (empty($img) || strlen($img) < 4) return SITE_PATH.'data/upload/nopic.gif';
if (file_exists(IAEWEB_PATH.$img)) {
$ext = fileext($img);
$thumb = $img.'.thumb.'.$width.'x'.$height.'.'.$ext;
if (!file_exists(IAEWEB_PATH.$thumb)) {
$image = iaeweb::load_class('image');
$image->thumb(IAEWEB_PATH.$img, IAEWEB_PATH.$thumb, $width, $height); // 生成图像缩略图
}
return $thumb;
}
return $img;
}
/**
* 字符截取 支持UTF8/GBK
*/
function strcut($string, $length, $dot = '')
{
if (strlen($string) <= $length) return $string;
$string = str_replace(array('&', '"', '<', '>'), array('&', '"', '<', '>'), $string);
$strcut = '';
$n = $tn = $noc = 0;
while ($n < strlen($string)) {
$t = ord($string[$n]);
if ($t == 9 || $t == 10 || (32 <= $t && $t <= 126)) {
$tn = 1;
$n++;
$noc++;
} elseif (194 <= $t && $t <= 223) {
$tn = 2;
$n += 2;
$noc += 2;
} elseif (224 <= $t && $t <= 239) {
$tn = 3;
$n += 3;
$noc += 2;
} elseif (240 <= $t && $t <= 247) {
$tn = 4;
$n += 4;
$noc += 2;
} elseif (248 <= $t && $t <= 251) {
$tn = 5;
$n += 5;
$noc += 2;
} elseif ($t == 252 || $t == 253) {
$tn = 6;
$n += 6;
$noc += 2;
} else {
$n++;
}
if ($noc >= $length) break;
}
if ($noc > $length) $n -= $tn;
$strcut = substr($string, 0, $n);
$strcut = str_replace(array('&', '"', '<', '>'), array('&', '"', '<', '>'), $strcut);
return $strcut.$dot;
}
/**
* 取得文件扩展
*/
function fileext($filename)
{
return pathinfo($filename, PATHINFO_EXTENSION);
}
/**
* 正则表达式验证email格式
*/
function is_email($email)
{
return strlen($email) > 6 && strlen($email) <= 32 && preg_match("/^([A-Za-z0-9\-_.+]+)@([A-Za-z0-9\-]+[.][A-Za-z0-9\-.]+)$/", $email);
}
/**
* 栏目面包屑导航 当前位置
*/
function position($catid, $symbol = ' > ')
{
if (empty($catid)) return false;
$cats = get_cache('category');
$catids = parentids($catid, $cats);
$catids = array_filter(explode(',', $catids));
krsort($catids);
$html = '';
foreach ($catids as $t) {
$html .= "<a href=\"".$cats[$t]['url']."\" title=\"".$cats[$t]['catname']."\">".$cats[$t]['catname']."</a>";
if ($catid != $t) $html .= $symbol;
}
return $html;
}
/**
* 递归获取上级栏目集合
*/
function parentids($catid, $cats)
{
if (empty($catid)) return false;
$catids = $catid.',';
if ($cats[$catid]['parentid']) $catids .= parentids($cats[$catid]['parentid'], $cats);
return $catids;
}
/**
* 获取当前栏目顶级栏目
*/
function get_top_cat($catid)
{
$cats = get_cache('category');
$cat = $cats[$catid];
if ($cat['parentid']) $cat = get_top_cat($cat['parentid']);
return $cat;
}
/**
* 程序执行时间
*/
function runtime()
{
$temptime = explode(' ', SYS_START_TIME);
$time = $temptime[1] + $temptime[0];
$temptime = explode(' ', microtime());
$now = $temptime[1] + $temptime[0];
return number_format($now - $time, 6);
}
/**
* 返回经stripslashes处理过的字符串或数组
*/
function new_stripslashes($string)
{
if (!is_array($string)) return stripslashes($string);
foreach ($string as $key => $val) $string[$key] = new_stripslashes($val);
return $string;
}
/**
* 将字符串转换为数组
*/
function string2array($data)
{
if ($data == '') return array();
return unserialize($data);
}
/**
* 将数组转换为字符串
*/
function array2string($data, $isformdata = 1)
{
if ($data == '') return '';
if ($isformdata) $data = new_stripslashes($data);
return serialize($data);
}
/**
* 字节格式化
*/
function file_size_count($size, $dec = 2)
{
$a = array("B", "KB", "MB", "GB", "TB", "PB");
$pos = 0;
while ($size >= 1024) {
$size /= 1024;
$pos++;
}
return round($size, $dec)." ".$a[$pos];
}
/**
* 汉字转为拼音
*/
function word2pinyin($word)
{
if (empty($word)) return '';
$pin = iaeweb::load_class('pinyin');
return str_replace('/', '', $pin->output($word));
}
/**
* 判断是否手机访问
*/
function is_mobile()
{
static $is_mobile;
if (isset($is_mobile)) return $is_mobile;
if (empty($_SERVER['HTTP_USER_AGENT'])) {
$is_mobile = false;
} elseif (strpos($_SERVER['HTTP_USER_AGENT'], 'Mobile') !== false // many mobile devices (all iPhone, iPad, etc.)
|| strpos($_SERVER['HTTP_USER_AGENT'], 'Android') !== false || strpos($_SERVER['HTTP_USER_AGENT'], 'Silk/') !== false || strpos($_SERVER['HTTP_USER_AGENT'], 'Kindle') !== false || strpos($_SERVER['HTTP_USER_AGENT'], 'BlackBerry') !== false || strpos($_SERVER['HTTP_USER_AGENT'], 'Opera Mini') !== false || strpos($_SERVER['HTTP_USER_AGENT'], 'Opera Mobi') !== false) {
$is_mobile = true;
} else {
$is_mobile = false;
}
return $is_mobile;
}
/**
* 判定微信端
*/
function is_wechat()
{
static $is_wechat;
if (isset($is_wechat)) return $is_wechat;
if (empty($_SERVER['HTTP_USER_AGENT'])) {
$is_wechat = false;
} elseif (strpos($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger') !== false) {
$is_wechat = true;
} else {
$is_wechat = false;
}
return $is_wechat;
}
/**
* 转化 \ 为 /
*/
function dir_path($path)
{
$path = str_replace('\\', '/', $path);
if (substr($path, -1) != '/') $path = $path.'/';
return $path;
}
/**
* 递归创建目录
*/
function mkdirs($dir)
{
if (empty($dir)) return false;
if (!is_dir($dir)) {
mkdirs(dirname($dir));
mkdir($dir);
}
}
/**
* 删除目录及目录下面的所有文件
*/
function delete_dir($dir)
{
$dir = dir_path($dir);
if (!is_dir($dir)) return FALSE;
$list = glob($dir.'*');
foreach ($list as $v) {
is_dir($v) ? delete_dir($v) : @unlink($v);
}
return @rmdir($dir);
}
/**
* 写入缓存
*/
function set_cache($cache_file, $value)
{
if (!$cache_file) return false;
$cache_file = DATA_DIR.'cache'.DIRECTORY_SEPARATOR.$cache_file.'.cache.php';
$value = (!is_array($value)) ? serialize(trim($value)) : serialize($value);
//增加安全
$value = "<?php if (!defined('IN_IAEWEB')) exit(); ?>".$value;
if (!is_dir(DATA_DIR.'cache'.DIRECTORY_SEPARATOR)) {
mkdirs(DATA_DIR.'cache'.DIRECTORY_SEPARATOR);
}
return file_put_contents($cache_file, $value, LOCK_EX) ? true : false;
}
/**
* 获取缓存
*/
function get_cache($cache_file)
{
if (!$cache_file) return false;
static $cacheid = array();
if (!isset($cacheid[$cache_file])) {
$file = DATA_DIR.'cache'.DIRECTORY_SEPARATOR.$cache_file.'.cache.php';
if (is_file($file)) {
$value=str_replace("<?php if (!defined('IN_IAEWEB')) exit(); ?>", "", file_get_contents($file));
//$value = preg_replace('!s:(\d+):"(.*?)";!se', "'s:'.strlen('$2').':\"$2\";'", $value);
$cacheid[$cache_file] = unserialize($value);
} else {
return false;
}
}
return $cacheid[$cache_file];
}
/**
* 删除缓存
*/
function delete_cache($cache_file)
{
if (!$cache_file) return true;
$cache_file = DATA_DIR.'cache'.DIRECTORY_SEPARATOR.$cache_file.'.cache.php';
return is_file($cache_file) ? unlink($cache_file) : true;
}
/**
* 组装url
*/
function url($route, $params = null)
{
if (!$route) return false;
$arr = explode('/', $route);
$arr = array_diff($arr, array(''));
$url = 'index.php';
if (isset($arr[0]) && $arr[0]) {
$url .= '?c='.strtolower($arr[0]);
if (isset($arr[1]) && $arr[1] && $arr[1] != 'index') $url .= '&a='.strtolower($arr[1]);
}
if (!is_null($params) && is_array($params)) {
$params_url = array();
foreach ($params as $key => $value) {
$params_url[] = trim($key).'='.trim($value);
}
$url .= '&'.implode('&', $params_url);
}
$url = str_replace('//', '/', $url);
return Base::get_base_url().$url;
}
/* hbsion PLUS*/
/**
* 递归获取上级栏目路径
*/
function get_parent_dir($catid, $symbol = '/')
{
if (empty($catid)) return false;
$cats = get_cache('category');
$catids = parentids($catid, $cats);
$catids = array_filter(explode(',', $catids));
krsort($catids);
$catdirs = '';
foreach ($catids as $t) {
$catdirs .= $cats[$t]['catdir'];
if ($catid != $t) $catdirs .= $symbol;
}
return $catdirs;
}
/**
* 字符串替换一次
*/
function str_replace_once($needkeywords, $replacekeywords, $content)
{
$pos = strpos($content, $needkeywords);
if ($pos === false) {
return $content;
}
return substr_replace($content, $replacekeywords, $pos, strlen($needkeywords));
}
//计算年龄
function birthday($birthday)
{
$age = strtotime($birthday);
if ($age == false) {
return false;
}
list($y1, $m1, $d1) = explode("-", date("Y-m-d", $age));
$now = strtotime("now");
list($y2, $m2, $d2) = explode("-", date("Y-m-d", $now));
$age = $y2 - $y1;
if ((int)($m2.$d2) < (int)($m1.$d1)) $age -= 1;
return $age;
}
/* 采集 PLUS*/
require("spider.function.php");
|
apache-2.0
|
wildfly-swarm/wildfly-swarm-javadocs
|
2017.11.0/apidocs/org/wildfly/swarm/messaging/class-use/MessagingServer.html
|
8794
|
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (1.8.0_112) on Mon Nov 06 11:57:27 MST 2017 -->
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Uses of Class org.wildfly.swarm.messaging.MessagingServer (BOM: * : All 2017.11.0 API)</title>
<meta name="date" content="2017-11-06">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">
<script type="text/javascript" src="../../../../../script.js"></script>
</head>
<body>
<script type="text/javascript"><!--
try {
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Uses of Class org.wildfly.swarm.messaging.MessagingServer (BOM: * : All 2017.11.0 API)";
}
}
catch(err) {
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar.top">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.top.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../../org/wildfly/swarm/messaging/MessagingServer.html" title="class in org.wildfly.swarm.messaging">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../../../../../overview-tree.html">Tree</a></li>
<li><a href="../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../help-doc.html">Help</a></li>
</ul>
<div class="aboutLanguage">WildFly Swarm API, 2017.11.0</div>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../index.html?org/wildfly/swarm/messaging/class-use/MessagingServer.html" target="_top">Frames</a></li>
<li><a href="MessagingServer.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip.navbar.top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<div class="header">
<h2 title="Uses of Class org.wildfly.swarm.messaging.MessagingServer" class="title">Uses of Class<br>org.wildfly.swarm.messaging.MessagingServer</h2>
</div>
<div class="classUseContainer">
<ul class="blockList">
<li class="blockList">
<table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing packages, and an explanation">
<caption><span>Packages that use <a href="../../../../../org/wildfly/swarm/messaging/MessagingServer.html" title="class in org.wildfly.swarm.messaging">MessagingServer</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Package</th>
<th class="colLast" scope="col">Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><a href="#org.wildfly.swarm.messaging">org.wildfly.swarm.messaging</a></td>
<td class="colLast"> </td>
</tr>
</tbody>
</table>
</li>
<li class="blockList">
<ul class="blockList">
<li class="blockList"><a name="org.wildfly.swarm.messaging">
<!-- -->
</a>
<h3>Uses of <a href="../../../../../org/wildfly/swarm/messaging/MessagingServer.html" title="class in org.wildfly.swarm.messaging">MessagingServer</a> in <a href="../../../../../org/wildfly/swarm/messaging/package-summary.html">org.wildfly.swarm.messaging</a></h3>
<table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation">
<caption><span>Methods in <a href="../../../../../org/wildfly/swarm/messaging/package-summary.html">org.wildfly.swarm.messaging</a> that return <a href="../../../../../org/wildfly/swarm/messaging/MessagingServer.html" title="class in org.wildfly.swarm.messaging">MessagingServer</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><code><a href="../../../../../org/wildfly/swarm/messaging/MessagingServer.html" title="class in org.wildfly.swarm.messaging">MessagingServer</a></code></td>
<td class="colLast"><span class="typeNameLabel">MessagingServer.</span><code><span class="memberNameLink"><a href="../../../../../org/wildfly/swarm/messaging/MessagingServer.html#enableInVMConnector--">enableInVMConnector</a></span>()</code> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code><a href="../../../../../org/wildfly/swarm/messaging/MessagingServer.html" title="class in org.wildfly.swarm.messaging">MessagingServer</a></code></td>
<td class="colLast"><span class="typeNameLabel">MessagingServer.</span><code><span class="memberNameLink"><a href="../../../../../org/wildfly/swarm/messaging/MessagingServer.html#enableInVMConnector-java.lang.String-">enableInVMConnector</a></span>(<a href="http://docs.oracle.com/javase/8/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a> jndiName)</code> </td>
</tr>
<tr class="altColor">
<td class="colFirst"><code><a href="../../../../../org/wildfly/swarm/messaging/MessagingServer.html" title="class in org.wildfly.swarm.messaging">MessagingServer</a></code></td>
<td class="colLast"><span class="typeNameLabel">MessagingServer.</span><code><span class="memberNameLink"><a href="../../../../../org/wildfly/swarm/messaging/MessagingServer.html#queue-java.lang.String-">queue</a></span>(<a href="http://docs.oracle.com/javase/8/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a> name)</code> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code><a href="../../../../../org/wildfly/swarm/messaging/MessagingServer.html" title="class in org.wildfly.swarm.messaging">MessagingServer</a></code></td>
<td class="colLast"><span class="typeNameLabel">MessagingServer.</span><code><span class="memberNameLink"><a href="../../../../../org/wildfly/swarm/messaging/MessagingServer.html#topic-java.lang.String-">topic</a></span>(<a href="http://docs.oracle.com/javase/8/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a> name)</code> </td>
</tr>
</tbody>
</table>
</li>
</ul>
</li>
</ul>
</div>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar.bottom">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.bottom.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../../org/wildfly/swarm/messaging/MessagingServer.html" title="class in org.wildfly.swarm.messaging">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../../../../../overview-tree.html">Tree</a></li>
<li><a href="../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../help-doc.html">Help</a></li>
</ul>
<div class="aboutLanguage">WildFly Swarm API, 2017.11.0</div>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../index.html?org/wildfly/swarm/messaging/class-use/MessagingServer.html" target="_top">Frames</a></li>
<li><a href="MessagingServer.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip.navbar.bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<p class="legalCopy"><small>Copyright © 2017 <a href="http://www.jboss.org">JBoss by Red Hat</a>. All rights reserved.</small></p>
</body>
</html>
|
apache-2.0
|
RISBIC/DataBroker
|
metadata-ws/src/main/java/com/arjuna/databroker/metadata/client/ContentProxy.java
|
1572
|
/*
* Copyright (c) 2013-2015, Arjuna Technologies Limited, Newcastle-upon-Tyne, England. All rights reserved.
*/
package com.arjuna.databroker.metadata.client;
import java.util.List;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
public interface ContentProxy
{
@GET
@Path("contents")
@Produces(MediaType.APPLICATION_JSON)
public List<String> listMetadata(@QueryParam("requesterId") String requesterId, @QueryParam("userId") String userId);
@GET
@Path("/content/{id}")
@Produces(MediaType.TEXT_PLAIN)
public String getMetadata(@PathParam("id") String id, @QueryParam("requesterId") String requesterId, @QueryParam("userId") String userId);
@POST
@Path("/contents")
@Consumes(MediaType.APPLICATION_JSON)
public String postMetadata(@QueryParam("requesterId") String requesterId, @QueryParam("userId") String userId, String content);
@POST
@Path("/contents")
@Consumes(MediaType.APPLICATION_JSON)
public String postMetadata(@QueryParam("parentId") String parentId, @QueryParam("requesterId") String requesterId, @QueryParam("userId") String userId, String content);
@PUT
@Path("/content/{id}")
@Consumes(MediaType.TEXT_PLAIN)
public void putMetadata(@PathParam("id") String id, @QueryParam("requesterId") String requesterId, @QueryParam("userId") String userId, String content);
}
|
apache-2.0
|
aws/aws-sdk-java
|
aws-java-sdk-devopsguru/src/main/java/com/amazonaws/services/devopsguru/model/ThrottlingException.java
|
5545
|
/*
* Copyright 2017-2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
package com.amazonaws.services.devopsguru.model;
import javax.annotation.Generated;
/**
* <p>
* The request was denied due to a request throttling.
* </p>
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class ThrottlingException extends com.amazonaws.services.devopsguru.model.AmazonDevOpsGuruException {
private static final long serialVersionUID = 1L;
/**
* <p>
* The code of the quota that was exceeded, causing the throttling exception.
* </p>
*/
private String quotaCode;
/**
* <p>
* The code of the service that caused the throttling exception.
* </p>
*/
private String serviceCode;
/**
* <p>
* The number of seconds after which the action that caused the throttling exception can be retried.
* </p>
*/
private Integer retryAfterSeconds;
/**
* Constructs a new ThrottlingException with the specified error message.
*
* @param message
* Describes the error encountered.
*/
public ThrottlingException(String message) {
super(message);
}
/**
* <p>
* The code of the quota that was exceeded, causing the throttling exception.
* </p>
*
* @param quotaCode
* The code of the quota that was exceeded, causing the throttling exception.
*/
@com.fasterxml.jackson.annotation.JsonProperty("QuotaCode")
public void setQuotaCode(String quotaCode) {
this.quotaCode = quotaCode;
}
/**
* <p>
* The code of the quota that was exceeded, causing the throttling exception.
* </p>
*
* @return The code of the quota that was exceeded, causing the throttling exception.
*/
@com.fasterxml.jackson.annotation.JsonProperty("QuotaCode")
public String getQuotaCode() {
return this.quotaCode;
}
/**
* <p>
* The code of the quota that was exceeded, causing the throttling exception.
* </p>
*
* @param quotaCode
* The code of the quota that was exceeded, causing the throttling exception.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public ThrottlingException withQuotaCode(String quotaCode) {
setQuotaCode(quotaCode);
return this;
}
/**
* <p>
* The code of the service that caused the throttling exception.
* </p>
*
* @param serviceCode
* The code of the service that caused the throttling exception.
*/
@com.fasterxml.jackson.annotation.JsonProperty("ServiceCode")
public void setServiceCode(String serviceCode) {
this.serviceCode = serviceCode;
}
/**
* <p>
* The code of the service that caused the throttling exception.
* </p>
*
* @return The code of the service that caused the throttling exception.
*/
@com.fasterxml.jackson.annotation.JsonProperty("ServiceCode")
public String getServiceCode() {
return this.serviceCode;
}
/**
* <p>
* The code of the service that caused the throttling exception.
* </p>
*
* @param serviceCode
* The code of the service that caused the throttling exception.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public ThrottlingException withServiceCode(String serviceCode) {
setServiceCode(serviceCode);
return this;
}
/**
* <p>
* The number of seconds after which the action that caused the throttling exception can be retried.
* </p>
*
* @param retryAfterSeconds
* The number of seconds after which the action that caused the throttling exception can be retried.
*/
@com.fasterxml.jackson.annotation.JsonProperty("Retry-After")
public void setRetryAfterSeconds(Integer retryAfterSeconds) {
this.retryAfterSeconds = retryAfterSeconds;
}
/**
* <p>
* The number of seconds after which the action that caused the throttling exception can be retried.
* </p>
*
* @return The number of seconds after which the action that caused the throttling exception can be retried.
*/
@com.fasterxml.jackson.annotation.JsonProperty("Retry-After")
public Integer getRetryAfterSeconds() {
return this.retryAfterSeconds;
}
/**
* <p>
* The number of seconds after which the action that caused the throttling exception can be retried.
* </p>
*
* @param retryAfterSeconds
* The number of seconds after which the action that caused the throttling exception can be retried.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public ThrottlingException withRetryAfterSeconds(Integer retryAfterSeconds) {
setRetryAfterSeconds(retryAfterSeconds);
return this;
}
}
|
apache-2.0
|
stratis-storage/stratis-cli
|
src/stratis_cli/_parser/_physical.py
|
1060
|
# Copyright 2016 Red Hat, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
Definition of block device actions to display in the CLI.
"""
from .._actions import PhysicalActions
PHYSICAL_SUBCMDS = [
(
"list",
dict(
help="List information about blockdevs in the pool",
args=[
(
"pool_name",
dict(action="store", default=None, nargs="?", help="Pool name"),
)
],
func=PhysicalActions.list_devices,
),
)
]
|
apache-2.0
|
UniversalDependencies/universaldependencies.github.io
|
treebanks/sk_snk/sk_snk-dep-csubj-pass.html
|
11649
|
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html lang="en-GB" xml:lang="en-GB" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<title>Statistics of csubj:pass in UD_Slovak-SNK</title>
<link rel="root" href=""/> <!-- for JS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css">
<link rel="stylesheet" type="text/css" href="../../css/jquery-ui-redmond.css"/>
<link rel="stylesheet" type="text/css" href="../../css/style.css"/>
<link rel="stylesheet" type="text/css" href="../../css/style-vis.css"/>
<link rel="stylesheet" type="text/css" href="../../css/hint.css"/>
<script type="text/javascript" src="../../lib/ext/head.load.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/anchor-js/3.2.2/anchor.min.js"></script>
<script>document.addEventListener("DOMContentLoaded", function(event) {anchors.add();});</script>
<!-- Set up this custom Google search at https://cse.google.com/cse/business/settings?cx=001145188882102106025:dl1mehhcgbo -->
<!-- DZ 2021-01-22: I am temporarily hiding the search field to find out whether it slows down loading of the title page.
<script>
(function() {
var cx = '001145188882102106025:dl1mehhcgbo';
var gcse = document.createElement('script');
gcse.type = 'text/javascript';
gcse.async = true;
gcse.src = 'https://cse.google.com/cse.js?cx=' + cx;
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(gcse, s);
})();
</script> -->
<!-- <link rel="shortcut icon" href="favicon.ico"/> -->
</head>
<body>
<div id="main" class="center">
<div id="hp-header">
<table width="100%"><tr><td width="50%">
<span class="header-text"><a href="http://universaldependencies.org/#language-">home</a></span>
<span class="header-text"><a href="https://github.com/universaldependencies/docs/edit/pages-source/treebanks/sk_snk/sk_snk-dep-csubj-pass.md" target="#">edit page</a></span>
<span class="header-text"><a href="https://github.com/universaldependencies/docs/issues">issue tracker</a></span>
</td><td>
<gcse:search></gcse:search>
</td></tr></table>
</div>
<hr/>
<div class="v2complete">
This page pertains to UD version 2.
</div>
<div id="content">
<noscript>
<div id="noscript">
It appears that you have Javascript disabled.
Please consider enabling Javascript for this page to see the visualizations.
</div>
</noscript>
<!-- The content may include scripts and styles, hence we must load the shared libraries before the content. -->
<script type="text/javascript">
console.time('loading libraries');
var root = '../../'; // filled in by jekyll
head.js(
// External libraries
// DZ: Copied from embedding.html. I don't know which one is needed for what, so I'm currently keeping them all.
root + 'lib/ext/jquery.min.js',
root + 'lib/ext/jquery.svg.min.js',
root + 'lib/ext/jquery.svgdom.min.js',
root + 'lib/ext/jquery.timeago.js',
root + 'lib/ext/jquery-ui.min.js',
root + 'lib/ext/waypoints.min.js',
root + 'lib/ext/jquery.address.min.js'
);
</script>
<h2 id="treebank-statistics-ud_slovak-snk-relations-csubjpass">Treebank Statistics: UD_Slovak-SNK: Relations: <code class="language-plaintext highlighter-rouge">csubj:pass</code></h2>
<p>This relation is a language-specific subtype of <tt><a href="sk_snk-dep-csubj.html">csubj</a></tt>.</p>
<p>21 nodes (0%) are attached to their parents as <code class="language-plaintext highlighter-rouge">csubj:pass</code>.</p>
<p>21 instances of <code class="language-plaintext highlighter-rouge">csubj:pass</code> (100%) are left-to-right (parent precedes child).
Average distance between parent and child is 5.57142857142857.</p>
<p>The following 4 pairs of parts of speech are connected with <code class="language-plaintext highlighter-rouge">csubj:pass</code>: <tt><a href="sk_snk-pos-VERB.html">VERB</a></tt>-<tt><a href="sk_snk-pos-VERB.html">VERB</a></tt> (15; 71% instances), <tt><a href="sk_snk-pos-VERB.html">VERB</a></tt>-<tt><a href="sk_snk-pos-NOUN.html">NOUN</a></tt> (3; 14% instances), <tt><a href="sk_snk-pos-VERB.html">VERB</a></tt>-<tt><a href="sk_snk-pos-ADJ.html">ADJ</a></tt> (2; 10% instances), <tt><a href="sk_snk-pos-ADJ.html">ADJ</a></tt>-<tt><a href="sk_snk-pos-VERB.html">VERB</a></tt> (1; 5% instances).</p>
<pre><code class="language-conllu"># visual-style 8 bgColor:blue
# visual-style 8 fgColor:white
# visual-style 1 bgColor:blue
# visual-style 1 fgColor:white
# visual-style 1 8 csubj:pass color:blue
1 Zdalo zdať VERB VLescn+ Aspect=Imp|Gender=Neut|Number=Sing|Polarity=Pos|Tense=Past|VerbForm=Part 0 root 0:root _
2 sa sa PRON R PronType=Prs|Reflex=Yes 1 expl:pass 1:expl:pass _
3 mu on PRON PFms3 Animacy=Anim|Case=Dat|Gender=Masc|Number=Sing|Person=3|PronType=Prs 1 obl:arg 1:obl:arg:dat SpaceAfter=No
4 , , PUNCT Z _ 8 punct 8:punct _
5 že že SCONJ O _ 8 mark 8:mark _
6 na na ADP Eu4 AdpType=Prep|Case=Acc 7 case 7:case _
7 neho on PRON PFis4 Animacy=Inan|Case=Acc|Gender=Masc|Number=Sing|PronType=Prs 8 obj 8:obj _
8 čakal čakať VERB VLescm+ Animacy=Anim|Aspect=Imp|Gender=Masc|Number=Sing|Polarity=Pos|Tense=Past|VerbForm=Part 1 csubj:pass 1:csubj:pass _
9 celý celý ADJ AAis4x Animacy=Inan|Case=Acc|Degree=Pos|Gender=Masc|Number=Sing 10 amod 10:amod _
10 život život NOUN SSis4 Animacy=Inan|Case=Acc|Gender=Masc|Number=Sing 8 obl 8:obl:acc SpaceAfter=No
11 . . PUNCT Z _ 1 punct 1:punct _
</code></pre>
<pre><code class="language-conllu"># visual-style 8 bgColor:blue
# visual-style 8 fgColor:white
# visual-style 1 bgColor:blue
# visual-style 1 fgColor:white
# visual-style 1 8 csubj:pass color:blue
1 Predpokladá predpokladať VERB VKesc+ Aspect=Imp|Mood=Ind|Number=Sing|Person=3|Polarity=Pos|Tense=Pres|VerbForm=Fin 0 root 0:root _
2 sa sa PRON R PronType=Prs|Reflex=Yes 1 expl:pass 1:expl:pass SpaceAfter=No
3 , , PUNCT Z _ 8 punct 8:punct _
4 že že SCONJ O _ 8 mark 8:mark _
5 toto toto DET PFns1 Case=Nom|Gender=Neut|Number=Sing|PronType=Dem 6 det 6:det _
6 hélium hélium NOUN SSns1 Case=Nom|Gender=Neut|Number=Sing 8 nsubj 8:nsubj _
7 je byť AUX VKesc+ Aspect=Imp|Mood=Ind|Number=Sing|Person=3|Polarity=Pos|Tense=Pres|VerbForm=Fin 8 cop 8:cop _
8 produktom produkt NOUN SSis7 Animacy=Inan|Case=Ins|Gender=Masc|Number=Sing 1 csubj:pass 1:csubj:pass _
9 jadrového jadrový ADJ AAis2x Animacy=Inan|Case=Gen|Degree=Pos|Gender=Masc|Number=Sing 10 amod 10:amod _
10 rozpadu rozpad NOUN SSis2 Animacy=Inan|Case=Gen|Gender=Masc|Number=Sing 8 nmod 8:nmod:gen _
11 prvkov prvok NOUN SSip2 Animacy=Inan|Case=Gen|Gender=Masc|Number=Plur 10 nmod 10:nmod:gen _
12 v v ADP Eu6 AdpType=Prep|Case=Loc 14 case 14:case _
13 zemskej zemský ADJ AAfs6x Case=Loc|Degree=Pos|Gender=Fem|Number=Sing 14 amod 14:amod _
14 kôre kôra NOUN SSfs6 Case=Loc|Gender=Fem|Number=Sing 11 nmod 11:nmod:v:loc SpaceAfter=No
15 . . PUNCT Z _ 1 punct 1:punct _
</code></pre>
<pre><code class="language-conllu"># visual-style 14 bgColor:blue
# visual-style 14 fgColor:white
# visual-style 8 bgColor:blue
# visual-style 8 fgColor:white
# visual-style 8 14 csubj:pass color:blue
1 Navštívil navštíviť VERB VLdscm+ Animacy=Anim|Aspect=Perf|Gender=Masc|Number=Sing|Polarity=Pos|Tense=Past|VerbForm=Part 0 root 0:root _
2 mešitu mešita NOUN SSfs4 Case=Acc|Gender=Fem|Number=Sing 1 obj 1:obj|8:obl:arg:o:loc _
3 Umajjovcov umajjovec PROPN SSmp2:r Animacy=Anim|Case=Gen|Gender=Masc|Number=Plur 2 nmod 2:nmod:gen SpaceAfter=No
4 , , PUNCT Z _ 8 punct 8:punct _
5 o o ADP Eu6 AdpType=Prep|Case=Loc 6 case 6:case _
6 ktorej ktorý DET PAfs6 Case=Loc|Gender=Fem|Number=Sing|PronType=Int,Rel 8 obl:arg 2:ref _
7 sa sa PRON R PronType=Prs|Reflex=Yes 8 expl:pass 8:expl:pass _
8 predpokladá predpokladať VERB VKesc+ Aspect=Imp|Mood=Ind|Number=Sing|Person=3|Polarity=Pos|Tense=Pres|VerbForm=Fin 2 acl:relcl 2:acl:relcl SpaceAfter=No
9 , , PUNCT Z _ 14 punct 14:punct _
10 že že SCONJ O _ 14 mark 14:mark _
11 je byť AUX VKesc+ Aspect=Imp|Mood=Ind|Number=Sing|Person=3|Polarity=Pos|Tense=Pres|VerbForm=Fin 14 cop 14:cop _
12 v v ADP Eu6 AdpType=Prep|Case=Loc 13 case 13:case _
13 nej ona PRON PFfs6 Case=Loc|Gender=Fem|Number=Sing|Person=3|PronType=Prs 14 obl 14:obl:v:loc _
14 pochovaný pochovaný ADJ Gtms1x Animacy=Anim|Case=Nom|Degree=Pos|Gender=Masc|Number=Sing|Polarity=Pos|VerbForm=Part|Voice=Pass 8 csubj:pass 8:csubj:pass _
15 aj aj CCONJ O _ 17 advmod:emph 17:advmod:emph _
16 Ján ján PROPN SSms1:r Animacy=Anim|Case=Nom|Gender=Masc|Number=Sing 17 nmod 17:nmod:nom _
17 Krstiteľ krstiteľ PROPN SSms1:r Animacy=Anim|Case=Nom|Gender=Masc|Number=Sing 14 nsubj 14:nsubj SpaceAfter=No
18 . . PUNCT Z _ 1 punct 1:punct _
</code></pre>
</div>
<!-- support for embedded visualizations -->
<script type="text/javascript">
var root = '../../'; // filled in by jekyll
head.js(
// We assume that external libraries such as jquery.min.js have already been loaded outside!
// (See _layouts/base.html.)
// brat helper modules
root + 'lib/brat/configuration.js',
root + 'lib/brat/util.js',
root + 'lib/brat/annotation_log.js',
root + 'lib/ext/webfont.js',
// brat modules
root + 'lib/brat/dispatcher.js',
root + 'lib/brat/url_monitor.js',
root + 'lib/brat/visualizer.js',
// embedding configuration
root + 'lib/local/config.js',
// project-specific collection data
root + 'lib/local/collections.js',
// Annodoc
root + 'lib/annodoc/annodoc.js',
// NOTE: non-local libraries
'https://spyysalo.github.io/conllu.js/conllu.js'
);
var webFontURLs = [
// root + 'static/fonts/Astloch-Bold.ttf',
root + 'static/fonts/PT_Sans-Caption-Web-Regular.ttf',
root + 'static/fonts/Liberation_Sans-Regular.ttf'
];
var setupTimeago = function() {
jQuery("time.timeago").timeago();
};
head.ready(function() {
setupTimeago();
// mark current collection (filled in by Jekyll)
Collections.listing['_current'] = '';
// perform all embedding and support functions
Annodoc.activate(Config.bratCollData, Collections.listing);
});
</script>
<!-- google analytics -->
<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-55233688-1', 'auto');
ga('send', 'pageview');
</script>
<div id="footer">
<p class="footer-text">© 2014–2021
<a href="http://universaldependencies.org/introduction.html#contributors" style="color:gray">Universal Dependencies contributors</a>.
Site powered by <a href="http://spyysalo.github.io/annodoc" style="color:gray">Annodoc</a> and <a href="http://brat.nlplab.org/" style="color:gray">brat</a></p>.
</div>
</div>
</body>
</html>
|
apache-2.0
|
zhou-dong/probabilistic-graphical-models
|
src/org/dongzhou/rescueTime/ApiUtil.java
|
767
|
package org.dongzhou.rescueTime;
import java.net.URI;
import java.net.URISyntaxException;
import org.apache.http.client.methods.RequestBuilder;
import org.apache.log4j.Logger;
public class ApiUtil {
private static Logger logger = Logger.getLogger(ApiUtil.class.getName());
private static final String KEY = "B63vb_55nMqMqfDXcvoNJQqYcavyMlGnClMPRLeT";
public static RequestBuilder createRequestBuilder(String uri) {
return createRequestBuilder(createURI(uri));
}
private static RequestBuilder createRequestBuilder(URI uri) {
return RequestBuilder.get().setUri(uri).addParameter("key", KEY);
}
private static URI createURI(String uri) {
try {
return new URI(uri);
} catch (URISyntaxException e) {
logger.error(e);
return null;
}
}
}
|
apache-2.0
|
Kellel/alertmanager
|
cli/config.go
|
1698
|
// Copyright 2018 Prometheus Team
// 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 cli
import (
"context"
"errors"
"github.com/prometheus/client_golang/api"
"gopkg.in/alecthomas/kingpin.v2"
"github.com/prometheus/alertmanager/cli/format"
"github.com/prometheus/alertmanager/client"
)
const configHelp = `View current config.
The amount of output is controlled by the output selection flag:
- Simple: Print just the running config
- Extended: Print the running config as well as uptime and all version info
- Json: Print entire config object as json
`
// configCmd represents the config command
func configureConfigCmd(app *kingpin.Application) {
app.Command("config", configHelp).Action(queryConfig).PreAction(requireAlertManagerURL)
}
func queryConfig(ctx *kingpin.ParseContext) error {
c, err := api.NewClient(api.Config{Address: alertmanagerURL.String()})
if err != nil {
return err
}
statusAPI := client.NewStatusAPI(c)
status, err := statusAPI.Get(context.Background())
if err != nil {
return err
}
formatter, found := format.Formatters[output]
if !found {
return errors.New("unknown output formatter")
}
return formatter.FormatConfig(status)
}
|
apache-2.0
|
yangyining/JFinal-plus
|
src/main/java/com/janeluo/jfinalplus/kit/ReflectException.java
|
2843
|
/**
* Copyright (c) 2011-2013, Lukas Eder, [email protected]
* All rights reserved.
*
* This software is licensed to you under the Apache License, Version 2.0
* (the "License"); You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* 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 "jOOR" nor the names of its contributors may be
* used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
package com.janeluo.jfinalplus.kit;
import java.lang.reflect.InvocationTargetException;
/**
* A unchecked wrapper for any of Java's checked reflection exceptions:
* <p>
* These exceptions are
* <ul>
* <li> {@link ClassNotFoundException}</li>
* <li> {@link IllegalAccessException}</li>
* <li> {@link IllegalArgumentException}</li>
* <li> {@link InstantiationException}</li>
* <li> {@link InvocationTargetException}</li>
* <li> {@link NoSuchMethodException}</li>
* <li> {@link NoSuchFieldException}</li>
* <li> {@link SecurityException}</li>
* </ul>
*
* @author Lukas Eder
*/
public class ReflectException extends RuntimeException {
/**
* Generated UID
*/
private static final long serialVersionUID = -6213149635297151442L;
public ReflectException(String message) {
super(message);
}
public ReflectException(String message, Throwable cause) {
super(message, cause);
}
public ReflectException() {
super();
}
public ReflectException(Throwable cause) {
super(cause);
}
}
|
apache-2.0
|
dbflute-session/erflute
|
src/org/dbflute/erflute/db/DBManagerBase.java
|
5834
|
package org.dbflute.erflute.db;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.Driver;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.List;
import java.util.ResourceBundle;
import java.util.Set;
import java.util.StringTokenizer;
import org.dbflute.erflute.core.util.Check;
import org.dbflute.erflute.editor.model.settings.JDBCDriverSetting;
import org.dbflute.erflute.preference.PreferenceInitializer;
import org.dbflute.erflute.preference.jdbc.JDBCPathDialog;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.ui.PlatformUI;
/**
* @author modified by jflute (originated in ermaster)
*/
public abstract class DBManagerBase implements DBManager {
private final Set<String> reservedWords;
public DBManagerBase() {
DBManagerFactory.addDB(this);
this.reservedWords = getReservedWords();
}
@Override
public String getURL(String serverName, String dbName, int port) {
String temp = serverName.replaceAll("\\\\", "\\\\\\\\");
String url = getURL().replaceAll("<SERVER NAME>", temp);
url = url.replaceAll("<PORT>", String.valueOf(port));
temp = dbName.replaceAll("\\\\", "\\\\\\\\");
url = url.replaceAll("<DB NAME>", temp);
return url;
}
@Override
public Class<Driver> getDriverClass(String driverClassName) {
String path = null;
try {
try {
@SuppressWarnings("unchecked")
final Class<Driver> clazz = (Class<Driver>) Class.forName(driverClassName);
return clazz;
} catch (final ClassNotFoundException e) {
path = PreferenceInitializer.getJDBCDriverPath(getId(), driverClassName);
if (Check.isEmpty(path)) {
throw new IllegalStateException(
String.format("JDBC Driver Class \"%s\" is not found.\rIs \"Preferences> ERFlute> JDBC Driver\" set correctly?",
driverClassName));
}
final ClassLoader loader = getClassLoader(path);
@SuppressWarnings("unchecked")
final Class<Driver> clazz = (Class<Driver>) loader.loadClass(driverClassName);
return clazz;
}
} catch (final MalformedURLException | ClassNotFoundException e) {
final JDBCPathDialog dialog = new JDBCPathDialog(
PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(),
getId(), driverClassName, path, new ArrayList<JDBCDriverSetting>(), false);
if (dialog.open() == IDialogConstants.OK_ID) {
final JDBCDriverSetting newDriverSetting =
new JDBCDriverSetting(getId(), dialog.getDriverClassName(), dialog.getPath());
final List<JDBCDriverSetting> driverSettingList = PreferenceInitializer.getJDBCDriverSettingList();
if (driverSettingList.contains(newDriverSetting)) {
driverSettingList.remove(newDriverSetting);
}
driverSettingList.add(newDriverSetting);
PreferenceInitializer.saveJDBCDriverSettingList(driverSettingList);
return getDriverClass(dialog.getDriverClassName());
}
}
return null;
}
private ClassLoader getClassLoader(String uri) throws MalformedURLException {
final StringTokenizer tokenizer = new StringTokenizer(uri, ";");
final int count = tokenizer.countTokens();
final URL[] urls = new URL[count];
for (int i = 0; i < urls.length; i++) {
urls[i] = new URL("file", "", tokenizer.nextToken());
}
return new URLClassLoader(urls, getClass().getClassLoader());
}
protected abstract String getURL();
@Override
public abstract String getDriverClassName();
protected Set<String> getReservedWords() {
final Set<String> reservedWords = new HashSet<>();
final ResourceBundle bundle = ResourceBundle.getBundle(getClass().getPackage().getName() + ".reserved_word");
final Enumeration<String> keys = bundle.getKeys();
while (keys.hasMoreElements()) {
reservedWords.add(keys.nextElement().toUpperCase());
}
return reservedWords;
}
@Override
public boolean isReservedWord(String str) {
return reservedWords.contains(str.toUpperCase());
}
@Override
public boolean isSupported(int supportItem) {
final int[] supportItems = getSupportItems();
for (int i = 0; i < supportItems.length; i++) {
if (supportItems[i] == supportItem) {
return true;
}
}
return false;
}
@Override
public boolean doesNeedURLDatabaseName() {
return true;
}
@Override
public boolean doesNeedURLServerName() {
return true;
}
abstract protected int[] getSupportItems();
@Override
public List<String> getImportSchemaList(Connection con) throws SQLException {
final List<String> schemaList = new ArrayList<>();
final DatabaseMetaData metaData = con.getMetaData();
try {
final ResultSet rs = metaData.getSchemas();
while (rs.next()) {
schemaList.add(rs.getString(1));
}
} catch (final SQLException ignored) {
// when schema is not supported
}
return schemaList;
}
@Override
public List<String> getSystemSchemaList() {
return new ArrayList<>();
}
}
|
apache-2.0
|
CenturyLinkCloud/mdw
|
mdw-common/src/com/centurylink/mdw/model/request/HandlerSpec.java
|
1912
|
package com.centurylink.mdw.model.request;
import com.centurylink.mdw.model.Jsonable;
import com.centurylink.mdw.xml.XmlPath;
import org.apache.xmlbeans.XmlException;
/**
* Request handler spec.
* TODO: JSONPath
*/
public class HandlerSpec implements Comparable<HandlerSpec>, Jsonable {
private String name;
public String getName() { return name; }
public void setName(String name) { this.name = name; }
private final String handlerClass;
public String getHandlerClass() { return handlerClass; }
private String path;
public String getPath() { return path; }
public void setPath(String path) { this.path = path; }
private boolean contentRouting = true;
public boolean isContentRouting() { return contentRouting; }
public void setContentRouting(boolean contentRouting) { this.contentRouting = contentRouting; }
public HandlerSpec(String name, String handlerClass) {
this.name = name;
this.handlerClass = handlerClass;
}
private XmlPath xpath;
public XmlPath getXpath() throws XmlException {
if (xpath == null)
xpath = new XmlPath(path);
return xpath;
}
private String assetPath;
public String getAssetPath() { return assetPath; }
public void setAssetPath(String assetPath) { this.assetPath = assetPath; }
@Override
public int compareTo(HandlerSpec other) {
if (handlerClass.equals(other.handlerClass))
return path.compareToIgnoreCase(other.handlerClass);
else
return handlerClass.compareToIgnoreCase(other.handlerClass);
}
@Override
public String toString() {
return path + " -> " + handlerClass;
}
@Override
public boolean equals(Object other) {
return this.toString().equals(other.toString());
}
@Override
public int hashCode() {
return toString().hashCode();
}
}
|
apache-2.0
|
sevoan/Carbon
|
samples/src/main/java/tk/zielony/carbonsamples/applibrary/RecyclerCardsActivity.java
|
1051
|
package tk.zielony.carbonsamples.applibrary;
import android.app.Activity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import java.util.Arrays;
import java.util.List;
import carbon.widget.RecyclerView;
import tk.zielony.carbonsamples.R;
/**
* Created by Marcin on 2014-12-15.
*/
public class RecyclerCardsActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_recycler_cards);
List<ViewModel> items = Arrays.asList(new ViewModel(), new ViewModel(), new ViewModel(), new ViewModel(), new ViewModel(), new ViewModel(), new ViewModel());
RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
recyclerView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
recyclerView.setAdapter(new RecyclerAdapter(items, R.layout.card));
recyclerView.setHeader(R.layout.header_scrollview);
}
}
|
apache-2.0
|
NoJPA-LESS-IS-MORE/NoJPA
|
nojpa_common/src/main/java/dk/lessismore/nojpa/net/link/ClientLink.java
|
687
|
package dk.lessismore.nojpa.net.link;
import dk.lessismore.nojpa.serialization.Serializer;
import java.net.Socket;
import java.io.IOException;
public class ClientLink extends AbstractLink {
public ClientLink(String serverName, int port) throws IOException {
this(serverName, port, null);
}
public ClientLink(String serverName, int port, Serializer serializer) throws IOException {
super(serializer);
socket = new Socket(serverName, port);
socket.setKeepAlive(true);
socket.setSoTimeout(0); // This implies that a read call will block forever.
in = socket.getInputStream();
out = socket.getOutputStream();
}
}
|
apache-2.0
|
HiddenStage/divide
|
Client/mock-client/src/main/java/io/divide/client/auth/MockKeyManager.java
|
1473
|
/*
* Copyright (C) 2014 Divide.io
*
* 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 io.divide.client.auth;
import io.divide.shared.server.KeyManager;
import io.divide.shared.util.Crypto;
import java.security.KeyPair;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
public class MockKeyManager implements KeyManager {
private String encryptionKey;
private String pushKey;
private KeyPair keyPair;
public MockKeyManager(String encryptionKey) throws NoSuchAlgorithmException {
this.encryptionKey = encryptionKey;
this.keyPair = Crypto.getNew();
}
public PublicKey getPublicKey(){
return keyPair.getPublic();
}
public PrivateKey getPrivateKey(){
return keyPair.getPrivate();
}
public String getSymmetricKey(){
return encryptionKey;
}
public String getPushKey() {
return pushKey;
}
}
|
apache-2.0
|
TravisFSmith/SweetSecurity
|
apache/flask/webapp/es.py
|
1377
|
def write(es,body,index,doc_type):
try:
res = es.index(index=index, doc_type=doc_type, body=body)
return res
except Exception, e:
return e
def search(es,body,index,doc_type,size=None):
if size is None:
size=1000
try:
res = es.search(index=index, doc_type=doc_type, body=body, size=size)
return res
except Exception, e:
return None
def update(es,body,index,doc_type,id):
res = es.update(index=index, id=id, doc_type=doc_type, body=body)
return res
def delete(es,index,doc_type,id):
res = es.delete(index=index,doc_type=doc_type,id=id)
return res
def compare(d1,d2):
d1_keys = set(d1.keys())
d2_keys = set(d2.keys())
intersect_keys = d1_keys.intersection(d2_keys)
compared = {o : (d1[o], d2[o]) for o in intersect_keys if d1[o] != d2[o]}
return compared
def consolidate(mac,es,type):
device1={}
deviceQuery = {"query": {"match_phrase": {"mac": { "query": mac }}}}
deviceInfo=search(es, deviceQuery, 'sweet_security', type)
for device in deviceInfo['hits']['hits']:
if len(device1) > 0:
modifiedInfo = compare(device1['_source'],device['_source'])
#usually just two, but we'll keep the oldest one, since that one has probably been modified
if modifiedInfo['firstSeen'][0] < modifiedInfo['firstSeen'][1]:
deleteID=device['_id']
else:
deleteID=device1['_id']
delete(es,'sweet_security',type,deleteID)
device1=device
|
apache-2.0
|
BottleRocketStudios/Android-Continuity
|
ContinuitySample/app/src/main/java/com/bottlerocketstudios/continuitysample/core/application/ContinuitySampleApplication.java
|
1583
|
package com.bottlerocketstudios.continuitysample.core.application;
import android.app.Application;
import android.databinding.DataBindingUtil;
import com.bottlerocketstudios.continuitysample.core.databinding.PicassoDataBindingComponent;
import com.bottlerocketstudios.continuitysample.core.injection.ServiceInitializer;
import com.bottlerocketstudios.groundcontrol.convenience.GroundControl;
public class ContinuitySampleApplication extends Application {
@Override
public void onCreate() {
super.onCreate();
//Avoid adding a whole DI framework and all of that just to keep a few objects around.
ServiceInitializer.initializeContext(this);
/**
* Set the default component for DataBinding to use Picasso. This could also be GlideDataBindingComponent();
* If there is an actual need to decide at launch which DataBindingComponent to use, it can be done here.
* Avoid repeatedly calling setDefaultComponent to switch on the fly. It will cause your application
* to behave unpredictably and is not thread safe. If a different DataBindingComponent is needed for a
* specific layout, you can specify that DataBindingComponent when you inflate the layout/setContentView.
*/
DataBindingUtil.setDefaultComponent(new PicassoDataBindingComponent());
/**
* GroundControl's default UI policy will use a built in cache. It isn't necessary and actually
* causes confusion as the Presenters serve this role.
*/
GroundControl.disableCache();
}
}
|
apache-2.0
|
csm-aut/csm
|
csmserver/work_units/convert_config_work_unit.py
|
3413
|
import subprocess
from constants import get_migration_directory, JobStatus
from models import ConvertConfigJob
from multi_process import WorkUnit
import os
import re
NOX_64_BINARY = "nox-linux-64.bin"
NOX_64_MAC = "nox-mac64.bin"
class ConvertConfigWorkUnit(WorkUnit):
def __init__(self, job_id):
WorkUnit.__init__(self)
self.job_id = job_id
def start(self, db_session, logger, process_name):
self.db_session = db_session
try:
self.convert_config_job = self.db_session.query(ConvertConfigJob).filter(ConvertConfigJob.id ==
self.job_id).first()
if self.convert_config_job is None:
logger.error('Unable to retrieve convert config job: %s' % self.job_id)
return
self.convert_config_job.set_status("Converting the configurations")
self.db_session.commit()
file_path = self.convert_config_job.file_path
nox_to_use = get_migration_directory() + NOX_64_BINARY
# nox_to_use = get_migration_directory() + NOX_64_MAC
print "start executing nox conversion..."
try:
commands = [subprocess.Popen(["chmod", "+x", nox_to_use]),
subprocess.Popen([nox_to_use, "-f", file_path],
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
]
nox_output, nox_error = commands[1].communicate()
print "the nox finished its job."
except OSError:
self.convert_config_job.set_status(JobStatus.FAILED)
self.db_session.commit()
logger.exception("Running the configuration migration tool " +
"{} on config file {} hit OSError.".format(nox_to_use, file_path))
conversion_successful = False
if nox_error:
self.convert_config_job.set_status(JobStatus.FAILED)
self.db_session.commit()
logger.exception("Running the configuration migration tool {} ".format(nox_to_use) +
"on config file {} hit error:\n {}".format(file_path, nox_error))
if re.search("Done \[.*\]", nox_output):
path = ""
filename = file_path
if file_path.count("/") > 0:
path_filename = file_path.rsplit("/", 1)
path = path_filename[0]
filename = path_filename[1]
converted_filename = filename.rsplit('.', 1)[0] + ".csv"
if os.path.isfile(os.path.join(path, converted_filename)):
self.convert_config_job.set_status(JobStatus.COMPLETED)
self.db_session.commit()
conversion_successful = True
if not conversion_successful:
self.convert_config_job.set_status(JobStatus.FAILED)
self.db_session.commit()
logger.exception("Configuration migration tool failed to convert {}".format(file_path) +
": {}".format(nox_output))
finally:
self.db_session.close()
def get_unique_key(self):
return 'convert_config_job_{}'.format(self.job_id)
|
apache-2.0
|
analyst-collective/dbt
|
core/dbt/include/global_project/macros/materializations/tests/where_subquery.sql
|
497
|
{% macro get_where_subquery(relation) -%}
{% do return(adapter.dispatch('get_where_subquery', 'dbt')(relation)) %}
{%- endmacro %}
{% macro default__get_where_subquery(relation) -%}
{% set where = config.get('where', '') %}
{% if where %}
{%- set filtered -%}
(select * from {{ relation }} where {{ where }}) dbt_subquery
{%- endset -%}
{% do return(filtered) %}
{%- else -%}
{% do return(relation) %}
{%- endif -%}
{%- endmacro %}
|
apache-2.0
|
ioanrogers/aws-sdk-perl
|
auto-lib/Paws/GameLift/LatencyMap.pm
|
1305
|
package Paws::GameLift::LatencyMap;
use Moose;
with 'Paws::API::StrToNativeMapParser';
has Map => (is => 'ro', isa => 'HashRef[Int]');
1;
### main pod documentation begin ###
=head1 NAME
Paws::GameLift::LatencyMap
=head1 USAGE
This class represents one of two things:
=head3 Arguments in a call to a service
Use the attributes of this class as arguments to methods. You shouldn't make instances of this class.
Each attribute should be used as a named argument in the calls that expect this type of object.
As an example, if Att1 is expected to be a Paws::GameLift::LatencyMap object:
$service_obj->Method(Att1 => { key1 => $value, ..., keyN => $value });
=head3 Results returned from an API call
Use accessors for each attribute. If Att1 is expected to be an Paws::GameLift::LatencyMap object:
$result = $service_obj->Method(...);
$result->Att1->Map->{ key1 }
=head1 DESCRIPTION
This class has no description
=head1 ATTRIBUTES
=head2 Map => Int
Use the Map method to retrieve a HashRef to the map
=head1 SEE ALSO
This class forms part of L<Paws>, describing an object used in L<Paws::GameLift>
=head1 BUGS and CONTRIBUTIONS
The source code is located here: https://github.com/pplu/aws-sdk-perl
Please report bugs to: https://github.com/pplu/aws-sdk-perl/issues
=cut
|
apache-2.0
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.