answer
stringlengths
15
1.25M
// This library was generated by the LoxiGen Compiler. // Automatically generated by LOXI from template of_class.java // Do not modify package org.projectfloodlight.openflow.protocol.ver13; import org.projectfloodlight.openflow.protocol.*; import org.projectfloodlight.openflow.protocol.action.*; import org.projectfloodlight.openflow.protocol.actionid.*; import org.projectfloodlight.openflow.protocol.bsntlv.*; import org.projectfloodlight.openflow.protocol.errormsg.*; import org.projectfloodlight.openflow.protocol.meterband.*; import org.projectfloodlight.openflow.protocol.instruction.*; import org.projectfloodlight.openflow.protocol.instructionid.*; import org.projectfloodlight.openflow.protocol.match.*; import org.projectfloodlight.openflow.protocol.oxm.*; import org.projectfloodlight.openflow.protocol.queueprop.*; import org.projectfloodlight.openflow.types.*; import org.projectfloodlight.openflow.util.*; import org.projectfloodlight.openflow.exceptions.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Set; import org.jboss.netty.buffer.ChannelBuffer; import com.google.common.hash.PrimitiveSink; import com.google.common.hash.Funnel; class <API key> implements OFOxmBsnUdf4Masked { private static final Logger logger = LoggerFactory.getLogger(<API key>.class); final static byte WIRE_VERSION = 4; final static int LENGTH = 12; private final static UDF DEFAULT_VALUE = UDF.ZERO; private final static UDF DEFAULT_VALUE_MASK = UDF.ZERO; // OF message fields private final UDF value; private final UDF mask; // Immutable default instance final static <API key> DEFAULT = new <API key>( DEFAULT_VALUE, DEFAULT_VALUE_MASK ); // package private constructor - used by readers, builders, and factory <API key>(UDF value, UDF mask) { if(value == null) { throw new <API key>("<API key>: property value cannot be null"); } if(mask == null) { throw new <API key>("<API key>: property mask cannot be null"); } this.value = value; this.mask = mask; } // Accessors for OF message fields @Override public long getTypeLen() { return 0x31908L; } @Override public UDF getValue() { return value; } @Override public UDF getMask() { return mask; } @Override public MatchField<UDF> getMatchField() { return MatchField.BSN_UDF4; } @Override public boolean isMasked() { return true; } public OFOxm<UDF> getCanonical() { if (UDF.NO_MASK.equals(mask)) { return new OFOxmBsnUdf4Ver13(value); } else if(UDF.FULL_MASK.equals(mask)) { return null; } else { return this; } } @Override public OFVersion getVersion() { return OFVersion.OF_13; } public OFOxmBsnUdf4Masked.Builder createBuilder() { return new BuilderWithParent(this); } static class BuilderWithParent implements OFOxmBsnUdf4Masked.Builder { final <API key> parentMessage; // OF message fields private boolean valueSet; private UDF value; private boolean maskSet; private UDF mask; BuilderWithParent(<API key> parentMessage) { this.parentMessage = parentMessage; } @Override public long getTypeLen() { return 0x31908L; } @Override public UDF getValue() { return value; } @Override public OFOxmBsnUdf4Masked.Builder setValue(UDF value) { this.value = value; this.valueSet = true; return this; } @Override public UDF getMask() { return mask; } @Override public OFOxmBsnUdf4Masked.Builder setMask(UDF mask) { this.mask = mask; this.maskSet = true; return this; } @Override public MatchField<UDF> getMatchField() { return MatchField.BSN_UDF4; } @Override public boolean isMasked() { return true; } @Override public OFOxm<UDF> getCanonical()throws <API key> { throw new <API key>("Property canonical not supported in version 1.3"); } @Override public OFVersion getVersion() { return OFVersion.OF_13; } @Override public OFOxmBsnUdf4Masked build() { UDF value = this.valueSet ? this.value : parentMessage.value; if(value == null) throw new <API key>("Property value must not be null"); UDF mask = this.maskSet ? this.mask : parentMessage.mask; if(mask == null) throw new <API key>("Property mask must not be null"); return new <API key>( value, mask ); } } static class Builder implements OFOxmBsnUdf4Masked.Builder { // OF message fields private boolean valueSet; private UDF value; private boolean maskSet; private UDF mask; @Override public long getTypeLen() { return 0x31908L; } @Override public UDF getValue() { return value; } @Override public OFOxmBsnUdf4Masked.Builder setValue(UDF value) { this.value = value; this.valueSet = true; return this; } @Override public UDF getMask() { return mask; } @Override public OFOxmBsnUdf4Masked.Builder setMask(UDF mask) { this.mask = mask; this.maskSet = true; return this; } @Override public MatchField<UDF> getMatchField() { return MatchField.BSN_UDF4; } @Override public boolean isMasked() { return true; } @Override public OFOxm<UDF> getCanonical()throws <API key> { throw new <API key>("Property canonical not supported in version 1.3"); } @Override public OFVersion getVersion() { return OFVersion.OF_13; } @Override public OFOxmBsnUdf4Masked build() { UDF value = this.valueSet ? this.value : DEFAULT_VALUE; if(value == null) throw new <API key>("Property value must not be null"); UDF mask = this.maskSet ? this.mask : DEFAULT_VALUE_MASK; if(mask == null) throw new <API key>("Property mask must not be null"); return new <API key>( value, mask ); } } final static Reader READER = new Reader(); static class Reader implements OFMessageReader<OFOxmBsnUdf4Masked> { @Override public OFOxmBsnUdf4Masked readFrom(ChannelBuffer bb) throws OFParseError { // fixed value property typeLen == 0x31908L int typeLen = bb.readInt(); if(typeLen != 0x31908) throw new OFParseError("Wrong typeLen: Expected=0x31908L(0x31908L), got="+typeLen); UDF value = UDF.read4Bytes(bb); UDF mask = UDF.read4Bytes(bb); <API key> <API key> = new <API key>( value, mask ); if(logger.isTraceEnabled()) logger.trace("readFrom - read={}", <API key>); return <API key>; } } public void putTo(PrimitiveSink sink) { FUNNEL.funnel(this, sink); } final static <API key> FUNNEL = new <API key>(); static class <API key> implements Funnel<<API key>> { private static final long serialVersionUID = 1L; @Override public void funnel(<API key> message, PrimitiveSink sink) { // fixed value property typeLen = 0x31908L sink.putInt(0x31908); message.value.putTo(sink); message.mask.putTo(sink); } } public void writeTo(ChannelBuffer bb) { WRITER.write(bb, this); } final static Writer WRITER = new Writer(); static class Writer implements OFMessageWriter<<API key>> { @Override public void write(ChannelBuffer bb, <API key> message) { // fixed value property typeLen = 0x31908L bb.writeInt(0x31908); message.value.write4Bytes(bb); message.mask.write4Bytes(bb); } } @Override public String toString() { StringBuilder b = new StringBuilder("<API key>("); b.append("value=").append(value); b.append(", "); b.append("mask=").append(mask); b.append(")"); return b.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; <API key> other = (<API key>) obj; if (value == null) { if (other.value != null) return false; } else if (!value.equals(other.value)) return false; if (mask == null) { if (other.mask != null) return false; } else if (!mask.equals(other.mask)) return false; return true; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((value == null) ? 0 : value.hashCode()); result = prime * result + ((mask == null) ? 0 : mask.hashCode()); return result; } }
<!DOCTYPE HTML PUBLIC "- <!-- NewPage --> <html lang="ro"> <head> <!-- Generated by javadoc (version 1.7.0_07) on Tue May 27 14:37:24 EEST 2014 --> <title>Uses of Class net.sf.jasperreports.components.list.HorizontalFillList (JasperReports 5.6.0 API)</title> <meta name="date" content="2014-05-27"> <link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style"> </head> <body> <script type="text/javascript"><! if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Uses of Class net.sf.jasperreports.components.list.HorizontalFillList (JasperReports 5.6.0 API)"; } </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <div class="topNav"><a name="navbar_top"> </a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow"> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../../../net/sf/jasperreports/components/list/HorizontalFillList.html" title="class in net.sf.jasperreports.components.list">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../../index-all.html">Index</a></li> <li><a href="../../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../../index.html?net/sf/jasperreports/components/list/class-use/HorizontalFillList.html" target="_top">Frames</a></li> <li><a href="HorizontalFillList.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="<API key>"> <li><a href="../../../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><! allClassesLink = document.getElementById("<API key>"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } </script> </div> <a name="skip-navbar_top"> </a></div> <div class="header"> <h2 title="Uses of Class net.sf.jasperreports.components.list.HorizontalFillList" class="title">Uses of Class<br>net.sf.jasperreports.components.list.HorizontalFillList</h2> </div> <div class="classUseContainer">No usage of net.sf.jasperreports.components.list.HorizontalFillList</div> <div class="bottomNav"><a name="navbar_bottom"> </a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="<API key>"> </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="../../../../../../net/sf/jasperreports/components/list/HorizontalFillList.html" title="class in net.sf.jasperreports.components.list">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../../index-all.html">Index</a></li> <li><a href="../../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../../index.html?net/sf/jasperreports/components/list/class-use/HorizontalFillList.html" target="_top">Frames</a></li> <li><a href="HorizontalFillList.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="<API key>"> <li><a href="../../../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><! allClassesLink = document.getElementById("<API key>"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } </script> </div> <a name="skip-navbar_bottom"> </a></div> <p class="legalCopy"><small> <span style="font-decoration:none;font-family:Arial,Helvetica,sans-serif;font-size:8pt;font-style:normal;color: </small></p> </body> </html>
package com.tamirhassan.pdfxtk.comparators; import java.util.Comparator; import com.tamirhassan.pdfxtk.model.GenericSegment; /** * @author Tamir Hassan, pdfanalyser@tamirhassan.com * @version PDF Analyser 0.9 * * Sorts on Xmid coordinate ((x1+x2)/2) */ public class XmidComparator implements Comparator<GenericSegment> { public int compare(GenericSegment obj1, GenericSegment obj2) { // sorts in x order double x1 = obj1.getXmid(); double x2 = obj2.getXmid(); // causes a contract violation (rounding?) // return (int) (x1 - x2); if (x2 > x1) return -1; else if (x2 == x1) return 0; else return 1; } public boolean equals(Object obj) { return obj.equals(this); } }
# BOESG-website Public facing website for British Open Educational Software Group at http: Note for Contributors Deployment is automated upon merge to the master branch via CI. Please raise PRs against the dev branch.
import com.google.common.base.Function; import javax.annotation.Nullable; public class <API key> implements Function<PojoDTO, Long>{ @Nullable @Override public Long apply(@Nullable final PojoDTO input) { return input.getDateTime().getMillis(); } }
package ru.stqa.javacourse.mantis.tests; import org.testng.annotations.Test; import ru.stqa.javacourse.mantis.model.Issue; import ru.stqa.javacourse.mantis.model.Project; import javax.xml.rpc.ServiceException; import java.net.<API key>; import java.rmi.RemoteException; import java.util.Set; import static org.testng.Assert.assertEquals; public class SoapTest extends TestBase { @Test public void testGetProjects() throws <API key>, ServiceException, RemoteException { Set<Project> projects = app.soap().getProjects(); System.out.println(projects.size()); for (Project project : projects) { System.out.println(project.getName()); } } @Test public void testCreateIssue() throws RemoteException, ServiceException, <API key> { Set<Project> projects = app.soap().getProjects(); Issue issue=new Issue().withSummary("test issue") .withDescription("test issue description").withProject(projects.iterator().next()); Issue created = app.soap().addIssue(issue); assertEquals(issue.getSummary(),created.getSummary()); } }
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/ads/googleads/v10/services/<API key>.proto package com.google.ads.googleads.v10.services; /** * <pre> * A single operation (update) on a customer conversion goal. * </pre> * * Protobuf type {@code google.ads.googleads.v10.services.<API key>} */ public final class <API key> extends com.google.protobuf.GeneratedMessageV3 implements // @@<API key>(message_implements:google.ads.googleads.v10.services.<API key>) <API key> { private static final long serialVersionUID = 0L; // Use <API key>.newBuilder() to construct. private <API key>(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private <API key>() { } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance( <API key> unused) { return new <API key>(); } @java.lang.Override public final com.google.protobuf.UnknownFieldSet getUnknownFields() { return this.unknownFields; } private <API key>( com.google.protobuf.CodedInputStream input, com.google.protobuf.<API key> extensionRegistry) throws com.google.protobuf.<API key> { this(); if (extensionRegistry == null) { throw new java.lang.<API key>(); } com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder(); try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { com.google.ads.googleads.v10.resources.<API key>.Builder subBuilder = null; if (operationCase_ == 1) { subBuilder = ((com.google.ads.googleads.v10.resources.<API key>) operation_).toBuilder(); } operation_ = input.readMessage(com.google.ads.googleads.v10.resources.<API key>.parser(), extensionRegistry); if (subBuilder != null) { subBuilder.mergeFrom((com.google.ads.googleads.v10.resources.<API key>) operation_); operation_ = subBuilder.buildPartial(); } operationCase_ = 1; break; } case 18: { com.google.protobuf.FieldMask.Builder subBuilder = null; if (updateMask_ != null) { subBuilder = updateMask_.toBuilder(); } updateMask_ = input.readMessage(com.google.protobuf.FieldMask.parser(), extensionRegistry); if (subBuilder != null) { subBuilder.mergeFrom(updateMask_); updateMask_ = subBuilder.buildPartial(); } break; } default: { if (!parseUnknownField( input, unknownFields, extensionRegistry, tag)) { done = true; } break; } } } } catch (com.google.protobuf.<API key> e) { throw e.<API key>(this); } catch (java.io.IOException e) { throw new com.google.protobuf.<API key>( e).<API key>(this); } finally { this.unknownFields = unknownFields.build(); <API key>(); } } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.ads.googleads.v10.services.<API key>.internal_static_google_ads_googleads_v10_services_CustomerConversionGoalOperation_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable <API key>() { return com.google.ads.googleads.v10.services.<API key>.internal_static_google_ads_googleads_v10_services_CustomerConversionGoalOperation_fieldAccessorTable .<API key>( com.google.ads.googleads.v10.services.<API key>.class, com.google.ads.googleads.v10.services.<API key>.Builder.class); } private int operationCase_ = 0; private java.lang.Object operation_; public enum OperationCase implements com.google.protobuf.Internal.EnumLite, com.google.protobuf.AbstractMessage.InternalOneOfEnum { UPDATE(1), OPERATION_NOT_SET(0); private final int value; private OperationCase(int value) { this.value = value; } /** * @param value The number of the enum to look for. * @return The enum associated with the given number. * @deprecated Use {@link #forNumber(int)} instead. */ @java.lang.Deprecated public static OperationCase valueOf(int value) { return forNumber(value); } public static OperationCase forNumber(int value) { switch (value) { case 1: return UPDATE; case 0: return OPERATION_NOT_SET; default: return null; } } public int getNumber() { return this.value; } }; public OperationCase getOperationCase() { return OperationCase.forNumber( operationCase_); } public static final int <API key> = 2; private com.google.protobuf.FieldMask updateMask_; /** * <pre> * FieldMask that determines which resource fields are modified in an update. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 2;</code> * @return Whether the updateMask field is set. */ @java.lang.Override public boolean hasUpdateMask() { return updateMask_ != null; } /** * <pre> * FieldMask that determines which resource fields are modified in an update. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 2;</code> * @return The updateMask. */ @java.lang.Override public com.google.protobuf.FieldMask getUpdateMask() { return updateMask_ == null ? com.google.protobuf.FieldMask.getDefaultInstance() : updateMask_; } /** * <pre> * FieldMask that determines which resource fields are modified in an update. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 2;</code> */ @java.lang.Override public com.google.protobuf.FieldMaskOrBuilder <API key>() { return getUpdateMask(); } public static final int UPDATE_FIELD_NUMBER = 1; /** * <pre> * Update operation: The customer conversion goal is expected to have a * valid resource name. * </pre> * * <code>.google.ads.googleads.v10.resources.<API key> update = 1;</code> * @return Whether the update field is set. */ @java.lang.Override public boolean hasUpdate() { return operationCase_ == 1; } /** * <pre> * Update operation: The customer conversion goal is expected to have a * valid resource name. * </pre> * * <code>.google.ads.googleads.v10.resources.<API key> update = 1;</code> * @return The update. */ @java.lang.Override public com.google.ads.googleads.v10.resources.<API key> getUpdate() { if (operationCase_ == 1) { return (com.google.ads.googleads.v10.resources.<API key>) operation_; } return com.google.ads.googleads.v10.resources.<API key>.getDefaultInstance(); } /** * <pre> * Update operation: The customer conversion goal is expected to have a * valid resource name. * </pre> * * <code>.google.ads.googleads.v10.resources.<API key> update = 1;</code> */ @java.lang.Override public com.google.ads.googleads.v10.resources.<API key> getUpdateOrBuilder() { if (operationCase_ == 1) { return (com.google.ads.googleads.v10.resources.<API key>) operation_; } return com.google.ads.googleads.v10.resources.<API key>.getDefaultInstance(); } private byte <API key> = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = <API key>; if (isInitialized == 1) return true; if (isInitialized == 0) return false; <API key> = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (operationCase_ == 1) { output.writeMessage(1, (com.google.ads.googleads.v10.resources.<API key>) operation_); } if (updateMask_ != null) { output.writeMessage(2, getUpdateMask()); } unknownFields.writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (operationCase_ == 1) { size += com.google.protobuf.CodedOutputStream .computeMessageSize(1, (com.google.ads.googleads.v10.resources.<API key>) operation_); } if (updateMask_ != null) { size += com.google.protobuf.CodedOutputStream .computeMessageSize(2, getUpdateMask()); } size += unknownFields.getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof com.google.ads.googleads.v10.services.<API key>)) { return super.equals(obj); } com.google.ads.googleads.v10.services.<API key> other = (com.google.ads.googleads.v10.services.<API key>) obj; if (hasUpdateMask() != other.hasUpdateMask()) return false; if (hasUpdateMask()) { if (!getUpdateMask() .equals(other.getUpdateMask())) return false; } if (!getOperationCase().equals(other.getOperationCase())) return false; switch (operationCase_) { case 1: if (!getUpdate() .equals(other.getUpdate())) return false; break; case 0: default: } if (!unknownFields.equals(other.unknownFields)) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); if (hasUpdateMask()) { hash = (37 * hash) + <API key>; hash = (53 * hash) + getUpdateMask().hashCode(); } switch (operationCase_) { case 1: hash = (37 * hash) + UPDATE_FIELD_NUMBER; hash = (53 * hash) + getUpdate().hashCode(); break; case 0: default: } hash = (29 * hash) + unknownFields.hashCode(); memoizedHashCode = hash; return hash; } public static com.google.ads.googleads.v10.services.<API key> parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.<API key> { return PARSER.parseFrom(data); } public static com.google.ads.googleads.v10.services.<API key> parseFrom( java.nio.ByteBuffer data, com.google.protobuf.<API key> extensionRegistry) throws com.google.protobuf.<API key> { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.ads.googleads.v10.services.<API key> parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.<API key> { return PARSER.parseFrom(data); } public static com.google.ads.googleads.v10.services.<API key> parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.<API key> extensionRegistry) throws com.google.protobuf.<API key> { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.ads.googleads.v10.services.<API key> parseFrom(byte[] data) throws com.google.protobuf.<API key> { return PARSER.parseFrom(data); } public static com.google.ads.googleads.v10.services.<API key> parseFrom( byte[] data, com.google.protobuf.<API key> extensionRegistry) throws com.google.protobuf.<API key> { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.ads.googleads.v10.services.<API key> parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .<API key>(PARSER, input); } public static com.google.ads.googleads.v10.services.<API key> parseFrom( java.io.InputStream input, com.google.protobuf.<API key> extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .<API key>(PARSER, input, extensionRegistry); } public static com.google.ads.googleads.v10.services.<API key> parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .<API key>(PARSER, input); } public static com.google.ads.googleads.v10.services.<API key> parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.<API key> extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .<API key>(PARSER, input, extensionRegistry); } public static com.google.ads.googleads.v10.services.<API key> parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .<API key>(PARSER, input); } public static com.google.ads.googleads.v10.services.<API key> parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.<API key> extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .<API key>(PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(com.google.ads.googleads.v10.services.<API key> prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * <pre> * A single operation (update) on a customer conversion goal. * </pre> * * Protobuf type {@code google.ads.googleads.v10.services.<API key>} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@<API key>(builder_implements:google.ads.googleads.v10.services.<API key>) com.google.ads.googleads.v10.services.<API key> { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.ads.googleads.v10.services.<API key>.internal_static_google_ads_googleads_v10_services_CustomerConversionGoalOperation_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable <API key>() { return com.google.ads.googleads.v10.services.<API key>.internal_static_google_ads_googleads_v10_services_CustomerConversionGoalOperation_fieldAccessorTable .<API key>( com.google.ads.googleads.v10.services.<API key>.class, com.google.ads.googleads.v10.services.<API key>.Builder.class); } // Construct using com.google.ads.googleads.v10.services.<API key>.newBuilder() private Builder() { <API key>(); } private Builder( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); <API key>(); } private void <API key>() { if (com.google.protobuf.GeneratedMessageV3 .<API key>) { } } @java.lang.Override public Builder clear() { super.clear(); if (updateMaskBuilder_ == null) { updateMask_ = null; } else { updateMask_ = null; updateMaskBuilder_ = null; } operationCase_ = 0; operation_ = null; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor <API key>() { return com.google.ads.googleads.v10.services.<API key>.internal_static_google_ads_googleads_v10_services_CustomerConversionGoalOperation_descriptor; } @java.lang.Override public com.google.ads.googleads.v10.services.<API key> <API key>() { return com.google.ads.googleads.v10.services.<API key>.getDefaultInstance(); } @java.lang.Override public com.google.ads.googleads.v10.services.<API key> build() { com.google.ads.googleads.v10.services.<API key> result = buildPartial(); if (!result.isInitialized()) { throw <API key>(result); } return result; } @java.lang.Override public com.google.ads.googleads.v10.services.<API key> buildPartial() { com.google.ads.googleads.v10.services.<API key> result = new com.google.ads.googleads.v10.services.<API key>(this); if (updateMaskBuilder_ == null) { result.updateMask_ = updateMask_; } else { result.updateMask_ = updateMaskBuilder_.build(); } if (operationCase_ == 1) { if (updateBuilder_ == null) { result.operation_ = operation_; } else { result.operation_ = updateBuilder_.build(); } } result.operationCase_ = operationCase_; onBuilt(); return result; } @java.lang.Override public Builder clone() { return super.clone(); } @java.lang.Override public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.setField(field, value); } @java.lang.Override public Builder clearField( com.google.protobuf.Descriptors.FieldDescriptor field) { return super.clearField(field); } @java.lang.Override public Builder clearOneof( com.google.protobuf.Descriptors.OneofDescriptor oneof) { return super.clearOneof(oneof); } @java.lang.Override public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return super.setRepeatedField(field, index, value); } @java.lang.Override public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.addRepeatedField(field, value); } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof com.google.ads.googleads.v10.services.<API key>) { return mergeFrom((com.google.ads.googleads.v10.services.<API key>)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.ads.googleads.v10.services.<API key> other) { if (other == com.google.ads.googleads.v10.services.<API key>.getDefaultInstance()) return this; if (other.hasUpdateMask()) { mergeUpdateMask(other.getUpdateMask()); } switch (other.getOperationCase()) { case UPDATE: { mergeUpdate(other.getUpdate()); break; } case OPERATION_NOT_SET: { break; } } this.mergeUnknownFields(other.unknownFields); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.<API key> extensionRegistry) throws java.io.IOException { com.google.ads.googleads.v10.services.<API key> parsedMessage = null; try { parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); } catch (com.google.protobuf.<API key> e) { parsedMessage = (com.google.ads.googleads.v10.services.<API key>) e.<API key>(); throw e.unwrapIOException(); } finally { if (parsedMessage != null) { mergeFrom(parsedMessage); } } return this; } private int operationCase_ = 0; private java.lang.Object operation_; public OperationCase getOperationCase() { return OperationCase.forNumber( operationCase_); } public Builder clearOperation() { operationCase_ = 0; operation_ = null; onChanged(); return this; } private com.google.protobuf.FieldMask updateMask_; private com.google.protobuf.<API key>< com.google.protobuf.FieldMask, com.google.protobuf.FieldMask.Builder, com.google.protobuf.FieldMaskOrBuilder> updateMaskBuilder_; /** * <pre> * FieldMask that determines which resource fields are modified in an update. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 2;</code> * @return Whether the updateMask field is set. */ public boolean hasUpdateMask() { return updateMaskBuilder_ != null || updateMask_ != null; } /** * <pre> * FieldMask that determines which resource fields are modified in an update. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 2;</code> * @return The updateMask. */ public com.google.protobuf.FieldMask getUpdateMask() { if (updateMaskBuilder_ == null) { return updateMask_ == null ? com.google.protobuf.FieldMask.getDefaultInstance() : updateMask_; } else { return updateMaskBuilder_.getMessage(); } } /** * <pre> * FieldMask that determines which resource fields are modified in an update. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 2;</code> */ public Builder setUpdateMask(com.google.protobuf.FieldMask value) { if (updateMaskBuilder_ == null) { if (value == null) { throw new <API key>(); } updateMask_ = value; onChanged(); } else { updateMaskBuilder_.setMessage(value); } return this; } /** * <pre> * FieldMask that determines which resource fields are modified in an update. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 2;</code> */ public Builder setUpdateMask( com.google.protobuf.FieldMask.Builder builderForValue) { if (updateMaskBuilder_ == null) { updateMask_ = builderForValue.build(); onChanged(); } else { updateMaskBuilder_.setMessage(builderForValue.build()); } return this; } /** * <pre> * FieldMask that determines which resource fields are modified in an update. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 2;</code> */ public Builder mergeUpdateMask(com.google.protobuf.FieldMask value) { if (updateMaskBuilder_ == null) { if (updateMask_ != null) { updateMask_ = com.google.protobuf.FieldMask.newBuilder(updateMask_).mergeFrom(value).buildPartial(); } else { updateMask_ = value; } onChanged(); } else { updateMaskBuilder_.mergeFrom(value); } return this; } /** * <pre> * FieldMask that determines which resource fields are modified in an update. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 2;</code> */ public Builder clearUpdateMask() { if (updateMaskBuilder_ == null) { updateMask_ = null; onChanged(); } else { updateMask_ = null; updateMaskBuilder_ = null; } return this; } /** * <pre> * FieldMask that determines which resource fields are modified in an update. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 2;</code> */ public com.google.protobuf.FieldMask.Builder <API key>() { onChanged(); return <API key>().getBuilder(); } /** * <pre> * FieldMask that determines which resource fields are modified in an update. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 2;</code> */ public com.google.protobuf.FieldMaskOrBuilder <API key>() { if (updateMaskBuilder_ != null) { return updateMaskBuilder_.getMessageOrBuilder(); } else { return updateMask_ == null ? com.google.protobuf.FieldMask.getDefaultInstance() : updateMask_; } } /** * <pre> * FieldMask that determines which resource fields are modified in an update. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 2;</code> */ private com.google.protobuf.<API key>< com.google.protobuf.FieldMask, com.google.protobuf.FieldMask.Builder, com.google.protobuf.FieldMaskOrBuilder> <API key>() { if (updateMaskBuilder_ == null) { updateMaskBuilder_ = new com.google.protobuf.<API key>< com.google.protobuf.FieldMask, com.google.protobuf.FieldMask.Builder, com.google.protobuf.FieldMaskOrBuilder>( getUpdateMask(), <API key>(), isClean()); updateMask_ = null; } return updateMaskBuilder_; } private com.google.protobuf.<API key>< com.google.ads.googleads.v10.resources.<API key>, com.google.ads.googleads.v10.resources.<API key>.Builder, com.google.ads.googleads.v10.resources.<API key>> updateBuilder_; /** * <pre> * Update operation: The customer conversion goal is expected to have a * valid resource name. * </pre> * * <code>.google.ads.googleads.v10.resources.<API key> update = 1;</code> * @return Whether the update field is set. */ @java.lang.Override public boolean hasUpdate() { return operationCase_ == 1; } /** * <pre> * Update operation: The customer conversion goal is expected to have a * valid resource name. * </pre> * * <code>.google.ads.googleads.v10.resources.<API key> update = 1;</code> * @return The update. */ @java.lang.Override public com.google.ads.googleads.v10.resources.<API key> getUpdate() { if (updateBuilder_ == null) { if (operationCase_ == 1) { return (com.google.ads.googleads.v10.resources.<API key>) operation_; } return com.google.ads.googleads.v10.resources.<API key>.getDefaultInstance(); } else { if (operationCase_ == 1) { return updateBuilder_.getMessage(); } return com.google.ads.googleads.v10.resources.<API key>.getDefaultInstance(); } } /** * <pre> * Update operation: The customer conversion goal is expected to have a * valid resource name. * </pre> * * <code>.google.ads.googleads.v10.resources.<API key> update = 1;</code> */ public Builder setUpdate(com.google.ads.googleads.v10.resources.<API key> value) { if (updateBuilder_ == null) { if (value == null) { throw new <API key>(); } operation_ = value; onChanged(); } else { updateBuilder_.setMessage(value); } operationCase_ = 1; return this; } /** * <pre> * Update operation: The customer conversion goal is expected to have a * valid resource name. * </pre> * * <code>.google.ads.googleads.v10.resources.<API key> update = 1;</code> */ public Builder setUpdate( com.google.ads.googleads.v10.resources.<API key>.Builder builderForValue) { if (updateBuilder_ == null) { operation_ = builderForValue.build(); onChanged(); } else { updateBuilder_.setMessage(builderForValue.build()); } operationCase_ = 1; return this; } /** * <pre> * Update operation: The customer conversion goal is expected to have a * valid resource name. * </pre> * * <code>.google.ads.googleads.v10.resources.<API key> update = 1;</code> */ public Builder mergeUpdate(com.google.ads.googleads.v10.resources.<API key> value) { if (updateBuilder_ == null) { if (operationCase_ == 1 && operation_ != com.google.ads.googleads.v10.resources.<API key>.getDefaultInstance()) { operation_ = com.google.ads.googleads.v10.resources.<API key>.newBuilder((com.google.ads.googleads.v10.resources.<API key>) operation_) .mergeFrom(value).buildPartial(); } else { operation_ = value; } onChanged(); } else { if (operationCase_ == 1) { updateBuilder_.mergeFrom(value); } updateBuilder_.setMessage(value); } operationCase_ = 1; return this; } /** * <pre> * Update operation: The customer conversion goal is expected to have a * valid resource name. * </pre> * * <code>.google.ads.googleads.v10.resources.<API key> update = 1;</code> */ public Builder clearUpdate() { if (updateBuilder_ == null) { if (operationCase_ == 1) { operationCase_ = 0; operation_ = null; onChanged(); } } else { if (operationCase_ == 1) { operationCase_ = 0; operation_ = null; } updateBuilder_.clear(); } return this; } /** * <pre> * Update operation: The customer conversion goal is expected to have a * valid resource name. * </pre> * * <code>.google.ads.googleads.v10.resources.<API key> update = 1;</code> */ public com.google.ads.googleads.v10.resources.<API key>.Builder getUpdateBuilder() { return <API key>().getBuilder(); } /** * <pre> * Update operation: The customer conversion goal is expected to have a * valid resource name. * </pre> * * <code>.google.ads.googleads.v10.resources.<API key> update = 1;</code> */ @java.lang.Override public com.google.ads.googleads.v10.resources.<API key> getUpdateOrBuilder() { if ((operationCase_ == 1) && (updateBuilder_ != null)) { return updateBuilder_.getMessageOrBuilder(); } else { if (operationCase_ == 1) { return (com.google.ads.googleads.v10.resources.<API key>) operation_; } return com.google.ads.googleads.v10.resources.<API key>.getDefaultInstance(); } } /** * <pre> * Update operation: The customer conversion goal is expected to have a * valid resource name. * </pre> * * <code>.google.ads.googleads.v10.resources.<API key> update = 1;</code> */ private com.google.protobuf.<API key>< com.google.ads.googleads.v10.resources.<API key>, com.google.ads.googleads.v10.resources.<API key>.Builder, com.google.ads.googleads.v10.resources.<API key>> <API key>() { if (updateBuilder_ == null) { if (!(operationCase_ == 1)) { operation_ = com.google.ads.googleads.v10.resources.<API key>.getDefaultInstance(); } updateBuilder_ = new com.google.protobuf.<API key>< com.google.ads.googleads.v10.resources.<API key>, com.google.ads.googleads.v10.resources.<API key>.Builder, com.google.ads.googleads.v10.resources.<API key>>( (com.google.ads.googleads.v10.resources.<API key>) operation_, <API key>(), isClean()); operation_ = null; } operationCase_ = 1; onChanged();; return updateBuilder_; } @java.lang.Override public final Builder setUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@<API key>(builder_scope:google.ads.googleads.v10.services.<API key>) } // @@<API key>(class_scope:google.ads.googleads.v10.services.<API key>) private static final com.google.ads.googleads.v10.services.<API key> DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.ads.googleads.v10.services.<API key>(); } public static com.google.ads.googleads.v10.services.<API key> getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<<API key>> PARSER = new com.google.protobuf.AbstractParser<<API key>>() { @java.lang.Override public <API key> parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.<API key> extensionRegistry) throws com.google.protobuf.<API key> { return new <API key>(input, extensionRegistry); } }; public static com.google.protobuf.Parser<<API key>> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<<API key>> getParserForType() { return PARSER; } @java.lang.Override public com.google.ads.googleads.v10.services.<API key> <API key>() { return DEFAULT_INSTANCE; } }
.container { clear: both; } body { font-family: Verdana, Arial, sans-serif; } h3 { font-family: Verdana, Arial, sans-serif; font-size: 18px; line-height: normal; } a.button, span.button { margin-left:10px; height:36px; } #sides{ margin:0; height:144px; width: 100%; } #left{ float:left; width:144px; overflow:hidden; } #right{ float:left; width:50%; overflow:hidden; } #image-data { margin: 20px 0px; width: 300px !important; height: auto; } .inst_table, .inst_table th, .inst_table td { border: 1px solid black; border-collapse: collapse; text-align: center; } .bottom { margin-top: 10px; margin-left: 20px; margin-bottom: 40px; float: left; } label.error { margin-left: 10px; } select.error, textarea.error, input.error { outline-style: solid; outline-width: 2px; outline-color: #FF0000; } .ui-dialog { position: fixed !important; }
package org.openjava.upay.web.domain; import java.util.List; public class TablePage<T> { private long start; private int length; private long recordsTotal; private long recordsFiltered; private List<T> data; public TablePage() { } public long getStart() { return start; } public void setStart(long start) { this.start = start; } public int getLength() { return length; } public void setLength(int length) { this.length = length; } public long getRecordsTotal() { return recordsTotal; } public void setRecordsTotal(long recordsTotal) { this.recordsTotal = recordsTotal; } public long getRecordsFiltered() { return recordsFiltered; } public void setRecordsFiltered(long recordsFiltered) { this.recordsFiltered = recordsFiltered; } public List<T> getData() { return data; } public void setData(List<T> data) { this.data = data; } public TablePage wrapData(long total, List<T> data) { this.recordsTotal = total; this.recordsFiltered = total; this.data = data; return this; } }
<!DOCTYPE HTML PUBLIC "- <!--NewPage <HTML> <HEAD> <!-- Generated by javadoc (build 1.6.0_24) on Tue Apr 26 20:40:28 CST 2011 --> <TITLE> com.numericalmethod.suanshu.optimization.constrained.linearprogramming.simplex.standard (SuanShu 1.3.1 API Documentation) </TITLE> <META NAME="date" CONTENT="2011-04-26"> <LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../../../../stylesheet.css" TITLE="Style"> </HEAD> <BODY BGCOLOR="white"> <FONT size="+1" CLASS="FrameTitleFont"> <A HREF="../../../../../../../../com/numericalmethod/suanshu/optimization/constrained/linearprogramming/simplex/standard/package-summary.html" target="classFrame">com.numericalmethod.suanshu.optimization.constrained.linearprogramming.simplex.standard</A></FONT> <TABLE BORDER="0" WIDTH="100%" SUMMARY=""> <TR> <TD NOWRAP><FONT size="+1" CLASS="FrameHeadingFont"> Classes</FONT>&nbsp; <FONT CLASS="FrameItemFont"> <BR> <A HREF="LpBoundedSolution.html" title="class in com.numericalmethod.suanshu.optimization.constrained.linearprogramming.simplex.standard" target="classFrame">LpBoundedSolution</A> <BR> <A HREF="LpUnboundedSolution.html" title="class in com.numericalmethod.suanshu.optimization.constrained.linearprogramming.simplex.standard" target="classFrame">LpUnboundedSolution</A> <BR> <A HREF="<API key>.html" title="class in com.numericalmethod.suanshu.optimization.constrained.linearprogramming.simplex.standard" target="classFrame"><API key></A> <BR> <A HREF="StandardSimplex.html" title="class in com.numericalmethod.suanshu.optimization.constrained.linearprogramming.simplex.standard" target="classFrame">StandardSimplex</A></FONT></TD> </TR> </TABLE> </BODY> </HTML>
package com.jy.controller.workflow.online.apply; import com.jy.common.ajax.AjaxRes; import com.jy.common.utils.DateUtils; import com.jy.common.utils.base.Const; import com.jy.common.utils.security.AccountShiroUtil; import com.jy.controller.base.BaseController; import com.jy.entity.attendance.WorkRecord; import com.jy.entity.oa.overtime.Overtime; import com.jy.entity.oa.patch.Patch; import com.jy.entity.oa.task.TaskInfo; import com.jy.service.oa.activiti.<API key>; import com.jy.service.oa.overtime.OvertimeService; import com.jy.service.oa.patch.PatchService; import com.jy.service.oa.task.TaskInfoService; import org.activiti.engine.IdentityService; import org.activiti.engine.RuntimeService; import org.activiti.engine.TaskService; import org.activiti.engine.impl.persistence.entity.ExecutionEntity; import org.activiti.engine.runtime.ProcessInstance; import org.activiti.engine.task.Task; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; @Controller @RequestMapping(value = "/backstage/workflow/online/patch/") public class PatchController extends BaseController<Object> { private static final String SECURITY_URL = "/backstage/workflow/online/patch/index"; @Autowired private RuntimeService runtimeService; @Autowired private TaskService taskService; @Autowired private TaskInfoService taskInfoService; @Autowired private IdentityService identityService; @Autowired private PatchService patchService; @Autowired private <API key> <API key>; @RequestMapping(value = "index") public String index(org.springframework.ui.Model model) { if (doSecurityIntercept(Const.RESOURCES_TYPE_MENU)) { model.addAttribute("permitBtn", getPermitBtn(Const.<API key>)); return "/system/workflow/online/apply/patch"; } return Const.NO_AUTHORIZED_URL; } @RequestMapping(value = "start", method = RequestMethod.POST) @ResponseBody public AjaxRes startWorkflow(Patch o) { AjaxRes ar = getAjaxRes(); if (ar.setNoAuth(doSecurityIntercept(Const.RESOURCES_TYPE_MENU, SECURITY_URL))) { try { String currentUserId = AccountShiroUtil.getCurrentUser().getAccountId(); String[] approvers = o.getApprover().split(","); Map<String, Object> variables = new HashMap<String, Object>(); for (int i = 0; i < approvers.length; i++) { variables.put("approver" + (i + 1), approvers[i]); } String workflowKey = "patch"; identityService.<API key>(currentUserId); Date now = new Date(); ProcessInstance processInstance = runtimeService.<API key>(workflowKey, variables, getCompany()); String pId = processInstance.getId(); String leaveID = get32UUID(); o.setPid(pId); o.setAccountId(currentUserId); o.setCreatetime(now); o.setIsvalid(0); o.setName(AccountShiroUtil.getCurrentUser().getName()); o.setId(leaveID); patchService.insert(o); Task task = taskService.createTaskQuery().processInstanceId(pId).singleResult(); String <API key> = ((ExecutionEntity) processInstance).getProcessInstance().<API key>().getName(); String subkect = <API key> + "-" + AccountShiroUtil.getCurrentUser().getName() + "-" + DateUtils.formatDate(now, "yyyy-MM-dd HH:mm"); TaskInfo taskInfo = new TaskInfo(); taskInfo.setId(get32UUID()); taskInfo.setBusinesskey(leaveID); taskInfo.setCode("start"); taskInfo.setName(""); taskInfo.setStatus(0); taskInfo.<API key>(subkect); taskInfo.setAttr1(<API key>); taskInfo.setCreatetime(DateUtils.addSeconds(now, -1)); taskInfo.setCompletetime(DateUtils.addSeconds(now, -1)); taskInfo.setCreator(currentUserId); taskInfo.setAssignee(currentUserId); taskInfo.setTaskid("0"); taskInfo.setPkey(workflowKey); taskInfo.setExecutionid("0"); taskInfo.<API key>(processInstance.getId()); taskInfo.<API key>(processInstance.<API key>()); taskInfoService.insert(taskInfo); taskInfo.setId(get32UUID()); taskInfo.setCode(processInstance.getActivityId()); taskInfo.setName(task.getName()); taskInfo.setStatus(1); taskInfo.setTaskid(task.getId()); taskInfo.setCreatetime(now); taskInfo.setCompletetime(null); taskInfo.setAssignee(approvers[0]); taskInfoService.insert(taskInfo); ar.setSucceedMsg("!"); } catch (Exception e) { logger.error(e.toString(), e); ar.setFailMsg(""); } finally { identityService.<API key>(null); } } return ar; } }
> A grunt plugin for [tslint](https://github.com/palantir/tslint). ## Getting Started This plugin requires [Grunt](http: npm install grunt-tslint --save-dev Once the plugin has been installed, it may be enabled inside your Gruntfile with this line of JavaScript: grunt.loadNpmTasks("grunt-tslint"); ## The "tslint" task Overview In your project's `Gruntfile.js`, add a section named `tslint` to the data object passed into `grunt.initConfig()`: js grunt.initConfig({ tslint: { options: { // Task-specific options go here. }, your_target: { // Target-specific file lists and/or options go here. }, }, }) Options * `options.configuration: Object | string` - A TSLint configuration; can either be a JSON configuration object or a path to a tslint.json config file. * `options.project: string` - `tsconfig.json` file location. If provided type checking will be enabled. * `options.force: boolean` - If `true`, the task will suceed even if lint failures are found. Defaults to `false`. * `options.fix: boolean` - If `true`, fixes linting errors for select rules. This may overwrite linted files. Defaults to `false`. Usage Example js grunt.initConfig({ tslint: { options: { // can be a configuration object or a filepath to tslint.json configuration: "tslint.json", // If set to true, tslint errors will be reported, but not fail the task // If set to false, tslint errors will be reported, and the task will fail force: false, fix: false }, files: { src: [ "src/file1.ts", "src/file2.ts" ] } } }) ## Contributing In lieu of a formal styleguide, take care to maintain the existing coding style. Add unit tests for any new or changed functionality. Lint and test your code using [Grunt](http://gruntjs.com/).
<!DOCTYPE html> <html> <head> <title>try chat(JAX-RS)</title> <meta charset="UTF-8"> <link rel="stylesheet" href="../webjars/bootstrap/3.3.1/css/bootstrap.min.css" /> <link rel="stylesheet" href="../resources/css/style.css" /> <script type='text/javascript' src="../webjars/jquery/2.1.1/jquery.min.js"></script> <script type='text/javascript' src="../webjars/bootstrap/3.3.1/js/bootstrap.min.js"></script> <script type='text/javascript' src="../webjars/vue/0.11.0/vue.min.js"></script> <script type='text/javascript' src="../resources/js/common.js"></script> </head> <body> <div class="container"> <div class="jumbotron"> <h1> JAX-RS</h1> <form id="form" class="login" v-on="submit:join"> <span id="error" >{{error_message}}</span> <div id="nameFg" class="form-group {{name_error_css}}"> <label for="name" class="control-label"> <span>{{name_message}}</span></label> <input id="name" name="name" placeholder="" type="text" class="form-control" v-model="name" /> </div> <div id="emailFg" class="form-group {{email_error_css}}"> <label for="email" class="control-label ">Gravatar <span>{{email_message}}</span></label> <input id="email" name="email" placeholder="Gravatar" type="email" class="form-control" v-model="email" /> </div> <input type="submit" value="join" class="btn btn-default" /> </form> <div> <a href="../" class="btn btn-link">JSF</a> </div> </div> </div> <script type='text/javascript' src="../resources/js/vm_index.js"></script> </body> </html>
var searchData= [ ['interactiontype',['InteractionType',['../<API key>.html#<API key>',1,'StudentRecord']]] ];
// modification, are permitted provided that the following conditions are // met: // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // 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. #include <base.h> #include "client/windows/crash_generation/minidump_generator.h" #include <cassert> #include "client/windows/common/<API key>.h" #include "common/windows/guid_string.h" using std::wstring; namespace google_breakpad { MinidumpGenerator::MinidumpGenerator(const wstring& dump_path) : dbghelp_module_(NULL), rpcrt4_module_(NULL), dump_path_(dump_path), write_dump_(NULL), create_uuid_(NULL) { <API key>(&module_load_sync_); <API key>(&<API key>); } MinidumpGenerator::~MinidumpGenerator() { if (dbghelp_module_) { FreeLibrary(dbghelp_module_); } if (rpcrt4_module_) { FreeLibrary(rpcrt4_module_); } <API key>(&<API key>); <API key>(&module_load_sync_); } bool MinidumpGenerator::WriteMinidump(HANDLE process_handle, DWORD process_id, DWORD thread_id, DWORD <API key>, EXCEPTION_POINTERS* exception_pointers, MDRawAssertionInfo* assert_info, MINIDUMP_TYPE dump_type, bool is_client_pointers, wstring* dump_path) { <API key> write_dump = GetWriteDump(); if (!write_dump) { return false; } wstring dump_file_path; if (!<API key>(&dump_file_path)) { return false; } // If the client requests a full memory dump, we will write a normal mini // dump and a full memory dump. Both dump files use the same uuid as file // name prefix. bool full_memory_dump = (dump_type & <API key>) != 0; wstring full_dump_file_path; if (full_memory_dump) { full_dump_file_path.assign(dump_file_path); full_dump_file_path.resize(full_dump_file_path.size() - 4); // strip .dmp full_dump_file_path.append(TEXT("-full.dmp")); } HANDLE dump_file = CreateFile(dump_file_path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_NEW, <API key>, NULL); if (dump_file == <API key>) { return false; } HANDLE full_dump_file = <API key>; if (full_memory_dump) { full_dump_file = CreateFile(full_dump_file_path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_NEW, <API key>, NULL); if (full_dump_file == <API key>) { CloseHandle(dump_file); return false; } } <API key>* <API key> = NULL; <API key> dump_exception_info; // Setup the exception information object only if it's a dump // due to an exception. if (exception_pointers) { <API key> = &dump_exception_info; dump_exception_info.ThreadId = thread_id; dump_exception_info.ExceptionPointers = exception_pointers; dump_exception_info.ClientPointers = is_client_pointers; } // Add an MDRawBreakpadInfo stream to the minidump, to provide additional // information about the exception handler to the Breakpad processor. // The information will help the processor determine which threads are // relevant. The Breakpad processor does not require this information but // can function better with Breakpad-generated dumps when it is present. // The native debugger is not harmed by the presence of this information. MDRawBreakpadInfo breakpad_info = {0}; if (!is_client_pointers) { // Set the dump thread id and requesting thread id only in case of // in-process dump generation. breakpad_info.validity = <API key> | <API key>; breakpad_info.dump_thread_id = thread_id; breakpad_info.<API key> = <API key>; } // Leave room in user_stream_array for a possible assertion info stream. <API key> user_stream_array[2]; user_stream_array[0].Type = <API key>; user_stream_array[0].BufferSize = sizeof(breakpad_info); user_stream_array[0].Buffer = &breakpad_info; <API key> user_streams; user_streams.UserStreamCount = 1; user_streams.UserStreamArray = user_stream_array; MDRawAssertionInfo* actual_assert_info = assert_info; MDRawAssertionInfo client_assert_info = {0}; if (assert_info) { // If the assertion info object lives in the client process, // read the memory of the client process. if (is_client_pointers) { SIZE_T bytes_read = 0; if (!ReadProcessMemory(process_handle, assert_info, &client_assert_info, sizeof(client_assert_info), &bytes_read)) { CloseHandle(dump_file); if (full_dump_file != <API key>) CloseHandle(full_dump_file); return false; } if (bytes_read != sizeof(client_assert_info)) { CloseHandle(dump_file); if (full_dump_file != <API key>) CloseHandle(full_dump_file); return false; } actual_assert_info = &client_assert_info; } user_stream_array[1].Type = <API key>; user_stream_array[1].BufferSize = sizeof(MDRawAssertionInfo); user_stream_array[1].Buffer = actual_assert_info; ++user_streams.UserStreamCount; } bool result_minidump = write_dump( process_handle, process_id, dump_file, static_cast<MINIDUMP_TYPE>((dump_type & (~<API key>)) | MiniDumpNormal), exception_pointers ? &dump_exception_info : NULL, &user_streams, NULL) != FALSE; bool result_full_memory = true; if (full_memory_dump) { result_full_memory = write_dump( process_handle, process_id, full_dump_file, static_cast<MINIDUMP_TYPE>(dump_type & (~MiniDumpNormal)), exception_pointers ? &dump_exception_info : NULL, &user_streams, NULL) != FALSE; } bool result = result_minidump && result_full_memory; CloseHandle(dump_file); if (full_dump_file != <API key>) CloseHandle(full_dump_file); // Store the path of the dump file in the out parameter if dump generation // succeeded. if (result && dump_path) { *dump_path = dump_file_path; } return result; } HMODULE MinidumpGenerator::GetDbghelpModule() { AutoCriticalSection lock(&module_load_sync_); if (!dbghelp_module_) { dbghelp_module_ = LoadLibrary(TEXT("dbghelp.dll")); } return dbghelp_module_; } MinidumpGenerator::<API key> MinidumpGenerator::GetWriteDump() { AutoCriticalSection lock(&<API key>); if (!write_dump_) { HMODULE module = GetDbghelpModule(); if (module) { FARPROC proc = GetProcAddress(module, "MiniDumpWriteDump"); write_dump_ = reinterpret_cast<<API key>>(proc); } } return write_dump_; } HMODULE MinidumpGenerator::GetRpcrt4Module() { AutoCriticalSection lock(&module_load_sync_); if (!rpcrt4_module_) { rpcrt4_module_ = LoadLibrary(TEXT("rpcrt4.dll")); } return rpcrt4_module_; } MinidumpGenerator::UuidCreateType MinidumpGenerator::GetCreateUuid() { AutoCriticalSection lock(&module_load_sync_); if (!create_uuid_) { HMODULE module = GetRpcrt4Module(); if (module) { FARPROC proc = GetProcAddress(module, "UuidCreate"); create_uuid_ = reinterpret_cast<UuidCreateType>(proc); } } return create_uuid_; } bool MinidumpGenerator::<API key>(wstring* file_path) { UUID id = {0}; UuidCreateType create_uuid = GetCreateUuid(); if(!create_uuid) { return false; } create_uuid(&id); wstring id_str = GUIDString::GUIDToWString(&id); *file_path = dump_path_ + TEXT("\\") + id_str + TEXT(".dmp"); return true; } } // namespace google_breakpad
package com.nosolojava.fsm.impl.runtime.executable.basic; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import com.nosolojava.fsm.runtime.Context; import com.nosolojava.fsm.runtime.executable.Elif; import com.nosolojava.fsm.runtime.executable.Else; import com.nosolojava.fsm.runtime.executable.Executable; import com.nosolojava.fsm.runtime.executable.If; public class BasicIf extends BasicConditional implements If { private static final long serialVersionUID = -415238773021486012L; private final List<Elif> elifs = new ArrayList<Elif>(); private final Else elseOperation; public BasicIf(String condition) { this(condition, null, null, null); } public BasicIf(String condition, List<Executable> executables) { this(condition, null, null, executables); } public BasicIf(String condition, Else elseOperation, List<Executable> executables) { this(condition, null, elseOperation, executables); } public BasicIf(String condition, List<Elif> elifs, Else elseOperation, List<Executable> executables) { super(condition, executables); if (elifs != null) { this.elifs.addAll(elifs); } this.elseOperation = elseOperation; } @Override public boolean runIf(Context context) { boolean result = false; // if condition fails if (super.runIf(context)) { result = true; } else { // try with elifs boolean enterElif = false; Iterator<Elif> iterElif = elifs.iterator(); Elif elif; while (!enterElif && iterElif.hasNext()) { elif = iterElif.next(); enterElif = elif.runIf(context); } // if no elif and else if (!enterElif && this.elseOperation != null) { elseOperation.run(context); } } return result; } public List<Elif> getElifs() { return this.elifs; } public void addElif(Elif elif) { this.elifs.add(elif); } public void addElifs(List<Elif> elifs) { this.elifs.addAll(elifs); } public void clearAndSetElifs(List<Elif> elifs) { this.elifs.clear(); addElifs(elifs); } }
package me.littlepanda.dadbear.core.queue; import java.util.Queue; /** * @author myplaylife@icloud.com * */ public interface DistributedQueue<T> extends Queue<T> { /** * <p></p> * @param queue_name * @param clazz */ abstract public void init(String queue_name, Class<T> clazz); }
# Changelog [![GitHub commits since latest release](https: ## Release Notes - [v3.2.0](#v3.2.0) - [v3.1.0](#v3.1.0) - [v3.0.0](#v3.0.0) - [v3.0.1](#v3.0.1) - [v2.5.0](#v2.5.0) - [v2.5.1](#v2.5.1) - [v2.4.0](#v2.4.0) - [v2.3.0](#v2.3.0) - [v2.2.0](#v2.2.0) - [v2.2.0-beta](#v2.2.0-beta) - [v2.1.0](#v2.1.0) - [v2.1.1](#v2.1.1) - [v2.0.0](#v2.0.0) - [v2.0.1](#v2.0.1) - [v2.0.2](#v2.0.2) - [v1.8.0](#v1.8.0) - [v1.8.1](#v1.8.1) - [v1.7.0](#v1.7.0) - [v1.6.0](#v1.6.0) - [v1.5.0](#v1.5.0) - [v1.5.1](#v1.5.1) - [v1.5.2](#v1.5.2) - [v1.4.0](#v1.4.0) - [v1.4.1](#v1.4.1) - [v1.3.0](#v1.3.0) - [v1.2.0](#v1.2.0) - [v1.1.0](#v1.1.0) - [v1.0.8](#v1.0.8) - [v1.0.7](#v1.0.7) - [v1.0.6](#v1.0.6) - [v1.0.5](#v1.0.5) - [v1.0.4](#v1.0.4) - [v1.0.3](#v1.0.3) - [v1.0.2](#v1.0.2) <! RELEASE CHANGELOG TEMPLATE: <a name="vX.Y.Z"></a> COMPATIBILITY KNOWN ISSUES BREAKING CHANGES Bug Fixes Features Improvements Docker Images Documentation <a name="v3.2.0"></a> COMPATIBILITY - VPP 20.09 (compatible) - VPP 20.05 (default) - VPP 20.01 (backwards compatible) - VPP 19.08 (backwards compatible) - ~~VPP 19.04~~ (no longer supported) Bug Fixes - Fixes and improvements for agentctl and models [ - Fix creation of multiple ipip tunnels [ - Fix IPSec tun protect + add IPSec e2e test [ - Fix bridge domain dump for VPP 20.05 [ - Fix IPSec SA add/del in VPP 20.05 [ - Update expected output of agentctl status command [ - vpp/ifplugin: Recognize interface name prefix "tun" as TAP [ - Fix IPv4 link-local IP address handling [ - maps caching prometheus gauges weren't really used [ - Permit agent to run even when VPP stats are unavailable [ - Fix grpc context timeout for agentctl import command [ - Changed nat44 pool key to prevent possible key collisions [ - Remove forced delay for linux interface notifications [ Features - agentctl: Add config get/update commands [ - agentctl: Support specific history seq num and improve layout [ - agentctl: Add config.resync subcommand (with resync) [ - IP Flow Information eXport (IPFIX) plugin [ - Add IPIP & IPSec point-to-multipoint support [ - Wireguard plugin support [ - Add tunnel mode support for VPP TAP interfaces [ - New REST endpoint for retrieving version of Agent [ - Add support for IPv6 ND address autoconfig [ - Add VRF field to proxy ARP range [ - Switch to new proto v2 (google.golang.org/protobuf) [ - ipsec: allow configuring salt for encryption algorithm [ - gtpu: Add RemoteTeid to GTPU interface [ - Added support for NAT44 static mapping twice-NAT pool IP address reference [ - add IP protocol number to ACL model [ - gtpu: Add support for arbitrary DecapNextNode [ - configurator: Add support for waiting until config update is done [ - telemetry: Add reading VPP threads to the telemetry plugin [ - linux: Add support for Linux VRFs [ - VRRP support [ Improvements - perf: Performance enhancement for adding many rules to Linux IP… [ - Improve testing process for e2e/integration tests [ Documentation - docs: Add example for developing agents with custom VPP plugins [ Other - Delete unused REST handler for VPP commands [ - separate model for IPSec Security Policies [ - do not mark host_if_name for AF_PACKET as deprecated [ - Store interface internal name & dev type as metadata [ - Check if HostIfName contains non-printable characters [ - Fix error message for duplicate keys [ <a name="v3.1.0"></a> BREAKING CHANGES * Switch cn-infra dependency to using vanity import path [ To migrate, replace all cn-infra import paths (`github.com/ligato/cn-infra` -> `go.ligato.io/cn-infra/v2`) To update cn-infra dependency, run `go get -u go.ligato.io/cn-infra/v2@master`. Bug Fixes * Add missing models to ConfigData [ * Fix watching VPP events [ Features * Allow customizing polling from stats poller [ * IPIP tunnel + IPSec tunnel protection support [ * Add prometheus metrics to govppmux [ * Add prometheus metrics to kvscheduler [ Improvements * Improve performance testing suite [ <a name="v3.0.1"></a> Bug Fixes * Add missing models to ConfigData (https://github.com/ligato/vpp-agent/pull/1625) <a name="v3.0.0"></a> COMPATIBILITY - **VPP 20.01** (default) - **VPP 19.08.1** (recommended) - **VPP 19.04.4** KNOWN ISSUES - VPP L3 plugin: `IPScanNeighbor` was disabled for VPP 20.01 due to VPP API changes (will be implemented later using new model) - VPP NAT plugin: `VirtualReassembly` in `Nat44Global` was disabled for VPP 20.01 due to VPP API changes (will be implemented later in VPP L3 plugin using new model) BREAKING CHANGES - migrate from dep to Go modules for dependency management and remove vendor directory [ - use vanity import path `go.ligato.io/vpp-agent/v3` in Go files [ - move all _.proto_ files into `proto/ligato` directory and add check for breaking changes [ Bug Fixes - check for duplicate Linux interface IP address [ New Features - VPP interface plugin: Allow AF-PACKET to reference target Linux interface via logical name [ - VPP L3 plugin: add support for L3 cross-connects [ - VPP L3 plugin: IP flow hash settings support [ - VPP NAT plugin: NAT interface and AddressPool API changes [ - VPP plugins: support disabling VPP plugins [ - VPP client: add support for govpp proxy [ Improvements - optimize getting model keys, with up to 20% faster transactions [ - agentctl output formatting improvements (#1581, #1582, #1589) - generated VPP binary API now imports common types from `*_types` packages - development docker images now have smaller size (~400MB less) - start using Github Workflows for CI/CD pipeline - add gRPC reflection service <a name="v2.5.1"></a> COMPATIBILITY - **VPP 20.01-379** (`20.01-rc0~379-ga6b93eac5`) - **VPP 20.01-324** (`20.01-rc0~324-g66a332cf1`) - **VPP 19.08.1** (default) - **VPP 19.04** (backward compatible) - cn-infra v2.2 Bug Fixes * Fix linux interface dump ([ * Fix VRF for SR policy ([ <a name="v2.5.0"></a> Compatibility - **VPP 20.01-379** (`20.01-rc0~379-ga6b93eac5`) - **VPP 20.01-324** (`20.01-rc0~324-g66a332cf1`) - **VPP 19.08.1** (default) - **VPP 19.04** (backward compatible) - cn-infra v2.2 New Features * SRv6 global config (encap source address) * Support for Linux configuration dumping Bug Fixes * Update GoVPP with fix for stats conversion panic <a name="v2.4.0"></a> Compatibility - **VPP 20.01-379** (`20.01-rc0~379-ga6b93eac5`) - **VPP 20.01-324** (`20.01-rc0~324-g66a332cf1`) - **VPP 19.08.1** (default) - **VPP 19.04** (backward compatible) - cn-infra v2.2 New Features This release introduces compatibility with two different commits of the VPP 20.01. Previously compatible version was updated to commit `324-g66a332cf1`, and support for `379-ga6b93eac5` was added. Other previous versions remained. * [Telemetry][vpp-telemetry] - Added `StatsPoller` service periodically retrieving VPP stats. <a name="v2.3.0"></a> Compatibility - **VPP 20.01** (`20.01-rc0~161-ge5948fb49~b3570`) - **VPP 19.08.1** (default) - **VPP 19.04** (backward compatible) - cn-infra v2.2 VPP support for version 19.08 was updated to 19.08.1. Support for 19.01 was dropped in this release. Bug Fixes * Linux interfaces with 'EXISTING' type should be resynced properly. * Resolved issue with SRv6 removal. * AgentCTL dump command fixed. * ACL ICMP rule is now properly configured and data can be obtained using the ACL dump. * Missing dependency for SRv6 L2 steering fixed. * Fixed issue with possible division by zero and missing interface MTU. * Namespace plugin uses a Docker event listener instead of periodical polling. This should prevent cases where quickly started microservice container was not detected. New Features * [netalloc-plugin][netalloc-plugin] - A new plugin called netalloc which allows disassociating topology from addressing in the network configuration. Interfaces, routes and other network objects' addresses can be symbolic references into the pool of allocated addresses known to netalloc plugin. See [model][<API key>] for more information. * [if-plugin][<API key>] - Added support for GRE tunnel interfaces. Choose the `GRE_TUNNEL` interface type with appropriate link data. * [agentctl][agentctl] - Many new features and enhancements added to the AgentCTL: * version is defined as a parameter for root command instead of the separate command * ETCD endpoints can be defined via the `ETCD_ENDPOINTS` environment variable * sub-command `config` supports `get/put/del` commands * `model` sub-commands improved * added VPP command to manage VPP instance Additionally, starting with this release the AgentCTL is a VPP-Agent main control tool and the vpp-agent-ctl was definitely removed. Improvements Many end-to-end tests introduced, gradually increasing VPP-Agent stability. * [if-plugin][<API key>] - IP addresses assigned by the DHCP are excluded from the interface address descriptor. - VPP-Agent now processes status change notifications labeled by the VPP as UNKNOWN. * [ns-plugin][linux-ns-plugin] - Dockerclient microservice polling replaced with an event listener. * [sr-plugin][sr-plugin] - SRv6 dynamic proxy routing now can be connected to a non-zero VRF table. <a name="v2.2.0"></a> Compatibility - **VPP 19.08** (rc1) - **VPP 19.04** (default) - **VPP 19.01** (backward compatible) - cn-infra v2.2 Bug Fixes - CN-infra version updated to 2.2 contains a supervisor fix which should prevent the issue where the supervisor logging occasionally caused the agent to crash during large outputs. New Features * [if-plugin][<API key>] - Added option to configure SPAN records. Northbound data are formatted by the [SPAN model][span-model]. Improvements * [orchestrator][orchestrator-plugin] - Clientv2 is now recognized as separate data source by the orchestrator plugin. This feature allows to use the localclient together with other data sources. Documentation - Updated documentation comments in the protobuf API. <a name="v2.2.0-beta"></a> Compatibility - **VPP 19.08** (rc1) - **VPP 19.04** (default) - **VPP 19.01** (backward compatible) Bug Fixes * Fixed SRv6 localsid delete case for non-zero VRF tables. * Fixed interface IPv6 detection in the descriptor. * Various bugs fixed in KV scheduler TXN post-processing. * Interface plugin config names fixed, no stats publishers are now used by default. Instead, datasync is used (by default ETCD, Redis and Consul). * Rx-placement and rx-mode is now correctly dependent on interface link state. * Fixed crash for iptables rulechain with default microservice. * Punt dump fixed in all supported VPP versions. * Removal of registered punt sockets fixed after a resync. * Punt socket paths should no longer be unintentionally recreated. * IP redirect is now correctly dependent on RX interface. * Fixed IPSec security association configuration for tunnel mode. * Fixed URL for VPP metrics in telemetry plugin * Routes are now properly dependent on VRF. New Features * Defined new environment variable `<API key>` to generally disable interface plugin stats. * Defined new environment variable `RESYNC_TIMEOU` to override default resync timeout. * Added [ETCD ansible python plugin][ansible] with example playbook. Consult [readme](ansible/README.md) for more information. Improvements * [govppmux-plugin][govppmux-plugin] - GoVPPMux stats can be read with rest under path `/govppmux/stats`. - Added disabling of interface stats via the environment variable `<API key>`. - Added disabling of interface status publishing via environment variable `<API key>`. * [kv-scheduler][kv-scheduler] - Added some more performance improvements. - The same key can be no more matched by multiple descriptors. * [abf-plugin][vpp-abf-plugin] - ABF plugin was added to config data model and is now initialized in configurator. * [if-plugin][<API key>] - Interface rx-placement and rx-mode was enhanced and now allows per-queue configuration. - Added [examples](examples/kvscheduler/rxplacement) for rx-placement and rx-mode. * [nat-plugin][vpp-nat-plugin] - NAT example updated for VPP 19.04 * [l3-plugin][vpp-l3-plugin] - Route keys were changed to prevent collisions with some types of configuration. Route with outgoing interface now contains the interface name in the key. - Added support for DHCP proxy. A new descriptor allows calling CRUD operations to VPP DHCP proxy servers. * [punt-plugin][vpp-punt-plugin] - Added support for Punt exceptions. - IP redirect dump was implemented for VPP 19.08. * [Telemetry][vpp-telemetry] - Interface metrics added to telemetry plugin. Note that the URL for prometheus export was changed to `/metrics/vpp`. - Plugin configuration file now has an option to skip certain metrics. * [rest-plugin][rest-plugin] - Added support for IPSec plugin - Added support for punt plugin * [agentctl][agentctl] - We continuously update the new CTL tool. Various bugs were fixed some new features added. - Added new command `import` which can import configuration from file. Docker Images * The supervisor was replaced with VPP-Agent init plugin. * Images now use pre-built VPP images from [ligato/vpp-base](https://github.com/ligato/vpp-base) <a name="v2.1.1"></a> Compatibility - **VPP 19.04** (`stable/1904`, recommended) - **VPP 19.01** (backward compatible) Bug Fixes * Fixed IPv6 detection for Linux interfaces [ * Fixed config file names for ifplugin in VPP & Linux [ * Fixed setting status publishers from env var: `<API key>`. Improvements * The start/stop timeouts for agent can be configured using env vars: `START_TIMEOUT=15s` and `STOP_TIMEOUT=5s`, with values parsed as duration. * ABF was added to the `ConfigData` message for VPP [ Docker Images * Images now install all compiled .deb packages from VPP (including `vpp-plugin-dpdk`). <a name="v2.1.0"></a> Compatibility - **VPP 19.04** (`stable/1904`, recommended) - **VPP 19.01** (backward compatible) - cn-infra v2.1 - Go 1.11 The VPP 18.10 was deprecated and is no longer compatible. BREAKING CHANGES * All non-zero VRF tables now must be explicitly created, providing a VRF proto-modeled data to the VPP-Agent. Otherwise, some configuration items will not be created as before (for example interface IP addresses). Bug Fixes * VPP ARP `retrieve` now also returns IPv6 entries. New Features * [govppmux-plugin][govppmux-plugin] - The GoVPPMux plugin configuration file contains a new option `ConnectViaShm`, which when set to `true` forces connecting to the VPP via shared memory prefix. This is an alternative to environment variable `GOVPPMUX_NOSOCK`. * [configurator][configurator-plugin] - The configurator plugin now collects statistics which are available via the `GetStats()` function or via REST on URL `/stats/configurator`. * [kv-scheduler][kv-scheduler] - Added transaction statistics. * [abf-plugin][vpp-abf-plugin] - Added new plugin ABF - ACL-based forwarding, providing an option to configure routing based on matching ACL rules. An ABF entry configures interfaces which will be attached, list of forwarding paths and associated access control list. * [if-plugin][<API key>] - Added support for Generic Segmentation Offload (GSO) for TAP interfaces. * [l3-plugin][vpp-l3-plugin] - A new model for VRF tables was introduced. Every VRF is defined by an index and an IP version, a new optional label was added. Configuration types using non-zero VRF now require it to be created, since the VRF is considered a dependency. VRFs with zero-index are present in the VPP by default and do not need to be configured (applies for both, IPv4 and IPv6). * [agentctl][agentctl] - This tool becomes obsolete and was completely replaced with a new implementation. Please note that the development of this tool is in the early stages, and functionality is quite limited now. New and improved functionality is planned for the next couple of releases since our goal is to have a single vpp-agent control utility. Because of this, we have also deprecated the vpp-agent-ctl tool which will be most likely removed in the next release. Improvements * [kv-scheduler][kv-scheduler] - The KV Scheduler received another performance improvements. * [if-plugin][<API key>] - Attempt to configure a Bond interface with already existing ID returns a non-retriable error. * [linux-if-plugin][<API key>] - Before adding an IPv6 address to the Linux interface, the plugins will use `sysctl` to ensure the IPv6 is enabled in the target OS. Docker Images - Supervisord is started as a process with PID 1 Documentation - The ligato.io webpage is finally available, check out it [here][ligato.io]! We have also released a [new documentation site][ligato-docs] with a lot of new or updated articles, guides, tutorials and many more. Most of the README.md files scattered across the code were removed or updated and moved to the site. <a name="v2.0.2"></a> Compatibility - **VPP 19.01** (updated to `v19.01.1-14-g0f36ef60d`) - **VPP 18.10** (backward compatible) - cn-infra v2.0 - Go 1.11 This minor release brought compatibility with updated version of the VPP 19.01. <a name="v2.0.1"></a> Compatibility - **VPP 19.01** (compatible by default, recommended) - **VPP 18.10** (backward compatible) - cn-infra v2.0 - Go 1.11 Bug Fixes * Fixed bug where Linux network namespace was not reverted in some cases. * The VPP socketclient connection checks (and waits) for the socket file in the same manner as for the shared memory, giving the GoVPPMux more time to connect in case the VPP startup is delayed. Also errors occurred during the shm/socket file watch are now properly handled. * Fixed wrong dependency for SRv6 end functions referencing VRF tables (DT6,DT4,T). Improvements * [GoVPPMux][govppmux-plugin] - Added option to adjust the number of connection attempts and time delay between them. Seek `retry-connect-count` and `<API key>` fields in [govpp.conf][govppmux-conf]. Also keep in mind the total time in which plugins can be initialized when using these fields. * [linux-if-plugin][<API key>] - Default loopback MTU was set to 65536. * [ns-plugin][linux-ns-plugin] - Plugin descriptor returns `ErrEscapedNetNs` if Linux namespace was changed but not reverted back before returned to scheduler. Docker Images * Supervisord process is now started with PID=1 <a name="v2.0.0"></a> Compatibility - **VPP 19.01** (compatible by default, recommended) - **VPP 18.10** (backward compatible) - cn-infra v2.0 - Go 1.11 BREAKING CHANGES * All northbound models were re-written and simplified and most of them are no longer compatible with model data from v1. * The `v1` label from all vpp-agent keys was updated to `v2`. * Plugins using some kind of dependency on other VPP/Linux plugin (for example required interface) should be updated and handled by the KVScheduler. Bug Fixes * We expect a lot of known and unknown race-condition and plugin dependency related issues to be solved by the KV Scheduler. * MTU is omitted for the sub-interface type. * If linux plugin attempts to switch to non-existing namespace, it prints appropriate log message as warning, and continues with execution instead of interrupt it with error. * Punt socket path string is cleaned from unwanted characters. * Added VPE compatibility check for L3 plugin vppcalls. * The MAC address assigned to an af-packet interface is used from the host only if not provided from the configuration. * Fixed bug causing the agent to crash in an attempt to 'update' rx-placement with empty value. * Switch interface from zero to non-zero VRF causes VPP issues - this limitation was now restricted only to unnumbered interfaces. * IPSec tunnel dump now also retrieves integ/crypto keys. * Errored operation should no more publish to the index mapping. * Some obsolete Retval checks were removed. * Error caused by missing DPDK interface is no longer retryable. * Linux interface IP address without mask is now handled properly. * Fixed bug causing agent to crash when some VPP plugin we support was not loaded. * Fixed metrics retrieval in telemetry plugin. Known Issues * The bidirectional forwarding detection (aka BFD plugin) was removed. We plan to add it in one of the future releases. * The L4 plugin (application namespaces) was removed. * We experienced problems with the VPP with some messages while using socket client connection. The issue kind was that the reply message was not returned (GoVPP could not decode it). If you encounter similar error, please try to setup VPP connection using shared memory (see below). Features * Performance - The vpp-agent now supports connection via socket client (in addition to shared memory). The socket client connection provides higher performance and message throughput, thus it was set as default connection type. The shared memory is still available via the environment variable `GOVPPMUX_NOSOCK`. - Many other changes, benchmarking and profiling was done to improve vpp-agent experience. * Multi-VPP support - The VPP-agent can connect to multiple versions of the VPP with the same binary file without any additional building or code changes. See compatibility part to know which versions are supported. The list will be extended in the future. * Models - All vpp-agent models were reviewed and cleaned up. Various changes were done, like simple renaming (in order to have more meaningful fields, avoid duplicated names in types, etc.), improved model convenience (interface type-specific fields are now defined as `oneof`, preventing to set multiple or incorrect data) and other. All models were also moved to the common [api][models] folder. * [KVScheduler][kv-scheduler] - Added new component called KVScheduler, as a reaction to various flaws and issues with race conditions between Vpp/Linux plugins, poor readability and poorly readable logging. Also the system of notifications between plugins was unreliable and hard to debug or even understand. Based on this experience, a new framework offers improved generic mechanisms to handle dependencies between configuration items and creates clean and readable transaction-based logging. Since this component significantly changed the way how plugins are defined, we recommend to learn more about it on the [VPP-Agent wiki page][wiki]. * [orchestrator][orchestrator-plugin] - The orchestrator is a new component which long-term added value will be a support for multiple northbound data sources (KVDB, GRPC, ...). The current implementation handles combination of GRPC + KVDB, which includes data changes and resync. In the future, any combination of sources will be supported. * [GoVPPMux][govppmux-plugin] - Added `Ping()` method to the VPE vppcalls usable to test the VPP connection. * [if-plugin][<API key>] - UDP encapsulation can be configured to an IPSec tunnel interface - Support for new Bond-type interfaces. - Support for L2 tag rewrite (currently present in the interface plugin because of the inconsistent VPP API) * [nat-plugin][vpp-nat-plugin] - Added support for session affinity in NAT44 static mapping with load balancer. * [sr-plugin][sr-plugin] - Support for Dynamic segment routing proxy with L2 segment routing unaware services. - Added support for SRv6 end function End.DT4 and End.DT6. * [linux-if-plugin][<API key>] - Added support for new Linux interface type - loopback. - Attempt to assign already existing IP address to the interface does not cause an error. * [linux-iptables][<API key>] - Added new linux IP tables plugin able to configure IP tables chain in the specified table, manage chain rules and set default chain policy. Improvements * [KVScheduler][kv-scheduler] - Performance improvements related to memory management. * [GoVPPMux][govppmux-plugin] - Need for config file was removed, GoVPP is now set with default values if the startup config is not provided. - `DefaultReplyTimeout` is now configured globally, instead of set for every request separately. - Tolerated default health check timeout is now set to 250ms (up from 100ms). The old value had not provide enough time in some cases. * [acl-plugin][vpp-acl-plugin] - Model moved to the [api/models][models] * [if-plugin][<API key>] - Model reviewed, updated and moved to the [api/models][models]. - Interface plugin now handles IPSec tunnel interfaces (previously done in IPSec plugin). - NAT related configuration was moved to its own plugin. - New interface stats (added in 1.8.1) use new GoVPP API, and publishing frequency was significantly decreased to handle creation of multiple interfaces in short period of time. * [IPSec-plugin][vpp-ipsec-plugin] - Model moved to the [api/models][models] - The IPSec interface is no longer processed by the IPSec plugin (moved to interface plugin). - The ipsec link in interface model now uses the enum definitions from IPSec model. Also some missing crypto algorithms were added. * [l2-plugin][vpp-l2-plugin] - Model moved to the [api/models][models] and split to three separate models for bridge domains, FIBs and cross connects. * [l3-plugin][vpp-l3-plugin] - Model moved to the [api/models][models] and split to three separate models for ARPs, Proxy ARPs including IP neighbor and Routes. * [nat-plugin][vpp-nat-plugin] - Defined new plugin to handle NAT-related configuration and its own [model][nat-proto] (before a part of interface plugin). * [punt-plugin][vpp-punt-plugin] - Model moved to the [api/models][models]. - Added retrieve support for punt socket. The current implementation is not final - plugin uses local cache (it will be enhanced when the appropriate VPP binary API call will be added). * [stn-plugin][vpp-stn-plugin] - Model moved to the [api/models][models]. * [linux-if-plugin][<API key>] - Model reviewed, updated and moved to the [api/models][models]. * [linux-l3-plugin][linux-l3-plugin] - Model moved to the [api/models][models] and split to separate models for ARPs and Routes. - Linux routes and ARPs have a new dependency - the target interface is required to contain an IP address. * [ns-plugin][ns-plugin] - New auxiliary plugin to handle linux namespaces and microservices (evolved from ns-handler). Also defines [model][ns-proto] for generic linux namespace definition. Docker Images * Configuration file for GoVPP was removed, forcing to use default values (which are the same as they were in the file). * Fixes for installing ARM64 debugger. * Kafka is no longer required in order to run vpp-agent from the image. Documentation * Added documentation for the punt plugin, describing main features and usage of the punt plugin. * Added documentation for the [IPSec plugin][vpp-ipsec-plugin], describing main and usage of the IPSec plugin. * Added documentation for the [interface plugin][<API key>]. The document is only available on [wiki page][wiki]. * Description improved in various proto files. * Added a lot of new documentation for the KVScheduler (examples, troubleshooting, debugging guides, diagrams, ...) * Added tutorial for KV Scheduler. * Added many new documentation articles to the [wiki page][wiki]. However, most of is there only temporary since we are preparing new ligato.io website with all the documentation and other information about the Ligato project. Also majority of readme files from the vpp-agent repository will be removed in the future. <a name="v1.8.1"></a> Motive for this minor release was updated VPP with several fixed bugs from the previous version. The VPP version also introduced new interface statistics mechanism, thus the stats processing was updated in the interface plugin. Compatibility - v19.01-16~gd30202244 - cn-infra v1.7 - GO 1.11 Bug Fixes - VPP bug: fixed crash when attempting to run in kubernetes pod - VPP bug: fixed crash in barrier sync when vlib_worker_threads is zero Features - [vpp-ifplugin][<API key>] * Support for new VPP stats (the support for old ones were deprecated by the VPP, thus removed from the vpp-agent as well). <a name="v1.8.0"></a> Compatibility - VPP v19.01-rc0~394-g6b4a32de - cn-infra v1.7 - Go 1.11 Bug Fixes * Pre-existing VETH-type interfaces are now read from the default OS namespace during resync if the Linux interfaces were dumped. * The Linux interface dump method does not return an error if some interface namespace becomes suddenly unavailable at the read-time. Instead, this case is logged and all the other interfaces are returned as usual. * The Linux localclient's delete case for Linux interfaces now works properly. * The Linux interface dump now uses OS link name (instead of vpp-agent specific name) to read the interface attributes. This sometimes caused errors where an incorrect or even none interface was read. * Fixed bug where the unsuccessful namespace switch left the namespace file opened. * Fixed crash if the Linux plugin was disabled. * Fixed occasional crash in vpp-agent interface notifications. * Corrected interface counters for TX packets. * Access list with created TCP/UDP/ICMP rule, which remained as empty struct no longer causes vpp-agent to crash Features - [vpp-ifplugin][<API key>] * Rx-mode and Rx-placement now support dump via the respective binary API call - vpp-rpc-plugin * GRPC now supports also IPSec configuration. * All currently supported configuration items can be also dumped/read via GRPC (similar to rest) * GRPC now allows to automatically persist configuration to the data store. The desired DB has to be defined in the new GRPC config file (see [readme][readme] for additional information). - [vpp-punt][punt-model] * Added simple new punt plugin. The plugin allows to register/unregister punt to host via Unix domain socket. The new [model][punt-model] was added for this configuration type. Since the VPP API is incomplete, the configuration does not support dump. Improvements - [vpp-ifplugin][<API key>] * The VxLAN interface now support IPv4/IPv6 virtual routing and forwarding (VRF tables). * Support for new interface type: VmxNet3. The VmxNet3 virtual network adapter has no physical counterpart since it is optimized for performance in a virtual machine. Because built-in drivers for this card are not provided by default in the OS, the user must install VMware Tools. The interface model was updated for the VmxNet3 specific configuration. - [ipsec-plugin][vpp-ipsec-plugin] * IPSec resync processing for security policy databases (SPD) and security associations (SA) was improved. Data are properly read from northbound and southbound, compared and partially configured/removed, instead of complete cleanup and re-configuration. This does not appeal to IPSec tunnel interfaces. * IPSec tunnel can be now set as an unnumbered interface. - [rest-plugin][rest-plugin] * In case of error, the output returns correct error code with cause (parsed from JSON) instead of an empty body <a name="v1.7.0"></a> Compatibility - VPP 18.10-rc0~505-ge23edac - cn-infra v1.6 - Go 1.11 Bug Fixes * Corrected several cases where various errors were silently ignored * GRPC registration is now done in Init() phase, ensuring that it finishes before GRPC server is started * Removed occasional cases where Linux tap interface was not configured correctly * Fixed FIB configuration failures caused by wrong updating of the metadata after several modifications * No additional characters are added to NAT tag and can be now configured with the full length without index out of range errors * Linux interface resync registers all VETH-type interfaces, despite the peer is not known * Status publishing to ETCD/Consul now should work properly * Fixed occasional failure caused by concurrent map access inside Linux plugin interface configurator * VPP route dump now correctly recognizes route type Features - [vpp-ifplugin][<API key>] * It is now possible to dump unnumbered interface data * Rx-placement now uses specific binary API to configure instead of generic CLI API - [vpp-l2plugin][vpp-l2-plugin] * Bridge domain ARP termination table can now be dumped - [linux-ifplugin][<API key>] * Linux interface watcher was reintroduced. * Linux interfaces can be now dumped. - [linux-l3plugin][linux-l3-plugin] * Linux ARP entries and routes can be dumped. Improvements - [vpp-plugins][vpp-plugins] * Improved error propagation in all the VPP plugins. Majority of errors now print the stack trace to the log output allowing better error tracing and debugging. * Stopwatch was removed from all vppcalls - [linux-plugins][linux-plugins] * Improved error propagation in all Linux plugins (same way as for VPP) * Stopwatch was removed from all linuxcalls - [govpp-plugn][govppmux-plugin] * Tracer (introduced in cn-infra 1.6) added to VPP message processing, replacing stopwatch. The measurement should be more precise and logged for all binary API calls. Also the rest plugin now allows showing traced entries. Docker Images * The image can now be built on ARM64 platform <a name="v1.6.0"></a> Compatibility - VPP 18.10-rc0~169-gb11f903a - cn-infra v1.5 BREAKING CHANGES - Flavors were replaced with new way of managing plugins. - REST interface URLs were changed, see [readme][readme] for complete list. Bug Fixes * if VPP routes are dumped, all paths are returned * NAT load-balanced static mappings should be resynced correctly * telemetry plugin now correctly parses parentheses for `show node counters` * telemetry plugin will not hide an error caused by value loading if the config file is not present * Linux plugin namespace handler now correctly handles namespace switching for interfaces with IPv6 addresses. Default IPv6 address (link local) will not be moved to the new namespace if there are no more IPv6 addresses configured within the interface. This should prevent failures in some cases where IPv6 is not enabled in the destination namespace. * VxLAN with non-zero VRF can be successfully removed * Lint is now working again * VPP route resync works correctly if next hop IP address is not defined Features * Deprecating flavors - CN-infra 1.5 brought new replacement for flavors and it would be a shame not to implement it in the vpp-agent. The old flavors package was removed and replaced with this new concept, visible in app package vpp-agent. - [rest plugin][rest-plugin] * All VPP configuration types are now supported to be dumped using REST. The output consists of two parts; data formatted as NB proto model, and metadata with VPP specific configuration (interface indexes, different counters, etc.). * REST prefix was changed. The new URL now contains API version and purpose (dump, put). The list of all URLs can be found in the [readme][readme] - [ifplugin][<API key>] * Added support for NAT virtual reassembly for both, IPv4 and IPv6. See change in [nat proto file][nat-proto] - [l3plugin][vpp-l3-plugin] * Vpp-agent now knows about DROP-type routes. They can be configured and also dumped. VPP default routes, which are DROP-type is recognized and registered. Currently, resync does not remove or correlate such a route type automatically, so no default routes are unintentionally removed. * New configurator for L3 IP scan neighbor was added, allowing to set/unset IP scan neigh parameters to the VPP. Improvements - [vpp plugins][vpp-plugins] * all vppcalls were unified under API defined for every configuration type (e.g. interfaces, l2, l3, ...). Configurators now use special handler object to access vppcalls. This should prevent duplicates and make vppcalls cleaner and more understandable. - [ifplugin][<API key>] * VPP interface DHCP configuration can now be dumped and added to resync processing * Interfaces and also L3 routes can be configured for non-zero VRF table if IPv6 is used. - [examples][examples] * All examples were reworked to use new flavors concept. The purpose was not changed. Docker Images - using Ubuntu 18.04 as the base image <a name="v1.5.2"></a> Compatibility - VPP 18.07-rc0~358-ga5ee900 - cn-infra v1.4.1 (minor version fixes bug in Consul) Bug Fixes - [Telemetry][vpp-telemetry] * Fixed bug where lack of config file could cause continuous polling. The interval now also cannot be changed to a value less than 5 seconds. * Telemetry plugin is now closed properly <a name="v1.5.1"></a> ## 1.5.1 (2018-07-20) Compatibility - VPP 18.07-rc0~358-ga5ee900 - cn-infra v1.4 Features - [Telemetry][vpp-telemetry] * Default polling interval was raised to 30s. * Added option to use telemetry config file to change polling interval, or turn the polling off, disabling the telemetry plugin. The change was added due to several reports where often polling is suspicious of interrupting VPP worker threads and causing packet drops and/or other negative impacts. More information how to use the config file can be found in the [readme][readme]. <a name="v1.5.0"></a> Compatibility - VPP 18.07-rc0~358-ga5ee900 - cn-infra v1.4 BREAKING CHANGES - The package `etcdv3` was renamed to `etcd`, along with its flag and configuration file. - The package `defaultplugins` was renamed to `vpp` to make the purpose of the package clear Bug Fixes - Fixed a few issues with parsing VPP metrics from CLI for [Telemetry][vpp-telemetry]. - Fixed bug in GoVPP occurring after some request timed out, causing the channel to receive replies from the previous request and always returning an error. - Fixed issue which prevented setting interface to non-existing VRF. - Fixed bug where removal of an af-packet interface caused attached Veth to go DOWN. - Fixed NAT44 address pool resolution which was not correct in some cases. - Fixed bug with adding SR policies causing incomplete configuration. Features - [LinuxPlugin][<API key>] * Is now optional and can be disabled via configuration file. - [ifplugin][<API key>] * Added support for VxLAN multicast * Rx-placement can be configured on VPP interfaces - [IPsec][vpp-ipsec-plugin] * IPsec UDP encapsulation can now be set (NAT traversal) Docker Images - Replace `START_AGENT` with `OMIT_AGENT` to match `RETAIN_SUPERVISOR` and keep both unset by default. - Refactored and cleaned up execute scripts and remove unused scripts. - Fixed some issues with `RETAIN_SUPERVISOR` option. - Location of supervisord pid file is now explicitly set to `/run/supervisord.pid` in *supervisord.conf* file. - The vpp-agent is now started with single flag `--config-dir=/opt/vpp-agent/dev`, and will automatically load all configuration from that directory. <a name="v1.4.1"></a> A minor release using newer VPP v18.04 version. Compatibility - VPP v18.04 (2302d0d) - cn-infra v1.3 Bug Fixes - VPP submodule was removed from the project. It should prevent various problems with dependency resolution. - Fixed known bug present in the previous version of the VPP, issued as [VPP-1280][vpp-issue-1280]. Current version contains appropriate fix. <a name="v1.4.0"></a> Compatibility - VPP v18.04 (ac2b736) - cn-infra v1.3 Bug Fixes * Fixed case where the creation of the Linux route with unreachable gateway threw an error. The route is now appropriately cached and created when possible. * Fixed issue with GoVPP channels returning errors after a timeout. * Fixed various issues related to caching and resync in L2 cross-connect * Split horizon group is now correctly assigned if an interface is created after bridge domain * Fixed issue where the creation of FIB while the interface was not a part of the bridge domain returned an error. Known issues * VPP crash may occur if there is interface with non-default VRF (>0). There is an [VPP-1280][vpp-issue-1280] issue created with more details Features - [Consul][consul] * Consul is now supported as a key-value store alternative to ETCD. More information in the [readme][readme]. - [Telemetry][vpp-telemetry] * New plugin for collecting telemetry data about VPP metrics and serving them via HTTP server for Prometheus. More information in the [readme][readme]. - [Ipsecplugin][vpp-ipsec-plugin] * Now supports tunnel interface for encrypting all the data passing through that interface. - GRPC * Vpp-agent itself can act as a GRPC server (no need for external executable) * All configuration types are supported (incl. Linux interfaces, routes and ARP) * Client can read VPP notifications via vpp-agent. - [SR plugin][sr-plugin] * New plugin with support for Segment Routing. More information in the [readme][readme]. Improvements - [ifplugin][<API key>] * Added support for self-twice-NAT - __vpp-agent-grpc__ executable merged with [vpp-agent][vpp-agent] command. - [govppmux][govppmux-plugin] * `configure reply timeout` can be configured. * Support for VPP started with custom shared memory prefix. SHM may be configured via the GoVPP plugin config file. More info in the [readme][readme] * Overall redundancy cleanup and corrected naming for all proto models. * Added more unit tests for increased coverage and code stability. Documentation - [localclient_linux][examples-vpp-local] now contains two examples, the old one demonstrating basic plugin functionality was moved to plugin package, and specialised example for [NAT][examples-nat] was added. - [localclient_linux][<API key>] now contains two examples, the old one demonstrating [veth][examples-veth] interface usage was moved to package and new example for linux [tap][examples-tap] was added. <a name="v1.3.0"></a> The vpp-agent is now using custom VPP branch [stable-1801-contiv][contiv-vpp1810]. Compatibility - VPP v18.01-rc0~605-g954d437 - cn-infra v1.2 Bug Fixes * Resync of ifplugin in both, VPP and Linux, was improved. Interfaces with the same configuration data are not recreated during resync. * STN does not fail if IP address with a mask is provided. * Fixed ingress/egress interface resolution in ACL. * Linux routes now check network reachability for gateway address before configuration. It should prevent "network unreachable" errors during config. * Corrected bridge domain crash in case non-bvi interface was added to another non-bvi interface. * Fixed several bugs related to VETH and AF-PACKET configuration and resync. Features - [ipsecplugin][vpp-ipsec-plugin]: * New plugin for IPSec added. The IPSec is supported for VPP only with Linux set manually for now. IKEv2 is not yet supported. More information in the [readme][readme]. - [nsplugin][linux-ns-plugin] * New namespace plugin added. The configurator handles common namespace and microservice processing and communication with other Linux plugins. - [ifplugin][<API key>] * Added support for Network address translation. NAT plugin supports a configuration of NAT44 interfaces, address pools and DNAT. More information in the [readme][readme]. * DHCP can now be configured for the interface - [l2plugin][vpp-l2-plugin] * Split-horizon group can be configured for bridge domain interface. - [l3plugin][vpp-l3-plugin] * Added support for proxy ARP. For more information and configuration example, please see [readme][readme]. - [linux ifplugin][<API key>] * Support for automatic interface configuration (currently only TAP). Improvements - [aclplugin][agentctl] * Removed configuration order of interfaces. The access list can be now configured even if interfaces do not exist yet, and add them later. - vpp-agent-ctl * The vpp-agent-ctl was refactored and command info was updated. Docker Images * VPP can be built and run in the release or debug mode. Read more information in the [readme][readme]. * Production image is now smaller by roughly 40% (229MB). <a name="v1.2.0"></a> Compatibility - VPP v18.04-rc0~90-gd95c39e - cn-infra v1.1 Bug Fixes - Fixed interface assignment in ACLs - Fixed bridge domain BVI modification resolution - vpp-agent-grpc (removed in 1.4 release, since then it is a part of the vpp-agent) now compiles properly together with other commands. Known Issues - VPP can occasionally cause a deadlock during checksum calculation (https://jira.fd.io/browse/VPP-1134) - VPP-Agent might not properly handle initialization across plugins (this is not occurring currently, but needs to be tested more) Improvements - [aclplugin][vpp-acl-plugin] * Improved resync of ACL entries. Every new ACL entry is correctly configured in the VPP and all obsolete entries are read and removed. - [ifplugin][<API key>] * Improved resync of interfaces, BFD sessions, authentication keys, echo functions and STN. Better resolution of persistence config for interfaces. - [l2plugin][vpp-l2-plugin] * Improved resync of bridge domains, FIB entries, and xConnect pairs. Resync now better correlates configuration present on the VPP with the NB setup. - [linux-ifplugin][<API key>] * ARP does not need the interface to be present on the VPP. Configuration is cached and put to the VPP if requirements are fulfilled. - Dependencies * Migrated from glide to dep Docker Images * VPP compilation now skips building of Java/C++ APIs, this saves build time and final image size. * Development image now runs VPP in debug mode with various debug options added in [VPP config file][vpp-conf-file]. <a name="v1.1.0"></a> Compatibility - VPP version v18.04-rc0~33-gb59bd65 - cn-infra v1.0.8 Bug Fixes - fixed skip-resync parameter if vpp-plugin.conf is not provided. - corrected af_packet type interface behavior if veth interface is created/removed. - several fixes related to the af_packet and veth interface type configuration. - microservice and veth-interface related events are synchronized. Known Issues - VPP can occasionally cause a deadlock during checksum calculation (https://jira.fd.io/browse/VPP-1134) - VPP-Agent might not properly handle initialization across plugins (this is not occurring currently, but needs to be tested more) Features - [ifplugin][<API key>] - added support for un-numbered interfaces. The nterface can be marked as un-numbered with information about another interface containing required IP address. A un-numbered interface does not need to have IP address set. - added support for virtio-based TAPv2 interfaces. - interface status is no longer stored in the ETCD by default and it can be turned on using the appropriate setting in vpp-plugin.conf. See [readme][readme] for more details. - [l2plugin][vpp-l2-plugin] - bridge domain status is no longer stored in the ETCD by default and it can be turned on using the appropriate setting in vpp-plugin.conf. See [readme][readme] for more details. Improvements - [ifplugin][<API key>] - default MTU value was removed in order to be able to just pass empty MTU field. MTU now can be set only in interface configuration (preferred) or defined in vpp-plugin.conf. If none of them is set, MTU value will be empty. - interface state data are stored in statuscheck readiness probe - [l3plugin][vpp-l3-plugin] - removed strict configuration order for VPP ARP entries and routes. Both ARP entry or route can be configured without interface already present. - l4plugin (removed in v2.0) - removed strict configuration order for application namespaces. Application namespace can be configured without interface already present. - localclient - added API for ARP entries, L4 features, Application namespaces, and STN rules. - logging - consolidated and improved logging in vpp and Linux plugins. <a name="v1.0.8"></a> Compatibility - VPP v18.01-rc0-309-g70bfcaf - cn-infra v1.0.7 Features - [ifplugin][<API key>] - ability to configure STN rules. See respective [readme][readme] in interface plugin for more details. - rx-mode settings can be set on interface. Ethernet-type interface can be set to POLLING mode, other types of interfaces supports also INTERRUPT and ADAPTIVE. Fields to set QueueID/QueueIDValid are also available - added possibility to add interface to any VRF table. - added defaultplugins API. - API contains new Method `DisableResync(keyPrefix ...string)`. One or more ETCD key prefixes can be used as a parameter to disable resync for that specific key(s). - l4plugin (removed in v2.0) - added new l4 plugin to the VPP plugins. It can be used to enable/disable L4 features and configure application namespaces. See respective [readme][readme] in L4 plugin for more details. - support for VPP plugins/l3plugin ARP configuration. The configurator can perform the basic CRUD operation with ARP config. - resync - resync error propagation improved. If any resynced configuration fails, rest of the resync completes and will not be interrupted. All errors which appear during resync are logged after. - [linux l3plugin][linux-l3-plugin] - route configuration does not return an error if the required interface is missing. Instead, the route data are internally stored and configured when the interface appears. - GoVPP - delay flag removed from GoVPP plugin Improvements - removed dead links from README files Documentation - improved in multiple vpp-agent packages <a name="v1.0.7"></a> Compatibility - VPP version v18.01-rc0~154-gfc1c612 - cn-infra v1.0.6 Features - [Default VPP plugin][<API key>] - added resync strategies. Resync of VPP plugins can be set using defaultpluigns config file; Resync can be set to full (always resync everything) or dependent on VPP configuration (if there is none, skip resync). Resync can be also forced to skip using the parameter. - [Linuxplugins L3Plugin][linux-l3-plugin] - added support for basic CRUD operations with the static Address resolution protocol entries and static Routes. <a name="v1.0.6"></a> Compatibility - cn-infra v1.0.5 Features - [LinuxPlugin][<API key>] - The configuration of vEth interfaces modified. Veth configuration defines two names: symbolic used internally and the one used in host OS. `HostIfName` field is optional. If it is not defined, the name in the host OS will be the same as the symbolic one - defined by `Name` field. <a name="v1.0.5"></a> Compatibility - VPP version v17.10-rc0~334-gce41a5c - cn-infra v1.0.4 Features - [GoVppMux][govppmux-plugin] - configuration file for govpp added - Kafka Partitions - Changes in offset handling, only automatically partitioned messages (hash, random) have their offset marked. Manually partitioned messages are not marked. - Implemented post-init consumer (for manual partitioner only) which allows starting consuming after kafka-plugin Init() - Minimalistic examples & documentation for Kafka API will be improved in a later release. <a name="v1.0.4"></a> Features - Kafka Partitions - Implemented new methods that allow to specify partitions & offset parameters: * publish: Mux.<API key>() & Mux.<API key>() * watch: ProtoWatcher.WatchPartition() - Minimalistic examples & documentation for Kafka API will be improved in a later release. - Flavors - reduced to only local.FlavorVppLocal & vpp.Flavor - GoVPP - updated version waits until the VPP is ready to accept a new connection <a name="v1.0.3"></a> Compatibility - VPP version v17.10-rc0~265-g809bc74 (upgraded because of VPP MEMIF fixes) Features Enabled support for wathing data store `OfDifferentAgent()` - see: * examples/idx_iface_cache (removed in v2.0) * examples/examples/idx_bd_cache (removed in v2.0) * examples/idx_veth_cache (removed in v2.0) Preview of new Kafka client API methods that allows to fill also partition and offset argument. New methods implementation ignores these new parameters for now (fallback to existing implementation based on `github.com/bsm/sarama-cluster` and `github.com/Shopify/sarama`). <a name="v1.0.2"></a> Compatibility - VPP version v17.10-rc0~203 Known Issues A rarely occurring problem during startup with binary API connectivity. VPP rejects binary API connectivity when VPP Agent tries to connect too early (plan fix this behavior in next release). Features Algorithms for applying northbound configuration (stored in ETCD key-value data store) to VPP in the proper order of VPP binary API calls implemented in [Default VPP plugin][<API key>]: - network interfaces, especially: - MEMIFs (optimized data plane network interface tailored for a container to container network connectivity) - VETHs (standard Linux Virtual Ethernet network interface) - AF_Packets (for accessing VETHs and similar type of interface) - VXLANs, Physical Network Interfaces, loopbacks ... - L2 BD & X-Connects - L3 IP Routes & VRFs - ACL (Access Control List) Support for Linux VETH northbound configuration implemented in [Linux Plugin][<API key>] applied in proper order with VPP AF_Packet configuration. Data Synchronization during startup for network interfaces & L2 BD (support for the situation when ETCD contain configuration before VPP Agent starts). Data replication and events: - Updating operational data in ETCD (VPP indexes such as sw_if_index) and statistics (port counters). - Updating statistics in Redis (optional once redis.conf available - see flags). - Publishing links up/down events to Kafka message bus. - [Examples][examples] - Tools: - [agentctl CLI tool][agentctl] that show state & configuration of VPP agents - [docker][docker]: container-based development environment for the VPP agent - other features inherited from cn-infra: - health: status check & k8s HTTP/REST probes - logging: changing log level at runtime - Ability to extend the behavior of the VPP Agent by creating new plugins on top of VPP Agent flavor (removed with CN-Infra v1.5). New plugins can access API for configured: - VPP Network interfaces, - Bridge domains and VETHs based on [idxvpp][idx-vpp] threadsafe map tailored for VPP data with advanced features (multiple watchers, secondary indexes). - VPP Agent is embeddable in different software projects and with different systems by using Local Flavor (removed with CN-Infra v1.5) to reuse VPP Agent algorithms. For doing this there is VPP Agent client version 1 (removed in v2.0): - local client - for embedded VPP Agent (communication inside one operating system process, VPP Agent effectively used as a library) - remote client - for remote configuration of VPP Agent (while integrating for example with control plane) [agentctl]: cmd/agentctl [ansible]: ansible [configurator-plugin]: plugins/configurator [consul]: https: [contiv-vpp1810]: https://github.com/vpp-dev/vpp/tree/stable-1801-contiv [docker]: docker [examples]: examples [<API key>]: examples/localclient_linux [examples-nat]: examples/localclient_vpp/nat [examples-tap]: examples/localclient_linux/tap [examples-veth]: examples/localclient_linux/veth [examples-vpp-local]: examples/localclient_vpp [govppmux-plugin]: plugins/govppmux [govppmux-conf]: plugins/govppmux/govpp.conf [idx-vpp]: pkg/idxvpp [kv-scheduler]: plugins/kvscheduler [ligato.io]: https://ligato.io/ [ligato-docs]: https://docs.ligato.io/en/latest/ [<API key>]: plugins/linux/ifplugin [<API key>]: plugins/linux/iptablesplugin [linux-l3-plugin]: plugins/linux/l3plugin [linux-ns-plugin]: plugins/linux/nsplugin [linux-plugins]: plugins/linux [nat-proto]: api/models/vpp/nat/nat.proto [netalloc-plugin]: plugins/netalloc [<API key>]: api/models/netalloc/netalloc.proto [ns-plugin]: plugins/linux/nsplugin [ns-proto]: api/models/linux/namespace/namespace.proto [models]: api/models [orchestrator-plugin]: plugins/orchestrator [punt-model]: api/models/vpp/punt/punt.proto [readme]: README.md [rest-plugin]: plugins/restapi [span-model]: api/models/vpp/interfaces/span.proto [sr-plugin]: plugins/vpp/srplugin [vpp-abf-plugin]: plugins/vpp/abfplugin [vpp-acl-plugin]: plugins/vpp/aclplugin [vpp-agent]: cmd/vpp-agent [vpp-conf-file]: docker/dev/vpp.conf [<API key>]: plugins/vpp/ifplugin [vpp-issue-1280]: https://jira.fd.io/browse/VPP-1280 [vpp-ipsec-plugin]: plugins/vpp/ipsecplugin [vpp-l2-plugin]: plugins/vpp/l2plugin [vpp-l3-plugin]: plugins/vpp/l3plugin [vpp-nat-plugin]: plugins/vpp/natplugin [vpp-plugins]: plugins/vpp [vpp-punt-plugin]: plugins/vpp/puntplugin [vpp-stn-plugin]: plugins/vpp/stnplugin [vpp-telemetry]: plugins/telemetry [wiki]: https://github.com/ligato/vpp-agent/wiki
<?php require 'common.php'; require Sc::$rootDir.'/driver/file.php'; class Test{ static public $d = NULL; static public function testAdd(){ if(empty(self::$d)){ self::$d = new Sc_Driver_File(); } self::$d->add(array( 'hash'=>'hash1', 'node'=>'192.168.1.1', 'fhash'=>'hashfile1' )); self::$d->add(array( 'hash'=>'hash1', 'node'=>'192.168.1.2', 'fhash'=>'hashfile2' )); } static public function testGet(){ if(empty(self::$d)){ self::$d = new Sc_Driver_File(); } var_dump(self::$d->get('hash1')); } static public function testDel(){ if(empty(self::$d)){ self::$d = new Sc_Driver_File(); } var_dump(self::$d->delete('<API key>')); } } //$a = 1/0; Test::testDel();
package debop4s.data.orm.hibernate.repository import com.mysema.query.jpa.hibernate._ import com.mysema.query.types.EntityPath import debop4s.data.orm.ReadOnlyConnection import debop4s.data.orm.model.HConnectPageImpl import org.hibernate.{LockOptions, Session, SessionFactory} import org.slf4j.LoggerFactory import org.springframework.data.domain.PageRequest import scala.annotation.varargs import scala.util.control.NonFatal /** * <API key> * @author debop created at 2014. 5. 20. */ class <API key>(val sessionFactory: SessionFactory) { private lazy val log = LoggerFactory.getLogger(getClass) private def session: Session = sessionFactory.getCurrentSession private def sessionStateless = sessionFactory.<API key>() def getQuery: HibernateQuery = new HibernateQuery(session) def from(path: EntityPath[_]): HibernateQuery = getQuery.from(path) @varargs def from(paths: EntityPath[_]*): HibernateQuery = getQuery.from(paths: _*) def deleteFrom(path: EntityPath[_]): <API key> = new <API key>(session, path) def updateFrom(path: EntityPath[_]): <API key> = new <API key>(session, path) def deleteStateless(path: EntityPath[_])(action: <API key> => Unit): Long = { try { val stateless = sessionFactory.<API key>() val deleteClause = new <API key>(stateless, path) action(deleteClause) deleteClause.execute() } catch { case NonFatal(e) => log.error(s" .", e) -1L } } def updateStateless(path: EntityPath[_])(action: <API key> => Unit): Long = { try { val stateless = sessionFactory.<API key>() val updateStateless = new <API key>(stateless, path) action(updateStateless) updateStateless.execute() } catch { case NonFatal(e) => log.error(s" .", e) -1L } } @ReadOnlyConnection def load[T](clazz: Class[T], id: java.io.Serializable): T = session.load(clazz, id).asInstanceOf[T] @ReadOnlyConnection def load[T](clazz: Class[T], id: java.io.Serializable, lockOptions: LockOptions) = session.load(clazz, id, lockOptions) @ReadOnlyConnection def get[T](clazz: Class[T], id: java.io.Serializable) = session.get(clazz, id) @ReadOnlyConnection def get[T](clazz: Class[T], id: java.io.Serializable, lockOptions: LockOptions) = session.get(clazz, id, lockOptions) @ReadOnlyConnection def findAll[T](path: EntityPath[T]) = getQuery.from(path).list(path) @ReadOnlyConnection def findAll[T](path: EntityPath[T], query: HibernateQuery, offset: Int, limit: Int) = query.offset(offset).limit(limit).list(path) @ReadOnlyConnection def getPage[T](path: EntityPath[T], query: HibernateQuery, pageNo: Int, pageSize: Int) = { val total = query.count() val offset = (pageNo - 1) * pageSize val limit = pageSize val items = findAll(path, query, offset, limit) new HConnectPageImpl(items, new PageRequest(pageNo, pageSize), total) } }
/** * Autogenerated by Thrift Compiler (0.10.0) * * DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING * @generated */ package lizard.api.TLZ; @SuppressWarnings("all") @javax.annotation.Generated(value = "Autogenerated by Thrift Compiler (0.10.0)", date = "2018-06-17") public class TLZ_Patch implements org.apache.thrift.TBase<TLZ_Patch, TLZ_Patch._Fields>, java.io.Serializable, Cloneable, Comparable<TLZ_Patch> { private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("TLZ_Patch"); private static final org.apache.thrift.protocol.TField ENTITIES_FIELD_DESC = new org.apache.thrift.protocol.TField("entities", org.apache.thrift.protocol.TType.LIST, (short)1); private static final org.apache.thrift.scheme.SchemeFactory <API key> = new <API key>(); private static final org.apache.thrift.scheme.SchemeFactory <API key> = new <API key>(); public java.util.List<TLZ_PatchEntry> entities; // required /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */ public enum _Fields implements org.apache.thrift.TFieldIdEnum { ENTITIES((short)1, "entities"); private static final java.util.Map<java.lang.String, _Fields> byName = new java.util.HashMap<java.lang.String, _Fields>(); static { for (_Fields field : java.util.EnumSet.allOf(_Fields.class)) { byName.put(field.getFieldName(), field); } } /** * Find the _Fields constant that matches fieldId, or null if its not found. */ public static _Fields findByThriftId(int fieldId) { switch(fieldId) { case 1: // ENTITIES return ENTITIES; default: return null; } } /** * Find the _Fields constant that matches fieldId, throwing an exception * if it is not found. */ public static _Fields <API key>(int fieldId) { _Fields fields = findByThriftId(fieldId); if (fields == null) throw new java.lang.<API key>("Field " + fieldId + " doesn't exist!"); return fields; } /** * Find the _Fields constant that matches name, or null if its not found. */ public static _Fields findByName(java.lang.String name) { return byName.get(name); } private final short _thriftId; private final java.lang.String _fieldName; _Fields(short thriftId, java.lang.String fieldName) { _thriftId = thriftId; _fieldName = fieldName; } public short getThriftFieldId() { return _thriftId; } public java.lang.String getFieldName() { return _fieldName; } } // isset id assignments public static final java.util.Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; static { java.util.Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new java.util.EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class); tmpMap.put(_Fields.ENTITIES, new org.apache.thrift.meta_data.FieldMetaData("entities", org.apache.thrift.<API key>.REQUIRED, new org.apache.thrift.meta_data.ListMetaData(org.apache.thrift.protocol.TType.LIST, new org.apache.thrift.meta_data.StructMetaData(org.apache.thrift.protocol.TType.STRUCT, TLZ_PatchEntry.class)))); metaDataMap = java.util.Collections.unmodifiableMap(tmpMap); org.apache.thrift.meta_data.FieldMetaData.<API key>(TLZ_Patch.class, metaDataMap); } public TLZ_Patch() { } public TLZ_Patch( java.util.List<TLZ_PatchEntry> entities) { this(); this.entities = entities; } /** * Performs a deep copy on <i>other</i>. */ public TLZ_Patch(TLZ_Patch other) { if (other.isSetEntities()) { java.util.List<TLZ_PatchEntry> __this__entities = new java.util.ArrayList<TLZ_PatchEntry>(other.entities.size()); for (TLZ_PatchEntry other_element : other.entities) { __this__entities.add(new TLZ_PatchEntry(other_element)); } this.entities = __this__entities; } } public TLZ_Patch deepCopy() { return new TLZ_Patch(this); } @Override public void clear() { this.entities = null; } public int getEntitiesSize() { return (this.entities == null) ? 0 : this.entities.size(); } public java.util.Iterator<TLZ_PatchEntry> getEntitiesIterator() { return (this.entities == null) ? null : this.entities.iterator(); } public void addToEntities(TLZ_PatchEntry elem) { if (this.entities == null) { this.entities = new java.util.ArrayList<TLZ_PatchEntry>(); } this.entities.add(elem); } public java.util.List<TLZ_PatchEntry> getEntities() { return this.entities; } public TLZ_Patch setEntities(java.util.List<TLZ_PatchEntry> entities) { this.entities = entities; return this; } public void unsetEntities() { this.entities = null; } /** Returns true if field entities is set (has been assigned a value) and false otherwise */ public boolean isSetEntities() { return this.entities != null; } public void setEntitiesIsSet(boolean value) { if (!value) { this.entities = null; } } public void setFieldValue(_Fields field, java.lang.Object value) { switch (field) { case ENTITIES: if (value == null) { unsetEntities(); } else { setEntities((java.util.List<TLZ_PatchEntry>)value); } break; } } public java.lang.Object getFieldValue(_Fields field) { switch (field) { case ENTITIES: return getEntities(); } throw new java.lang.<API key>(); } /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */ public boolean isSet(_Fields field) { if (field == null) { throw new java.lang.<API key>(); } switch (field) { case ENTITIES: return isSetEntities(); } throw new java.lang.<API key>(); } @Override public boolean equals(java.lang.Object that) { if (that == null) return false; if (that instanceof TLZ_Patch) return this.equals((TLZ_Patch)that); return false; } public boolean equals(TLZ_Patch that) { if (that == null) return false; if (this == that) return true; boolean <API key> = true && this.isSetEntities(); boolean <API key> = true && that.isSetEntities(); if (<API key> || <API key>) { if (!(<API key> && <API key>)) return false; if (!this.entities.equals(that.entities)) return false; } return true; } @Override public int hashCode() { int hashCode = 1; hashCode = hashCode * 8191 + ((isSetEntities()) ? 131071 : 524287); if (isSetEntities()) hashCode = hashCode * 8191 + entities.hashCode(); return hashCode; } @Override public int compareTo(TLZ_Patch other) { if (!getClass().equals(other.getClass())) { return getClass().getName().compareTo(other.getClass().getName()); } int lastComparison = 0; lastComparison = java.lang.Boolean.valueOf(isSetEntities()).compareTo(other.isSetEntities()); if (lastComparison != 0) { return lastComparison; } if (isSetEntities()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.entities, other.entities); if (lastComparison != 0) { return lastComparison; } } return 0; } public _Fields fieldForId(int fieldId) { return _Fields.findByThriftId(fieldId); } public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException { scheme(iprot).read(iprot, this); } public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException { scheme(oprot).write(oprot, this); } @Override public java.lang.String toString() { java.lang.StringBuilder sb = new java.lang.StringBuilder("TLZ_Patch("); boolean first = true; sb.append("entities:"); if (this.entities == null) { sb.append("null"); } else { sb.append(this.entities); } first = false; sb.append(")"); return sb.toString(); } public void validate() throws org.apache.thrift.TException { // check for required fields if (entities == null) { throw new org.apache.thrift.protocol.TProtocolException("Required field 'entities' was not present! Struct: " + toString()); } // check for sub-struct validity } private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { try { write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, java.lang.<API key> { try { read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private static class <API key> implements org.apache.thrift.scheme.SchemeFactory { public <API key> getScheme() { return new <API key>(); } } private static class <API key> extends org.apache.thrift.scheme.StandardScheme<TLZ_Patch> { public void read(org.apache.thrift.protocol.TProtocol iprot, TLZ_Patch struct) throws org.apache.thrift.TException { org.apache.thrift.protocol.TField schemeField; iprot.readStructBegin(); while (true) { schemeField = iprot.readFieldBegin(); if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { break; } switch (schemeField.id) { case 1: // ENTITIES if (schemeField.type == org.apache.thrift.protocol.TType.LIST) { { org.apache.thrift.protocol.TList _list8 = iprot.readListBegin(); struct.entities = new java.util.ArrayList<TLZ_PatchEntry>(_list8.size); TLZ_PatchEntry _elem9; for (int _i10 = 0; _i10 < _list8.size; ++_i10) { _elem9 = new TLZ_PatchEntry(); _elem9.read(iprot); struct.entities.add(_elem9); } iprot.readListEnd(); } struct.setEntitiesIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; default: org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } iprot.readFieldEnd(); } iprot.readStructEnd(); // check for required fields of primitive type, which can't be checked in the validate method struct.validate(); } public void write(org.apache.thrift.protocol.TProtocol oprot, TLZ_Patch struct) throws org.apache.thrift.TException { struct.validate(); oprot.writeStructBegin(STRUCT_DESC); if (struct.entities != null) { oprot.writeFieldBegin(ENTITIES_FIELD_DESC); { oprot.writeListBegin(new org.apache.thrift.protocol.TList(org.apache.thrift.protocol.TType.STRUCT, struct.entities.size())); for (TLZ_PatchEntry _iter11 : struct.entities) { _iter11.write(oprot); } oprot.writeListEnd(); } oprot.writeFieldEnd(); } oprot.writeFieldStop(); oprot.writeStructEnd(); } } private static class <API key> implements org.apache.thrift.scheme.SchemeFactory { public <API key> getScheme() { return new <API key>(); } } private static class <API key> extends org.apache.thrift.scheme.TupleScheme<TLZ_Patch> { @Override public void write(org.apache.thrift.protocol.TProtocol prot, TLZ_Patch struct) throws org.apache.thrift.TException { org.apache.thrift.protocol.TTupleProtocol oprot = (org.apache.thrift.protocol.TTupleProtocol) prot; { oprot.writeI32(struct.entities.size()); for (TLZ_PatchEntry _iter12 : struct.entities) { _iter12.write(oprot); } } } @Override public void read(org.apache.thrift.protocol.TProtocol prot, TLZ_Patch struct) throws org.apache.thrift.TException { org.apache.thrift.protocol.TTupleProtocol iprot = (org.apache.thrift.protocol.TTupleProtocol) prot; { org.apache.thrift.protocol.TList _list13 = new org.apache.thrift.protocol.TList(org.apache.thrift.protocol.TType.STRUCT, iprot.readI32()); struct.entities = new java.util.ArrayList<TLZ_PatchEntry>(_list13.size); TLZ_PatchEntry _elem14; for (int _i15 = 0; _i15 < _list13.size; ++_i15) { _elem14 = new TLZ_PatchEntry(); _elem14.read(iprot); struct.entities.add(_elem14); } } struct.setEntitiesIsSet(true); } } private static <S extends org.apache.thrift.scheme.IScheme> S scheme(org.apache.thrift.protocol.TProtocol proto) { return (org.apache.thrift.scheme.StandardScheme.class.equals(proto.getScheme()) ? <API key> : <API key>).getScheme(); } }
package ru.job4j.pro.collections.list; import org.junit.Test; import static org.hamcrest.core.Is.is; import static org.junit.Assert.assertThat; /** * NodeListTest class. * * @author Vladimir Ivanov * @version 0.1 * @since 30.08.2017 */ public class NodeListTest { /** * Test list is not cycled. */ @Test public void <API key>() { Node<Integer> first = new Node<>(1); Node<Integer> two = new Node<>(2); Node<Integer> third = new Node<>(3); Node<Integer> four = new Node<>(4); Node<Integer> five = new Node<>(5); first.next = two; two.next = third; third.next = four; four.next = five; NodeList<Integer> list = new NodeList<>(first); boolean result = list.hasCycle(); assertThat(result, is(false)); } /** * Test list is cycled. */ @Test public void <API key>() { Node<Integer> first = new Node<>(1); Node<Integer> two = new Node<>(2); Node<Integer> third = new Node<>(3); Node<Integer> four = new Node<>(4); first.next = two; two.next = third; third.next = four; four.next = first; NodeList<Integer> list = new NodeList<>(first); boolean result = list.hasCycle(); assertThat(result, is(true)); } /** * Test list is cycled. */ @Test public void <API key>() { Node<Integer> node = new Node<>(0); Node<Integer> cycleFrom = null; Node<Integer> cycleTo = null; NodeList<Integer> list = new NodeList<>(node); for (int value = 1; value < 10000000; value++) { node.next = new Node<>(value); node = node.next; if (value == 900000) { cycleTo = node; } else if (value == 9990000) { cycleFrom = node; } } cycleFrom.next = cycleTo; boolean result = list.hasCycle(); assertThat(result, is(true)); } }
'use strict'; /** * @ngdoc function * @name lubriApp.controller:MembersCtrl * @description * # MembersCtrl * Controller of the lubriApp */ angular.module('lubriApp') .config(function($stateProvider) { $stateProvider.state('app.members', { abstract: true, url: '/members', templateUrl: 'views/members/main.html', controller: 'MembersCtrl' }) .state('app.members.list', { url: '', templateUrl: 'views/members/list.html', controller: 'MembersCtrl' }) .state('app.members.add', { url: '/add', templateUrl: 'views/members/form.html', controller: 'MembersCtrl' }) .state('app.members.import', { url: '/import', templateUrl: 'views/members/import.html', controller: 'MembersCtrl' }) .state('app.members.edit', { url: '/:id/edit', templateUrl: 'views/members/form.html', controller: 'MembersCtrl' }) .state('app.members.view', { url: '/:id', templateUrl: 'views/members/view.html', controller: 'MembersCtrl' }); }) .controller('MembersCtrl', function($scope, $state, $stateParams, $q, $interval, toasty, Member, SweetAlert, i18nService) { var memberId = $stateParams.id; i18nService.setCurrentLang('zh-cn'); $scope.importData = []; $scope.gridImportOptions = { enableGridMenu: true, <API key>: function( grid, newObjects ) { $scope.importData = $scope.importData.concat( newObjects ); }, onRegisterApi: function(gridApi){ $scope.gridImportApi = gridApi; gridApi.rowEdit.on.saveRow($scope, $scope.saveRow); }, data: 'importData' }; $scope.saveRow = function( rowEntity ) { // create a fake promise - normally you'd use the promise returned by $http or $resource var promise = $q.defer(); $scope.gridImportApi.rowEdit.setSavePromise( $scope.gridImportApi.grid, rowEntity, promise.promise ); $interval( function() { promise.resolve(); }, 1000, 1); }; $scope.saveImport = function () { if ($scope.importData.length > 0) { var members = $scope.importData; for (var i=0;i<members.length;i++) { var member = members[i]; member.created = new Date(); delete member.$$hashKey; Member.upsert(member, function() { }, function(err) { console.log(err); }); }; toasty.pop.success({title: '', msg: members.length + '', sound: false}); loadItems(); $state.go('^.list'); }; }; if (memberId) { $scope.member = Member.findById({ id: memberId }, function() {}, function(err) { console.log(err); }); } else { $scope.member = {}; } $scope.gridOptions = { data: 'members', enableFiltering: true, paginationPageSizes: [5, 10, 15], paginationPageSize: 10, headerRowHeight: 39, rowHeight: 39, columnFooterHeight: 39, gridFooterHeight: 39, <API key>: 39, columnDefs: [ { name: 'Edit', width: 80, displayName: '', enableSorting: false, enableFiltering: false, cellTemplate: '<a href="" class="ui-state-hover" ui-sref="^.edit({id: row.entity.id})"> <i class="fa fa-pencil fa-lg blue"></i></a> <a href="" class="ui-state-hover" style="margin-left:5px;" ng-click="getExternalScopes().delete({id: row.entity.id})"><i class="fa fa-trash-o fa-lg red"></i></a>' }, { name: 'name', displayName: '', cellTemplate: '<div class="<API key>"><a href="" ui-sref="^.view({id: row.entity.id})"> {{ COL_FIELD }} </a></div>'} ,{ name: 'firstName', displayName: '' } ,{ name: 'lastName', displayName: '' } ,{ name: 'displayName', displayName: '' } ,{ name: 'position', displayName: '' } , { name: 'priority', displayName: '' } ], enableGridMenu: true, enableSelectAll: true, exporterCsvFilename: 'members.csv', <API key>: ['Edit'], <API key>: {fontSize: 9}, <API key>: {margin: [30, 30, 30, 30]}, <API key>: {fontSize: 10, bold: true, italics: true, color: 'red'}, exporterPdfHeader: { text: "Meeting Member Information", style: 'headerStyle' }, exporterPdfFooter: function ( currentPage, pageCount ) { return { text: currentPage.toString() + ' of ' + pageCount.toString(), style: 'footerStyle' }; }, <API key>: function ( docDefinition ) { docDefinition.styles.headerStyle = { fontSize: 22, bold: true }; docDefinition.styles.footerStyle = { fontSize: 10, bold: true }; return docDefinition; }, <API key>: 'portrait', exporterPdfPageSize: 'LETTER', <API key>: 500, <API key>: angular.element(document.querySelectorAll(".<API key>")) }; $scope.gridOptions.onRegisterApi = function (gridApi) { $scope.gridApi = gridApi; }; function loadItems() { $scope.members = Member.find(); } loadItems(); $scope.viewActions = { delete : $scope.delete }; $scope.delete = function(id) { SweetAlert.swal({ title: '?', type: 'warning', showCancelButton: true, confirmButtonColor: '#DD6B55' }, function(isConfirm){ if (isConfirm) { Member.deleteById(id, function() { toasty.pop.success({title: '', msg: '!', sound: false}); loadItems(); $state.go($state.current, {}, {reload: true}); //$state.go('app.members.list'); }, function(err) { toasty.pop.error({title: '', msg: '' + err, sound: false}); }); } else { return false; } }); }; $scope.formFields = [{ key: 'name', type: 'text', label: '', required: true }, { key: 'firstName', type: 'text', label: '', required: true }, { key: 'lastName', type: 'text', label: '', required: true }, { key: 'displayName', type: 'text', label: '', required: true }, { key: 'position', type: 'text', label: '', required: true }, { key: 'priority', type: 'number', label: '', required: true }]; $scope.formOptions = { uniqueFormId: true, hideSubmit: false, submitCopy: '' }; $scope.onSubmit = function() { if (($scope.member.created === null) || ($scope.member.created === undefined)){ $scope.member.created = new Date(); }; Member.upsert($scope.member, function() { toasty.pop.success({title: '', msg: '', sound: false}); loadItems(); $state.go('^.list'); }, function(err) { console.log(err); }); }; });
package com.intel.media.mts.dao.impl; import org.junit.Assert; import org.junit.Test; import com.intel.media.mts.dao.DaoTestSupport; import com.intel.media.mts.model.Software; public class SoftwareDaoImplTest extends DaoTestSupport { @Test public void test(){ Software s = new Software(); String name = "Ubuntu"; String desc = "OS type 12.04"; s.setName(name); s.setDescription(desc); softwareDao.doSave(s); System.out.println(s); Software s2 = softwareDao.findById(s.getId()); Assert.assertEquals(name, s2.getName()); Assert.assertEquals(desc, s2.getDescription()); } }
package com.thinkgem.jeesite.modules.purifier.dao; import com.thinkgem.jeesite.common.persistence.CrudDao; import com.thinkgem.jeesite.common.persistence.annotation.MyBatisDao; import com.thinkgem.jeesite.modules.purifier.entity.Ware; /** * dao * * @author addison * @since 20170302 */ @MyBatisDao public interface WareDao extends CrudDao<Ware> { int deleteByWare(Ware ware); }
<form class="form-horizontal" role="form" name="form" ng-show="model" ng-submit="onFormSubmit()"> <div class="form-custom-alerts"> <alert ng-repeat="alert in alerts" type="{{alert.type}}" close="closeAlert($index)">{{alert.msg}}</alert> </div> <div ng-form ng-repeat="field in fields" name="innerForm" ng-if="!field.hidden"> <div class="form-group" ng-class="{'has-feedback has-success': isSuccess(innerForm), 'has-feedback has-error': isError(innerForm)}"> <label class="col-sm-2 control-label">{{field.describe}}</label> <div class="col-sm-4" ng-switch="field.type"> <div class="checkbox" ng-switch-when='checkbox'> <label> <input type="checkbox" name="input" ng-model="model[field.name]"> {{field.checkBoxMessage != null ? field.checkBoxMessage : field.describe}} </label> </div> <div class="radio" ng-switch-when='radio'> <div class="radio" ng-repeat='option in field.options'> <label> <input type="radio" name="input" value="{{option.value}}" ng-model="model[field.name]" ng-required="true"> {{option.text}} </label> </div> </div> <div ng-switch-when='select'> <select class="form-control" name="input" ng-model="model[field.name]" ng-options="option.value as option.name for option in field.options" ng-required="field.required == null ? true : field.required"></select> </div> <div ng-switch-default> <input type="{{field.type || 'text'}}" class="form-control" placeholder="{{field.placeholder || ''}}" ng-disabled="!!field.disabled" ng-model="model[field.name]" name="input" ui-validate="validators" ng-required="field.required == null ? true : field.required" ng-pattern="patternForField(field)"> <span class="glyphicon glyphicon-ok <API key>" ng-show="isSuccess(innerForm)"></span> <span class="glyphicon glyphicon-remove <API key>" ng-show="isError(innerForm)"></span> </div> </div> <div class="help-block col-sm-6" ng-show='!hideError || attempted || innerForm.input.$dirty'> <p ng-show="innerForm.input.$error.required">{{field.describe}}</p> <p ng-show="innerForm.input.$error.pattern">{{field.describe}}</p> <p ng-show="innerForm.input.$error.minLength">{{field.describe}}{{field.minLength}}</p> <p ng-show="innerForm.input.$error.maxLength">{{field.describe}}{{field.maxLength}}</p> <p ng-show="innerForm.input.$error.custom"> <span ng-show="!!field.validateMessage">{{field.validateMessage}}</span> <span ng-show="!field.validateMessage">{{field.describe}}</span> </p> </div> </div> <div ng-if="field.type == 'password' && field.needConfirm == true" class="form-group" ng-class="{'has-feedback has-success': isSuccess(innerForm, 'confirm'), 'has-feedback has-error': isError(innerForm, 'confirm')}"> <label class="col-sm-2 control-label"></label> <div class="col-sm-4"> <input type="password" class="form-control" ng-model="extraModel[field.name]" name="confirm" ng-required="field.required == null || field.required || !!model[fieldname]" ui-validate="{passwordMatch: '$value==model[field.name]'}" ui-validate-watch=" 'model[field.name]' "> <span class="glyphicon glyphicon-ok <API key>" ng-show="isSuccess(innerForm, 'confirm')"></span> <span class="glyphicon glyphicon-remove <API key>" ng-show="isError(innerForm, 'confirm')"></span> </div> <div class="help-block col-sm-6" ng-show='!hideError || attempted || innerForm.confirm.$dirty'> <span ng-show="innerForm.confirm.$error.required"></span> <span ng-show="!innerForm.confirm.$error.required && innerForm.confirm.$error.passwordMatch"></span> </div> </div> </div> <div class="form-group" ng-if="submitButton != 'none'"> <div class="col-sm-offset-2 col-sm-8"> <button type="submit" class="btn btn-primary">{{submitButton || ''}}</button> </div> </div> <div ng-transclude></div> </form>
function buildName(firstName = "Will", lastName: string) { return firstName + " " + lastName; } let result1 = buildName("Bob"); // error, too few parameters let result2 = buildName("Bob", "Adams", "Sr."); // error, too many parameters let result3 = buildName("Bob", "Adams"); // okay and returns "Bob Adams" let result4 = buildName(undefined, "Adams"); // okay and returns "Will Adams"
#!/usr/bin/env ruby require 'erb' require 'json' require 'optparse' @target = nil @users = 1 @concurrency = 1 @maxrate = 10 @maxhits = nil OptionParser.new do | opts | opts.banner = "Usage: generate.rb [options] target" opts.on('--target [string]', "Specify the target server for requests (required)") do | v | @target = v.split(':') end opts.on('--virtual-users [int]', Integer, "Specify the number of virtual users (default: #{@users})") do | v | @users = v end opts.on('--virtual-user-clones [int]', Integer, "Specify the number of each virtual user clones (default: #{@concurrency})") do | v | @concurrency = v end opts.on('--max-request-rate [float]', Float, "Specify the maximum requests per minute (default: #{@maxrate})") do | v | @maxrate = v end opts.on('--max-hits [int]', Integer, "Maximum number of hits to generate jmeter requests (default: #{@maxhits})") do | v | @maxhits = v end opts.on('-h', '--help', 'Display this help') do puts opts exit end end.parse! raise OptionParser::InvalidOption if @target.nil? json = JSON.parse ARGF.read @buckets = Array.new(@users) { Array.new } json['hits']['hits'].each_with_index do | hit, i | next if not @maxhits.nil? and i > @maxhits source = hit['_source'] next if '/_bulk' == source['path'] @buckets[i % @users].push( { :id => hit['_index'] + ':' + hit['_id'], :method => source['method'], :path => source['path'], :querydata => source['querystr'], :requestdata => source['data'], } ) end template = ERB.new File.new("jmeter.jmx.erb").read, nil, "%" puts template.result(binding)
package gr.iti.mklab.reveal.forensics.util.ThumbnailExtractor.image.jpeg; import java.io.IOException; import java.io.InputStream; class TIFFHeader { boolean bigEndian; int ifdOffset; TIFFHeader(InputStream in) throws IOException { byte[] array = new byte[4]; if(<API key>.readFully(in, array, 2, false)!=2) { throw new IOException("Incomplete TIFF Header"); } if(array[0]==73 && array[1]==73) { //little endian bigEndian = false; } else if(array[0]==77 && array[1]==77) { //big endian bigEndian = true; } else { throw new IOException("Unrecognized endian encoding."); } if(<API key>.readFully(in, array, 2, !bigEndian)!=2) { throw new IOException("Incomplete TIFF Header"); } if(!(array[0]==0 && array[1]==42)) { //required byte in TIFF header throw new IOException("Missing required identifier 0x002A."); } if(<API key>.readFully(in, array, 4, !bigEndian)!=4) { throw new IOException("Incomplete TIFF Header"); } ifdOffset = ((array[0] & 0xff) << 24) + ((array[1] & 0xff) << 16) + ((array[2] & 0xff) << 8) + ((array[3] & 0xff) << 0) ; } /** The length of this TIFF header. */ int getLength() { return 8; } }
<?php use App\Models\Post; use Illuminate\Support\Facades\DB; use Test\Factory; use Test\TestCase; class PostControllerTest extends TestCase { public function setUp() { parent::setUp(); DB::table('posts')->delete(); $this->user = Factory::create('user'); $this->be($this->user); } public function testIndex() { $this->call('GET', 'posts'); $this->assertResponseOk(); $this->assertViewHas('posts'); } public function testCreate() { $this->call('GET', 'posts/create'); $this->assertResponseOk(); } public function testStore() { $countPosts = Post::count(); $inputs = [ 'title' => 'title POst', 'content' => 'Content posts' ]; $this->call('POST', 'posts', $inputs); $this->assertEquals($countPosts + 1, Post::count()); $this->assertRedirectedTo('/posts'); } public function testEdit() { $post = Factory::create('post'); $this->call('GET', 'posts/'.$post->id.'/edit'); $this->assertResponseOk(); } public function testUpdate() { $oldTitle = 'Old title'; $newTitle = 'New title'; $post = Factory::create('post', ['title' => $oldTitle]); $inputs = [ 'title' => $newTitle, ]; $this->shouldRedirectBack(); $this->call('PUT', 'posts/'.$post->id, $inputs); $freshPost = Post::find($post->id); $this->assertEquals($newTitle, $freshPost->title); } public function testDestroy() { $post = Factory::create('post'); $countPosts = Post::count(); $this->shouldRedirectBack(); $this->call('DELETE', 'posts/'.$post->id); $this->assertEquals($countPosts - 1, Post::count()); } }
package eu.ailao.hub.dialog; import eu.ailao.hub.corefresol.answers.ClueMemorizer; import eu.ailao.hub.corefresol.concepts.ConceptMemorizer; import eu.ailao.hub.questions.Question; import java.util.ArrayList; public class Dialog { private int id; private ArrayList<Question> questionsOfDialogue; private ConceptMemorizer conceptMemorizer; private ClueMemorizer clueMemorizer; public Dialog(int id) { this.id = id; this.questionsOfDialogue = new ArrayList<>(); this.conceptMemorizer = new ConceptMemorizer(); this.clueMemorizer = new ClueMemorizer(); } /** * Adds question to dialog * @param questionID id of question */ public void addQuestion(Question questionID) { questionsOfDialogue.add(questionID); } public ArrayList<Question> getQuestions() { return questionsOfDialogue; } /** * Gets all question's ids of dialog * @return array list of question's ids in dialog */ public ArrayList<Integer> getQuestionsIDs() { ArrayList<Integer> questionIDs = new ArrayList<Integer>(); for (int i = 0; i < questionsOfDialogue.size(); i++) { questionIDs.add(questionsOfDialogue.get(i).getYodaQuestionID()); } return questionIDs; } public int getId() { return id; } public ConceptMemorizer getConceptMemorizer() { return conceptMemorizer; } public ClueMemorizer getClueMemorizer() { return clueMemorizer; } public boolean hasQuestionWithId(int id) { for (Question question : questionsOfDialogue) { if (question.getYodaQuestionID() == id) { return true; } } return false; } }
package com.yahoo.bard.webservice.data.metric; /** * LogicalMetricColumn. */ public class LogicalMetricColumn extends MetricColumn { private final LogicalMetric metric; /** * Constructor. * * @param name The column name * @param metric The logical metric * * @deprecated because LogicalMetricColumn is really only a thing for LogicalTable, so there's no reason for there * to be an alias on the LogicalMetric inside the LogicalTableSchema. */ @Deprecated public LogicalMetricColumn(String name, LogicalMetric metric) { super(name); this.metric = metric; } /** * Constructor. * * @param metric The logical metric */ public LogicalMetricColumn(LogicalMetric metric) { super(metric.getName()); this.metric = metric; } /** * Getter for a logical metric. * * @return logical metric */ public LogicalMetric getLogicalMetric() { return this.metric; } @Override public String toString() { return "{logicalMetric:'" + getName() + "'}"; } }
require 'tpaga' Tpaga::Swagger.configure do |config| config.scheme = 'https' config.host = 'sandbox.tpaga.co' config.base_path = '/api' config.inject_format = false config.api_key = ENV["TPAGA_API_KEY"] end
package esidev import ( "net/http" "time" "github.com/gorilla/mux" ) var _ time.Time var _ = mux.NewRouter func GetIncursions(w http.ResponseWriter, r *http.Request) { var ( localV interface{} err error datasource string ) // shut up warnings localV = localV err = err j := `[ { "constellation_id" : 20000607, "faction_id" : 500019, "has_boss" : true, "<API key>" : [ 30004148, 30004149, 30004150, 30004151, 30004152, 30004153, 30004154 ], "influence" : 0.9, "<API key>" : 30004154, "state" : "mobilizing", "type" : "Incursion" } ]` if err := r.ParseForm(); err != nil { errorOut(w, r, err) return } if r.Form.Get("datasource") != "" { localV, err = processParameters(datasource, r.Form.Get("datasource")) if err != nil { errorOut(w, r, err) return } datasource = localV.(string) } if r.Form.Get("page") != "" { var ( localPage int32 localIntPage interface{} ) localIntPage, err := processParameters(localPage, r.Form.Get("page")) if err != nil { errorOut(w, r, err) return } localPage = localIntPage.(int32) if localPage > 1 { w.Header().Set("Content-Type", "application/json") w.WriteHeader(http.StatusOK) w.Write([]byte("[]")) return } } w.Header().Set("Content-Type", "application/json") w.WriteHeader(http.StatusOK) w.Write([]byte(j)) }
using System.Collections.Generic; using RestSharp; using SimpleJson; namespace MoneySharp.Internal.Model { public class SalesInvoicePost : SalesInvoice { public IList<SalesInvoiceDetail> details_attributes { get; set; } public JsonObject <API key> { get; set; } } }
package coop.ekologia.presentation.controller.user; import java.io.IOException; import javax.inject.Inject; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import coop.ekologia.presentation.EkologiaServlet; import coop.ekologia.presentation.session.LoginSession; /** * Servlet implementation class <API key> */ @WebServlet(<API key>.routing) public class <API key> extends EkologiaServlet { private static final long serialVersionUID = 1L; public static final String routing = "/login/deconnection"; public static final String routing(HttpServletRequest request) { return getUrl(request, routing); } @Inject LoginSession loginSession; /** * @see HttpServlet#HttpServlet() */ public <API key>() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { loginSession.setUser(null); response.sendRedirect(request.getHeader("referer")); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub } }
// <API key>.h // Tools #import "BaseViewController.h" @interface <API key> : BaseViewController @property (nonatomic, strong) NSString *url; @end
package org.seasar.doma.internal.jdbc.dialect; import org.seasar.doma.internal.jdbc.sql.<API key>; import org.seasar.doma.internal.jdbc.sql.node.AnonymousNode; import org.seasar.doma.jdbc.SqlNode; public class <API key> extends <API key><SqlNode, Void> { protected boolean processed; public SqlNode transform(SqlNode sqlNode) { AnonymousNode result = new AnonymousNode(); for (SqlNode child : sqlNode.getChildren()) { result.appendNode(child.accept(this, null)); } return result; } @Override protected SqlNode defaultAction(SqlNode node, Void p) { return node; } }
# Phaeosphaeria juncicola (Rehm ex G. Winter) L. Holm, 1957 SPECIES # Status ACCEPTED # According to The Catalogue of Life, 3rd January 2011 # Published in Symb. bot. upsal. 14(no. 3): 129 (1957) # Original name Leptosphaeria juncicola Rehm, 1879 Remarks null
<div class="uk-width-1-4@m"> <div class="uk-card uk-card-default uk-card-body <API key>"> <h3 class="uk-panel-title"></h3> <ul class="uk-list uk-list-line"> <li><a href="#">PHP</a></li> <li><a href="#">Javascript</a></li> </ul> </div> <div class="uk-card uk-card-default uk-card-body"> <h3 class="uk-panel-title"></h3> <ul class="uk-list"> </ul> </div> </div>
/* -*- mode: c; c-basic-offset: 4; indent-tabs-mode: nil -*- */ #include <errno.h> #include <string.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <regex.h> #include "pkinit.h" typedef struct _pkinit_cert_info pkinit_cert_info; typedef enum { kw_undefined = 0, kw_subject = 1, kw_issuer = 2, kw_san = 3, kw_eku = 4, kw_ku = 5 } keyword_type; static char * keyword2string(unsigned int kw) { switch(kw) { case kw_undefined: return "NONE"; break; case kw_subject: return "SUBJECT"; break; case kw_issuer: return "ISSUER"; break; case kw_san: return "SAN"; break; case kw_eku: return "EKU"; break; case kw_ku: return "KU"; break; default: return "INVALID"; break; } } typedef enum { relation_none = 0, relation_and = 1, relation_or = 2 } relation_type; static char * relation2string(unsigned int rel) { switch(rel) { case relation_none: return "NONE"; break; case relation_and: return "AND"; break; case relation_or: return "OR"; break; default: return "INVALID"; break; } } typedef enum { kwvaltype_undefined = 0, kwvaltype_regexp = 1, kwvaltype_list = 2 } kw_value_type; static char * kwval2string(unsigned int kwval) { switch(kwval) { case kwvaltype_undefined: return "NONE"; break; case kwvaltype_regexp: return "REGEXP"; break; case kwvaltype_list: return "LIST"; break; default: return "INVALID"; break; } } struct keyword_desc { const char *value; size_t length; keyword_type kwtype; kw_value_type kwvaltype; } matching_keywords[] = { { "<KU>", 4, kw_ku, kwvaltype_list }, { "<EKU>", 5, kw_eku, kwvaltype_list }, { "<SAN>", 5, kw_san, kwvaltype_regexp }, { "<ISSUER>", 8, kw_issuer, kwvaltype_regexp }, { "<SUBJECT>", 9, kw_subject, kwvaltype_regexp }, { NULL, 0, kw_undefined, kwvaltype_undefined}, }; struct ku_desc { const char *value; size_t length; unsigned int bitval; }; struct ku_desc ku_keywords[] = { { "digitalSignature", 16, <API key> }, { "keyEncipherment", 15, <API key> }, { NULL, 0, 0 }, }; struct ku_desc eku_keywords[] = { { "pkinit", 6, PKINIT_EKU_PKINIT }, { "msScLogin", 9, <API key> }, { "clientAuth", 10, <API key> }, { "emailProtection", 15, <API key> }, { NULL, 0, 0 }, }; /* Rule component */ typedef struct _rule_component { struct _rule_component *next; keyword_type kw_type; kw_value_type kwval_type; regex_t regexp; /* Compiled regular expression */ char *regsrc; /* The regular expression source (for debugging) */ unsigned int ku_bits; unsigned int eku_bits; } rule_component; /* Set rule components */ typedef struct _rule_set { relation_type relation; int num_crs; rule_component *crs; } rule_set; static krb5_error_code free_rule_component(krb5_context context, rule_component *rc) { if (rc == NULL) return 0; if (rc->kwval_type == kwvaltype_regexp) { free(rc->regsrc); regfree(&rc->regexp); } free(rc); return 0; } static krb5_error_code free_rule_set(krb5_context context, rule_set *rs) { rule_component *rc, *trc; if (rs == NULL) return 0; for (rc = rs->crs; rc != NULL;) { trc = rc->next; free_rule_component(context, rc); rc = trc; } free(rs); return 0; } static krb5_error_code parse_list_value(krb5_context context, keyword_type type, char *value, rule_component *rc) { krb5_error_code retval; char *comma; struct ku_desc *ku = NULL; int found; size_t len; unsigned int *bitptr; if (value == NULL || value[0] == '\0') { pkiDebug("%s: Missing or empty value for list keyword type %d\n", __FUNCTION__, type); retval = EINVAL; goto out; } if (type == kw_eku) { bitptr = &rc->eku_bits; } else if (type == kw_ku) { bitptr = &rc->ku_bits; } else { pkiDebug("%s: Unknown list keyword type %d\n", __FUNCTION__, type); retval = EINVAL; goto out; } do { found = 0; comma = strchr(value, ','); if (comma != NULL) len = comma - value; else len = strlen(value); if (type == kw_eku) { ku = eku_keywords; } else if (type == kw_ku) { ku = ku_keywords; } for (; ku->value != NULL; ku++) { if (strncasecmp(value, ku->value, len) == 0) { *bitptr |= ku->bitval; found = 1; pkiDebug("%s: Found value '%s', bitfield is now 0x%x\n", __FUNCTION__, ku->value, *bitptr); break; } } if (found) { value += ku->length; if (*value == ',') value += 1; } else { pkiDebug("%s: Urecognized value '%s'\n", __FUNCTION__, value); retval = EINVAL; goto out; } } while (found && *value != '\0'); retval = 0; out: pkiDebug("%s: returning %d\n", __FUNCTION__, retval); return retval; } static krb5_error_code <API key>(krb5_context context, const char **rule, int *remaining, rule_component **ret_rule) { krb5_error_code retval; rule_component *rc = NULL; keyword_type kw_type; kw_value_type kwval_type; char err_buf[128]; int ret; struct keyword_desc *kw, *nextkw; char *nk; int found_next_kw = 0; char *value = NULL; size_t len; for (kw = matching_keywords; kw->value != NULL; kw++) { if (strncmp(*rule, kw->value, kw->length) == 0) { kw_type = kw->kwtype; kwval_type = kw->kwvaltype; *rule += kw->length; *remaining -= kw->length; break; } } if (kw->value == NULL) { pkiDebug("%s: Missing or invalid keyword in rule '%s'\n", __FUNCTION__, *rule); retval = ENOENT; goto out; } pkiDebug("%s: found keyword '%s'\n", __FUNCTION__, kw->value); rc = calloc(1, sizeof(*rc)); if (rc == NULL) { retval = ENOMEM; goto out; } rc->next = NULL; rc->kw_type = kw_type; rc->kwval_type = kwval_type; /* * Before procesing the value for this keyword, * (compiling the regular expression or processing the list) * we need to find the end of it. That means parsing for the * beginning of the next keyword (or the end of the rule). */ nk = strchr(*rule, '<'); while (nk != NULL) { /* Possibly another keyword, check it out */ for (nextkw = matching_keywords; nextkw->value != NULL; nextkw++) { if (strncmp(nk, nextkw->value, nextkw->length) == 0) { /* Found a keyword, nk points to the beginning */ found_next_kw = 1; break; /* Need to break out of the while! */ } } if (!found_next_kw) nk = strchr(nk+1, '<'); /* keep looking */ else break; } if (nk != NULL && found_next_kw) len = (nk - *rule); else len = (*remaining); if (len == 0) { pkiDebug("%s: Missing value for keyword '%s'\n", __FUNCTION__, kw->value); retval = EINVAL; goto out; } value = calloc(1, len+1); if (value == NULL) { retval = ENOMEM; goto out; } memcpy(value, *rule, len); *remaining -= len; *rule += len; pkiDebug("%s: found value '%s'\n", __FUNCTION__, value); if (kw->kwvaltype == kwvaltype_regexp) { ret = regcomp(&rc->regexp, value, REG_EXTENDED); if (ret) { regerror(ret, &rc->regexp, err_buf, sizeof(err_buf)); pkiDebug("%s: Error compiling reg-exp '%s': %s\n", __FUNCTION__, value, err_buf); retval = ret; goto out; } rc->regsrc = strdup(value); if (rc->regsrc == NULL) { retval = ENOMEM; goto out; } } else if (kw->kwvaltype == kwvaltype_list) { retval = parse_list_value(context, rc->kw_type, value, rc); if (retval) { pkiDebug("%s: Error %d, parsing list values for keyword %s\n", __FUNCTION__, retval, kw->value); goto out; } } *ret_rule = rc; retval = 0; out: free(value); if (retval && rc != NULL) free_rule_component(context, rc); pkiDebug("%s: returning %d\n", __FUNCTION__, retval); return retval; } static krb5_error_code parse_rule_set(krb5_context context, const char *rule_in, rule_set **out_rs) { const char *rule; int remaining; krb5_error_code ret, retval; rule_component *rc = NULL, *trc; rule_set *rs; if (rule_in == NULL) return EINVAL; rule = rule_in; remaining = strlen(rule); rs = calloc(1, sizeof(*rs)); if (rs == NULL) { retval = ENOMEM; goto cleanup; } rs->relation = relation_none; if (remaining > 1) { if (rule[0] == '&' && rule[1] == '&') { rs->relation = relation_and; rule += 2; remaining -= 2; } else if (rule_in[0] == '|' && rule_in[1] == '|') { rs->relation = relation_or; rule +=2; remaining -= 2; } } rs->num_crs = 0; while (remaining > 0) { if (rs->relation == relation_none && rs->num_crs > 0) { pkiDebug("%s: Assuming AND relation for multiple components in rule '%s'\n", __FUNCTION__, rule_in); rs->relation = relation_and; } ret = <API key>(context, &rule, &remaining, &rc); if (ret) { retval = ret; goto cleanup; } pkiDebug("%s: After <API key>, remaining %d, rule '%s'\n", __FUNCTION__, remaining, rule); rs->num_crs++; /* * Chain the new component on the end (order matters since * we can short-circuit an OR or an AND relation if an * earlier check passes */ for (trc = rs->crs; trc != NULL && trc->next != NULL; trc = trc->next); if (trc == NULL) rs->crs = rc; else { trc->next = rc; } } *out_rs = rs; retval = 0; cleanup: if (retval && rs != NULL) { free_rule_set(context, rs); } pkiDebug("%s: returning %d\n", __FUNCTION__, retval); return retval; } static int regexp_match(krb5_context context, rule_component *rc, char *value) { int code; pkiDebug("%s: checking %s rule '%s' with value '%s'\n", __FUNCTION__, keyword2string(rc->kw_type), rc->regsrc, value); code = regexec(&rc->regexp, value, 0, NULL, 0); pkiDebug("%s: the result is%s a match\n", __FUNCTION__, code == REG_NOMATCH ? " NOT" : ""); return (code == 0 ? 1: 0); } static int component_match(krb5_context context, rule_component *rc, <API key> *md) { int match = 0; int i; krb5_principal p; char *princ_string; switch (rc->kwval_type) { case kwvaltype_regexp: switch (rc->kw_type) { case kw_subject: match = regexp_match(context, rc, md->subject_dn); break; case kw_issuer: match = regexp_match(context, rc, md->issuer_dn); break; case kw_san: if (md->sans == NULL) break; for (i = 0, p = md->sans[i]; p != NULL; p = md->sans[++i]) { krb5_unparse_name(context, p, &princ_string); match = regexp_match(context, rc, princ_string); <API key>(context, princ_string); if (match) break; } break; default: pkiDebug("%s: keyword %s, keyword value %s mismatch\n", __FUNCTION__, keyword2string(rc->kw_type), kwval2string(kwvaltype_regexp)); break; } break; case kwvaltype_list: switch(rc->kw_type) { case kw_eku: pkiDebug("%s: checking %s: rule 0x%08x, cert 0x%08x\n", __FUNCTION__, keyword2string(rc->kw_type), rc->eku_bits, md->eku_bits); if ((rc->eku_bits & md->eku_bits) == rc->eku_bits) match = 1; break; case kw_ku: pkiDebug("%s: checking %s: rule 0x%08x, cert 0x%08x\n", __FUNCTION__, keyword2string(rc->kw_type), rc->ku_bits, md->ku_bits); if ((rc->ku_bits & md->ku_bits) == rc->ku_bits) match = 1; break; default: pkiDebug("%s: keyword %s, keyword value %s mismatch\n", __FUNCTION__, keyword2string(rc->kw_type), kwval2string(kwvaltype_regexp)); break; } break; default: pkiDebug("%s: unknown keyword value type %d\n", __FUNCTION__, rc->kwval_type); break; } pkiDebug("%s: returning match = %d\n", __FUNCTION__, match); return match; } /* * Returns match_found == 1 only if exactly one certificate matches * the given rule */ static krb5_error_code check_all_certs(krb5_context context, <API key> plg_cryptoctx, <API key> req_cryptoctx, <API key> id_cryptoctx, krb5_principal princ, rule_set *rs, /* rule to check */ <API key> **matchdata, int *match_found, size_t *match_index) { krb5_error_code retval; <API key> *md; int i; int comp_match = 0; int total_cert_matches = 0; rule_component *rc; int certs_checked = 0; size_t save_index = 0; if (match_found == NULL || match_index == NULL) return EINVAL; *match_index = 0; *match_found = 0; pkiDebug("%s: matching rule relation is %s with %d components\n", __FUNCTION__, relation2string(rs->relation), rs->num_crs); /* * Loop through all the certs available and count * how many match the rule */ for (i = 0, md = matchdata[i]; md != NULL; md = matchdata[++i]) { pkiDebug("%s: subject: '%s'\n", __FUNCTION__, md->subject_dn); #if 0 pkiDebug("%s: issuer: '%s'\n", __FUNCTION__, md->subject_dn); for (j = 0, p = md->sans[j]; p != NULL; p = md->sans[++j]) { char *san_string; krb5_unparse_name(context, p, &san_string); pkiDebug("%s: san: '%s'\n", __FUNCTION__, san_string); <API key>(context, san_string); } #endif certs_checked++; for (rc = rs->crs; rc != NULL; rc = rc->next) { comp_match = component_match(context, rc, md); if (comp_match) { pkiDebug("%s: match for keyword type %s\n", __FUNCTION__, keyword2string(rc->kw_type)); } if (comp_match && rs->relation == relation_or) { pkiDebug("%s: cert matches rule (OR relation)\n", __FUNCTION__); total_cert_matches++; save_index = i; goto nextcert; } if (!comp_match && rs->relation == relation_and) { pkiDebug("%s: cert does not match rule (AND relation)\n", __FUNCTION__); goto nextcert; } } if (rc == NULL && comp_match) { pkiDebug("%s: cert matches rule (AND relation)\n", __FUNCTION__); total_cert_matches++; save_index = i; } nextcert: continue; } pkiDebug("%s: After checking %d certs, we found %d matches\n", __FUNCTION__, certs_checked, total_cert_matches); if (total_cert_matches == 1) { *match_found = 1; *match_index = save_index; } retval = 0; pkiDebug("%s: returning %d, match_found %d\n", __FUNCTION__, retval, *match_found); return retval; } krb5_error_code <API key>(krb5_context context, <API key> plg_cryptoctx, <API key> req_cryptoctx, <API key> id_cryptoctx, krb5_principal princ) { krb5_error_code retval = <API key>; int x; char **rules = NULL; rule_set *rs = NULL; int match_found = 0; <API key> **matchdata = NULL; size_t match_index = 0; /* If no matching rules, select the default cert and we're done */ <API key>(context, krb5_princ_realm(context, princ), <API key>, &rules); if (rules == NULL) { pkiDebug("%s: no matching rules found in config file\n", __FUNCTION__); retval = <API key>(context, plg_cryptoctx, req_cryptoctx, id_cryptoctx); goto cleanup; } /* parse each rule line one at a time and check all the certs against it */ for (x = 0; rules[x] != NULL; x++) { pkiDebug("%s: Processing rule '%s'\n", __FUNCTION__, rules[x]); /* Free rules from previous time through... */ if (rs != NULL) { free_rule_set(context, rs); rs = NULL; } retval = parse_rule_set(context, rules[x], &rs); if (retval) { if (retval == EINVAL) { pkiDebug("%s: Ignoring invalid rule pkinit_cert_match = '%s'\n", __FUNCTION__, rules[x]); continue; } goto cleanup; } /* * Optimize so that we do not get cert info unless we have * valid rules to check. Once obtained, keep it around * until we are done. */ if (matchdata == NULL) { retval = <API key>(context, plg_cryptoctx, req_cryptoctx, id_cryptoctx, &matchdata); if (retval || matchdata == NULL) { pkiDebug("%s: Error %d obtaining certificate information\n", __FUNCTION__, retval); retval = ENOENT; goto cleanup; } } retval = check_all_certs(context, plg_cryptoctx, req_cryptoctx, id_cryptoctx, princ, rs, matchdata, &match_found, &match_index); if (retval) { pkiDebug("%s: Error %d, checking certs against rule '%s'\n", __FUNCTION__, retval, rules[x]); goto cleanup; } if (match_found) { pkiDebug("%s: We have an exact match with rule '%s'\n", __FUNCTION__, rules[x]); break; } } if (match_found) { pkiDebug("%s: Selecting the matching cert!\n", __FUNCTION__); retval = crypto_cert_select(context, id_cryptoctx, match_index); if (retval) { pkiDebug("%s: crypto_cert_select error %d, %s\n", __FUNCTION__, retval, error_message(retval)); goto cleanup; } } else { <API key>(context); retval = ENOENT; /* XXX */ goto cleanup; } retval = 0; cleanup: profile_free_list(rules); free_rule_set(context, rs); <API key>(context, matchdata); return retval; } krb5_error_code <API key>(krb5_context context, <API key> plgctx, <API key> reqctx, const char *match_rule, krb5_boolean *matched) { krb5_error_code ret; <API key> *md = NULL; rule_component *rc = NULL; int comp_match = 0; rule_set *rs = NULL; *matched = FALSE; ret = parse_rule_set(context, match_rule, &rs); if (ret) goto cleanup; ret = <API key>(context, plgctx, reqctx, &md); if (ret) goto cleanup; for (rc = rs->crs; rc != NULL; rc = rc->next) { comp_match = component_match(context, rc, md); if ((comp_match && rs->relation == relation_or) || (!comp_match && rs->relation == relation_and)) { break; } } *matched = comp_match; cleanup: free_rule_set(context, rs); <API key>(context, md); return ret; }
package marcin_szyszka.mobileseconndhand.models; public class RegisterUserModel { public String Email; public String Password; public String ConfirmPassword; public RegisterUserModel(){ } }
// MianTableViewCell.h // SweetFood #import <UIKit/UIKit.h> #import "MianModel.h" #import "MainModel.h" @interface MianTableViewCell : UITableViewCell @property (strong, nonatomic) UIImageView *cellImage; @property (strong, nonatomic) UILabel *titleLable; @end
# AUTOGENERATED FILE FROM balenalib/<API key>:34-build # > At the moment, setting "LANG=C" on a Linux system *fundamentally breaks Python 3*, and that's not OK. ENV LANG C.UTF-8 RUN dnf install -y \ python3-pip \ python3-dbus \ && dnf clean all # install "virtualenv", since the vast majority of users of this image will want it RUN pip3 install -U --no-cache-dir --ignore-installed pip setuptools \ && pip3 install --no-cache-dir virtualenv RUN [ ! -d /.balena/messages ] && mkdir -p /.balena/messages; echo $'As of January 1st, 2020, Python 2 was end-of-life, we will change the latest tag for Balenalib Python base image to Python 3.x and drop support for Python 2 soon. So after 1st July, 2020, all the balenalib Python latest tag will point to the latest Python 3 version and no changes, or fixes will be made to balenalib Python 2 base image. If you are using Python 2 for your application, please upgrade to Python 3 before 1st July.' > /.balena/messages/<API key> 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/<SHA1-like>/scripts/assets/tests/test-stack@python.sh" \ && echo "Running test-stack@python" \ && chmod +x test-stack@python.sh \ && bash test-stack@python.sh \ && rm -rf test-stack@python.sh RUN [ ! -d /.balena/messages ] && mkdir -p /.balena/messages; echo $'Here are a few details about this Docker image (For more information please visit https: RUN echo $'#!/bin/sh.real\nbalena-info\nrm -f /bin/sh\ncp /bin/sh.real /bin/sh\n/bin/sh "$@"' > /bin/sh-shim \ && chmod +x /bin/sh-shim \ && cp /bin/sh /bin/sh.real \ && mv /bin/sh-shim /bin/sh
// Generated by esidl 0.3.0. // This file is expected to be modified for the Web IDL interface #include "AudioTrackListImp.h" namespace org { namespace w3c { namespace dom { namespace bootstrap { unsigned int AudioTrackListImp::getLength() { // TODO: implement me! return 0; } html::AudioTrack AudioTrackListImp::getElement(unsigned int index) { // TODO: implement me! return nullptr; } html::AudioTrack AudioTrackListImp::getTrackById(const std::u16string& id) { // TODO: implement me! return nullptr; } events::EventHandlerNonNull AudioTrackListImp::getOnchange() { // TODO: implement me! return nullptr; } void AudioTrackListImp::setOnchange(events::EventHandlerNonNull onchange) { // TODO: implement me! } events::EventHandlerNonNull AudioTrackListImp::getOnaddtrack() { // TODO: implement me! return nullptr; } void AudioTrackListImp::setOnaddtrack(events::EventHandlerNonNull onaddtrack) { // TODO: implement me! } events::EventHandlerNonNull AudioTrackListImp::getOnremovetrack() { // TODO: implement me! return nullptr; } void AudioTrackListImp::setOnremovetrack(events::EventHandlerNonNull onremovetrack) { // TODO: implement me! } } } } }
package org.annoconf; public interface PropertyValueSource { boolean hasValue(String key); String getValue(String key); }
<!DOCTYPE HTML PUBLIC "- <!--NewPage <HTML> <HEAD> <!-- Generated by javadoc (build 1.6.0_29) on Sun Feb 05 12:13:54 CET 2012 --> <META http-equiv="Content-Type" content="text/html; charset=UTF-8"> <TITLE> Uses of Class org.jboss.netty.channel.socket.nio.<API key> (The Netty Project API Reference (3.3.1.Final)) </TITLE> <META NAME="date" CONTENT="2012-02-05"> <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.jboss.netty.channel.socket.nio.<API key> (The Netty Project API Reference (3.3.1.Final))"; } } </SCRIPT> <NOSCRIPT> </NOSCRIPT> </HEAD> <BODY BGCOLOR="white" onload="windowTitle();"> <HR> <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>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../org/jboss/netty/channel/socket/nio/<API key>.html" title="class in org.jboss.netty.channel.socket.nio"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;PREV&nbsp; &nbsp;NEXT</FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../../../../index.html?org/jboss/netty/channel/socket/nio//<API key>.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="<API key>.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<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> <HR> <CENTER> <H2> <B>Uses of Class<br>org.jboss.netty.channel.socket.nio.<API key></B></H2> </CENTER> No usage of org.jboss.netty.channel.socket.nio.<API key> <P> <HR> <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="<API key>"></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>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../org/jboss/netty/channel/socket/nio/<API key>.html" title="class in org.jboss.netty.channel.socket.nio"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;PREV&nbsp; &nbsp;NEXT</FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../../../../index.html?org/jboss/netty/channel/socket/nio//<API key>.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="<API key>.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<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> <HR> Copyright & </BODY> </HTML>
package com.delmar.core.service; import com.delmar.core.model.CorePage; import com.delmar.core.service.CoreService; /** * @author 2016-08-26 17:08:24 */ public interface CorePageService extends CoreService<CorePage> { /** * @param ids */ void deleteCorePageList(Integer[] ids); }
package de.hsmainz.pubapp.geocoder.controller; import com.google.gson.Gson; import de.hsmainz.pubapp.geocoder.model.ClientInputJson; import de.hsmainz.pubapp.geocoder.model.ErrorJson; import de.hsmainz.pubapp.geocoder.model.geojson.GeoJsonCollection; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import java.util.Locale; import java.util.ResourceBundle; /** * Interface for all different geocoder APIs * * @author Arno * @since 15.12.2016 */ public abstract class HttpAPIRequest { /** * Executes request to geocoder API and creates GeoJSON. Custom ClientJson is used for the input * * @param inputJson the request parameters combined in a custom ClientJson * @return API response converted to a String */ public String requestGeocoder(ClientInputJson inputJson) { String returnString; if (!validateInput(inputJson)) { returnString = gson.toJson(new ErrorJson(lables.getString("message_Input_Empty"))); } else { returnString = requestGeocoder(inputJson.getQueryString(), inputJson.getLocale()); } return returnString; } /** * Executes request to geocoder API and creates GeoJSON * * @param queryString the string containing the address * @param locale the string defining the used language * @return API response converted to a String */ public String requestGeocoder(String queryString, String locale) { String returnString; if (!validateInput(queryString)) { returnString = gson.toJson(new ErrorJson(lables.getString("message_Input_Empty"))); } else { try { URI uri = buildUri(queryString, locale); returnString = request(uri); } catch (URISyntaxException e) { logger.catching(e); returnString = gson.toJson(new ErrorJson(lables.getString("error_incorrect_URI"))); } } return returnString; } /** * Creates the URI for API request * * @param queryString the string containing the address * @param locale the string defining the used language * @return Uri for geocoder request to graphhopper API */ abstract URI buildUri(String queryString, String locale) throws URISyntaxException; /** * Executes the request to the API * * @param uri the geocoder URL * @return the requested geoJSON * @throws throws an exception if the request fails */ abstract GeoJsonCollection doHttpGet(URI uri) throws IOException; /** * Method to catch exceptions and create ErrorJSONs * * @param uri * @return returns the GeoJSON or ErrorJSON as a String */ String request(URI uri) { String returnString; try { GeoJsonCollection geoJsonCollection = doHttpGet(uri); if (validateOutput(geoJsonCollection)) { returnString = gson.toJson(geoJsonCollection); } else { returnString = gson.toJson(new ErrorJson(lables.getString("message_no_location"))); } } catch (IOException e) { logger.catching(e); returnString = gson.toJson(new ErrorJson(lables.getString("<API key>"))); } return returnString; } /** * validates the Input to reduce unnecessary request to API * * @param inputJson the InputJSON to be validated * @return returns true if InputJSON is valid */ boolean validateInput(ClientInputJson inputJson) { boolean returnValue = true; if (inputJson.getQueryString() == null || inputJson.getQueryString().isEmpty()) { returnValue = false; } if (inputJson.getLocale() == null || inputJson.getLocale().isEmpty()) { returnValue = false; } return returnValue; } /** * validates the Input to reduce unnecessary request to API * * @param inputString the Input String to be validated * @return true if Input String is not Empty */ boolean validateInput(String inputString) { boolean returnValue = true; if (inputString == null || inputString.isEmpty()) { returnValue = false; } return returnValue; } /** * validates the output from the API * * @param geoJsonCollection the API outputJSON to be validated * @return returns true if the outputJSON is not empty */ private boolean validateOutput(GeoJsonCollection geoJsonCollection) { return !geoJsonCollection.getFeatures().isEmpty(); }
package com.txtr.hibernatedelta.model; import static javax.xml.bind.annotation.XmlAccessType.FIELD; import java.util.ArrayList; import java.util.List; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlElementWrapper; import javax.xml.bind.annotation.XmlType; import org.apache.commons.lang3.StringUtils; @XmlAccessorType(FIELD) @XmlType(propOrder = {"name", "columns", "explicitIndexes"}) public class HibernateTable implements <API key> { @XmlAttribute private String name; @XmlElementWrapper(name = "columns") @XmlElement(name = "column") private List<HibernateColumn> columns = new ArrayList<HibernateColumn>(); @XmlElementWrapper(name = "indexes") @XmlElement(name = "index") private List<<API key>> explicitIndexes = new ArrayList<<API key>>(); @XmlAttribute private String sequenceName; @XmlAttribute private boolean virtualRootTable; public HibernateTable(String name, String sequenceName, boolean virtualRootTable) { this.sequenceName = sequenceName; this.virtualRootTable = virtualRootTable; this.name = name; } @SuppressWarnings("UnusedDeclaration") public HibernateTable() { } @Override public String getName() { return name; } public void setName(String name) { this.name = name; } public List<HibernateColumn> getColumns() { return columns; } public List<<API key>> getExplicitIndexes() { return explicitIndexes; } public void addColumn(HibernateColumn column) { columns.add(column); } public HibernateColumn getColumn(String name) { for (HibernateColumn column : columns) { if (column.getName().equalsIgnoreCase(name)) { return column; } } throw new <API key>("column not found: " + name); } public void addExplicitIndex(<API key> hibernateIndex) { explicitIndexes.add(hibernateIndex); } public String getIndexPrefix() { return StringUtils.left(name, 28); } public List<HibernateColumn> <API key>() { List<HibernateColumn> result = new ArrayList<HibernateColumn>(); for (HibernateColumn column : columns) { if (column.isPrimaryKey()) { result.add(column); } } return result; } public String getSequenceName() { return sequenceName; } public boolean isVirtualRootTable() { return virtualRootTable; } }
package me.learn.personal.month5; import java.util.HashSet; import java.util.List; import java.util.Set; /** * Title : * * Date : Dec 23, 2020 * * @author bramanarayan * */ public class WordBreakable { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub } public boolean wordBreak(String s, List<String> wordDict) { Set<String> wordDictSet = new HashSet<>(wordDict); boolean[] dp = new boolean[s.length() + 1]; dp[0] = true; for (int i = 1; i <= s.length(); i++) { for (int j = 0; j < i; j++) { if (dp[j] && wordDictSet.contains(s.substring(j, i))) { dp[i] = true; break; } } } return dp[s.length()]; } }
package scadla.utils import scadla._ import squants.space.Length import scala.language.postfixOps import squants.space.LengthConversions._ object Tube { def apply(outerRadius: Length, innerRadius: Length, height: Length) = { Difference( Cylinder(outerRadius, height), Translate(0 mm, 0 mm, -1 mm, Cylinder(innerRadius, height + (2 mm))) ) } }
package web; import graphUtil.<API key>; import graphUtil.EdgeChain; import ilog.concert.IloException; import java.util.HashMap; import java.util.List; import java.util.Map; import kepLib.KepInstance; import kepLib.KepProblemData; import kepModeler.<API key>; import kepModeler.KepModeler; import kepModeler.ModelerInputs; import kepModeler.ObjectiveMode; import replicator.DonorEdge; import threading.FixedThreadPool; import com.google.common.base.Optional; import com.google.common.collect.ImmutableList; import com.google.common.collect.Lists; import data.Donor; import data.ExchangeUnit; import database.KidneyDataBase; import exchangeGraph.<API key>; import exchangeGraph.SolverOption; public class KidneyServerSolver { private KidneyDataBase database; private Map<String, ModelerInputs<ExchangeUnit, DonorEdge>> dataCache = new HashMap<String, ModelerInputs<ExchangeUnit, DonorEdge>>(); private Optional<FixedThreadPool> threadPool; Optional<Double> maxSolveTimeMs = Optional.of(100.0); public KidneyServerSolver(KidneyDataBase database, Optional<FixedThreadPool> threadPool) { this.database = database; this.threadPool = threadPool; } public ImmutableList<String> availableDatasets() { return database.availableDatasets(); } public Map<Object, Object> getInputs(String databaseName) { return <API key>(getModelerInputs(databaseName)); } public Map<Object, Object> getSolution(String databaseName) throws IloException { ModelerInputs<ExchangeUnit, DonorEdge> inputs = getModelerInputs(databaseName); KepModeler modeler = new KepModeler(3, Integer.MAX_VALUE, <API key>.none, new ObjectiveMode.<API key>()); KepInstance<ExchangeUnit, DonorEdge> instance = modeler.makeKepInstance( inputs, null); <API key><ExchangeUnit, DonorEdge> solver = new <API key><ExchangeUnit, DonorEdge>( instance, true, maxSolveTimeMs, threadPool, SolverOption.makeCheckedOptions(SolverOption.cutsetMode, SolverOption.<API key>, SolverOption.userCutCallback)); solver.solve(); <API key><ExchangeUnit, DonorEdge> solution = solver .getSolution(); solver.cleanUp(); return flattenSolution(inputs.getKepProblemData(), solution); } private ModelerInputs<ExchangeUnit, DonorEdge> getModelerInputs( String databaseName) { if (this.dataCache.containsKey(databaseName)) { return this.dataCache.get(databaseName); } else { ModelerInputs<ExchangeUnit, DonorEdge> inputs = database .loadInputs(databaseName); this.dataCache.put(databaseName, inputs); return inputs; } } public static Map<Object, Object> <API key>( ModelerInputs<ExchangeUnit, DonorEdge> inputs) { Map<Object, Object> ans = new HashMap<Object, Object>(); List<Map<Object, Object>> flatUnits = Lists.newArrayList(); List<Map<Object, Object>> flatEdges = Lists.newArrayList(); for (ExchangeUnit unit : inputs.getKepProblemData().getGraph() .getVertices()) { flatUnits.add(flattenExchangeUnit(inputs, unit)); } for (DonorEdge edge : inputs.getKepProblemData().getGraph().getEdges()) { flatEdges.add(flattenDonorEdge(inputs.getKepProblemData(), edge)); } ans.put("nodes", flatUnits); ans.put("links", flatEdges); return ans; } public static Map<Object, Object> flattenSolution( KepProblemData<ExchangeUnit, DonorEdge> problemData, <API key><ExchangeUnit, DonorEdge> solution) { Map<Object, Object> ans = new HashMap<Object, Object>(); List<Map<Object, Object>> flatEdges = Lists.newArrayList(); for (EdgeChain<DonorEdge> edgeChain : solution.getEdgeChains()) { for (DonorEdge edge : edgeChain) { flatEdges.add(flattenDonorEdge(problemData, edge)); } } ans.put("links", flatEdges); return ans; } private static Map<Object, Object> flattenDonorEdge( KepProblemData<ExchangeUnit, DonorEdge> kepProblemData, DonorEdge edge) { Map<Object, Object> ans = new HashMap<Object, Object>(); ExchangeUnit source = kepProblemData.getGraph().getSource(edge); ExchangeUnit dest = kepProblemData.getGraph().getDest(edge); String sourceId = makeNodeId(kepProblemData, source); String destId = makeNodeId(kepProblemData, dest); ans.put("sourceId", sourceId); ans.put("targetId", destId); ans.put("id", sourceId + destId); return ans; } private static Map<Object, Object> flattenExchangeUnit( ModelerInputs<ExchangeUnit, DonorEdge> inputs, ExchangeUnit unit) { Map<Object, Object> ans = new HashMap<Object, Object>(); ans.put("id", makeNodeId(inputs.getKepProblemData(), unit)); ans.put("type", makeType(inputs.getKepProblemData(), unit)); ans.put("reachable", true); ans.put("sensitized", <API key>(inputs, unit)); return ans; } private static String makeNodeId( KepProblemData<ExchangeUnit, DonorEdge> kepProblemData, ExchangeUnit unit) { if (kepProblemData.getRootNodes().contains(unit)) { return unit.getDonor().get(0).getId(); } else { return unit.getReceiver().getId(); } } private static String makeType( KepProblemData<ExchangeUnit, DonorEdge> kepProblemData, ExchangeUnit unit) { if (kepProblemData.getRootNodes().contains(unit)) { return "root"; } else if (kepProblemData.getPairedNodes().contains(unit)) { return "paired"; } else if (kepProblemData.getTerminalNodes().contains(unit)) { return "terminal"; } else { throw new RuntimeException(); } } private static int <API key>( ModelerInputs<ExchangeUnit, DonorEdge> inputs, ExchangeUnit unit) { Map<ExchangeUnit, Double> donorPower = inputs.<API key>() .<API key>(); Map<ExchangeUnit, Double> receiverPower = inputs .<API key>().<API key>(); // System.out.println(donorPower); // System.out.println(receiverPower); if (inputs.getKepProblemData().getRootNodes().contains(unit)) { if (donorPower.containsKey(unit.getDonor().get(0))) { return <API key>(donorPower.get(unit.getDonor().get(0))); } else { // System.err.println("missing donor power data for: " + unit); return 0; } } else if (inputs.getKepProblemData().getPairedNodes().contains(unit)) { double unitDonorPower = 0; for (Donor donor : unit.getDonor()) { if (donorPower.containsKey(donor)) { unitDonorPower += donorPower.get(donor); } else { // System.err.println("missing donor power data for: " + unit); return 0; } } if (receiverPower.containsKey(unit.getReceiver())) { return <API key>(unitDonorPower, receiverPower.get(unit.getReceiver())); } else { // System.err.println("missing receiver power for: " + unit); return 0; } } else if (inputs.getKepProblemData().getTerminalNodes().contains(unit)) { if (receiverPower.containsKey(unit.getReceiver())) { return <API key>(receiverPower.get(unit.getReceiver())); } else { // System.err.println("missing receiver power for: " + unit); return 0; } } else { throw new RuntimeException(); } } private static int <API key>(double matchPower) { if (matchPower < .01) { return 3; } else if (matchPower < .08) { return 2; } else if (matchPower < .2) { return 1; } else { return 0; } } private static int <API key>(double donorMatchPower, double receiverMatchPower) { double pmp = 10000 * donorMatchPower * receiverMatchPower; if (pmp < .1) { return 4; } else if (pmp < 5) { return 3; } else if (pmp < 20) { return 2; } else if (pmp < 60) { return 1; } else { return 0; } } }
# encoding: utf-8 import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Adding model 'Journey' db.create_table('places_journey', ( ('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)), ('route', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['places.Route'])), ('external_ref', self.gf('django.db.models.fields.TextField')()), ('notes', self.gf('django.db.models.fields.TextField')(null=True, blank=True)), ('runs_on_monday', self.gf('django.db.models.fields.BooleanField')(default=False)), ('runs_on_tuesday', self.gf('django.db.models.fields.BooleanField')(default=False)), ('runs_on_wednesday', self.gf('django.db.models.fields.BooleanField')(default=False)), ('runs_on_thursday', self.gf('django.db.models.fields.BooleanField')(default=False)), ('runs_on_friday', self.gf('django.db.models.fields.BooleanField')(default=False)), ('runs_on_saturday', self.gf('django.db.models.fields.BooleanField')(default=False)), ('runs_on_sunday', self.gf('django.db.models.fields.BooleanField')(default=False)), ('runs_in_termtime', self.gf('django.db.models.fields.BooleanField')(default=False)), ('<API key>', self.gf('django.db.models.fields.BooleanField')(default=False)), ('<API key>', self.gf('django.db.models.fields.BooleanField')(default=False)), ('<API key>', self.gf('django.db.models.fields.BooleanField')(default=False)), ('runs_from', self.gf('django.db.models.fields.DateField')()), ('runs_until', self.gf('django.db.models.fields.DateField')()), ('vehicle', self.gf('django.db.models.fields.TextField')()), )) db.send_create_signal('places', ['Journey']) # Adding model 'ScheduledStop' db.create_table('<API key>', ( ('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)), ('entity', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['places.Entity'])), ('journey', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['places.Journey'])), ('order', self.gf('django.db.models.fields.IntegerField')()), ('sta', self.gf('django.db.models.fields.TimeField')(null=True, blank=True)), ('std', self.gf('django.db.models.fields.TimeField')(null=True, blank=True)), ('times_estimated', self.gf('django.db.models.fields.BooleanField')(default=False)), ('fare_stage', self.gf('django.db.models.fields.BooleanField')(default=False)), ('activity', self.gf('django.db.models.fields.CharField')(default='B', max_length=1)), )) db.send_create_signal('places', ['ScheduledStop']) def backwards(self, orm): # Deleting model 'Journey' db.delete_table('places_journey') # Deleting model 'ScheduledStop' db.delete_table('<API key>') models = { 'places.entity': { 'Meta': {'object_name': 'Entity'}, '_identifiers': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['places.Identifier']", 'symmetrical': 'False'}), '_metadata': ('django.db.models.fields.TextField', [], {'default': "'{}'"}), 'absolute_url': ('django.db.models.fields.TextField', [], {}), 'all_types': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'related_name': "'entities'", 'blank': 'True', 'to': "orm['places.EntityType']"}), '<API key>': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'related_name': "'entities_completion'", 'blank': 'True', 'to': "orm['places.EntityType']"}), 'geometry': ('django.contrib.gis.db.models.fields.GeometryField', [], {'null': 'True'}), 'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['places.EntityGroup']", 'symmetrical': 'False'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'identifier_scheme': ('django.db.models.fields.CharField', [], {'max_length': '32'}), 'identifier_value': ('django.db.models.fields.CharField', [], {'max_length': '256'}), 'is_stack': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'is_sublocation': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'location': ('django.contrib.gis.db.models.fields.PointField', [], {'null': 'True'}), 'parent': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['places.Entity']", 'null': 'True'}), 'primary_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['places.EntityType']", 'null': 'True'}), 'source': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['places.Source']"}) }, 'places.entitygroup': { 'Meta': {'object_name': 'EntityGroup'}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'ref_code': ('django.db.models.fields.CharField', [], {'max_length': '256'}), 'source': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['places.Source']"}) }, 'places.entitygroupname': { 'Meta': {'unique_together': "(('entity_group', 'language_code'),)", 'object_name': 'EntityGroupName'}, 'entity_group': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'names'", 'to': "orm['places.EntityGroup']"}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'language_code': ('django.db.models.fields.CharField', [], {'max_length': '10'}), 'title': ('django.db.models.fields.TextField', [], {}) }, 'places.entityname': { 'Meta': {'unique_together': "(('entity', 'language_code'),)", 'object_name': 'EntityName'}, 'entity': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'names'", 'to': "orm['places.Entity']"}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'language_code': ('django.db.models.fields.CharField', [], {'max_length': '10'}), 'title': ('django.db.models.fields.TextField', [], {}) }, 'places.entitytype': { 'Meta': {'object_name': 'EntityType'}, 'category': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['places.EntityTypeCategory']"}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'note': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), '<API key>': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'show_in_nearby_list': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'slug': ('django.db.models.fields.SlugField', [], {'max_length': '50', 'db_index': 'True'}), 'subtype_of': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'related_name': "'subtypes'", 'blank': 'True', 'to': "orm['places.EntityType']"}), '<API key>': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'related_name': "'subtypes_completion'", 'blank': 'True', 'to': "orm['places.EntityType']"}) }, 'places.entitytypecategory': { 'Meta': {'object_name': 'EntityTypeCategory'}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.TextField', [], {}) }, 'places.entitytypename': { 'Meta': {'unique_together': "(('entity_type', 'language_code'),)", 'object_name': 'EntityTypeName'}, 'entity_type': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'names'", 'to': "orm['places.EntityType']"}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'language_code': ('django.db.models.fields.CharField', [], {'max_length': '10'}), 'verbose_name': ('django.db.models.fields.TextField', [], {}), 'verbose_name_plural': ('django.db.models.fields.TextField', [], {}), '<API key>': ('django.db.models.fields.TextField', [], {}) }, 'places.identifier': { 'Meta': {'object_name': 'Identifier'}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'scheme': ('django.db.models.fields.CharField', [], {'max_length': '32'}), 'value': ('django.db.models.fields.CharField', [], {'max_length': '256'}) }, 'places.journey': { 'Meta': {'object_name': 'Journey'}, 'external_ref': ('django.db.models.fields.TextField', [], {}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'notes': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), 'route': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['places.Route']"}), 'runs_from': ('django.db.models.fields.DateField', [], {}), '<API key>': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'runs_in_termtime': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), '<API key>': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'runs_on_friday': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'runs_on_monday': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), '<API key>': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'runs_on_saturday': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'runs_on_sunday': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'runs_on_thursday': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'runs_on_tuesday': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'runs_on_wednesday': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'runs_until': ('django.db.models.fields.DateField', [], {}), 'vehicle': ('django.db.models.fields.TextField', [], {}) }, 'places.route': { 'Meta': {'object_name': 'Route'}, 'external_ref': ('django.db.models.fields.TextField', [], {}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'operator': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), 'service_id': ('django.db.models.fields.TextField', [], {}), 'service_name': ('django.db.models.fields.TextField', [], {'null': 'True'}), 'stops': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['places.Entity']", 'through': "orm['places.StopOnRoute']", 'symmetrical': 'False'}) }, 'places.scheduledstop': { 'Meta': {'ordering': "['order']", 'object_name': 'ScheduledStop'}, 'activity': ('django.db.models.fields.CharField', [], {'default': "'B'", 'max_length': '1'}), 'entity': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['places.Entity']"}), 'fare_stage': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'journey': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['places.Journey']"}), 'order': ('django.db.models.fields.IntegerField', [], {}), 'sta': ('django.db.models.fields.TimeField', [], {'null': 'True', 'blank': 'True'}), 'std': ('django.db.models.fields.TimeField', [], {'null': 'True', 'blank': 'True'}), 'times_estimated': ('django.db.models.fields.BooleanField', [], {'default': 'False'}) }, 'places.source': { 'Meta': {'object_name': 'Source'}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'last_updated': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}), 'module_name': ('django.db.models.fields.CharField', [], {'max_length': '128'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '128'}) }, 'places.stoponroute': { 'Meta': {'ordering': "['order']", 'object_name': 'StopOnRoute'}, 'entity': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['places.Entity']"}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'order': ('django.db.models.fields.IntegerField', [], {}), 'route': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['places.Route']"}) } } complete_apps = ['places']
package com.jaivox.ui.appmaker; import java.io.*; import java.util.*; import bitpix.list.*; public class Rule2Fsm { static String dir = "./"; basicTree tree; TreeMap <String, String> states; TreeMap <String, String> tags; static String name = "data/road1.tree"; static String yes = "yes"; String startState = "def"; static String casedefault = "(default) (def)"; static basicNode casedefaultnode; Vector <String> store; public Rule2Fsm () { String filename = dir + name; startState = startState; tree = new basicTree (filename); // tree.WriteTree (); states = new TreeMap <String, String> (); tags = new TreeMap <String, String> (); Vector <bitpix.list.basicNode> list = tree.Root.ListChild; casedefaultnode = new basicNode (casedefault); store = new Vector <String> (); store.add ("\n#include errors.dlg\n"); for (int i=0; i<list.size (); i++) { basicNode child = list.elementAt (i); gt (child, startState); } int pos = filename.lastIndexOf ("."); String outfile = filename.substring (0, pos+1) + "dlg"; // writefile (outfile, store); } void Debug (String s) { System.out.println ("[Rule2Fsm]" + s); } void gt (basicNode node, String sofar) { Vector <bitpix.list.basicNode> list = node.ListChild; if (list == null || list.size () == 0) { // emit a state with def emit (node, sofar, "def"); } else { String nextstate = createNextState (node); String morefar = sofar + " " + nextstate; emit (node, sofar, nextstate); list.add (casedefaultnode); for (int i=0; i<list.size (); i++) { basicNode child = list.elementAt (i); gt (child, morefar); } } } void emit (basicNode node, String sofar, String next) { int pos = sofar.lastIndexOf (" "); pos++; String last = sofar.substring (pos); String tag = sofar.replaceAll (" ", "_"); tag = tag + "_" + next; tag = getuniquetag (tag); StringBuffer sb = new StringBuffer (); sb.append ("{\n["+tag+"]\n"); String t = (String)node.Tag; if (t.trim ().length () == 0) return; StringTokenizer st = new StringTokenizer (t, "()"); if (st.countTokens () < 2) { Debug ("Don't have two tokens from "+t); return; } String input = filter (st.nextToken ()).trim (); String output = filter (st.nextToken ()).trim (); while (output.length () == 0) output = filter (st.nextToken ()).trim (); // Debug ("tag="+t+" / input="+input+" output="+output); // sb.append ("\t"+sofar+" ;\n"); // with Gui2Gram, convert input and output to use dotted head tag form String indot = input.replaceAll (" ", "."); String outdot = output.replaceAll (" ", "."); sb.append ("\t"+last+" ;\n"); // sb.append ("\t"+input+" ;\n"); // sb.append ("\t"+output+" ;\n"); sb.append ("\t"+indot+" ;\n"); sb.append ("\t"+outdot+" ;\n"); sb.append ("\t"+next+" ;\n"); sb.append ("}\n"); String all = new String (sb); store.add (all); // System.out.println (all); } static String filter (String line) { return Gui2Gram.filter (line); } String createNextState (basicNode node) { String tag = (String)(node.Tag); StringTokenizer st = new StringTokenizer (tag, "()"); if (st.countTokens () < 2) { Debug ("don't have two tokens in "+tag); return "def"; } String input = st.nextToken ().trim (); String output = st.nextToken ().trim (); while (output.length () == 0) output = st.nextToken ().trim (); StringTokenizer tt = new StringTokenizer (output); int n = tt.countTokens (); StringBuffer sb = new StringBuffer (); for (int i=0; i<Math.min (n, 3); i++) { String token = tt.nextToken (); sb.append (token.charAt (0)); } if (n < 3) { for (int j=n; j<3; j++) { sb.append ('x'); } } String s = new String (sb); String test = states.get (s); if (test != null) { for (int i=1; i<10; i++) { String next = s + i; if (states.get (next) == null) { s = next; break; } } } states.put (s, yes); return s; } String getuniquetag (String in) { if (tags.get (in) == null) { tags.put (in, yes); return in; } else { for (int i=1; i<99; i++) { String next = in+"_"+i; if (tags.get (next) != null) { continue; } tags.put (next, yes); return next; } Debug ("More than 99 tags starting with "+in); return "error"; } } void writeRules (PrintWriter out) { try { for (int i=0; i<store.size (); i++) { out.println (store.elementAt (i)); } } catch (Exception e) { e.printStackTrace (); } } }
/** * Provides commands for the Application API. */ package ca.phon.opgraph.app.commands;
<?php class Gep_ScoreController extends <API key> { public function init() { /* Initialize action controller here */ header('content-type: text/html; charset=utf8'); } public function indexAction(){ } public function fullResultAction(){ } }
<!DOCTYPE HTML PUBLIC "- <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (1.8.0_151) on Wed Jan 16 10:54:22 MST 2019 --> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>org.wildfly.swarm.jaeger (BOM: * : All 2.3.0.Final-SNAPSHOT API)</title> <meta name="date" content="2019-01-16"> <link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style"> <script type="text/javascript" src="../../../../script.js"></script> </head> <body> <h1 class="bar"><a href="../../../../org/wildfly/swarm/jaeger/package-summary.html" target="classFrame">org.wildfly.swarm.jaeger</a></h1> <div class="indexContainer"> <h2 title="Classes">Classes</h2> <ul title="Classes"> <li><a href="JaegerFraction.html" title="class in org.wildfly.swarm.jaeger" target="classFrame">JaegerFraction</a></li> </ul> </div> </body> </html>
CREATE TABLE TASK_EXECUTION ( TASK_EXECUTION_ID BIGINT NOT NULL PRIMARY KEY , START_TIME DATETIME DEFAULT NULL , END_TIME DATETIME DEFAULT NULL , TASK_NAME VARCHAR(100) , EXIT_CODE INTEGER , EXIT_MESSAGE VARCHAR(2500) , ERROR_MESSAGE VARCHAR(2500) , LAST_UPDATED DATETIME , <API key> VARCHAR(255), PARENT_EXECUTION_ID BIGINT ); CREATE TABLE <API key> ( TASK_EXECUTION_ID BIGINT NOT NULL , TASK_PARAM VARCHAR(2500) , constraint TASK_EXEC_PARAMS_FK foreign key (TASK_EXECUTION_ID) references TASK_EXECUTION(TASK_EXECUTION_ID) ) ; CREATE TABLE TASK_TASK_BATCH ( TASK_EXECUTION_ID BIGINT NOT NULL , JOB_EXECUTION_ID BIGINT NOT NULL , constraint TASK_EXEC_BATCH_FK foreign key (TASK_EXECUTION_ID) references TASK_EXECUTION(TASK_EXECUTION_ID) ) ; CREATE TABLE TASK_SEQ (ID BIGINT IDENTITY);
<!DOCTYPE html> <html xmlns="http: <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/> <link rel="SHORTCUT ICON" href="../../../../../img/clover.ico" /> <link rel="stylesheet" href="../../../../../aui/css/aui.min.css" media="all"/> <link rel="stylesheet" href="../../../../../aui/css/aui-experimental.min.css" media="all"/> <!--[if IE 9]><link rel="stylesheet" href="../../../../../aui/css/aui-ie9.min.css" media="all"/><![endif]--> <style type="text/css" media="all"> @import url('../../../../../style.css'); @import url('../../../../../tree.css'); </style> <script src="../../../../../jquery-1.8.3.min.js" type="text/javascript"></script> <script src="../../../../../aui/js/aui.min.js" type="text/javascript"></script> <script src="../../../../../aui/js/aui-experimental.min.js" type="text/javascript"></script> <script src="../../../../../aui/js/aui-soy.min.js" type="text/javascript"></script> <script src="../../../../../package-nodes-tree.js" type="text/javascript"></script> <script src="../../../../../clover-tree.js" type="text/javascript"></script> <script src="../../../../../clover.js" type="text/javascript"></script> <script src="../../../../../clover-descriptions.js" type="text/javascript"></script> <script src="../../../../../cloud.js" type="text/javascript"></script> <title>ABA Route Transit Number Validator 1.0.1-SNAPSHOT</title> </head> <body> <div id="page"> <header id="header" role="banner"> <nav class="aui-header <API key>" role="navigation"> <div class="aui-header-inner"> <div class="aui-header-primary"> <h1 id="logo" class="aui-header-logo <API key>"> <a href="http://openclover.org" title="Visit OpenClover home page"><span class="<API key>">OpenClover</span></a> </h1> </div> <div class="<API key>"> <ul class="aui-nav"> <li id="system-help-menu"> <a class="aui-nav-link" title="Open online documentation" target="_blank" href="http://openclover.org/documentation"> <span class="aui-icon aui-icon-small aui-iconfont-help">&#160;Help</span> </a> </li> </ul> </div> </div> </nav> </header> <div class="aui-page-panel"> <div class="<API key>"> <div class="aui-page-panel-nav <API key>"> <div class="<API key>" style="margin-bottom: 20px;"> <div class="<API key>"> <a href="http://cardatechnologies.com" target="_top"> <div class="aui-avatar aui-avatar-large aui-avatar-project"> <div class="aui-avatar-inner"> <img src="../../../../../img/clover_logo_large.png" alt="Clover icon"/> </div> </div> </a> </div> <div class="<API key>" > <h1> <a href="http://cardatechnologies.com" target="_top"> ABA Route Transit Number Validator 1.0.1-SNAPSHOT </a> </h1> </div> </div> <nav class="aui-navgroup <API key>"> <div class="aui-navgroup-inner"> <ul class="aui-nav"> <li class=""> <a href="../../../../../dashboard.html">Project overview</a> </li> </ul> <div class="aui-nav-heading <API key>"> <strong>Packages</strong> </div> <div class="aui-nav project-packages"> <form method="get" action="#" class="aui <API key>"> <input type="text" autocomplete="off" class="package-filter text" placeholder="Type to filter packages..." name="package-filter" id="package-filter" title="Start typing package name (or part of the name) to search through the tree. Use arrow keys and the Enter key to navigate."/> </form> <p class="<API key> hidden"> <small>No results found.</small> </p> <div class="<API key>" data-root-relative="../../../../../" data-package-name="com.cardatechnologies.utils.validators.abaroutevalidator"> <div class="<API key>"></div> <div class="<API key>"></div> </div> </div> </div> </nav> </div> <section class="<API key>"> <div class="<API key>"> <div class="<API key>"><ol class="aui-nav aui-nav-breadcrumbs"> <li><a href="../../../../../dashboard.html"> Project Clover database Sat Aug 7 2021 12:29:33 MDT</a></li> <li><a href="test-pkg-summary.html">Package com.cardatechnologies.utils.validators.abaroutevalidator</a></li> <li><a href="<API key>.html">Class <API key></a></li> </ol></div> <h1 class="aui-h2-clover"> Test <API key> </h1> <table class="aui"> <thead> <tr> <th>Test</th> <th><label title="The test result. Either a Pass, Fail or Error.">Status</label></th> <th><label title="When the test execution was started">Start time</label></th> <th><label title="The total time in seconds taken to run this test.">Time (seconds)</label></th> <th><label title="A failure or error message if the test is not successful.">Message</label></th> </tr> </thead> <tbody> <tr> <td> <a href="../../../../../com/cardatechnologies/utils/validators/abaroutevalidator/<API key>.html?line=15641#src-15641" ><API key></a> </td> <td> <span class="sortValue">1</span><span class="aui-lozenge aui-lozenge-success">PASS</span> </td> <td> 7 Aug 12:33:30 </td> <td> 0.0 </td> <td> <div></div> <div class="errorMessage"></div> </td> </tr> </tbody> </table> <div>&#160;</div> <table class="aui aui-table-sortable"> <thead> <tr> <th style="white-space:nowrap;"><label title="A class that was directly hit by this test.">Target Class</label></th> <th colspan="4"><label title="The percentage of coverage contributed by each single test.">Coverage contributed by</label> <API key></th> </tr> </thead> <tbody> <tr> <td> <span class="sortValue">com.cardatechnologies.utils.validators.abaroutevalidator.AbaRouteValidator</span> &#160;&#160;<a href="../../../../../com/cardatechnologies/utils/validators/abaroutevalidator/AbaRouteValidator.html?id=27318#AbaRouteValidator" title="AbaRouteValidator" name="sl-47">com.cardatechnologies.utils.validators.abaroutevalidator.AbaRouteValidator</a> </td> <td> <span class="sortValue">0.7352941</span>73.5% </td> <td class="align-middle" style="width: 100%" colspan="3"> <div> <div title="73.5% Covered" style="min-width:40px;" class="barNegative contribBarNegative contribBarNegative"><div class="barPositive contribBarPositive contribBarPositive" style="width:73.5%"></div></div></div> </td> </tr> </tbody> </table> </div> <!-- class="<API key>" --> <footer id="footer" role="contentinfo"> <section class="footer-body"> <ul> <li> Report generated by <a target="_new" href="http://openclover.org">OpenClover</a> v 4.4.1 on Sat Aug 7 2021 12:49:26 MDT using coverage data from Sat Aug 7 2021 12:47:23 MDT. </li> </ul> <ul> <li>OpenClover is free and open-source software. </li> </ul> </section> </footer> </section> <!-- class="<API key>" --> </div> <!-- class="<API key>" --> </div> <!-- class="aui-page-panel" --> </div> <!-- id="page" --> </body> </html>
package dao import ( "context" "testing" "github.com/smartystreets/goconvey/convey" ) func <API key>(t *testing.T) { convey.Convey("BusinessAllV2", t, func(convCtx convey.C) { var ( c = context.Background() ) convCtx.Convey("When everything goes positive", func(convCtx convey.C) { list, err := d.BusinessAllV2(c) convCtx.Convey("Then err should be nil.list should not be nil.", func(convCtx convey.C) { convCtx.So(err, convey.ShouldBeNil) convCtx.So(list, convey.ShouldNotBeNil) }) }) }) } func <API key>(t *testing.T) { convey.Convey("BusinessInfoV2", t, func(convCtx convey.C) { var ( c = context.Background() name = "dm" ) convCtx.Convey("When everything goes positive", func(convCtx convey.C) { b, err := d.BusinessInfoV2(c, name) convCtx.Convey("Then err should be nil.b should not be nil.", func(convCtx convey.C) { convCtx.So(err, convey.ShouldBeNil) convCtx.So(b, convey.ShouldNotBeNil) }) }) }) } //func TestDaoBusinessIns(t *testing.T) { // convey.Convey("BusinessIns", t, func(convCtx convey.C) { // var ( // c = context.Background() // pid = int64(0) // name = "" // description = "" // convCtx.Convey("When everything goes positive", func(convCtx convey.C) { // rows, err := d.BusinessIns(c, pid, name, description) // convCtx.Convey("Then err should be nil.rows should not be nil.", func(convCtx convey.C) { // convCtx.So(err, convey.ShouldBeNil) // convCtx.So(rows, convey.ShouldNotBeNil) //func <API key>(t *testing.T) { // convey.Convey("BusinessUpdate", t, func(convCtx convey.C) { // var ( // c = context.Background() // name = "" // field = "" // value = "" // convCtx.Convey("When everything goes positive", func(convCtx convey.C) { // rows, err := d.BusinessUpdate(c, name, field, value) // convCtx.Convey("Then err should be nil.rows should not be nil.", func(convCtx convey.C) { // convCtx.So(err, convey.ShouldBeNil) // convCtx.So(rows, convey.ShouldNotBeNil) func <API key>(t *testing.T) { convey.Convey("AssetDBTables", t, func(convCtx convey.C) { var ( c = context.Background() ) convCtx.Convey("When everything goes positive", func(convCtx convey.C) { list, err := d.AssetDBTables(c) convCtx.Convey("Then err should be nil.list should not be nil.", func(convCtx convey.C) { convCtx.So(err, convey.ShouldBeNil) convCtx.So(list, convey.ShouldNotBeNil) }) }) }) } //func TestDaoAssetDBIns(t *testing.T) { // convey.Convey("AssetDBIns", t, func(convCtx convey.C) { // var ( // c = context.Background() // name = "" // description = "" // dsn = "" // convCtx.Convey("When everything goes positive", func(convCtx convey.C) { // rows, err := d.AssetDBIns(c, name, description, dsn) // convCtx.Convey("Then err should be nil.rows should not be nil.", func(convCtx convey.C) { // convCtx.So(err, convey.ShouldBeNil) // convCtx.So(rows, convey.ShouldNotBeNil) //func <API key>(t *testing.T) { // convey.Convey("AssetTableIns", t, func(convCtx convey.C) { // var ( // c = context.Background() // name = "" // regex = "" // fields = "" // description = "" // convCtx.Convey("When everything goes positive", func(convCtx convey.C) { // rows, err := d.AssetTableIns(c, name, db, regex, fields, description) // convCtx.Convey("Then err should be nil.rows should not be nil.", func(convCtx convey.C) { // convCtx.So(err, convey.ShouldBeNil) // convCtx.So(rows, convey.ShouldNotBeNil) func TestDaoAsset(t *testing.T) { convey.Convey("Asset", t, func(convCtx convey.C) { var ( c = context.Background() name = "bilibili_article" ) convCtx.Convey("When everything goes positive", func(convCtx convey.C) { r, err := d.Asset(c, name) convCtx.Convey("Then err should be nil.r should not be nil.", func(convCtx convey.C) { convCtx.So(err, convey.ShouldBeNil) convCtx.So(r, convey.ShouldNotBeNil) }) }) }) }
using UnityEngine; namespace DefaultNamespace { public class <API key> : MonoBehaviour { public void Update() { int[,] test = new int[2,2]; test[0, 0] = 5; test[test[0,{caret} 1], test[0, test[0,1]]] = 5; } } }
package com.bzu.yhd.pocketcampus.bottomnav.user.view; import android.content.Context; import android.util.AttributeSet; import com.facebook.rebound.<API key>; import com.facebook.rebound.Spring; import com.facebook.rebound.SpringSystem; import de.hdodenhof.circleimageview.CircleImageView; public class AnimateImageView extends CircleImageView { private Spring springX, springY; private <API key> followerListenerX, followerListenerY; // viewviewendValue public AnimateImageView(Context context) { this(context, null); } public AnimateImageView(Context context, AttributeSet attrs) { this(context, attrs, 0); } public AnimateImageView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); SpringSystem mSpringSystem = SpringSystem.create(); springX = mSpringSystem.createSpring(); springY = mSpringSystem.createSpring(); springX.addListener(new <API key>() { @Override public void onSpringUpdate(Spring spring) { int xPos = (int) spring.getCurrentValue(); setScreenX(xPos); } }); springY.addListener(new <API key>() { @Override public void onSpringUpdate(Spring spring) { int yPos = (int) spring.getCurrentValue(); setScreenY(yPos); } }); followerListenerX = new <API key>() { @Override public void onSpringUpdate(Spring spring) { int xPos = (int) spring.getCurrentValue(); springX.setEndValue(xPos); } }; followerListenerY = new <API key>() { @Override public void onSpringUpdate(Spring spring) { int yPos = (int) spring.getCurrentValue(); springY.setEndValue(yPos); } }; } private void setScreenX(int screenX) { this.offsetLeftAndRight(screenX - getLeft()); } private void setScreenY(int screenY) { this.offsetTopAndBottom(screenY - getTop()); } public void animTo(int xPos, int yPos) { springX.setEndValue(xPos); springY.setEndValue(yPos); } /** * ImageView */ public void stopAnimation() { springX.setAtRest(); springY.setAtRest(); } /** * view */ public void onRelease(int xPos, int yPos) { setCurrentSpringPos(getLeft(), getTop()); animTo(xPos, yPos); } /** * spring */ public void setCurrentSpringPos(int xPos, int yPos) { springX.setCurrentValue(xPos); springY.setCurrentValue(yPos); } public Spring getSpringX() { return springX; } public Spring getSpringY() { return springY; } public <API key> <API key>() { return followerListenerX; } public <API key> <API key>() { return followerListenerY; } }
import Vue from 'vue' import { hasFetch, normalizeError, addLifecycleHook } from '../utils' const isSsrHydration = (vm) => vm.$vnode && vm.$vnode.elm && vm.$vnode.elm.dataset && vm.$vnode.elm.dataset.fetchKey const nuxtState = window.<%= globals.context %> export default { beforeCreate () { if (!hasFetch(this)) { return } this._fetchDelay = typeof this.$options.fetchDelay === 'number' ? this.$options.fetchDelay : 200 Vue.util.defineReactive(this, '$fetchState', { pending: false, error: null, timestamp: Date.now() }) this.$fetch = $fetch.bind(this) addLifecycleHook(this, 'created', created) addLifecycleHook(this, 'beforeMount', beforeMount) } } function beforeMount() { if (!this._hydrated) { return this.$fetch() } } function created() { if (!isSsrHydration(this)) { return } // Hydrate component this._hydrated = true this._fetchKey = +this.$vnode.elm.dataset.fetchKey const data = nuxtState.fetch[this._fetchKey] // If fetch error if (data && data._error) { this.$fetchState.error = data._error return } // Merge data for (const key in data) { Vue.set(this.$data, key, data[key]) } } async function $fetch() { this.$nuxt.nbFetching++ this.$fetchState.pending = true this.$fetchState.error = null this._hydrated = false let error = null const startTime = Date.now() try { await this.$options.fetch.call(this) } catch (err) { error = normalizeError(err) } const delayLeft = this._fetchDelay - (Date.now() - startTime) if (delayLeft > 0) { await new Promise(resolve => setTimeout(resolve, delayLeft)) } this.$fetchState.error = error this.$fetchState.pending = false this.$fetchState.timestamp = Date.now() this.$nextTick(() => this.$nuxt.nbFetching }
# AUTOGENERATED FILE FROM balenalib/zc702-zynq7-ubuntu:xenial-run ENV NODE_VERSION 14.18.3 ENV YARN_VERSION 1.22.4 RUN buildDeps='curl libatomic1' \ && set -x \ && for key in \ <API key> \ ; do \ gpg --keyserver pgp.mit.edu --recv-keys "$key" || \ gpg --keyserver keyserver.pgp.com --recv-keys "$key" || \ gpg --keyserver keyserver.ubuntu.com --recv-keys "$key" ; \ done \ && apt-get update && apt-get install -y $buildDeps --<API key> \
package com.qmx.wxmp.common.web; /** * UTF-8 charset MediaType. * * Jax-RSSpringMediaTypeUTF-8 * GoogleMediaTypetoString()Restfulannotation * * @author free lance */ public class MediaTypes { public static final String APPLICATION_XML = "application/xml"; public static final String <API key> = "application/xml; charset=UTF-8"; public static final String JSON = "application/json"; public static final String JSON_UTF_8 = "application/json; charset=UTF-8"; public static final String JAVASCRIPT = "application/javascript"; public static final String JAVASCRIPT_UTF_8 = "application/javascript; charset=UTF-8"; public static final String <API key> = "application/xhtml+xml"; public static final String <API key> = "application/xhtml+xml; charset=UTF-8"; public static final String TEXT_PLAIN = "text/plain"; public static final String TEXT_PLAIN_UTF_8 = "text/plain; charset=UTF-8"; public static final String TEXT_XML = "text/xml"; public static final String TEXT_XML_UTF_8 = "text/xml; charset=UTF-8"; public static final String TEXT_HTML = "text/html"; public static final String TEXT_HTML_UTF_8 = "text/html; charset=UTF-8"; }
<p> Even - {{ number }} </p>
<link rel="import" href="../../bower_components/polymer/polymer-element.html"> <dom-module id="balance-text-field"> <script> class BalanceTextField extends Vaadin.TextFieldElement { static get is() { return 'balance-text-field'; } static get properties() { return { max: Number, min: Number, message: { type: String, computed: '_computedMessage(errorMessage)', } } } _computedMessage(errorMessage) { return errorMessage; } checkValidity() { if (super.checkValidity()) { if (this.max && Number(this.value) > this.max) { this.errorMessage = ' You have insufficient Balance'; return false; } if(this.min && Number(this.value) < this.min){ this.errorMessage = ' must be bigger than ' + this.min; return false; } return true; } else { this.errorMessage = this.message; return false; } } } window.customElements.define(BalanceTextField.is, BalanceTextField); </script> </dom-module>
package cn.oeaom.CoolWeather; import android.content.Intent; import android.content.SharedPreferences; import android.graphics.Typeface; import android.media.Image; import android.os.Bundle; import android.preference.PreferenceManager; import android.support.design.widget.<API key>; import android.support.design.widget.Snackbar; import android.support.v4.view.GravityCompat; import android.support.v4.widget.DrawerLayout; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import java.io.IOException; import cn.oeaom.CoolWeather.GSON.Weather; import cn.oeaom.CoolWeather.Util.Utility; import okhttp3.Call; import okhttp3.Callback; import cn.oeaom.CoolWeather.Util.HttpUtil; import okhttp3.Response; public class WeatherActivity extends AppCompatActivity { private static final String TAG = "WeatherActivity"; private static final String <TwitterConsumerkey>"; public DrawerLayout drawerLayout; //public TextView tvTitle; // * private TextView weatherTime; private TextView weatherDegree; private TextView measure2; private TextView weatherPlace; private TextView weatherType; private String mWeatherId; private ImageView weatherStat; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_weather); //Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); //setSupportActionBar(toolbar); // <API key> fab = (<API key>) findViewById(R.id.fab); // fab.setOnClickListener(new View.OnClickListener() { // @Override // public void onClick(View view) { // Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG) // .setAction("Action", null).show(); Typeface fontFace = Typeface.createFromAsset(getAssets(), "fonts/AndroidClock.ttf"); // true type font(ttf) // ( Droid Sans) // android, weatherTime = (TextView)findViewById(R.id.weather_info_time); weatherTime.setTypeface(fontFace); weatherDegree = (TextView)findViewById(R.id.degree_value); weatherDegree.setTypeface(fontFace); TextView measure = (TextView)findViewById(R.id.degree_measure); // measure.setTypeface(fontFace); measure2 = (TextView)findViewById(R.id.degree_measure2); //measure2.setTypeface(fontFace); weatherPlace = (TextView)findViewById(R.id.weather_info_place); //weatherPlace.setTypeface(fontFace); weatherType = (TextView)findViewById(R.id.weather_info_text); //weatherType.setTypeface(fontFace); weatherStat = (ImageView)findViewById(R.id.weatherIcon); // TextView weatherInfo = (TextView)findViewById(R.id.weather_info_text); // weatherInfo.setTypeface(fontFace); //text.setTextSize(50); Intent intent=getIntent(); //IntentExtra String weatherId=intent.getStringExtra("weather_id"); String CountryName = intent.getStringExtra("CountryName"); // tvTitle = (TextView)findViewById(R.id.title_text_weather); // //tvTitle.setText(weatherId); // tvTitle.setText(CountryName); // // tvTitle.setTextSize(60); // tvTitle.setTypeface(fontFace); drawerLayout = (DrawerLayout)findViewById(R.id.drawer_layout); Button btnBack = (Button)findViewById(R.id.btn_home); btnBack.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { //Intent intent = new Intent(WeatherActivity.this,MainActivity.class); //startActivity(intent); // WeatherActivity.this.finish(); drawerLayout.openDrawer(GravityCompat.START); Log.v(TAG,"Clicked nav btn"); } }); SharedPreferences prefs = PreferenceManager.<API key>(this); String weatherString = prefs.getString("weather", null); if (weatherString != null) { Weather weather = Utility.<API key>(weatherString); mWeatherId = weather.basic.weatherId; showWeatherInfo(weather); } else { mWeatherId = getIntent().getStringExtra("weather_id"); // weatherLayout.setVisibility(View.INVISIBLE); requestWeather(mWeatherId); } // swipeRefresh.<API key>(new SwipeRefreshLayout.OnRefreshListener() { // @Override // public void onRefresh() { // requestWeather(mWeatherId); } // public void requestWeather(final String weatherId){ // tvTitle.setText(weatherId); public void requestWeather(final String weatherId) { String weatherUrl = "http://guolin.tech/api/weather?cityid=" + weatherId + "&key="+API_KEY; HttpUtil.sendOkHttpRequest(weatherUrl, new Callback() { @Override public void onResponse(Call call, Response response) throws IOException { final String responseText = response.body().string(); Log.v(TAG,"======================================================================="); Log.v(TAG,responseText); Log.v(TAG,"======================================================================="); final Weather weather = Utility.<API key>(responseText); runOnUiThread(new Runnable() { @Override public void run() { if (weather != null && "ok".equals(weather.status)) { SharedPreferences.Editor editor = PreferenceManager.<API key>(WeatherActivity.this).edit(); editor.putString("weather", responseText); editor.apply(); //mWeatherId = weather.basic.weatherId; showWeatherInfo(weather); } else { Toast.makeText(WeatherActivity.this, "", Toast.LENGTH_SHORT).show(); } //swipeRefresh.setRefreshing(false); } }); } @Override public void onFailure(Call call, IOException e) { e.printStackTrace(); runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(WeatherActivity.this, "", Toast.LENGTH_SHORT).show(); //swipeRefresh.setRefreshing(false); } }); } }); //loadBingPic(); } private int <API key>(String weatherName) { switch(weatherName) { case "":return R.drawable.a044; case "":return R.drawable.a045; case "":return R.drawable.a046; case "":return R.drawable.a047; case "":return R.drawable.a048; case "":return R.drawable.a049; case "":return R.drawable.a050; case "":return R.drawable.a000; case "":return R.drawable.a001; case "":return R.drawable.a002; case "":return R.drawable.a003; case "":return R.drawable.a003; case "":return R.drawable.a004; case "":return R.drawable.a005; case "":return R.drawable.a006; case "":return R.drawable.a007; case "":return R.drawable.a008; case "":return R.drawable.a009; case "":return R.drawable.a012; case "":return R.drawable.a013; case "":return R.drawable.a014; case "":return R.drawable.a015; case "":return R.drawable.a016; case "":return R.drawable.a017; case "":return R.drawable.a018; case "":return R.drawable.a019; case "":return R.drawable.a020; case "":return R.drawable.a021; case "":return R.drawable.a021; case "":return R.drawable.a022; case "":return R.drawable.a023; case "":return R.drawable.a024; case "":return R.drawable.a025; case "":return R.drawable.a026; case "":return R.drawable.a027; case "":return R.drawable.a028; case "":return R.drawable.a029; case "":return R.drawable.a030; case "":return R.drawable.a031; case "":return R.drawable.a032; case "":return R.drawable.a033; case "":return R.drawable.a034; case "":return R.drawable.a035; case "":return R.drawable.a036; case "":return R.drawable.a037; case "":return R.drawable.a038; case "":return R.drawable.a039; case "":return R.drawable.a041; case "":return R.drawable.a042; case "":return R.drawable.a040; case "":return R.drawable.a043; default:{ break; } } return -1; } private void showWeatherInfo(Weather weather) { String cityName = weather.basic.cityName; String updateTime = weather.basic.update.updateTime.split(" ")[1]; String degree = weather.now.temperature; String weatherInfo = weather.now.more.info; weatherPlace.setText(cityName); weatherTime.setText(updateTime); weatherDegree.setText(degree); weatherType.setText(weatherInfo); weatherStat.setImageResource(<API key>(weatherInfo)); // forecastLayout.removeAllViews(); // for (Forecast forecast : weather.forecastList) { // View view = LayoutInflater.from(this).inflate(R.layout.forecast_item, forecastLayout, false); // TextView dateText = (TextView) view.findViewById(R.id.date_text); // TextView infoText = (TextView) view.findViewById(R.id.info_text); // TextView maxText = (TextView) view.findViewById(R.id.max_text); // TextView minText = (TextView) view.findViewById(R.id.min_text); // dateText.setText(forecast.date); // infoText.setText(forecast.more.info); // maxText.setText(forecast.temperature.max); // minText.setText(forecast.temperature.min); // forecastLayout.addView(view); // if (weather.aqi != null) { // aqiText.setText(weather.aqi.city.aqi); // pm25Text.setText(weather.aqi.city.pm25); // String comfort = "" + weather.suggestion.comfort.info; // String carWash = "" + weather.suggestion.carWash.info; // String sport = "" + weather.suggestion.sport.info; // comfortText.setText(comfort); // carWashText.setText(carWash); // sportText.setText(sport); // weatherLayout.setVisibility(View.VISIBLE); // Intent intent = new Intent(this, AutoUpdateService.class); // startService(intent); } }
layout: "fluid/docs_base" version: "3.9.2" versionHref: "/docs/v3/3.9.2" path: "" category: api id: "toastcontroller" title: "ToastController" header_sub_title: "Ionic API Documentation" doc: "ToastController" docType: "class" show_preview_device: true preview_device_url: "/docs/v3/demos/src/toast/www/" angular_controller: APIDemoCtrl <h1 class="api-title"> <a class="anchor" name="toast-controller" href="#toast-controller"></a> ToastController </h1> <a class="improve-v2-docs" href="http://github.com/ionic-team/ionic/edit/v3/src/components/toast/toast-controller.ts Improve this doc </a> <p>A Toast is a subtle notification commonly used in modern applications. It can be used to provide feedback about an operation or to display a system message. The toast appears on top of the app&#39;s content, and can be dismissed by the app to resume user interaction with the app.</p> <h3><a class="anchor" name="creating" href="#creating">Creating</a></h3> <p>All of the toast options should be passed in the first argument of the create method: <code>create(opts)</code>. The message to display should be passed in the <code>message</code> property. The <code>showCloseButton</code> option can be set to true in order to display a close button on the toast. See the <a href="#create">create</a> method below for all available options.</p> <h3><a class="anchor" name="positioning" href="#positioning">Positioning</a></h3> <p>Toasts can be positioned at the top, bottom or middle of the view port. The position can be passed to the <code>Toast.create(opts)</code> method. The position option is a string, and the values accepted are <code>top</code>, <code>bottom</code> and <code>middle</code>. If the position is not specified, the toast will be displayed at the bottom of the view port.</p> <h3><a class="anchor" name="dismissing" href="#dismissing">Dismissing</a></h3> <p>The toast can be dismissed automatically after a specific amount of time by passing the number of milliseconds to display it in the <code>duration</code> of the toast options. If <code>showCloseButton</code> is set to true, then the close button will dismiss the toast. To dismiss the toast after creation, call the <code>dismiss()</code> method on the Toast instance. The <code>onDidDismiss</code> function can be called to perform an action after the toast is dismissed.</p> <!-- @usage tag --> <h2><a class="anchor" name="usage" href="#usage">Usage</a></h2> <pre><code class="lang-ts">import { ToastController } from &#39;ionic-angular&#39;; constructor(private toastCtrl: ToastController) { } presentToast() { let toast = this.toastCtrl.create({ message: &#39;User was added successfully&#39;, duration: 3000, position: &#39;top&#39; }); toast.onDidDismiss(() =&gt; { console.log(&#39;Dismissed toast&#39;); }); toast.present(); } </code></pre> <!-- @property tags --> <!-- instance methods on the class --> <h2><a class="anchor" name="instance-members" href="#instance-members">Instance Members</a></h2> <div id="config"></div> <h3> <a class="anchor" name="config" href="#config"> <code>config</code> </a> </h3> <div id="create"></div> <h3> <a class="anchor" name="create" href="#create"> <code>create(opts)</code> </a> </h3> Create a new toast component. See options below <table class="table param-table" style="margin:0;"> <thead> <tr> <th>Param</th> <th>Type</th> <th>Details</th> </tr> </thead> <tbody> <tr> <td> opts </td> <td> <code>ToastOptions</code> </td> <td> <p>Toast options. See the below table for available options.</p> </td> </tr> </tbody> </table> <h2><a class="anchor" name="advanced" href="#advanced">Advanced</a></h2> <table> <thead> <tr> <th>Property</th> <th>Type</th> <th>Default</th> <th>Description</th> </tr> </thead> <tbody> <tr> <td>message</td> <td><code>string</code></td> <td>-</td> <td>The message for the toast. Long strings will wrap and the toast container will expand.</td> </tr> <tr> <td>duration</td> <td><code>number</code></td> <td>-</td> <td>How many milliseconds to wait before hiding the toast. By default, it will show until <code>dismiss()</code> is called.</td> </tr> <tr> <td>position</td> <td><code>string</code></td> <td>&quot;bottom&quot;</td> <td>The position of the toast on the screen. Accepted values: &quot;top&quot;, &quot;middle&quot;, &quot;bottom&quot;.</td> </tr> <tr> <td>cssClass</td> <td><code>string</code></td> <td>-</td> <td>Additional classes for custom styles, separated by spaces.</td> </tr> <tr> <td>showCloseButton</td> <td><code>boolean</code></td> <td>false</td> <td>Whether or not to show a button to close the toast.</td> </tr> <tr> <td>closeButtonText</td> <td><code>string</code></td> <td>&quot;Close&quot;</td> <td>Text to display in the close button.</td> </tr> <tr> <td>dismissOnPageChange</td> <td><code>boolean</code></td> <td>false</td> <td>Whether to dismiss the toast when navigating to a new page.</td> </tr> </tbody> </table> <h2 id="<API key>"><a class="anchor" name="sass-variables" href="#sass-variables">Sass Variables</a></h2> <div id="sass-variables" ng-controller="SassToggleCtrl"> <div class="<API key>"> <a ng-init="setSassPlatform('base')" ng-class="{ active: active === 'base' }" ng-click="setSassPlatform('base')" >All</a> <a ng-class="{ active: active === 'ios' }" ng-click="setSassPlatform('ios')">iOS</a> <a ng-class="{ active: active === 'md' }" ng-click="setSassPlatform('md')">Material Design</a> <a ng-class="{ active: active === 'wp' }" ng-click="setSassPlatform('wp')">Windows Platform</a> </div> <table ng-show="active === 'base'" id="sass-base" class="table param-table" style="margin:0;"> <thead> <tr> <th>Property</th> <th>Default</th> <th>Description</th> </tr> </thead> <tbody> <tr> <td><code>$toast-width</code></td> <td><code>100%</code></td> <td><p>Width of the toast</p> </td> </tr> <tr> <td><code>$toast-max-width</code></td> <td><code>700px</code></td> <td><p>Max width of the toast</p> </td> </tr> </tbody> </table> <table ng-show="active === 'ios'" id="sass-ios" class="table param-table" style="margin:0;"> <thead> <tr> <th>Property</th> <th>Default</th> <th>Description</th> </tr> </thead> <tbody> <tr> <td><code>$<API key></code></td> <td><code>rgba(0, 0, 0, .9)</code></td> <td><p>Background of the toast wrapper</p> </td> </tr> <tr> <td><code>$<API key></code></td> <td><code>.65rem</code></td> <td><p>Border radius of the toast wrapper</p> </td> </tr> <tr> <td><code>$<API key></code></td> <td><code>#fff</code></td> <td><p>Color of the toast title</p> </td> </tr> <tr> <td><code>$<API key></code></td> <td><code>1.4rem</code></td> <td><p>Font size of the toast title</p> </td> </tr> <tr> <td><code>$<API key></code></td> <td><code>1.5rem</code></td> <td><p>Padding top of the toast title</p> </td> </tr> <tr> <td><code>$<API key></code></td> <td><code>$<API key></code></td> <td><p>Padding end of the toast title</p> </td> </tr> <tr> <td><code>$<API key></code></td> <td><code>$<API key></code></td> <td><p>Padding bottom of the toast title</p> </td> </tr> <tr> <td><code>$<API key></code></td> <td><code>$<API key></code></td> <td><p>Padding start of the toast title</p> </td> </tr> </tbody> </table> <table ng-show="active === 'md'" id="sass-md" class="table param-table" style="margin:0;"> <thead> <tr> <th>Property</th> <th>Default</th> <th>Description</th> </tr> </thead> <tbody> <tr> <td><code>$toast-md-background</code></td> <td><code>#333</code></td> <td><p>Background of the toast wrapper</p> </td> </tr> <tr> <td><code>$<API key></code></td> <td><code>#fff</code></td> <td><p>Color of the toast title</p> </td> </tr> <tr> <td><code>$<API key></code></td> <td><code>1.5rem</code></td> <td><p>Font size of the toast title</p> </td> </tr> <tr> <td><code>$<API key></code></td> <td><code>19px</code></td> <td><p>Padding top of the toast title</p> </td> </tr> <tr> <td><code>$<API key></code></td> <td><code>16px</code></td> <td><p>Padding end of the toast title</p> </td> </tr> <tr> <td><code>$<API key></code></td> <td><code>17px</code></td> <td><p>Padding bottom of the toast title</p> </td> </tr> <tr> <td><code>$<API key></code></td> <td><code>$<API key></code></td> <td><p>Padding start of the toast title</p> </td> </tr> </tbody> </table> <table ng-show="active === 'wp'" id="sass-wp" class="table param-table" style="margin:0;"> <thead> <tr> <th>Property</th> <th>Default</th> <th>Description</th> </tr> </thead> <tbody> <tr> <td><code>$toast-wp-background</code></td> <td><code>rgba(0, 0, 0, 1)</code></td> <td><p>Background of the toast wrapper</p> </td> </tr> <tr> <td><code>$<API key></code></td> <td><code>0</code></td> <td><p>Border radius of the toast wrapper</p> </td> </tr> <tr> <td><code>$<API key></code></td> <td><code>#fff</code></td> <td><p>Color of the toast button</p> </td> </tr> <tr> <td><code>$<API key></code></td> <td><code>#fff</code></td> <td><p>Color of the toast title</p> </td> </tr> <tr> <td><code>$<API key></code></td> <td><code>1.4rem</code></td> <td><p>Font size of the toast title</p> </td> </tr> <tr> <td><code>$<API key></code></td> <td><code>1.5rem</code></td> <td><p>Padding top of the toast title</p> </td> </tr> <tr> <td><code>$<API key></code></td> <td><code>$<API key></code></td> <td><p>Padding end of the toast title</p> </td> </tr> <tr> <td><code>$<API key></code></td> <td><code>$<API key></code></td> <td><p>Padding bottom of the toast title</p> </td> </tr> <tr> <td><code>$<API key></code></td> <td><code>$<API key></code></td> <td><p>Padding start of the toast title</p> </td> </tr> </tbody> </table> </div> <!-- related link --><!-- end content block --> <!-- end body block -->
#include <Wire.h> #include "lis331dlh.h" #include "l3g4200d.h" #include "lis3mdl.h" #include "LPS331.h" #include "MadgwickAHRS.h" // Accelerometer #define ACCEL_ADDRESS_V1 <API key> #define ACCEL_ADDRESS_V2 <API key> // Gyroscope #define GYRO_ADDRESS_V1 <API key> #define GYRO_ADDRESS_V2 <API key> // Compass #define COMPASS_ADDRESS_V1 LIS3MDL_TWI_ADDRESS #define COMPASS_ADDRESS_V2 <API key> // Barometer #define BARO_ADDRESS_V1 <API key> #define BARO_ADDRESS_V2 <API key> class Accelerometer : public LIS331DLH_TWI { public: Accelerometer(uint8_t addr = ACCEL_ADDRESS_V1) : LIS331DLH_TWI(addr) {} }; class Gyroscope : public L3G4200D_TWI { public: Gyroscope(uint8_t addr = GYRO_ADDRESS_V1) : L3G4200D_TWI(addr) {} }; class Compass : public LIS3MDL_TWI { public: Compass(uint8_t addr = COMPASS_ADDRESS_V1) : LIS3MDL_TWI(addr) {} }; class Barometer : public LPS331 { public: Barometer(uint8_t addr = BARO_ADDRESS_V1) : LPS331(addr) {} };
# -*- coding:utf-8 -*- __author__ = 'q00222219@huawei' import time from heat.openstack.common import log as logging import heat.engine.resources.cloudmanager.commonutils as commonutils import heat.engine.resources.cloudmanager.constant as constant import heat.engine.resources.cloudmanager.exception as exception import pdb LOG = logging.getLogger(__name__) class CascadedConfiger(object): def __init__(self, public_ip_api, api_ip, domain, user, password, cascading_domain, cascading_api_ip, cascaded_domain, cascaded_api_ip, <API key>): self.public_ip_api = public_ip_api self.api_ip = api_ip self.domain = domain self.user = user self.password = password self.cascading_domain = cascading_domain self.cascading_api_ip = cascading_api_ip self.cascaded_domain = cascaded_domain self.cascaded_ip = cascaded_api_ip self.gateway = <API key> def do_config(self): start_time = time.time() #pdb.set_trace() LOG.info("start config cascaded, cascaded: %s" % self.domain) # wait cascaded tunnel can visit commonutils.check_host_status(host=self.public_ip_api, user=self.user, password=self.password, retry_time=500, interval=1) # config cascaded host self._config_az_cascaded() cost_time = time.time() - start_time LOG.info("first config success, cascaded: %s, cost time: %d" % (self.domain, cost_time)) # check config result for i in range(3): try: # check 90s commonutils.check_host_status( host=self.public_ip_api, user=constant.VcloudConstant.ROOT, password=constant.VcloudConstant.ROOT_PWD, retry_time=15, interval=1) LOG.info("cascaded api is ready..") break except exception.<API key>: if i == 2: LOG.error("check cascaded api failed ...") break LOG.error("check cascaded api error, " "retry config cascaded ...") self._config_az_cascaded() cost_time = time.time() - start_time LOG.info("config cascaded success, cascaded: %s, cost_time: %d" % (self.domain, cost_time)) def _config_az_cascaded(self): LOG.info("start config cascaded host, host: %s" % self.api_ip) # modify dns server address address = "/%(cascading_domain)s/%(cascading_ip)s,/%(cascaded_domain)s/%(cascaded_ip)s" \ % {"cascading_domain": self.cascading_domain, "cascading_ip": self.cascading_api_ip, "cascaded_domain":self.cascaded_domain, "cascaded_ip":self.cascaded_ip} for i in range(30): try: commonutils.<API key>( host=self.public_ip_api, user=self.user, password=self.password, cmd='cd %(dir)s; source /root/adminrc; sh %(script)s replace %(address)s' % {"dir": constant.PublicConstant.SCRIPTS_DIR, "script": constant.PublicConstant. <API key>, "address": address}) break except exception.SSHCommandFailure as e: LOG.error("modify cascaded dns address error, cascaded: " "%s, error: %s" % (self.domain, e.format_message())) time.sleep(1) LOG.info( "config cascaded dns address success, cascaded: %s" % self.public_ip_api) return True
#ifdef WINDOWS_PLATFORM #include "WindowsInputService.hpp" #include "<API key>.hpp" #include "<API key>.hpp" namespace MPACK { namespace Input { WindowsInputService::WindowsInputService() { m_pMouse = new <API key>; m_pKeyboard = new <API key>; Reset(); } WindowsInputService::~WindowsInputService() { } void WindowsInputService::Update() { m_pMouse->Update(); m_pKeyboard->Update(); } void WindowsInputService::Reset() { m_pMouse->Reset(); m_pKeyboard->Reset(); } MouseInterface* WindowsInputService::GetMouse() const { return m_pMouse; } KeyboardInterface* WindowsInputService::GetKeyboard() const { return m_pKeyboard; } } } #endif
namespace <API key>.WPFControls.FilterTree { <summary> Arguments for a drag and drop operation in the <see cref="XamlFilterTree"/>. </summary> public class <API key> { <summary> Initialises a new instance of the <API key> class. </summary> <param name="dragItem">The item being dragged.</param> <param name="dropTarget">The target where the dragged item will be dropped.</param> public <API key>(object dragItem, object dropTarget) { DragItem = dragItem; DropTarget = dropTarget; } <summary> Gets the object being dragged. </summary> public object DragItem { get; private set; } <summary> Gets the drop target for the object being dragged. </summary> public object DropTarget { get; private set; } } }
package com.structurizr.view; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.<API key>; import com.structurizr.model.*; import java.util.HashSet; import java.util.LinkedHashSet; import java.util.Set; import java.util.stream.Collectors; @<API key>(ignoreUnknown=true) public abstract class View implements Comparable<View> { private SoftwareSystem softwareSystem; private String softwareSystemId; private String description = ""; private PaperSize paperSize = PaperSize.A4_Portrait; private Set<ElementView> elementViews = new LinkedHashSet<>(); View() { } public View(SoftwareSystem softwareSystem) { this.softwareSystem = softwareSystem; } @JsonIgnore public Model getModel() { return softwareSystem.getModel(); } @JsonIgnore public SoftwareSystem getSoftwareSystem() { return softwareSystem; } public void setSoftwareSystem(SoftwareSystem softwareSystem) { this.softwareSystem = softwareSystem; } public String getSoftwareSystemId() { if (this.softwareSystem != null) { return this.softwareSystem.getId(); } else { return this.softwareSystemId; } } void setSoftwareSystemId(String softwareSystemId) { this.softwareSystemId = softwareSystemId; } public abstract ViewType getType(); public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public PaperSize getPaperSize() { return paperSize; } public void setPaperSize(PaperSize paperSize) { this.paperSize = paperSize; } /** * Adds all software systems in the model to this view. */ public void <API key>() { getModel().getSoftwareSystems().forEach(this::addElement); } /** * Adds the given software system to this view. * * @param softwareSystem the SoftwareSystem to add */ public void addSoftwareSystem(SoftwareSystem softwareSystem) { addElement(softwareSystem); } /** * Adds all software systems in the model to this view. */ public void addAllPeople() { getModel().getPeople().forEach(this::addElement); } /** * Adds the given person to this view. * * @param person the Person to add */ public void addPerson(Person person) { addElement(person); } protected void addElement(Element element) { if (softwareSystem.getModel().contains(element)) { elementViews.add(new ElementView(element)); } } protected void removeElement(Element element) { ElementView elementView = new ElementView(element); elementViews.remove(elementView); } /** * Gets the set of elements in this view. * * @return a Set of ElementView objects */ public Set<ElementView> getElements() { return elementViews; } public Set<RelationshipView> getRelationships() { Set<Relationship> relationships = new HashSet<>(); Set<Element> elements = getElements().stream() .map(ElementView::getElement) .collect(Collectors.toSet()); elements.forEach(b -> relationships.addAll(b.getRelationships())); return relationships.stream() .filter(r -> elements.contains(r.getSource()) && elements.contains(r.getDestination())) .map(RelationshipView::new) .collect(Collectors.toSet()); } public void setRelationships(Set<RelationshipView> relationships) { // do nothing ... this are determined automatically } /** * Removes all elements that have no relationships * to other elements in this view. */ public void <API key>() { Set<RelationshipView> relationships = getRelationships(); Set<String> elementIds = new HashSet<>(); relationships.forEach(rv -> elementIds.add(rv.getRelationship().getSourceId())); relationships.forEach(rv -> elementIds.add(rv.getRelationship().getDestinationId())); elementViews.removeIf(ev -> !elementIds.contains(ev.getId())); } public void <API key>(Element element) { Set<String> elementIdsToShow = new HashSet<>(); findElementsToShow(element, elementIdsToShow, 1); elementViews.removeIf(ev -> !elementIdsToShow.contains(ev.getId())); } private void findElementsToShow(Element element, Set<String> elementIds, int depth) { if (elementViews.contains(new ElementView(element))) { elementIds.add(element.getId()); if (depth < 100) { element.getRelationships().forEach(r -> findElementsToShow(r.getDestination(), elementIds, depth + 1)); } } } public abstract String getName(); @Override public int compareTo(View view) { return getTitle().compareTo(view.getTitle()); } private String getTitle() { return getName() + " - " + getDescription(); } ElementView findElementView(Element element) { for (ElementView elementView : getElements()) { if (elementView.getElement().equals(element)) { return elementView; } } return null; } public void <API key>(View source) { this.setPaperSize(source.getPaperSize()); for (ElementView sourceElementView : source.getElements()) { ElementView <API key> = findElementView(sourceElementView.getElement()); if (<API key> != null) { <API key>.<API key>(sourceElementView); } } } }
// <auto-generated/> #nullable disable using System.Text.Json; using Azure.Core; namespace Azure.Management.Network.Models { internal partial class ErrorDetails { internal static ErrorDetails <API key>(JsonElement element) { string code = default; string target = default; string message = default; foreach (var property in element.EnumerateObject()) { if (property.NameEquals("code")) { if (property.Value.ValueKind == JsonValueKind.Null) { continue; } code = property.Value.GetString(); continue; } if (property.NameEquals("target")) { if (property.Value.ValueKind == JsonValueKind.Null) { continue; } target = property.Value.GetString(); continue; } if (property.NameEquals("message")) { if (property.Value.ValueKind == JsonValueKind.Null) { continue; } message = property.Value.GetString(); continue; } } return new ErrorDetails(code, target, message); } } }
package io.vertx.ext.consul; import io.vertx.codegen.annotations.DataObject; import io.vertx.core.json.JsonObject; import java.util.List; @DataObject(generateConverter = true) public class Coordinate { private String node; private float adj; private float err; private float height; private List<Float> vec; /** * Default constructor */ public Coordinate() {} /** * Copy constructor * * @param coordinate the one to copy */ public Coordinate(Coordinate coordinate) { this.node = coordinate.node; this.adj = coordinate.adj; this.err = coordinate.err; this.height = coordinate.height; this.vec = coordinate.vec; } /** * Constructor from JSON * * @param coordinate the JSON */ public Coordinate(JsonObject coordinate) { CoordinateConverter.fromJson(coordinate, this); } /** * Convert to JSON * * @return the JSON */ public JsonObject toJson() { JsonObject jsonObject = new JsonObject(); CoordinateConverter.toJson(this, jsonObject); return jsonObject; } /** * Get name of node * * @return name of node */ public String getNode() { return node; } /** * Get adjustment * * @return adjustment */ public float getAdj() { return adj; } /** * Get error * * @return error */ public float getErr() { return err; } /** * Get height * * @return height */ public float getHeight() { return height; } /** * Get vector * * @return vector */ public List<Float> getVec() { return vec; } /** * Set name of node * * @param node name of node * @return reference to this, for fluency */ public Coordinate setNode(String node) { this.node = node; return this; } /** * Set adjustment * * @param adj adjustment * @return reference to this, for fluency */ public Coordinate setAdj(float adj) { this.adj = adj; return this; } /** * Set error * * @param err error * @return reference to this, for fluency */ public Coordinate setErr(float err) { this.err = err; return this; } /** * Set height * * @param height height * @return reference to this, for fluency */ public Coordinate setHeight(float height) { this.height = height; return this; } /** * Set vector * * @param vec vector * @return reference to this, for fluency */ public Coordinate setVec(List<Float> vec) { this.vec = vec; return this; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Coordinate that = (Coordinate) o; if (Float.compare(that.adj, adj) != 0) return false; if (Float.compare(that.err, err) != 0) return false; if (Float.compare(that.height, height) != 0) return false; if (node != null ? !node.equals(that.node) : that.node != null) return false; return vec != null ? vec.equals(that.vec) : that.vec == null; } @Override public int hashCode() { int result = node != null ? node.hashCode() : 0; result = 31 * result + (adj != +0.0f ? Float.floatToIntBits(adj) : 0); result = 31 * result + (err != +0.0f ? Float.floatToIntBits(err) : 0); result = 31 * result + (height != +0.0f ? Float.floatToIntBits(height) : 0); result = 31 * result + (vec != null ? vec.hashCode() : 0); return result; } }
import { Component, Input, EventEmitter, SimpleChanges, OnChanges } from '@angular/core'; import { ToasterService } from 'angular2-toaster'; import { TranslateService } from 'ng2-translate'; import { Notification } from '../notification.model'; import { NotificationService } from '../notification.service'; import { PaginationComponent } from '../../shared/pagination/pagination.component'; @Component({ moduleId: module.id, selector: '<API key>', templateUrl: 'notifications-list.component.html', styleUrls: ['notifications-list.component.css'] }) export class <API key> { @Input() notifications: Notification[]; // @Input() selectedStatus: String; // @Input() <API key>: String; translatedResponse: any; // pagination parameters currentPage = 1; pageSize = 10; totalItems: number; // will contain the notification satisfying the selected status and type <API key>: Notification[] = []; constructor(private notificationService: NotificationService, private toasterService: ToasterService, private translateService: TranslateService) {} private markAsRead(notificationId: number) { this.notificationService.<API key>(notificationId) .then( (response: any) => { let readNotification = this.notifications.filter( function (notification) { return notification.id === notificationId; } )[0]; readNotification.read = true; // notify change to the service which notifies the toolbar this.notificationService.<API key>(1); } ).catch( (error: any) => { this.toasterService.pop('error', this.getTranslatedString('Could not mark notification as read')); } ); } getTranslatedString(data: any) { this.translateService.get(data).subscribe( (value: any) => { this.translatedResponse = value; } ); return this.translatedResponse; } getPage(page: number) { this.currentPage = page; } }
package org.jboss.resteasy.spi; import org.jboss.resteasy.specimpl.MultivaluedMapImpl; import org.jboss.resteasy.specimpl.PathSegmentImpl; import org.jboss.resteasy.specimpl.ResteasyUriBuilder; import org.jboss.resteasy.util.Encode; import javax.ws.rs.core.MultivaluedMap; import javax.ws.rs.core.PathSegment; import javax.ws.rs.core.UriBuilder; import javax.ws.rs.core.UriInfo; import java.io.<API key>; import java.net.URI; import java.net.URLDecoder; import java.util.ArrayList; import java.util.List; /** * UriInfo implementation with some added extra methods to help process requests * * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a> * @version $Revision: 1 $ */ public class ResteasyUriInfo implements UriInfo { private String path; private String encodedPath; private String matchingPath; private MultivaluedMap<String, String> queryParameters; private MultivaluedMap<String, String> <API key>; private MultivaluedMap<String, String> pathParameters; private MultivaluedMap<String, String> <API key>; private MultivaluedMap<String, PathSegment[]> <API key>; private MultivaluedMap<String, PathSegment[]> <API key>; private List<PathSegment> pathSegments; private List<PathSegment> encodedPathSegments; private URI absolutePath; private URI requestURI; private URI baseURI; private List<String> matchedUris; private List<String> encodedMatchedUris; private List<String> encodedMatchedPaths = new ArrayList<String>(); private List<Object> ancestors; public ResteasyUriInfo(URI base, URI relative) { String b = base.toString(); if (!b.endsWith("/")) b += "/"; String r = relative.getRawPath(); if (r.startsWith("/")) { encodedPath = r; path = relative.getPath(); } else { encodedPath = "/" + r; path = "/" + relative.getPath(); } requestURI = UriBuilder.fromUri(base).path(relative.getRawPath()).replaceQuery(relative.getRawQuery()).build(); baseURI = base; encodedPathSegments = PathSegmentImpl.parseSegments(encodedPath, false); this.pathSegments = new ArrayList<PathSegment>(encodedPathSegments.size()); for (PathSegment segment : encodedPathSegments) { pathSegments.add(new PathSegmentImpl(((PathSegmentImpl) segment).getOriginal(), true)); } extractParameters(requestURI.getRawQuery()); extractMatchingPath(encodedPathSegments); absolutePath = UriBuilder.fromUri(requestURI).replaceQuery(null).build(); } public ResteasyUriInfo(URI requestURI) { String r = requestURI.getRawPath(); if (r.startsWith("/")) { encodedPath = r; path = requestURI.getPath(); } else { encodedPath = "/" + r; path = "/" + requestURI.getPath(); } this.requestURI = requestURI; baseURI = UriBuilder.fromUri(requestURI).replacePath("").build(); encodedPathSegments = PathSegmentImpl.parseSegments(encodedPath, false); this.pathSegments = new ArrayList<PathSegment>(encodedPathSegments.size()); for (PathSegment segment : encodedPathSegments) { pathSegments.add(new PathSegmentImpl(((PathSegmentImpl) segment).getOriginal(), true)); } extractParameters(requestURI.getRawQuery()); extractMatchingPath(encodedPathSegments); absolutePath = UriBuilder.fromUri(requestURI).replaceQuery(null).build(); } /** * matching path without matrix parameters * * @param encodedPathSegments */ protected void extractMatchingPath(List<PathSegment> encodedPathSegments) { StringBuilder preprocessedPath = new StringBuilder(); for (PathSegment pathSegment : encodedPathSegments) { preprocessedPath.append("/").append(pathSegment.getPath()); } matchingPath = preprocessedPath.toString(); } /** * Encoded path without matrix parameters * * @return */ public String getMatchingPath() { return matchingPath; } /** * Create a UriInfo from the baseURI * * @param relative * @return */ public ResteasyUriInfo setRequestUri(URI relative) { String rel = relative.toString(); if (rel.startsWith(baseURI.toString())) { relative = URI.create(rel.substring(baseURI.toString().length())); } return new ResteasyUriInfo(baseURI, relative); } public String getPath() { return path; } public String getPath(boolean decode) { if (decode) return getPath(); return encodedPath; } public List<PathSegment> getPathSegments() { return pathSegments; } public List<PathSegment> getPathSegments(boolean decode) { if (decode) return getPathSegments(); return encodedPathSegments; } public URI getRequestUri() { return requestURI; } public UriBuilder <API key>() { return UriBuilder.fromUri(requestURI); } public URI getAbsolutePath() { return absolutePath; } public UriBuilder <API key>() { return UriBuilder.fromUri(absolutePath); } public URI getBaseUri() { return baseURI; } public UriBuilder getBaseUriBuilder() { return UriBuilder.fromUri(baseURI); } public MultivaluedMap<String, String> getPathParameters() { if (pathParameters == null) { pathParameters = new MultivaluedMapImpl<String, String>(); } return pathParameters; } public void <API key>(String name, String value) { <API key>().add(name, value); String value1 = Encode.decodePath(value); getPathParameters().add(name, value1); } private MultivaluedMap<String, String> <API key>() { if (<API key> == null) { <API key> = new MultivaluedMapImpl<String, String>(); } return <API key>; } public MultivaluedMap<String, PathSegment[]> <API key>() { if (<API key> == null) { <API key> = new MultivaluedMapImpl<String, PathSegment[]>(); } return <API key>; } public MultivaluedMap<String, PathSegment[]> <API key>() { if (<API key> == null) { <API key> = new MultivaluedMapImpl<String, PathSegment[]>(); } return <API key>; } public MultivaluedMap<String, String> getPathParameters(boolean decode) { if (decode) return getPathParameters(); return <API key>(); } public MultivaluedMap<String, String> getQueryParameters() { if (queryParameters == null) { queryParameters = new MultivaluedMapImpl<String, String>(); } return queryParameters; } protected MultivaluedMap<String, String> <API key>() { if (<API key> == null) { this.<API key> = new MultivaluedMapImpl<String, String>(); } return <API key>; } public MultivaluedMap<String, String> getQueryParameters(boolean decode) { if (decode) return getQueryParameters(); else return <API key>(); } protected void extractParameters(String queryString) { if (queryString == null || queryString.equals("")) return; String[] params = queryString.split("&"); for (String param : params) { if (param.indexOf('=') >= 0) { String[] nv = param.split("=", 2); try { String name = URLDecoder.decode(nv[0], "UTF-8"); String val = nv.length > 1 ? nv[1] : ""; <API key>().add(name, val); getQueryParameters().add(name, URLDecoder.decode(val, "UTF-8")); } catch (<API key> e) { throw new RuntimeException(e); } } else { try { String name = URLDecoder.decode(param, "UTF-8"); <API key>().add(name, ""); getQueryParameters().add(name, ""); } catch (<API key> e) { throw new RuntimeException(e); } } } } public List<String> getMatchedURIs(boolean decode) { if (decode) { if (matchedUris == null) matchedUris = new ArrayList<String>(); return matchedUris; } else { if (encodedMatchedUris == null) encodedMatchedUris = new ArrayList<String>(); return encodedMatchedUris; } } public List<String> getMatchedURIs() { return getMatchedURIs(true); } public List<Object> getMatchedResources() { if (ancestors == null) ancestors = new ArrayList<Object>(); return ancestors; } public void pushCurrentResource(Object resource) { if (ancestors == null) ancestors = new ArrayList<Object>(); ancestors.add(0, resource); } public void pushMatchedPath(String encoded) { encodedMatchedPaths.add(0, encoded); } public List<String> <API key>() { return encodedMatchedPaths; } public void popMatchedPath() { encodedMatchedPaths.remove(0); } public void pushMatchedURI(String encoded) { if (encoded.endsWith("/")) encoded = encoded.substring(0, encoded.length() - 1); if (encoded.startsWith("/")) encoded = encoded.substring(1); String decoded = Encode.decode(encoded); if (encodedMatchedUris == null) encodedMatchedUris = new ArrayList<String>(); encodedMatchedUris.add(0, encoded); if (matchedUris == null) matchedUris = new ArrayList<String>(); matchedUris.add(0, decoded); } @Override public URI resolve(URI uri) { return getBaseUri().resolve(uri); } @Override public URI relativize(URI uri) { URI from = getRequestUri(); URI to = uri; if (uri.getScheme() == null && uri.getHost() == null) { to = getBaseUriBuilder().replaceQuery(null).path(uri.getPath()).replaceQuery(uri.getQuery()).fragment(uri.getFragment()).build(); } return ResteasyUriBuilder.relativize(from, to); } }
package com.cabinetms.client; import java.util.List; import com.google.common.collect.Lists; public class TacticMediaCommand { private String command; private String clientIp; private String destination; private Integer startDate; private Integer endDate; private List<<API key>> detailList = Lists.newLinkedList(); public List<<API key>> getDetailList() { return detailList; } public void setDetailList(List<<API key>> detailList) { this.detailList = detailList; } public String getCommand() { return command; } public void setCommand(String command) { this.command = command; } public String getClientIp() { return clientIp; } public void setClientIp(String clientIp) { this.clientIp = clientIp; } public String getDestination() { return destination; } public void setDestination(String destination) { this.destination = destination; } public Integer getStartDate() { return startDate; } public void setStartDate(Integer startDate) { this.startDate = startDate; } public Integer getEndDate() { return endDate; } public void setEndDate(Integer endDate) { this.endDate = endDate; } }
'use strict'; (function (factory) { if (typeof module === 'object' && module.exports) { factory['default'] = factory; module.exports = factory; } else if (typeof define === 'function' && define.amd) { define('highcharts/modules/treemap', ['highcharts'], function (Highcharts) { factory(Highcharts); factory.Highcharts = Highcharts; return factory; }); } else { factory(typeof Highcharts !== 'undefined' ? Highcharts : undefined); } }(function (Highcharts) { var _modules = Highcharts ? Highcharts._modules : {}; function _registerModule(obj, path, args, fn) { if (!obj.hasOwnProperty(path)) { obj[path] = fn.apply(null, args); } } _registerModule(_modules, 'mixins/tree-series.js', [_modules['parts/Globals.js']], function (H) { var extend = H.extend, isArray = H.isArray, isBoolean = function (x) { return typeof x === 'boolean'; }, isFn = function (x) { return typeof x === 'function'; }, isObject = H.isObject, isNumber = H.isNumber, merge = H.merge, pick = H.pick; // TODO Combine buildTree and buildNode with setTreeValues // TODO Remove logic from Treemap and make it utilize this mixin. var setTreeValues = function setTreeValues(tree, options) { var before = options.before, idRoot = options.idRoot, mapIdToNode = options.mapIdToNode, nodeRoot = mapIdToNode[idRoot], levelIsConstant = ( isBoolean(options.levelIsConstant) ? options.levelIsConstant : true ), points = options.points, point = points[tree.i], optionsPoint = point && point.options || {}, childrenTotal = 0, children = [], value; extend(tree, { levelDynamic: tree.level - (levelIsConstant ? 0 : nodeRoot.level), name: pick(point && point.name, ''), visible: ( idRoot === tree.id || (isBoolean(options.visible) ? options.visible : false) ) }); if (isFn(before)) { tree = before(tree, options); } // First give the children some values tree.children.forEach(function (child, i) { var newOptions = extend({}, options); extend(newOptions, { index: i, siblings: tree.children.length, visible: tree.visible }); child = setTreeValues(child, newOptions); children.push(child); if (child.visible) { childrenTotal += child.val; } }); tree.visible = childrenTotal > 0 || tree.visible; // Set the values value = pick(optionsPoint.value, childrenTotal); extend(tree, { children: children, childrenTotal: childrenTotal, isLeaf: tree.visible && !childrenTotal, val: value }); return tree; }; var getColor = function getColor(node, options) { var index = options.index, mapOptionsToLevel = options.mapOptionsToLevel, parentColor = options.parentColor, parentColorIndex = options.parentColorIndex, series = options.series, colors = options.colors, siblings = options.siblings, points = series.points, getColorByPoint, chartOptionsChart = series.chart.options.chart, point, level, colorByPoint, colorIndexByPoint, color, colorIndex; function variation(color) { var colorVariation = level && level.colorVariation; if (colorVariation) { if (colorVariation.key === 'brightness') { return H.color(color).brighten( colorVariation.to * (index / siblings) ).get(); } } return color; } if (node) { point = points[node.i]; level = mapOptionsToLevel[node.level] || {}; getColorByPoint = point && level.colorByPoint; if (getColorByPoint) { colorIndexByPoint = point.index % (colors ? colors.length : chartOptionsChart.colorCount ); colorByPoint = colors && colors[colorIndexByPoint]; } // Select either point color, level color or inherited color. if (!series.chart.styledMode) { color = pick( point && point.options.color, level && level.color, colorByPoint, parentColor && variation(parentColor), series.color ); } colorIndex = pick( point && point.options.colorIndex, level && level.colorIndex, colorIndexByPoint, parentColorIndex, options.colorIndex ); } return { color: color, colorIndex: colorIndex }; }; /** * Creates a map from level number to its given options. * * @private * @function getLevelOptions * * @param {object} params * Object containing parameters. * - `defaults` Object containing default options. The default options * are merged with the userOptions to get the final options for a * specific level. * - `from` The lowest level number. * - `levels` User options from series.levels. * - `to` The highest level number. * * @return {Highcharts.Dictionary<object>} * Returns a map from level number to its given options. */ var getLevelOptions = function getLevelOptions(params) { var result = null, defaults, converted, i, from, to, levels; if (isObject(params)) { result = {}; from = isNumber(params.from) ? params.from : 1; levels = params.levels; converted = {}; defaults = isObject(params.defaults) ? params.defaults : {}; if (isArray(levels)) { converted = levels.reduce(function (obj, item) { var level, levelIsConstant, options; if (isObject(item) && isNumber(item.level)) { options = merge({}, item); levelIsConstant = ( isBoolean(options.levelIsConstant) ? options.levelIsConstant : defaults.levelIsConstant ); // Delete redundant properties. delete options.levelIsConstant; delete options.level; // Calculate which level these options apply to. level = item.level + (levelIsConstant ? 0 : from - 1); if (isObject(obj[level])) { extend(obj[level], options); } else { obj[level] = options; } } return obj; }, {}); } to = isNumber(params.to) ? params.to : 1; for (i = 0; i <= to; i++) { result[i] = merge( {}, defaults, isObject(converted[i]) ? converted[i] : {} ); } } return result; }; /** * Update the rootId property on the series. Also makes sure that it is * accessible to exporting. * * @private * @function updateRootId * * @param {object} series * The series to operate on. * * @return {string} * Returns the resulting rootId after update. */ var updateRootId = function (series) { var rootId, options; if (isObject(series)) { // Get the series options. options = isObject(series.options) ? series.options : {}; // Calculate the rootId. rootId = pick(series.rootNode, options.rootId, ''); // Set rootId on series.userOptions to pick it up in exporting. if (isObject(series.userOptions)) { series.userOptions.rootId = rootId; } // Set rootId on series to pick it up on next update. series.rootNode = rootId; } return rootId; }; var result = { getColor: getColor, getLevelOptions: getLevelOptions, setTreeValues: setTreeValues, updateRootId: updateRootId }; return result; }); _registerModule(_modules, 'mixins/draw-point.js', [], function () { var isFn = function (x) { return typeof x === 'function'; }; /** * Handles the drawing of a component. * Can be used for any type of component that reserves the graphic property, and * provides a shouldDraw on its context. * * @private * @function draw * * @param {object} params * Parameters. * * TODO: add type checking. * TODO: export this function to enable usage */ var draw = function draw(params) { var component = this, graphic = component.graphic, animatableAttribs = params.animatableAttribs, onComplete = params.onComplete, css = params.css, renderer = params.renderer; if (component.shouldDraw()) { if (!graphic) { component.graphic = graphic = renderer[params.shapeType](params.shapeArgs).add(params.group); } graphic .css(css) .attr(params.attribs) .animate( animatableAttribs, params.isNew ? false : undefined, onComplete ); } else if (graphic) { var destroy = function () { component.graphic = graphic = graphic.destroy(); if (isFn(onComplete)) { onComplete(); } }; // animate only runs complete callback if something was animated. if (Object.keys(animatableAttribs).length) { graphic.animate(animatableAttribs, undefined, function () { destroy(); }); } else { destroy(); } } }; /** * An extended version of draw customized for points. * It calls additional methods that is expected when rendering a point. * * @param {object} params Parameters */ var drawPoint = function drawPoint(params) { var point = this, attribs = params.attribs = params.attribs || {}; // Assigning class in dot notation does go well in IE8 // <API key> dot-notation attribs['class'] = point.getClassName(); // Call draw to render component draw.call(point, params); }; return drawPoint; }); _registerModule(_modules, 'modules/treemap.src.js', [_modules['parts/Globals.js'], _modules['mixins/tree-series.js'], _modules['mixins/draw-point.js']], function (H, mixinTreeSeries, drawPoint) { var seriesType = H.seriesType, seriesTypes = H.seriesTypes, addEvent = H.addEvent, merge = H.merge, extend = H.extend, error = H.error, defined = H.defined, noop = H.noop, fireEvent = H.fireEvent, getColor = mixinTreeSeries.getColor, getLevelOptions = mixinTreeSeries.getLevelOptions, isArray = H.isArray, isBoolean = function (x) { return typeof x === 'boolean'; }, isNumber = H.isNumber, isObject = H.isObject, isString = H.isString, pick = H.pick, Series = H.Series, stableSort = H.stableSort, color = H.Color, eachObject = function (list, func, context) { context = context || this; H.objectEach(list, function (val, key) { func.call(context, val, key, list); }); }, // @todo find correct name for this function. // @todo Similar to reduce, this function is likely redundant recursive = function (item, func, context) { var next; context = context || this; next = func.call(context, item); if (next !== false) { recursive(next, func, context); } }, updateRootId = mixinTreeSeries.updateRootId; /** * @private * @class * @name Highcharts.seriesTypes.treemap * * @augments Highcharts.Series */ seriesType( 'treemap', 'scatter' /** * A treemap displays hierarchical data using nested rectangles. The data * can be laid out in varying ways depending on options. * * @sample highcharts/demo/<API key>/ * Treemap * * @extends plotOptions.scatter * @excluding marker, jitter * @product highcharts * @optionparent plotOptions.treemap */ , { /** * When enabled the user can click on a point which is a parent and * zoom in on its children. Deprecated and replaced by * [allowTraversingTree](#plotOptions.treemap.allowTraversingTree). * * @sample {highcharts} highcharts/plotoptions/<API key>/ * Enabled * * @deprecated * @type {boolean} * @default false * @since 4.1.0 * @product highcharts * @apioption plotOptions.treemap.allowDrillToNode */ /** * When enabled the user can click on a point which is a parent and * zoom in on its children. * * @sample {highcharts} highcharts/plotoptions/<API key>/ * Enabled * * @since 7.0.3 * @product highcharts */ allowTraversingTree: false, animationLimit: 250, /** * When the series contains less points than the crop threshold, all * points are drawn, event if the points fall outside the visible plot * area at the current zoom. The advantage of drawing all points * (including markers and columns), is that animation is performed on * updates. On the other hand, when the series contains more points than * the crop threshold, the series data is cropped to only contain points * that fall within the plot area. The advantage of cropping away * invisible points is to increase performance on large series. * * @type {number} * @default 300 * @since 4.1.0 * @product highcharts * @apioption plotOptions.treemap.cropThreshold */ /** * Fires on a request for change of root node for the tree, before the * update is made. An event object is passed to the function, containing * additional properties `newRootId`, `previousRootId`, `redraw` and * `trigger`. * * @type {function} * @default undefined * @sample {highcharts} highcharts/plotoptions/<API key>/ * Alert update information on setRootNode event. * @since 7.0.3 * @product highcharts * @apioption plotOptions.treemap.events.setRootNode */ /** * This option decides if the user can interact with the parent nodes * or just the leaf nodes. When this option is undefined, it will be * true by default. However when allowTraversingTree is true, then it * will be false by default. * * @sample {highcharts} highcharts/plotoptions/<API key>/ * False * @sample {highcharts} highcharts/plotoptions/<API key>/ * InteractByLeaf and allowTraversingTree is true * * @type {boolean} * @since 4.1.2 * @product highcharts * @apioption plotOptions.treemap.interactByLeaf */ /** * The sort index of the point inside the treemap level. * * @sample {highcharts} highcharts/plotoptions/treemap-sortindex/ * Sort by years * * @type {number} * @since 4.1.10 * @product highcharts * @apioption plotOptions.treemap.sortIndex */ /** * When using automatic point colors pulled from the `options.colors` * collection, this option determines whether the chart should receive * one color per series or one color per point. * * @see [series colors](#plotOptions.treemap.colors) * * @type {boolean} * @default false * @since 2.0 * @product highcharts * @apioption plotOptions.treemap.colorByPoint */ /** * A series specific or series type specific color set to apply instead * of the global [colors](#colors) when * [colorByPoint](#plotOptions.treemap.colorByPoint) is true. * * @type {Array<Highcharts.ColorString|Highcharts.GradientColorObject|Highcharts.PatternObject>} * @since 3.0 * @product highcharts * @apioption plotOptions.treemap.colors */ /** * Whether to display this series type or specific series item in the * legend. */ showInLegend: false, /** * @ignore-option */ marker: false, colorByPoint: false, /** * @since 4.1.0 */ dataLabels: { /** @ignore-option */ defer: false, /** @ignore-option */ enabled: true, /** @ignore-option */ formatter: function () { var point = this && this.point ? this.point : {}, name = isString(point.name) ? point.name : ''; return name; }, /** @ignore-option */ inside: true, /** @ignore-option */ verticalAlign: 'middle' }, tooltip: { headerFormat: '', pointFormat: '<b>{point.name}</b>: {point.value}<br/>' }, /** * Whether to ignore hidden points when the layout algorithm runs. * If `false`, hidden points will leave open spaces. * * @since 5.0.8 */ ignoreHiddenPoint: true, layoutAlgorithm: 'sliceAndDice', /** * Defines which direction the layout algorithm will start drawing. * * @since 4.1.0 * @validvalue ["vertical", "horizontal"] */ <API key>: 'vertical', /** * Enabling this option will make the treemap alternate the drawing * direction between vertical and horizontal. The next levels starting * direction will always be the opposite of the previous. * * @sample {highcharts} highcharts/plotoptions/<API key>/ * Enabled * * @since 4.1.0 */ <API key>: false, /** * Used together with the levels and allowTraversingTree options. When * set to false the first level visible to be level one, which is * dynamic when traversing the tree. Otherwise the level will be the * same as the tree structure. * * @since 4.1.0 */ levelIsConstant: true, /** * Options for the button appearing when drilling down in a treemap. * Deprecated and replaced by * [traverseUpButton](#plotOptions.treemap.traverseUpButton). * * @deprecated */ drillUpButton: { /** * The position of the button. * * @deprecated */ position: { /** * Vertical alignment of the button. * * @deprecated * @type {Highcharts.VerticalAlignValue} * @default top * @product highcharts * @apioption plotOptions.treemap.drillUpButton.position.verticalAlign */ /** * Horizontal alignment of the button. * * @deprecated * @type {Highcharts.AlignValue} */ align: 'right', /** * Horizontal offset of the button. * * @deprecated */ x: -10, /** * Vertical offset of the button. * * @deprecated */ y: 10 } }, /** * Options for the button appearing when traversing down in a treemap. */ traverseUpButton: { /** * The position of the button. */ position: { /** * Vertical alignment of the button. * * @type {Highcharts.VerticalAlignValue} * @default top * @product highcharts * @apioption plotOptions.treemap.traverseUpButton.position.verticalAlign */ /** * Horizontal alignment of the button. * * @type {Highcharts.AlignValue} */ align: 'right', /** * Horizontal offset of the button. */ x: -10, /** * Vertical offset of the button. */ y: 10 } }, /** * Set options on specific levels. Takes precedence over series options, * but not point options. * * @sample {highcharts} highcharts/plotoptions/treemap-levels/ * Styling dataLabels and borders * @sample {highcharts} highcharts/demo/treemap-with-levels/ * Different layoutAlgorithm * * @type {Array<*>} * @since 4.1.0 * @product highcharts * @apioption plotOptions.treemap.levels */ /** * Can set a `borderColor` on all points which lies on the same level. * * @type {Highcharts.ColorString} * @since 4.1.0 * @product highcharts * @apioption plotOptions.treemap.levels.borderColor */ /** * Set the dash style of the border of all the point which lies on the * level. See <a href"#plotoptions.scatter.dashstyle"> * plotOptions.scatter.dashStyle</a> for possible options. * * @type {string} * @since 4.1.0 * @product highcharts * @apioption plotOptions.treemap.levels.borderDashStyle */ /** * Can set the borderWidth on all points which lies on the same level. * * @type {number} * @since 4.1.0 * @product highcharts * @apioption plotOptions.treemap.levels.borderWidth */ /** * Can set a color on all points which lies on the same level. * * @type {Highcharts.ColorString|Highcharts.GradientColorObject|Highcharts.PatternObject} * @since 4.1.0 * @product highcharts * @apioption plotOptions.treemap.levels.color */ /** * A configuration object to define how the color of a child varies from * the parent's color. The variation is distributed among the children * of node. For example when setting brightness, the brightness change * will range from the parent's original brightness on the first child, * to the amount set in the `to` setting on the last node. This allows a * gradient-like color scheme that sets children out from each other * while highlighting the grouping on treemaps and sectors on sunburst * charts. * * @sample highcharts/demo/sunburst/ * Sunburst with color variation * * @since 6.0.0 * @product highcharts * @apioption plotOptions.treemap.levels.colorVariation */ /** * The key of a color variation. Currently supports `brightness` only. * * @type {string} * @since 6.0.0 * @product highcharts * @validvalue ["brightness"] * @apioption plotOptions.treemap.levels.colorVariation.key */ /** * The ending value of a color variation. The last sibling will receive * this value. * * @type {number} * @since 6.0.0 * @product highcharts * @apioption plotOptions.treemap.levels.colorVariation.to */ /** * Can set the options of dataLabels on each point which lies on the * level. * [plotOptions.treemap.dataLabels](#plotOptions.treemap.dataLabels) for * possible values. * * @type {object} * @since 4.1.0 * @product highcharts * @apioption plotOptions.treemap.levels.dataLabels */ /** * Can set the layoutAlgorithm option on a specific level. * * @type {string} * @since 4.1.0 * @product highcharts * @validvalue ["sliceAndDice", "stripes", "squarified", "strip"] * @apioption plotOptions.treemap.levels.layoutAlgorithm */ /** * Can set the <API key> option on a specific level. * * @type {string} * @since 4.1.0 * @product highcharts * @validvalue ["vertical", "horizontal"] * @apioption plotOptions.treemap.levels.<API key> */ /** * Decides which level takes effect from the options set in the levels * object. * * @sample {highcharts} highcharts/plotoptions/treemap-levels/ * Styling of both levels * * @type {number} * @since 4.1.0 * @product highcharts * @apioption plotOptions.treemap.levels.level */ // Presentational options /** * The color of the border surrounding each tree map item. * * @type {Highcharts.ColorString} */ borderColor: '#e6e6e6', /** * The width of the border surrounding each tree map item. */ borderWidth: 1, /** * The opacity of a point in treemap. When a point has children, the * visibility of the children is determined by the opacity. * * @since 4.2.4 */ opacity: 0.15, /** * A wrapper object for all the series options in specific states. * * @extends plotOptions.heatmap.states */ states: { /** * Options for the hovered series * * @extends plotOptions.heatmap.states.hover * @excluding halo */ hover: { /** * The border color for the hovered state. */ borderColor: '#999999', /** * Brightness for the hovered point. Defaults to 0 if the * heatmap series is loaded first, otherwise 0.1. * * @type {number} * @default undefined */ brightness: seriesTypes.heatmap ? 0 : 0.1, /** * @extends plotOptions.heatmap.states.hover.halo */ halo: false, /** * The opacity of a point in treemap. When a point has children, * the visibility of the children is determined by the opacity. * * @since 4.2.4 */ opacity: 0.75, /** * The shadow option for hovered state. */ shadow: false } } // Prototype members }, { pointArrayMap: ['value'], directTouch: true, optionalAxis: 'colorAxis', getSymbol: noop, parallelArrays: ['x', 'y', 'value', 'colorValue'], colorKey: 'colorValue', // Point color option key trackerGroups: ['group', 'dataLabelsGroup'], /** * Creates an object map from parent id to childrens index. * * @private * @function Highcharts.Series#getListOfParents * * @param {Highcharts.<API key>} data * List of points set in options. * * @param {Array<string>} existingIds * List of all point ids. * * @return {object} * Map from parent id to children index in data. */ getListOfParents: function (data, existingIds) { var arr = isArray(data) ? data : [], ids = isArray(existingIds) ? existingIds : [], listOfParents = arr.reduce(function (prev, curr, i) { var parent = pick(curr.parent, ''); if (prev[parent] === undefined) { prev[parent] = []; } prev[parent].push(i); return prev; }, { '': [] // Root of tree }); // If parent does not exist, hoist parent to root of tree. eachObject(listOfParents, function (children, parent, list) { if ((parent !== '') && (ids.indexOf(parent) === -1)) { children.forEach(function (child) { list[''].push(child); }); delete list[parent]; } }); return listOfParents; }, // Creates a tree structured object from the series points getTree: function () { var series = this, allIds = this.data.map(function (d) { return d.id; }), parentList = series.getListOfParents(this.data, allIds); series.nodeMap = []; return series.buildNode('', -1, 0, parentList, null); }, // Define hasData function for non-cartesian series. // Returns true if the series has points at all. hasData: function () { return !!this.processedXData.length; }, init: function (chart, options) { var series = this, colorSeriesMixin = H.colorSeriesMixin; // If color series logic is loaded, add some properties if (H.colorSeriesMixin) { this.translateColors = colorSeriesMixin.translateColors; this.colorAttribs = colorSeriesMixin.colorAttribs; this.axisTypes = colorSeriesMixin.axisTypes; } // Handle deprecated options. addEvent(series, 'setOptions', function (event) { var options = event.userOptions; if ( defined(options.allowDrillToNode) && !defined(options.allowTraversingTree) ) { options.allowTraversingTree = options.allowDrillToNode; delete options.allowDrillToNode; } if ( defined(options.drillUpButton) && !defined(options.traverseUpButton) ) { options.traverseUpButton = options.drillUpButton; delete options.drillUpButton; } }); Series.prototype.init.call(series, chart, options); if (series.options.allowTraversingTree) { addEvent(series, 'click', series.onClickDrillToNode); } }, buildNode: function (id, i, level, list, parent) { var series = this, children = [], point = series.points[i], height = 0, node, child; // Actions ((list[id] || [])).forEach(function (i) { child = series.buildNode( series.points[i].id, i, (level + 1), list, id ); height = Math.max(child.height + 1, height); children.push(child); }); node = { id: id, i: i, children: children, height: height, level: level, parent: parent, visible: false // @todo move this to better location }; series.nodeMap[node.id] = node; if (point) { point.node = node; } return node; }, setTreeValues: function (tree) { var series = this, options = series.options, idRoot = series.rootNode, mapIdToNode = series.nodeMap, nodeRoot = mapIdToNode[idRoot], levelIsConstant = ( isBoolean(options.levelIsConstant) ? options.levelIsConstant : true ), childrenTotal = 0, children = [], val, point = series.points[tree.i]; // First give the children some values tree.children.forEach(function (child) { child = series.setTreeValues(child); children.push(child); if (!child.ignore) { childrenTotal += child.val; } }); // Sort the children stableSort(children, function (a, b) { return a.sortIndex - b.sortIndex; }); // Set the values val = pick(point && point.options.value, childrenTotal); if (point) { point.value = val; } extend(tree, { children: children, childrenTotal: childrenTotal, // Ignore this node if point is not visible ignore: !(pick(point && point.visible, true) && (val > 0)), isLeaf: tree.visible && !childrenTotal, levelDynamic: ( tree.level - (levelIsConstant ? 0 : nodeRoot.level) ), name: pick(point && point.name, ''), sortIndex: pick(point && point.sortIndex, -val), val: val }); return tree; }, /** * Recursive function which calculates the area for all children of a * node. * * @private * @function Highcharts.Series#<API key> * * @param {object} node * The node which is parent to the children. * * @param {object} area * The rectangular area of the parent. */ <API key>: function (parent, area) { var series = this, options = series.options, mapOptionsToLevel = series.mapOptionsToLevel, level = mapOptionsToLevel[parent.level + 1], algorithm = pick( ( series[level && level.layoutAlgorithm] && level.layoutAlgorithm ), options.layoutAlgorithm ), alternate = options.<API key>, childrenValues = [], children; // Collect all children which should be included children = parent.children.filter(function (n) { return !n.ignore; }); if (level && level.<API key>) { area.direction = level.<API key> === 'vertical' ? 0 : 1; } childrenValues = series[algorithm](area, children); children.forEach(function (child, index) { var values = childrenValues[index]; child.values = merge(values, { val: child.childrenTotal, direction: (alternate ? 1 - area.direction : area.direction) }); child.pointValues = merge(values, { x: (values.x / series.axisRatio), width: (values.width / series.axisRatio) }); // If node has children, then call method recursively if (child.children.length) { series.<API key>(child, child.values); } }); }, setPointValues: function () { var series = this, xAxis = series.xAxis, yAxis = series.yAxis; series.points.forEach(function (point) { var node = point.node, values = node.pointValues, x1, x2, y1, y2, crispCorr = 0; // Get the crisp correction in classic mode. For this to work in // styled mode, we would need to first add the shape (without x, // y, width and height), then read the rendered stroke width // using point.graphic.strokeWidth(), then modify and apply the // shapeArgs. This applies also to column series, but the // downside is performance and code complexity. if (!series.chart.styledMode) { crispCorr = ( (series.pointAttribs(point)['stroke-width'] || 0) % 2 ) / 2; } // Points which is ignored, have no values. if (values && node.visible) { x1 = Math.round( xAxis.translate(values.x, 0, 0, 0, 1) ) - crispCorr; x2 = Math.round( xAxis.translate(values.x + values.width, 0, 0, 0, 1) ) - crispCorr; y1 = Math.round( yAxis.translate(values.y, 0, 0, 0, 1) ) - crispCorr; y2 = Math.round( yAxis.translate(values.y + values.height, 0, 0, 0, 1) ) - crispCorr; // Set point values point.shapeArgs = { x: Math.min(x1, x2), y: Math.min(y1, y2), width: Math.abs(x2 - x1), height: Math.abs(y2 - y1) }; point.plotX = point.shapeArgs.x + (point.shapeArgs.width / 2); point.plotY = point.shapeArgs.y + (point.shapeArgs.height / 2); } else { // Reset visibility delete point.plotX; delete point.plotY; } }); }, // Set the node's color recursively, from the parent down. setColorRecursive: function ( node, parentColor, colorIndex, index, siblings ) { var series = this, chart = series && series.chart, colors = chart && chart.options && chart.options.colors, colorInfo, point; if (node) { colorInfo = getColor(node, { colors: colors, index: index, mapOptionsToLevel: series.mapOptionsToLevel, parentColor: parentColor, parentColorIndex: colorIndex, series: series, siblings: siblings }); point = series.points[node.i]; if (point) { point.color = colorInfo.color; point.colorIndex = colorInfo.colorIndex; } // Do it all again with the children (node.children || []).forEach(function (child, i) { series.setColorRecursive( child, colorInfo.color, colorInfo.colorIndex, i, node.children.length ); }); } }, algorithmGroup: function (h, w, d, p) { this.height = h; this.width = w; this.plot = p; this.direction = d; this.startDirection = d; this.total = 0; this.nW = 0; this.lW = 0; this.nH = 0; this.lH = 0; this.elArr = []; this.lP = { total: 0, lH: 0, nH: 0, lW: 0, nW: 0, nR: 0, lR: 0, aspectRatio: function (w, h) { return Math.max((w / h), (h / w)); } }; this.addElement = function (el) { this.lP.total = this.elArr[this.elArr.length - 1]; this.total = this.total + el; if (this.direction === 0) { // Calculate last point old aspect ratio this.lW = this.nW; this.lP.lH = this.lP.total / this.lW; this.lP.lR = this.lP.aspectRatio(this.lW, this.lP.lH); // Calculate last point new aspect ratio this.nW = this.total / this.height; this.lP.nH = this.lP.total / this.nW; this.lP.nR = this.lP.aspectRatio(this.nW, this.lP.nH); } else { // Calculate last point old aspect ratio this.lH = this.nH; this.lP.lW = this.lP.total / this.lH; this.lP.lR = this.lP.aspectRatio(this.lP.lW, this.lH); // Calculate last point new aspect ratio this.nH = this.total / this.width; this.lP.nW = this.lP.total / this.nH; this.lP.nR = this.lP.aspectRatio(this.lP.nW, this.nH); } this.elArr.push(el); }; this.reset = function () { this.nW = 0; this.lW = 0; this.elArr = []; this.total = 0; }; }, algorithmCalcPoints: function ( directionChange, last, group, childrenArea ) { var pX, pY, pW, pH, gW = group.lW, gH = group.lH, plot = group.plot, keep, i = 0, end = group.elArr.length - 1; if (last) { gW = group.nW; gH = group.nH; } else { keep = group.elArr[group.elArr.length - 1]; } group.elArr.forEach(function (p) { if (last || (i < end)) { if (group.direction === 0) { pX = plot.x; pY = plot.y; pW = gW; pH = p / pW; } else { pX = plot.x; pY = plot.y; pH = gH; pW = p / pH; } childrenArea.push({ x: pX, y: pY, width: pW, height: H.correctFloat(pH) }); if (group.direction === 0) { plot.y = plot.y + pH; } else { plot.x = plot.x + pW; } } i = i + 1; }); // Reset variables group.reset(); if (group.direction === 0) { group.width = group.width - gW; } else { group.height = group.height - gH; } plot.y = plot.parent.y + (plot.parent.height - group.height); plot.x = plot.parent.x + (plot.parent.width - group.width); if (directionChange) { group.direction = 1 - group.direction; } // If not last, then add uncalculated element if (!last) { group.addElement(keep); } }, <API key>: function (directionChange, parent, children) { var childrenArea = [], series = this, pTot, plot = { x: parent.x, y: parent.y, parent: parent }, direction = parent.direction, i = 0, end = children.length - 1, group = new this.algorithmGroup( // eslint-disable-line new-cap parent.height, parent.width, direction, plot ); // Loop through and calculate all areas children.forEach(function (child) { pTot = (parent.width * parent.height) * (child.val / parent.val); group.addElement(pTot); if (group.lP.nR > group.lP.lR) { series.algorithmCalcPoints( directionChange, false, group, childrenArea, plot ); } // If last child, then calculate all remaining areas if (i === end) { series.algorithmCalcPoints( directionChange, true, group, childrenArea, plot ); } i = i + 1; }); return childrenArea; }, algorithmFill: function (directionChange, parent, children) { var childrenArea = [], pTot, direction = parent.direction, x = parent.x, y = parent.y, width = parent.width, height = parent.height, pX, pY, pW, pH; children.forEach(function (child) { pTot = (parent.width * parent.height) * (child.val / parent.val); pX = x; pY = y; if (direction === 0) { pH = height; pW = pTot / pH; width = width - pW; x = x + pW; } else { pW = width; pH = pTot / pW; height = height - pH; y = y + pH; } childrenArea.push({ x: pX, y: pY, width: pW, height: pH }); if (directionChange) { direction = 1 - direction; } }); return childrenArea; }, strip: function (parent, children) { return this.<API key>(false, parent, children); }, squarified: function (parent, children) { return this.<API key>(true, parent, children); }, sliceAndDice: function (parent, children) { return this.algorithmFill(true, parent, children); }, stripes: function (parent, children) { return this.algorithmFill(false, parent, children); }, translate: function () { var series = this, options = series.options, // NOTE: updateRootId modifies series. rootId = updateRootId(series), rootNode, pointValues, seriesArea, tree, val; // Call prototype function Series.prototype.translate.call(series); // @todo Only if series.isDirtyData is true tree = series.tree = series.getTree(); rootNode = series.nodeMap[rootId]; series.<API key>(rootId); series.mapOptionsToLevel = getLevelOptions({ from: rootNode.level + 1, levels: options.levels, to: tree.height, defaults: { levelIsConstant: series.options.levelIsConstant, colorByPoint: options.colorByPoint } }); if ( rootId !== '' && (!rootNode || !rootNode.children.length) ) { series.setRootNode('', false); rootId = series.rootNode; rootNode = series.nodeMap[rootId]; } // Parents of the root node is by default visible recursive(series.nodeMap[series.rootNode], function (node) { var next = false, p = node.parent; node.visible = true; if (p || p === '') { next = series.nodeMap[p]; } return next; }); // Children of the root node is by default visible recursive( series.nodeMap[series.rootNode].children, function (children) { var next = false; children.forEach(function (child) { child.visible = true; if (child.children.length) { next = (next || []).concat(child.children); } }); return next; } ); series.setTreeValues(tree); // Calculate plotting values. series.axisRatio = (series.xAxis.len / series.yAxis.len); series.nodeMap[''].pointValues = pointValues = { x: 0, y: 0, width: 100, height: 100 }; series.nodeMap[''].values = seriesArea = merge(pointValues, { width: (pointValues.width * series.axisRatio), direction: ( options.<API key> === 'vertical' ? 0 : 1 ), val: tree.val }); series.<API key>(tree, seriesArea); // Logic for point colors if (series.colorAxis) { series.translateColors(); } else if (!options.colorByPoint) { series.setColorRecursive(series.tree); } // Update axis extremes according to the root node. if (options.allowTraversingTree) { val = rootNode.pointValues; series.xAxis.setExtremes(val.x, val.x + val.width, false); series.yAxis.setExtremes(val.y, val.y + val.height, false); series.xAxis.setScale(); series.yAxis.setScale(); } // Assign values to points. series.setPointValues(); }, /** * Extend drawDataLabels with logic to handle custom options related to * the treemap series: * * - Points which is not a leaf node, has dataLabels disabled by * default. * * - Options set on series.levels is merged in. * * - Width of the dataLabel is set to match the width of the point * shape. * * @private * @function Highcharts.Series#drawDataLabels */ drawDataLabels: function () { var series = this, mapOptionsToLevel = series.mapOptionsToLevel, points = series.points.filter(function (n) { return n.node.visible; }), options, level; points.forEach(function (point) { level = mapOptionsToLevel[point.node.level]; // Set options to new object to avoid problems with scope options = { style: {} }; // If not a leaf, then label should be disabled as default if (!point.node.isLeaf) { options.enabled = false; } // If options for level exists, include them as well if (level && level.dataLabels) { options = merge(options, level.dataLabels); series._hasPointLabels = true; } // Set dataLabel width to the width of the point shape. if (point.shapeArgs) { options.style.width = point.shapeArgs.width; if (point.dataLabel) { point.dataLabel.css({ width: point.shapeArgs.width + 'px' }); } } // Merge custom options with point options point.dlOptions = merge(options, point.options.dataLabels); }); Series.prototype.drawDataLabels.call(this); }, // Over the alignment method by setting z index alignDataLabel: function (point, dataLabel, labelOptions) { var style = labelOptions.style; // #8160: Prevent the label from exceeding the point's // boundaries in treemaps by applying ellipsis overflow. // The issue was happening when datalabel's text contained a // long sequence of characters without a whitespace. if ( !H.defined(style.textOverflow) && dataLabel.text && dataLabel.getBBox().width > dataLabel.text.textWidth ) { dataLabel.css({ textOverflow: 'ellipsis', // unit (px) is required when useHTML is true width: style.width += 'px' }); } seriesTypes.column.prototype.alignDataLabel.apply(this, arguments); if (point.dataLabel) { // point.node.zIndex could be undefined (#6956) point.dataLabel.attr({ zIndex: (point.node.zIndex || 0) + 1 }); } }, // Get presentational attributes pointAttribs: function (point, state) { var series = this, mapOptionsToLevel = ( isObject(series.mapOptionsToLevel) ? series.mapOptionsToLevel : {} ), level = point && mapOptionsToLevel[point.node.level] || {}, options = this.options, attr, stateOptions = (state && options.states[state]) || {}, className = (point && point.getClassName()) || '', opacity; // Set attributes by precedence. Point trumps level trumps series. // Stroke width uses pick because it can be 0. attr = { 'stroke': (point && point.borderColor) || level.borderColor || stateOptions.borderColor || options.borderColor, 'stroke-width': pick( point && point.borderWidth, level.borderWidth, stateOptions.borderWidth, options.borderWidth ), 'dashstyle': (point && point.borderDashStyle) || level.borderDashStyle || stateOptions.borderDashStyle || options.borderDashStyle, 'fill': (point && point.color) || this.color }; // Hide levels above the current view if (className.indexOf('<API key>') !== -1) { attr.fill = 'none'; attr['stroke-width'] = 0; // Nodes with children that accept interaction } else if ( className.indexOf('<API key>') !== -1 ) { opacity = pick(stateOptions.opacity, options.opacity); attr.fill = color(attr.fill).setOpacity(opacity).get(); attr.cursor = 'pointer'; // Hide nodes that have children } else if (className.indexOf('<API key>') !== -1) { attr.fill = 'none'; } else if (state) { // Brighten and hoist the hover nodes attr.fill = color(attr.fill) .brighten(stateOptions.brightness) .get(); } return attr; }, // Override drawPoints drawPoints: function () { var series = this, chart = series.chart, renderer = chart.renderer, points = series.points, styledMode = chart.styledMode, options = series.options, shadow = styledMode ? {} : options.shadow, borderRadius = options.borderRadius, <API key> = chart.pointCount < options.animationLimit, allowTraversingTree = options.allowTraversingTree; points.forEach(function (point) { var levelDynamic = point.node.levelDynamic, animate = {}, attr = {}, css = {}, groupKey = 'level-group-' + levelDynamic, hasGraphic = !!point.graphic, shouldAnimate = <API key> && hasGraphic, shapeArgs = point.shapeArgs; // Don't bother with calculate styling if the point is not drawn if (point.shouldDraw()) { if (borderRadius) { attr.r = borderRadius; } merge( true, // Extend object // Which object to extend shouldAnimate ? animate : attr, // Add shapeArgs to animate/attr if graphic exists hasGraphic ? shapeArgs : {}, // Add style attribs if !styleMode styledMode ? {} : series.pointAttribs( point, point.selected && 'select' ) ); // In styled mode apply point.color. Use CSS, otherwise the // fill used in the style sheet will take precedence over // the fill attribute. if (series.colorAttribs && styledMode) { // Heatmap is loaded extend(css, series.colorAttribs(point)); } if (!series[groupKey]) { series[groupKey] = renderer.g(groupKey) .attr({ // @todo Set the zIndex based upon the number of // levels, instead of using 1000 zIndex: 1000 - levelDynamic }) .add(series.group); } } // Draw the point point.draw({ animatableAttribs: animate, attribs: attr, css: css, group: series[groupKey], renderer: renderer, shadow: shadow, shapeArgs: shapeArgs, shapeType: 'rect' }); // If setRootNode is allowed, set a point cursor on clickables & // add drillId to point if (allowTraversingTree && point.graphic) { point.drillId = options.interactByLeaf ? series.drillToByLeaf(point) : series.drillToByGroup(point); } }); }, // Add drilling on the suitable points onClickDrillToNode: function (event) { var series = this, point = event.point, drillId = point && point.drillId; // If a drill id is returned, add click event and cursor. if (isString(drillId)) { point.setState(''); // Remove hover series.setRootNode(drillId, true, { trigger: 'click' }); } }, /** * Finds the drill id for a parent node. Returns false if point should * not have a click event. * * @private * @function Highcharts.Series#drillToByGroup * * @param {object} point * * @return {boolean|string} * Drill to id or false when point should not have a click * event. */ drillToByGroup: function (point) { var series = this, drillId = false; if ((point.node.level - series.nodeMap[series.rootNode].level) === 1 && !point.node.isLeaf ) { drillId = point.id; } return drillId; }, /** * Finds the drill id for a leaf node. Returns false if point should not * have a click event * * @private * @function Highcharts.Series#drillToByLeaf * * @param {object} point * * @return {boolean|string} * Drill to id or false when point should not have a click * event. */ drillToByLeaf: function (point) { var series = this, drillId = false, nodeParent; if ((point.node.parent !== series.rootNode) && point.node.isLeaf ) { nodeParent = point.node; while (!drillId) { nodeParent = series.nodeMap[nodeParent.parent]; if (nodeParent.parent === series.rootNode) { drillId = nodeParent.id; } } } return drillId; }, drillUp: function () { var series = this, node = series.nodeMap[series.rootNode]; if (node && isString(node.parent)) { series.setRootNode( node.parent, true, { trigger: 'traverseUpButton' } ); } }, // TODO remove this function at a suitable version. drillToNode: function (id, redraw) { error( 'WARNING: treemap.drillToNode has been renamed to treemap.' + 'setRootNode, and will be removed in the next major version.' ); this.setRootNode(id, redraw); }, /** * Sets a new root node for the series. * * @private * @function Highcharts.Series#setRootNode * * @param {string} id The id of the new root node. * @param {boolean} [redraw=true] Wether to redraw the chart or not. * @param {object} [eventArguments] Arguments to be accessed in * event handler. * @param {string} [eventArguments.newRootId] Id of the new root. * @param {string} [eventArguments.previousRootId] Id of the previous * root. * @param {boolean} [eventArguments.redraw] Wether to redraw the * chart after. * @param {object} [eventArguments.series] The series to update the root * of. * @param {string} [eventArguments.trigger] The action which * triggered the event. Undefined if the setRootNode is called * directly. */ setRootNode: function (id, redraw, eventArguments) { var series = this, eventArgs = extend({ newRootId: id, previousRootId: series.rootNode, redraw: pick(redraw, true), series: series }, eventArguments); /** * The default functionality of the setRootNode event. * * @private * @param {object} args The event arguments. * @param {string} args.newRootId Id of the new root. * @param {string} args.previousRootId Id of the previous root. * @param {boolean} args.redraw Wether to redraw the chart after. * @param {object} args.series The series to update the root of. * @param {string} [args.trigger=undefined] The action which * triggered the event. Undefined if the setRootNode is called * directly. */ var defaultFn = function (args) { var series = args.series; // Store previous and new root ids on the series. series.idPreviousRoot = args.previousRootId; series.rootNode = args.newRootId; // Redraw the chart series.isDirty = true; // Force redraw if (args.redraw) { series.chart.redraw(); } }; // Fire setRootNode event. fireEvent(series, 'setRootNode', eventArgs, defaultFn); }, <API key>: function (rootId) { var series = this, nodeMap = series.nodeMap, node = nodeMap[rootId], name = node.name, buttonOptions = series.options.traverseUpButton, backText = pick(buttonOptions.text, name, '< Back'), attr, states; if (rootId === '') { if (series.drillUpButton) { series.drillUpButton = series.drillUpButton.destroy(); } } else if (!this.drillUpButton) { attr = buttonOptions.theme; states = attr && attr.states; this.drillUpButton = this.chart.renderer.button( backText, null, null, function () { series.drillUp(); }, attr, states && states.hover, states && states.select ) .addClass('<API key>') .attr({ align: buttonOptions.position.align, zIndex: 7 }) .add() .align( buttonOptions.position, false, buttonOptions.relativeTo || 'plotBox' ); } else { this.drillUpButton.placed = false; this.drillUpButton.attr({ text: backText }) .align(); } }, buildKDTree: noop, drawLegendSymbol: H.LegendSymbolMixin.drawRectangle, getExtremes: function () { // Get the extremes from the value data Series.prototype.getExtremes.call(this, this.colorValueData); this.valueMin = this.dataMin; this.valueMax = this.dataMax; // Get the extremes from the y data Series.prototype.getExtremes.call(this); }, getExtremesFromAll: true, bindAxes: function () { var treeAxis = { endOnTick: false, gridLineWidth: 0, lineWidth: 0, min: 0, dataMin: 0, minPadding: 0, max: 100, dataMax: 100, maxPadding: 0, startOnTick: false, title: null, tickPositions: [] }; Series.prototype.bindAxes.call(this); H.extend(this.yAxis.options, treeAxis); H.extend(this.xAxis.options, treeAxis); }, /** * Workaround for `inactive` state. Since `series.opacity` option is * already reserved, don't use that state at all by disabling * `inactiveOtherPoints` and not inheriting states by points. * * @private */ setState: function (state) { this.options.inactiveOtherPoints = true; Series.prototype.setState.call(this, state, false); this.options.inactiveOtherPoints = false; }, utils: { recursive: recursive } // Point class }, { draw: drawPoint, getClassName: function () { var className = H.Point.prototype.getClassName.call(this), series = this.series, options = series.options; // Above the current level if (this.node.level <= series.nodeMap[series.rootNode].level) { className += ' <API key>'; } else if ( !this.node.isLeaf && !pick(options.interactByLeaf, !options.allowTraversingTree) ) { className += ' <API key>'; } else if (!this.node.isLeaf) { className += ' <API key>'; } return className; }, /** * A tree point is valid if it has han id too, assume it may be a parent * item. * * @private * @function Highcharts.Point#isValid */ isValid: function () { return this.id || isNumber(this.value); }, setState: function (state) { H.Point.prototype.setState.call(this, state); // Graphic does not exist when point is not visible. if (this.graphic) { this.graphic.attr({ zIndex: state === 'hover' ? 1 : 0 }); } }, setVisible: seriesTypes.pie.prototype.pointClass.prototype.setVisible, shouldDraw: function () { var point = this; return isNumber(point.plotY) && point.y !== null; } } ); /** * A `treemap` series. If the [type](#series.treemap.type) option is * not specified, it is inherited from [chart.type](#chart.type). * * @extends series,plotOptions.treemap * @excluding dataParser, dataURL, stack * @product highcharts * @apioption series.treemap */ /** * An array of data points for the series. For the `treemap` series * type, points can be given in the following ways: * * 1. An array of numerical values. In this case, the numerical values will be * interpreted as `value` options. Example: * ```js * data: [0, 5, 3, 5] * ``` * * 2. An array of objects with named values. The following snippet shows only a * few settings, see the complete options set below. If the total number of * data points exceeds the series' * [turboThreshold](#series.treemap.turboThreshold), * this option is not available. * ```js * data: [{ * value: 9, * name: "Point2", * color: "#00FF00" * }, { * value: 6, * name: "Point1", * color: "#FF00FF" * }] * ``` * * @sample {highcharts} highcharts/chart/reflow-true/ * Numerical values * @sample {highcharts} highcharts/series/<API key>/ * Config objects * * @type {Array<number|null|*>} * @extends series.heatmap.data * @excluding x, y * @product highcharts * @apioption series.treemap.data */ /** * The value of the point, resulting in a relative area of the point * in the treemap. * * @type {number|null} * @product highcharts * @apioption series.treemap.data.value */ /** * Serves a purpose only if a `colorAxis` object is defined in the chart * options. This value will decide which color the point gets from the * scale of the colorAxis. * * @type {number} * @since 4.1.0 * @product highcharts * @apioption series.treemap.data.colorValue */ /** * Only for treemap. Use this option to build a tree structure. The * value should be the id of the point which is the parent. If no points * has a matching id, or this option is undefined, then the parent will * be set to the root. * * @sample {highcharts} highcharts/point/parent/ * Point parent * @sample {highcharts} highcharts/demo/treemap-with-levels/ * Example where parent id is not matching * * @type {string} * @since 4.1.0 * @product highcharts * @apioption series.treemap.data.parent */ }); _registerModule(_modules, 'masters/modules/treemap.src.js', [], function () { }); }));
<?php require_once __DIR__.'/../vendor/autoload.php'; $db = connectDB(); $redis = connectRedis(); const USER_SIZE = 1000; const THREAD_NUM = 200; const MIN_POST = 0; const MAX_POST = 10000; const CONTENT_MIN = 3; const CONTENT_MAX = 1000; function unichr( $unicode , $encoding = 'UTF-8' ) { return mb_convert_encoding("&#{$unicode};", $encoding, 'HTML-ENTITIES'); } class <API key> { private $seed; private $strtmp; private $seedSize; private $cnt = 0; public function __construct(bool $only_ascii = false, bool $multi_line = true) { $this->seed = '<API key>'; if(!$only_ascii) { for ($i = 12353; $i <= 12435; $i++) { $this->seed .= unichr($i); } for ($i = 12449; $i <= 12534; $i++) { $this->seed .= unichr($i); } $file_content = file_get_contents('joyo.csv'); $unicode_list = preg_split('/(\r\n)|[\r\n]/', $file_content); foreach ($unicode_list as $code_point) { $this->seed .= unichr(hexdec($code_point)); } } if($multi_line) { $this->seed .= '\n'; } $this->seedSize = mb_strlen($this->seed); $this->shuffle(); } private function shuffle() { $this->strtmp = ''; for($i = 0; $i < $this->seedSize; $i++) { $this->strtmp .= mb_substr($this->seed, mt_rand(0, $this->seedSize - 1), 1); } } public function pseudo(int $length) { if(++$this->cnt > 1000) { $this->cnt = 0; $this->shuffle(); } $offset_max = $this->seedSize - $length; return mb_substr($this->strtmp, mt_rand(0, $offset_max), $length); } public function generate(int $length) { $str = ''; for($i = 0; $i < $length; $i++) { $str .= mb_substr($this->seed, mt_rand(0, $this->seedSize - 1), 1); } return $str; } } $single_gen = new <API key>(true, false); $content_gen = new <API key>(); $gen_content = function() use($content_gen) { return $content_gen->pseudo(mt_rand(CONTENT_MIN, CONTENT_MAX)); }; echo "Creating users...\n"; $user_ids = []; for($i = 0; $i < USER_SIZE; $i++) { $password = $single_gen->pseudo(mt_rand(7, 40)); $user_name = $single_gen->generate(mt_rand(4, 8)); $user = new mb\models\User($user_name, $user_name.'@example.com', $password, $password); if($user->create($db)) { $user_ids[] = $user->id; } } $user_count = count($user_ids); $gen_user_id = function() use($user_ids, $user_count) { return $user_ids[mt_rand(0, $user_count - 1)]; }; echo "End creating users.\n"; echo "Creating threads...\n"; for($i = 0; $i < THREAD_NUM; $i++) { $thread_owner = $gen_user_id(); $thread = new mb\models\Thread($db, $single_gen->generate(mt_rand(5, 80)), $thread_owner); $thread->create($db, $redis); $post_first = new mb\models\Post($db, $thread->id, $thread_owner, $gen_content()); $post_first->create($db); $post_num = mt_rand(MIN_POST, MAX_POST); for($j = 0; $j < $post_num; $j++) { $post = new mb\models\Post($db, $thread->id, $gen_user_id(), $gen_content()); $post->create($db); } } echo "End creating thread.\n";
package com.jason.showcase.lambdas; public class Lambda { public void execute(Action action) { action.run("Hello Lambda!"); } public void test() { execute(System.out::println); } public static void main(String[] args) { new Lambda().test(); } }
package com.common.dao; import java.sql.PreparedStatement; import java.sql.SQLException; import java.util.logging.Logger; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import javax.persistence.<API key>; public class BaseDAO { /** * Constante que representa el character '%'. */ public static final String SYMBOLO_LIKE = "%"; /** * Constante que representa la cadena "'". */ public static final String SYMBOLO_APOSTROFE = "'"; protected static final Logger LOGGER = Logger.getLogger(BaseDAO.class.getName()); /** * Objeto que maneja las operaciones de persistencia. */ @PersistenceContext(name = "punit") private EntityManager em; /** * Constructor por defecto. */ public BaseDAO() { } protected EntityManager getEntityManager() { if (em == null) { throw new <API key>( "EntityManager no ha sido asignado a DAO antes del uso."); } else { return em; } } public void ejecutarNativo(String sentencia) { try { java.sql.Connection connection = em.unwrap(java.sql.Connection.class); PreparedStatement ps = connection.prepareStatement(sentencia); ps.execute(); ps.close(); } catch (<API key> e) { LOGGER.info("Error al ejecutar sentencia"+ e.getMessage()); } catch (SQLException e) { LOGGER.info("Error al ejecutar sentencia"+ e.getMessage()); } } protected String comillar(String cadena) { return SYMBOLO_APOSTROFE + cadena + SYMBOLO_APOSTROFE; } }
#include <memory> #include "envoy/config/endpoint/v3/endpoint.pb.h" #include "envoy/config/endpoint/v3/endpoint.pb.validate.h" #include "envoy/service/discovery/v3/discovery.pb.h" #include "source/common/common/empty_string.h" #include "source/common/config/api_version.h" #include "source/common/config/grpc_mux_impl.h" #include "source/common/config/protobuf_link_hacks.h" #include "source/common/config/utility.h" #include "source/common/protobuf/protobuf.h" #include "source/common/stats/isolated_store_impl.h" #include "test/common/stats/stat_test_utility.h" #include "test/mocks/common.h" #include "test/mocks/config/mocks.h" #include "test/mocks/event/mocks.h" #include "test/mocks/grpc/mocks.h" #include "test/mocks/local_info/mocks.h" #include "test/mocks/runtime/mocks.h" #include "test/test_common/logging.h" #include "test/test_common/resources.h" #include "test/test_common/<API key>.h" #include "test/test_common/test_time.h" #include "test/test_common/utility.h" #include "gmock/gmock.h" #include "gtest/gtest.h" using testing::_; using testing::AtLeast; using testing::InSequence; using testing::Invoke; using testing::IsSubstring; using testing::NiceMock; using testing::Return; using testing::ReturnRef; namespace Envoy { namespace Config { namespace { // We test some mux specific stuff below, other unit test coverage for singleton use of GrpcMuxImpl // is provided in [grpc_]<API key>.cc. class GrpcMuxImplTestBase : public testing::Test { public: GrpcMuxImplTestBase() : async_client_(new Grpc::MockAsyncClient()), <API key>( stats_.gauge("control_plane.connected_state", Stats::Gauge::ImportMode::NeverImport)), <API key>( stats_.gauge("control_plane.pending_requests", Stats::Gauge::ImportMode::NeverImport)) {} void setup() { grpc_mux_ = std::make_unique<GrpcMuxImpl>( local_info_, std::unique_ptr<Grpc::MockAsyncClient>(async_client_), dispatcher_, *Protobuf::DescriptorPool::generated_pool()->FindMethodByName( "envoy.service.discovery.v3.<API key>.<API key>"), random_, stats_, <API key>, true); } void setup(const RateLimitSettings& <API key>) { grpc_mux_ = std::make_unique<GrpcMuxImpl>( local_info_, std::unique_ptr<Grpc::MockAsyncClient>(async_client_), dispatcher_, *Protobuf::DescriptorPool::generated_pool()->FindMethodByName( "envoy.service.discovery.v3.<API key>.<API key>"), random_, stats_, <API key>, true); } void expectSendMessage(const std::string& type_url, const std::vector<std::string>& resource_names, const std::string& version, bool first = false, const std::string& nonce = "", const Protobuf::int32 error_code = Grpc::Status::WellKnownGrpcStatus::Ok, const std::string& error_message = "") { envoy::service::discovery::v3::DiscoveryRequest expected_request; if (first) { expected_request.mutable_node()->CopyFrom(local_info_.node()); } for (const auto& resource : resource_names) { expected_request.add_resource_names(resource); } if (!version.empty()) { expected_request.set_version_info(version); } expected_request.set_response_nonce(nonce); expected_request.set_type_url(type_url); if (error_code != Grpc::Status::WellKnownGrpcStatus::Ok) { ::google::rpc::Status* error_detail = expected_request.<API key>(); error_detail->set_code(error_code); error_detail->set_message(error_message); } EXPECT_CALL(async_stream_, sendMessageRaw_(Grpc::ProtoBufferEq(expected_request), false)); } NiceMock<Event::MockDispatcher> dispatcher_; NiceMock<Random::MockRandomGenerator> random_; NiceMock<LocalInfo::MockLocalInfo> local_info_; Grpc::MockAsyncClient* async_client_; Grpc::MockAsyncStream async_stream_; GrpcMuxImplPtr grpc_mux_; NiceMock<<API key>> callbacks_; NiceMock<<API key>> resource_decoder_; Stats::TestUtil::TestStore stats_; Envoy::Config::RateLimitSettings <API key>; Stats::Gauge& <API key>; Stats::Gauge& <API key>; }; class GrpcMuxImplTest : public GrpcMuxImplTestBase { public: Event::SimulatedTimeSystem time_system_; }; // Validate behavior when multiple type URL watches are maintained, watches are created/destroyed // (via RAII). TEST_F(GrpcMuxImplTest, <API key>) { setup(); InSequence s; auto foo_sub = grpc_mux_->addWatch("foo", {"x", "y"}, callbacks_, resource_decoder_, {}); auto bar_sub = grpc_mux_->addWatch("bar", {}, callbacks_, resource_decoder_, {}); EXPECT_CALL(*async_client_, startRaw(_, _, _, _)).WillOnce(Return(&async_stream_)); expectSendMessage("foo", {"x", "y"}, "", true); expectSendMessage("bar", {}, ""); grpc_mux_->start(); EXPECT_EQ(1, <API key>.value()); expectSendMessage("bar", {"z"}, ""); auto bar_z_sub = grpc_mux_->addWatch("bar", {"z"}, callbacks_, resource_decoder_, {}); expectSendMessage("bar", {"zz", "z"}, ""); auto bar_zz_sub = grpc_mux_->addWatch("bar", {"zz"}, callbacks_, resource_decoder_, {}); expectSendMessage("bar", {"z"}, ""); expectSendMessage("bar", {}, ""); expectSendMessage("foo", {}, ""); } // Validate behavior when dynamic context parameters are updated. TEST_F(GrpcMuxImplTest, <API key>) { setup(); InSequence s; auto foo_sub = grpc_mux_->addWatch("foo", {"x", "y"}, callbacks_, resource_decoder_, {}); auto bar_sub = grpc_mux_->addWatch("bar", {}, callbacks_, resource_decoder_, {}); EXPECT_CALL(*async_client_, startRaw(_, _, _, _)).WillOnce(Return(&async_stream_)); expectSendMessage("foo", {"x", "y"}, "", true); expectSendMessage("bar", {}, ""); grpc_mux_->start(); // Unknown type, shouldn't do anything. local_info_.context_provider_.update_cb_handler_.runCallbacks("baz"); // Update to foo type should resend Node. expectSendMessage("foo", {"x", "y"}, "", true); local_info_.context_provider_.update_cb_handler_.runCallbacks("foo"); // Update to bar type should resend Node. expectSendMessage("bar", {}, "", true); local_info_.context_provider_.update_cb_handler_.runCallbacks("bar"); // Adding a new foo resource to the watch shouldn't send Node. expectSendMessage("foo", {"z", "x", "y"}, ""); auto foo_z_sub = grpc_mux_->addWatch("foo", {"z"}, callbacks_, resource_decoder_, {}); expectSendMessage("foo", {"x", "y"}, ""); expectSendMessage("foo", {}, ""); } // Validate behavior when multiple type URL watches are maintained and the stream is reset. TEST_F(GrpcMuxImplTest, ResetStream) { InSequence s; auto* timer = new Event::MockTimer(&dispatcher_); // TTL timers. new Event::MockTimer(&dispatcher_); new Event::MockTimer(&dispatcher_); new Event::MockTimer(&dispatcher_); setup(); auto foo_sub = grpc_mux_->addWatch("foo", {"x", "y"}, callbacks_, resource_decoder_, {}); auto bar_sub = grpc_mux_->addWatch("bar", {}, callbacks_, resource_decoder_, {}); auto baz_sub = grpc_mux_->addWatch("baz", {"z"}, callbacks_, resource_decoder_, {}); EXPECT_CALL(*async_client_, startRaw(_, _, _, _)).WillOnce(Return(&async_stream_)); expectSendMessage("foo", {"x", "y"}, "", true); expectSendMessage("bar", {}, ""); expectSendMessage("baz", {"z"}, ""); grpc_mux_->start(); // Send another message for foo so that the node is cleared in the cached request. // This is to test that the node is set again in the first message below. expectSendMessage("foo", {"z", "x", "y"}, ""); auto foo_z_sub = grpc_mux_->addWatch("foo", {"z"}, callbacks_, resource_decoder_, {}); EXPECT_CALL(callbacks_, <API key>(Envoy::Config::<API key>::ConnectionFailure, _)) .Times(4); EXPECT_CALL(random_, random()); EXPECT_CALL(*timer, enableTimer(_, _)); grpc_mux_->grpcStreamForTest().onRemoteClose(Grpc::Status::WellKnownGrpcStatus::Canceled, ""); EXPECT_EQ(0, <API key>.value()); EXPECT_EQ(0, <API key>.value()); EXPECT_CALL(*async_client_, startRaw(_, _, _, _)).WillOnce(Return(&async_stream_)); expectSendMessage("foo", {"z", "x", "y"}, "", true); expectSendMessage("bar", {}, ""); expectSendMessage("baz", {"z"}, ""); expectSendMessage("foo", {"x", "y"}, ""); timer->invokeCallback(); expectSendMessage("baz", {}, ""); expectSendMessage("foo", {}, ""); } // Validate pause-resume behavior. TEST_F(GrpcMuxImplTest, PauseResume) { setup(); InSequence s; GrpcMuxWatchPtr foo_sub; GrpcMuxWatchPtr foo_z_sub; GrpcMuxWatchPtr foo_zz_sub; foo_sub = grpc_mux_->addWatch("foo", {"x", "y"}, callbacks_, resource_decoder_, {}); { ScopedResume a = grpc_mux_->pause("foo"); EXPECT_CALL(*async_client_, startRaw(_, _, _, _)).WillOnce(Return(&async_stream_)); grpc_mux_->start(); expectSendMessage("foo", {"x", "y"}, "", true); } { ScopedResume a = grpc_mux_->pause("bar"); expectSendMessage("foo", {"z", "x", "y"}, ""); foo_z_sub = grpc_mux_->addWatch("foo", {"z"}, callbacks_, resource_decoder_, {}); } { ScopedResume a = grpc_mux_->pause("foo"); foo_zz_sub = grpc_mux_->addWatch("foo", {"zz"}, callbacks_, resource_decoder_, {}); expectSendMessage("foo", {"zz", "z", "x", "y"}, ""); } // When nesting, we only have a single resumption. { ScopedResume a = grpc_mux_->pause("foo"); ScopedResume b = grpc_mux_->pause("foo"); foo_zz_sub = grpc_mux_->addWatch("foo", {"zz"}, callbacks_, resource_decoder_, {}); expectSendMessage("foo", {"zz", "z", "x", "y"}, ""); } grpc_mux_->pause("foo")->cancel(); } // Validate behavior when type URL mismatches occur. TEST_F(GrpcMuxImplTest, TypeUrlMismatch) { setup(); auto invalid_response = std::make_unique<envoy::service::discovery::v3::DiscoveryResponse>(); InSequence s; auto foo_sub = grpc_mux_->addWatch("foo", {"x", "y"}, callbacks_, resource_decoder_, {}); EXPECT_CALL(*async_client_, startRaw(_, _, _, _)).WillOnce(Return(&async_stream_)); expectSendMessage("foo", {"x", "y"}, "", true); grpc_mux_->start(); { auto response = std::make_unique<envoy::service::discovery::v3::DiscoveryResponse>(); response->set_type_url("bar"); response->set_version_info("bar-version"); grpc_mux_->grpcStreamForTest().onReceiveMessage(std::move(response)); } { invalid_response->set_type_url("foo"); invalid_response->set_version_info("foo-version"); invalid_response->mutable_resources()->Add()->set_type_url("bar"); EXPECT_CALL(callbacks_, <API key>(_, _)) .WillOnce(Invoke([](Envoy::Config::<API key>, const EnvoyException* e) { EXPECT_TRUE(IsSubstring( "", "", "bar does not match the message-wide type URL foo in DiscoveryResponse", e->what())); })); expectSendMessage( "foo", {"x", "y"}, "", false, "", Grpc::Status::WellKnownGrpcStatus::Internal, fmt::format("bar does not match the message-wide type URL foo in DiscoveryResponse {}", invalid_response->DebugString())); grpc_mux_->grpcStreamForTest().onReceiveMessage(std::move(invalid_response)); } expectSendMessage("foo", {}, ""); } TEST_F(GrpcMuxImplTest, <API key>) { setup(); auto invalid_response = std::make_unique<envoy::service::discovery::v3::DiscoveryResponse>(); InSequence s; auto foo_sub = grpc_mux_->addWatch("foo", {"x", "y"}, callbacks_, resource_decoder_, {}); EXPECT_CALL(*async_client_, startRaw(_, _, _, _)).WillOnce(Return(&async_stream_)); expectSendMessage("foo", {"x", "y"}, "", true); grpc_mux_->start(); { // Large error message sent back to management server is truncated. const std::string very_large_type_url(1 << 20, 'A'); invalid_response->set_type_url("foo"); invalid_response->set_version_info("invalid"); invalid_response->mutable_resources()->Add()->set_type_url(very_large_type_url); EXPECT_CALL(callbacks_, <API key>(_, _)) .WillOnce(Invoke([&very_large_type_url](Envoy::Config::<API key>, const EnvoyException* e) { EXPECT_TRUE(IsSubstring( "", "", fmt::format("{} does not match the message-wide type URL foo in DiscoveryResponse", very_large_type_url), // Local error message is not truncated. e->what())); })); expectSendMessage("foo", {"x", "y"}, "", false, "", Grpc::Status::WellKnownGrpcStatus::Internal, fmt::format("{}...(truncated)", std::string(4096, 'A'))); grpc_mux_->grpcStreamForTest().onReceiveMessage(std::move(invalid_response)); } expectSendMessage("foo", {}, ""); } envoy::service::discovery::v3::Resource heartbeatResource(std::chrono::milliseconds ttl, const std::string& name) { envoy::service::discovery::v3::Resource resource; resource.mutable_ttl()->CopyFrom(Protobuf::util::TimeUtil::<API key>(ttl.count())); resource.set_name(name); return resource; } envoy::service::discovery::v3::Resource resourceWithTtl(std::chrono::milliseconds ttl, envoy::config::endpoint::v3::<API key>& cla) { envoy::service::discovery::v3::Resource resource; resource.mutable_resource()->PackFrom(cla); resource.mutable_ttl()->CopyFrom(Protobuf::util::TimeUtil::<API key>(ttl.count())); resource.set_name(cla.cluster_name()); return resource; } // Validates the behavior when the TTL timer expires. TEST_F(GrpcMuxImplTest, ResourceTTL) { setup(); time_system_.setSystemTime(std::chrono::seconds(0)); TestUtility::<API key><envoy::config::endpoint::v3::<API key>> resource_decoder("cluster_name"); const std::string& type_url = Config::TypeUrl::get().<API key>; InSequence s; auto* ttl_timer = new Event::MockTimer(&dispatcher_); auto eds_sub = grpc_mux_->addWatch(type_url, {"x"}, callbacks_, resource_decoder, {}); EXPECT_CALL(*async_client_, startRaw(_, _, _, _)).WillOnce(Return(&async_stream_)); expectSendMessage(type_url, {"x"}, "", true); grpc_mux_->start(); { auto response = std::make_unique<envoy::service::discovery::v3::DiscoveryResponse>(); response->set_type_url(type_url); response->set_version_info("1"); envoy::config::endpoint::v3::<API key> load_assignment; load_assignment.set_cluster_name("x"); auto wrapped_resource = resourceWithTtl(std::chrono::milliseconds(1000), load_assignment); response->add_resources()->PackFrom(wrapped_resource); EXPECT_CALL(callbacks_, onConfigUpdate(_, "1")) .WillOnce(Invoke([](const std::vector<DecodedResourceRef>& resources, const std::string&) { EXPECT_EQ(1, resources.size()); })); EXPECT_CALL(*ttl_timer, enabled()); EXPECT_CALL(*ttl_timer, enableTimer(std::chrono::milliseconds(1000), _)); expectSendMessage(type_url, {"x"}, "1"); grpc_mux_->grpcStreamForTest().onReceiveMessage(std::move(response)); } // Increase the TTL. { auto response = std::make_unique<envoy::service::discovery::v3::DiscoveryResponse>(); response->set_type_url(type_url); response->set_version_info("1"); envoy::config::endpoint::v3::<API key> load_assignment; load_assignment.set_cluster_name("x"); auto wrapped_resource = resourceWithTtl(std::chrono::milliseconds(10000), load_assignment); response->add_resources()->PackFrom(wrapped_resource); EXPECT_CALL(callbacks_, onConfigUpdate(_, "1")) .WillOnce(Invoke([](const std::vector<DecodedResourceRef>& resources, const std::string&) { EXPECT_EQ(1, resources.size()); })); EXPECT_CALL(*ttl_timer, enabled()); EXPECT_CALL(*ttl_timer, enableTimer(std::chrono::milliseconds(10000), _)); // No update, just a change in TTL. expectSendMessage(type_url, {"x"}, "1"); grpc_mux_->grpcStreamForTest().onReceiveMessage(std::move(response)); } // Refresh the TTL with a heartbeat response. { auto response = std::make_unique<envoy::service::discovery::v3::DiscoveryResponse>(); response->set_type_url(type_url); response->set_version_info("1"); auto wrapped_resource = heartbeatResource(std::chrono::milliseconds(10000), "x"); response->add_resources()->PackFrom(wrapped_resource); EXPECT_CALL(*ttl_timer, enabled()); // No update, just a change in TTL. expectSendMessage(type_url, {"x"}, "1"); grpc_mux_->grpcStreamForTest().onReceiveMessage(std::move(response)); } // Remove the TTL. { auto response = std::make_unique<envoy::service::discovery::v3::DiscoveryResponse>(); response->set_type_url(type_url); response->set_version_info("1"); envoy::config::endpoint::v3::<API key> load_assignment; load_assignment.set_cluster_name("x"); response->add_resources()->PackFrom(load_assignment); EXPECT_CALL(callbacks_, onConfigUpdate(_, "1")) .WillOnce(Invoke([](const std::vector<DecodedResourceRef>& resources, const std::string&) { EXPECT_EQ(1, resources.size()); })); EXPECT_CALL(*ttl_timer, disableTimer()); expectSendMessage(type_url, {"x"}, "1"); grpc_mux_->grpcStreamForTest().onReceiveMessage(std::move(response)); } // Put the TTL back. { auto response = std::make_unique<envoy::service::discovery::v3::DiscoveryResponse>(); response->set_type_url(type_url); response->set_version_info("1"); envoy::config::endpoint::v3::<API key> load_assignment; load_assignment.set_cluster_name("x"); auto wrapped_resource = resourceWithTtl(std::chrono::milliseconds(10000), load_assignment); response->add_resources()->PackFrom(wrapped_resource); EXPECT_CALL(callbacks_, onConfigUpdate(_, "1")) .WillOnce(Invoke([](const std::vector<DecodedResourceRef>& resources, const std::string&) { EXPECT_EQ(1, resources.size()); })); EXPECT_CALL(*ttl_timer, enabled()); EXPECT_CALL(*ttl_timer, enableTimer(std::chrono::milliseconds(10000), _)); // No update, just a change in TTL. expectSendMessage(type_url, {"x"}, "1"); grpc_mux_->grpcStreamForTest().onReceiveMessage(std::move(response)); } time_system_.setSystemTime(std::chrono::seconds(11)); EXPECT_CALL(callbacks_, onConfigUpdate(_, _, "")) .WillOnce(Invoke([](auto, const auto& removed, auto) { EXPECT_EQ(1, removed.size()); EXPECT_EQ("x", removed.Get(0)); })); // Fire the TTL timer. EXPECT_CALL(*ttl_timer, disableTimer()); ttl_timer->invokeCallback(); expectSendMessage(type_url, {}, "1"); } // Checks that the control plane identifier is logged TEST_F(GrpcMuxImplTest, <API key>) { setup(); std::string type_url = "foo"; auto foo_sub = grpc_mux_->addWatch(type_url, {}, callbacks_, resource_decoder_, {}); EXPECT_CALL(*async_client_, startRaw(_, _, _, _)).WillOnce(Return(&async_stream_)); expectSendMessage(type_url, {}, "", true); grpc_mux_->start(); { auto response = std::make_unique<envoy::service::discovery::v3::DiscoveryResponse>(); response->set_type_url(type_url); response->set_version_info("1"); response-><API key>()->set_identifier("control_plane_ID"); EXPECT_CALL(callbacks_, onConfigUpdate(_, _)); expectSendMessage(type_url, {}, "1"); EXPECT_LOG_CONTAINS("debug", "for foo from control_plane_ID", grpc_mux_->grpcStreamForTest().onReceiveMessage(std::move(response))); } { auto response = std::make_unique<envoy::service::discovery::v3::DiscoveryResponse>(); response->set_type_url(type_url); response->set_version_info("2"); response-><API key>()->set_identifier("different_ID"); EXPECT_CALL(callbacks_, onConfigUpdate(_, _)); expectSendMessage(type_url, {}, "2"); EXPECT_LOG_CONTAINS("debug", "for foo from different_ID", grpc_mux_->grpcStreamForTest().onReceiveMessage(std::move(response))); } } // Validate behavior when watches has an unknown resource name. TEST_F(GrpcMuxImplTest, WildcardWatch) { setup(); InSequence s; const std::string& type_url = Config::TypeUrl::get().<API key>; TestUtility::<API key><envoy::config::endpoint::v3::<API key>> resource_decoder("cluster_name"); auto foo_sub = grpc_mux_->addWatch(type_url, {}, callbacks_, resource_decoder, {}); EXPECT_CALL(*async_client_, startRaw(_, _, _, _)).WillOnce(Return(&async_stream_)); expectSendMessage(type_url, {}, "", true); grpc_mux_->start(); { auto response = std::make_unique<envoy::service::discovery::v3::DiscoveryResponse>(); response->set_type_url(type_url); response->set_version_info("1"); envoy::config::endpoint::v3::<API key> load_assignment; load_assignment.set_cluster_name("x"); response->add_resources()->PackFrom(load_assignment); EXPECT_CALL(callbacks_, onConfigUpdate(_, "1")) .WillOnce(Invoke([&load_assignment](const std::vector<DecodedResourceRef>& resources, const std::string&) { EXPECT_EQ(1, resources.size()); const auto& expected_assignment = dynamic_cast<const envoy::config::endpoint::v3::<API key>&>( resources[0].get().resource()); EXPECT_TRUE(TestUtility::protoEqual(expected_assignment, load_assignment)); })); expectSendMessage(type_url, {}, "1"); grpc_mux_->grpcStreamForTest().onReceiveMessage(std::move(response)); } } // Validate behavior when watches specify resources (potentially overlapping). TEST_F(GrpcMuxImplTest, WatchDemux) { setup(); InSequence s; TestUtility::<API key><envoy::config::endpoint::v3::<API key>> resource_decoder("cluster_name"); const std::string& type_url = Config::TypeUrl::get().<API key>; NiceMock<<API key>> foo_callbacks; auto foo_sub = grpc_mux_->addWatch(type_url, {"x", "y"}, foo_callbacks, resource_decoder, {}); NiceMock<<API key>> bar_callbacks; auto bar_sub = grpc_mux_->addWatch(type_url, {"y", "z"}, bar_callbacks, resource_decoder, {}); EXPECT_CALL(*async_client_, startRaw(_, _, _, _)).WillOnce(Return(&async_stream_)); // Should dedupe the "x" resource. expectSendMessage(type_url, {"y", "z", "x"}, "", true); grpc_mux_->start(); { auto response = std::make_unique<envoy::service::discovery::v3::DiscoveryResponse>(); response->set_type_url(type_url); response->set_version_info("1"); envoy::config::endpoint::v3::<API key> load_assignment; load_assignment.set_cluster_name("x"); response->add_resources()->PackFrom(load_assignment); EXPECT_CALL(bar_callbacks, onConfigUpdate(_, "1")).Times(0); EXPECT_CALL(foo_callbacks, onConfigUpdate(_, "1")) .WillOnce(Invoke([&load_assignment](const std::vector<DecodedResourceRef>& resources, const std::string&) { EXPECT_EQ(1, resources.size()); const auto& expected_assignment = dynamic_cast<const envoy::config::endpoint::v3::<API key>&>( resources[0].get().resource()); EXPECT_TRUE(TestUtility::protoEqual(expected_assignment, load_assignment)); })); expectSendMessage(type_url, {"y", "z", "x"}, "1"); grpc_mux_->grpcStreamForTest().onReceiveMessage(std::move(response)); } { auto response = std::make_unique<envoy::service::discovery::v3::DiscoveryResponse>(); response->set_type_url(type_url); response->set_version_info("2"); envoy::config::endpoint::v3::<API key> load_assignment_x; load_assignment_x.set_cluster_name("x"); response->add_resources()->PackFrom(load_assignment_x); envoy::config::endpoint::v3::<API key> load_assignment_y; load_assignment_y.set_cluster_name("y"); response->add_resources()->PackFrom(load_assignment_y); envoy::config::endpoint::v3::<API key> load_assignment_z; load_assignment_z.set_cluster_name("z"); response->add_resources()->PackFrom(load_assignment_z); EXPECT_CALL(bar_callbacks, onConfigUpdate(_, "2")) .WillOnce(Invoke([&load_assignment_y, &load_assignment_z]( const std::vector<DecodedResourceRef>& resources, const std::string&) { EXPECT_EQ(2, resources.size()); const auto& expected_assignment = dynamic_cast<const envoy::config::endpoint::v3::<API key>&>( resources[0].get().resource()); EXPECT_TRUE(TestUtility::protoEqual(expected_assignment, load_assignment_y)); const auto& <API key> = dynamic_cast<const envoy::config::endpoint::v3::<API key>&>( resources[1].get().resource()); EXPECT_TRUE(TestUtility::protoEqual(<API key>, load_assignment_z)); })); EXPECT_CALL(foo_callbacks, onConfigUpdate(_, "2")) .WillOnce(Invoke([&load_assignment_x, &load_assignment_y]( const std::vector<DecodedResourceRef>& resources, const std::string&) { EXPECT_EQ(2, resources.size()); const auto& expected_assignment = dynamic_cast<const envoy::config::endpoint::v3::<API key>&>( resources[0].get().resource()); EXPECT_TRUE(TestUtility::protoEqual(expected_assignment, load_assignment_x)); const auto& <API key> = dynamic_cast<const envoy::config::endpoint::v3::<API key>&>( resources[1].get().resource()); EXPECT_TRUE(TestUtility::protoEqual(<API key>, load_assignment_y)); })); expectSendMessage(type_url, {"y", "z", "x"}, "2"); grpc_mux_->grpcStreamForTest().onReceiveMessage(std::move(response)); } expectSendMessage(type_url, {"x", "y"}, "2"); expectSendMessage(type_url, {}, "2"); } // Validate behavior when we have multiple watchers that send empty updates. TEST_F(GrpcMuxImplTest, <API key>) { setup(); InSequence s; const std::string& type_url = Config::TypeUrl::get().<API key>; NiceMock<<API key>> foo_callbacks; auto foo_sub = grpc_mux_->addWatch(type_url, {"x", "y"}, foo_callbacks, resource_decoder_, {}); EXPECT_CALL(*async_client_, startRaw(_, _, _, _)).WillOnce(Return(&async_stream_)); expectSendMessage(type_url, {"x", "y"}, "", true); grpc_mux_->start(); auto response = std::make_unique<envoy::service::discovery::v3::DiscoveryResponse>(); response->set_type_url(type_url); response->set_version_info("1"); EXPECT_CALL(foo_callbacks, onConfigUpdate(_, "1")).Times(0); expectSendMessage(type_url, {"x", "y"}, "1"); grpc_mux_->grpcStreamForTest().onReceiveMessage(std::move(response)); expectSendMessage(type_url, {}, "1"); } // Validate behavior when we have Single Watcher that sends Empty updates. TEST_F(GrpcMuxImplTest, <API key>) { setup(); const std::string& type_url = Config::TypeUrl::get().Cluster; NiceMock<<API key>> foo_callbacks; auto foo_sub = grpc_mux_->addWatch(type_url, {}, foo_callbacks, resource_decoder_, {}); EXPECT_CALL(*async_client_, startRaw(_, _, _, _)).WillOnce(Return(&async_stream_)); expectSendMessage(type_url, {}, "", true); grpc_mux_->start(); auto response = std::make_unique<envoy::service::discovery::v3::DiscoveryResponse>(); response->set_type_url(type_url); response->set_version_info("1"); // Validate that onConfigUpdate is called with empty resources. EXPECT_CALL(foo_callbacks, onConfigUpdate(_, "1")) .WillOnce(Invoke([](const std::vector<DecodedResourceRef>& resources, const std::string&) { EXPECT_TRUE(resources.empty()); })); expectSendMessage(type_url, {}, "1"); grpc_mux_->grpcStreamForTest().onReceiveMessage(std::move(response)); } // Exactly one test requires a mock time system to provoke behavior that cannot // easily be achieved with a SimulatedTimeSystem. class <API key> : public GrpcMuxImplTestBase { public: Event::<API key><MockTimeSystem> mock_time_system_; }; // Verifies that rate limiting is not enforced with defaults. TEST_F(<API key>, <API key>) { auto ttl_timer = new Event::MockTimer(&dispatcher_); // Retry timer, new Event::MockTimer(&dispatcher_); // Validate that rate limiter is not created. EXPECT_CALL(*mock_time_system_, monotonicTime()).Times(0); setup(); EXPECT_CALL(async_stream_, sendMessageRaw_(_, false)).Times(AtLeast(99)); EXPECT_CALL(*async_client_, startRaw(_, _, _, _)).WillOnce(Return(&async_stream_)); const auto onReceiveMessage = [&](uint64_t burst) { for (uint64_t i = 0; i < burst; i++) { auto response = std::make_unique<envoy::service::discovery::v3::DiscoveryResponse>(); response->set_version_info("baz"); response->set_nonce("bar"); response->set_type_url("foo"); EXPECT_CALL(*ttl_timer, disableTimer()); grpc_mux_->grpcStreamForTest().onReceiveMessage(std::move(response)); } }; auto foo_sub = grpc_mux_->addWatch("foo", {"x"}, callbacks_, resource_decoder_, {}); expectSendMessage("foo", {"x"}, "", true); grpc_mux_->start(); // Exhausts the limit. onReceiveMessage(99); // API calls go over the limit but we do not see the stat incremented. onReceiveMessage(1); EXPECT_EQ(0, stats_.counter("control_plane.rate_limit_enforced").value()); } // Verifies that default rate limiting is enforced with empty RateLimitSettings. TEST_F(GrpcMuxImplTest, <API key>) { // Validate that request drain timer is created. auto ttl_timer = new Event::MockTimer(&dispatcher_); Event::MockTimer* drain_request_timer = new Event::MockTimer(&dispatcher_); Event::MockTimer* retry_timer = new Event::MockTimer(&dispatcher_); RateLimitSettings <API key>; <API key>.enabled_ = true; setup(<API key>); // Attempt to send 99 messages. One of them is rate limited (and we never drain). EXPECT_CALL(async_stream_, sendMessageRaw_(_, false)).Times(99); EXPECT_CALL(*async_client_, startRaw(_, _, _, _)).WillOnce(Return(&async_stream_)); const auto onReceiveMessage = [&](uint64_t burst) { for (uint64_t i = 0; i < burst; i++) { auto response = std::make_unique<envoy::service::discovery::v3::DiscoveryResponse>(); response->set_version_info("baz"); response->set_nonce("bar"); response->set_type_url("foo"); EXPECT_CALL(*ttl_timer, disableTimer()); grpc_mux_->grpcStreamForTest().onReceiveMessage(std::move(response)); } }; auto foo_sub = grpc_mux_->addWatch("foo", {"x"}, callbacks_, resource_decoder_, {}); expectSendMessage("foo", {"x"}, "", true); grpc_mux_->start(); // Validate that drain_request_timer is enabled when there are no tokens. EXPECT_CALL(*drain_request_timer, enableTimer(std::chrono::milliseconds(100), _)); // The drain timer enable is checked twice, once when we limit, again when the watch is destroyed. EXPECT_CALL(*drain_request_timer, enabled()).Times(11); onReceiveMessage(110); EXPECT_EQ(11, stats_.counter("control_plane.rate_limit_enforced").value()); EXPECT_EQ(11, <API key>.value()); // Validate that when we reset a stream with pending requests, it reverts back to the initial // query (i.e. the queue is discarded). EXPECT_CALL(callbacks_, <API key>(Envoy::Config::<API key>::ConnectionFailure, _)); EXPECT_CALL(random_, random()); EXPECT_CALL(*retry_timer, enableTimer(_, _)); grpc_mux_->grpcStreamForTest().onRemoteClose(Grpc::Status::WellKnownGrpcStatus::Canceled, ""); EXPECT_EQ(11, <API key>.value()); EXPECT_EQ(0, <API key>.value()); EXPECT_CALL(async_stream_, sendMessageRaw_(_, false)); EXPECT_CALL(*async_client_, startRaw(_, _, _, _)).WillOnce(Return(&async_stream_)); time_system_.setMonotonicTime(std::chrono::seconds(30)); retry_timer->invokeCallback(); EXPECT_EQ(0, <API key>.value()); // One more message on the way out when the watch is destroyed. EXPECT_CALL(async_stream_, sendMessageRaw_(_, false)); } // Verifies that rate limiting is enforced with custom RateLimitSettings. TEST_F(GrpcMuxImplTest, <API key>) { // Validate that request drain timer is created. // TTL timer. auto ttl_timer = new Event::MockTimer(&dispatcher_); Event::MockTimer* drain_request_timer = new Event::MockTimer(&dispatcher_); // Retry timer. new Event::MockTimer(&dispatcher_); RateLimitSettings <API key>; <API key>.enabled_ = true; <API key>.max_tokens_ = 250; <API key>.fill_rate_ = 2; setup(<API key>); EXPECT_CALL(async_stream_, sendMessageRaw_(_, false)).Times(AtLeast(260)); EXPECT_CALL(*async_client_, startRaw(_, _, _, _)).WillOnce(Return(&async_stream_)); const auto onReceiveMessage = [&](uint64_t burst) { for (uint64_t i = 0; i < burst; i++) { auto response = std::make_unique<envoy::service::discovery::v3::DiscoveryResponse>(); response->set_version_info("baz"); response->set_nonce("bar"); response->set_type_url("foo"); EXPECT_CALL(*ttl_timer, disableTimer()); grpc_mux_->grpcStreamForTest().onReceiveMessage(std::move(response)); } }; auto foo_sub = grpc_mux_->addWatch("foo", {"x"}, callbacks_, resource_decoder_, {}); expectSendMessage("foo", {"x"}, "", true); grpc_mux_->start(); // Validate that rate limit is not enforced for 100 requests. onReceiveMessage(100); EXPECT_EQ(0, stats_.counter("control_plane.rate_limit_enforced").value()); // Validate that drain_request_timer is enabled when there are no tokens. EXPECT_CALL(*drain_request_timer, enableTimer(std::chrono::milliseconds(500), _)); EXPECT_CALL(*drain_request_timer, enabled()).Times(11); onReceiveMessage(160); EXPECT_EQ(11, stats_.counter("control_plane.rate_limit_enforced").value()); EXPECT_EQ(11, <API key>.value()); // Validate that drain requests call when there are multiple requests in queue. time_system_.setMonotonicTime(std::chrono::seconds(10)); drain_request_timer->invokeCallback(); // Check that the pending_requests stat is updated with the queue drain. EXPECT_EQ(0, <API key>.value()); } // Verifies that a message with no resources is accepted. TEST_F(GrpcMuxImplTest, <API key>) { setup(); EXPECT_CALL(*async_client_, startRaw(_, _, _, _)).WillOnce(Return(&async_stream_)); const std::string& type_url = Config::TypeUrl::get().<API key>; grpc_mux_->start(); { // subscribe and unsubscribe to simulate a cluster added and removed expectSendMessage(type_url, {"y"}, "", true); auto temp_sub = grpc_mux_->addWatch(type_url, {"y"}, callbacks_, resource_decoder_, {}); expectSendMessage(type_url, {}, ""); } // simulate the server sending empty CLA message to notify envoy that the CLA was removed. auto response = std::make_unique<envoy::service::discovery::v3::DiscoveryResponse>(); response->set_nonce("bar"); response->set_version_info("1"); response->set_type_url(type_url); // TODO(fredlas) the expectation of no discovery request here is against the xDS spec. // The upcoming xDS overhaul (part of/followup to PR7293) will fix this. // This contains zero resources. No discovery request should be sent. grpc_mux_->grpcStreamForTest().onReceiveMessage(std::move(response)); // when we add the new subscription version should be 1 and nonce should be bar expectSendMessage(type_url, {"x"}, "1", false, "bar"); // simulate a new cluster x is added. add CLA subscription for it. auto sub = grpc_mux_->addWatch(type_url, {"x"}, callbacks_, resource_decoder_, {}); expectSendMessage(type_url, {}, "1", false, "bar"); } // Verifies that a message with some resources is rejected when there are no watches. TEST_F(GrpcMuxImplTest, <API key>) { setup(); EXPECT_CALL(*async_client_, startRaw(_, _, _, _)).WillOnce(Return(&async_stream_)); const std::string& type_url = Config::TypeUrl::get().<API key>; grpc_mux_->start(); // subscribe and unsubscribe (by not keeping the return watch) so that the type is known to envoy expectSendMessage(type_url, {"y"}, "", true); expectSendMessage(type_url, {}, ""); grpc_mux_->addWatch(type_url, {"y"}, callbacks_, resource_decoder_, {}); // simulate the server sending CLA message to notify envoy that the CLA was added, // even though envoy doesn't expect it. Envoy should reject this update. auto response = std::make_unique<envoy::service::discovery::v3::DiscoveryResponse>(); response->set_nonce("bar"); response->set_version_info("1"); response->set_type_url(type_url); envoy::config::endpoint::v3::<API key> load_assignment; load_assignment.set_cluster_name("x"); response->add_resources()->PackFrom(load_assignment); // The message should be rejected. expectSendMessage(type_url, {}, "", false, "bar"); EXPECT_LOG_CONTAINS("warning", "Ignoring unwatched type URL " + type_url, grpc_mux_->grpcStreamForTest().onReceiveMessage(std::move(response))); } TEST_F(GrpcMuxImplTest, <API key>) { EXPECT_CALL(local_info_, clusterName()).WillOnce(ReturnRef(EMPTY_STRING)); <API key>( GrpcMuxImpl( local_info_, std::unique_ptr<Grpc::MockAsyncClient>(async_client_), dispatcher_, *Protobuf::DescriptorPool::generated_pool()->FindMethodByName( "envoy.service.discovery.v3.<API key>.<API key>"), random_, stats_, <API key>, true), EnvoyException, "ads: node 'id' and 'cluster' are required. Set it either in 'node' config or via " "--service-node and --service-cluster options."); } TEST_F(GrpcMuxImplTest, <API key>) { EXPECT_CALL(local_info_, nodeName()).WillOnce(ReturnRef(EMPTY_STRING)); <API key>( GrpcMuxImpl( local_info_, std::unique_ptr<Grpc::MockAsyncClient>(async_client_), dispatcher_, *Protobuf::DescriptorPool::generated_pool()->FindMethodByName( "envoy.service.discovery.v3.<API key>.<API key>"), random_, stats_, <API key>, true), EnvoyException, "ads: node 'id' and 'cluster' are required. Set it either in 'node' config or via " "--service-node and --service-cluster options."); } } // namespace } // namespace Config } // namespace Envoy
<!DOCTYPE HTML> <html> <head> <meta http-equiv="Content-type" content="text/html; charset=utf-8"> <title>Hovercards6 user</title> <script src="http://platform.twitter.com/anywhere.js?id=[API]&amp;v=1" type="text/javascript"></script> </head> <body> @twitterapi <br> <img src="./twitter4j.png" id="image" alt="t4j_news"/> <script type="text/javascript"> twttr.anywhere(function (T) { T.hovercards(); T("#image").hovercards( {username: function(node){return node.alt}}); }); </script> </body> </html>
package com.netwebx.hackerrank.rpc.client; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; import java.net.InetSocketAddress; import java.net.Socket; public class RpcImporter<S> { public S importer(final Class<?> serviceClass, final InetSocketAddress addr) { return (S) Proxy.newProxyInstance( serviceClass.getClassLoader(), new Class<?>[]{serviceClass.getInterfaces()[0]}, new InvocationHandler() { @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { Socket socket = null; ObjectOutputStream output = null; ObjectInputStream input = null; try { socket = new Socket(); socket.connect(addr); output = new ObjectOutputStream(socket.getOutputStream()); output.writeUTF(serviceClass.getName()); output.writeUTF(method.getName()); output.writeObject(method.getParameterTypes()); output.writeObject(args); input = new ObjectInputStream(socket.getInputStream()); return input.readObject(); } finally { if (socket != null) { socket.close(); } if (output != null) { output.close(); } if (input != null) { input.close(); } } } } ); } }
require 'adrian/queue' require 'fileutils' module Adrian class DirectoryQueue < Adrian::Queue include Filters def self.create(options = {}) queue = new(options) FileUtils.mkdir_p(queue.available_path) FileUtils.mkdir_p(queue.reserved_path) queue end attr_reader :available_path, :reserved_path, :logger # Note: # There is the possibility of an item being consumed by multiple processes when its still in the queue after its lock expires. # The reason for allowing this is: # 1. It's much simpler than introducing a seperate monitoring process to handle lock expiry. # 2. This is an acceptable and rare event. e.g. it only happens when the process working on the item crashes without being able to release the lock def initialize(options = {}) super @available_path = options.fetch(:path) @reserved_path = options.fetch(:reserved_path, <API key>) @logger = options[:logger] filters << Filters::FileLock.new(:duration => options[:lock_duration], :reserved_path => reserved_path) filters << Filters::Delay.new(:duration => options[:delay]) if options[:delay] end def pop_item items.each do |item| return item if reserve(item) end nil end def push_item(value) item = wrap_item(value) item.move(available_path) item.touch self end def length available_files.count { |file| File.file?(file) } end def include?(value) item = wrap_item(value) items.include?(item) end protected def wrap_item(value) item = value.is_a?(FileItem) ? value : FileItem.new(value) item.logger ||= logger item end def reserve(item) item.move(reserved_path) item.touch true rescue Errno::ENOENT => e false end def items items = files.map { |file| wrap_item(file) } items.reject! { |item| !item.exist? || filter?(item) } items.sort_by(&:updated_at) end def files (available_files + reserved_files).select { |file| File.file?(file) } end def available_files
// SERVER-4516 and SERVER-6913: test that update and findAndModify tolerate // an _id in the update document, as long as the _id will not be modified var t = db.jstests_server4516; var startingDoc = {_id: 1, a: 1}; function prepare() { t.drop(); t.save(startingDoc); } function update_succeeds(updateDoc, qid, resultDoc) { prepare(); t.update({_id: qid}, updateDoc, true); assert.eq(t.findOne({_id: qid}), resultDoc); prepare(); t.findAndModify({query: {_id: qid}, update: updateDoc, upsert: true}); assert.eq(t.findOne({_id: qid}), resultDoc); } update_succeeds({_id: 1, a: 2}, 1, {_id: 1, a: 2}); update_succeeds({$set: {_id: 1}}, 1, {_id: 1, a: 1}); update_succeeds({_id: 1, b: "a"}, 1, {_id: 1, b: "a"}); update_succeeds({_id: 2, a: 3}, 2, {_id: 2, a: 3}); function update_fails(updateDoc, qid) { prepare(); var res = t.update({_id: qid}, updateDoc, true); assert.writeError(res); assert.eq(t.count(), 1); assert.eq(t.findOne(), startingDoc); prepare(); assert.throws(function() { t.findAndModify({query: {_id: qid}, update: updateDoc, upsert: true}); }); assert.eq(t.count(), 1); assert.eq(t.findOne(), startingDoc); } update_fails({$set: {_id: 2}}, 1); update_fails({_id: 2, a: 3}, 1); update_fails({_id: 2, a: 3}, 3);
package com.oath.cyclops.internal.stream.spliterators.push; import com.oath.cyclops.types.persistent.<API key>; import java.util.Collection; import java.util.concurrent.TimeUnit; import java.util.function.Consumer; import java.util.function.Function; import java.util.function.Supplier; public class <API key><T,C extends <API key><? super T>,R> extends BaseOperator<T,R> { private final Supplier<? extends C> factory; private final Function<? super C, ? extends R> finalizer; private final long time; private final TimeUnit t; public <API key>(Operator<T> source, Supplier<? extends C> factory, Function<? super C, ? extends R> finalizer,long time, TimeUnit t){ super(source); this.factory = factory; this.finalizer = finalizer; this.time = time; this.t = t; } @Override public StreamSubscription subscribe(Consumer<? super R> onNext, Consumer<? super Throwable> onError, Runnable onComplete) { long toRun = t.toNanos(time); <API key>[] next = {factory.get()}; long[] start ={System.nanoTime()}; StreamSubscription[] upstream = {null}; StreamSubscription sub = new StreamSubscription(){ @Override public void request(long n) { if(n<=0) { onError.accept(new <API key>("3.9 While the Subscription is not cancelled, Subscription.request(long n) MUST throw a java.lang.<API key> if the argument is <= 0.")); return; } if(!isOpen) return; super.request(n); upstream[0].request(n); } @Override public void cancel() { upstream[0].cancel(); super.cancel(); } }; upstream[0] = source.subscribe(e-> { try { next[0] = next[0].plus(e); if(System.nanoTime()-start[0] > toRun){ onNext.accept(finalizer.apply((C)next[0])); sub.requested.decrementAndGet(); next[0] = factory.get(); start[0] = System.nanoTime(); } else{ request( upstream,1l); } } catch (Throwable t) { onError.accept(t); } } ,t->{onError.accept(t); sub.requested.decrementAndGet(); if(sub.isActive()) request( upstream,1); },()->{ if(next[0].size()>0) { try { onNext.accept(finalizer.apply((C) next[0])); } catch(Throwable t){ onError.accept(t); } sub.requested.decrementAndGet(); } sub.cancel(); onComplete.run(); }); return sub; } @Override public void subscribeAll(Consumer<? super R> onNext, Consumer<? super Throwable> onError, Runnable onCompleteDs) { long toRun = t.toNanos(time); <API key>[] next = {factory.get()}; long[] start ={System.nanoTime()}; source.subscribeAll(e-> { try { next[0] = next[0].plus(e); if(System.nanoTime()-start[0] > toRun){ onNext.accept(finalizer.apply((C)next[0])); next[0] = factory.get(); start[0] = System.nanoTime(); } } catch (Throwable t) { onError.accept(t); } } ,onError,()->{ if(next[0].size()>0) { try { onNext.accept(finalizer.apply((C) next[0])); } catch(Throwable t){ onError.accept(t); } } onCompleteDs.run(); }); } }
package net.tcp.socket; import java.io.DataOutputStream; import java.io.IOException; import java.net.ServerSocket; import java.net.Socket; /** * 1 ServerSocket(int port) 2 3+ * */ public class Server { /** * @param args * @throws IOException */ public static void main(String[] args) throws IOException { // 1 ServerSocket(int port) ServerSocket server = new ServerSocket(8888); while (true) { Socket socket = server.accept(); System.out.println(""); String msg = ""; /* * BufferedWriter bw = new BufferedWriter( new OutputStreamWriter( * socket.getOutputStream())); * * bw.write(msg); bw.newLine(); bw.flush(); */ DataOutputStream dos = new DataOutputStream(socket.getOutputStream()); dos.writeUTF(msg); dos.flush(); } } }
package org.neo4j.management.impl; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.Hashtable; import java.util.List; import java.util.<API key>; import javax.management.<API key>; import javax.management.<API key>; import javax.management.ObjectInstance; import javax.management.ObjectName; import org.neo4j.jmx.ManagementInterface; /** * Does not have any public methods - since the public interface of * {@link org.neo4j.management.Neo4jManager} should be defined completely in * that class. * * Does not have any (direct or transitive) dependencies on any part of the jmx * component - since this class is used in * {@link org.neo4j.management.impl.jconsole.Neo4jPlugin the JConsole plugin}, * and the jmx component is not on the class path in JConsole. * * @author Tobias Ivarsson <tobias.ivarsson@neotechnology.com> */ public abstract class KernelProxy { static final String KERNEL_BEAN_TYPE = "org.neo4j.jmx.Kernel"; protected static final String KERNEL_BEAN_NAME = "Kernel"; static final String MBEAN_QUERY = "MBeanQuery"; protected final <API key> server; protected final ObjectName kernel; protected KernelProxy( <API key> server, ObjectName kernel ) { String className = null; try { className = server.getMBeanInfo( kernel ).getClassName(); } catch ( Exception e ) { // fall through } if ( !KERNEL_BEAN_TYPE.equals( className ) ) { throw new <API key>( "The specified ObjectName does not represent a Neo4j Kernel bean in the specified MBean server." ); } this.server = server; this.kernel = kernel; } protected List<Object> allBeans() { List<Object> beans = new ArrayList<Object>(); Iterable<ObjectInstance> mbeans; try { mbeans = server.queryMBeans( mbeanQuery(), null ); } catch ( IOException handled ) { return beans; } for ( ObjectInstance instance : mbeans ) { String className = instance.getClassName(); Class<?> beanType = null; try { if ( className != null ) beanType = Class.forName( className ); } catch ( Exception ignored ) { // fall through } catch ( LinkageError ignored ) { // fall through } if ( beanType != null ) { try { beans.add( BeanProxy.load( server, beanType, instance.getObjectName() ) ); } catch ( Exception ignored ) { // fall through } } } return beans; } private ObjectName assertExists( ObjectName name ) { try { if ( !server.queryNames( name, null ).isEmpty() ) { return name; } } catch ( IOException handled ) { // fall through } throw new <API key>( "No MBeans matching " + name ); } protected <T> T getBean( Class<T> beanInterface ) { return BeanProxy.load( server, beanInterface, createObjectName( beanInterface ) ); } protected <T> Collection<T> getBeans( Class<T> beanInterface ) { return BeanProxy.loadAll( server, beanInterface, <API key>( beanInterface ) ); } private ObjectName <API key>( Class<?> beanInterface ) { return <API key>( mbeanQuery(), beanInterface ); } private ObjectName createObjectName( Class<?> beanInterface ) { return assertExists( createObjectName( mbeanQuery(), beanInterface ) ); } protected ObjectName createObjectName( String beanName ) { return assertExists( createObjectName( mbeanQuery(), beanName, false ) ); } protected ObjectName mbeanQuery() { try { return (ObjectName) server.getAttribute( kernel, MBEAN_QUERY ); } catch ( Exception cause ) { throw new <API key>( "Could not get MBean query.", cause ); } } protected static ObjectName createObjectName( String kernelIdentifier, Class<?> beanInterface ) { return createObjectName( kernelIdentifier, beanName( beanInterface ) ); } protected static ObjectName createObjectName( String kernelIdentifier, String beanName, String... extraNaming ) { Hashtable<String, String> properties = new Hashtable<String, String>(); properties.put( "instance", "kernel#" + kernelIdentifier ); return createObjectName( "org.neo4j", properties, beanName, false, extraNaming ); } static ObjectName <API key>( String kernelIdentifier, String beanName, String... extraNaming ) { Hashtable<String, String> properties = new Hashtable<String, String>(); properties.put( "instance", "kernel#" + kernelIdentifier ); return createObjectName( "org.neo4j", properties, beanName, true, extraNaming ); } static ObjectName createObjectName( ObjectName query, Class<?> beanInterface ) { return createObjectName( query, beanName( beanInterface ), false ); } static ObjectName <API key>( ObjectName query, Class<?> beanInterface ) { return createObjectName( query, beanName( beanInterface ), true ); } private static ObjectName createObjectName( ObjectName query, String beanName, boolean isQuery ) { Hashtable<String, String> properties = new Hashtable<String, String>(query.getKeyPropertyList()); return createObjectName( query.getDomain(), properties, beanName, isQuery ); } static String beanName( Class<?> beanInterface ) { if ( beanInterface.isInterface() ) { ManagementInterface management = beanInterface.getAnnotation( ManagementInterface.class ); if ( management != null ) { return management.name(); } } throw new <API key>( beanInterface + " is not a Neo4j Management Been interface" ); } private static ObjectName createObjectName( String domain, Hashtable<String, String> properties, String beanName, boolean query, String... extraNaming ) { properties.put( "name", beanName ); for ( int i = 0; i < extraNaming.length; i++ ) { properties.put( "name" + i, extraNaming[i] ); } ObjectName result; try { result = new ObjectName( domain, properties ); if ( query ) result = ObjectName.getInstance( result.toString() + ",*" ); } catch ( <API key> e ) { return null; } return result; } }
<div class="contanier"> <div class="link right"> <span></span> <a href=" <a href=" </div> <div class="logo"> <img src="../img/talk_bg.png" alt=""> <span></span> </div> </div>
# AUTOGENERATED FILE FROM balenalib/<API key>:disco-build ENV NODE_VERSION 10.23.1 ENV YARN_VERSION 1.22.4 RUN for key in \ <API key> \ ; do \ gpg --keyserver pgp.mit.edu --recv-keys "$key" || \ gpg --keyserver keyserver.pgp.com --recv-keys "$key" || \ gpg --keyserver ha.pool.sks-keyservers.net --recv-keys "$key" ; \ done \ && curl -SLO "http://nodejs.org/dist/v$NODE_VERSION/node-v$<API key>.tar.gz" \ && echo "<SHA256-like> node-v$<API key>.tar.gz" | sha256sum -c - \ && tar -xzf "node-v$<API key>.tar.gz" -C /usr/local --strip-components=1 \ && rm "node-v$<API key>.tar.gz" \ && curl -fSLO --compressed "https://yarnpkg.com/downloads/$YARN_VERSION/yarn-v$YARN_VERSION.tar.gz" \ && curl -fSLO --compressed "https://yarnpkg.com/downloads/$YARN_VERSION/yarn-v$YARN_VERSION.tar.gz.asc" \ && gpg --batch --verify yarn-v$YARN_VERSION.tar.gz.asc yarn-v$YARN_VERSION.tar.gz \ && mkdir -p /opt/yarn \ && tar -xzf yarn-v$YARN_VERSION.tar.gz -C /opt/yarn --strip-components=1 \ && ln -s /opt/yarn/bin/yarn /usr/local/bin/yarn \ && ln -s /opt/yarn/bin/yarn /usr/local/bin/yarnpkg \ && rm yarn-v$YARN_VERSION.tar.gz.asc yarn-v$YARN_VERSION.tar.gz \ && npm config set unsafe-perm true -g --unsafe-perm \
package de.mhus.cha.cao.action; import java.io.File; import de.mhus.lib.cao.CaoElement; import de.mhus.lib.cao.CaoException; import de.mhus.lib.cao.CaoList; import de.mhus.lib.cao.CaoMonitor; import de.mhus.lib.cao.CaoOperation; import de.mhus.cap.core.Access; import de.mhus.cha.cao.ChaConnection; import de.mhus.cha.cao.ChaElement; import de.mhus.lib.MFile; import de.mhus.lib.form.MForm; import de.mhus.lib.form.annotations.FormElement; import de.mhus.lib.form.annotations.FormSortId; @FormElement("name='cha_copy_to_folder' title='Copy'") public class CopyToOperation extends CaoOperation implements MForm { private CaoList<Access> sources; private ChaElement target; private ChaConnection connection; public CopyToOperation(ChaElement ChaElement) { target = ChaElement; } @Override public void dispose() throws CaoException { } @Override public void execute() throws CaoException { connection = (ChaConnection)target.getConnection(); //collect all affected entries monitor.beginTask("count", CaoMonitor.UNKNOWN); int cnt = 0; for (CaoElement<Access> element : sources.getElements()) { cnt = count( ((ChaElement)element).getFile(), cnt ); } monitor.beginTask("copy", cnt); cnt = 0; for (CaoElement<Access> element : sources.getElements()) { cnt = copy( target.getFile(), ((ChaElement)element).getFile(), cnt ); } } private int copy(File target, File file, int cnt) { // validate action if (monitor.isCanceled()) return cnt; if ( !file.isDirectory()) return cnt; // for secure // new path File newTarget = null; cnt++; monitor.worked(cnt); newTarget = new File(target,connection.createUID()); monitor.log().debug("Create Dir: " + newTarget.getAbsolutePath()); monitor.subTask(file.getAbsolutePath()); // validate path if ( newTarget.exists() ) { monitor.log().warn("Folder already exists: " + newTarget.getAbsolutePath()); return cnt; } // create if ( ! newTarget.mkdir() ) { newTarget = null; monitor.log().warn("Can't create folder: " + target.getAbsolutePath() + "/" + file.getName()); return cnt; } // set id connection.addIdPath(newTarget.getName(), newTarget.getAbsolutePath()); // events connection.fireElementCreated(newTarget.getName()); connection.fireElementLink(target.getName(), newTarget.getName()); // copy files for ( File sub : file.listFiles()) { if (sub.isFile()) { monitor.log().debug("Copy File: " + file.getAbsolutePath()); File targetFile = new File(target,file.getName()); if (targetFile.exists()) { monitor.log().warn("Can't overwrite file: " + file.getAbsolutePath()); } else if ( !MFile.copyFile(file, targetFile) ) { monitor.log().warn("Can't copy file: " + file.getAbsolutePath()); } } } // copy sub folders for ( File sub : file.listFiles(connection.<API key>())) { cnt = copy(newTarget, sub,cnt); } return cnt; } private int count(File file, int cnt) { if (monitor.isCanceled()) return cnt; if ( file.isDirectory() ) cnt++; if (!file.isDirectory()) return cnt; // for secure for ( File sub : file.listFiles(connection.<API key>())) { cnt = count(sub,cnt); } return cnt; } @Override public void initialize() throws CaoException { } public void setSources(CaoList<Access> list) { sources = list; } }
package jp.hashiwa.elasticsearch.authplugin; import org.apache.logging.log4j.Logger; import org.elasticsearch.client.node.NodeClient; import org.elasticsearch.common.bytes.BytesArray; import org.elasticsearch.common.bytes.BytesReference; import org.elasticsearch.common.logging.Loggers; import org.elasticsearch.rest.*; import java.util.*; import java.util.regex.Pattern; import java.util.stream.Stream; public class AuthRestHandler implements RestHandler { private final Logger logger = Loggers.getLogger(AuthRestHandler.class); private final RestHandler originalHandler; private final RestResponse <API key> = new RestResponse() { @Override public String contentType() { return "application/json"; } @Override public BytesReference content() { return new BytesArray(""); } @Override public RestStatus status() { return RestStatus.UNAUTHORIZED; } }; private final Map<RestRequest.Method, Stream<Pattern>> authPatterns = new HashMap<RestRequest.Method, Stream<Pattern>>() { { this.put(RestRequest.Method.POST, Stream.of( Pattern.compile("^/testindex(/.*)?$") )); this.put(RestRequest.Method.PUT, Stream.of( Pattern.compile("^/testindex(/.*)?$") )); // all methods this.put(null, Stream.of( Pattern.compile("^/adminindex(/.*)?$") )); } }; AuthRestHandler(RestHandler restHandler) { this.originalHandler = restHandler; } @Override public void handleRequest(RestRequest restRequest, RestChannel restChannel, NodeClient nodeClient) throws Exception { this.logger.debug(restRequest.path()); this.logger.debug(restRequest.rawPath()); if (isOk(restRequest)) { this.originalHandler.handleRequest(restRequest, restChannel, nodeClient); } else { restChannel.sendResponse(<API key>); } } private boolean needAuth(RestRequest.Method method, String path) { if (authPatterns.containsKey(method)) { Stream<Pattern> patterns = authPatterns.get(method); boolean match = patterns.anyMatch( p -> p.matcher(path).matches() ); return match; } return false; } private boolean isOk(RestRequest restRequest) { RestRequest.Method method = restRequest.method(); String path = restRequest.path(); // use rawpath() ? boolean needAuth = needAuth(method, path) || needAuth(null, path); if (! needAuth) { return true; } for (java.util.Map.Entry<String, String> entry: restRequest.headers()) { String key = entry.getKey(); String value = entry.getValue(); if (key.equals("user") && value.equals("admin")) { return true; } } return false; // ES 5.4 // return restRequest.getHeaders().get("user").equals("admin"); } }
#pragma once #include "il2cpp-config.h" #ifndef _MSC_VER # include <alloca.h> #else # include <malloc.h> #endif #include <stdint.h> // System.Object struct Il2CppObject; // System.IAsyncResult struct <API key>; // System.AsyncCallback struct <API key>; #include "<API key>.h" #include "<API key>.h" #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Collections.Generic.Dictionary`2/Transform`1<System.Int32,System.Object,System.Object> struct <API key> : public <API key> { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif
layout: post title: Spring subtitle: date: 2017-12-19 author: Felix header-img: img/home-bg-art.jpg catalog: true tags: - hibernate hibernate ## hibernate 1.hibernateJDBCjarhibernate 2. ## jar(-.-) jar swift 1.antlr-.-jar 2.classmate-.-jar 3.dom4j-.-jar 4.<API key>-.-jar 5.hibernate-core-.-jar 6.hibernate-jpa-.-api-.-jar 7.jandex-.-jar 8.javassist-logging-.-jar 9.jboss-logging-.-jar 10.<API key>-.-jar //mysqljar 11.mysql-connector-jar-.-jar ## .hbm.xml pojo*.hbm.xml* swift <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http: `<hibernate-mapping>``classtableidtypeproperty` ## config hibernate.cfg.xmlclass/src swift <!-- Configuration cfg = new Configuration().configure() --> <!DOCTYPE <API key> PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http: <<API key>> <!-- session --> <session-factory> <!-- URL --> <property name="connection.url">jdbc:mysql://localhost:3306/hiberstudy</property> <property name="connection.username">root</property> <property name="connection.password">123456</property> <property name="connection.diver_class">com.mysql.jdbc.Driver</property> <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property> <!-- hibernate --> <property name="hibernate.show_sql">true</property> <property name="hibernate.hbm2ddl.auto">create</property> <property name="hibernate.jdbc.batch_size">50</property> <property name="hibernate.cache.<API key>">false</property> <property name="hibernate.query.factory_class"> org.hibernate.hql.ast.<API key></property><!-- HQL/SQL / --> <mapping resource="com/lzf/vo/User.hbm.xml"/> </session-factory> </<API key>> swift //hibernate,config Configuration cfg = new Configuration(); //session SesstionFactory sessionFactory = cfg.configure().buildSessionFactory(); //session Session session = sessionFactory.openSession(); Transaction t= session.beginTransaction(); //commit t.commit();
--TEST swoole_server/ssl: dtls --SKIPIF <?php require __DIR__ . '/../../include/skipif.inc'; ?> --FILE <?php require __DIR__ . '/../../include/bootstrap.php'; $pm = new SwooleTest\ProcessManager; $pm->parentFunc = function ($pid) use ($pm) { $client = new Swoole\Client(SWOOLE_SOCK_UDP | SWOOLE_SSL, SWOOLE_SOCK_SYNC); if (!$client->connect('127.0.0.1', $pm->getFreePort())) { exit("connect failed\n"); } $client->send("hello world"); Assert::same($client->recv(), "Swoole hello world"); $pm->kill(); }; $pm->childFunc = function () use ($pm) { $serv = new Swoole\Server('127.0.0.1', $pm->getFreePort(), SWOOLE_BASE, SWOOLE_SOCK_UDP | SWOOLE_SSL); $serv->set([ 'log_file' => '/dev/null', 'ssl_cert_file' => SSL_FILE_DIR . '/server.crt', 'ssl_key_file' => SSL_FILE_DIR . '/server.key', ]); $serv->on("workerStart", function ($serv) use ($pm) { $pm->wakeup(); }); $serv->on('receive', function ($serv, $fd, $tid, $data) { $serv->send($fd, "Swoole $data"); }); $serv->on('packet', function ($serv, $fd, $tid, $data) { $serv->send($fd, "Swoole $data"); }); $serv->start(); }; $pm->childFirst(); $pm->run(); ?> --EXPECT
package com.bagri.server.hazelcast.task.schema; import static com.bagri.core.Constants.pn_schema_password; import static com.bagri.server.hazelcast.serialize.<API key>.<API key>; import static com.bagri.support.security.Encryptor.encrypt; import java.io.IOException; import java.util.Properties; import java.util.Map.Entry; import com.bagri.core.system.Schema; import com.hazelcast.nio.ObjectDataInput; import com.hazelcast.nio.ObjectDataOutput; import com.hazelcast.nio.serialization.<API key>; public class SchemaUpdater extends SchemaProcessor implements <API key> { private boolean override; private Properties properties; public SchemaUpdater() { } public SchemaUpdater(int version, String admin, boolean override, Properties properties) { super(version, admin); this.override = override; this.properties = properties; } @Override public Object process(Entry<String, Schema> entry) { logger.debug("process.enter; entry: {}", entry); if (entry.getValue() != null) { Schema schema = entry.getValue(); if (schema.getVersion() == getVersion()) { //if (schema.isActive()) { // if (<API key>(schema) > 0) { // don't go further // return null; if (override) { String pwd = properties.getProperty(pn_schema_password); if (pwd != null) { properties.setProperty(pn_schema_password, encrypt(pwd)); } schema.setProperties(properties); } else { for (String name: properties.stringPropertyNames()) { String value = properties.getProperty(name); if (pn_schema_password.equals(name)) { value = encrypt(value); } schema.setProperty(name, value); } } //if (schema.isActive()) { // if (initSchemaInCluster(schema) == 0) { // schema.setActive(false); schema.updateVersion(getAdmin()); entry.setValue(schema); auditEntity(AuditType.update, schema); return schema; } } return null; } @Override public int getId() { return <API key>; } @Override public void readData(ObjectDataInput in) throws IOException { super.readData(in); override = in.readBoolean(); properties = in.readObject(); } @Override public void writeData(ObjectDataOutput out) throws IOException { super.writeData(out); out.writeBoolean(override); out.writeObject(properties); } }