code
stringlengths 3
1.05M
| repo_name
stringlengths 4
116
| path
stringlengths 3
942
| language
stringclasses 30
values | license
stringclasses 15
values | size
int32 3
1.05M
|
---|---|---|---|---|---|
//===- FragmentRef.h ------------------------------------------------------===//
//
// The MCLinker Project
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#ifndef MCLD_FRAGMENT_FRAGMENT_REFERENCE_H
#define MCLD_FRAGMENT_FRAGMENT_REFERENCE_H
#ifdef ENABLE_UNITTEST
#include <gtest.h>
#endif
#include <mcld/Config/Config.h>
#include <mcld/ADT/SizeTraits.h>
#include <mcld/ADT/TypeTraits.h>
#include <mcld/Support/Allocators.h>
namespace mcld {
class Fragment;
class LDSection;
class Layout;
/** \class FragmentRef
* \brief FragmentRef is a reference of a Fragment's contetnt.
*
*/
class FragmentRef
{
public:
typedef uint64_t Offset; // FIXME: use SizeTraits<T>::Offset
typedef NonConstTraits<unsigned char>::pointer Address;
typedef ConstTraits<unsigned char>::pointer ConstAddress;
public:
/// Create - create a fragment reference for a given fragment.
///
/// @param pFrag - the given fragment
/// @param pOffset - the offset, can be larger than the fragment, but can not
/// be larger than the section size.
/// @return if the offset is legal, return the fragment reference. Otherwise,
/// return NULL.
static FragmentRef* Create(Fragment& pFrag, uint64_t pOffset);
static FragmentRef* Create(LDSection& pSection, uint64_t pOffset);
/// Clear - clear all generated FragmentRef in the system.
static void Clear();
static FragmentRef* Null();
// ----- modifiers ----- //
FragmentRef& assign(const FragmentRef& pCopy);
FragmentRef& assign(Fragment& pFrag, Offset pOffset = 0);
/// memcpy - copy memory
/// copy memory from the fragment to the pDesc.
/// @pDest - the destination address
/// @pNBytes - copies pNBytes from the fragment[offset()+pOffset]
/// @pOffset - additional offset.
/// the start address offset from fragment[offset()]
void memcpy(void* pDest, size_t pNBytes, Offset pOffset = 0) const;
// ----- observers ----- //
bool isNull() const { return (this == Null()); }
Fragment* frag()
{ return m_pFragment; }
const Fragment* frag() const
{ return m_pFragment; }
Offset offset() const
{ return m_Offset; }
Offset getOutputOffset() const;
// ----- dereference ----- //
Address deref();
ConstAddress deref() const;
Address operator*()
{ return deref(); }
ConstAddress operator*() const
{ return deref(); }
private:
friend FragmentRef& NullFragmentRef();
friend class Chunk<FragmentRef, MCLD_SECTIONS_PER_INPUT>;
friend class Relocation;
FragmentRef();
FragmentRef(Fragment& pFrag, Offset pOffset = 0);
private:
Fragment* m_pFragment;
Offset m_Offset;
static FragmentRef g_NullFragmentRef;
};
} // namespace of mcld
#endif
|
indashnet/InDashNet.Open.UN2000
|
android/frameworks/compile/mclinker/include/mcld/Fragment/FragmentRef.h
|
C
|
apache-2.0
| 2,877 |
package psidev.psi.mi.jami.utils.clone;
import psidev.psi.mi.jami.binary.BinaryInteraction;
import psidev.psi.mi.jami.binary.BinaryInteractionEvidence;
import psidev.psi.mi.jami.binary.ModelledBinaryInteraction;
import psidev.psi.mi.jami.model.*;
import psidev.psi.mi.jami.model.impl.DefaultModelledParticipant;
import psidev.psi.mi.jami.model.impl.DefaultParticipant;
import psidev.psi.mi.jami.model.impl.DefaultParticipantEvidence;
import java.util.Iterator;
/**
* Utility class to clone and copy interaction properties
*
* @author Marine Dumousseau ([email protected])
* @version $Id$
* @since <pre>13/02/13</pre>
*/
public class InteractionCloner {
/**
*
* This method will copy properties of interaction source in interaction target and will override all the other properties of Target interaction.
* This method will set the experiment of this interaction evidence but it will not add this interaction to the list of interactionEvidences
* This method will add all the participant evidences of the source but will not set their interactionEvidence to the target
*
* @param source a {@link psidev.psi.mi.jami.model.InteractionEvidence} object.
* @param target a {@link psidev.psi.mi.jami.model.InteractionEvidence} object.
* @param createNewParticipant If true, this method will clone each participant from source instead of reusing the participant instances from source.
* It will then set the interactionEvidence of the cloned participants to target
* @param ignoreParticipants If true, this method will clone the interaction properties and ignore the participants of the source
*/
public static void copyAndOverrideInteractionEvidenceProperties(InteractionEvidence source, InteractionEvidence target, boolean createNewParticipant, boolean ignoreParticipants){
if (source != null && target != null){
target.setAvailability(source.getAvailability());
target.setExperiment(source.getExperiment());
target.setInferred(source.isInferred());
target.setCreatedDate(source.getCreatedDate());
target.setNegative(source.isNegative());
target.setShortName(source.getShortName());
target.setInteractionType(source.getInteractionType());
target.setUpdatedDate(source.getUpdatedDate());
// copy collections
target.getAnnotations().clear();
target.getAnnotations().addAll(source.getAnnotations());
target.getChecksums().clear();
target.getChecksums().addAll(source.getChecksums());
target.getConfidences().clear();
target.getConfidences().addAll(source.getConfidences());
target.getXrefs().clear();
target.getXrefs().addAll(source.getXrefs());
target.getIdentifiers().clear();
target.getIdentifiers().addAll(source.getIdentifiers());
target.getParameters().clear();
target.getParameters().addAll(source.getParameters());
target.getVariableParameterValues().clear();
target.getVariableParameterValues().addAll(source.getVariableParameterValues());
// copy or create participants if not ignored
if (!ignoreParticipants){
target.getParticipants().clear();
if (!createNewParticipant){
target.getParticipants().addAll(source.getParticipants());
}
else{
for (ParticipantEvidence p : source.getParticipants()){
ParticipantEvidence clone = new DefaultParticipantEvidence(p.getInteractor());
ParticipantCloner.copyAndOverrideParticipantEvidenceProperties(p, clone, true);
target.addParticipant(clone);
}
}
}
}
}
/**
*
* This method will copy properties of interaction source in interaction target and will override all the other properties of Target interaction.
* This method will add all the participant of the source but will not set their modelledInteraction to the target
*
* @param source a {@link psidev.psi.mi.jami.model.ModelledInteraction} object.
* @param target a {@link psidev.psi.mi.jami.model.ModelledInteraction} object.
* @param createNewParticipant If true, this method will clone each participant from source instead of reusing the participant instances from source.
* It will then set the modelledInteraction of the cloned participants to target
* @param ignoreParticipants If true, this method will clone the interaction properties and ignore the participants of the source
*/
public static void copyAndOverrideModelledInteractionProperties(ModelledInteraction source, ModelledInteraction target, boolean createNewParticipant, boolean ignoreParticipants){
if (source != null && target != null){
target.setSource(source.getSource());
target.setCreatedDate(source.getCreatedDate());
target.setShortName(source.getShortName());
target.setInteractionType(source.getInteractionType());
target.setUpdatedDate(source.getUpdatedDate());
target.setEvidenceType(source.getEvidenceType());
// copy collections
target.getAnnotations().clear();
target.getAnnotations().addAll(source.getAnnotations());
target.getChecksums().clear();
target.getChecksums().addAll(source.getChecksums());
target.getModelledConfidences().clear();
target.getModelledConfidences().addAll(source.getModelledConfidences());
target.getXrefs().clear();
target.getXrefs().addAll(source.getXrefs());
target.getIdentifiers().clear();
target.getIdentifiers().addAll(source.getIdentifiers());
target.getModelledParameters().clear();
target.getModelledParameters().addAll(source.getModelledParameters());
target.getInteractionEvidences().clear();
target.getInteractionEvidences().addAll(source.getInteractionEvidences());
target.getCooperativeEffects().clear();
target.getCooperativeEffects().addAll(source.getCooperativeEffects());
// copy or create participants if not ignored
if (!ignoreParticipants){
target.getParticipants().clear();
if (!createNewParticipant){
target.getParticipants().addAll(source.getParticipants());
}
else{
for (ModelledParticipant p : source.getParticipants()){
ModelledParticipant clone = new DefaultModelledParticipant(p.getInteractor());
ParticipantCloner.copyAndOverrideModelledParticipantProperties(p, clone, true);
target.addParticipant(clone);
}
}
}
}
}
/**
*
* This method will copy basic properties of interaction source in interaction target and will override all the other properties of Target interaction.
*
* @param source a {@link psidev.psi.mi.jami.model.Interaction} object.
* @param target a {@link psidev.psi.mi.jami.model.Interaction} object.
* @param createNewParticipant If true, this method will clone each participant from source instead of reusing the participant instances from source.
* @param ignoreParticipants If true, this method will clone the interaction properties and ignore the participants of the source
*/
public static void copyAndOverrideBasicInteractionProperties(Interaction source, Interaction target, boolean createNewParticipant, boolean ignoreParticipants){
if (source != null && target != null){
target.setCreatedDate(source.getCreatedDate());
target.setShortName(source.getShortName());
target.setInteractionType(source.getInteractionType());
target.setUpdatedDate(source.getUpdatedDate());
// copy collections
target.getAnnotations().clear();
target.getAnnotations().addAll(source.getAnnotations());
target.getChecksums().clear();
target.getChecksums().addAll(source.getChecksums());
target.getXrefs().clear();
target.getXrefs().addAll(source.getXrefs());
target.getIdentifiers().clear();
target.getIdentifiers().addAll(source.getIdentifiers());
// copy or create participants if not ignored
if (!ignoreParticipants){
target.getParticipants().clear();
if (!createNewParticipant){
target.getParticipants().addAll(source.getParticipants());
}
else{
for (Object o : source.getParticipants()){
Participant p = (Participant)o;
Participant clone = new DefaultParticipant(p.getInteractor());
ParticipantCloner.copyAndOverrideBasicParticipantProperties(p, clone, true);
target.getParticipants().add(clone);
}
}
}
}
}
/**
*
* This method will copy participants of interaction evidence source in binary target.
*
* @param source a {@link psidev.psi.mi.jami.model.InteractionEvidence} object.
* @param target a {@link psidev.psi.mi.jami.binary.BinaryInteractionEvidence} object.
* @param createNewParticipant If true, this method will clone each participant from source instead of reusing the participant instances from source.
* It will then set the interactionEvidence of the cloned participants to target
* @param self If true, it will only look at the first participant and duplicate this participant with stoichiometry 0
* @throws java.lang.IllegalArgumentException if the number of participants in source is superior to 2 or superior to 1 with self = true
*/
public static void copyAndOverrideParticipantsEvidencesToBinary(InteractionEvidence source, BinaryInteractionEvidence target, boolean createNewParticipant, boolean self){
if (source != null && target != null){
if (source.getParticipants().size() > 2){
throw new IllegalArgumentException("We cannot copy the participants from the source because it contains more than 2 participants : " +source.getParticipants().size());
}
else if (source.getParticipants().size() != 1 && self){
throw new IllegalArgumentException("We cannot copy the participants from the source because it is a self interaction containing more than one participant");
}
if (source.getParticipants().isEmpty()){
target.setParticipantA(null);
target.setParticipantB(null);
}
else {
Iterator<ParticipantEvidence> iterator = source.getParticipants().iterator();
if (!createNewParticipant){
ParticipantEvidence first = iterator.next();
target.setParticipantA(first);
if (self){
ParticipantEvidence clone = new DefaultParticipantEvidence(first.getInteractor());
ParticipantCloner.copyAndOverrideParticipantEvidenceProperties(first, clone, true);
clone.setInteraction(target);
// second self interactor has stoichiometry 0 if necessary
if (first.getStoichiometry() != null){
clone.setStoichiometry(0);
}
target.setParticipantB(clone);
}
else if (iterator.hasNext()){
target.setParticipantB(iterator.next());
}
else {
target.setParticipantB(null);
}
}
else {
ParticipantEvidence first = iterator.next();
ParticipantEvidence clone = new DefaultParticipantEvidence(first.getInteractor());
ParticipantCloner.copyAndOverrideParticipantEvidenceProperties(first, clone, true);
target.setParticipantA(clone);
clone.setInteraction(target);
if (self){
ParticipantEvidence clone2 = new DefaultParticipantEvidence(first.getInteractor());
ParticipantCloner.copyAndOverrideParticipantEvidenceProperties(first, clone2, true);
clone2.setInteraction(target);
// second self interactor has stoichiometry 0 if necessary
if (first.getStoichiometry() != null){
clone2.setStoichiometry(0);
}
target.setParticipantB(clone2);
}
else if (iterator.hasNext()){
ParticipantEvidence second = iterator.next();
ParticipantEvidence clone2 = new DefaultParticipantEvidence(second.getInteractor());
ParticipantCloner.copyAndOverrideParticipantEvidenceProperties(second, clone2, true);
target.setParticipantB(clone2);
clone2.setInteraction(target);
}
else {
target.setParticipantB(null);
}
}
}
}
}
/**
*
* This method will copy participants of modelled interaction source in binary target.
*
* @param source a {@link psidev.psi.mi.jami.model.ModelledInteraction} object.
* @param target a {@link psidev.psi.mi.jami.binary.ModelledBinaryInteraction} object.
* @param createNewParticipant If true, this method will clone each participant from source instead of reusing the participant instances from source.
* It will then set the modelledInteraction of the cloned participants to target
* @param self if true, we only take the first participant and duplicate it in the Binary interaction. We then set the stoichiometry to 0 for the second interactor
* @throws java.lang.IllegalArgumentException if the source has more than two participants or more than one participant when self is true
*/
public static void copyAndOverrideModelledParticipantsToBinary(ModelledInteraction source, ModelledBinaryInteraction target, boolean createNewParticipant, boolean self){
if (source != null && target != null){
if (source.getParticipants().size() > 2){
throw new IllegalArgumentException("We cannot copy the participants from the source because it contains more than 2 participants : " +source.getParticipants().size());
}
else if (source.getParticipants().size() != 1 && self){
throw new IllegalArgumentException("We cannot copy the participants from the source because it is a self interaction containing more than one participant");
}
if (source.getParticipants().isEmpty()){
target.setParticipantA(null);
target.setParticipantB(null);
}
else {
Iterator<ModelledParticipant> iterator = source.getParticipants().iterator();
if (!createNewParticipant){
ModelledParticipant first = iterator.next();
target.setParticipantA(first);
if (self){
ModelledParticipant clone = new DefaultModelledParticipant(first.getInteractor());
ParticipantCloner.copyAndOverrideModelledParticipantProperties(first, clone, true);
clone.setInteraction(target);
// second self interactor has stoichiometry 0 if necessary
if (first.getStoichiometry() != null){
clone.setStoichiometry(0);
}
target.setParticipantB(clone);
}
else if (iterator.hasNext()){
target.setParticipantB(iterator.next());
}
else {
target.setParticipantB(null);
}
}
else {
ModelledParticipant first = iterator.next();
ModelledParticipant clone = new DefaultModelledParticipant(first.getInteractor());
ParticipantCloner.copyAndOverrideModelledParticipantProperties(first, clone, true);
target.setParticipantA(clone);
clone.setInteraction(target);
if (self){
ModelledParticipant clone2 = new DefaultModelledParticipant(first.getInteractor());
ParticipantCloner.copyAndOverrideModelledParticipantProperties(first, clone2, true);
clone2.setInteraction(target);
// second self interactor has stoichiometry 0 if necessary
if (first.getStoichiometry() != null){
clone2.setStoichiometry(0);
}
target.setParticipantB(clone2);
}
else if (iterator.hasNext()){
ModelledParticipant second = iterator.next();
ModelledParticipant clone2 = new DefaultModelledParticipant(second.getInteractor());
ParticipantCloner.copyAndOverrideModelledParticipantProperties(second, clone2, true);
target.setParticipantB(clone2);
clone2.setInteraction(target);
}
else {
target.setParticipantB(null);
}
}
}
}
}
/**
*
* This method will copy participants of interaction source in binary target.
*
* @param source a {@link psidev.psi.mi.jami.model.Interaction} object.
* @param target a {@link psidev.psi.mi.jami.binary.BinaryInteraction} object.
* @param createNewParticipant If true, this method will clone each participant from source instead of reusing the participant instances from source.
* @param self if true, we only take the first participant and duplicate it in the Binary interaction. We then set the stoichiometry to 0 for the second interactor
* @throws java.lang.IllegalArgumentException if the source has more than two participants or more than one participant when self is true
*/
public static void copyAndOverrideBasicParticipantsToBinary(Interaction source, BinaryInteraction target, boolean createNewParticipant, boolean self){
if (source != null && target != null){
if (source.getParticipants().size() > 2){
throw new IllegalArgumentException("We cannot copy the participants from the source because it contains more than 2 participants : " +source.getParticipants().size());
}
else if (source.getParticipants().size() != 1 && self){
throw new IllegalArgumentException("We cannot copy the participants from the source because it is a self interaction containing more than one participant");
}
if (source.getParticipants().isEmpty()){
target.setParticipantA(null);
target.setParticipantB(null);
}
else {
Iterator<? extends Participant> iterator = source.getParticipants().iterator();
if (!createNewParticipant){
Participant first = iterator.next();
target.setParticipantA(first);
if (self){
Participant clone = new DefaultParticipant(first.getInteractor());
ParticipantCloner.copyAndOverrideBasicParticipantProperties(first, clone, true);
// second self interactor has stoichiometry 0 if necessary
if (first.getStoichiometry() != null){
clone.setStoichiometry(0);
}
target.setParticipantB(clone);
}
else if (iterator.hasNext()){
target.setParticipantB(iterator.next());
}
else {
target.setParticipantB(null);
}
}
else {
Participant first = iterator.next();
Participant clone = new DefaultParticipant(first.getInteractor());
ParticipantCloner.copyAndOverrideBasicParticipantProperties(first, clone, true);
target.setParticipantA(clone);
if (self){
Participant clone2 = new DefaultParticipant(first.getInteractor());
ParticipantCloner.copyAndOverrideBasicParticipantProperties(first, clone2, true);
// second self interactor has stoichiometry 0 if necessary
if (first.getStoichiometry() != null){
clone2.setStoichiometry(0);
}
target.setParticipantB(clone2);
}
else if (iterator.hasNext()){
Participant second = iterator.next();
Participant clone2 = new DefaultParticipant(second.getInteractor());
ParticipantCloner.copyAndOverrideBasicParticipantProperties(second, clone2, true);
target.setParticipantB(clone2);
}
else {
target.setParticipantB(null);
}
}
}
}
}
}
|
MICommunity/psi-jami
|
jami-core/src/main/java/psidev/psi/mi/jami/utils/clone/InteractionCloner.java
|
Java
|
apache-2.0
| 22,480 |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.geronimo.st.v11.ui.pages;
import org.apache.geronimo.st.ui.pages.AbstractGeronimoFormPage;
import org.apache.geronimo.st.v11.ui.sections.OpenEjbJarGeneralSection;
import org.eclipse.ui.forms.IManagedForm;
import org.eclipse.ui.forms.editor.FormEditor;
public class EjbOverviewPage extends AbstractGeronimoFormPage {
public EjbOverviewPage(FormEditor editor, String id, String title) {
super(editor, id, title);
}
/*
* (non-Javadoc)
*
* @see org.apache.geronimo.st.ui.pages.AbstractGeronimoFormPage#fillBody(org.eclipse.ui.forms.IManagedForm)
*/
protected void fillBody(IManagedForm managedForm) {
managedForm.addPart(new OpenEjbJarGeneralSection(body, toolkit, getStyle(), getDeploymentPlan()));
}
}
|
apache/geronimo-devtools
|
plugins/org.apache.geronimo.st.v11.ui/src/org/apache/geronimo/st/v11/ui/pages/EjbOverviewPage.java
|
Java
|
apache-2.0
| 1,543 |
// Copyright (c) 2008 The Board of Trustees of The Leland Stanford Junior University
// Copyright (c) 2011, 2012 Open Networking Foundation
// Copyright (c) 2012, 2013 Big Switch Networks, Inc.
// This library was generated by the LoxiGen Compiler.
// See the file LICENSE.txt which should have been included in the source distribution
// Automatically generated by LOXI from template of_class.java
// Do not modify
package org.projectfloodlight.openflow.protocol.ver14;
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 OFRoleReplyVer14 implements OFRoleReply {
private static final Logger logger = LoggerFactory.getLogger(OFRoleReplyVer14.class);
// version: 1.4
final static byte WIRE_VERSION = 5;
final static int LENGTH = 24;
private final static long DEFAULT_XID = 0x0L;
private final static U64 DEFAULT_GENERATION_ID = U64.ZERO;
// OF message fields
private final long xid;
private final OFControllerRole role;
private final U64 generationId;
//
// package private constructor - used by readers, builders, and factory
OFRoleReplyVer14(long xid, OFControllerRole role, U64 generationId) {
if(role == null) {
throw new NullPointerException("OFRoleReplyVer14: property role cannot be null");
}
if(generationId == null) {
throw new NullPointerException("OFRoleReplyVer14: property generationId cannot be null");
}
this.xid = xid;
this.role = role;
this.generationId = generationId;
}
// Accessors for OF message fields
@Override
public OFVersion getVersion() {
return OFVersion.OF_14;
}
@Override
public OFType getType() {
return OFType.ROLE_REPLY;
}
@Override
public long getXid() {
return xid;
}
@Override
public OFControllerRole getRole() {
return role;
}
@Override
public U64 getGenerationId() {
return generationId;
}
public OFRoleReply.Builder createBuilder() {
return new BuilderWithParent(this);
}
static class BuilderWithParent implements OFRoleReply.Builder {
final OFRoleReplyVer14 parentMessage;
// OF message fields
private boolean xidSet;
private long xid;
private boolean roleSet;
private OFControllerRole role;
private boolean generationIdSet;
private U64 generationId;
BuilderWithParent(OFRoleReplyVer14 parentMessage) {
this.parentMessage = parentMessage;
}
@Override
public OFVersion getVersion() {
return OFVersion.OF_14;
}
@Override
public OFType getType() {
return OFType.ROLE_REPLY;
}
@Override
public long getXid() {
return xid;
}
@Override
public OFRoleReply.Builder setXid(long xid) {
this.xid = xid;
this.xidSet = true;
return this;
}
@Override
public OFControllerRole getRole() {
return role;
}
@Override
public OFRoleReply.Builder setRole(OFControllerRole role) {
this.role = role;
this.roleSet = true;
return this;
}
@Override
public U64 getGenerationId() {
return generationId;
}
@Override
public OFRoleReply.Builder setGenerationId(U64 generationId) {
this.generationId = generationId;
this.generationIdSet = true;
return this;
}
@Override
public OFRoleReply build() {
long xid = this.xidSet ? this.xid : parentMessage.xid;
OFControllerRole role = this.roleSet ? this.role : parentMessage.role;
if(role == null)
throw new NullPointerException("Property role must not be null");
U64 generationId = this.generationIdSet ? this.generationId : parentMessage.generationId;
if(generationId == null)
throw new NullPointerException("Property generationId must not be null");
//
return new OFRoleReplyVer14(
xid,
role,
generationId
);
}
}
static class Builder implements OFRoleReply.Builder {
// OF message fields
private boolean xidSet;
private long xid;
private boolean roleSet;
private OFControllerRole role;
private boolean generationIdSet;
private U64 generationId;
@Override
public OFVersion getVersion() {
return OFVersion.OF_14;
}
@Override
public OFType getType() {
return OFType.ROLE_REPLY;
}
@Override
public long getXid() {
return xid;
}
@Override
public OFRoleReply.Builder setXid(long xid) {
this.xid = xid;
this.xidSet = true;
return this;
}
@Override
public OFControllerRole getRole() {
return role;
}
@Override
public OFRoleReply.Builder setRole(OFControllerRole role) {
this.role = role;
this.roleSet = true;
return this;
}
@Override
public U64 getGenerationId() {
return generationId;
}
@Override
public OFRoleReply.Builder setGenerationId(U64 generationId) {
this.generationId = generationId;
this.generationIdSet = true;
return this;
}
//
@Override
public OFRoleReply build() {
long xid = this.xidSet ? this.xid : DEFAULT_XID;
if(!this.roleSet)
throw new IllegalStateException("Property role doesn't have default value -- must be set");
if(role == null)
throw new NullPointerException("Property role must not be null");
U64 generationId = this.generationIdSet ? this.generationId : DEFAULT_GENERATION_ID;
if(generationId == null)
throw new NullPointerException("Property generationId must not be null");
return new OFRoleReplyVer14(
xid,
role,
generationId
);
}
}
final static Reader READER = new Reader();
static class Reader implements OFMessageReader<OFRoleReply> {
@Override
public OFRoleReply readFrom(ChannelBuffer bb) throws OFParseError {
int start = bb.readerIndex();
// fixed value property version == 5
byte version = bb.readByte();
if(version != (byte) 0x5)
throw new OFParseError("Wrong version: Expected=OFVersion.OF_14(5), got="+version);
// fixed value property type == 25
byte type = bb.readByte();
if(type != (byte) 0x19)
throw new OFParseError("Wrong type: Expected=OFType.ROLE_REPLY(25), got="+type);
int length = U16.f(bb.readShort());
if(length != 24)
throw new OFParseError("Wrong length: Expected=24(24), got="+length);
if(bb.readableBytes() + (bb.readerIndex() - start) < length) {
// Buffer does not have all data yet
bb.readerIndex(start);
return null;
}
if(logger.isTraceEnabled())
logger.trace("readFrom - length={}", length);
long xid = U32.f(bb.readInt());
OFControllerRole role = OFControllerRoleSerializerVer14.readFrom(bb);
// pad: 4 bytes
bb.skipBytes(4);
U64 generationId = U64.ofRaw(bb.readLong());
OFRoleReplyVer14 roleReplyVer14 = new OFRoleReplyVer14(
xid,
role,
generationId
);
if(logger.isTraceEnabled())
logger.trace("readFrom - read={}", roleReplyVer14);
return roleReplyVer14;
}
}
public void putTo(PrimitiveSink sink) {
FUNNEL.funnel(this, sink);
}
final static OFRoleReplyVer14Funnel FUNNEL = new OFRoleReplyVer14Funnel();
static class OFRoleReplyVer14Funnel implements Funnel<OFRoleReplyVer14> {
private static final long serialVersionUID = 1L;
@Override
public void funnel(OFRoleReplyVer14 message, PrimitiveSink sink) {
// fixed value property version = 5
sink.putByte((byte) 0x5);
// fixed value property type = 25
sink.putByte((byte) 0x19);
// fixed value property length = 24
sink.putShort((short) 0x18);
sink.putLong(message.xid);
OFControllerRoleSerializerVer14.putTo(message.role, sink);
// skip pad (4 bytes)
message.generationId.putTo(sink);
}
}
public void writeTo(ChannelBuffer bb) {
WRITER.write(bb, this);
}
final static Writer WRITER = new Writer();
static class Writer implements OFMessageWriter<OFRoleReplyVer14> {
@Override
public void write(ChannelBuffer bb, OFRoleReplyVer14 message) {
// fixed value property version = 5
bb.writeByte((byte) 0x5);
// fixed value property type = 25
bb.writeByte((byte) 0x19);
// fixed value property length = 24
bb.writeShort((short) 0x18);
bb.writeInt(U32.t(message.xid));
OFControllerRoleSerializerVer14.writeTo(bb, message.role);
// pad: 4 bytes
bb.writeZero(4);
bb.writeLong(message.generationId.getValue());
}
}
@Override
public String toString() {
StringBuilder b = new StringBuilder("OFRoleReplyVer14(");
b.append("xid=").append(xid);
b.append(", ");
b.append("role=").append(role);
b.append(", ");
b.append("generationId=").append(generationId);
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;
OFRoleReplyVer14 other = (OFRoleReplyVer14) obj;
if( xid != other.xid)
return false;
if (role == null) {
if (other.role != null)
return false;
} else if (!role.equals(other.role))
return false;
if (generationId == null) {
if (other.generationId != null)
return false;
} else if (!generationId.equals(other.generationId))
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * (int) (xid ^ (xid >>> 32));
result = prime * result + ((role == null) ? 0 : role.hashCode());
result = prime * result + ((generationId == null) ? 0 : generationId.hashCode());
return result;
}
}
|
o3project/openflowj-otn
|
src/main/java/org/projectfloodlight/openflow/protocol/ver14/OFRoleReplyVer14.java
|
Java
|
apache-2.0
| 11,950 |
package dp;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
/**
* https://oj.leetcode.com/problems/word-break-ii/
* Given a string s and a dictionary of words dict, add spaces in s to construct a sentence where each word is a valid dictionary word.
* Return all such possible sentences.
* For example, given
* s = "catsanddog",
* dict = ["cat", "cats", "and", "sand", "dog"].
* A solution is ["cats and dog", "cat sand dog"]
*/
public class WordBreakII {
public List<String> wordBreak(String s, Set<String> dict) {
List<String> res = new ArrayList<>();
int length = s == null ? 0 : s.length();
if (length == 0) return res;
boolean[] dp = new boolean[length + 1];
Arrays.fill(dp, true);
helper(res, new StringBuilder(), 0, length, s, dict, dp);
return res;
}
private void helper(List<String> res, StringBuilder path, int start, int length, String s, Set<String> dict, boolean[] dp) {
if (start >= length) {
path.setLength(path.length() - 1);
res.add(path.toString());
return;
}
for (int i = start + 1; i <= length; i++) {
String word = s.substring(start, i);
if (dp[i] && dict.contains(word)) {
int size = res.size();
int tmp = path.length();
path.append(word).append(" ");
helper(res, path, i, length, s, dict, dp);
if (size == res.size()) {
dp[i] = false;
}
path.setLength(tmp);
}
}
}
}
|
jinglongyang/leetcode
|
src/dp/WordBreakII.java
|
Java
|
apache-2.0
| 1,658 |
/*
Copyright 2017-2019 Google Inc. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS-IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include "lullaby/modules/stategraph/stategraph.h"
#include "lullaby/util/logging.h"
namespace lull {
void Stategraph::AddState(std::unique_ptr<StategraphState> state) {
const HashValue id = state->GetId();
auto iter = states_.find(id);
if (iter != states_.end()) {
LOG(DFATAL) << "State already in stategraph: " << id;
}
states_[id] = std::move(state);
}
const StategraphState* Stategraph::GetState(HashValue id) const {
auto iter = states_.find(id);
return iter != states_.end() ? iter->second.get() : nullptr;
}
Stategraph::Path Stategraph::FindPathHelper(const StategraphState* node,
const StategraphState* dest,
std::set<HashValue> visited) const {
if (node == dest) {
LOG(DFATAL) << "Should not have reached this far.";
return {};
}
Path shortest_path;
bool first = true;
visited.insert(node->GetId());
const std::vector<StategraphTransition>& transitions = node->GetTransitions();
for (const StategraphTransition& transition : transitions) {
const StategraphState* next = GetState(transition.to_state);
if (next == nullptr) {
LOG(DFATAL) << "Found a transition to an invalid state: "
<< transition.to_state;
continue;
}
if (visited.count(transition.to_state) != 0) {
continue;
}
Path path;
path.push_back(transition);
if (next == dest) {
shortest_path = std::move(path);
break;
}
Path tmp = FindPathHelper(next, dest, visited);
if (tmp.empty()) {
continue;
}
path.insert(path.end(), tmp.begin(), tmp.end());
if (first) {
first = false;
shortest_path = std::move(path);
} else if (path.size() < shortest_path.size()) {
shortest_path = std::move(path);
}
}
return shortest_path;
}
Stategraph::Path Stategraph::FindPath(HashValue from_state_id,
HashValue to_state_id) const {
Path path;
const StategraphState* from_state = GetState(from_state_id);
if (from_state == nullptr) {
LOG(DFATAL) << "Could not find initial state: " << from_state_id;
return {};
}
const StategraphState* to_state = GetState(to_state_id);
if (to_state == nullptr) {
LOG(DFATAL) << "Could not find ending state: " << to_state_id;
return {};
}
if (from_state == to_state) {
return {};
}
std::set<HashValue> visited;
return FindPathHelper(from_state, to_state, visited);
}
std::string Stategraph::GetGraphDebugString() const {
std::stringstream str;
str << "digraph {\n";
for (const auto& state : states_) {
for (const auto& trans : state.second->GetTransitions()) {
#ifdef LULLABY_DEBUG_HASH
str << Unhash(trans.from_state) << "->" << Unhash(trans.to_state)
<< ";\n";
#else
str << trans.from_state << "->" << trans.to_state << ";\n";
#endif
}
}
str << "}";
return str.str();
}
} // namespace lull
|
google/lullaby
|
lullaby/modules/stategraph/stategraph.cc
|
C++
|
apache-2.0
| 3,567 |
const correctAnswer = {
digitsQ1 : '3 9 4',
digitsQ2 : '4 1 8 3',
digitsQ3 : '1 7 9 2 6',
digitsQ4 : '2 6 4 8 1 7',
monthsBackwards : 'december november october september august july june may april march february january'
}
const assessAnswer = (params, answer) => {
return correctAnswer[params] == answer;
}
module.exports = assessAnswer;
|
andrewwk/concussion-app
|
server/concentration.js
|
JavaScript
|
apache-2.0
| 382 |
<?php get_header(); ?>
<div id="primary" class="content-area">
<div id="content" class="site-content" role="main">
<header class="page-header">
<h1 class="page-title"><?php _e( 'Nothing Found', 'simpleportal' ); ?></h1>
</header>
<div class="page-wrapper">
<div class="page-content">
<h2><?php _e( 'This is somewhat embarrassing, isn’t it?', 'simpleportal' ); ?></h2>
<p><?php _e( 'It looks like nothing was found at this location or perhaps you were trying to access a private page? Log in first', 'simpleportal' ); ?></p>
</div><!-- .page-content -->
</div><!-- .page-wrapper -->
</div><!-- #content -->
</div><!-- #primary -->
<?php get_footer(); ?>
|
darkpsy3934/community-plugins
|
ofsocial/src/wp-content/themes/simple-portal/404.php
|
PHP
|
apache-2.0
| 703 |
#!/usr/bin/env python
import nltk
from nltk.corpus import wordnet as wn
# This method requires to run dw_wordnet prior to any execution with this suggester
class WNSearch():
"""Class to perform searches in WordNet"""
def suggest_terms(self,query_word):
term_dict={}
for syn in wn.synsets(query_word):
term_dict[syn._name.split('.')[0]]=1
for hyp in syn.hypernyms():
term_dict[hyp._name.split('.')[0]]=1
return term_dict
|
nlesc-sherlock/concept-search
|
termsuggester/wnsearch.py
|
Python
|
apache-2.0
| 495 |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.apache.ivy.core.module.id;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import org.apache.ivy.plugins.matcher.MapMatcher;
import org.apache.ivy.util.Checks;
import org.apache.ivy.util.Message;
import org.apache.ivy.util.filter.Filter;
import org.apache.ivy.util.filter.NoFilter;
/**
* A list of module specific rules.
* <p>
* This class defines a list of module specific rules. For each module only one rule apply,
* sometimes none.
* </p>
* <p>
* To know which rule to apply, they are configured using matchers. So you can define a rule
* applying to all module from one particular organization, or to all modules with a revisions
* matching a pattern, and so on.
* </p>
* <p>
* Rules condition are evaluated in order, so the first matching rule is returned.
* </p>
* <p>
* Rules themselves can be represented by any object, depending on the purpose of the rule (define
* which resolver to use, which TTL in cache, ...)
* </p>
*/
public class ModuleRules {
private Map/*<MapMatcher,Object>*/ rules = new LinkedHashMap();
/**
* Constructs an empty ModuleRules.
*/
public ModuleRules() {
}
private ModuleRules(Map/*<MapMatcher,Object>*/ rules) {
this.rules = new LinkedHashMap(rules);
}
/**
* Defines a new rule for the given condition.
*
* @param condition
* the condition for which the rule should be applied. Must not be <code>null</code>.
* @param rule
* the rule to apply. Must not be <code>null</code>.
*/
public void defineRule(MapMatcher condition, Object rule) {
Checks.checkNotNull(condition, "condition");
Checks.checkNotNull(rule, "rule");
rules.put(condition, rule);
}
/**
* Returns the rule object matching the given {@link ModuleId}, or <code>null</code>
* if no rule applies.
*
* @param mid
* the {@link ModuleId} to search the rule for.
* Must not be <code>null</code>.
* @return the rule object matching the given {@link ModuleId}, or <code>null</code>
* if no rule applies.
* @see #getRule(ModuleId, Filter)
*/
public Object getRule(ModuleId mid) {
return getRule(mid, NoFilter.INSTANCE);
}
/**
* Returns the rules objects matching the given {@link ModuleId}, or an empty array
* if no rule applies.
*
* @param mid
* the {@link ModuleId} to search the rule for.
* Must not be <code>null</code>.
* @return an array of rule objects matching the given {@link ModuleId}.
*/
public Object[] getRules(ModuleId mid) {
return getRules(mid.getAttributes(), NoFilter.INSTANCE);
}
/**
* Returns the rule object matching the given {@link ModuleRevisionId}, or <code>null</code>
* if no rule applies.
*
* @param mrid
* the {@link ModuleRevisionId} to search the rule for.
* Must not be <code>null</code>.
* @return the rule object matching the given {@link ModuleRevisionId}, or <code>null</code>
* if no rule applies.
* @see #getRule(ModuleRevisionId, Filter)
*/
public Object getRule(ModuleRevisionId mrid) {
return getRule(mrid, NoFilter.INSTANCE);
}
/**
* Returns the rule object matching the given {@link ModuleId} and accepted by the given
* {@link Filter}, or <code>null</code> if no rule applies.
*
* @param mid
* the {@link ModuleRevisionId} to search the rule for.
* Must not be <code>null</code>.
* @param filter
* the filter to use to filter the rule to return. The {@link Filter#accept(Object)}
* method will be called only with rule objects matching the given
* {@link ModuleId}, and the first rule object accepted by the filter will
* be returned. Must not be <code>null</code>.
* @return the rule object matching the given {@link ModuleId}, or <code>null</code>
* if no rule applies.
* @see #getRule(ModuleRevisionId, Filter)
*/
public Object getRule(ModuleId mid, Filter filter) {
Checks.checkNotNull(mid, "mid");
return getRule(mid.getAttributes(), filter);
}
/**
* Returns the rule object matching the given {@link ModuleRevisionId} and accepted by the given
* {@link Filter}, or <code>null</code> if no rule applies.
*
* @param mrid
* the {@link ModuleRevisionId} to search the rule for.
* Must not be <code>null</code>.
* @param filter
* the filter to use to filter the rule to return. The {@link Filter#accept(Object)}
* method will be called only with rule objects matching the given
* {@link ModuleRevisionId}, and the first rule object accepted by the filter will
* be returned. Must not be <code>null</code>.
* @return the rule object matching the given {@link ModuleRevisionId}, or <code>null</code>
* if no rule applies.
* @see #getRule(ModuleRevisionId)
*/
public Object getRule(ModuleRevisionId mrid, Filter filter) {
Checks.checkNotNull(mrid, "mrid");
Checks.checkNotNull(filter, "filter");
Map moduleAttributes = mrid.getAttributes();
return getRule(moduleAttributes, filter);
}
private Object getRule(Map moduleAttributes, Filter filter) {
for (Iterator iter = rules.entrySet().iterator(); iter.hasNext();) {
Map.Entry ruleEntry = (Entry) iter.next();
MapMatcher midm = (MapMatcher) ruleEntry.getKey();
if (midm.matches(moduleAttributes)) {
Object rule = ruleEntry.getValue();
if (filter.accept(rule)) {
return rule;
}
}
}
return null;
}
/**
* Returns the rules object matching the given {@link ModuleRevisionId} and accepted by the
* given {@link Filter}, or an empty array if no rule applies.
*
* @param mrid
* the {@link ModuleRevisionId} to search the rule for.
* Must not be <code>null</code>.
* @param filter
* the filter to use to filter the rule to return. The {@link Filter#accept(Object)}
* method will be called only with rule objects matching the given
* {@link ModuleRevisionId}. Must not be <code>null</code>.
* @return an array of rule objects matching the given {@link ModuleRevisionId}.
*/
public Object[] getRules(ModuleRevisionId mrid, Filter filter) {
Checks.checkNotNull(mrid, "mrid");
Checks.checkNotNull(filter, "filter");
Map moduleAttributes = mrid.getAttributes();
return getRules(moduleAttributes, filter);
}
private Object[] getRules(Map moduleAttributes, Filter filter) {
List matchingRules = new ArrayList();
for (Iterator iter = rules.entrySet().iterator(); iter.hasNext();) {
Map.Entry ruleEntry = (Entry) iter.next();
MapMatcher midm = (MapMatcher) ruleEntry.getKey();
if (midm.matches(moduleAttributes)) {
Object rule = ruleEntry.getValue();
if (filter.accept(rule)) {
matchingRules.add(rule);
}
}
}
return matchingRules.toArray();
}
/**
* Dump the list of rules to {@link Message#debug(String)}
*
* @param prefix
* the prefix to use for each line dumped
*/
public void dump(String prefix) {
if (rules.isEmpty()) {
Message.debug(prefix + "NONE");
} else {
for (Iterator iter = rules.keySet().iterator(); iter.hasNext();) {
MapMatcher midm = (MapMatcher) iter.next();
Object rule = rules.get(midm);
Message.debug(prefix + midm + " -> " + rule);
}
}
}
/**
* Returns an unmodifiable view of all the rules defined on this ModuleRules.
* <p>
* The rules are returned in a Map where they keys are the MapMatchers matching the rules
* object, and the values are the rules object themselves.
* </p>
*
* @return an unmodifiable view of all the rules defined on this ModuleRules.
*/
public Map/*<MapMatcher,Object>*/ getAllRules() {
return Collections.unmodifiableMap(rules);
}
public Object clone() {
return new ModuleRules(rules);
}
}
|
sbt/ivy
|
src/java/org/apache/ivy/core/module/id/ModuleRules.java
|
Java
|
apache-2.0
| 9,699 |
# videostreaming
|
zensip/videostreaming
|
README.md
|
Markdown
|
apache-2.0
| 17 |
# Geastrum pseudolimbatus Hollós SPECIES
#### Status
ACCEPTED
#### According to
Index Fungorum
#### Published in
null
#### Original name
Geastrum pseudolimbatus Hollós
### Remarks
null
|
mdoering/backbone
|
life/Fungi/Basidiomycota/Agaricomycetes/Geastrales/Geastraceae/Geastrum/Geastrum pseudolimbatus/README.md
|
Markdown
|
apache-2.0
| 191 |
import d3 from "d3";
import React from "react";
import Maths from "../../utils/Maths";
var TimeSeriesMouseOver = React.createClass({
displayName: "TimeSeriesMouseOver",
propTypes: {
addMouseHandler: React.PropTypes.func.isRequired,
data: React.PropTypes.array.isRequired,
getBoundingBox: React.PropTypes.func.isRequired,
height: React.PropTypes.number.isRequired,
removeMouseHandler: React.PropTypes.func.isRequired,
width: React.PropTypes.number.isRequired,
xScale: React.PropTypes.func.isRequired,
y: React.PropTypes.string.isRequired,
yScale: React.PropTypes.func.isRequired,
yCaption: React.PropTypes.string.isRequired
},
componentDidMount() {
this.props.addMouseHandler(this.handleMouseMove, this.handleMouseOut);
},
componentWillUnmount() {
this.props.removeMouseHandler(this.handleMouseMove, this.handleMouseOut);
},
calculateMousePositionInGraph(e) {
var boundingBox = this.props.getBoundingBox();
var mouse = {
x: e.clientX || e.pageX,
y: e.clientY || e.pageY
};
if (
mouse.x < boundingBox.left ||
mouse.y < boundingBox.top ||
mouse.x > boundingBox.right ||
mouse.y > boundingBox.bottom
) {
return false;
}
mouse.x -= boundingBox.left;
mouse.y -= boundingBox.top;
return mouse;
},
handleMouseMove(e) {
var mouse = this.calculateMousePositionInGraph(e);
// This means that mouse is out of bounds
if (mouse === false) {
return;
}
var props = this.props;
var domain = props.xScale.domain();
var firstDataSet = props.data[0];
// how many data points we don't show
var hiddenDataPoints = 1;
// find the data point at the given mouse position
var index =
mouse.x *
(firstDataSet.values.length - hiddenDataPoints - 1) /
props.width;
index = Math.round(index + hiddenDataPoints);
d3
.select(this.refs.xMousePosition)
.transition()
.duration(50)
.attr("x1", mouse.x)
.attr("x2", mouse.x);
d3
.select(this.refs.yMousePosition)
.transition()
.duration(50)
.attr("y1", props.yScale(firstDataSet.values[index][props.y]))
.attr("y2", props.yScale(firstDataSet.values[index][props.y]));
d3
.select(this.refs.yAxisCurrent)
.transition()
.duration(50)
.attr("y", props.yScale(firstDataSet.values[index][props.y]))
// Default to 0 if state is unsuccessful.
.text((firstDataSet.values[index][props.y] || 0) + props.yCaption);
// An extra -2 on each because we show the extra data point at the end
var _index = mouse.x * (firstDataSet.values.length - 1) / props.width;
var mappedValue = Maths.mapValue(Math.round(_index), {
min: firstDataSet.values.length - hiddenDataPoints,
max: 0
});
var value = Maths.unmapValue(mappedValue, {
min: Math.abs(domain[1]),
max: Math.abs(domain[0])
});
value = Math.round(value);
var characterWidth = 7;
var xPosition = mouse.x - value.toString().length * characterWidth;
if (value === 0) {
xPosition += characterWidth / 2;
} else {
value = "-" + value + "s";
}
d3
.select(this.refs.xAxisCurrent)
.transition()
.duration(50)
.attr("x", xPosition)
// Default to 0 if state is unsuccessful.
.text(value || 0);
},
handleMouseOut() {
d3.select(this.refs.yMousePosition).interrupt();
d3.select(this.refs.xMousePosition).interrupt();
d3.select(this.refs.xAxisCurrent).text("");
d3.select(this.refs.yAxisCurrent).text("");
},
render() {
var height = this.props.height;
// dy=.71em, y=9 and x=-9, dy=.32em are magic numbers from looking at
// d3.js text values
return (
<g>
<g className="x axis">
<text
className="current-value shadow"
ref="xAxisCurrent"
dy=".71em"
y="9"
transform={"translate(0," + height + ")"}
/>
</g>
<g className="y axis">
<text
className="current-value shadow"
ref="yAxisCurrent"
style={{ textAnchor: "end" }}
dy=".32em"
x="-9"
/>
</g>
<line
className="chart-cursor-position-marker"
ref="xMousePosition"
y1={0}
y2={height}
/>
<line
className="chart-cursor-position-marker"
ref="yMousePosition"
x1={0}
x2={this.props.width}
/>
</g>
);
}
});
module.exports = TimeSeriesMouseOver;
|
jcloud-shengtai/dcos-ui_CN
|
src/js/components/charts/TimeSeriesMouseOver.js
|
JavaScript
|
apache-2.0
| 4,651 |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (1.8.0_151) on Tue Dec 12 12:37:09 MST 2017 -->
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>MarkerContainer (BOM: * : All 2012.12.0 API)</title>
<meta name="date" content="2017-12-12">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">
<script type="text/javascript" src="../../../../../script.js"></script>
</head>
<body>
<script type="text/javascript"><!--
try {
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="MarkerContainer (BOM: * : All 2012.12.0 API)";
}
}
catch(err) {
}
//-->
var methods = {"i0":17,"i1":18,"i2":17,"i3":18};
var tabs = {65535:["t0","All Methods"],1:["t1","Static Methods"],2:["t2","Instance Methods"],16:["t5","Default Methods"]};
var altColor = "altColor";
var rowColor = "rowColor";
var tableTab = "tableTab";
var activeTableTab = "activeTableTab";
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar.top">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.top.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="class-use/MarkerContainer.html">Use</a></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 class="aboutLanguage">WildFly Swarm API, 2012.12.0</div>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../../../org/wildfly/swarm/spi/api/JBossDeploymentStructureContainer.html" title="interface in org.wildfly.swarm.spi.api"><span class="typeNameLink">Prev Class</span></a></li>
<li><a href="../../../../../org/wildfly/swarm/spi/api/Module.html" title="class in org.wildfly.swarm.spi.api"><span class="typeNameLink">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../../../../index.html?org/wildfly/swarm/spi/api/MarkerContainer.html" target="_top">Frames</a></li>
<li><a href="MarkerContainer.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li>Nested | </li>
<li><a href="#field.summary">Field</a> | </li>
<li>Constr | </li>
<li><a href="#method.summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li><a href="#field.detail">Field</a> | </li>
<li>Constr | </li>
<li><a href="#method.detail">Method</a></li>
</ul>
</div>
<a name="skip.navbar.top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<!-- ======== START OF CLASS DATA ======== -->
<div class="header">
<div class="subTitle">org.wildfly.swarm.spi.api</div>
<h2 title="Interface MarkerContainer" class="title">Interface MarkerContainer<T extends <any>></h2>
</div>
<div class="contentContainer">
<div class="description">
<ul class="blockList">
<li class="blockList">
<dl>
<dt>All Known Subinterfaces:</dt>
<dd><a href="../../../../../org/wildfly/swarm/spi/api/DependenciesContainer.html" title="interface in org.wildfly.swarm.spi.api">DependenciesContainer</a><T>, <a href="../../../../../org/wildfly/swarm/jaxrs/JAXRSArchive.html" title="interface in org.wildfly.swarm.jaxrs">JAXRSArchive</a>, <a href="../../../../../org/wildfly/swarm/teiid/VDBArchive.html" title="interface in org.wildfly.swarm.teiid">VDBArchive</a>, <a href="../../../../../org/wildfly/swarm/undertow/WARArchive.html" title="interface in org.wildfly.swarm.undertow">WARArchive</a></dd>
</dl>
<hr>
<br>
<pre>public interface <span class="typeNameLabel">MarkerContainer<T extends <any>></span></pre>
<div class="block">Utility to track internal markers regarding operations performed upon archives.</div>
<dl>
<dt><span class="simpleTagLabel">Author:</span></dt>
<dd>Ken Finnigan</dd>
</dl>
</li>
</ul>
</div>
<div class="summary">
<ul class="blockList">
<li class="blockList">
<!-- =========== FIELD SUMMARY =========== -->
<ul class="blockList">
<li class="blockList"><a name="field.summary">
<!-- -->
</a>
<h3>Field Summary</h3>
<table class="memberSummary" border="0" cellpadding="3" cellspacing="0" summary="Field Summary table, listing fields, and an explanation">
<caption><span>Fields</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Field and Description</th>
</tr>
<tr class="altColor">
<td class="colFirst"><code>static ArchivePath</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../org/wildfly/swarm/spi/api/MarkerContainer.html#PATH_MARKERS">PATH_MARKERS</a></span></code> </td>
</tr>
</table>
</li>
</ul>
<!-- ========== METHOD SUMMARY =========== -->
<ul class="blockList">
<li class="blockList"><a name="method.summary">
<!-- -->
</a>
<h3>Method Summary</h3>
<table class="memberSummary" border="0" cellpadding="3" cellspacing="0" summary="Method Summary table, listing methods, and an explanation">
<caption><span id="t0" class="activeTableTab"><span>All Methods</span><span class="tabEnd"> </span></span><span id="t1" class="tableTab"><span><a href="javascript:show(1);">Static Methods</a></span><span class="tabEnd"> </span></span><span id="t2" class="tableTab"><span><a href="javascript:show(2);">Instance Methods</a></span><span class="tabEnd"> </span></span><span id="t5" class="tableTab"><span><a href="javascript:show(16);">Default Methods</a></span><span class="tabEnd"> </span></span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tr id="i0" class="altColor">
<td class="colFirst"><code>static void</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../org/wildfly/swarm/spi/api/MarkerContainer.html#addMarker--java.lang.String-">addMarker</a></span>(<any> manifestContainer,
<a href="http://docs.oracle.com/javase/8/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a> markerName)</code> </td>
</tr>
<tr id="i1" class="rowColor">
<td class="colFirst"><code>default <a href="../../../../../org/wildfly/swarm/spi/api/MarkerContainer.html" title="type parameter in MarkerContainer">T</a></code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../org/wildfly/swarm/spi/api/MarkerContainer.html#addMarker-java.lang.String-">addMarker</a></span>(<a href="http://docs.oracle.com/javase/8/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a> markerName)</code> </td>
</tr>
<tr id="i2" class="altColor">
<td class="colFirst"><code>static boolean</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../org/wildfly/swarm/spi/api/MarkerContainer.html#hasMarker--java.lang.String-">hasMarker</a></span>(<any> archive,
<a href="http://docs.oracle.com/javase/8/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a> markerName)</code> </td>
</tr>
<tr id="i3" class="rowColor">
<td class="colFirst"><code>default boolean</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../org/wildfly/swarm/spi/api/MarkerContainer.html#hasMarker-java.lang.String-">hasMarker</a></span>(<a href="http://docs.oracle.com/javase/8/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a> markerName)</code> </td>
</tr>
</table>
</li>
</ul>
</li>
</ul>
</div>
<div class="details">
<ul class="blockList">
<li class="blockList">
<!-- ============ FIELD DETAIL =========== -->
<ul class="blockList">
<li class="blockList"><a name="field.detail">
<!-- -->
</a>
<h3>Field Detail</h3>
<a name="PATH_MARKERS">
<!-- -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>PATH_MARKERS</h4>
<pre>static final ArchivePath PATH_MARKERS</pre>
</li>
</ul>
</li>
</ul>
<!-- ============ METHOD DETAIL ========== -->
<ul class="blockList">
<li class="blockList"><a name="method.detail">
<!-- -->
</a>
<h3>Method Detail</h3>
<a name="addMarker-java.lang.String-">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>addMarker</h4>
<pre>default <a href="../../../../../org/wildfly/swarm/spi/api/MarkerContainer.html" title="type parameter in MarkerContainer">T</a> addMarker(<a href="http://docs.oracle.com/javase/8/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a> markerName)</pre>
</li>
</ul>
<a name="hasMarker-java.lang.String-">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>hasMarker</h4>
<pre>default boolean hasMarker(<a href="http://docs.oracle.com/javase/8/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a> markerName)</pre>
</li>
</ul>
<a name="addMarker--java.lang.String-">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>addMarker</h4>
<pre>static void addMarker(<any> manifestContainer,
<a href="http://docs.oracle.com/javase/8/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a> markerName)</pre>
</li>
</ul>
<a name="hasMarker--java.lang.String-">
<!-- -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>hasMarker</h4>
<pre>static boolean hasMarker(<any> archive,
<a href="http://docs.oracle.com/javase/8/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a> markerName)</pre>
</li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
</div>
<!-- ========= END OF CLASS DATA ========= -->
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar.bottom">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.bottom.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="class-use/MarkerContainer.html">Use</a></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 class="aboutLanguage">WildFly Swarm API, 2012.12.0</div>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../../../org/wildfly/swarm/spi/api/JBossDeploymentStructureContainer.html" title="interface in org.wildfly.swarm.spi.api"><span class="typeNameLink">Prev Class</span></a></li>
<li><a href="../../../../../org/wildfly/swarm/spi/api/Module.html" title="class in org.wildfly.swarm.spi.api"><span class="typeNameLink">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../../../../index.html?org/wildfly/swarm/spi/api/MarkerContainer.html" target="_top">Frames</a></li>
<li><a href="MarkerContainer.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li>Nested | </li>
<li><a href="#field.summary">Field</a> | </li>
<li>Constr | </li>
<li><a href="#method.summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li><a href="#field.detail">Field</a> | </li>
<li>Constr | </li>
<li><a href="#method.detail">Method</a></li>
</ul>
</div>
<a name="skip.navbar.bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<p class="legalCopy"><small>Copyright © 2017 <a href="http://www.jboss.org">JBoss by Red Hat</a>. All rights reserved.</small></p>
</body>
</html>
|
wildfly-swarm/wildfly-swarm-javadocs
|
2012.12.0/apidocs/org/wildfly/swarm/spi/api/MarkerContainer.html
|
HTML
|
apache-2.0
| 13,371 |
<!-- Default box -->
<div class="box">
<div class="box-header with-border">
<h3 class="box-title">{{ "Lista de Citas" }}</h3>
<div class="box-tools pull-right">
<a title="{{ "Añadir Cita" }}" href="{{ $Module->url("addquote", ["n"=>"y"]) }}" type="button" class="btn btn-box-tool"><i class="fa fa-plus"></i></a>
</div>
</div>
<div class="box-body">
@foreach($quotes AS $q)
<div class="col-xs-12 col-sm-12 col-md-6 col-lg-6">
<div class="quotation">
<p class="quote_content">
<img width="20px" src="{!! $Module->getAssetUrl("img/quote_start.png") !!}" />{!! $q -> quote !!} <img width="20px" src="{!! $Module->getAssetUrl("img/quote_end.png") !!}" />
</p>
<p class="quote_footer">
<i>{!! $q -> origin !!} - {!! $q -> name !!}</i>
</p>
<div class="quotation_options">
<a target="_blank" title="{{ "Ver" }}" href="{{ $Module->url("quotespecial", ["id"=>$q->id]) }}"><i class="fa fa-eye"></i></a>
<a title="{{ "Editar" }}" href="{{ $Module->url("addquote", ["id"=>$q->id]) }}"><i class="fa fa-pencil"></i></a>
</div>
</div>
</div>
@endforeach
</div>
<!-- /.box-body -->
<div class="box-footer">
</div>
<!-- /.box-footer-->
</div>
<!-- /.box -->
|
danilor/Luminus
|
resources/views/modules/cutequotes/quotes_list.blade.php
|
PHP
|
apache-2.0
| 1,739 |
package org.gradle.test.performance.mediummonolithicjavaproject.p186;
public class Production3735 {
private Production3732 property0;
public Production3732 getProperty0() {
return property0;
}
public void setProperty0(Production3732 value) {
property0 = value;
}
private Production3733 property1;
public Production3733 getProperty1() {
return property1;
}
public void setProperty1(Production3733 value) {
property1 = value;
}
private Production3734 property2;
public Production3734 getProperty2() {
return property2;
}
public void setProperty2(Production3734 value) {
property2 = value;
}
private String property3;
public String getProperty3() {
return property3;
}
public void setProperty3(String value) {
property3 = value;
}
private String property4;
public String getProperty4() {
return property4;
}
public void setProperty4(String value) {
property4 = value;
}
private String property5;
public String getProperty5() {
return property5;
}
public void setProperty5(String value) {
property5 = value;
}
private String property6;
public String getProperty6() {
return property6;
}
public void setProperty6(String value) {
property6 = value;
}
private String property7;
public String getProperty7() {
return property7;
}
public void setProperty7(String value) {
property7 = value;
}
private String property8;
public String getProperty8() {
return property8;
}
public void setProperty8(String value) {
property8 = value;
}
private String property9;
public String getProperty9() {
return property9;
}
public void setProperty9(String value) {
property9 = value;
}
}
|
oehme/analysing-gradle-performance
|
my-app/src/main/java/org/gradle/test/performance/mediummonolithicjavaproject/p186/Production3735.java
|
Java
|
apache-2.0
| 1,963 |
<!DOCTYPE html>
<html lang="en" class="js csstransforms3d">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
<meta name="generator" content="Hugo 0.21" />
<meta name="description" content="">
<link rel="shortcut icon" href="/images/favicon.png" type="image/x-icon" />
<title>What is this Ian ?</title>
<link href="http://goian.io/css/nucleus.css" rel="stylesheet">
<link href="http://goian.io/css/font-awesome.min.css" rel="stylesheet">
<link href="http://goian.io/css/hybrid.css" rel="stylesheet">
<link href="http://goian.io/css/featherlight.min.css" rel="stylesheet">
<link href="http://goian.io/css/perfect-scrollbar.min.css" rel="stylesheet">
<link href="http://goian.io/css/horsey.css" rel="stylesheet">
<link href="http://goian.io/css/theme.css" rel="stylesheet">
<link href="http://goian.io/css/hugo-theme.css" rel="stylesheet">
<script src="http://goian.io/js/jquery-2.x.min.js"></script>
<style type="text/css">:root #header + #content > #left > #rlblock_left
{display:none !important;}</style>
</head>
<body class="" data-url="/basics/what-is-ian/">
<nav id="sidebar">
<div id="header-wrapper">
<div id="header">
<img src="/img/logo_white.png" alt="ian-logo">
</div>
</div>
<div class="highlightable">
<ul class="topics">
<li class="dd-item parent" data-nav-id="/basics/">
<a href="/basics/">
<span>
<b>1. </b>
Basics
</span>
</a>
<ul>
<li class="dd-item active" data-nav-id="/basics/what-is-ian/">
<a href="/basics/what-is-ian/">
<span>What is this Ian ? </i></span>
</a>
</li>
<li class="dd-item " data-nav-id="/basics/getting-started/">
<a href="/basics/getting-started/">
<span>Getting started </i></span>
</a>
</li>
<li class="dd-item " data-nav-id="/basics/configuration/">
<a href="/basics/configuration/">
<span>Configuration </i></span>
</a>
</li>
</ul>
</li>
<li class="dd-item " data-nav-id="/contributing/">
<a href="/contributing/">
<span>
<b>2. </b>
Contributing
</span>
</a>
</li>
<li class="dd-item " data-nav-id="/changelog/">
<a href="/changelog/">
<span>
<b>3. </b>
Changelog
</span>
</a>
</li>
<li class="dd-item " data-nav-id="/license/">
<a href="/license/">
<span>
<b>4. </b>
License
</span>
</a>
</li>
</ul>
<hr>
<section id="footer">
<p>Built with <a href="https://github.com/matcornic/hugo-theme-learn"><i class="fa fa-heart"></i></a> from <a href="http://getgrav.org">Grav</a> and <a href="http://gohugo.io/">Hugo</a></p>
</section>
</div>
</nav>
<section id="body">
<div id="overlay"></div>
<div class="padding highlightable">
<div id="top-bar">
<div id="top-github-link">
<a class="github-link" href="https://github.com/thylong/ian/edit/master/docs/content/basics/what-is-ian.md" target="blank">
<i class="fa fa-code-fork"></i>
Edit this page
</a>
</div>
<div id="breadcrumbs" itemscope="" itemtype="http://data-vocabulary.org/Breadcrumb">
<span id="sidebar-toggle-span">
<a href="#" id="sidebar-toggle" data-sidebar-toggle="">
<i class="fa fa-bars"></i>
</a>
</span>
<a href="/basics/" itemprop="url"><span itemprop="title">Basics</span></a> <i class="fa fa-angle-right"></i>
<span itemprop="title"> What is this Ian ?</span>
</div>
</div>
<div id="body-inner">
<h1>What is this Ian ?</h1>
<p><strong>Ian is a simple tool to manage your development environment and your coding projects.</strong></p>
<h2 id="the-idea-behind-ian">The idea behind Ian</h2>
<p>Us, developers, love to work with the terminal. More reliable and simpler than most GUIs, this “black screen” allows also automation through scripting and blazing fast manipulation.</p>
<p>But even with these capabilities, we still execute pretty repetitive tasks and have troubles to make our local environment portable.
Sometimes, we’re looking in our history to retrieve a database URI, change from one project directory to another one just to execute a command, and so on.</p>
<p>Ian was designed and created to solve these problems.</p>
<h2 id="how-does-ian-tackle-this-problem">How does ian tackle this problem ?</h2>
<p>ian propose your to store and persist your projects and env configuration in order to interact with them more easily.
You can (among others things):</p>
<ul>
<li>List the packages installed on your environment and have them installed anytime you run ian on another device.</li>
<li>Register commands per projects and give them an alias</li>
<li>Update/upgrade your environment with a unified interface</li>
</ul>
<h2 id="every-developer-is-unique">Every developer is unique</h2>
<p>… Which bring us to customization and social interactions (yes, for those who still doubt about it, we are human too) !</p>
<h3 id="maximum-customization">Maximum customization</h3>
<p>We decided to offer the maximum customization possible to make you able to interact with your environment the way you like it.
In brief, we give you a set of default commands that we find useful in general and we let you add any subcommands you’d like to execute.</p>
<h3 id="the-notion-of-project-context">The notion of project context</h3>
<p>Projects depend on a huge number of factors: languages, platforms, frameworks, host ressources, etc
With ian, through an interactive setup you can provide the infos necessary to specific the context of execution of all the project commmands.</p>
<h3 id="share-your-configuration">Share your configuration</h3>
<p>Using ian share, you can share your ian configuration files</p>
<p>In the next page, we’ll go though the setup together :)</p>
</div>
</div>
<div id="navigation">
<a class="nav nav-prev" href="http://goian.io/basics"> <i class="fa fa-chevron-left"></i></a>
<a class="nav nav-next" href="http://goian.io/basics/getting-started" style="margin-right: 0px;"><i class="fa fa-chevron-right"></i></a>
</div>
</section>
<div style="left: -1000px; overflow: scroll; position: absolute; top: -1000px; border: none; box-sizing: content-box; height: 200px; margin: 0px; padding: 0px; width: 200px;">
<div style="border: none; box-sizing: content-box; height: 200px; margin: 0px; padding: 0px; width: 200px;"></div>
</div>
<script src="http://goian.io/js/clipboard.min.js"></script>
<script src="http://goian.io/js/perfect-scrollbar.min.js"></script>
<script src="http://goian.io/js/perfect-scrollbar.jquery.min.js"></script>
<script src="http://goian.io/js/jquery.sticky-kit.min.js"></script>
<script src="http://goian.io/js/featherlight.min.js"></script>
<script src="http://goian.io/js/html5shiv-printshiv.min.js"></script>
<script src="http://goian.io/js/highlight.pack.js"></script>
<script>hljs.initHighlightingOnLoad();</script>
<script src="http://goian.io/js/modernizr.custom.71422.js"></script>
<script src="http://goian.io/js/learn.js"></script>
<script src="http://goian.io/js/hugo-learn.js"></script>
</body>
</html>
|
thylong/ian
|
docs/basics/what-is-ian/index.html
|
HTML
|
apache-2.0
| 9,231 |
/*
* Copyright 2015-2020 OpenCB
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.opencb.cellbase.lib.install;
import org.opencb.cellbase.core.common.Species;
import org.opencb.cellbase.core.config.CellBaseConfiguration;
import org.opencb.cellbase.core.config.SpeciesConfiguration;
import org.opencb.cellbase.core.exception.CellBaseException;
import org.opencb.cellbase.core.utils.SpeciesUtils;
import org.opencb.cellbase.lib.db.MongoDBManager;
import org.opencb.commons.datastore.mongodb.MongoDataStore;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.List;
public class InstallManager {
private CellBaseConfiguration configuration;
private Logger logger;
public InstallManager(CellBaseConfiguration configuration) {
this.configuration = configuration;
logger = LoggerFactory.getLogger(this.getClass());
}
/**
* Add shard indexes and ranges in Mongo based on config file entries.
*
* @param speciesName name of species
* @param assemblyName name of assembly
* @throws CellBaseException if invalid input
*/
public void install(String speciesName, String assemblyName) throws CellBaseException {
// TDDO check database credentials
// user API perms
// check repl sets
Species species = SpeciesUtils.getSpecies(configuration, speciesName, assemblyName);
SpeciesConfiguration speciesConfiguration = configuration.getSpeciesConfig(species.getId());
if (speciesConfiguration == null) {
LoggerFactory.getLogger(MongoDBShardUtils.class).warn("No config found for '" + species.getId() + "'");
return;
}
List<SpeciesConfiguration.ShardConfig> shards = speciesConfiguration.getShards();
if (shards != null) {
// if sharding in config
shard(species);
}
}
private void shard(Species species) throws CellBaseException {
MongoDBManager mongoDBManager = new MongoDBManager(configuration);
MongoDataStore mongoDBDatastore = mongoDBManager.createMongoDBDatastore(species.getId(), species.getAssembly());
MongoDBShardUtils.shard(mongoDBDatastore, configuration, species);
}
}
|
opencb/cellbase
|
cellbase-lib/src/main/java/org/opencb/cellbase/lib/install/InstallManager.java
|
Java
|
apache-2.0
| 2,757 |
#!/usr/bin/env bash
docker pull clakech/docker-spark
docker run -d -t -P --name spark_master clakech/docker-spark /start-master.sh "$@"
|
clakech/docker-spark
|
start-master.sh
|
Shell
|
apache-2.0
| 136 |
// (C) Copyright 2014-2016 Hewlett Packard Enterprise Development LP
import Grommet from './index-commonjs';
const BaseIcons = {};
Object.keys(Grommet.Icons.Base).forEach((icon) => {
BaseIcons[icon.replace('Icon', '')] = Grommet.Icons.Base[icon];
});
export const Icons = Object.assign({}, Grommet.Icons, { Base: BaseIcons });
export { default as Accordion } from './components/Accordion';
export { default as AccordionPanel } from './components/AccordionPanel';
export { default as Anchor } from './components/Anchor';
export { default as Animate } from './components/Animate';
export { default as App } from './components/App';
export { default as Article } from './components/Article';
export { default as Box } from './components/Box';
export { default as Button } from './components/Button';
export { default as Card } from './components/Card';
export { default as Carousel } from './components/Carousel';
export * from './components/chart';
export { default as CheckBox } from './components/CheckBox';
export { default as Columns } from './components/Columns';
export { default as DateTime } from './components/DateTime';
export { default as Distribution } from './components/Distribution';
export { default as Footer } from './components/Footer';
export { default as Form } from './components/Form';
export { default as FormattedMessage } from './components/FormattedMessage';
export { default as FormField } from './components/FormField';
export { default as FormFields } from './components/FormFields';
export { default as Grommet } from './components/Grommet';
export { default as Header } from './components/Header';
export { default as Heading } from './components/Heading';
export { default as Headline } from './components/Headline';
export { default as Hero } from './components/Hero';
export { default as Image } from './components/Image';
export { default as Label } from './components/Label';
export { default as Layer } from './components/Layer';
export { default as Legend } from './components/Legend';
export { default as List } from './components/List';
export { default as ListItem } from './components/ListItem';
export { default as LoginForm } from './components/LoginForm';
export { default as Map } from './components/Map';
export { default as Markdown } from './components/Markdown';
export { default as Menu } from './components/Menu';
export { default as Meter } from './components/Meter';
export { default as Notification } from './components/Notification';
export { default as NumberInput } from './components/NumberInput';
export { default as Object } from './components/Object';
export { default as Paragraph } from './components/Paragraph';
export { default as Quote } from './components/Quote';
export { default as RadioButton } from './components/RadioButton';
export { default as Search } from './components/Search';
export { default as SearchInput } from './components/SearchInput';
export { default as Section } from './components/Section';
export { default as Select } from './components/Select';
export { default as Sidebar } from './components/Sidebar';
export { default as SkipLinkAnchor } from './components/SkipLinkAnchor';
export { default as SkipLinks } from './components/SkipLinks';
export { default as SocialShare } from './components/SocialShare';
export { default as Split } from './components/Split';
export { default as SunBurst } from './components/SunBurst';
export { default as SVGIcon } from './components/SVGIcon';
export { default as Tab } from './components/Tab';
export { default as Table } from './components/Table';
export { default as TableHeader } from './components/TableHeader';
export { default as TableRow } from './components/TableRow';
export { default as Tabs } from './components/Tabs';
export { default as TBD } from './components/TBD';
export { default as TextInput } from './components/TextInput';
export { default as Tile } from './components/Tile';
export { default as Tiles } from './components/Tiles';
export { default as Timestamp } from './components/Timestamp';
export { default as Tip } from './components/Tip';
export { default as Title } from './components/Title';
export { default as Toast } from './components/Toast';
export { default as Topology } from './components/Topology';
export { default as Value } from './components/Value';
export { default as Video } from './components/Video';
export { default as WorldMap } from './components/WorldMap';
export * from './components/icons';
export { default as Cookies }from './utils/Cookies';
export { default as DOM } from './utils/DOM';
export { default as KeyboardAccelerators } from './utils/KeyboardAccelerators';
export { default as Locale } from './utils/Locale';
export { default as Responsive } from './utils/Responsive';
export { default as Rest } from './utils/Rest';
export { default as Validator } from './utils/Validator';
export default { ...Grommet };
|
linde12/grommet
|
src/js/index.js
|
JavaScript
|
apache-2.0
| 4,911 |
package org.apache.http.impl.cookie;
/*
* #%L
* Matos
* $Id:$
* $HeadURL:$
* %%
* Copyright (C) 2010 - 2014 Orange SA
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
@com.francetelecom.rd.stubs.annotation.ClassDone(0)
public class BasicPathHandler
implements org.apache.http.cookie.CookieAttributeHandler
{
// Constructors
public BasicPathHandler(){
}
// Methods
public void parse(org.apache.http.cookie.SetCookie arg1, java.lang.String arg2) throws org.apache.http.cookie.MalformedCookieException{
}
public boolean match(org.apache.http.cookie.Cookie arg1, org.apache.http.cookie.CookieOrigin arg2){
return false;
}
public void validate(org.apache.http.cookie.Cookie arg1, org.apache.http.cookie.CookieOrigin arg2) throws org.apache.http.cookie.MalformedCookieException{
}
}
|
Orange-OpenSource/matos-profiles
|
matos-android/src/main/java/org/apache/http/impl/cookie/BasicPathHandler.java
|
Java
|
apache-2.0
| 1,340 |
package net.miz_hi.smileessence.theme.impl;
import net.miz_hi.smileessence.R;
import net.miz_hi.smileessence.theme.IColorTheme;
public class LightColorTheme implements IColorTheme
{
@Override
public int getBackground1()
{
return R.color.White;
}
@Override
public int getBackground2()
{
return R.color.LightGray;
}
@Override
public int getNormalTextColor()
{
return R.color.Gray;
}
@Override
public int getHeaderTextColor()
{
return R.color.ThickGreen;
}
@Override
public int getHintTextColor()
{
return R.color.Gray2;
}
@Override
public int getSpecialTextColor()
{
return R.color.DarkBlue;
}
@Override
public int getMentionsBackgroundColor()
{
return R.color.LightRed;
}
@Override
public int getRetweetBackgroundColor()
{
return R.color.LightBlue;
}
@Override
public int getDialogBorderColor()
{
return R.color.MetroBlue;
}
@Override
public int getTitleTextColor()
{
return R.color.MetroBlue;
}
@Override
public int getHyperlinkTextColor()
{
return R.color.MetroBlue;
}
@Override
public int getMenuItemLayout()
{
return R.layout.menuitem_white;
}
@Override
public int getMenuParentLayout()
{
return R.layout.menuparent_white;
}
@Override
public int getMenuParentCloseIcon()
{
return R.drawable.expand_close;
}
@Override
public int getMenuParentOpenIcon()
{
return R.drawable.expand_open;
}
@Override
public int getMessageIcon()
{
return R.drawable.icon_message;
}
@Override
public int getRetweetIcon()
{
return R.drawable.icon_retweet_off;
}
@Override
public int getFavoriteOffIcon()
{
return R.drawable.icon_favorite_off;
}
@Override
public int getFavoriteOnIcon()
{
return R.drawable.icon_favorite_on;
}
@Override
public int getGarbageIcon()
{
return R.drawable.icon_garbage;
}
@Override
public int getMenuIcon()
{
return R.drawable.icon_menu;
}
@Override
public int getPictureIcon()
{
return R.drawable.icon_pict;
}
@Override
public int getConfigIcon()
{
return R.drawable.icon_config;
}
@Override
public int getDeleteIcon()
{
return R.drawable.icon_delete;
}
}
|
laco0416/SmileEssence-Lite
|
src/net/miz_hi/smileessence/theme/impl/LightColorTheme.java
|
Java
|
apache-2.0
| 2,569 |
package com.graphhopper.routing.util.probabilistic;
public enum GridEntryValueType
{
WEATHER_ATMOSPHERE_HUMIDITY,
WEATHER_ATMOSPHERE_PRESSURE,
WEATHER_CLOUDAGE,
WEATHER_MAXIMUM_WIND_SPEED,
WEATHER_PRECIPITATION_DEPTH,
WEATHER_SNOW_HEIGHT,
WEATHER_SUNSHINE_DURATION,
WEATHER_TEMPERATURE,
WEATHER_TEMPERATURE_HIGH,
WEATHER_TEMPERATURE_LOW,
WEATHER_WINDCHILL,
}
|
CEPFU/graphhopper
|
core/src/main/java/com/graphhopper/routing/util/probabilistic/GridEntryValueType.java
|
Java
|
apache-2.0
| 404 |
<?php
class Magentothem_Imagerotator_IndexController extends Mage_Core_Controller_Front_Action
{
public function indexAction()
{
/*
* Load an object by id
* Request looking like:
* http://site.com/imagerotator?id=15
* or
* http://site.com/imagerotator/id/15
*/
/*
$imagerotator_id = $this->getRequest()->getParam('id');
if($imagerotator_id != null && $imagerotator_id != '') {
$imagerotator = Mage::getModel('imagerotator/imagerotator')->load($imagerotator_id)->getData();
} else {
$imagerotator = null;
}
*/
/*
* If no param we load a the last created item
*/
/*
if($imagerotator == null) {
$resource = Mage::getSingleton('core/resource');
$read= $resource->getConnection('core_read');
$imagerotatorTable = $resource->getTableName('imagerotator');
$select = $read->select()
->from($imagerotatorTable,array('imagerotator_id','title','content','status'))
->where('status',1)
->order('created_time DESC') ;
$imagerotator = $read->fetchRow($select);
}
Mage::register('imagerotator', $imagerotator);
*/
$this->loadLayout();
$this->renderLayout();
}
}
|
cArLiiToX/dtstore
|
app/code/local/Magentothem/Imagerotator/controllers/IndexController.php
|
PHP
|
apache-2.0
| 1,275 |
// ----------------------------------------------------------------------------
// Copyright 2007-2011, GeoTelematic Solutions, Inc.
// All rights reserved
// ----------------------------------------------------------------------------
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// ----------------------------------------------------------------------------
// Database specific 'DELETE' handler.
// ----------------------------------------------------------------------------
// Change History:
// 2007/09/16 Martin D. Flynn
// -Initial release
// -NOTE: This module is not thread safe (this is typically not an issue, since
// the use of this class is limited to the creation for a specific 'DELETE'
// statement within a given thread).
// ----------------------------------------------------------------------------
package org.opengts.dbtools;
import java.lang.*;
import java.util.*;
import java.io.*;
import java.text.*;
import java.sql.*;
import org.opengts.util.*;
/**
*** <code>DBDelete</code> provides the creation of the SQL provider specific
*** DELETE statement.
**/
public class DBDelete
{
// ------------------------------------------------------------------------
private DBFactory factory = null;
private String utableName = null;
private String where = null;
/**
*** Constructor
*** @param fact The table DBFactory
**/
public DBDelete(DBFactory fact)
{
this.factory = fact;
}
// ------------------------------------------------------------------------
/**
*** Returns true if a DBFactory has been defined
*** @return True if a DBFactory has been defined
**/
public boolean hasFactory()
{
return (this.factory != null);
}
/**
*** Gets the DBFactory defined for this DBDelete
*** @return The defined DBFactory
**/
public DBFactory getFactory()
{
return this.factory;
}
// ------------------------------------------------------------------------
/**
*** Sets the untranslated table name for this DBDelete (if not set, the table
*** name of the defined DBFactory will be used).
*** @param utableName The table name
**/
public void setUntranslatedTableName(String utableName)
{
this.utableName = !StringTools.isBlank(utableName)? utableName : null;
}
/**
*** Gets the untranslated table name for this DBDelete
*** @return The defined table name
**/
public String getUntranslatedTableName()
{
if (this.utableName != null) {
return this.utableName;
} else
if (this.hasFactory()) {
return this.getFactory().getUntranslatedTableName();
} else {
return "UNKNOWN";
}
}
/**
*** Gets the table name for this DBSelect
*** @return The defined table name
**/
public String getTranslatedTableName()
{
return DBProvider.translateTableName(this.getUntranslatedTableName());
}
// ------------------------------------------------------------------------
/**
*** Creates a new DBWhere instance (calling 'setWhere(...)' is still required in order
*** to used the created DBWhere instance for this DBDelete).
*** @return The new DBWhere instance
**/
public DBWhere createDBWhere()
{
return new DBWhere(this.getFactory());
}
/**
*** Sets the DBWhere instance used for this DBDelete
*** @param wh The DBWhere instance used for this DBDelete
**/
public void setWhere(String wh)
{
if (StringTools.isBlank(wh)) {
this.where = null;
} else {
wh = wh.trim();
if (StringTools.startsWithIgnoreCase(wh,"WHERE ")) {
this.where = wh;
} else {
this.where = "WHERE ( " + wh + " )";
}
}
}
/**
*** Returns true if this DBDelete has a defined where clause
*** @return True if this DBDelete has a defined where clause
**/
public boolean hasWhere()
{
return (this.where != null);
}
/**
*** Gets the where clause for this DBDelete
*** @return The where clause for this DBDelete
**/
public String getWhere()
{
return this.where;
}
// ------------------------------------------------------------------------
/**
*** Returns the DELETE statement for this DBDelete
*** @return The DELETE statement for this DBDelete
**/
public String toString()
{
StringBuffer sb = new StringBuffer();
/* DELETE FROM */
sb.append("DELETE FROM ");
sb.append(this.getTranslatedTableName());
/* WHERE */
if (this.hasWhere()) {
sb.append(" ");
sb.append(this.getWhere());
}
return sb.toString();
}
// ------------------------------------------------------------------------
}
|
CASPED/OpenGTS
|
src/org/opengts/dbtools/DBDelete.java
|
Java
|
apache-2.0
| 5,553 |
/*
* Copyright 2010-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
#pragma once
#include <aws/fsx/FSx_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <aws/core/utils/memory/stl/AWSVector.h>
#include <aws/fsx/model/Tag.h>
#include <utility>
namespace Aws
{
namespace Utils
{
namespace Json
{
class JsonValue;
class JsonView;
} // namespace Json
} // namespace Utils
namespace FSx
{
namespace Model
{
/**
* <p>The response object for the Microsoft Windows file system used in the
* <code>DeleteFileSystem</code> operation.</p><p><h3>See Also:</h3> <a
* href="http://docs.aws.amazon.com/goto/WebAPI/fsx-2018-03-01/DeleteFileSystemWindowsResponse">AWS
* API Reference</a></p>
*/
class AWS_FSX_API DeleteFileSystemWindowsResponse
{
public:
DeleteFileSystemWindowsResponse();
DeleteFileSystemWindowsResponse(Aws::Utils::Json::JsonView jsonValue);
DeleteFileSystemWindowsResponse& operator=(Aws::Utils::Json::JsonView jsonValue);
Aws::Utils::Json::JsonValue Jsonize() const;
/**
* <p>The ID of the final backup for this file system.</p>
*/
inline const Aws::String& GetFinalBackupId() const{ return m_finalBackupId; }
/**
* <p>The ID of the final backup for this file system.</p>
*/
inline bool FinalBackupIdHasBeenSet() const { return m_finalBackupIdHasBeenSet; }
/**
* <p>The ID of the final backup for this file system.</p>
*/
inline void SetFinalBackupId(const Aws::String& value) { m_finalBackupIdHasBeenSet = true; m_finalBackupId = value; }
/**
* <p>The ID of the final backup for this file system.</p>
*/
inline void SetFinalBackupId(Aws::String&& value) { m_finalBackupIdHasBeenSet = true; m_finalBackupId = std::move(value); }
/**
* <p>The ID of the final backup for this file system.</p>
*/
inline void SetFinalBackupId(const char* value) { m_finalBackupIdHasBeenSet = true; m_finalBackupId.assign(value); }
/**
* <p>The ID of the final backup for this file system.</p>
*/
inline DeleteFileSystemWindowsResponse& WithFinalBackupId(const Aws::String& value) { SetFinalBackupId(value); return *this;}
/**
* <p>The ID of the final backup for this file system.</p>
*/
inline DeleteFileSystemWindowsResponse& WithFinalBackupId(Aws::String&& value) { SetFinalBackupId(std::move(value)); return *this;}
/**
* <p>The ID of the final backup for this file system.</p>
*/
inline DeleteFileSystemWindowsResponse& WithFinalBackupId(const char* value) { SetFinalBackupId(value); return *this;}
/**
* <p>The set of tags applied to the final backup.</p>
*/
inline const Aws::Vector<Tag>& GetFinalBackupTags() const{ return m_finalBackupTags; }
/**
* <p>The set of tags applied to the final backup.</p>
*/
inline bool FinalBackupTagsHasBeenSet() const { return m_finalBackupTagsHasBeenSet; }
/**
* <p>The set of tags applied to the final backup.</p>
*/
inline void SetFinalBackupTags(const Aws::Vector<Tag>& value) { m_finalBackupTagsHasBeenSet = true; m_finalBackupTags = value; }
/**
* <p>The set of tags applied to the final backup.</p>
*/
inline void SetFinalBackupTags(Aws::Vector<Tag>&& value) { m_finalBackupTagsHasBeenSet = true; m_finalBackupTags = std::move(value); }
/**
* <p>The set of tags applied to the final backup.</p>
*/
inline DeleteFileSystemWindowsResponse& WithFinalBackupTags(const Aws::Vector<Tag>& value) { SetFinalBackupTags(value); return *this;}
/**
* <p>The set of tags applied to the final backup.</p>
*/
inline DeleteFileSystemWindowsResponse& WithFinalBackupTags(Aws::Vector<Tag>&& value) { SetFinalBackupTags(std::move(value)); return *this;}
/**
* <p>The set of tags applied to the final backup.</p>
*/
inline DeleteFileSystemWindowsResponse& AddFinalBackupTags(const Tag& value) { m_finalBackupTagsHasBeenSet = true; m_finalBackupTags.push_back(value); return *this; }
/**
* <p>The set of tags applied to the final backup.</p>
*/
inline DeleteFileSystemWindowsResponse& AddFinalBackupTags(Tag&& value) { m_finalBackupTagsHasBeenSet = true; m_finalBackupTags.push_back(std::move(value)); return *this; }
private:
Aws::String m_finalBackupId;
bool m_finalBackupIdHasBeenSet;
Aws::Vector<Tag> m_finalBackupTags;
bool m_finalBackupTagsHasBeenSet;
};
} // namespace Model
} // namespace FSx
} // namespace Aws
|
cedral/aws-sdk-cpp
|
aws-cpp-sdk-fsx/include/aws/fsx/model/DeleteFileSystemWindowsResponse.h
|
C
|
apache-2.0
| 5,034 |
# txspider
txspider 蜘蛛程序
### 环境推荐
> php5.5+
> mysql 5.6+
> 打开rewrite
### 安装步骤
1.创建 txspider数据库(默认编码utf8mb4),并导入 update/txspider.sql
2.在 data目录下创建 conf/database.php 文件,内容如下:
```php
<?php
return [
// 数据库类型
'type' => 'mysql',
// 服务器地址
'hostname' => 'localhost',
// 数据库名
'database' => '你的数据库名',
// 用户名
'username' => '你的数据库用户名',
// 密码
'password' => '你的数据库密码',
// 端口
'hostport' => '3306',
// 数据库编码默认采用utf8
'charset' => 'utf8mb4',
// 数据库表前缀
'prefix' => 'cmf_',
"authcode" => 'CviMdXkZ3vUxyJCwNt',
];
```
更改为你的数据库信息
3.把 public目录做为网站根目录,入口文件在 public/index.php
4.后台 你的域名/admin
用户名/密码:admin/111111
|
txterm/txsprider
|
README.md
|
Markdown
|
apache-2.0
| 982 |
# Lycaste deppei var. punctatissima VARIETY
#### Status
SYNONYM
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null
|
mdoering/backbone
|
life/Plantae/Magnoliophyta/Liliopsida/Asparagales/Orchidaceae/Lycaste/Lycaste smeeana/ Syn. Lycaste deppei punctatissima/README.md
|
Markdown
|
apache-2.0
| 190 |
# Diaporthe castanea (Tul. & C. Tul.) Sacc., 1882 SPECIES
#### Status
SYNONYM
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
Syll. fung. (Abellini) 1: 624 (1882)
#### Original name
Valsa castanea Tul. & C. Tul., 1863
### Remarks
null
|
mdoering/backbone
|
life/Fungi/Ascomycota/Sordariomycetes/Diaporthales/Gnomoniaceae/Cryptodiaporthe/Cryptodiaporthe castanea/ Syn. Diaporthe castanea/README.md
|
Markdown
|
apache-2.0
| 267 |
# Argyrolobium calycinum (M.Bieb.) Jaub. & Spach SPECIES
#### Status
SYNONYM
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
Ill. pl. orient. 1:115. 1843
#### Original name
null
### Remarks
null
|
mdoering/backbone
|
life/Plantae/Magnoliophyta/Magnoliopsida/Fabales/Fabaceae/Argyrolobium/Argyrolobium biebersteinii/ Syn. Argyrolobium calycinum/README.md
|
Markdown
|
apache-2.0
| 227 |
package com.myit.server.service.member.impl;
import javax.annotation.Resource;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;
import com.myit.common.util.Constant;
import com.myit.common.util.RetCode;
import com.myit.common.util.StringConvert;
import com.myit.intf.bean.member.CloseAccountReq;
import com.myit.intf.bean.member.CloseAccountResp;
import com.myit.intf.bean.member.LoginReq;
import com.myit.intf.bean.member.LoginResp;
import com.myit.intf.bean.member.LogoutReq;
import com.myit.intf.bean.member.LogoutResp;
import com.myit.intf.bean.member.RegistReq;
import com.myit.intf.bean.member.RegistResp;
import com.myit.intf.service.member.MemberService;
import com.myit.server.dao.member.MemberInfoDao;
import com.myit.server.model.member.MemberInfo;
@Service("memberService")
public class MemberServiceImpl implements MemberService {
private static final Logger LOGGER = Logger.getLogger(MemberServiceImpl.class);
@Resource
private MemberInfoDao memberInfoDao;
public RegistResp regist(RegistReq registReq) throws Exception {
LOGGER.info("regist IN");
RegistResp registResp = new RegistResp();
// 验证参数是否完整
if (registReq == null) {
LOGGER.warn("registReq is null");
registResp.setRetCode(RetCode.FAILED);
return registResp;
}
// 构造会员实体类
MemberInfo memberInfo = initMemberInfo(registReq);
// 会员密码md5+key加密
String key = Constant.KEY_PASSWORD;
String memberPwd = StringConvert.passwordMD5(registReq.getPassword(), key);
memberInfo.setPassword(memberPwd);
// 持久化到数据库
LOGGER.info("persist MemberInfo");
memberInfoDao.persistMemberInfo(memberInfo);
// 持久化成功
registResp.setRetCode(RetCode.SUCCESS);
registResp.setMemberNo(registReq.getMemberNo());
LOGGER.info("regist OUT");
return registResp;
}
private MemberInfo initMemberInfo(RegistReq registReq) {
MemberInfo memberInfo = new MemberInfo();
memberInfo.setAccount(registReq.getMemberNo());
memberInfo.setMobile(registReq.getMobile());
memberInfo.setBirthday(registReq.getBirthday());
memberInfo.setProvince(registReq.getProvinceId());
memberInfo.setCity(registReq.getCityId());
memberInfo.setArea(registReq.getAreaId());
memberInfo.setAddress(registReq.getAddress());
// 置会员状态为正常
memberInfo.setStatus(Constant.ACTIVE);
return memberInfo;
}
public CloseAccountResp closeAccount(CloseAccountReq evt) throws Exception {
LOGGER.info("closeAccount IN");
LOGGER.info("closeAccount OUT");
return null;
}
public LoginResp login(LoginReq loginReq) throws Exception {
LOGGER.info("login IN");
LOGGER.debug("loginReq=" + loginReq);
LoginResp loginResp = new LoginResp();
if (loginReq == null || StringConvert.isEmpty(loginReq.getAccount())
|| StringConvert.isEmpty(loginReq.getPassword())) {
LOGGER.error("userName or password is null");
loginResp.setRetCode(RetCode.FAILED);
LOGGER.debug("loginResp=" + loginResp);
LOGGER.info("login OUT");
return loginResp;
}
MemberInfo memberInfo = null;
try {
memberInfo = memberInfoDao.findMemberInfosByAccount(loginReq.getAccount());
} catch (Exception e) {
LOGGER.warn("findMemberInfosByAccount failed", e);
}
// 会员不存在
if (memberInfo == null) {
LOGGER.error("member not exsit");
loginResp.setRetCode(RetCode.MEMBER_NOT_EXSIT);
LOGGER.debug("loginResp=" + loginResp);
LOGGER.info("login OUT");
return loginResp;
}
// 判断密码是否正确,取出密码MD5加密后比较结果是否相等
String key = Constant.KEY_PASSWORD;
String passwordReq = StringConvert.passwordMD5(loginReq.getPassword(), key);
// 密码错误
if (!passwordReq.equals(memberInfo.getPassword())) {
LOGGER.error("password is increct");
loginResp.setRetCode(RetCode.PASSWORD_INCRECT);
} else if (Constant.ACTIVE.equals(loginResp.getStatus())) {// 判断会员状态是否禁用
LOGGER.error("password is inactive");
loginResp.setRetCode(RetCode.MEMBER_INACTIVE);
} else {
// 登录成功
loginResp.setRetCode(RetCode.SUCCESS);
// 返回登录信息
loginResp.setMemberNo(memberInfo.getAccount());
loginResp.setPassword(memberInfo.getPassword());
loginResp.setRealName(memberInfo.getNick());
}
LOGGER.debug("loginResp=" + loginResp);
LOGGER.info("login OUT");
return loginResp;
}
public LogoutResp logout(LogoutReq req) throws Exception {
LOGGER.info("logout IN");
LOGGER.info("logout OUT");
return null;
}
}
|
346674058/SuRui
|
code/myit-server/src/main/java/com/myit/server/service/member/impl/MemberServiceImpl.java
|
Java
|
apache-2.0
| 5,338 |
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { SubLayersToggleComponent } from './sub-layers-toggle.component';
describe('SubLayersToggleComponent', () => {
let component: SubLayersToggleComponent;
let fixture: ComponentFixture<SubLayersToggleComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [SubLayersToggleComponent]
}).compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(SubLayersToggleComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});
|
TheKeithStewart/angular-esri-components
|
projects/angular-esri-components/src/lib/widgets/layers-toggle/sub-layers-toggle/sub-layers-toggle.component.spec.ts
|
TypeScript
|
apache-2.0
| 686 |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.felix.http.base.internal.dispatch;
import org.apache.felix.http.base.internal.handler.HandlerRegistry;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.ServletException;
import java.io.IOException;
public final class Dispatcher
{
private final HandlerRegistry handlerRegistry;
public Dispatcher(HandlerRegistry handlerRegistry)
{
this.handlerRegistry = handlerRegistry;
}
public void dispatch(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException
{
ServletPipeline servletPipeline = new ServletPipeline(this.handlerRegistry.getServlets());
FilterPipeline filterPipeline = new FilterPipeline(this.handlerRegistry.getFilters(), servletPipeline);
filterPipeline.dispatch(req, res, new NotFoundFilterChain());
}
}
|
boneman1231/org.apache.felix
|
trunk/http/base/src/main/java/org/apache/felix/http/base/internal/dispatch/Dispatcher.java
|
Java
|
apache-2.0
| 1,701 |
package liquibase.executor;
import liquibase.change.Change;
import liquibase.database.Database;
import liquibase.exception.DatabaseException;
import liquibase.sql.visitor.SqlVisitor;
import liquibase.statement.SqlStatement;
import java.util.List;
import java.util.Map;
/**
* Interface for a class that is capable of executing statements/queries against a DBMS.
*/
public interface Executor {
/**
* Configures the Executor for the Database to run statements/queries against.
*
* @param database The database
*/
void setDatabase(Database database);
/**
* Execute a query that is expected to return a scalar (1 row, 1 column).
* It is expected that the scalar can be cast into an object of type T.
*
* @param sql The query to execute
* @return An object of type T, if successful. May also return null if no object is found.
* @throws DatabaseException in case something goes wrong during the query execution
*/
<T> T queryForObject(SqlStatement sql, Class<T> requiredType) throws DatabaseException;
/**
* Applies a number of SqlVisitors to the sql query.
* Then, executes the (possibly modified) query.
* The query is expected to return a scalar (1 row, 1 column).
* That scalar is expected to return a single value that can be cast into an object of type T.
*
* @param sql The query to execute
* @return An object of type T, if successful. May also return null if no object is found.
* @throws DatabaseException in case something goes wrong during the query execution
*/
<T> T queryForObject(SqlStatement sql, Class<T> requiredType, List<SqlVisitor> sqlVisitors) throws DatabaseException;
/**
* Executes a query that is expected to return a scalar (1 row, 1 column).
* It is expected that the scalar can be cast into a long.
*
* @param sql The query to execute
* @return A long value, if successful
* @throws DatabaseException in case something goes wrong during the query execution
*/
long queryForLong(SqlStatement sql) throws DatabaseException;
/**
* Applies a number of SqlVisitors to the sql query.
* Then, executes the (possibly modified) query.
* The query is expected to return a scalar (1 row, 1 column), and that scalar is expected to be a long value.
*
* @param sql The query to execute
* @return A long value, if successful
* @throws DatabaseException in case something goes wrong during the query execution
*/
long queryForLong(SqlStatement sql, List<SqlVisitor> sqlVisitors) throws DatabaseException;
/**
* Executes a query that is expected to return a scalar (1 row, 1 column).
* It is expected that the scalar can be cast into an int.
*
* @param sql The query to execute
* @return An integer, if successful
* @throws DatabaseException in case something goes wrong during the query execution
*/
int queryForInt(SqlStatement sql) throws DatabaseException;
/**
* Applies a number of SqlVisitors to the sql query.
* Then, executes the (possibly modified) query.
* The query is expected to return a scalar (1 row, 1 column), and that scalar is expected to be an int.
*
* @param sql The query to execute
* @return An integer, if successful
* @throws DatabaseException in case something goes wrong during the query execution
*/
int queryForInt(SqlStatement sql, List<SqlVisitor> sqlVisitors) throws DatabaseException;
List queryForList(SqlStatement sql, Class elementType) throws DatabaseException;
List queryForList(SqlStatement sql, Class elementType, List<SqlVisitor> sqlVisitors) throws DatabaseException;
/**
* Executes a given SQL statement and returns a List of rows. Each row is represented a a Map<String, ?>,
* where the String is the column name and the value if the content of the column in the row (=cell).
*
* @param sql the SQL query to execute
* @return a List of [Column name] -> [column value]-mapped rows.
* @throws DatabaseException if an error occurs during SQL processing (e.g. the SQL is not valid for the database)
*/
List<Map<String, ?>> queryForList(SqlStatement sql) throws DatabaseException;
/**
* Applies a list of SqlVisitors to the SQL query, then executes the (possibly modified) SQL query and lastly,
* returns the list of rows. Each row is represented a a Map<String, ?>,
* where the String is the column name and the value if the content of the column in the row (=cell).
*
* @param sql the SQL query to execute
* @return a List of [Column name] -> [column value]-mapped rows.
* @throws DatabaseException if an error occurs during SQL processing (e.g. the SQL is not valid for the database)
*/
List<Map<String, ?>> queryForList(SqlStatement sql, List<SqlVisitor> sqlVisitors) throws DatabaseException;
/** Write methods */
void execute(Change change) throws DatabaseException;
void execute(Change change, List<SqlVisitor> sqlVisitors) throws DatabaseException;
void execute(SqlStatement sql) throws DatabaseException;
void execute(SqlStatement sql, List<SqlVisitor> sqlVisitors) throws DatabaseException;
int update(SqlStatement sql) throws DatabaseException;
int update(SqlStatement sql, List<SqlVisitor> sqlVisitors) throws DatabaseException;
/**
* Adds a comment to the database. Currently does nothing but is over-ridden in the output JDBC template
* @param message
* @throws liquibase.exception.DatabaseException
*/
void comment(String message) throws DatabaseException;
boolean updatesDatabase();
}
|
Datical/liquibase
|
liquibase-core/src/main/java/liquibase/executor/Executor.java
|
Java
|
apache-2.0
| 5,739 |
/*
* generated by Xtext
*/
package xtext.scoping.adventures.ui;
import org.eclipse.xtext.ui.guice.AbstractGuiceAwareExecutableExtensionFactory;
import org.osgi.framework.Bundle;
import com.google.inject.Injector;
import xtext.scoping.adventures.ui.internal.Xscope1Activator;
/**
* This class was generated. Customizations should only happen in a newly
* introduced subclass.
*/
public class Xscope1ExecutableExtensionFactory extends AbstractGuiceAwareExecutableExtensionFactory {
@Override
protected Bundle getBundle() {
return Xscope1Activator.getInstance().getBundle();
}
@Override
protected Injector getInjector() {
return Xscope1Activator.getInstance().getInjector(Xscope1Activator.XTEXT_SCOPING_ADVENTURES_XSCOPE1);
}
}
|
sfinnie/xtext.scoping.adventures
|
chapter1/xtext.scoping.adventures.xscope1.ui/src-gen/xtext/scoping/adventures/ui/Xscope1ExecutableExtensionFactory.java
|
Java
|
apache-2.0
| 750 |
<!DOCTYPE html>
<html>
<head>
<meta charset='utf-8' />
<meta http-equiv="X-UA-Compatible" content="chrome=1" />
<meta name="description" content="jsrsasign : The 'jsrsasign' (RSA-Sign JavaScript Library) is a open source free pure JavaScript implementation of PKCS#1 v2.1 RSASSA-PKCS1-v1_5 RSA signing and validation algorithm." />
<link rel="stylesheet" type="text/css" media="screen" href="stylesheets/stylesheet.css">
<title>Time Stamp Request Generator</title>
<!-- for pkcs5pkey -->
<script language="JavaScript" type="text/javascript" src="jsrsasign-latest-all-min.js"></script>
<script language="JavaScript" type="text/javascript">
function doIt() {
var f1 = document.form1;
var json = {
mi: { hashAlg: f1.hashalg1.value,
hashValue: f1.hashval1.value }
};
if (f1.policy1.value != "")
json.policy = {oid: f1.policy1.value};
if (f1.nonce1.value != "")
json.nonce = {hex: f1.nonce1.value};
if (f1.certreq1.checked) {
json.certreq = true;
} else {
json.certreq = false;
}
f1.newreq1.value = "generating ...";
var o = new KJUR.asn1.tsp.TimeStampReq(json);
var hex = o.getEncodedHex();
var b64 = hex2b64(hex);
var pemBody = b64.replace(/(.{64})/g, "$1\r\n");
pemBody = pemBody.replace(/\r\n$/, '');
f1.newreq1.value = pemBody;
}
</script>
</head>
<body>
<!-- HEADER -->
<div id="header_wrap" class="outer">
<header class="inner">
<h1 id="project_title">TimeStampReq Generator</h1>
<h2 id="project_tagline">RFC 3161 Time Stamp Request Generator</h2>
<a href="http://kjur.github.io/jsrsasign/">TOP</a> |
<a href="https://github.com/kjur/jsrsasign/tags/" target="_blank">DOWNLOADS</a> |
<a href="https://github.com/kjur/jsrsasign/wiki#programming-tutorial">TUTORIALS</a> |
<a href="http://kjur.github.io/jsrsasign/api/" target="_blank">API REFERENCE</a> |
<a href="http://kjur.github.io/jsrsasign/index.html#demo" target="_blank">DEMOS</a> |
</header>
</div>
<!-- MAIN CONTENT -->
<div id="main_content_wrap" class="outer">
<section id="main_content" class="inner">
<!-- now editing -->
<form name="form1">
<h4>(Step1) Fill Fields</h4>
<table>
<tr><th colspan="2">MessageImprint</th></tr>
<tr><td>hashAlg:</td><td>
<select name="hashalg1">
<option value="sha256">SHA-256
<option value="sha512">SHA-512
<option value="sha384">SHA-384
<option value="sha224">SHA-224
<option value="sha1">SHA-1
<option value="md5">MD5
<option value="ripemd160">RIPEMD160
</select>
</td></tr>
<tr><td>hashValue(hex):</td><td><input type="text" name="hashval1" value="9834876dcfb05cb167a5c24953eba58c4ac89b1adf57f28f2f9d09af107ee8f0" size="80"/><br/>
Fill hash value of document to be time-stamped. You can use sha256sum or 'openssl dgst -HASHALG FILE' command.
</td></tr>
<tr><th colspan="2">Other Optional Fields</th></tr>
<tr><td>ReqPolicy:</td>
<td><input type="text" name="policy1" value="1.2.3.4.5" size="80"/></td></tr>
<tr><td>Nonce:</td><td>
<input type="text" name="nonce1" value="1a1b1c1e1f2a2b2c2d2e2f" size="40"/>
</td></tr>
<tr><td>certReq:</td><td>
exists<input type="checkbox" name="certreq1" value="1" checked/>
</td></tr>
</table>
<h4>(Step2) Press "Generate" button</h4>
<input type="button" value="Generate Request" onClick="doIt();"/>
<input type="reset" name="reset" value="Reset"/>
<h2>Generated TimeStampReq</h2>
<textarea name="newreq1" cols="65" rows="8"></textarea>
<br/>
To see this request by openssl, save this to a file and:
<blockquote>
% openssl base64 -in FILE -out FILE2<br/>
% openssl ts -query -in FILE2 -text<br/>
</blockquote>
You can copy this request and generate time stamp token
for it at <a href="tool_tsres.html">another sample page.</a>
</form>
<!-- now editing -->
</section>
</div>
<!-- FOOTER -->
<div id="footer_wrap" class="outer">
<footer class="inner">
<p class="copyright">jsrsasign maintained by <a href="https://github.com/kjur">kjur</a></p>
<p>Published with <a href="http://pages.github.com">GitHub Pages</a></p>
<div align="center" style="color: white">
Copyright © 2010-2014 Kenji Urushima. All rights reserved.
</div>
</footer>
</div>
</body>
</html>
|
rwth-acis/Anatomy2.0
|
src/external/jsrsasign/tool_tsreq.html
|
HTML
|
apache-2.0
| 4,154 |
# Stictina mougeotiana f. mougeotiana (Delise) Nyl. FORM
#### Status
ACCEPTED
#### According to
Index Fungorum
#### Published in
null
#### Original name
Stictina mougeotiana f. mougeotiana (Delise) Nyl.
### Remarks
null
|
mdoering/backbone
|
life/Fungi/Ascomycota/Lecanoromycetes/Peltigerales/Lobariaceae/Stictina/Stictina mougeotiana/Stictina mougeotiana mougeotiana/README.md
|
Markdown
|
apache-2.0
| 224 |
/* DO NOT EDIT THIS FILE - it is machine generated */
#include <jni.h>
/* Header for class com_jph_utils_PatchUtils */
#ifndef _Included_com_jph_utils_PatchUtils
#define _Included_com_jph_utils_PatchUtils
#ifdef __cplusplus
extern "C" {
#endif
/*
* Class: com_jph_utils_PatchUtils
* Method: patch
* Signature: (Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)I
*/
JNIEXPORT jint JNICALL Java_com_jph_utils_PatchUtils_patch
(JNIEnv *, jclass, jstring, jstring, jstring);
#ifdef __cplusplus
}
#endif
#endif
|
crazycodeboy/IncrementalUpdate
|
ApkPatchLibrary/jni/com_jph_utils_PatchUtils.h
|
C
|
apache-2.0
| 557 |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!--NewPage-->
<HTML>
<HEAD>
<!-- Generated by javadoc (build 1.6.0_45) on Fri Mar 06 22:16:05 CST 2015 -->
<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
<TITLE>
Uses of Class org.apache.hadoop.mapred.MapTask.MapOutputBuffer.InMemValBytes (hadoop-mapreduce-client-core 2.3.0 API)
</TITLE>
<META NAME="date" CONTENT="2015-03-06">
<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../stylesheet.css" TITLE="Style">
<SCRIPT type="text/javascript">
function windowTitle()
{
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Uses of Class org.apache.hadoop.mapred.MapTask.MapOutputBuffer.InMemValBytes (hadoop-mapreduce-client-core 2.3.0 API)";
}
}
</SCRIPT>
<NOSCRIPT>
</NOSCRIPT>
</HEAD>
<BODY BGCOLOR="white" onload="windowTitle();">
<HR>
<!-- ========= START OF TOP NAVBAR ======= -->
<A NAME="navbar_top"><!-- --></A>
<A HREF="#skip-navbar_top" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_top_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../org/apache/hadoop/mapred/MapTask.MapOutputBuffer.InMemValBytes.html" title="class in org.apache.hadoop.mapred"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
PREV
NEXT</FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../index.html?org/apache/hadoop/mapred//class-useMapTask.MapOutputBuffer.InMemValBytes.html" target="_top"><B>FRAMES</B></A>
<A HREF="MapTask.MapOutputBuffer.InMemValBytes.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!--
if(window==top) {
document.writeln('<A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_top"></A>
<!-- ========= END OF TOP NAVBAR ========= -->
<HR>
<CENTER>
<H2>
<B>Uses of Class<br>org.apache.hadoop.mapred.MapTask.MapOutputBuffer.InMemValBytes</B></H2>
</CENTER>
No usage of org.apache.hadoop.mapred.MapTask.MapOutputBuffer.InMemValBytes
<P>
<HR>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<A NAME="navbar_bottom"><!-- --></A>
<A HREF="#skip-navbar_bottom" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_bottom_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../org/apache/hadoop/mapred/MapTask.MapOutputBuffer.InMemValBytes.html" title="class in org.apache.hadoop.mapred"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
PREV
NEXT</FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../index.html?org/apache/hadoop/mapred//class-useMapTask.MapOutputBuffer.InMemValBytes.html" target="_top"><B>FRAMES</B></A>
<A HREF="MapTask.MapOutputBuffer.InMemValBytes.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!--
if(window==top) {
document.writeln('<A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_bottom"></A>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<HR>
Copyright © 2015 <a href="http://www.apache.org">Apache Software Foundation</a>. All Rights Reserved.
</BODY>
</HTML>
|
jsrudani/HadoopHDFSProject
|
hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-core/target/org/apache/hadoop/mapred/class-use/MapTask.MapOutputBuffer.InMemValBytes.html
|
HTML
|
apache-2.0
| 6,400 |
/*
Copyright 2017 The Kubernetes Authors All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package unversioned
import (
api "k8s.io/kubernetes/pkg/api"
registered "k8s.io/kubernetes/pkg/apimachinery/registered"
restclient "k8s.io/kubernetes/pkg/client/restclient"
)
type FederationInterface interface {
GetRESTClient() *restclient.RESTClient
ClustersGetter
}
// FederationClient is used to interact with features provided by the Federation group.
type FederationClient struct {
*restclient.RESTClient
}
func (c *FederationClient) Clusters() ClusterInterface {
return newClusters(c)
}
// NewForConfig creates a new FederationClient for the given config.
func NewForConfig(c *restclient.Config) (*FederationClient, error) {
config := *c
if err := setConfigDefaults(&config); err != nil {
return nil, err
}
client, err := restclient.RESTClientFor(&config)
if err != nil {
return nil, err
}
return &FederationClient{client}, nil
}
// NewForConfigOrDie creates a new FederationClient for the given config and
// panics if there is an error in the config.
func NewForConfigOrDie(c *restclient.Config) *FederationClient {
client, err := NewForConfig(c)
if err != nil {
panic(err)
}
return client
}
// New creates a new FederationClient for the given RESTClient.
func New(c *restclient.RESTClient) *FederationClient {
return &FederationClient{c}
}
func setConfigDefaults(config *restclient.Config) error {
// if federation group is not registered, return an error
g, err := registered.Group("federation")
if err != nil {
return err
}
config.APIPath = "/apis"
if config.UserAgent == "" {
config.UserAgent = restclient.DefaultKubernetesUserAgent()
}
// TODO: Unconditionally set the config.Version, until we fix the config.
//if config.Version == "" {
copyGroupVersion := g.GroupVersion
config.GroupVersion = ©GroupVersion
//}
config.NegotiatedSerializer = api.Codecs
if config.QPS == 0 {
config.QPS = 5
}
if config.Burst == 0 {
config.Burst = 10
}
return nil
}
// GetRESTClient returns a RESTClient that is used to communicate
// with API server by this client implementation.
func (c *FederationClient) GetRESTClient() *restclient.RESTClient {
if c == nil {
return nil
}
return c.RESTClient
}
|
hyperhq/hypernetes
|
federation/client/clientset_generated/federation_internalclientset/typed/federation/unversioned/federation_client.go
|
GO
|
apache-2.0
| 2,756 |
<?php
/**
* Indicate where a criterion's bid came from: criterion or the adgroup it
* belongs to.
* @package Google_Api_Ads_AdWords_v201605
* @subpackage v201605
*/
class BidSource
{
const WSDL_NAMESPACE = "https://adwords.google.com/api/adwords/cm/v201605";
const XSI_TYPE = "BidSource";
/**
* Gets the namesapce of this class
* @return string the namespace of this class
*/
public function getNamespace()
{
return self::WSDL_NAMESPACE;
}
/**
* Gets the xsi:type name of this class
* @return string the xsi:type name of this class
*/
public function getXsiTypeName()
{
return self::XSI_TYPE;
}
public function __construct()
{
}
}
|
SonicGD/google-adwords-api-light
|
Google/Api/Ads/AdWords/v201605/classes/BidSource.php
|
PHP
|
apache-2.0
| 743 |
## Support custom enhance
Here is an optional plugin `apm-customize-enhance-plugin`
## Introduce
SkyWalking has provided [Java agent plugin development guide](https://github.com/apache/skywalking/blob/master/docs/en/guides/Java-Plugin-Development-Guide.md) to help developers to build new plugin.
This plugin is not designed for replacement but for user convenience. The behaviour is very similar with [@Trace toolkit](Application-toolkit-trace.md), but without code change requirement, and more powerful, such as provide tag and log.
## How to configure
Implementing enhancements to custom classes requires two steps.
1. Active the plugin, move the `optional-plugins/apm-customize-enhance-plugin.jar` to `plugin/apm-customize-enhance-plugin.jar`.
2. Set `plugin.customize.enhance_file` in agent.config, which targets to rule file, such as `/absolute/path/to/customize_enhance.xml`.
3. Set enhancement rules in `customize_enhance.xml`.
```xml
<?xml version="1.0" encoding="UTF-8"?>
<enhanced>
<class class_name="test.apache.skywalking.testcase.customize.service.TestService1">
<method method="staticMethod()" operation_name="/is_static_method" static="true"/>
<method method="staticMethod(java.lang.String,int.class,java.util.Map,java.util.List,[Ljava.lang.Object;)" operation_name="/is_static_method_args" static="true">
<operation_name_suffix>arg[0]</operation_name_suffix>
<operation_name_suffix>arg[1]</operation_name_suffix>
<operation_name_suffix>arg[3].[0]</operation_name_suffix>
<tag key="tag_1">arg[2].['k1']</tag>
<tag key="tag_2">arg[4].[1]</tag>
<log key="log_1">arg[4].[2]</log>
</method>
<method method="method()" static="false"/>
<method method="method(java.lang.String,int.class)" operation_name="/method_2" static="false">
<operation_name_suffix>arg[0]</operation_name_suffix>
<tag key="tag_1">arg[0]</tag>
<log key="log_1">arg[1]</log>
</method>
<method method="method(test.apache.skywalking.testcase.customize.model.Model0,java.lang.String,int.class)" operation_name="/method_3" static="false">
<operation_name_suffix>arg[0].id</operation_name_suffix>
<operation_name_suffix>arg[0].model1.name</operation_name_suffix>
<operation_name_suffix>arg[0].model1.getId()</operation_name_suffix>
<tag key="tag_os">arg[0].os.[1]</tag>
<log key="log_map">arg[0].getM().['k1']</log>
</method>
</class>
<class class_name="test.apache.skywalking.testcase.customize.service.TestService2">
<method method="staticMethod(java.lang.String,int.class)" operation_name="/is_2_static_method" static="true">
<tag key="tag_2_1">arg[0]</tag>
<log key="log_1_1">arg[1]</log>
</method>
<method method="method([Ljava.lang.Object;)" operation_name="/method_4" static="false">
<tag key="tag_4_1">arg[0].[0]</tag>
</method>
<method method="method(java.util.List,int.class)" operation_name="/method_5" static="false">
<tag key="tag_5_1">arg[0].[0]</tag>
<log key="log_5_1">arg[1]</log>
</method>
</class>
</enhanced>
```
- Explanation of the configuration in the file
| configuration | explanation |
|:----------------- |:---------------|
| class_name | The enhanced class |
| method | The interceptor method of the class |
| operation_name | If fill it out, will use it instead of the default operation_name. |
| operation_name\_suffix | What it means adding dynamic data after the operation_name. |
| static | Is this method static. |
| tag | Will add a tag in local span. The value of key needs to be represented on the XML node. |
| log | Will add a log in local span. The value of key needs to be represented on the XML node. |
| arg[x] | What it means is to get the input arguments. such as arg[0] is means get first arguments. |
| .[x] | When the parsing object is Array or List, you can use it to get the object at the specified index. |
| .['key'] | When the parsing object is Map, you can get the map 'key' through it.|
|
wu-sheng/sky-walking
|
docs/en/setup/service-agent/java-agent/Customize-enhance-trace.md
|
Markdown
|
apache-2.0
| 4,345 |
package com.siams.orientdb.evaluation;
import com.orientechnologies.orient.core.Orient;
import com.orientechnologies.orient.core.db.document.ODatabaseDocumentTx;
import com.orientechnologies.orient.core.intent.OIntentMassiveInsert;
import com.orientechnologies.orient.core.iterator.ORecordIteratorClass;
import com.orientechnologies.orient.core.record.impl.ODocument;
import com.orientechnologies.orient.core.record.impl.ORecordBytes;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
/**
* Created by [email protected] on 3/12/2015.
*/
public class RandomFill {
private final Random random = new Random();
private final byte[] imageData = new byte[256 * 256];
private int recordCount;
private int nextTileId;
private long t0;
private RandomFill(ODatabaseDocumentTx db) {
random.nextBytes(imageData);
nextTileId = LocalDB.getMaxTileId(db) + 1;
}
public static void main(String[] args) throws IOException {
final String url = LocalDB.toURI(args);
if (!Orient.instance().loadStorage(url).exists()) {
CreateDB.main(args);
}
try (final ODatabaseDocumentTx db = new ODatabaseDocumentTx(url)
.open("admin", "admin")) {
final RandomFill action = new RandomFill(db);
db.declareIntent(new OIntentMassiveInsert());
System.out.println("warming up...");
action.execute(db, 100, 1000);
System.out.println("executing...");
action.recordCount = 0;
action.t0 = System.currentTimeMillis();
action.execute(db, 65536, 100);
action.printTime();
action.saveConfiguration(db);
db.declareIntent(null);
db.close();
System.out.println("shutdown...");
Orient.instance().shutdown();
action.printTime();
}
}
private void printTime() {
final long t1 = System.currentTimeMillis();
final long time = t1 - t0;
System.out.printf("done: %dms / %d = %s ms/record%n",
time, recordCount,
((double) time) / recordCount
);
}
private void saveConfiguration(ODatabaseDocumentTx db) {
final ORecordIteratorClass<ODocument> configurations = db.browseClass("Configuration");
final ODocument configuration;
if (configurations.hasNext()) {
configuration = configurations.next();
} else {
configuration = db.newInstance("Configuration");
}
configuration
.field("imageSize", imageData.length)
.save();
}
private void execute(ODatabaseDocumentTx db, int tileCount, int particleCount) {
for (int ti = 0; ti < tileCount; ti++) {
final List<ODocument> particles = new ArrayList<>();
for (int pi = 0; pi < particleCount; pi++) {
final ODocument particle = db.newInstance("Particle");
particle
.field("x", random.nextLong())
.field("y", random.nextLong());
particle.save();
recordCount++;
particles.add(particle);
}
final ODocument tile = db.newInstance("Tile");
tile
.field("id", nextTileId++)
.field("x", random.nextLong())
.field("y", random.nextLong())
.field("image", new ORecordBytes(imageData))
.field("particles", particles)
;
tile.save();
recordCount++;
}
}
}
|
imaging4j/orientdb-performance-evaluation
|
src/main/java/com/siams/orientdb/evaluation/RandomFill.java
|
Java
|
apache-2.0
| 3,730 |
# Monopyle macrocarpa var. isophylla Benth. VARIETY
#### Status
ACCEPTED
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null
|
mdoering/backbone
|
life/Plantae/Magnoliophyta/Magnoliopsida/Lamiales/Gesneriaceae/Monopyle/Monopyle macrocarpa/Monopyle macrocarpa isophylla/README.md
|
Markdown
|
apache-2.0
| 199 |
package org.grobid.core.lang;
import org.grobid.core.exceptions.GrobidException;
/**
* Date: 11/24/11
* Time: 11:39 AM
*
* @author Vyacheslav Zholudev
*/
public final class Language {
//common language constants
public static final String EN = "en";
public static final String DE = "de";
public static final String FR = "fr";
private String lang;
private double conf;
// default construction for jackson mapping
public Language() {}
public Language(String langId, double confidence) {
if (langId == null) {
throw new GrobidException("Language id cannot be null");
}
if ((langId.length() != 3 && langId.length() != 2 && (!langId.equals("sorb")) &&
(!langId.equals("zh-cn")) && (!langId.equals("zh-tw"))) || !(Character.isLetter(langId.charAt(0))
&& Character.isLetter(langId.charAt(1)))) {
throw new GrobidException("Language id should consist of two or three letters, but was: " + langId);
}
this.lang = langId;
this.conf = confidence;
}
public boolean isChinese() {
return "zh".equals(lang) || "zh-cn".equals(lang) || "zh-tw".equals(lang);
}
public boolean isJapaneses() {
return "ja".equals(lang);
}
public boolean isKorean() {
return "kr".equals(lang);
}
public boolean isArabic() {
return "ar".equals(lang);
}
public String getLang() {
return lang;
}
public void setLang(String lang) {
this.lang = lang;
}
@SuppressWarnings({"UnusedDeclaration"})
public double getConf() {
return conf;
}
public void setConf(double conf) {
this.conf = conf;
}
@Override
public String toString() {
return lang + ";" + conf;
}
public String toJSON() {
return "{\"lang\":\""+lang+"\", \"conf\": "+conf+"}";
}
}
|
iorala/grobid
|
grobid-core/src/main/java/org/grobid/core/lang/Language.java
|
Java
|
apache-2.0
| 1,905 |
/*
* Copyright 2020 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/cloud/compute/v1/compute.proto
package com.google.cloud.compute.v1;
public interface BfdStatusPacketCountsOrBuilder
extends
// @@protoc_insertion_point(interface_extends:google.cloud.compute.v1.BfdStatusPacketCounts)
com.google.protobuf.MessageOrBuilder {
/**
*
*
* <pre>
* Number of packets received since the beginning of the current BFD session.
* </pre>
*
* <code>optional uint32 num_rx = 39375263;</code>
*
* @return Whether the numRx field is set.
*/
boolean hasNumRx();
/**
*
*
* <pre>
* Number of packets received since the beginning of the current BFD session.
* </pre>
*
* <code>optional uint32 num_rx = 39375263;</code>
*
* @return The numRx.
*/
int getNumRx();
/**
*
*
* <pre>
* Number of packets received that were rejected because of errors since the beginning of the current BFD session.
* </pre>
*
* <code>optional uint32 num_rx_rejected = 281007902;</code>
*
* @return Whether the numRxRejected field is set.
*/
boolean hasNumRxRejected();
/**
*
*
* <pre>
* Number of packets received that were rejected because of errors since the beginning of the current BFD session.
* </pre>
*
* <code>optional uint32 num_rx_rejected = 281007902;</code>
*
* @return The numRxRejected.
*/
int getNumRxRejected();
/**
*
*
* <pre>
* Number of packets received that were successfully processed since the beginning of the current BFD session.
* </pre>
*
* <code>optional uint32 num_rx_successful = 455361850;</code>
*
* @return Whether the numRxSuccessful field is set.
*/
boolean hasNumRxSuccessful();
/**
*
*
* <pre>
* Number of packets received that were successfully processed since the beginning of the current BFD session.
* </pre>
*
* <code>optional uint32 num_rx_successful = 455361850;</code>
*
* @return The numRxSuccessful.
*/
int getNumRxSuccessful();
/**
*
*
* <pre>
* Number of packets transmitted since the beginning of the current BFD session.
* </pre>
*
* <code>optional uint32 num_tx = 39375325;</code>
*
* @return Whether the numTx field is set.
*/
boolean hasNumTx();
/**
*
*
* <pre>
* Number of packets transmitted since the beginning of the current BFD session.
* </pre>
*
* <code>optional uint32 num_tx = 39375325;</code>
*
* @return The numTx.
*/
int getNumTx();
}
|
googleapis/java-compute
|
proto-google-cloud-compute-v1/src/main/java/com/google/cloud/compute/v1/BfdStatusPacketCountsOrBuilder.java
|
Java
|
apache-2.0
| 3,151 |
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var index = require('./routes/index');
var users = require('./routes/users');
var service = require('./routes/service');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
/*允许跨域*/
app.all('*', function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "X-Requested-With");
res.header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");
res.header("X-Powered-By",' 3.2.1');
res.header("Content-Type", "application/json;charset=utf-8");
next();
});
app.use('/', index);
app.use('/users', users);
app.use('/service', service);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
module.exports = app;
|
HuaguoshanRD/dzt-helper-mysql
|
RemoteBackupManage/app.js
|
JavaScript
|
apache-2.0
| 1,695 |
namespace Sqloogle.Libs.Rhino.Etl.Core.Exceptions
{
/// <summary>
/// Thrown when an access to a quacking dictionary is made with more than a single
/// parameter
/// </summary>
[global::System.Serializable]
public class ParameterCountException : System.Exception
{
/// <summary>
/// Initializes a new instance of the <see cref="ParameterCountException"/> class.
/// </summary>
public ParameterCountException()
{
}
/// <summary>
/// Initializes a new instance of the <see cref="ParameterCountException"/> class.
/// </summary>
/// <param name="message">The message.</param>
public ParameterCountException(string message) : base(message)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="ParameterCountException"/> class.
/// </summary>
/// <param name="message">The message.</param>
/// <param name="inner">The inner.</param>
public ParameterCountException(string message, System.Exception inner) : base(message, inner)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="ParameterCountException"/> class.
/// </summary>
/// <param name="info">The <see cref="T:System.Runtime.Serialization.SerializationInfo"/> that holds the serialized object data about the exception being thrown.</param>
/// <param name="context">The <see cref="T:System.Runtime.Serialization.StreamingContext"/> that contains contextual information about the source or destination.</param>
/// <exception cref="T:System.ArgumentNullException">The <paramref name="info"/> parameter is null. </exception>
/// <exception cref="T:System.Runtime.Serialization.SerializationException">The class name is null or <see cref="P:System.Exception.HResult"/> is zero (0). </exception>
protected ParameterCountException(
System.Runtime.Serialization.SerializationInfo info,
System.Runtime.Serialization.StreamingContext context)
: base(info, context)
{
}
}
}
|
dineshkummarc/SQLoogle
|
Sqloogle/Libs/Rhino.Etl/Core/Exceptions/ParameterCountException.cs
|
C#
|
apache-2.0
| 2,166 |
# AUTOGENERATED FILE
FROM balenalib/generic-aarch64-debian:bookworm-build
# A few reasons for installing distribution-provided OpenJDK:
#
# 1. Oracle. Licensing prevents us from redistributing the official JDK.
#
# 2. Compiling OpenJDK also requires the JDK to be installed, and it gets
# really hairy.
#
# For some sample build times, see Debian's buildd logs:
# https://buildd.debian.org/status/logs.php?pkg=openjdk-8
RUN apt-get update && apt-get install -y --no-install-recommends \
bzip2 \
unzip \
xz-utils \
binutils \
fontconfig libfreetype6 \
ca-certificates p11-kit \
&& rm -rf /var/lib/apt/lists/*
ENV JAVA_HOME /usr/local/openjdk-16
ENV PATH $JAVA_HOME/bin:$PATH
# Default to UTF-8 file.encoding
ENV LANG C.UTF-8
RUN curl -SLO "https://download.java.net/java/GA/jdk16.0.1/7147401fd7354114ac51ef3e1328291f/9/GPL/openjdk-16.0.1_linux-aarch64_bin.tar.gz" \
&& echo "602b005074777df2a0b4306e20152a6446803edd87ccbab95b2f313c4d9be6ba openjdk-16.0.1_linux-aarch64_bin.tar.gz" | sha256sum -c - \
&& mkdir -p "$JAVA_HOME" \
&& tar --extract \
--file openjdk-16.0.1_linux-aarch64_bin.tar.gz \
--directory "$JAVA_HOME" \
--strip-components 1 \
--no-same-owner \
&& rm -f openjdk-16.0.1_linux-aarch64_bin.tar.gz \
&& { \
echo '#!/usr/bin/env bash'; \
echo 'set -Eeuo pipefail'; \
echo 'trust extract --overwrite --format=java-cacerts --filter=ca-anchors --purpose=server-auth "$JAVA_HOME/lib/security/cacerts"'; \
} > /etc/ca-certificates/update.d/docker-openjdk \
&& chmod +x /etc/ca-certificates/update.d/docker-openjdk \
&& /etc/ca-certificates/update.d/docker-openjdk \
&& find "$JAVA_HOME/lib" -name '*.so' -exec dirname '{}' ';' | sort -u > /etc/ld.so.conf.d/docker-openjdk.conf \
&& ldconfig \
&& java -Xshare:dump \
&& fileEncoding="$(echo 'System.out.println(System.getProperty("file.encoding"))' | jshell -s -)"; [ "$fileEncoding" = 'UTF-8' ]; rm -rf ~/.java \
&& javac --version \
&& java --version
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 [ ! -d /.balena/messages ] && mkdir -p /.balena/messages; echo 'Here are a few details about this Docker image (For more information please visit https://www.balena.io/docs/reference/base-images/base-images/): \nArchitecture: ARM v8 \nOS: Debian Bookworm \nVariant: build variant \nDefault variable(s): UDEV=off \nThe following software stack is preinstalled: \nOpenJDK v16-jdk \nExtra features: \n- Easy way to install packages with `install_packages <package-name>` command \n- Run anywhere with cross-build feature (for ARM only) \n- Keep the container idling with `balena-idle` command \n- Show base image details with `balena-info` command' > /.balena/messages/image-info
RUN echo '#!/bin/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
|
resin-io-library/base-images
|
balena-base-images/openjdk/generic-aarch64/debian/bookworm/16-jdk/build/Dockerfile
|
Dockerfile
|
apache-2.0
| 3,029 |
/*
* Copyright 2010-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
#pragma once
#include <aws/cloudfront/CloudFront_EXPORTS.h>
#include <aws/cloudfront/model/StreamingDistributionList.h>
#include <utility>
namespace Aws
{
template<typename RESULT_TYPE>
class AmazonWebServiceResult;
namespace Utils
{
namespace Xml
{
class XmlDocument;
} // namespace Xml
} // namespace Utils
namespace CloudFront
{
namespace Model
{
/**
* The returned result of the corresponding request.<p><h3>See Also:</h3> <a
* href="http://docs.aws.amazon.com/goto/WebAPI/cloudfront-2016-01-28/ListStreamingDistributionsResult">AWS
* API Reference</a></p>
*/
class AWS_CLOUDFRONT_API ListStreamingDistributions2016_01_28Result
{
public:
ListStreamingDistributions2016_01_28Result();
ListStreamingDistributions2016_01_28Result(const AmazonWebServiceResult<Aws::Utils::Xml::XmlDocument>& result);
ListStreamingDistributions2016_01_28Result& operator=(const AmazonWebServiceResult<Aws::Utils::Xml::XmlDocument>& result);
/**
* The StreamingDistributionList type.
*/
inline const StreamingDistributionList& GetStreamingDistributionList() const{ return m_streamingDistributionList; }
/**
* The StreamingDistributionList type.
*/
inline void SetStreamingDistributionList(const StreamingDistributionList& value) { m_streamingDistributionList = value; }
/**
* The StreamingDistributionList type.
*/
inline void SetStreamingDistributionList(StreamingDistributionList&& value) { m_streamingDistributionList = std::move(value); }
/**
* The StreamingDistributionList type.
*/
inline ListStreamingDistributions2016_01_28Result& WithStreamingDistributionList(const StreamingDistributionList& value) { SetStreamingDistributionList(value); return *this;}
/**
* The StreamingDistributionList type.
*/
inline ListStreamingDistributions2016_01_28Result& WithStreamingDistributionList(StreamingDistributionList&& value) { SetStreamingDistributionList(std::move(value)); return *this;}
private:
StreamingDistributionList m_streamingDistributionList;
};
} // namespace Model
} // namespace CloudFront
} // namespace Aws
|
chiaming0914/awe-cpp-sdk
|
aws-cpp-sdk-cloudfront/include/aws/cloudfront/model/ListStreamingDistributions2016_01_28Result.h
|
C
|
apache-2.0
| 2,721 |
function loadText()
{
document.getElementById("txtLang").innerHTML = "Naam";
document.getElementById("btnCancel").value = "annuleren";
document.getElementById("btnInsert").value = "invoegen";
document.getElementById("btnApply").value = "toepassen";
document.getElementById("btnOk").value = " ok ";
}
function writeTitle()
{
document.write("<title>Bladwijzer</title>")
}
|
studiodev/archives
|
2009 - Team D4 (IxGamer)/include/Editor/scripts/language/dutch/bookmark.js
|
JavaScript
|
apache-2.0
| 420 |
/*
Copyright (c) 2014-2016 DataStax
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include <boost/test/unit_test.hpp>
#include <boost/test/debug.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/cstdint.hpp>
#include <boost/format.hpp>
#include <boost/asio/io_service.hpp>
#include <boost/thread/thread.hpp>
#include <boost/thread/future.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/make_shared.hpp>
#include <boost/move/move.hpp>
#include <boost/container/vector.hpp>
#include <boost/version.hpp>
#include "cassandra.h"
#include "constants.hpp"
#include "test_utils.hpp"
#if (defined(WIN32) || defined(_WIN32))
#define CONTAINER std::vector
#else
#define CONTAINER boost::container::vector
#endif
struct AllTypes {
CassUuid id;
CassString text_sample;
cass_int32_t int_sample;
cass_int64_t bigint_sample;
cass_float_t float_sample;
cass_double_t double_sample;
CassDecimal decimal_sample;
CassBytes blob_sample;
cass_bool_t boolean_sample;
cass_int64_t timestamp_sample;
CassInet inet_sample;
cass_int8_t tinyint_sample;
cass_int16_t smallint_sample;
CassDate date_sample;
CassTime time_sample;
};
// This crashes in Boost 1.57 and the test_utils::CassPreparedPtr version
// doesn't compile against Boost 1.55 or 1.56
#if BOOST_VERSION < 105700
// Move emulation wrapper for CassPrepared. This has to be used
// with boost::container's because they have boost move emulation support.
class CassPreparedMovable {
public:
CassPreparedMovable(const CassPrepared* prepared = NULL)
: prepared_(prepared) {}
CassPreparedMovable(BOOST_RV_REF(CassPreparedMovable) r)
: prepared_(r.prepared_) {
r.prepared_ = NULL;
}
CassPreparedMovable(const CassPreparedMovable& r)
: prepared_(r.prepared_) {
}
CassPreparedMovable& operator=(BOOST_RV_REF(CassPreparedMovable) r) {
if (prepared_ != NULL) {
cass_prepared_free(prepared_);
}
prepared_ = r.prepared_;
r.prepared_ = NULL;
return *this;
}
~CassPreparedMovable() {
if (prepared_ != NULL) {
cass_prepared_free(prepared_);
}
}
const CassPrepared* get() const { return prepared_; }
private:
BOOST_MOVABLE_BUT_NOT_COPYABLE(CassPreparedMovable)
const CassPrepared* prepared_;
};
#endif
struct PreparedTests : public test_utils::SingleSessionTest {
static const char* ALL_TYPE_TABLE_NAME;
std::string columns_;
std::string values_;
size_t column_size_;
PreparedTests() : test_utils::SingleSessionTest(2, 0) {
test_utils::execute_query(session, str(boost::format(test_utils::CREATE_KEYSPACE_SIMPLE_FORMAT)
% test_utils::SIMPLE_KEYSPACE % "1"));
test_utils::execute_query(session, str(boost::format("USE %s") % test_utils::SIMPLE_KEYSPACE));
if ((version.major_version >= 2 && version.minor_version >= 2) || version.major_version >= 3) {
test_utils::execute_query(session, str(boost::format(test_utils::CREATE_TABLE_ALL_TYPES_V4) % ALL_TYPE_TABLE_NAME));
column_size_ = 15;
} else {
test_utils::execute_query(session, str(boost::format(test_utils::CREATE_TABLE_ALL_TYPES) % ALL_TYPE_TABLE_NAME));
column_size_ = 11;
}
columns_ = "id, text_sample, int_sample, bigint_sample, float_sample, double_sample, decimal_sample, "
"blob_sample, boolean_sample, timestamp_sample, inet_sample";
values_ = "?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?";
if ((version.major_version >= 2 && version.minor_version >= 2) || version.major_version >= 3) {
columns_ += ", tinyint_sample, smallint_sample, date_sample, time_sample";
values_ += ", ?, ?, ?, ?";
}
}
~PreparedTests() {
// Drop the keyspace (ignore any and all errors)
test_utils::execute_query_with_error(session,
str(boost::format(test_utils::DROP_KEYSPACE_FORMAT)
% test_utils::SIMPLE_KEYSPACE));
}
void insert_all_types(CassSession* session, const CassPrepared* prepared, const AllTypes& all_types) {
test_utils::CassStatementPtr statement(cass_prepared_bind(prepared));
cass_statement_bind_uuid(statement.get(), 0, all_types.id);
cass_statement_bind_string_n(statement.get(), 1,
all_types.text_sample.data, all_types.text_sample.length);
cass_statement_bind_int32(statement.get(), 2, all_types.int_sample);
cass_statement_bind_int64(statement.get(), 3, all_types.bigint_sample);
cass_statement_bind_float(statement.get(), 4, all_types.float_sample);
cass_statement_bind_double(statement.get(), 5, all_types.double_sample);
cass_statement_bind_decimal(statement.get(), 6,
all_types.decimal_sample.varint, all_types.decimal_sample.varint_size,
all_types.decimal_sample.scale);
cass_statement_bind_bytes(statement.get(), 7,
all_types.blob_sample.data, all_types.blob_sample.size);
cass_statement_bind_bool(statement.get(), 8, all_types.boolean_sample);
cass_statement_bind_int64(statement.get(), 9, all_types.timestamp_sample);
cass_statement_bind_inet(statement.get(), 10, all_types.inet_sample);
if ((version.major_version >= 2 && version.minor_version >= 2) || version.major_version >= 3) {
cass_statement_bind_int8(statement.get(), 11, all_types.tinyint_sample);
cass_statement_bind_int16(statement.get(), 12, all_types.smallint_sample);
cass_statement_bind_uint32(statement.get(), 13, all_types.date_sample.date);
cass_statement_bind_int64(statement.get(), 14, all_types.time_sample.time);
}
test_utils::CassFuturePtr future(cass_session_execute(session, statement.get()));
test_utils::wait_and_check_error(future.get());
}
void compare_all_types(const AllTypes& input, const CassRow* row) {
AllTypes output;
BOOST_REQUIRE(cass_value_get_string(cass_row_get_column(row, 1), &output.text_sample.data, &output.text_sample.length) == CASS_OK);
BOOST_REQUIRE(test_utils::Value<CassString>::equal(input.text_sample, output.text_sample));
BOOST_REQUIRE(cass_value_get_int32(cass_row_get_column(row, 2), &output.int_sample) == CASS_OK);
BOOST_REQUIRE(test_utils::Value<cass_int32_t>::equal(input.int_sample, output.int_sample));
BOOST_REQUIRE(cass_value_get_int64(cass_row_get_column(row, 3), &output.bigint_sample) == CASS_OK);
BOOST_REQUIRE(test_utils::Value<cass_int64_t>::equal(input.bigint_sample, output.bigint_sample));
BOOST_REQUIRE(cass_value_get_float(cass_row_get_column(row, 4), &output.float_sample) == CASS_OK);
BOOST_REQUIRE(test_utils::Value<cass_float_t>::equal(input.float_sample, output.float_sample));
BOOST_REQUIRE(cass_value_get_double(cass_row_get_column(row, 5), &output.double_sample) == CASS_OK);
BOOST_REQUIRE(test_utils::Value<cass_double_t>::equal(input.double_sample, output.double_sample));
BOOST_REQUIRE(cass_value_get_decimal(cass_row_get_column(row, 6),
&output.decimal_sample.varint,
&output.decimal_sample.varint_size,
&output.decimal_sample.scale) == CASS_OK);
BOOST_REQUIRE(test_utils::Value<CassDecimal>::equal(input.decimal_sample, output.decimal_sample));
BOOST_REQUIRE(cass_value_get_bytes(cass_row_get_column(row, 7), &output.blob_sample.data, &output.blob_sample.size) == CASS_OK);
BOOST_REQUIRE(test_utils::Value<CassBytes>::equal(input.blob_sample, output.blob_sample));
BOOST_REQUIRE(cass_value_get_bool(cass_row_get_column(row, 8), &output.boolean_sample) == CASS_OK);
BOOST_REQUIRE(test_utils::Value<cass_bool_t>::equal(input.boolean_sample, output.boolean_sample));
BOOST_REQUIRE(cass_value_get_int64(cass_row_get_column(row, 9), &output.timestamp_sample) == CASS_OK);
BOOST_REQUIRE(test_utils::Value<cass_int64_t>::equal(input.timestamp_sample, output.timestamp_sample));
BOOST_REQUIRE(cass_value_get_inet(cass_row_get_column(row, 10), &output.inet_sample) == CASS_OK);
BOOST_REQUIRE(test_utils::Value<CassInet>::equal(input.inet_sample, output.inet_sample));
if ((version.major_version >= 2 && version.minor_version >= 2) || version.major_version >= 3) {
BOOST_REQUIRE(cass_value_get_int8(cass_row_get_column(row, 11), &output.tinyint_sample) == CASS_OK);
BOOST_REQUIRE(test_utils::Value<cass_int8_t>::equal(input.tinyint_sample, output.tinyint_sample));
BOOST_REQUIRE(cass_value_get_int16(cass_row_get_column(row, 12), &output.smallint_sample) == CASS_OK);
BOOST_REQUIRE(test_utils::Value<cass_int16_t>::equal(input.smallint_sample, output.smallint_sample));
BOOST_REQUIRE(cass_value_get_uint32(cass_row_get_column(row, 13), &output.date_sample.date) == CASS_OK);
BOOST_REQUIRE(test_utils::Value<CassDate>::equal(input.date_sample, output.date_sample));
BOOST_REQUIRE(cass_value_get_int64(cass_row_get_column(row, 14), &output.time_sample.time) == CASS_OK);
BOOST_REQUIRE(test_utils::Value<CassTime>::equal(input.time_sample, output.time_sample));
}
}
};
const char* PreparedTests::ALL_TYPE_TABLE_NAME = "all_types_table_prepared";
BOOST_FIXTURE_TEST_SUITE(prepared, PreparedTests)
BOOST_AUTO_TEST_CASE(bound_all_types_different_values)
{
std::string insert_query = str(boost::format("INSERT INTO %s (%s) VALUES (%s)")
% ALL_TYPE_TABLE_NAME
% columns_
% values_);
test_utils::CassFuturePtr prepared_future(cass_session_prepare_n(session,
insert_query.data(), insert_query.size()));
test_utils::wait_and_check_error(prepared_future.get());
test_utils::CassPreparedPtr prepared(cass_future_get_prepared(prepared_future.get()));
uint8_t varint1[] = { 1, 2, 3 };
uint8_t varint2[] = { 0, 0, 0 };
uint8_t varint3[] = { 255, 255, 255, 255, 255 };
uint8_t bytes1[] = { 255, 255 };
uint8_t bytes2[] = { 0, 0 };
uint8_t bytes3[] = { 1, 1 };
uint8_t address1[CASS_INET_V4_LENGTH] = { 192, 168, 0, 100 };
uint8_t address2[CASS_INET_V4_LENGTH] = { 0, 0, 0, 0 };
uint8_t address3[CASS_INET_V6_LENGTH] = { 255, 128, 12, 1, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255 };
const size_t all_types_count = 3;
AllTypes all_types[all_types_count];
all_types[0].id = test_utils::generate_time_uuid(uuid_gen);
all_types[0].text_sample = CassString("first");
all_types[0].int_sample = 10;
all_types[0].bigint_sample = CASS_INT64_MAX - 1L;
all_types[0].float_sample = 1.999f;
all_types[0].double_sample = 32.002;
all_types[0].decimal_sample = CassDecimal(varint1, sizeof(varint1), 1);
all_types[0].blob_sample = CassBytes(bytes1, sizeof(bytes1));
all_types[0].boolean_sample = cass_true;
all_types[0].timestamp_sample = 1123200000;
all_types[0].inet_sample = cass_inet_init_v4(address1);
if ((version.major_version >= 2 && version.minor_version >= 2) || version.major_version >= 3) {
all_types[0].tinyint_sample = 37;
all_types[0].smallint_sample = 456;
all_types[0].date_sample = test_utils::Value<CassDate>::max_value();
all_types[0].time_sample = test_utils::Value<CassTime>::max_value();
}
all_types[1].id = test_utils::generate_time_uuid(uuid_gen);
all_types[1].text_sample = CassString("second");
all_types[1].int_sample = 0;
all_types[1].bigint_sample = 0L;
all_types[1].float_sample = 0.0f;
all_types[1].double_sample = 0.0;
all_types[1].decimal_sample = CassDecimal(varint2, sizeof(varint2), 2);
all_types[1].blob_sample = CassBytes(bytes2, sizeof(bytes2));
all_types[1].boolean_sample = cass_false;
all_types[1].timestamp_sample = 0;
all_types[1].inet_sample = cass_inet_init_v4(address2);
if ((version.major_version >= 2 && version.minor_version >= 2) || version.major_version >= 3) {
all_types[1].tinyint_sample = 0;
all_types[1].smallint_sample = 0;
all_types[1].date_sample = 0;
all_types[1].time_sample = 0;
}
all_types[2].id = test_utils::generate_time_uuid(uuid_gen);
all_types[2].text_sample = CassString("third");
all_types[2].int_sample = -100;
all_types[2].bigint_sample = CASS_INT64_MIN + 1;
all_types[2].float_sample = -150.111f;
all_types[2].double_sample = -5.12342;
all_types[2].decimal_sample = CassDecimal(varint3, sizeof(varint3), 3);
all_types[2].blob_sample = CassBytes(bytes3, sizeof(bytes3));
all_types[2].boolean_sample = cass_true;
all_types[2].timestamp_sample = -13462502400;
all_types[2].inet_sample = cass_inet_init_v4(address3);
if ((version.major_version >= 2 && version.minor_version >= 2) || version.major_version >= 3) {
all_types[2].tinyint_sample = 127;
all_types[2].smallint_sample = 32767;
all_types[2].date_sample = test_utils::Value<CassDate>::min_value();
all_types[2].time_sample = 12345678;
}
for (size_t i = 0; i < all_types_count; ++i) {
insert_all_types(session, prepared.get(), all_types[i]);
}
std::string select_query = str(boost::format("SELECT %s FROM %s WHERE id IN (%s, %s, %s)")
% columns_
% ALL_TYPE_TABLE_NAME
% test_utils::string_from_uuid(all_types[0].id)
% test_utils::string_from_uuid(all_types[1].id)
% test_utils::string_from_uuid(all_types[2].id));
test_utils::CassResultPtr result;
test_utils::execute_query(session, select_query, &result);
BOOST_REQUIRE(cass_result_row_count(result.get()) == all_types_count);
BOOST_REQUIRE(cass_result_column_count(result.get()) == column_size_);
test_utils::CassIteratorPtr iterator(cass_iterator_from_result(result.get()));
while (cass_iterator_next(iterator.get())) {
const CassRow* row = cass_iterator_get_row(iterator.get());
CassUuid id;
cass_value_get_uuid(cass_row_get_column(row, 0), &id);
for (size_t i = 0; i < all_types_count; ++i) {
if (test_utils::Value<CassUuid>::equal(id, all_types[i].id)) {
compare_all_types(all_types[i], row);
}
}
}
}
BOOST_AUTO_TEST_CASE(bound_all_types_null_values)
{
std::string insert_query = str(boost::format("INSERT INTO %s (%s) VALUES (%s)")
% ALL_TYPE_TABLE_NAME
% columns_
% values_);
test_utils::CassFuturePtr prepared_future(cass_session_prepare_n(session,
insert_query.data(), insert_query.size()));
test_utils::wait_and_check_error(prepared_future.get());
test_utils::CassPreparedPtr prepared(cass_future_get_prepared(prepared_future.get()));
test_utils::CassStatementPtr statement(cass_prepared_bind(prepared.get()));
CassUuid id = test_utils::generate_time_uuid(uuid_gen);
cass_statement_bind_uuid(statement.get(), 0, id);
for (size_t i = 1; i < column_size_; ++i) {
cass_statement_bind_null(statement.get(), i);
}
test_utils::CassFuturePtr future(cass_session_execute(session, statement.get()));
test_utils::wait_and_check_error(future.get());
std::string select_query = str(boost::format("SELECT %s FROM %s WHERE id IN (%s)")
% columns_
% ALL_TYPE_TABLE_NAME
% test_utils::string_from_uuid(id));
test_utils::CassResultPtr result;
test_utils::execute_query(session, select_query, &result);
BOOST_REQUIRE(cass_result_row_count(result.get()) == 1);
BOOST_REQUIRE(cass_result_column_count(result.get()) == column_size_);
const CassRow* row = cass_result_first_row(result.get());
CassUuid result_id;
BOOST_REQUIRE(cass_value_get_uuid(cass_row_get_column(row, 0), &result_id) == CASS_OK);
BOOST_REQUIRE(test_utils::Value<CassUuid>::equal(id, result_id));
for (size_t i = 1; i < column_size_; ++i) {
BOOST_REQUIRE(cass_value_is_null(cass_row_get_column(row, i)));
}
}
BOOST_AUTO_TEST_CASE(select_one)
{
std::string table_name = str(boost::format("table_%s") % test_utils::generate_unique_str(uuid_gen));
std::string create_table_query = str(boost::format("CREATE TABLE %s (tweet_id int PRIMARY KEY, numb double, label text);") % table_name);
test_utils::execute_query(session, create_table_query);
for (int i = 0; i < 10; ++i) {
std::string insert_query = str(boost::format("INSERT INTO %s (tweet_id, numb, label) VALUES(%d, 0.01,'row%d')") % table_name % i % i);
test_utils::execute_query(session, insert_query);
}
std::string select_query = str(boost::format("SELECT * FROM %s WHERE tweet_id = ?;") % table_name);
test_utils::CassFuturePtr prepared_future(cass_session_prepare_n(session,
select_query.data(), select_query.size()));
test_utils::wait_and_check_error(prepared_future.get());
test_utils::CassPreparedPtr prepared(cass_future_get_prepared(prepared_future.get()));
int tweet_id = 5;
test_utils::CassStatementPtr statement(cass_prepared_bind(prepared.get()));
BOOST_REQUIRE(cass_statement_bind_int32(statement.get(), 0, tweet_id) == CASS_OK);
test_utils::CassFuturePtr future(cass_session_execute(session, statement.get()));
test_utils::wait_and_check_error(future.get());
test_utils::CassResultPtr result(cass_future_get_result(future.get()));
BOOST_REQUIRE(cass_result_row_count(result.get()) == 1);
BOOST_REQUIRE(cass_result_column_count(result.get()) == 3);
const CassRow* row = cass_result_first_row(result.get());
int result_tweet_id;
CassString result_label;
BOOST_REQUIRE(cass_value_get_int32(cass_row_get_column(row, 0), &result_tweet_id) == CASS_OK);
BOOST_REQUIRE(test_utils::Value<cass_int32_t>::equal(tweet_id, result_tweet_id));
BOOST_REQUIRE(cass_value_get_string(cass_row_get_column(row, 1), &result_label.data, &result_label.length) == CASS_OK);
BOOST_REQUIRE(test_utils::Value<CassString>::equal(CassString("row5"), result_label));
}
#if BOOST_VERSION < 105700
CassPreparedMovable prepare_statement(CassSession* session, std::string query) {
#else
test_utils::CassPreparedPtr prepare_statement(CassSession* session, std::string query) {
#endif
test_utils::CassFuturePtr prepared_future(cass_session_prepare_n(session,
query.data(), query.size()));
test_utils::wait_and_check_error(prepared_future.get());
#if BOOST_VERSION < 105700
return CassPreparedMovable(cass_future_get_prepared(prepared_future.get()));
#else
return test_utils::CassPreparedPtr(cass_future_get_prepared(prepared_future.get()));
#endif
}
void execute_statement(CassSession* session, const CassPrepared* prepared, int value) {
test_utils::CassStatementPtr statement(cass_prepared_bind(prepared));
BOOST_REQUIRE(cass_statement_bind_double(statement.get(), 0, static_cast<double>(value)) == CASS_OK);
BOOST_REQUIRE(cass_statement_bind_int32(statement.get(), 1, value) == CASS_OK);
test_utils::CassFuturePtr future(cass_session_execute(session, statement.get()));
test_utils::wait_and_check_error(future.get());
}
BOOST_AUTO_TEST_CASE(massive_number_of_prepares)
{
std::string table_name = str(boost::format("table_%s") % test_utils::generate_unique_str(uuid_gen));
std::string create_table_query = str(boost::format("CREATE TABLE %s (tweet_id uuid PRIMARY KEY, numb1 double, numb2 int);") % table_name);
size_t number_of_prepares = 100;
test_utils::execute_query(session, create_table_query);
#if BOOST_VERSION < 105700
CONTAINER<boost::BOOST_THREAD_FUTURE<CassPreparedMovable> > prepare_futures;
#else
CONTAINER<boost::BOOST_THREAD_FUTURE<test_utils::CassPreparedPtr> > prepare_futures;
#endif
std::vector<CassUuid> tweet_ids;
for (size_t i = 0; i < number_of_prepares; ++i) {
CassUuid tweet_id = test_utils::generate_time_uuid(uuid_gen);
std::string insert_query = str(boost::format("INSERT INTO %s (tweet_id, numb1, numb2) VALUES (%s, ?, ?);") % table_name % test_utils::string_from_uuid(tweet_id));
prepare_futures.push_back(boost::async(boost::launch::async, boost::bind(prepare_statement, session, insert_query)));
tweet_ids.push_back(tweet_id);
}
std::vector<boost::shared_future<void> > execute_futures;
#if BOOST_VERSION < 105700
CONTAINER<CassPreparedMovable> prepares;
#else
CONTAINER<test_utils::CassPreparedPtr> prepares;
#endif
for (size_t i = 0; i < prepare_futures.size(); ++i) {
#if BOOST_VERSION < 105700
CassPreparedMovable prepared = prepare_futures[i].get();
#else
test_utils::CassPreparedPtr prepared = prepare_futures[i].get();
#endif
execute_futures.push_back(boost::async(boost::launch::async, boost::bind(execute_statement, session, prepared.get(), i)).share());
prepares.push_back(boost::move(prepared));
}
boost::wait_for_all(execute_futures.begin(), execute_futures.end());
std::string select_query = str(boost::format("SELECT * FROM %s;") % table_name);
test_utils::CassResultPtr result;
test_utils::execute_query(session, select_query, &result);
BOOST_REQUIRE(cass_result_row_count(result.get()) == number_of_prepares);
test_utils::CassIteratorPtr iterator(cass_iterator_from_result(result.get()));
while (cass_iterator_next(iterator.get())) {
const CassRow* row = cass_iterator_get_row(iterator.get());
CassUuid result_tweet_id;
cass_value_get_uuid(cass_row_get_column(row, 0), &result_tweet_id);
BOOST_REQUIRE(std::find(tweet_ids.begin(), tweet_ids.end(), result_tweet_id) != tweet_ids.end());
}
}
BOOST_AUTO_TEST_SUITE_END()
|
flightaware/cpp-driver
|
test/integration_tests/src/test_prepared.cpp
|
C++
|
apache-2.0
| 22,099 |
package pl.touk.sputnik.processor.ktlint;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import pl.touk.sputnik.configuration.Configuration;
import pl.touk.sputnik.configuration.ConfigurationBuilder;
import pl.touk.sputnik.review.Review;
import pl.touk.sputnik.review.ReviewFile;
import pl.touk.sputnik.review.ReviewFormatterFactory;
import pl.touk.sputnik.review.ReviewResult;
import pl.touk.sputnik.review.Severity;
import pl.touk.sputnik.review.Violation;
import java.util.ArrayList;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
class KtlintProcessorTest {
private static final String CONFIGURATION_WITH_KTLINT_ENABLED = "ktlint/configuration/configurationWithEnabledKtlint.properties";
private static final String CONFIGURATION_WITH_KTLINT_ENABLED_AND_EXCLUDE = "ktlint/configuration/configurationWithEnabledKtlintAndExclude.properties";
private static final String REVIEW_FILE_WITH_ONE_VIOLATION = "src/test/resources/ktlint/testFiles/OneViolation.kt";
private static final String REVIEW_FILE_WITH_NO_VIOLATIONS = "src/test/resources/ktlint/testFiles/NoViolations.kt";
private static final String REVIEW_FILE_WITH_MANY_VIOLATIONS = "src/test/resources/ktlint/testFiles/ManyViolations.kt";
private static final String REVIEW_GROOVY_FILE = "src/test/resources/codeNarc/testFiles/FileWithOneViolationLevel2.groovy";
private KtlintProcessor sut;
private Configuration config;
@BeforeEach
void setUp() throws Exception {
config = ConfigurationBuilder.initFromResource(CONFIGURATION_WITH_KTLINT_ENABLED);
sut = new KtlintProcessor(config);
}
@Test
void shouldReturnOneViolationsForFile() {
Review review = getReview(REVIEW_FILE_WITH_ONE_VIOLATION);
ReviewResult result = sut.process(review);
assertThat(result).isNotNull();
assertThat(result.getViolations())
.hasSize(1)
.contains(new Violation(REVIEW_FILE_WITH_ONE_VIOLATION, 3, "[no-empty-class-body] Unnecessary block (\"{}\") in column 20", Severity.WARNING));
}
@Test
void shouldReturnNoViolationsForNotKotlinFiles() {
Review review = getReview(REVIEW_GROOVY_FILE);
ReviewResult result = sut.process(review);
assertThat(result).isNotNull();
assertThat(result.getViolations()).isEmpty();
}
@Test
void shouldReturnNoViolationsForEmptyReview() {
Review review = getReview();
ReviewResult result = sut.process(review);
assertThat(result).isNotNull();
assertThat(result.getViolations()).isEmpty();
}
@Test
void shouldReturnViolationsFromManyFiles() {
Review review = getReview(REVIEW_FILE_WITH_MANY_VIOLATIONS, REVIEW_FILE_WITH_NO_VIOLATIONS, REVIEW_FILE_WITH_ONE_VIOLATION);
ReviewResult result = sut.process(review);
assertThat(result).isNotNull();
assertThat(result.getViolations())
.hasSize(11)
.contains(new Violation(REVIEW_FILE_WITH_MANY_VIOLATIONS, 3, "[no-wildcard-imports] Wildcard import in column 1", Severity.WARNING))
.contains(new Violation(REVIEW_FILE_WITH_MANY_VIOLATIONS, 6, "[indent] Unexpected indentation (2) (should be 4) in column 1", Severity.WARNING))
.contains(new Violation(REVIEW_FILE_WITH_MANY_VIOLATIONS, 6, "[curly-spacing] Missing spacing before \"{\" in column 21", Severity.WARNING))
.contains(new Violation(REVIEW_FILE_WITH_MANY_VIOLATIONS, 7, "[indent] Unexpected indentation (6) (should be 8) in column 1", Severity.WARNING))
.contains(new Violation(REVIEW_FILE_WITH_MANY_VIOLATIONS, 7, "[no-semi] Unnecessary semicolon in column 17", Severity.WARNING))
.contains(new Violation(REVIEW_FILE_WITH_MANY_VIOLATIONS, 8, "[indent] Unexpected indentation (6) (should be 8) in column 1", Severity.WARNING))
.contains(new Violation(REVIEW_FILE_WITH_MANY_VIOLATIONS, 8, "[string-template] Redundant curly braces in column 16", Severity.WARNING))
.contains(new Violation(REVIEW_FILE_WITH_MANY_VIOLATIONS, 8, "[string-template] Redundant \"toString()\" call in string template in column 23", Severity.WARNING))
.contains(new Violation(REVIEW_FILE_WITH_MANY_VIOLATIONS, 9, "[indent] Unexpected indentation (2) (should be 4) in column 1", Severity.WARNING))
.contains(new Violation(REVIEW_FILE_WITH_MANY_VIOLATIONS, 11, "[curly-spacing] Missing spacing before \"{\" in column 14", Severity.WARNING))
.contains(new Violation(REVIEW_FILE_WITH_ONE_VIOLATION, 3, "[no-empty-class-body] Unnecessary block (\"{}\") in column 20", Severity.WARNING));
}
@Test
void shouldReturnOnlyNotExcludedViolations() {
KtlintProcessor sut = new KtlintProcessor(ConfigurationBuilder.initFromResource(CONFIGURATION_WITH_KTLINT_ENABLED_AND_EXCLUDE));
Review review = getReview(REVIEW_FILE_WITH_MANY_VIOLATIONS);
ReviewResult result = sut.process(review);
assertThat(result).isNotNull();
assertThat(result.getViolations())
.hasSize(5)
.contains(new Violation(REVIEW_FILE_WITH_MANY_VIOLATIONS, 3, "[no-wildcard-imports] Wildcard import in column 1", Severity.WARNING))
.contains(new Violation(REVIEW_FILE_WITH_MANY_VIOLATIONS, 6, "[curly-spacing] Missing spacing before \"{\" in column 21", Severity.WARNING))
.contains(new Violation(REVIEW_FILE_WITH_MANY_VIOLATIONS, 8, "[string-template] Redundant curly braces in column 16", Severity.WARNING))
.contains(new Violation(REVIEW_FILE_WITH_MANY_VIOLATIONS, 8, "[string-template] Redundant \"toString()\" call in string template in column 23", Severity.WARNING))
.contains(new Violation(REVIEW_FILE_WITH_MANY_VIOLATIONS, 11, "[curly-spacing] Missing spacing before \"{\" in column 14", Severity.WARNING));
}
private Review getReview(String... filePaths) {
List<ReviewFile> files = new ArrayList<>();
for (String filePath : filePaths) {
files.add(new ReviewFile(filePath));
}
return new Review(files, ReviewFormatterFactory.get(config));
}
}
|
TouK/sputnik
|
src/test/java/pl/touk/sputnik/processor/ktlint/KtlintProcessorTest.java
|
Java
|
apache-2.0
| 6,283 |
/**
* Copyright (c) 2014-2016 https://github.com/playersun
*
* Licensed under the Apache License, Version 2.0 (the "License");
*/
package com.playersun.jbf.modules.sys.service;
import javax.annotation.PostConstruct;
import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import com.playersun.jbf.common.utils.UserLogUtils;
import com.playersun.jbf.common.utils.security.Md5Utils;
import com.playersun.jbf.modules.sys.entity.User;
import com.playersun.jbf.modules.sys.exception.UserPasswordNotMatchException;
import com.playersun.jbf.modules.sys.exception.UserPasswordRetryLimitExceedException;
/**
* 密码服务类
* @author PlayerSun
* @date Oct 5, 2015
*/
@Service
public class PasswordService {
@Value(value = "${user.password.maxRetryCount}")
private int maxRetryCount = 10;
public void setMaxRetryCount(int maxRetryCount) {
this.maxRetryCount = maxRetryCount;
}
@Autowired
private CacheManager ehcacheManager;
private Cache loginRecordCache;
@PostConstruct
public void init() {
loginRecordCache = ehcacheManager.getCache("loginRecordCache");
}
public void clearLoginRecordCache(String username) {
loginRecordCache.remove(username);
}
public int getMaxRetryCoun() {
return this.maxRetryCount;
}
public void validate(User user, String password) {
String username = user.getUsername();
int retryCount = 0;
Element cacheElement = loginRecordCache.get(username);
if (cacheElement != null) {
retryCount = (Integer) cacheElement.getObjectValue();
if (retryCount >= maxRetryCount) {
UserLogUtils.log(
username,
"passwordError",
"password error, retry limit exceed! password: {},max retry count {}",
password, maxRetryCount);
throw new UserPasswordRetryLimitExceedException(maxRetryCount);
}
}
if (!matches(user, password)) {
loginRecordCache.put(new Element(username, ++retryCount));
UserLogUtils.log(
username,
"passwordError",
"password error! password: {} retry count: {}",
password, retryCount);
throw new UserPasswordNotMatchException();
} else {
clearLoginRecordCache(username);
}
}
public boolean matches(User user, String newPassword) {
// return user.getPassword().equals(encryptPassword(user.getUsername(), newPassword, user.getSalt()));
return user.getPassword().equals(newPassword);
}
public String encryptPassword(String username, String password, String salt) {
return Md5Utils.hash(username + password + salt);
}
}
|
playersun/jee-basic-function
|
src/main/java/com/playersun/jbf/modules/sys/service/PasswordService.java
|
Java
|
apache-2.0
| 3,083 |
package com.slickqa.client.model;
import java.util.Date;
public class ResultReference {
private String status = null;
/* A String representation of a BSON ObjectId */
private String resultId = null;
/* The number of milliseconds since EPOCH GMT */
private Date recorded = null;
private BuildReference build = null;
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getResultId() {
return resultId;
}
public void setResultId(String resultId) {
this.resultId = resultId;
}
public Date getRecorded() {
return recorded;
}
public void setRecorded(Date recorded) {
this.recorded = recorded;
}
public BuildReference getBuild() {
return build;
}
public void setBuild(BuildReference build) {
this.build = build;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class ResultReference {\n");
sb.append(" status: ").append(status).append("\n");
sb.append(" resultId: ").append(resultId).append("\n");
sb.append(" recorded: ").append(recorded).append("\n");
sb.append(" build: ").append(build).append("\n");
sb.append("}\n");
return sb.toString();
}
}
|
slickqa/slickqa-java-client
|
src/main/java/com/slickqa/client/model/ResultReference.java
|
Java
|
apache-2.0
| 1,278 |
/*
* Copyright (c) 2015 Markus Poeschl
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package de.poeschl.apps.tryandremove.models;
import android.content.SharedPreferences;
import javax.inject.Singleton;
import dagger.Module;
import dagger.Provides;
import de.poeschl.apps.tryandremove.annotations.IsMockMode;
import de.poeschl.apps.tryandremove.annotations.ScalpelEnabled;
import de.poeschl.apps.tryandremove.annotations.ScalpelWireframeEnabled;
import de.poeschl.apps.tryandremove.annotations.SettingsDrawerSeen;
/**
* Created by Markus Pöschl on 09.12.2014.
*/
@Module(
library = true,
complete = false
)
public class DebugModelModule {
@Provides
@Singleton
@ScalpelEnabled
BooleanPreference provideScalpelEnabled(SharedPreferences preferences) {
return new BooleanPreference(preferences, "debug_scalpel_enabled", false);
}
@Provides
@Singleton
@ScalpelWireframeEnabled
BooleanPreference provideScalpelWireframeEnabled(SharedPreferences preferences) {
return new BooleanPreference(preferences, "debug_scalpel_wireframe_enabled", false);
}
@Provides
@Singleton
@SettingsDrawerSeen
BooleanPreference provideSettingsDrawerSeen(SharedPreferences preferences) {
return new BooleanPreference(preferences, "debug_settings_seen", false);
}
@Provides
@IsMockMode
BooleanPreference provideIsMockMode(SharedPreferences preferences) {
return new BooleanPreference(preferences, "debug_mock_mode_boolean", false);
}
}
|
Poeschl/TryAndRemove
|
app/src/debug/java/de/poeschl/apps/tryandremove/models/DebugModelModule.java
|
Java
|
apache-2.0
| 2,059 |
<div>
<p>
A YAML file containing the specification for the executable portion of your Jenkins job configuration.
</p>
<p>
For Example:<code><pre>
$class: !freestyle
builder:
$class: !shell
command: echo Hello World</pre></code></p>
<p>
To see what your job configuration might look like as a YAML, try creating it through the traditional Jenkins web interface, and then clicking on the "<img src="${rootURL}/plugin/yaml-project-plugin/images/24x24/yaml.png" height="18" width="18" style="vertical-align: bottom"/><span style="font-family: courier; color: red; font-size: 150%">YAML</span> Project" in the left-hand navigation pane.
</p>
</div>
|
jenkinsci/yaml-project-plugin
|
src/main/resources/com/google/jenkins/plugins/dsl/YamlProject/help-yamlPath.html
|
HTML
|
apache-2.0
| 670 |
using System;
using System.Xml.Serialization;
namespace Aop.Api.Domain
{
/// <summary>
/// AlipayOfflineMarketShopQuerydetailModel Data Structure.
/// </summary>
[Serializable]
public class AlipayOfflineMarketShopQuerydetailModel : AopObject
{
/// <summary>
/// 店铺id
/// </summary>
[XmlElement("shop_id")]
public string ShopId { get; set; }
}
}
|
oceanho/AnyPayment
|
docs/alipay-sdk-NET-20151130120112/Domain/AlipayOfflineMarketShopQuerydetailModel.cs
|
C#
|
apache-2.0
| 418 |
/*
* Copyright 2013 Anton Karmanov
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.antkar.syn.sample.script.rt.op;
import org.antkar.syn.sample.script.rt.value.RValue;
import org.antkar.syn.sample.script.rt.value.Value;
/**
* Script Language <code>/</code> operator.
*/
final class DivBinaryOperator extends BinaryOperator {
DivBinaryOperator() {
super("/");
}
@Override
RValue evaluate(long left, long right) {
return Value.forLong(left / right);
}
@Override
RValue evaluate(double left, double right) {
return Value.forDouble(left / right);
}
}
|
antkar/syn
|
syn-sample-script/src/main/java/org/antkar/syn/sample/script/rt/op/DivBinaryOperator.java
|
Java
|
apache-2.0
| 1,136 |
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.azrul.langkuik.framework.activechoice;
/**
*
* @author azrulm
*/
public interface ActiveChoiceEnum<E> {
E getParent();
}
|
azrulhasni/Langkuik
|
src/main/java/org/azrul/langkuik/framework/activechoice/ActiveChoiceEnum.java
|
Java
|
apache-2.0
| 327 |
Read data from one or multiple streams, only returning entries with an
ID greater than the last received ID reported by the caller.
This command has an option to block if items are not available, in a similar
fashion to `BRPOP` or `BZPOPMIN` and others.
Please note that before reading this page, if you are new to streams,
we recommend to read [our introduction to Redis Streams](/topics/streams-intro).
## Non-blocking usage
If the **BLOCK** option is not used, the command is synchronous, and can
be considered somewhat related to `XRANGE`: it will return a range of items
inside streams, however it has two fundamental differences compared to `XRANGE`
even if we just consider the synchronous usage:
* This command can be called with multiple streams if we want to read at
the same time from a number of keys. This is a key feature of `XREAD` because
especially when blocking with **BLOCK**, to be able to listen with a single
connection to multiple keys is a vital feature.
* While `XRANGE` returns items in a range of IDs, `XREAD` is more suited in
order to consume the stream starting from the first entry which is greater
than any other entry we saw so far. So what we pass to `XREAD` is, for each
stream, the ID of the last element that we received from that stream.
For example, if I have two streams `mystream` and `writers`, and I want to
read data from both the streams starting from the first element they contain,
I could call `XREAD` like in the following example.
Note: we use the **COUNT** option in the example, so that for each stream
the call will return at maximum two elements per stream.
```
> XREAD COUNT 2 STREAMS mystream writers 0-0 0-0
1) 1) "mystream"
2) 1) 1) 1526984818136-0
2) 1) "duration"
2) "1532"
3) "event-id"
4) "5"
5) "user-id"
6) "7782813"
2) 1) 1526999352406-0
2) 1) "duration"
2) "812"
3) "event-id"
4) "9"
5) "user-id"
6) "388234"
2) 1) "writers"
2) 1) 1) 1526985676425-0
2) 1) "name"
2) "Virginia"
3) "surname"
4) "Woolf"
2) 1) 1526985685298-0
2) 1) "name"
2) "Jane"
3) "surname"
4) "Austen"
```
The **STREAMS** option is mandatory and MUST be the final option because
such option gets a variable length of argument in the following format:
STREAMS key_1 key_2 key_3 ... key_N ID_1 ID_2 ID_3 ... ID_N
So we start with a list of keys, and later continue with all the associated
IDs, representing *the last ID we received for that stream*, so that the
call will serve us only greater IDs from the same stream.
For instance in the above example, the last items that we received
for the stream `mystream` has ID `1526999352406-0`, while for the
stream `writers` has the ID `1526985685298-0`.
To continue iterating the two streams I'll call:
```
> XREAD COUNT 2 STREAMS mystream writers 1526999352406-0 1526985685298-0
1) 1) "mystream"
2) 1) 1) 1526999626221-0
2) 1) "duration"
2) "911"
3) "event-id"
4) "7"
5) "user-id"
6) "9488232"
2) 1) "writers"
2) 1) 1) 1526985691746-0
2) 1) "name"
2) "Toni"
3) "surname"
4) "Morrison"
2) 1) 1526985712947-0
2) 1) "name"
2) "Agatha"
3) "surname"
4) "Christie"
```
And so forth. Eventually, the call will not return any item, but just an
empty array, then we know that there is nothing more to fetch from our
stream (and we would have to retry the operation, hence this command
also supports a blocking mode).
## Incomplete IDs
To use incomplete IDs is valid, like it is valid for `XRANGE`. However
here the sequence part of the ID, if missing, is always interpreted as
zero, so the command:
```
> XREAD COUNT 2 STREAMS mystream writers 0 0
```
is exactly equivalent to
```
> XREAD COUNT 2 STREAMS mystream writers 0-0 0-0
```
## Blocking for data
In its synchronous form, the command can get new data as long as there
are more items available. However, at some point, we'll have to wait for
producers of data to use `XADD` to push new entries inside the streams
we are consuming. In order to avoid polling at a fixed or adaptive interval
the command is able to block if it could not return any data, according
to the specified streams and IDs, and automatically unblock once one of
the requested keys accept data.
It is important to understand that this command *fans out* to all the
clients that are waiting for the same range of IDs, so every consumer will
get a copy of the data, unlike to what happens when blocking list pop
operations are used.
In order to block, the **BLOCK** option is used, together with the number
of milliseconds we want to block before timing out. Normally Redis blocking
commands take timeouts in seconds, however this command takes a millisecond
timeout, even if normally the server will have a timeout resolution near
to 0.1 seconds. This time it is possible to block for a shorter time in
certain use cases, and if the server internals will improve over time, it is
possible that the resolution of timeouts will improve.
When the **BLOCK** command is passed, but there is data to return at
least in one of the streams passed, the command is executed synchronously
*exactly like if the BLOCK option would be missing*.
This is an example of blocking invocation, where the command later returns
a null reply because the timeout has elapsed without new data arriving:
```
> XREAD BLOCK 1000 STREAMS mystream 1526999626221-0
(nil)
```
## The special `$` ID.
When blocking sometimes we want to receive just entries that are added
to the stream via `XADD` starting from the moment we block. In such a case
we are not interested in the history of already added entries. For
this use case, we would have to check the stream top element ID, and use
such ID in the `XREAD` command line. This is not clean and requires to
call other commands, so instead it is possible to use the special `$`
ID to signal the stream that we want only the new things.
It is **very important** to understand that you should use the `$`
ID only for the first call to `XREAD`. Later the ID should be the one
of the last reported item in the stream, otherwise you could miss all
the entries that are added in between.
This is how a typical `XREAD` call looks like in the first iteration
of a consumer willing to consume only new entries:
```
> XREAD BLOCK 5000 COUNT 100 STREAMS mystream $
```
Once we get some replies, the next call will be something like:
```
> XREAD BLOCK 5000 COUNT 100 STREAMS mystream 1526999644174-3
```
And so forth.
## How multiple clients blocked on a single stream are served
Blocking list operations on lists or sorted sets have a *pop* behavior.
Basically, the element is removed from the list or sorted set in order
to be returned to the client. In this scenario you want the items
to be consumed in a fair way, depending on the moment clients blocked
on a given key arrived. Normally Redis uses the FIFO semantics in this
use cases.
However note that with streams this is not a problem: stream entries
are not removed from the stream when clients are served, so every
client waiting will be served as soon as an `XADD` command provides
data to the stream.
@return
@array-reply, specifically:
The command returns an array of results: each element of the returned
array is an array composed of a two element containing the key name and
the entries reported for that key. The entries reported are full stream
entries, having IDs and the list of all the fields and values. Field and
values are guaranteed to be reported in the same order they were added
by `XADD`.
When **BLOCK** is used, on timeout a null reply is returned.
Reading the [Redis Streams introduction](/topics/streams-intro) is highly
suggested in order to understand more about the streams overall behavior
and semantics.
|
mmkal/handy-redis
|
docs/redis-doc/commands/xread.md
|
Markdown
|
apache-2.0
| 8,068 |
package org.jbpm.services.task.impl.model.xml;
import static org.jbpm.services.task.impl.model.xml.AbstractJaxbTaskObject.convertListFromInterfaceToJaxbImpl;
import static org.jbpm.services.task.impl.model.xml.AbstractJaxbTaskObject.unsupported;
import static org.jbpm.services.task.impl.model.xml.JaxbOrganizationalEntity.convertListFromJaxbImplToInterface;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.util.Collections;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlSchemaType;
import javax.xml.bind.annotation.XmlType;
import org.codehaus.jackson.annotate.JsonAutoDetect;
import org.jbpm.services.task.impl.model.xml.InternalJaxbWrapper.GetterUser;
import org.kie.api.task.model.OrganizationalEntity;
import org.kie.api.task.model.PeopleAssignments;
import org.kie.api.task.model.User;
import org.kie.internal.task.api.model.InternalPeopleAssignments;
@XmlType(name="people-assignments")
@XmlAccessorType(XmlAccessType.FIELD)
@JsonAutoDetect(getterVisibility=JsonAutoDetect.Visibility.NONE, setterVisibility=JsonAutoDetect.Visibility.NONE, fieldVisibility=JsonAutoDetect.Visibility.ANY)
public class JaxbPeopleAssignments implements InternalPeopleAssignments {
@XmlElement(name="task-initiator-id")
@XmlSchemaType(name="string")
private String taskInitiatorId;
@XmlElement(name="potential-owners")
private List<JaxbOrganizationalEntity> potentialOwners;
@XmlElement(name="business-administrators")
private List<JaxbOrganizationalEntity> businessAdministrators;
@XmlElement(name="excluded-owners")
private List<JaxbOrganizationalEntity> excludedOwners;
@XmlElement(name="task-stakeholders")
private List<JaxbOrganizationalEntity> taskStakeholders;
@XmlElement
private List<JaxbOrganizationalEntity> recipients;
public JaxbPeopleAssignments() {
// Default constructor for JAXB
}
public JaxbPeopleAssignments(PeopleAssignments peopleAssignments) {
User taskInitiatorUser = peopleAssignments.getTaskInitiator();
if( taskInitiatorUser != null ) {
this.taskInitiatorId = taskInitiatorUser.getId();
}
this.businessAdministrators = convertListFromInterfaceToJaxbImpl(((InternalPeopleAssignments) peopleAssignments).getBusinessAdministrators(), OrganizationalEntity.class, JaxbOrganizationalEntity.class);
this.excludedOwners = convertListFromInterfaceToJaxbImpl(((InternalPeopleAssignments) peopleAssignments).getExcludedOwners(), OrganizationalEntity.class, JaxbOrganizationalEntity.class);
this.potentialOwners = convertListFromInterfaceToJaxbImpl(((InternalPeopleAssignments) peopleAssignments).getPotentialOwners(), OrganizationalEntity.class, JaxbOrganizationalEntity.class);
this.recipients = convertListFromInterfaceToJaxbImpl(((InternalPeopleAssignments) peopleAssignments).getRecipients(), OrganizationalEntity.class, JaxbOrganizationalEntity.class);
this.taskStakeholders = convertListFromInterfaceToJaxbImpl(((InternalPeopleAssignments) peopleAssignments).getTaskStakeholders(), OrganizationalEntity.class, JaxbOrganizationalEntity.class);
}
@Override
public User getTaskInitiator() {
if( this.taskInitiatorId != null ) {
return new GetterUser(this.taskInitiatorId);
}
return null;
}
public void setTaskInitiator(User taskInitiatorUser) {
if( taskInitiatorUser != null ) {
this.taskInitiatorId = taskInitiatorUser.getId();
}
}
public String getTaskInitiatorId() {
return taskInitiatorId;
}
public void setTaskInitiatorId(String taskInitiatorId) {
this.taskInitiatorId = taskInitiatorId;
}
@Override
public List<OrganizationalEntity> getPotentialOwners() {
if( potentialOwners == null ) {
return Collections.emptyList();
}
return Collections.unmodifiableList(convertListFromJaxbImplToInterface(potentialOwners));
}
public void setPotentialOwners(List<OrganizationalEntity> potentialOwners) {
this.potentialOwners = convertListFromInterfaceToJaxbImpl(potentialOwners, OrganizationalEntity.class, JaxbOrganizationalEntity.class);
}
@Override
public List<OrganizationalEntity> getBusinessAdministrators() {
if( businessAdministrators == null ) {
return Collections.emptyList();
}
return Collections.unmodifiableList(convertListFromJaxbImplToInterface(businessAdministrators));
}
public void setBusinessAdministrators(List<OrganizationalEntity> businessAdministrators) {
this.businessAdministrators = convertListFromInterfaceToJaxbImpl(businessAdministrators, OrganizationalEntity.class, JaxbOrganizationalEntity.class);
}
@Override
public List<OrganizationalEntity> getExcludedOwners() {
if( excludedOwners == null ) {
return Collections.emptyList();
}
return Collections.unmodifiableList(convertListFromJaxbImplToInterface(excludedOwners));
}
@Override
public void setExcludedOwners(List<OrganizationalEntity> excludedOwners) {
this.excludedOwners = convertListFromInterfaceToJaxbImpl(excludedOwners, OrganizationalEntity.class, JaxbOrganizationalEntity.class);
}
@Override
public List<OrganizationalEntity> getTaskStakeholders() {
if( taskStakeholders == null ) {
return Collections.emptyList();
}
return Collections.unmodifiableList(convertListFromJaxbImplToInterface(taskStakeholders));
}
@Override
public void setTaskStakeholders(List<OrganizationalEntity> taskStakeholders) {
this.taskStakeholders = convertListFromInterfaceToJaxbImpl(taskStakeholders, OrganizationalEntity.class, JaxbOrganizationalEntity.class);
}
@Override
public List<OrganizationalEntity> getRecipients() {
if( recipients == null ) {
return Collections.emptyList();
}
return Collections.unmodifiableList(convertListFromJaxbImplToInterface(recipients));
}
@Override
public void setRecipients(List<OrganizationalEntity> recipients) {
this.recipients = convertListFromInterfaceToJaxbImpl(recipients, OrganizationalEntity.class, JaxbOrganizationalEntity.class);
}
@Override
public void writeExternal( ObjectOutput out ) throws IOException {
unsupported(PeopleAssignments.class);
}
@Override
public void readExternal( ObjectInput in ) throws IOException, ClassNotFoundException {
unsupported(PeopleAssignments.class);
}
}
|
hxf0801/jbpm
|
jbpm-human-task/jbpm-human-task-core/src/main/java/org/jbpm/services/task/impl/model/xml/JaxbPeopleAssignments.java
|
Java
|
apache-2.0
| 6,809 |
package com.scalaAsm.x86
package Instructions
package General
// Description: Conditional Move - less/not greater (SF!=OF)
// Category: general/datamov
trait CMOVNGE extends InstructionDefinition {
val mnemonic = "CMOVNGE"
}
object CMOVNGE extends TwoOperands[CMOVNGE] with CMOVNGEImpl
trait CMOVNGEImpl extends CMOVNGE {
implicit object _0 extends TwoOp[r16, rm16] {
val opcode: TwoOpcodes = (0x0F, 0x4C) /r
val format = RegRmFormat
}
implicit object _1 extends TwoOp[r32, rm32] {
val opcode: TwoOpcodes = (0x0F, 0x4C) /r
val format = RegRmFormat
}
implicit object _2 extends TwoOp[r64, rm64] {
val opcode: TwoOpcodes = (0x0F, 0x4C) /r
override def prefix = REX.W(true)
val format = RegRmFormat
}
}
|
bdwashbu/scala-x86-inst
|
src/main/scala/com/scalaAsm/x86/Instructions/General/CMOVNGE.scala
|
Scala
|
apache-2.0
| 748 |
--
-- script executed against the 'extra database'
--
create table foo_extra (acol integer);
|
avaje/docker-commands
|
src/test/resources/init-extra-database.sql
|
SQL
|
apache-2.0
| 93 |
//
// BRRelutionCampaignService.h
// BlueRangeSDK
//
// Copyright (c) 2016-2017, M-Way Solutions GmbH
// All rights reserved.
//
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
//
#import <Foundation/Foundation.h>
@protocol BRIBeaconMessageActionMapper;
@protocol BRRelutionTagMessageActionMapper;
@protocol RelutionUUIDRegistry;
@protocol BRBeaconActionListener;
@protocol BRBeaconActionDebugListener;
@class BRRelutionTagMessageActionMapperEmptyStub;
@class BRIBeaconMessageScanner;
@class BRBeaconMessageActionTrigger;
@class BRRelution;
/**
* A Relution campaign service can trigger actions defined in a Relution campaign. Internally
* this class uses the {@link BRBeaconMessageActionTrigger} of the SDK's core layer. The action
* registry obtains all action informations from the Relution system. To start the trigger, just
* call the {@link #start} method. The start method will periodically update a list of iBeacons
* each 10 seconds. In future versions actions will also be triggered when Relution tags will be
* received..
*/
@interface BRRelutionCampaignService : NSObject {
// Registry
id<BRIBeaconMessageActionMapper> _iBeaconMessageActionMapper;
BRRelutionTagMessageActionMapperEmptyStub* _relutionTagMessageActionMapper;
// Message processing graph
BRIBeaconMessageScanner *_scanner;
BRBeaconMessageActionTrigger *_trigger;
}
- (id) initWithScanner: (BRIBeaconMessageScanner*) scanner andRelution: (BRRelution*) relution;
- (void) start;
- (void) stop;
- (void) addActionListener: (NSObject<BRBeaconActionListener>*) listener;
- (void) addDebugActionListener: (NSObject<BRBeaconActionDebugListener>*) listener;
@end
|
mwaylabs/BlueRange-SDK-iOS
|
BlueRangeSDK/BRRelutionCampaignService.h
|
C
|
apache-2.0
| 2,427 |
package butterknife;
import butterknife.compiler.ButterKnifeProcessor;
import com.google.testing.compile.JavaFileObjects;
import javax.tools.JavaFileObject;
import org.junit.Test;
import static com.google.common.truth.Truth.assertAbout;
import static com.google.testing.compile.JavaSourceSubjectFactory.javaSource;
public class OnFocusChangeTest {
@Test public void focusChange() {
JavaFileObject source = JavaFileObjects.forSourceString("test.Test", ""
+ "package test;\n"
+ "import android.app.Activity;\n"
+ "import butterknife.OnFocusChange;\n"
+ "public class Test extends Activity {\n"
+ " @OnFocusChange(1) void doStuff() {}\n"
+ "}"
);
JavaFileObject bindingSource = JavaFileObjects.forSourceString("test/Test_ViewBinding", ""
+ "package test;\n"
+ "import android.support.annotation.CallSuper;\n"
+ "import android.support.annotation.UiThread;\n"
+ "import android.view.View;\n"
+ "import butterknife.Unbinder;\n"
+ "import butterknife.internal.Utils;\n"
+ "import java.lang.IllegalStateException;\n"
+ "import java.lang.Override;\n"
+ "public class Test_ViewBinding<T extends Test> implements Unbinder {\n"
+ " protected T target;\n"
+ " private View view1;\n"
+ " @UiThread\n"
+ " public Test_ViewBinding(final T target, View source) {\n"
+ " this.target = target;\n"
+ " View view;\n"
+ " view = Utils.findRequiredView(source, 1, \"method 'doStuff'\");\n"
+ " view1 = view;\n"
+ " view.setOnFocusChangeListener(new View.OnFocusChangeListener() {\n"
+ " @Override\n"
+ " public void onFocusChange(View p0, boolean p1) {\n"
+ " target.doStuff();\n"
+ " }\n"
+ " });\n"
+ " }\n"
+ " @Override\n"
+ " @CallSuper\n"
+ " public void unbind() {\n"
+ " if (this.target == null) throw new IllegalStateException(\"Bindings already cleared.\");\n"
+ " view1.setOnFocusChangeListener(null);\n"
+ " view1 = null;\n"
+ " this.target = null;\n"
+ " }\n"
+ "}"
);
assertAbout(javaSource()).that(source)
.withCompilerOptions("-Xlint:-processing")
.processedWith(new ButterKnifeProcessor())
.compilesWithoutWarnings()
.and()
.generatesSources(bindingSource);
}
}
|
qingsong-xu/butterknife
|
butterknife-compiler/src/test/java/butterknife/OnFocusChangeTest.java
|
Java
|
apache-2.0
| 2,500 |
package com.vijaysharma.ehyo.core;
import java.io.File;
import java.util.Map.Entry;
import com.google.common.collect.ImmutableMap;
import com.vijaysharma.ehyo.api.logging.Output;
import com.vijaysharma.ehyo.api.logging.TextOutput;
import com.vijaysharma.ehyo.core.utils.EFileUtil;
public class BinaryFileChangeManager implements ChangeManager<PluginActions> {
static class BinaryFileChangeManagerFactory {
public BinaryFileChangeManager create() {
return new BinaryFileChangeManager();
}
}
private final ImmutableMap.Builder<File, File> changes;
private final TextOutput out;
private BinaryFileChangeManager() {
this.changes = ImmutableMap.builder();
out = Output.out;
}
@Override
public void apply(PluginActions actions) {
changes.putAll(actions.getBinaryFiles());
}
@Override
public void commit(boolean dryrun) {
for ( Entry<File, File> file : changes.build().entrySet() ) {
File from = file.getKey();
File to = file.getValue();
if (dryrun) {
out.println("Copying from: [" + from + "] to: [" + to + "]");
}
else {
out.println("Creating " + to);
EFileUtil.copyFile(from, to);
}
}
}
}
|
vijaysharm/ehyo-android
|
src/main/java/com/vijaysharma/ehyo/core/BinaryFileChangeManager.java
|
Java
|
apache-2.0
| 1,154 |
# Tremella damaecornis Möller SPECIES
#### Status
SYNONYM
#### According to
Index Fungorum
#### Published in
null
#### Original name
Tremella damaecornis Möller
### Remarks
null
|
mdoering/backbone
|
life/Fungi/Basidiomycota/Tremellomycetes/Tremellales/Tremellaceae/Holtermannia/Holtermannia damicornis/ Syn. Tremella damaecornis/README.md
|
Markdown
|
apache-2.0
| 184 |
/*! ******************************************************************************
*
* Pentaho Data Integration
*
* Copyright (C) 2002-2013 by Pentaho : http://www.pentaho.com
*
*******************************************************************************
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
******************************************************************************/
package org.pentaho.di.trans.steps.xmlinputsax;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.pentaho.di.core.Const;
import org.pentaho.di.core.exception.KettleValueException;
import org.pentaho.di.core.logging.LogChannelInterface;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
/**
* Parse XML document using SAX and retreive fields
*
* @author Youssef
* @since 22-may-2006
*/
public class XMLInputSaxFieldRetriever extends DefaultHandler {
List<XMLInputSaxField> fields;
int[] position = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 };
// list of elements to the root element
private List<XMLInputSaxFieldPosition> pathToRootElement = new ArrayList<XMLInputSaxFieldPosition>();
// list of elements to the root element
private List<XMLInputSaxFieldPosition> _pathToRootElement = new ArrayList<XMLInputSaxFieldPosition>();
// count the deep to the current element in pathToStartElement
private int counter = 0;
// count the deep to the current element in xml file
private int _counter = -1;
// true when the root element is reached
private boolean rootFound = false;
// source xml file name
private String sourceFile;
private XMLInputSaxMeta meta;
private LogChannelInterface log;
// private String tempVal;
public XMLInputSaxFieldRetriever( LogChannelInterface log, String sourceFile, XMLInputSaxMeta meta ) {
this.log = log;
for ( int i = 0; i < meta.getInputPosition().length; i++ ) {
this.pathToRootElement.add( meta.getInputPosition()[i] );
}
this.meta = meta;
this.sourceFile = sourceFile;
fields = new ArrayList<XMLInputSaxField>();
}
public List<XMLInputSaxField> getFields() {
parseDocument();
return this.fields;
}
private void parseDocument() {
// get a factory
SAXParserFactory spf = SAXParserFactory.newInstance();
try {
// get a new instance of parser
SAXParser sp = spf.newSAXParser();
// parse the file and also register this class for call backs
sp.parse( sourceFile, this );
} catch ( SAXException se ) {
log.logError( Const.getStackTracker( se ) );
} catch ( ParserConfigurationException pce ) {
log.logError( Const.getStackTracker( pce ) );
} catch ( IOException ie ) {
log.logError( Const.getStackTracker( ie ) );
}
}
private void counterUp() {
if ( counter == pathToRootElement.size() - 1 ) {
rootFound = true;
counter++;
} else {
counter++;
}
}
private boolean comparePaths( int count ) {
for ( int i = 0; i <= count; i++ ) {
if ( !pathToRootElement.get( i ).equals( pathToRootElement.get( i ) ) ) {
return false;
}
}
return true;
}
private void counterDown() {
if ( ( counter - 1 == _counter ) && comparePaths( _counter ) ) {
_pathToRootElement.remove( _counter );
counter--;
_counter--;
rootFound = false;
} else {
_pathToRootElement.remove( _counter );
_counter--;
}
}
private String naming( XMLInputSaxFieldPosition[] path ) {
String ret = "";
for ( int i = pathToRootElement.size(); i < path.length; i++ ) {
String name;
if ( path[i].getType() == XMLInputSaxFieldPosition.XML_ELEMENT_ATT ) {
name = path[i].getAttributeValue();
} else {
name = path[i].getName() + path[i].getElementNr();
}
if ( i > pathToRootElement.size() ) {
ret += "_" + name;
} else {
ret += name;
}
}
return ret;
}
// Event Handlers
public void startElement( String uri, String localName, String qName, Attributes attributes )
throws SAXException {
// set the _counter level
position[_counter + 1] += 1;
_counter++;
try {
if ( !rootFound ) {
XMLInputSaxFieldPosition el = null;
try {
el = pathToRootElement.get( counter );
} catch ( IndexOutOfBoundsException e ) {
throw new SAXException( e );
}
if ( ( counter == _counter ) && qName.equalsIgnoreCase( el.getName() ) ) {
if ( el.getType() == XMLInputSaxFieldPosition.XML_ELEMENT_ATT ) {
String att1 = attributes.getValue( el.getAttribute() ); // must throw exception
String att2 = el.getAttributeValue();
if ( att1.equals( att2 ) ) {
_pathToRootElement.add( new XMLInputSaxFieldPosition( qName, el.getAttribute(), el
.getAttributeValue() ) ); // to
// test
// with
// clone
if ( counter == pathToRootElement.size() - 1 ) {
for ( int i = 0; i < attributes.getLength(); i++ ) {
XMLInputSaxFieldPosition tempP =
new XMLInputSaxFieldPosition(
attributes.getQName( i ), XMLInputSaxFieldPosition.XML_ATTRIBUTE, i + 1 );
_pathToRootElement.add( tempP );
XMLInputSaxFieldPosition[] path = new XMLInputSaxFieldPosition[_pathToRootElement.size()];
_pathToRootElement.toArray( path );
_pathToRootElement.remove( _pathToRootElement.size() - 1 );
XMLInputSaxField tempF = new XMLInputSaxField( tempP.getName(), path );
if ( !fields.contains( tempF ) ) {
fields.add( tempF );
}
}
}
counterUp();
} else {
_pathToRootElement.add( new XMLInputSaxFieldPosition(
qName, XMLInputSaxFieldPosition.XML_ELEMENT_POS, position[_counter] + 1 ) );
}
} else {
_pathToRootElement.add( new XMLInputSaxFieldPosition(
qName, XMLInputSaxFieldPosition.XML_ELEMENT_POS, position[_counter] + 1 ) );
counterUp();
}
} else {
_pathToRootElement.add( new XMLInputSaxFieldPosition(
qName, XMLInputSaxFieldPosition.XML_ELEMENT_POS, position[_counter] + 1 ) );
}
} else {
XMLInputSaxField temp = null;
if ( attributes.getValue( meta.getDefiningAttribute( qName ) ) == null ) {
_pathToRootElement.add( new XMLInputSaxFieldPosition(
qName, XMLInputSaxFieldPosition.XML_ELEMENT_POS, position[_counter] + 1 ) );
XMLInputSaxFieldPosition[] path = new XMLInputSaxFieldPosition[_pathToRootElement.size()];
_pathToRootElement.toArray( path );
temp = new XMLInputSaxField( naming( path ), path );
} else {
String attribute = meta.getDefiningAttribute( qName );
_pathToRootElement
.add( new XMLInputSaxFieldPosition( qName, attribute, attributes.getValue( attribute ) ) );
XMLInputSaxFieldPosition[] path = new XMLInputSaxFieldPosition[_pathToRootElement.size()];
_pathToRootElement.toArray( path );
temp = new XMLInputSaxField( naming( path ), path );
}
if ( !fields.contains( temp ) ) {
fields.add( temp );
}
}
} catch ( KettleValueException e ) {
log.logError( Const.getStackTracker( e ) );
throw new SAXException( _counter
+ "," + counter + _pathToRootElement.get( _pathToRootElement.size() - 1 ).toString(), e );
}
}
public void characters( char[] ch, int start, int length ) throws SAXException {
// tempVal = new String(ch,start,length);
}
public void endElement( String uri, String localName, String qName ) throws SAXException {
position[_counter + 1] = -1;
counterDown();
}
/*
* public static void main(String[] args){ XMLvInputFieldPosition[] path=new XMLvInputFieldPosition[3]; try {
* path[0]=new XMLvInputFieldPosition("Ep=raml"); path[1]=new XMLvInputFieldPosition("Ep=cmData"); path[2]=new
* XMLvInputFieldPosition("Ea=managedObject/class:BTS"); } catch (KettleValueException e) { // TODO Auto-generated
* catch block LogWriter.getInstance().logError(toString(), Const.getStackTracker(e)); } //System.out.println(new
* xmlElement("hello","hello","hello").equals(new xmlElement("hello","hello","hello"))); XMLvSaxFieldRetreiver spe =
* new XMLvSaxFieldRetreiver("D:\\NOKIA\\Project\\Ressources\\CASA-1.XML",path,"name"); ArrayList l=spe.getFields();
* System.out.println(l.size()); for(int i=0;i<l.size();i++){
* System.out.println(((XMLvInputField)l.get(i)).getFieldPositionsCode(3)); } }
*/
}
|
rfellows/pentaho-kettle
|
engine/src/org/pentaho/di/trans/steps/xmlinputsax/XMLInputSaxFieldRetriever.java
|
Java
|
apache-2.0
| 9,673 |
""" Cisco_IOS_XR_manageability_perfmgmt_oper
This module contains a collection of YANG definitions
for Cisco IOS\-XR manageability\-perfmgmt package operational data.
This module contains definitions
for the following management objects\:
perf\-mgmt\: Performance Management agent operational data
Copyright (c) 2013\-2016 by Cisco Systems, Inc.
All rights reserved.
"""
import re
import collections
from enum import Enum
from ydk.types import Empty, YList, YLeafList, DELETE, Decimal64, FixedBitsDict
from ydk.errors import YPYError, YPYModelError
class PerfMgmt(object):
"""
Performance Management agent operational data
.. attribute:: monitor
Data from monitor (one history period) requests
**type**\: :py:class:`Monitor <ydk.models.cisco_ios_xr.Cisco_IOS_XR_manageability_perfmgmt_oper.PerfMgmt.Monitor>`
.. attribute:: periodic
Data from periodic requests
**type**\: :py:class:`Periodic <ydk.models.cisco_ios_xr.Cisco_IOS_XR_manageability_perfmgmt_oper.PerfMgmt.Periodic>`
"""
_prefix = 'manageability-perfmgmt-oper'
_revision = '2015-11-09'
def __init__(self):
self.monitor = PerfMgmt.Monitor()
self.monitor.parent = self
self.periodic = PerfMgmt.Periodic()
self.periodic.parent = self
class Periodic(object):
"""
Data from periodic requests
.. attribute:: bgp
Collected BGP data
**type**\: :py:class:`Bgp <ydk.models.cisco_ios_xr.Cisco_IOS_XR_manageability_perfmgmt_oper.PerfMgmt.Periodic.Bgp>`
.. attribute:: interface
Collected Interface data
**type**\: :py:class:`Interface <ydk.models.cisco_ios_xr.Cisco_IOS_XR_manageability_perfmgmt_oper.PerfMgmt.Periodic.Interface>`
.. attribute:: mpls
Collected MPLS data
**type**\: :py:class:`Mpls <ydk.models.cisco_ios_xr.Cisco_IOS_XR_manageability_perfmgmt_oper.PerfMgmt.Periodic.Mpls>`
.. attribute:: nodes
Nodes for which data is collected
**type**\: :py:class:`Nodes <ydk.models.cisco_ios_xr.Cisco_IOS_XR_manageability_perfmgmt_oper.PerfMgmt.Periodic.Nodes>`
.. attribute:: ospf
Collected OSPF data
**type**\: :py:class:`Ospf <ydk.models.cisco_ios_xr.Cisco_IOS_XR_manageability_perfmgmt_oper.PerfMgmt.Periodic.Ospf>`
"""
_prefix = 'manageability-perfmgmt-oper'
_revision = '2015-11-09'
def __init__(self):
self.parent = None
self.bgp = PerfMgmt.Periodic.Bgp()
self.bgp.parent = self
self.interface = PerfMgmt.Periodic.Interface()
self.interface.parent = self
self.mpls = PerfMgmt.Periodic.Mpls()
self.mpls.parent = self
self.nodes = PerfMgmt.Periodic.Nodes()
self.nodes.parent = self
self.ospf = PerfMgmt.Periodic.Ospf()
self.ospf.parent = self
class Ospf(object):
"""
Collected OSPF data
.. attribute:: ospfv2_protocol_instances
OSPF v2 instances for which protocol statistics are collected
**type**\: :py:class:`Ospfv2ProtocolInstances <ydk.models.cisco_ios_xr.Cisco_IOS_XR_manageability_perfmgmt_oper.PerfMgmt.Periodic.Ospf.Ospfv2ProtocolInstances>`
.. attribute:: ospfv3_protocol_instances
OSPF v3 instances for which protocol statistics are collected
**type**\: :py:class:`Ospfv3ProtocolInstances <ydk.models.cisco_ios_xr.Cisco_IOS_XR_manageability_perfmgmt_oper.PerfMgmt.Periodic.Ospf.Ospfv3ProtocolInstances>`
"""
_prefix = 'manageability-perfmgmt-oper'
_revision = '2015-11-09'
def __init__(self):
self.parent = None
self.ospfv2_protocol_instances = PerfMgmt.Periodic.Ospf.Ospfv2ProtocolInstances()
self.ospfv2_protocol_instances.parent = self
self.ospfv3_protocol_instances = PerfMgmt.Periodic.Ospf.Ospfv3ProtocolInstances()
self.ospfv3_protocol_instances.parent = self
class Ospfv2ProtocolInstances(object):
"""
OSPF v2 instances for which protocol statistics
are collected
.. attribute:: ospfv2_protocol_instance
Protocol samples for a particular OSPF v2 instance
**type**\: list of :py:class:`Ospfv2ProtocolInstance <ydk.models.cisco_ios_xr.Cisco_IOS_XR_manageability_perfmgmt_oper.PerfMgmt.Periodic.Ospf.Ospfv2ProtocolInstances.Ospfv2ProtocolInstance>`
"""
_prefix = 'manageability-perfmgmt-oper'
_revision = '2015-11-09'
def __init__(self):
self.parent = None
self.ospfv2_protocol_instance = YList()
self.ospfv2_protocol_instance.parent = self
self.ospfv2_protocol_instance.name = 'ospfv2_protocol_instance'
class Ospfv2ProtocolInstance(object):
"""
Protocol samples for a particular OSPF v2
instance
.. attribute:: instance_name <key>
OSPF Instance Name
**type**\: str
**pattern:** [\\w\\\-\\.\:,\_@#%$\\+=\\\|;]+
.. attribute:: samples
Sample Table for an OSPV v2 instance
**type**\: :py:class:`Samples <ydk.models.cisco_ios_xr.Cisco_IOS_XR_manageability_perfmgmt_oper.PerfMgmt.Periodic.Ospf.Ospfv2ProtocolInstances.Ospfv2ProtocolInstance.Samples>`
"""
_prefix = 'manageability-perfmgmt-oper'
_revision = '2015-11-09'
def __init__(self):
self.parent = None
self.instance_name = None
self.samples = PerfMgmt.Periodic.Ospf.Ospfv2ProtocolInstances.Ospfv2ProtocolInstance.Samples()
self.samples.parent = self
class Samples(object):
"""
Sample Table for an OSPV v2 instance
.. attribute:: sample
Generic Counters sample
**type**\: list of :py:class:`Sample <ydk.models.cisco_ios_xr.Cisco_IOS_XR_manageability_perfmgmt_oper.PerfMgmt.Periodic.Ospf.Ospfv2ProtocolInstances.Ospfv2ProtocolInstance.Samples.Sample>`
"""
_prefix = 'manageability-perfmgmt-oper'
_revision = '2015-11-09'
def __init__(self):
self.parent = None
self.sample = YList()
self.sample.parent = self
self.sample.name = 'sample'
class Sample(object):
"""
Generic Counters sample
.. attribute:: sample_id <key>
Sample ID
**type**\: int
**range:** \-2147483648..2147483647
.. attribute:: checksum_errors
Number of packets received with checksum errors
**type**\: int
**range:** 0..4294967295
.. attribute:: input_db_ds
Number of DBD packets received
**type**\: int
**range:** 0..4294967295
.. attribute:: input_db_ds_lsa
Number of LSA received in DBD packets
**type**\: int
**range:** 0..4294967295
.. attribute:: input_hello_packets
Number of Hello packets received
**type**\: int
**range:** 0..4294967295
.. attribute:: input_ls_requests
Number of LS Requests received
**type**\: int
**range:** 0..4294967295
.. attribute:: input_ls_requests_lsa
Number of LSA received in LS Requests
**type**\: int
**range:** 0..4294967295
.. attribute:: input_lsa_acks
Number of LSA Acknowledgements received
**type**\: int
**range:** 0..4294967295
.. attribute:: input_lsa_acks_lsa
Number of LSA received in LSA Acknowledgements
**type**\: int
**range:** 0..4294967295
.. attribute:: input_lsa_updates
Number of LSA Updates received
**type**\: int
**range:** 0..4294967295
.. attribute:: input_lsa_updates_lsa
Number of LSA received in LSA Updates
**type**\: int
**range:** 0..4294967295
.. attribute:: input_packets
Total number of packets received
**type**\: int
**range:** 0..4294967295
.. attribute:: output_db_ds
Number of DBD packets sent
**type**\: int
**range:** 0..4294967295
.. attribute:: output_db_ds_lsa
Number of LSA sent in DBD packets
**type**\: int
**range:** 0..4294967295
.. attribute:: output_hello_packets
Number of Hello packets sent
**type**\: int
**range:** 0..4294967295
.. attribute:: output_ls_requests
Number of LS Requests sent
**type**\: int
**range:** 0..4294967295
.. attribute:: output_ls_requests_lsa
Number of LSA sent in LS Requests
**type**\: int
**range:** 0..4294967295
.. attribute:: output_lsa_acks
Number of LSA Acknowledgements sent
**type**\: int
**range:** 0..4294967295
.. attribute:: output_lsa_acks_lsa
Number of LSA sent in LSA Acknowledgements
**type**\: int
**range:** 0..4294967295
.. attribute:: output_lsa_updates
Number of LSA Updates sent
**type**\: int
**range:** 0..4294967295
.. attribute:: output_lsa_updates_lsa
Number of LSA sent in LSA Updates
**type**\: int
**range:** 0..4294967295
.. attribute:: output_packets
Total number of packets sent
**type**\: int
**range:** 0..4294967295
.. attribute:: time_stamp
Timestamp of sample in seconds drom UCT
**type**\: int
**range:** 0..18446744073709551615
**units**\: second
"""
_prefix = 'manageability-perfmgmt-oper'
_revision = '2015-11-09'
def __init__(self):
self.parent = None
self.sample_id = None
self.checksum_errors = None
self.input_db_ds = None
self.input_db_ds_lsa = None
self.input_hello_packets = None
self.input_ls_requests = None
self.input_ls_requests_lsa = None
self.input_lsa_acks = None
self.input_lsa_acks_lsa = None
self.input_lsa_updates = None
self.input_lsa_updates_lsa = None
self.input_packets = None
self.output_db_ds = None
self.output_db_ds_lsa = None
self.output_hello_packets = None
self.output_ls_requests = None
self.output_ls_requests_lsa = None
self.output_lsa_acks = None
self.output_lsa_acks_lsa = None
self.output_lsa_updates = None
self.output_lsa_updates_lsa = None
self.output_packets = None
self.time_stamp = None
@property
def _common_path(self):
if self.parent is None:
raise YPYModelError('parent is not set . Cannot derive path.')
if self.sample_id is None:
raise YPYModelError('Key property sample_id is None')
return self.parent._common_path +'/Cisco-IOS-XR-manageability-perfmgmt-oper:sample[Cisco-IOS-XR-manageability-perfmgmt-oper:sample-id = ' + str(self.sample_id) + ']'
def is_config(self):
''' Returns True if this instance represents config data else returns False '''
return False
def _has_data(self):
if self.sample_id is not None:
return True
if self.checksum_errors is not None:
return True
if self.input_db_ds is not None:
return True
if self.input_db_ds_lsa is not None:
return True
if self.input_hello_packets is not None:
return True
if self.input_ls_requests is not None:
return True
if self.input_ls_requests_lsa is not None:
return True
if self.input_lsa_acks is not None:
return True
if self.input_lsa_acks_lsa is not None:
return True
if self.input_lsa_updates is not None:
return True
if self.input_lsa_updates_lsa is not None:
return True
if self.input_packets is not None:
return True
if self.output_db_ds is not None:
return True
if self.output_db_ds_lsa is not None:
return True
if self.output_hello_packets is not None:
return True
if self.output_ls_requests is not None:
return True
if self.output_ls_requests_lsa is not None:
return True
if self.output_lsa_acks is not None:
return True
if self.output_lsa_acks_lsa is not None:
return True
if self.output_lsa_updates is not None:
return True
if self.output_lsa_updates_lsa is not None:
return True
if self.output_packets is not None:
return True
if self.time_stamp is not None:
return True
return False
@staticmethod
def _meta_info():
from ydk.models.cisco_ios_xr._meta import _Cisco_IOS_XR_manageability_perfmgmt_oper as meta
return meta._meta_table['PerfMgmt.Periodic.Ospf.Ospfv2ProtocolInstances.Ospfv2ProtocolInstance.Samples.Sample']['meta_info']
@property
def _common_path(self):
if self.parent is None:
raise YPYModelError('parent is not set . Cannot derive path.')
return self.parent._common_path +'/Cisco-IOS-XR-manageability-perfmgmt-oper:samples'
def is_config(self):
''' Returns True if this instance represents config data else returns False '''
return False
def _has_data(self):
if self.sample is not None:
for child_ref in self.sample:
if child_ref._has_data():
return True
return False
@staticmethod
def _meta_info():
from ydk.models.cisco_ios_xr._meta import _Cisco_IOS_XR_manageability_perfmgmt_oper as meta
return meta._meta_table['PerfMgmt.Periodic.Ospf.Ospfv2ProtocolInstances.Ospfv2ProtocolInstance.Samples']['meta_info']
@property
def _common_path(self):
if self.instance_name is None:
raise YPYModelError('Key property instance_name is None')
return '/Cisco-IOS-XR-manageability-perfmgmt-oper:perf-mgmt/Cisco-IOS-XR-manageability-perfmgmt-oper:periodic/Cisco-IOS-XR-manageability-perfmgmt-oper:ospf/Cisco-IOS-XR-manageability-perfmgmt-oper:ospfv2-protocol-instances/Cisco-IOS-XR-manageability-perfmgmt-oper:ospfv2-protocol-instance[Cisco-IOS-XR-manageability-perfmgmt-oper:instance-name = ' + str(self.instance_name) + ']'
def is_config(self):
''' Returns True if this instance represents config data else returns False '''
return False
def _has_data(self):
if self.instance_name is not None:
return True
if self.samples is not None and self.samples._has_data():
return True
return False
@staticmethod
def _meta_info():
from ydk.models.cisco_ios_xr._meta import _Cisco_IOS_XR_manageability_perfmgmt_oper as meta
return meta._meta_table['PerfMgmt.Periodic.Ospf.Ospfv2ProtocolInstances.Ospfv2ProtocolInstance']['meta_info']
@property
def _common_path(self):
return '/Cisco-IOS-XR-manageability-perfmgmt-oper:perf-mgmt/Cisco-IOS-XR-manageability-perfmgmt-oper:periodic/Cisco-IOS-XR-manageability-perfmgmt-oper:ospf/Cisco-IOS-XR-manageability-perfmgmt-oper:ospfv2-protocol-instances'
def is_config(self):
''' Returns True if this instance represents config data else returns False '''
return False
def _has_data(self):
if self.ospfv2_protocol_instance is not None:
for child_ref in self.ospfv2_protocol_instance:
if child_ref._has_data():
return True
return False
@staticmethod
def _meta_info():
from ydk.models.cisco_ios_xr._meta import _Cisco_IOS_XR_manageability_perfmgmt_oper as meta
return meta._meta_table['PerfMgmt.Periodic.Ospf.Ospfv2ProtocolInstances']['meta_info']
class Ospfv3ProtocolInstances(object):
"""
OSPF v3 instances for which protocol statistics
are collected
.. attribute:: ospfv3_protocol_instance
Protocol samples for a particular OSPF v3 instance
**type**\: list of :py:class:`Ospfv3ProtocolInstance <ydk.models.cisco_ios_xr.Cisco_IOS_XR_manageability_perfmgmt_oper.PerfMgmt.Periodic.Ospf.Ospfv3ProtocolInstances.Ospfv3ProtocolInstance>`
"""
_prefix = 'manageability-perfmgmt-oper'
_revision = '2015-11-09'
def __init__(self):
self.parent = None
self.ospfv3_protocol_instance = YList()
self.ospfv3_protocol_instance.parent = self
self.ospfv3_protocol_instance.name = 'ospfv3_protocol_instance'
class Ospfv3ProtocolInstance(object):
"""
Protocol samples for a particular OSPF v3
instance
.. attribute:: instance_name <key>
OSPF Instance Name
**type**\: str
**pattern:** [\\w\\\-\\.\:,\_@#%$\\+=\\\|;]+
.. attribute:: samples
Sample Table for an OSPV v3 instance
**type**\: :py:class:`Samples <ydk.models.cisco_ios_xr.Cisco_IOS_XR_manageability_perfmgmt_oper.PerfMgmt.Periodic.Ospf.Ospfv3ProtocolInstances.Ospfv3ProtocolInstance.Samples>`
"""
_prefix = 'manageability-perfmgmt-oper'
_revision = '2015-11-09'
def __init__(self):
self.parent = None
self.instance_name = None
self.samples = PerfMgmt.Periodic.Ospf.Ospfv3ProtocolInstances.Ospfv3ProtocolInstance.Samples()
self.samples.parent = self
class Samples(object):
"""
Sample Table for an OSPV v3 instance
.. attribute:: sample
Generic Counters sample
**type**\: list of :py:class:`Sample <ydk.models.cisco_ios_xr.Cisco_IOS_XR_manageability_perfmgmt_oper.PerfMgmt.Periodic.Ospf.Ospfv3ProtocolInstances.Ospfv3ProtocolInstance.Samples.Sample>`
"""
_prefix = 'manageability-perfmgmt-oper'
_revision = '2015-11-09'
def __init__(self):
self.parent = None
self.sample = YList()
self.sample.parent = self
self.sample.name = 'sample'
class Sample(object):
"""
Generic Counters sample
.. attribute:: sample_id <key>
Sample ID
**type**\: int
**range:** \-2147483648..2147483647
.. attribute:: input_db_ds
Number of DBD packets received
**type**\: int
**range:** 0..4294967295
.. attribute:: input_db_ds_lsa
Number of LSA received in DBD packets
**type**\: int
**range:** 0..4294967295
.. attribute:: input_hello_packets
Number of Hello packets received
**type**\: int
**range:** 0..4294967295
.. attribute:: input_ls_requests
Number of LS Requests received
**type**\: int
**range:** 0..4294967295
.. attribute:: input_ls_requests_lsa
Number of LSA received in LS Requests
**type**\: int
**range:** 0..4294967295
.. attribute:: input_lsa_acks
Number of LSA Acknowledgements received
**type**\: int
**range:** 0..4294967295
.. attribute:: input_lsa_acks_lsa
Number of LSA received in LSA Acknowledgements
**type**\: int
**range:** 0..4294967295
.. attribute:: input_lsa_updates
Number of LSA Updates received
**type**\: int
**range:** 0..4294967295
.. attribute:: input_lsa_updates_lsa
Number of LSA received in LSA Updates
**type**\: int
**range:** 0..4294967295
.. attribute:: input_packets
Total number of packets received
**type**\: int
**range:** 0..4294967295
.. attribute:: output_db_ds
Number of DBD packets sent
**type**\: int
**range:** 0..4294967295
.. attribute:: output_db_ds_lsa
Number of LSA sent in DBD packets
**type**\: int
**range:** 0..4294967295
.. attribute:: output_hello_packets
Number of Hello packets sent
**type**\: int
**range:** 0..4294967295
.. attribute:: output_ls_requests
Number of LS Requests sent
**type**\: int
**range:** 0..4294967295
.. attribute:: output_ls_requests_lsa
Number of LSA sent in LS Requests
**type**\: int
**range:** 0..4294967295
.. attribute:: output_lsa_acks
Number of LSA Acknowledgements sent
**type**\: int
**range:** 0..4294967295
.. attribute:: output_lsa_acks_lsa
Number of LSA sent in LSA Acknowledgements
**type**\: int
**range:** 0..4294967295
.. attribute:: output_lsa_updates
Number of LSA Updates sent
**type**\: int
**range:** 0..4294967295
.. attribute:: output_lsa_updates_lsa
Number of LSA sent in LSA Updates
**type**\: int
**range:** 0..4294967295
.. attribute:: output_packets
Total number of packets sent
**type**\: int
**range:** 0..4294967295
.. attribute:: time_stamp
Timestamp of sample in seconds drom UCT
**type**\: int
**range:** 0..18446744073709551615
**units**\: second
"""
_prefix = 'manageability-perfmgmt-oper'
_revision = '2015-11-09'
def __init__(self):
self.parent = None
self.sample_id = None
self.input_db_ds = None
self.input_db_ds_lsa = None
self.input_hello_packets = None
self.input_ls_requests = None
self.input_ls_requests_lsa = None
self.input_lsa_acks = None
self.input_lsa_acks_lsa = None
self.input_lsa_updates = None
self.input_lsa_updates_lsa = None
self.input_packets = None
self.output_db_ds = None
self.output_db_ds_lsa = None
self.output_hello_packets = None
self.output_ls_requests = None
self.output_ls_requests_lsa = None
self.output_lsa_acks = None
self.output_lsa_acks_lsa = None
self.output_lsa_updates = None
self.output_lsa_updates_lsa = None
self.output_packets = None
self.time_stamp = None
@property
def _common_path(self):
if self.parent is None:
raise YPYModelError('parent is not set . Cannot derive path.')
if self.sample_id is None:
raise YPYModelError('Key property sample_id is None')
return self.parent._common_path +'/Cisco-IOS-XR-manageability-perfmgmt-oper:sample[Cisco-IOS-XR-manageability-perfmgmt-oper:sample-id = ' + str(self.sample_id) + ']'
def is_config(self):
''' Returns True if this instance represents config data else returns False '''
return False
def _has_data(self):
if self.sample_id is not None:
return True
if self.input_db_ds is not None:
return True
if self.input_db_ds_lsa is not None:
return True
if self.input_hello_packets is not None:
return True
if self.input_ls_requests is not None:
return True
if self.input_ls_requests_lsa is not None:
return True
if self.input_lsa_acks is not None:
return True
if self.input_lsa_acks_lsa is not None:
return True
if self.input_lsa_updates is not None:
return True
if self.input_lsa_updates_lsa is not None:
return True
if self.input_packets is not None:
return True
if self.output_db_ds is not None:
return True
if self.output_db_ds_lsa is not None:
return True
if self.output_hello_packets is not None:
return True
if self.output_ls_requests is not None:
return True
if self.output_ls_requests_lsa is not None:
return True
if self.output_lsa_acks is not None:
return True
if self.output_lsa_acks_lsa is not None:
return True
if self.output_lsa_updates is not None:
return True
if self.output_lsa_updates_lsa is not None:
return True
if self.output_packets is not None:
return True
if self.time_stamp is not None:
return True
return False
@staticmethod
def _meta_info():
from ydk.models.cisco_ios_xr._meta import _Cisco_IOS_XR_manageability_perfmgmt_oper as meta
return meta._meta_table['PerfMgmt.Periodic.Ospf.Ospfv3ProtocolInstances.Ospfv3ProtocolInstance.Samples.Sample']['meta_info']
@property
def _common_path(self):
if self.parent is None:
raise YPYModelError('parent is not set . Cannot derive path.')
return self.parent._common_path +'/Cisco-IOS-XR-manageability-perfmgmt-oper:samples'
def is_config(self):
''' Returns True if this instance represents config data else returns False '''
return False
def _has_data(self):
if self.sample is not None:
for child_ref in self.sample:
if child_ref._has_data():
return True
return False
@staticmethod
def _meta_info():
from ydk.models.cisco_ios_xr._meta import _Cisco_IOS_XR_manageability_perfmgmt_oper as meta
return meta._meta_table['PerfMgmt.Periodic.Ospf.Ospfv3ProtocolInstances.Ospfv3ProtocolInstance.Samples']['meta_info']
@property
def _common_path(self):
if self.instance_name is None:
raise YPYModelError('Key property instance_name is None')
return '/Cisco-IOS-XR-manageability-perfmgmt-oper:perf-mgmt/Cisco-IOS-XR-manageability-perfmgmt-oper:periodic/Cisco-IOS-XR-manageability-perfmgmt-oper:ospf/Cisco-IOS-XR-manageability-perfmgmt-oper:ospfv3-protocol-instances/Cisco-IOS-XR-manageability-perfmgmt-oper:ospfv3-protocol-instance[Cisco-IOS-XR-manageability-perfmgmt-oper:instance-name = ' + str(self.instance_name) + ']'
def is_config(self):
''' Returns True if this instance represents config data else returns False '''
return False
def _has_data(self):
if self.instance_name is not None:
return True
if self.samples is not None and self.samples._has_data():
return True
return False
@staticmethod
def _meta_info():
from ydk.models.cisco_ios_xr._meta import _Cisco_IOS_XR_manageability_perfmgmt_oper as meta
return meta._meta_table['PerfMgmt.Periodic.Ospf.Ospfv3ProtocolInstances.Ospfv3ProtocolInstance']['meta_info']
@property
def _common_path(self):
return '/Cisco-IOS-XR-manageability-perfmgmt-oper:perf-mgmt/Cisco-IOS-XR-manageability-perfmgmt-oper:periodic/Cisco-IOS-XR-manageability-perfmgmt-oper:ospf/Cisco-IOS-XR-manageability-perfmgmt-oper:ospfv3-protocol-instances'
def is_config(self):
''' Returns True if this instance represents config data else returns False '''
return False
def _has_data(self):
if self.ospfv3_protocol_instance is not None:
for child_ref in self.ospfv3_protocol_instance:
if child_ref._has_data():
return True
return False
@staticmethod
def _meta_info():
from ydk.models.cisco_ios_xr._meta import _Cisco_IOS_XR_manageability_perfmgmt_oper as meta
return meta._meta_table['PerfMgmt.Periodic.Ospf.Ospfv3ProtocolInstances']['meta_info']
@property
def _common_path(self):
return '/Cisco-IOS-XR-manageability-perfmgmt-oper:perf-mgmt/Cisco-IOS-XR-manageability-perfmgmt-oper:periodic/Cisco-IOS-XR-manageability-perfmgmt-oper:ospf'
def is_config(self):
''' Returns True if this instance represents config data else returns False '''
return False
def _has_data(self):
if self.ospfv2_protocol_instances is not None and self.ospfv2_protocol_instances._has_data():
return True
if self.ospfv3_protocol_instances is not None and self.ospfv3_protocol_instances._has_data():
return True
return False
@staticmethod
def _meta_info():
from ydk.models.cisco_ios_xr._meta import _Cisco_IOS_XR_manageability_perfmgmt_oper as meta
return meta._meta_table['PerfMgmt.Periodic.Ospf']['meta_info']
class Mpls(object):
"""
Collected MPLS data
.. attribute:: ldp_neighbors
LDP neighbors for which statistics are collected
**type**\: :py:class:`LdpNeighbors <ydk.models.cisco_ios_xr.Cisco_IOS_XR_manageability_perfmgmt_oper.PerfMgmt.Periodic.Mpls.LdpNeighbors>`
"""
_prefix = 'manageability-perfmgmt-oper'
_revision = '2015-11-09'
def __init__(self):
self.parent = None
self.ldp_neighbors = PerfMgmt.Periodic.Mpls.LdpNeighbors()
self.ldp_neighbors.parent = self
class LdpNeighbors(object):
"""
LDP neighbors for which statistics are
collected
.. attribute:: ldp_neighbor
Samples for a particular LDP neighbor
**type**\: list of :py:class:`LdpNeighbor <ydk.models.cisco_ios_xr.Cisco_IOS_XR_manageability_perfmgmt_oper.PerfMgmt.Periodic.Mpls.LdpNeighbors.LdpNeighbor>`
"""
_prefix = 'manageability-perfmgmt-oper'
_revision = '2015-11-09'
def __init__(self):
self.parent = None
self.ldp_neighbor = YList()
self.ldp_neighbor.parent = self
self.ldp_neighbor.name = 'ldp_neighbor'
class LdpNeighbor(object):
"""
Samples for a particular LDP neighbor
.. attribute:: nbr <key>
Neighbor Address
**type**\: str
**pattern:** (([0\-9]\|[1\-9][0\-9]\|1[0\-9][0\-9]\|2[0\-4][0\-9]\|25[0\-5])\\.){3}([0\-9]\|[1\-9][0\-9]\|1[0\-9][0\-9]\|2[0\-4][0\-9]\|25[0\-5])(%[\\p{N}\\p{L}]+)?
.. attribute:: samples
Samples for a particular LDP neighbor
**type**\: :py:class:`Samples <ydk.models.cisco_ios_xr.Cisco_IOS_XR_manageability_perfmgmt_oper.PerfMgmt.Periodic.Mpls.LdpNeighbors.LdpNeighbor.Samples>`
"""
_prefix = 'manageability-perfmgmt-oper'
_revision = '2015-11-09'
def __init__(self):
self.parent = None
self.nbr = None
self.samples = PerfMgmt.Periodic.Mpls.LdpNeighbors.LdpNeighbor.Samples()
self.samples.parent = self
class Samples(object):
"""
Samples for a particular LDP neighbor
.. attribute:: sample
LDP neighbor statistics sample
**type**\: list of :py:class:`Sample <ydk.models.cisco_ios_xr.Cisco_IOS_XR_manageability_perfmgmt_oper.PerfMgmt.Periodic.Mpls.LdpNeighbors.LdpNeighbor.Samples.Sample>`
"""
_prefix = 'manageability-perfmgmt-oper'
_revision = '2015-11-09'
def __init__(self):
self.parent = None
self.sample = YList()
self.sample.parent = self
self.sample.name = 'sample'
class Sample(object):
"""
LDP neighbor statistics sample
.. attribute:: sample_id <key>
Sample ID
**type**\: int
**range:** \-2147483648..2147483647
.. attribute:: address_msgs_rcvd
Address messages received
**type**\: int
**range:** 0..65535
.. attribute:: address_msgs_sent
Address messages sent
**type**\: int
**range:** 0..65535
.. attribute:: address_withdraw_msgs_rcvd
Address withdraw messages received
**type**\: int
**range:** 0..65535
.. attribute:: address_withdraw_msgs_sent
Address withdraw messages sent
**type**\: int
**range:** 0..65535
.. attribute:: init_msgs_rcvd
Tnit messages received
**type**\: int
**range:** 0..65535
.. attribute:: init_msgs_sent
Init messages sent
**type**\: int
**range:** 0..65535
.. attribute:: keepalive_msgs_rcvd
Keepalive messages received
**type**\: int
**range:** 0..65535
.. attribute:: keepalive_msgs_sent
Keepalive messages sent
**type**\: int
**range:** 0..65535
.. attribute:: label_mapping_msgs_rcvd
Label mapping messages received
**type**\: int
**range:** 0..65535
.. attribute:: label_mapping_msgs_sent
Label mapping messages sent
**type**\: int
**range:** 0..65535
.. attribute:: label_release_msgs_rcvd
Label release messages received
**type**\: int
**range:** 0..65535
.. attribute:: label_release_msgs_sent
Label release messages sent
**type**\: int
**range:** 0..65535
.. attribute:: label_withdraw_msgs_rcvd
Label withdraw messages received
**type**\: int
**range:** 0..65535
.. attribute:: label_withdraw_msgs_sent
Label withdraw messages sent
**type**\: int
**range:** 0..65535
.. attribute:: notification_msgs_rcvd
Notification messages received
**type**\: int
**range:** 0..65535
.. attribute:: notification_msgs_sent
Notification messages sent
**type**\: int
**range:** 0..65535
.. attribute:: time_stamp
Timestamp of sample in seconds drom UCT
**type**\: int
**range:** 0..18446744073709551615
**units**\: second
.. attribute:: total_msgs_rcvd
Total messages received
**type**\: int
**range:** 0..65535
.. attribute:: total_msgs_sent
Total messages sent
**type**\: int
**range:** 0..65535
"""
_prefix = 'manageability-perfmgmt-oper'
_revision = '2015-11-09'
def __init__(self):
self.parent = None
self.sample_id = None
self.address_msgs_rcvd = None
self.address_msgs_sent = None
self.address_withdraw_msgs_rcvd = None
self.address_withdraw_msgs_sent = None
self.init_msgs_rcvd = None
self.init_msgs_sent = None
self.keepalive_msgs_rcvd = None
self.keepalive_msgs_sent = None
self.label_mapping_msgs_rcvd = None
self.label_mapping_msgs_sent = None
self.label_release_msgs_rcvd = None
self.label_release_msgs_sent = None
self.label_withdraw_msgs_rcvd = None
self.label_withdraw_msgs_sent = None
self.notification_msgs_rcvd = None
self.notification_msgs_sent = None
self.time_stamp = None
self.total_msgs_rcvd = None
self.total_msgs_sent = None
@property
def _common_path(self):
if self.parent is None:
raise YPYModelError('parent is not set . Cannot derive path.')
if self.sample_id is None:
raise YPYModelError('Key property sample_id is None')
return self.parent._common_path +'/Cisco-IOS-XR-manageability-perfmgmt-oper:sample[Cisco-IOS-XR-manageability-perfmgmt-oper:sample-id = ' + str(self.sample_id) + ']'
def is_config(self):
''' Returns True if this instance represents config data else returns False '''
return False
def _has_data(self):
if self.sample_id is not None:
return True
if self.address_msgs_rcvd is not None:
return True
if self.address_msgs_sent is not None:
return True
if self.address_withdraw_msgs_rcvd is not None:
return True
if self.address_withdraw_msgs_sent is not None:
return True
if self.init_msgs_rcvd is not None:
return True
if self.init_msgs_sent is not None:
return True
if self.keepalive_msgs_rcvd is not None:
return True
if self.keepalive_msgs_sent is not None:
return True
if self.label_mapping_msgs_rcvd is not None:
return True
if self.label_mapping_msgs_sent is not None:
return True
if self.label_release_msgs_rcvd is not None:
return True
if self.label_release_msgs_sent is not None:
return True
if self.label_withdraw_msgs_rcvd is not None:
return True
if self.label_withdraw_msgs_sent is not None:
return True
if self.notification_msgs_rcvd is not None:
return True
if self.notification_msgs_sent is not None:
return True
if self.time_stamp is not None:
return True
if self.total_msgs_rcvd is not None:
return True
if self.total_msgs_sent is not None:
return True
return False
@staticmethod
def _meta_info():
from ydk.models.cisco_ios_xr._meta import _Cisco_IOS_XR_manageability_perfmgmt_oper as meta
return meta._meta_table['PerfMgmt.Periodic.Mpls.LdpNeighbors.LdpNeighbor.Samples.Sample']['meta_info']
@property
def _common_path(self):
if self.parent is None:
raise YPYModelError('parent is not set . Cannot derive path.')
return self.parent._common_path +'/Cisco-IOS-XR-manageability-perfmgmt-oper:samples'
def is_config(self):
''' Returns True if this instance represents config data else returns False '''
return False
def _has_data(self):
if self.sample is not None:
for child_ref in self.sample:
if child_ref._has_data():
return True
return False
@staticmethod
def _meta_info():
from ydk.models.cisco_ios_xr._meta import _Cisco_IOS_XR_manageability_perfmgmt_oper as meta
return meta._meta_table['PerfMgmt.Periodic.Mpls.LdpNeighbors.LdpNeighbor.Samples']['meta_info']
@property
def _common_path(self):
if self.nbr is None:
raise YPYModelError('Key property nbr is None')
return '/Cisco-IOS-XR-manageability-perfmgmt-oper:perf-mgmt/Cisco-IOS-XR-manageability-perfmgmt-oper:periodic/Cisco-IOS-XR-manageability-perfmgmt-oper:mpls/Cisco-IOS-XR-manageability-perfmgmt-oper:ldp-neighbors/Cisco-IOS-XR-manageability-perfmgmt-oper:ldp-neighbor[Cisco-IOS-XR-manageability-perfmgmt-oper:nbr = ' + str(self.nbr) + ']'
def is_config(self):
''' Returns True if this instance represents config data else returns False '''
return False
def _has_data(self):
if self.nbr is not None:
return True
if self.samples is not None and self.samples._has_data():
return True
return False
@staticmethod
def _meta_info():
from ydk.models.cisco_ios_xr._meta import _Cisco_IOS_XR_manageability_perfmgmt_oper as meta
return meta._meta_table['PerfMgmt.Periodic.Mpls.LdpNeighbors.LdpNeighbor']['meta_info']
@property
def _common_path(self):
return '/Cisco-IOS-XR-manageability-perfmgmt-oper:perf-mgmt/Cisco-IOS-XR-manageability-perfmgmt-oper:periodic/Cisco-IOS-XR-manageability-perfmgmt-oper:mpls/Cisco-IOS-XR-manageability-perfmgmt-oper:ldp-neighbors'
def is_config(self):
''' Returns True if this instance represents config data else returns False '''
return False
def _has_data(self):
if self.ldp_neighbor is not None:
for child_ref in self.ldp_neighbor:
if child_ref._has_data():
return True
return False
@staticmethod
def _meta_info():
from ydk.models.cisco_ios_xr._meta import _Cisco_IOS_XR_manageability_perfmgmt_oper as meta
return meta._meta_table['PerfMgmt.Periodic.Mpls.LdpNeighbors']['meta_info']
@property
def _common_path(self):
return '/Cisco-IOS-XR-manageability-perfmgmt-oper:perf-mgmt/Cisco-IOS-XR-manageability-perfmgmt-oper:periodic/Cisco-IOS-XR-manageability-perfmgmt-oper:mpls'
def is_config(self):
''' Returns True if this instance represents config data else returns False '''
return False
def _has_data(self):
if self.ldp_neighbors is not None and self.ldp_neighbors._has_data():
return True
return False
@staticmethod
def _meta_info():
from ydk.models.cisco_ios_xr._meta import _Cisco_IOS_XR_manageability_perfmgmt_oper as meta
return meta._meta_table['PerfMgmt.Periodic.Mpls']['meta_info']
class Nodes(object):
"""
Nodes for which data is collected
.. attribute:: node
Node Instance
**type**\: list of :py:class:`Node <ydk.models.cisco_ios_xr.Cisco_IOS_XR_manageability_perfmgmt_oper.PerfMgmt.Periodic.Nodes.Node>`
"""
_prefix = 'manageability-perfmgmt-oper'
_revision = '2015-11-09'
def __init__(self):
self.parent = None
self.node = YList()
self.node.parent = self
self.node.name = 'node'
class Node(object):
"""
Node Instance
.. attribute:: node_id <key>
Node ID
**type**\: str
**pattern:** ([a\-zA\-Z0\-9\_]\*\\d+/){1,2}([a\-zA\-Z0\-9\_]\*\\d+)
.. attribute:: processes
Processes data
**type**\: :py:class:`Processes <ydk.models.cisco_ios_xr.Cisco_IOS_XR_manageability_perfmgmt_oper.PerfMgmt.Periodic.Nodes.Node.Processes>`
.. attribute:: sample_xr
Node CPU data
**type**\: :py:class:`SampleXr <ydk.models.cisco_ios_xr.Cisco_IOS_XR_manageability_perfmgmt_oper.PerfMgmt.Periodic.Nodes.Node.SampleXr>`
.. attribute:: samples
Node Memory data
**type**\: :py:class:`Samples <ydk.models.cisco_ios_xr.Cisco_IOS_XR_manageability_perfmgmt_oper.PerfMgmt.Periodic.Nodes.Node.Samples>`
"""
_prefix = 'manageability-perfmgmt-oper'
_revision = '2015-11-09'
def __init__(self):
self.parent = None
self.node_id = None
self.processes = PerfMgmt.Periodic.Nodes.Node.Processes()
self.processes.parent = self
self.sample_xr = PerfMgmt.Periodic.Nodes.Node.SampleXr()
self.sample_xr.parent = self
self.samples = PerfMgmt.Periodic.Nodes.Node.Samples()
self.samples.parent = self
class SampleXr(object):
"""
Node CPU data
.. attribute:: sample
Node CPU data sample
**type**\: list of :py:class:`Sample <ydk.models.cisco_ios_xr.Cisco_IOS_XR_manageability_perfmgmt_oper.PerfMgmt.Periodic.Nodes.Node.SampleXr.Sample>`
"""
_prefix = 'manageability-perfmgmt-oper'
_revision = '2015-11-09'
def __init__(self):
self.parent = None
self.sample = YList()
self.sample.parent = self
self.sample.name = 'sample'
class Sample(object):
"""
Node CPU data sample
.. attribute:: sample_id <key>
Sample ID
**type**\: int
**range:** \-2147483648..2147483647
.. attribute:: average_cpu_used
Average system %CPU utilization
**type**\: int
**range:** 0..4294967295
.. attribute:: no_processes
Number of processes in the system
**type**\: int
**range:** 0..4294967295
.. attribute:: time_stamp
Timestamp of sample in seconds drom UCT
**type**\: int
**range:** 0..18446744073709551615
**units**\: second
"""
_prefix = 'manageability-perfmgmt-oper'
_revision = '2015-11-09'
def __init__(self):
self.parent = None
self.sample_id = None
self.average_cpu_used = None
self.no_processes = None
self.time_stamp = None
@property
def _common_path(self):
if self.parent is None:
raise YPYModelError('parent is not set . Cannot derive path.')
if self.sample_id is None:
raise YPYModelError('Key property sample_id is None')
return self.parent._common_path +'/Cisco-IOS-XR-manageability-perfmgmt-oper:sample[Cisco-IOS-XR-manageability-perfmgmt-oper:sample-id = ' + str(self.sample_id) + ']'
def is_config(self):
''' Returns True if this instance represents config data else returns False '''
return False
def _has_data(self):
if self.sample_id is not None:
return True
if self.average_cpu_used is not None:
return True
if self.no_processes is not None:
return True
if self.time_stamp is not None:
return True
return False
@staticmethod
def _meta_info():
from ydk.models.cisco_ios_xr._meta import _Cisco_IOS_XR_manageability_perfmgmt_oper as meta
return meta._meta_table['PerfMgmt.Periodic.Nodes.Node.SampleXr.Sample']['meta_info']
@property
def _common_path(self):
if self.parent is None:
raise YPYModelError('parent is not set . Cannot derive path.')
return self.parent._common_path +'/Cisco-IOS-XR-manageability-perfmgmt-oper:sample-xr'
def is_config(self):
''' Returns True if this instance represents config data else returns False '''
return False
def _has_data(self):
if self.sample is not None:
for child_ref in self.sample:
if child_ref._has_data():
return True
return False
@staticmethod
def _meta_info():
from ydk.models.cisco_ios_xr._meta import _Cisco_IOS_XR_manageability_perfmgmt_oper as meta
return meta._meta_table['PerfMgmt.Periodic.Nodes.Node.SampleXr']['meta_info']
class Processes(object):
"""
Processes data
.. attribute:: process
Process data
**type**\: list of :py:class:`Process <ydk.models.cisco_ios_xr.Cisco_IOS_XR_manageability_perfmgmt_oper.PerfMgmt.Periodic.Nodes.Node.Processes.Process>`
"""
_prefix = 'manageability-perfmgmt-oper'
_revision = '2015-11-09'
def __init__(self):
self.parent = None
self.process = YList()
self.process.parent = self
self.process.name = 'process'
class Process(object):
"""
Process data
.. attribute:: process_id <key>
Process ID
**type**\: int
**range:** \-2147483648..2147483647
.. attribute:: samples
Process data
**type**\: :py:class:`Samples <ydk.models.cisco_ios_xr.Cisco_IOS_XR_manageability_perfmgmt_oper.PerfMgmt.Periodic.Nodes.Node.Processes.Process.Samples>`
"""
_prefix = 'manageability-perfmgmt-oper'
_revision = '2015-11-09'
def __init__(self):
self.parent = None
self.process_id = None
self.samples = PerfMgmt.Periodic.Nodes.Node.Processes.Process.Samples()
self.samples.parent = self
class Samples(object):
"""
Process data
.. attribute:: sample
Process data sample
**type**\: list of :py:class:`Sample <ydk.models.cisco_ios_xr.Cisco_IOS_XR_manageability_perfmgmt_oper.PerfMgmt.Periodic.Nodes.Node.Processes.Process.Samples.Sample>`
"""
_prefix = 'manageability-perfmgmt-oper'
_revision = '2015-11-09'
def __init__(self):
self.parent = None
self.sample = YList()
self.sample.parent = self
self.sample.name = 'sample'
class Sample(object):
"""
Process data sample
.. attribute:: sample_id <key>
Sample ID
**type**\: int
**range:** \-2147483648..2147483647
.. attribute:: average_cpu_used
Average %CPU utilization
**type**\: int
**range:** 0..4294967295
.. attribute:: no_threads
Number of threads
**type**\: int
**range:** 0..4294967295
.. attribute:: peak_memory
Max. dynamic memory (KBytes) used since startup time
**type**\: int
**range:** 0..4294967295
**units**\: kilobyte
.. attribute:: time_stamp
Timestamp of sample in seconds drom UCT
**type**\: int
**range:** 0..18446744073709551615
**units**\: second
"""
_prefix = 'manageability-perfmgmt-oper'
_revision = '2015-11-09'
def __init__(self):
self.parent = None
self.sample_id = None
self.average_cpu_used = None
self.no_threads = None
self.peak_memory = None
self.time_stamp = None
@property
def _common_path(self):
if self.parent is None:
raise YPYModelError('parent is not set . Cannot derive path.')
if self.sample_id is None:
raise YPYModelError('Key property sample_id is None')
return self.parent._common_path +'/Cisco-IOS-XR-manageability-perfmgmt-oper:sample[Cisco-IOS-XR-manageability-perfmgmt-oper:sample-id = ' + str(self.sample_id) + ']'
def is_config(self):
''' Returns True if this instance represents config data else returns False '''
return False
def _has_data(self):
if self.sample_id is not None:
return True
if self.average_cpu_used is not None:
return True
if self.no_threads is not None:
return True
if self.peak_memory is not None:
return True
if self.time_stamp is not None:
return True
return False
@staticmethod
def _meta_info():
from ydk.models.cisco_ios_xr._meta import _Cisco_IOS_XR_manageability_perfmgmt_oper as meta
return meta._meta_table['PerfMgmt.Periodic.Nodes.Node.Processes.Process.Samples.Sample']['meta_info']
@property
def _common_path(self):
if self.parent is None:
raise YPYModelError('parent is not set . Cannot derive path.')
return self.parent._common_path +'/Cisco-IOS-XR-manageability-perfmgmt-oper:samples'
def is_config(self):
''' Returns True if this instance represents config data else returns False '''
return False
def _has_data(self):
if self.sample is not None:
for child_ref in self.sample:
if child_ref._has_data():
return True
return False
@staticmethod
def _meta_info():
from ydk.models.cisco_ios_xr._meta import _Cisco_IOS_XR_manageability_perfmgmt_oper as meta
return meta._meta_table['PerfMgmt.Periodic.Nodes.Node.Processes.Process.Samples']['meta_info']
@property
def _common_path(self):
if self.parent is None:
raise YPYModelError('parent is not set . Cannot derive path.')
if self.process_id is None:
raise YPYModelError('Key property process_id is None')
return self.parent._common_path +'/Cisco-IOS-XR-manageability-perfmgmt-oper:process[Cisco-IOS-XR-manageability-perfmgmt-oper:process-id = ' + str(self.process_id) + ']'
def is_config(self):
''' Returns True if this instance represents config data else returns False '''
return False
def _has_data(self):
if self.process_id is not None:
return True
if self.samples is not None and self.samples._has_data():
return True
return False
@staticmethod
def _meta_info():
from ydk.models.cisco_ios_xr._meta import _Cisco_IOS_XR_manageability_perfmgmt_oper as meta
return meta._meta_table['PerfMgmt.Periodic.Nodes.Node.Processes.Process']['meta_info']
@property
def _common_path(self):
if self.parent is None:
raise YPYModelError('parent is not set . Cannot derive path.')
return self.parent._common_path +'/Cisco-IOS-XR-manageability-perfmgmt-oper:processes'
def is_config(self):
''' Returns True if this instance represents config data else returns False '''
return False
def _has_data(self):
if self.process is not None:
for child_ref in self.process:
if child_ref._has_data():
return True
return False
@staticmethod
def _meta_info():
from ydk.models.cisco_ios_xr._meta import _Cisco_IOS_XR_manageability_perfmgmt_oper as meta
return meta._meta_table['PerfMgmt.Periodic.Nodes.Node.Processes']['meta_info']
class Samples(object):
"""
Node Memory data
.. attribute:: sample
Node Memory data sample
**type**\: list of :py:class:`Sample <ydk.models.cisco_ios_xr.Cisco_IOS_XR_manageability_perfmgmt_oper.PerfMgmt.Periodic.Nodes.Node.Samples.Sample>`
"""
_prefix = 'manageability-perfmgmt-oper'
_revision = '2015-11-09'
def __init__(self):
self.parent = None
self.sample = YList()
self.sample.parent = self
self.sample.name = 'sample'
class Sample(object):
"""
Node Memory data sample
.. attribute:: sample_id <key>
Sample ID
**type**\: int
**range:** \-2147483648..2147483647
.. attribute:: curr_memory
Current application memory (Bytes) in use
**type**\: int
**range:** 0..4294967295
**units**\: byte
.. attribute:: peak_memory
Max. system memory (MBytes) used since bootup
**type**\: int
**range:** 0..4294967295
**units**\: megabyte
.. attribute:: time_stamp
Timestamp of sample in seconds drom UCT
**type**\: int
**range:** 0..18446744073709551615
**units**\: second
"""
_prefix = 'manageability-perfmgmt-oper'
_revision = '2015-11-09'
def __init__(self):
self.parent = None
self.sample_id = None
self.curr_memory = None
self.peak_memory = None
self.time_stamp = None
@property
def _common_path(self):
if self.parent is None:
raise YPYModelError('parent is not set . Cannot derive path.')
if self.sample_id is None:
raise YPYModelError('Key property sample_id is None')
return self.parent._common_path +'/Cisco-IOS-XR-manageability-perfmgmt-oper:sample[Cisco-IOS-XR-manageability-perfmgmt-oper:sample-id = ' + str(self.sample_id) + ']'
def is_config(self):
''' Returns True if this instance represents config data else returns False '''
return False
def _has_data(self):
if self.sample_id is not None:
return True
if self.curr_memory is not None:
return True
if self.peak_memory is not None:
return True
if self.time_stamp is not None:
return True
return False
@staticmethod
def _meta_info():
from ydk.models.cisco_ios_xr._meta import _Cisco_IOS_XR_manageability_perfmgmt_oper as meta
return meta._meta_table['PerfMgmt.Periodic.Nodes.Node.Samples.Sample']['meta_info']
@property
def _common_path(self):
if self.parent is None:
raise YPYModelError('parent is not set . Cannot derive path.')
return self.parent._common_path +'/Cisco-IOS-XR-manageability-perfmgmt-oper:samples'
def is_config(self):
''' Returns True if this instance represents config data else returns False '''
return False
def _has_data(self):
if self.sample is not None:
for child_ref in self.sample:
if child_ref._has_data():
return True
return False
@staticmethod
def _meta_info():
from ydk.models.cisco_ios_xr._meta import _Cisco_IOS_XR_manageability_perfmgmt_oper as meta
return meta._meta_table['PerfMgmt.Periodic.Nodes.Node.Samples']['meta_info']
@property
def _common_path(self):
if self.node_id is None:
raise YPYModelError('Key property node_id is None')
return '/Cisco-IOS-XR-manageability-perfmgmt-oper:perf-mgmt/Cisco-IOS-XR-manageability-perfmgmt-oper:periodic/Cisco-IOS-XR-manageability-perfmgmt-oper:nodes/Cisco-IOS-XR-manageability-perfmgmt-oper:node[Cisco-IOS-XR-manageability-perfmgmt-oper:node-id = ' + str(self.node_id) + ']'
def is_config(self):
''' Returns True if this instance represents config data else returns False '''
return False
def _has_data(self):
if self.node_id is not None:
return True
if self.processes is not None and self.processes._has_data():
return True
if self.sample_xr is not None and self.sample_xr._has_data():
return True
if self.samples is not None and self.samples._has_data():
return True
return False
@staticmethod
def _meta_info():
from ydk.models.cisco_ios_xr._meta import _Cisco_IOS_XR_manageability_perfmgmt_oper as meta
return meta._meta_table['PerfMgmt.Periodic.Nodes.Node']['meta_info']
@property
def _common_path(self):
return '/Cisco-IOS-XR-manageability-perfmgmt-oper:perf-mgmt/Cisco-IOS-XR-manageability-perfmgmt-oper:periodic/Cisco-IOS-XR-manageability-perfmgmt-oper:nodes'
def is_config(self):
''' Returns True if this instance represents config data else returns False '''
return False
def _has_data(self):
if self.node is not None:
for child_ref in self.node:
if child_ref._has_data():
return True
return False
@staticmethod
def _meta_info():
from ydk.models.cisco_ios_xr._meta import _Cisco_IOS_XR_manageability_perfmgmt_oper as meta
return meta._meta_table['PerfMgmt.Periodic.Nodes']['meta_info']
class Bgp(object):
"""
Collected BGP data
.. attribute:: bgp_neighbors
Neighbors for which statistics are collected
**type**\: :py:class:`BgpNeighbors <ydk.models.cisco_ios_xr.Cisco_IOS_XR_manageability_perfmgmt_oper.PerfMgmt.Periodic.Bgp.BgpNeighbors>`
"""
_prefix = 'manageability-perfmgmt-oper'
_revision = '2015-11-09'
def __init__(self):
self.parent = None
self.bgp_neighbors = PerfMgmt.Periodic.Bgp.BgpNeighbors()
self.bgp_neighbors.parent = self
class BgpNeighbors(object):
"""
Neighbors for which statistics are collected
.. attribute:: bgp_neighbor
Samples for particular neighbor
**type**\: list of :py:class:`BgpNeighbor <ydk.models.cisco_ios_xr.Cisco_IOS_XR_manageability_perfmgmt_oper.PerfMgmt.Periodic.Bgp.BgpNeighbors.BgpNeighbor>`
"""
_prefix = 'manageability-perfmgmt-oper'
_revision = '2015-11-09'
def __init__(self):
self.parent = None
self.bgp_neighbor = YList()
self.bgp_neighbor.parent = self
self.bgp_neighbor.name = 'bgp_neighbor'
class BgpNeighbor(object):
"""
Samples for particular neighbor
.. attribute:: ip_address <key>
BGP Neighbor Identifier
**type**\: str
**pattern:** (([0\-9]\|[1\-9][0\-9]\|1[0\-9][0\-9]\|2[0\-4][0\-9]\|25[0\-5])\\.){3}([0\-9]\|[1\-9][0\-9]\|1[0\-9][0\-9]\|2[0\-4][0\-9]\|25[0\-5])(%[\\p{N}\\p{L}]+)?
.. attribute:: samples
Sample Table for a BGP neighbor
**type**\: :py:class:`Samples <ydk.models.cisco_ios_xr.Cisco_IOS_XR_manageability_perfmgmt_oper.PerfMgmt.Periodic.Bgp.BgpNeighbors.BgpNeighbor.Samples>`
"""
_prefix = 'manageability-perfmgmt-oper'
_revision = '2015-11-09'
def __init__(self):
self.parent = None
self.ip_address = None
self.samples = PerfMgmt.Periodic.Bgp.BgpNeighbors.BgpNeighbor.Samples()
self.samples.parent = self
class Samples(object):
"""
Sample Table for a BGP neighbor
.. attribute:: sample
Neighbor statistics sample
**type**\: list of :py:class:`Sample <ydk.models.cisco_ios_xr.Cisco_IOS_XR_manageability_perfmgmt_oper.PerfMgmt.Periodic.Bgp.BgpNeighbors.BgpNeighbor.Samples.Sample>`
"""
_prefix = 'manageability-perfmgmt-oper'
_revision = '2015-11-09'
def __init__(self):
self.parent = None
self.sample = YList()
self.sample.parent = self
self.sample.name = 'sample'
class Sample(object):
"""
Neighbor statistics sample
.. attribute:: sample_id <key>
Sample ID
**type**\: int
**range:** \-2147483648..2147483647
.. attribute:: conn_dropped
Number of times connection was dropped
**type**\: int
**range:** 0..4294967295
.. attribute:: conn_established
Number of times the connection was established
**type**\: int
**range:** 0..4294967295
.. attribute:: errors_received
Number of error notifications received on the connection
**type**\: int
**range:** 0..4294967295
.. attribute:: errors_sent
Number of error notifications sent on the connection
**type**\: int
**range:** 0..4294967295
.. attribute:: input_messages
Number of messages received
**type**\: int
**range:** 0..4294967295
.. attribute:: input_update_messages
Number of update messages received
**type**\: int
**range:** 0..4294967295
.. attribute:: output_messages
Number of messages sent
**type**\: int
**range:** 0..4294967295
.. attribute:: output_update_messages
Number of update messages sent
**type**\: int
**range:** 0..4294967295
.. attribute:: time_stamp
Timestamp of sample in seconds drom UCT
**type**\: int
**range:** 0..18446744073709551615
**units**\: second
"""
_prefix = 'manageability-perfmgmt-oper'
_revision = '2015-11-09'
def __init__(self):
self.parent = None
self.sample_id = None
self.conn_dropped = None
self.conn_established = None
self.errors_received = None
self.errors_sent = None
self.input_messages = None
self.input_update_messages = None
self.output_messages = None
self.output_update_messages = None
self.time_stamp = None
@property
def _common_path(self):
if self.parent is None:
raise YPYModelError('parent is not set . Cannot derive path.')
if self.sample_id is None:
raise YPYModelError('Key property sample_id is None')
return self.parent._common_path +'/Cisco-IOS-XR-manageability-perfmgmt-oper:sample[Cisco-IOS-XR-manageability-perfmgmt-oper:sample-id = ' + str(self.sample_id) + ']'
def is_config(self):
''' Returns True if this instance represents config data else returns False '''
return False
def _has_data(self):
if self.sample_id is not None:
return True
if self.conn_dropped is not None:
return True
if self.conn_established is not None:
return True
if self.errors_received is not None:
return True
if self.errors_sent is not None:
return True
if self.input_messages is not None:
return True
if self.input_update_messages is not None:
return True
if self.output_messages is not None:
return True
if self.output_update_messages is not None:
return True
if self.time_stamp is not None:
return True
return False
@staticmethod
def _meta_info():
from ydk.models.cisco_ios_xr._meta import _Cisco_IOS_XR_manageability_perfmgmt_oper as meta
return meta._meta_table['PerfMgmt.Periodic.Bgp.BgpNeighbors.BgpNeighbor.Samples.Sample']['meta_info']
@property
def _common_path(self):
if self.parent is None:
raise YPYModelError('parent is not set . Cannot derive path.')
return self.parent._common_path +'/Cisco-IOS-XR-manageability-perfmgmt-oper:samples'
def is_config(self):
''' Returns True if this instance represents config data else returns False '''
return False
def _has_data(self):
if self.sample is not None:
for child_ref in self.sample:
if child_ref._has_data():
return True
return False
@staticmethod
def _meta_info():
from ydk.models.cisco_ios_xr._meta import _Cisco_IOS_XR_manageability_perfmgmt_oper as meta
return meta._meta_table['PerfMgmt.Periodic.Bgp.BgpNeighbors.BgpNeighbor.Samples']['meta_info']
@property
def _common_path(self):
if self.ip_address is None:
raise YPYModelError('Key property ip_address is None')
return '/Cisco-IOS-XR-manageability-perfmgmt-oper:perf-mgmt/Cisco-IOS-XR-manageability-perfmgmt-oper:periodic/Cisco-IOS-XR-manageability-perfmgmt-oper:bgp/Cisco-IOS-XR-manageability-perfmgmt-oper:bgp-neighbors/Cisco-IOS-XR-manageability-perfmgmt-oper:bgp-neighbor[Cisco-IOS-XR-manageability-perfmgmt-oper:ip-address = ' + str(self.ip_address) + ']'
def is_config(self):
''' Returns True if this instance represents config data else returns False '''
return False
def _has_data(self):
if self.ip_address is not None:
return True
if self.samples is not None and self.samples._has_data():
return True
return False
@staticmethod
def _meta_info():
from ydk.models.cisco_ios_xr._meta import _Cisco_IOS_XR_manageability_perfmgmt_oper as meta
return meta._meta_table['PerfMgmt.Periodic.Bgp.BgpNeighbors.BgpNeighbor']['meta_info']
@property
def _common_path(self):
return '/Cisco-IOS-XR-manageability-perfmgmt-oper:perf-mgmt/Cisco-IOS-XR-manageability-perfmgmt-oper:periodic/Cisco-IOS-XR-manageability-perfmgmt-oper:bgp/Cisco-IOS-XR-manageability-perfmgmt-oper:bgp-neighbors'
def is_config(self):
''' Returns True if this instance represents config data else returns False '''
return False
def _has_data(self):
if self.bgp_neighbor is not None:
for child_ref in self.bgp_neighbor:
if child_ref._has_data():
return True
return False
@staticmethod
def _meta_info():
from ydk.models.cisco_ios_xr._meta import _Cisco_IOS_XR_manageability_perfmgmt_oper as meta
return meta._meta_table['PerfMgmt.Periodic.Bgp.BgpNeighbors']['meta_info']
@property
def _common_path(self):
return '/Cisco-IOS-XR-manageability-perfmgmt-oper:perf-mgmt/Cisco-IOS-XR-manageability-perfmgmt-oper:periodic/Cisco-IOS-XR-manageability-perfmgmt-oper:bgp'
def is_config(self):
''' Returns True if this instance represents config data else returns False '''
return False
def _has_data(self):
if self.bgp_neighbors is not None and self.bgp_neighbors._has_data():
return True
return False
@staticmethod
def _meta_info():
from ydk.models.cisco_ios_xr._meta import _Cisco_IOS_XR_manageability_perfmgmt_oper as meta
return meta._meta_table['PerfMgmt.Periodic.Bgp']['meta_info']
class Interface(object):
"""
Collected Interface data
.. attribute:: basic_counter_interfaces
Interfaces for which Basic Counters are collected
**type**\: :py:class:`BasicCounterInterfaces <ydk.models.cisco_ios_xr.Cisco_IOS_XR_manageability_perfmgmt_oper.PerfMgmt.Periodic.Interface.BasicCounterInterfaces>`
.. attribute:: data_rate_interfaces
Interfaces for which Data Rates are collected
**type**\: :py:class:`DataRateInterfaces <ydk.models.cisco_ios_xr.Cisco_IOS_XR_manageability_perfmgmt_oper.PerfMgmt.Periodic.Interface.DataRateInterfaces>`
.. attribute:: generic_counter_interfaces
Interfaces for which Generic Counters are collected
**type**\: :py:class:`GenericCounterInterfaces <ydk.models.cisco_ios_xr.Cisco_IOS_XR_manageability_perfmgmt_oper.PerfMgmt.Periodic.Interface.GenericCounterInterfaces>`
"""
_prefix = 'manageability-perfmgmt-oper'
_revision = '2015-11-09'
def __init__(self):
self.parent = None
self.basic_counter_interfaces = PerfMgmt.Periodic.Interface.BasicCounterInterfaces()
self.basic_counter_interfaces.parent = self
self.data_rate_interfaces = PerfMgmt.Periodic.Interface.DataRateInterfaces()
self.data_rate_interfaces.parent = self
self.generic_counter_interfaces = PerfMgmt.Periodic.Interface.GenericCounterInterfaces()
self.generic_counter_interfaces.parent = self
class GenericCounterInterfaces(object):
"""
Interfaces for which Generic Counters are
collected
.. attribute:: generic_counter_interface
Samples for a particular interface
**type**\: list of :py:class:`GenericCounterInterface <ydk.models.cisco_ios_xr.Cisco_IOS_XR_manageability_perfmgmt_oper.PerfMgmt.Periodic.Interface.GenericCounterInterfaces.GenericCounterInterface>`
"""
_prefix = 'manageability-perfmgmt-oper'
_revision = '2015-11-09'
def __init__(self):
self.parent = None
self.generic_counter_interface = YList()
self.generic_counter_interface.parent = self
self.generic_counter_interface.name = 'generic_counter_interface'
class GenericCounterInterface(object):
"""
Samples for a particular interface
.. attribute:: interface_name <key>
Interface Name
**type**\: str
**pattern:** (([a\-zA\-Z0\-9\_]\*\\d+/){3,4}\\d+)\|(([a\-zA\-Z0\-9\_]\*\\d+/){3,4}\\d+\\.\\d+)\|(([a\-zA\-Z0\-9\_]\*\\d+/){2}([a\-zA\-Z0\-9\_]\*\\d+))\|(([a\-zA\-Z0\-9\_]\*\\d+/){2}([a\-zA\-Z0\-9\_]+))\|([a\-zA\-Z0\-9\_\-]\*\\d+)\|([a\-zA\-Z0\-9\_\-]\*\\d+\\.\\d+)\|(mpls)\|(dwdm)
.. attribute:: samples
Generic Counter samples for an interface
**type**\: :py:class:`Samples <ydk.models.cisco_ios_xr.Cisco_IOS_XR_manageability_perfmgmt_oper.PerfMgmt.Periodic.Interface.GenericCounterInterfaces.GenericCounterInterface.Samples>`
"""
_prefix = 'manageability-perfmgmt-oper'
_revision = '2015-11-09'
def __init__(self):
self.parent = None
self.interface_name = None
self.samples = PerfMgmt.Periodic.Interface.GenericCounterInterfaces.GenericCounterInterface.Samples()
self.samples.parent = self
class Samples(object):
"""
Generic Counter samples for an interface
.. attribute:: sample
Generic Counters sample
**type**\: list of :py:class:`Sample <ydk.models.cisco_ios_xr.Cisco_IOS_XR_manageability_perfmgmt_oper.PerfMgmt.Periodic.Interface.GenericCounterInterfaces.GenericCounterInterface.Samples.Sample>`
"""
_prefix = 'manageability-perfmgmt-oper'
_revision = '2015-11-09'
def __init__(self):
self.parent = None
self.sample = YList()
self.sample.parent = self
self.sample.name = 'sample'
class Sample(object):
"""
Generic Counters sample
.. attribute:: sample_id <key>
Sample ID
**type**\: int
**range:** \-2147483648..2147483647
.. attribute:: in_broadcast_pkts
Broadcast packets received
**type**\: int
**range:** 0..18446744073709551615
.. attribute:: in_multicast_pkts
Multicast packets received
**type**\: int
**range:** 0..18446744073709551615
.. attribute:: in_octets
Bytes received
**type**\: int
**range:** 0..18446744073709551615
**units**\: byte
.. attribute:: in_packets
Packets received
**type**\: int
**range:** 0..18446744073709551615
.. attribute:: in_ucast_pkts
Unicast packets received
**type**\: int
**range:** 0..18446744073709551615
.. attribute:: input_crc
Inbound packets discarded with incorrect CRC
**type**\: int
**range:** 0..4294967295
.. attribute:: input_frame
Inbound framing errors
**type**\: int
**range:** 0..4294967295
.. attribute:: input_overrun
Input overruns
**type**\: int
**range:** 0..4294967295
.. attribute:: input_queue_drops
Input queue drops
**type**\: int
**range:** 0..4294967295
.. attribute:: input_total_drops
Inbound correct packets discarded
**type**\: int
**range:** 0..4294967295
.. attribute:: input_total_errors
Inbound incorrect packets discarded
**type**\: int
**range:** 0..4294967295
.. attribute:: input_unknown_proto
Inbound packets discarded with unknown proto
**type**\: int
**range:** 0..4294967295
.. attribute:: out_broadcast_pkts
Broadcast packets sent
**type**\: int
**range:** 0..18446744073709551615
.. attribute:: out_multicast_pkts
Multicast packets sent
**type**\: int
**range:** 0..18446744073709551615
.. attribute:: out_octets
Bytes sent
**type**\: int
**range:** 0..18446744073709551615
**units**\: byte
.. attribute:: out_packets
Packets sent
**type**\: int
**range:** 0..18446744073709551615
.. attribute:: out_ucast_pkts
Unicast packets sent
**type**\: int
**range:** 0..18446744073709551615
.. attribute:: output_total_drops
Outbound correct packets discarded
**type**\: int
**range:** 0..4294967295
.. attribute:: output_total_errors
Outbound incorrect packets discarded
**type**\: int
**range:** 0..4294967295
.. attribute:: output_underrun
Output underruns
**type**\: int
**range:** 0..4294967295
.. attribute:: time_stamp
Timestamp of sample in seconds drom UCT
**type**\: int
**range:** 0..18446744073709551615
**units**\: second
"""
_prefix = 'manageability-perfmgmt-oper'
_revision = '2015-11-09'
def __init__(self):
self.parent = None
self.sample_id = None
self.in_broadcast_pkts = None
self.in_multicast_pkts = None
self.in_octets = None
self.in_packets = None
self.in_ucast_pkts = None
self.input_crc = None
self.input_frame = None
self.input_overrun = None
self.input_queue_drops = None
self.input_total_drops = None
self.input_total_errors = None
self.input_unknown_proto = None
self.out_broadcast_pkts = None
self.out_multicast_pkts = None
self.out_octets = None
self.out_packets = None
self.out_ucast_pkts = None
self.output_total_drops = None
self.output_total_errors = None
self.output_underrun = None
self.time_stamp = None
@property
def _common_path(self):
if self.parent is None:
raise YPYModelError('parent is not set . Cannot derive path.')
if self.sample_id is None:
raise YPYModelError('Key property sample_id is None')
return self.parent._common_path +'/Cisco-IOS-XR-manageability-perfmgmt-oper:sample[Cisco-IOS-XR-manageability-perfmgmt-oper:sample-id = ' + str(self.sample_id) + ']'
def is_config(self):
''' Returns True if this instance represents config data else returns False '''
return False
def _has_data(self):
if self.sample_id is not None:
return True
if self.in_broadcast_pkts is not None:
return True
if self.in_multicast_pkts is not None:
return True
if self.in_octets is not None:
return True
if self.in_packets is not None:
return True
if self.in_ucast_pkts is not None:
return True
if self.input_crc is not None:
return True
if self.input_frame is not None:
return True
if self.input_overrun is not None:
return True
if self.input_queue_drops is not None:
return True
if self.input_total_drops is not None:
return True
if self.input_total_errors is not None:
return True
if self.input_unknown_proto is not None:
return True
if self.out_broadcast_pkts is not None:
return True
if self.out_multicast_pkts is not None:
return True
if self.out_octets is not None:
return True
if self.out_packets is not None:
return True
if self.out_ucast_pkts is not None:
return True
if self.output_total_drops is not None:
return True
if self.output_total_errors is not None:
return True
if self.output_underrun is not None:
return True
if self.time_stamp is not None:
return True
return False
@staticmethod
def _meta_info():
from ydk.models.cisco_ios_xr._meta import _Cisco_IOS_XR_manageability_perfmgmt_oper as meta
return meta._meta_table['PerfMgmt.Periodic.Interface.GenericCounterInterfaces.GenericCounterInterface.Samples.Sample']['meta_info']
@property
def _common_path(self):
if self.parent is None:
raise YPYModelError('parent is not set . Cannot derive path.')
return self.parent._common_path +'/Cisco-IOS-XR-manageability-perfmgmt-oper:samples'
def is_config(self):
''' Returns True if this instance represents config data else returns False '''
return False
def _has_data(self):
if self.sample is not None:
for child_ref in self.sample:
if child_ref._has_data():
return True
return False
@staticmethod
def _meta_info():
from ydk.models.cisco_ios_xr._meta import _Cisco_IOS_XR_manageability_perfmgmt_oper as meta
return meta._meta_table['PerfMgmt.Periodic.Interface.GenericCounterInterfaces.GenericCounterInterface.Samples']['meta_info']
@property
def _common_path(self):
if self.interface_name is None:
raise YPYModelError('Key property interface_name is None')
return '/Cisco-IOS-XR-manageability-perfmgmt-oper:perf-mgmt/Cisco-IOS-XR-manageability-perfmgmt-oper:periodic/Cisco-IOS-XR-manageability-perfmgmt-oper:interface/Cisco-IOS-XR-manageability-perfmgmt-oper:generic-counter-interfaces/Cisco-IOS-XR-manageability-perfmgmt-oper:generic-counter-interface[Cisco-IOS-XR-manageability-perfmgmt-oper:interface-name = ' + str(self.interface_name) + ']'
def is_config(self):
''' Returns True if this instance represents config data else returns False '''
return False
def _has_data(self):
if self.interface_name is not None:
return True
if self.samples is not None and self.samples._has_data():
return True
return False
@staticmethod
def _meta_info():
from ydk.models.cisco_ios_xr._meta import _Cisco_IOS_XR_manageability_perfmgmt_oper as meta
return meta._meta_table['PerfMgmt.Periodic.Interface.GenericCounterInterfaces.GenericCounterInterface']['meta_info']
@property
def _common_path(self):
return '/Cisco-IOS-XR-manageability-perfmgmt-oper:perf-mgmt/Cisco-IOS-XR-manageability-perfmgmt-oper:periodic/Cisco-IOS-XR-manageability-perfmgmt-oper:interface/Cisco-IOS-XR-manageability-perfmgmt-oper:generic-counter-interfaces'
def is_config(self):
''' Returns True if this instance represents config data else returns False '''
return False
def _has_data(self):
if self.generic_counter_interface is not None:
for child_ref in self.generic_counter_interface:
if child_ref._has_data():
return True
return False
@staticmethod
def _meta_info():
from ydk.models.cisco_ios_xr._meta import _Cisco_IOS_XR_manageability_perfmgmt_oper as meta
return meta._meta_table['PerfMgmt.Periodic.Interface.GenericCounterInterfaces']['meta_info']
class BasicCounterInterfaces(object):
"""
Interfaces for which Basic Counters are
collected
.. attribute:: basic_counter_interface
Samples for a particular interface
**type**\: list of :py:class:`BasicCounterInterface <ydk.models.cisco_ios_xr.Cisco_IOS_XR_manageability_perfmgmt_oper.PerfMgmt.Periodic.Interface.BasicCounterInterfaces.BasicCounterInterface>`
"""
_prefix = 'manageability-perfmgmt-oper'
_revision = '2015-11-09'
def __init__(self):
self.parent = None
self.basic_counter_interface = YList()
self.basic_counter_interface.parent = self
self.basic_counter_interface.name = 'basic_counter_interface'
class BasicCounterInterface(object):
"""
Samples for a particular interface
.. attribute:: interface_name <key>
Interface Name
**type**\: str
**pattern:** (([a\-zA\-Z0\-9\_]\*\\d+/){3,4}\\d+)\|(([a\-zA\-Z0\-9\_]\*\\d+/){3,4}\\d+\\.\\d+)\|(([a\-zA\-Z0\-9\_]\*\\d+/){2}([a\-zA\-Z0\-9\_]\*\\d+))\|(([a\-zA\-Z0\-9\_]\*\\d+/){2}([a\-zA\-Z0\-9\_]+))\|([a\-zA\-Z0\-9\_\-]\*\\d+)\|([a\-zA\-Z0\-9\_\-]\*\\d+\\.\\d+)\|(mpls)\|(dwdm)
.. attribute:: samples
Basic Counter samples for an interface
**type**\: :py:class:`Samples <ydk.models.cisco_ios_xr.Cisco_IOS_XR_manageability_perfmgmt_oper.PerfMgmt.Periodic.Interface.BasicCounterInterfaces.BasicCounterInterface.Samples>`
"""
_prefix = 'manageability-perfmgmt-oper'
_revision = '2015-11-09'
def __init__(self):
self.parent = None
self.interface_name = None
self.samples = PerfMgmt.Periodic.Interface.BasicCounterInterfaces.BasicCounterInterface.Samples()
self.samples.parent = self
class Samples(object):
"""
Basic Counter samples for an interface
.. attribute:: sample
Basic Counters sample
**type**\: list of :py:class:`Sample <ydk.models.cisco_ios_xr.Cisco_IOS_XR_manageability_perfmgmt_oper.PerfMgmt.Periodic.Interface.BasicCounterInterfaces.BasicCounterInterface.Samples.Sample>`
"""
_prefix = 'manageability-perfmgmt-oper'
_revision = '2015-11-09'
def __init__(self):
self.parent = None
self.sample = YList()
self.sample.parent = self
self.sample.name = 'sample'
class Sample(object):
"""
Basic Counters sample
.. attribute:: sample_id <key>
Sample ID
**type**\: int
**range:** \-2147483648..2147483647
.. attribute:: in_octets
Bytes received
**type**\: int
**range:** 0..18446744073709551615
**units**\: byte
.. attribute:: in_packets
Packets received
**type**\: int
**range:** 0..18446744073709551615
.. attribute:: input_queue_drops
Input queue drops
**type**\: int
**range:** 0..18446744073709551615
.. attribute:: input_total_drops
Inbound correct packets discarded
**type**\: int
**range:** 0..18446744073709551615
.. attribute:: input_total_errors
Inbound incorrect packets discarded
**type**\: int
**range:** 0..18446744073709551615
.. attribute:: out_octets
Bytes sent
**type**\: int
**range:** 0..18446744073709551615
**units**\: byte
.. attribute:: out_packets
Packets sent
**type**\: int
**range:** 0..18446744073709551615
.. attribute:: output_queue_drops
Output queue drops
**type**\: int
**range:** 0..18446744073709551615
.. attribute:: output_total_drops
Outbound correct packets discarded
**type**\: int
**range:** 0..18446744073709551615
.. attribute:: output_total_errors
Outbound incorrect packets discarded
**type**\: int
**range:** 0..18446744073709551615
.. attribute:: time_stamp
Timestamp of sample in seconds from UCT
**type**\: int
**range:** 0..18446744073709551615
**units**\: second
"""
_prefix = 'manageability-perfmgmt-oper'
_revision = '2015-11-09'
def __init__(self):
self.parent = None
self.sample_id = None
self.in_octets = None
self.in_packets = None
self.input_queue_drops = None
self.input_total_drops = None
self.input_total_errors = None
self.out_octets = None
self.out_packets = None
self.output_queue_drops = None
self.output_total_drops = None
self.output_total_errors = None
self.time_stamp = None
@property
def _common_path(self):
if self.parent is None:
raise YPYModelError('parent is not set . Cannot derive path.')
if self.sample_id is None:
raise YPYModelError('Key property sample_id is None')
return self.parent._common_path +'/Cisco-IOS-XR-manageability-perfmgmt-oper:sample[Cisco-IOS-XR-manageability-perfmgmt-oper:sample-id = ' + str(self.sample_id) + ']'
def is_config(self):
''' Returns True if this instance represents config data else returns False '''
return False
def _has_data(self):
if self.sample_id is not None:
return True
if self.in_octets is not None:
return True
if self.in_packets is not None:
return True
if self.input_queue_drops is not None:
return True
if self.input_total_drops is not None:
return True
if self.input_total_errors is not None:
return True
if self.out_octets is not None:
return True
if self.out_packets is not None:
return True
if self.output_queue_drops is not None:
return True
if self.output_total_drops is not None:
return True
if self.output_total_errors is not None:
return True
if self.time_stamp is not None:
return True
return False
@staticmethod
def _meta_info():
from ydk.models.cisco_ios_xr._meta import _Cisco_IOS_XR_manageability_perfmgmt_oper as meta
return meta._meta_table['PerfMgmt.Periodic.Interface.BasicCounterInterfaces.BasicCounterInterface.Samples.Sample']['meta_info']
@property
def _common_path(self):
if self.parent is None:
raise YPYModelError('parent is not set . Cannot derive path.')
return self.parent._common_path +'/Cisco-IOS-XR-manageability-perfmgmt-oper:samples'
def is_config(self):
''' Returns True if this instance represents config data else returns False '''
return False
def _has_data(self):
if self.sample is not None:
for child_ref in self.sample:
if child_ref._has_data():
return True
return False
@staticmethod
def _meta_info():
from ydk.models.cisco_ios_xr._meta import _Cisco_IOS_XR_manageability_perfmgmt_oper as meta
return meta._meta_table['PerfMgmt.Periodic.Interface.BasicCounterInterfaces.BasicCounterInterface.Samples']['meta_info']
@property
def _common_path(self):
if self.interface_name is None:
raise YPYModelError('Key property interface_name is None')
return '/Cisco-IOS-XR-manageability-perfmgmt-oper:perf-mgmt/Cisco-IOS-XR-manageability-perfmgmt-oper:periodic/Cisco-IOS-XR-manageability-perfmgmt-oper:interface/Cisco-IOS-XR-manageability-perfmgmt-oper:basic-counter-interfaces/Cisco-IOS-XR-manageability-perfmgmt-oper:basic-counter-interface[Cisco-IOS-XR-manageability-perfmgmt-oper:interface-name = ' + str(self.interface_name) + ']'
def is_config(self):
''' Returns True if this instance represents config data else returns False '''
return False
def _has_data(self):
if self.interface_name is not None:
return True
if self.samples is not None and self.samples._has_data():
return True
return False
@staticmethod
def _meta_info():
from ydk.models.cisco_ios_xr._meta import _Cisco_IOS_XR_manageability_perfmgmt_oper as meta
return meta._meta_table['PerfMgmt.Periodic.Interface.BasicCounterInterfaces.BasicCounterInterface']['meta_info']
@property
def _common_path(self):
return '/Cisco-IOS-XR-manageability-perfmgmt-oper:perf-mgmt/Cisco-IOS-XR-manageability-perfmgmt-oper:periodic/Cisco-IOS-XR-manageability-perfmgmt-oper:interface/Cisco-IOS-XR-manageability-perfmgmt-oper:basic-counter-interfaces'
def is_config(self):
''' Returns True if this instance represents config data else returns False '''
return False
def _has_data(self):
if self.basic_counter_interface is not None:
for child_ref in self.basic_counter_interface:
if child_ref._has_data():
return True
return False
@staticmethod
def _meta_info():
from ydk.models.cisco_ios_xr._meta import _Cisco_IOS_XR_manageability_perfmgmt_oper as meta
return meta._meta_table['PerfMgmt.Periodic.Interface.BasicCounterInterfaces']['meta_info']
class DataRateInterfaces(object):
"""
Interfaces for which Data Rates are collected
.. attribute:: data_rate_interface
Samples for a particular interface
**type**\: list of :py:class:`DataRateInterface <ydk.models.cisco_ios_xr.Cisco_IOS_XR_manageability_perfmgmt_oper.PerfMgmt.Periodic.Interface.DataRateInterfaces.DataRateInterface>`
"""
_prefix = 'manageability-perfmgmt-oper'
_revision = '2015-11-09'
def __init__(self):
self.parent = None
self.data_rate_interface = YList()
self.data_rate_interface.parent = self
self.data_rate_interface.name = 'data_rate_interface'
class DataRateInterface(object):
"""
Samples for a particular interface
.. attribute:: interface_name <key>
Interface Name
**type**\: str
**pattern:** (([a\-zA\-Z0\-9\_]\*\\d+/){3,4}\\d+)\|(([a\-zA\-Z0\-9\_]\*\\d+/){3,4}\\d+\\.\\d+)\|(([a\-zA\-Z0\-9\_]\*\\d+/){2}([a\-zA\-Z0\-9\_]\*\\d+))\|(([a\-zA\-Z0\-9\_]\*\\d+/){2}([a\-zA\-Z0\-9\_]+))\|([a\-zA\-Z0\-9\_\-]\*\\d+)\|([a\-zA\-Z0\-9\_\-]\*\\d+\\.\\d+)\|(mpls)\|(dwdm)
.. attribute:: samples
Data Rate samples for an interface
**type**\: :py:class:`Samples <ydk.models.cisco_ios_xr.Cisco_IOS_XR_manageability_perfmgmt_oper.PerfMgmt.Periodic.Interface.DataRateInterfaces.DataRateInterface.Samples>`
"""
_prefix = 'manageability-perfmgmt-oper'
_revision = '2015-11-09'
def __init__(self):
self.parent = None
self.interface_name = None
self.samples = PerfMgmt.Periodic.Interface.DataRateInterfaces.DataRateInterface.Samples()
self.samples.parent = self
class Samples(object):
"""
Data Rate samples for an interface
.. attribute:: sample
Data Rates sample
**type**\: list of :py:class:`Sample <ydk.models.cisco_ios_xr.Cisco_IOS_XR_manageability_perfmgmt_oper.PerfMgmt.Periodic.Interface.DataRateInterfaces.DataRateInterface.Samples.Sample>`
"""
_prefix = 'manageability-perfmgmt-oper'
_revision = '2015-11-09'
def __init__(self):
self.parent = None
self.sample = YList()
self.sample.parent = self
self.sample.name = 'sample'
class Sample(object):
"""
Data Rates sample
.. attribute:: sample_id <key>
Sample ID
**type**\: int
**range:** \-2147483648..2147483647
.. attribute:: bandwidth
Bandwidth (in kbps)
**type**\: int
**range:** 0..4294967295
**units**\: kbit/s
.. attribute:: input_data_rate
Input datarate in 1000's of bps
**type**\: int
**range:** 0..4294967295
**units**\: bit/s
.. attribute:: input_packet_rate
Input packets per second
**type**\: int
**range:** 0..4294967295
**units**\: packet/s
.. attribute:: input_peak_pkts
Peak input packet rate
**type**\: int
**range:** 0..4294967295
.. attribute:: input_peak_rate
Peak input datarate
**type**\: int
**range:** 0..4294967295
.. attribute:: output_data_rate
Output datarate in 1000's of bps
**type**\: int
**range:** 0..4294967295
**units**\: bit/s
.. attribute:: output_packet_rate
Output packets per second
**type**\: int
**range:** 0..4294967295
**units**\: packet/s
.. attribute:: output_peak_pkts
Peak output packet rate
**type**\: int
**range:** 0..4294967295
.. attribute:: output_peak_rate
Peak output datarate
**type**\: int
**range:** 0..4294967295
.. attribute:: time_stamp
Timestamp of sample in seconds drom UCT
**type**\: int
**range:** 0..18446744073709551615
**units**\: second
"""
_prefix = 'manageability-perfmgmt-oper'
_revision = '2015-11-09'
def __init__(self):
self.parent = None
self.sample_id = None
self.bandwidth = None
self.input_data_rate = None
self.input_packet_rate = None
self.input_peak_pkts = None
self.input_peak_rate = None
self.output_data_rate = None
self.output_packet_rate = None
self.output_peak_pkts = None
self.output_peak_rate = None
self.time_stamp = None
@property
def _common_path(self):
if self.parent is None:
raise YPYModelError('parent is not set . Cannot derive path.')
if self.sample_id is None:
raise YPYModelError('Key property sample_id is None')
return self.parent._common_path +'/Cisco-IOS-XR-manageability-perfmgmt-oper:sample[Cisco-IOS-XR-manageability-perfmgmt-oper:sample-id = ' + str(self.sample_id) + ']'
def is_config(self):
''' Returns True if this instance represents config data else returns False '''
return False
def _has_data(self):
if self.sample_id is not None:
return True
if self.bandwidth is not None:
return True
if self.input_data_rate is not None:
return True
if self.input_packet_rate is not None:
return True
if self.input_peak_pkts is not None:
return True
if self.input_peak_rate is not None:
return True
if self.output_data_rate is not None:
return True
if self.output_packet_rate is not None:
return True
if self.output_peak_pkts is not None:
return True
if self.output_peak_rate is not None:
return True
if self.time_stamp is not None:
return True
return False
@staticmethod
def _meta_info():
from ydk.models.cisco_ios_xr._meta import _Cisco_IOS_XR_manageability_perfmgmt_oper as meta
return meta._meta_table['PerfMgmt.Periodic.Interface.DataRateInterfaces.DataRateInterface.Samples.Sample']['meta_info']
@property
def _common_path(self):
if self.parent is None:
raise YPYModelError('parent is not set . Cannot derive path.')
return self.parent._common_path +'/Cisco-IOS-XR-manageability-perfmgmt-oper:samples'
def is_config(self):
''' Returns True if this instance represents config data else returns False '''
return False
def _has_data(self):
if self.sample is not None:
for child_ref in self.sample:
if child_ref._has_data():
return True
return False
@staticmethod
def _meta_info():
from ydk.models.cisco_ios_xr._meta import _Cisco_IOS_XR_manageability_perfmgmt_oper as meta
return meta._meta_table['PerfMgmt.Periodic.Interface.DataRateInterfaces.DataRateInterface.Samples']['meta_info']
@property
def _common_path(self):
if self.interface_name is None:
raise YPYModelError('Key property interface_name is None')
return '/Cisco-IOS-XR-manageability-perfmgmt-oper:perf-mgmt/Cisco-IOS-XR-manageability-perfmgmt-oper:periodic/Cisco-IOS-XR-manageability-perfmgmt-oper:interface/Cisco-IOS-XR-manageability-perfmgmt-oper:data-rate-interfaces/Cisco-IOS-XR-manageability-perfmgmt-oper:data-rate-interface[Cisco-IOS-XR-manageability-perfmgmt-oper:interface-name = ' + str(self.interface_name) + ']'
def is_config(self):
''' Returns True if this instance represents config data else returns False '''
return False
def _has_data(self):
if self.interface_name is not None:
return True
if self.samples is not None and self.samples._has_data():
return True
return False
@staticmethod
def _meta_info():
from ydk.models.cisco_ios_xr._meta import _Cisco_IOS_XR_manageability_perfmgmt_oper as meta
return meta._meta_table['PerfMgmt.Periodic.Interface.DataRateInterfaces.DataRateInterface']['meta_info']
@property
def _common_path(self):
return '/Cisco-IOS-XR-manageability-perfmgmt-oper:perf-mgmt/Cisco-IOS-XR-manageability-perfmgmt-oper:periodic/Cisco-IOS-XR-manageability-perfmgmt-oper:interface/Cisco-IOS-XR-manageability-perfmgmt-oper:data-rate-interfaces'
def is_config(self):
''' Returns True if this instance represents config data else returns False '''
return False
def _has_data(self):
if self.data_rate_interface is not None:
for child_ref in self.data_rate_interface:
if child_ref._has_data():
return True
return False
@staticmethod
def _meta_info():
from ydk.models.cisco_ios_xr._meta import _Cisco_IOS_XR_manageability_perfmgmt_oper as meta
return meta._meta_table['PerfMgmt.Periodic.Interface.DataRateInterfaces']['meta_info']
@property
def _common_path(self):
return '/Cisco-IOS-XR-manageability-perfmgmt-oper:perf-mgmt/Cisco-IOS-XR-manageability-perfmgmt-oper:periodic/Cisco-IOS-XR-manageability-perfmgmt-oper:interface'
def is_config(self):
''' Returns True if this instance represents config data else returns False '''
return False
def _has_data(self):
if self.basic_counter_interfaces is not None and self.basic_counter_interfaces._has_data():
return True
if self.data_rate_interfaces is not None and self.data_rate_interfaces._has_data():
return True
if self.generic_counter_interfaces is not None and self.generic_counter_interfaces._has_data():
return True
return False
@staticmethod
def _meta_info():
from ydk.models.cisco_ios_xr._meta import _Cisco_IOS_XR_manageability_perfmgmt_oper as meta
return meta._meta_table['PerfMgmt.Periodic.Interface']['meta_info']
@property
def _common_path(self):
return '/Cisco-IOS-XR-manageability-perfmgmt-oper:perf-mgmt/Cisco-IOS-XR-manageability-perfmgmt-oper:periodic'
def is_config(self):
''' Returns True if this instance represents config data else returns False '''
return False
def _has_data(self):
if self.bgp is not None and self.bgp._has_data():
return True
if self.interface is not None and self.interface._has_data():
return True
if self.mpls is not None and self.mpls._has_data():
return True
if self.nodes is not None and self.nodes._has_data():
return True
if self.ospf is not None and self.ospf._has_data():
return True
return False
@staticmethod
def _meta_info():
from ydk.models.cisco_ios_xr._meta import _Cisco_IOS_XR_manageability_perfmgmt_oper as meta
return meta._meta_table['PerfMgmt.Periodic']['meta_info']
class Monitor(object):
"""
Data from monitor (one history period) requests
.. attribute:: bgp
Collected BGP data
**type**\: :py:class:`Bgp <ydk.models.cisco_ios_xr.Cisco_IOS_XR_manageability_perfmgmt_oper.PerfMgmt.Monitor.Bgp>`
.. attribute:: interface
Collected Interface data
**type**\: :py:class:`Interface <ydk.models.cisco_ios_xr.Cisco_IOS_XR_manageability_perfmgmt_oper.PerfMgmt.Monitor.Interface>`
.. attribute:: mpls
Collected MPLS data
**type**\: :py:class:`Mpls <ydk.models.cisco_ios_xr.Cisco_IOS_XR_manageability_perfmgmt_oper.PerfMgmt.Monitor.Mpls>`
.. attribute:: nodes
Nodes for which data is collected
**type**\: :py:class:`Nodes <ydk.models.cisco_ios_xr.Cisco_IOS_XR_manageability_perfmgmt_oper.PerfMgmt.Monitor.Nodes>`
.. attribute:: ospf
Collected OSPF data
**type**\: :py:class:`Ospf <ydk.models.cisco_ios_xr.Cisco_IOS_XR_manageability_perfmgmt_oper.PerfMgmt.Monitor.Ospf>`
"""
_prefix = 'manageability-perfmgmt-oper'
_revision = '2015-11-09'
def __init__(self):
self.parent = None
self.bgp = PerfMgmt.Monitor.Bgp()
self.bgp.parent = self
self.interface = PerfMgmt.Monitor.Interface()
self.interface.parent = self
self.mpls = PerfMgmt.Monitor.Mpls()
self.mpls.parent = self
self.nodes = PerfMgmt.Monitor.Nodes()
self.nodes.parent = self
self.ospf = PerfMgmt.Monitor.Ospf()
self.ospf.parent = self
class Ospf(object):
"""
Collected OSPF data
.. attribute:: ospfv2_protocol_instances
OSPF v2 instances for which protocol statistics are collected
**type**\: :py:class:`Ospfv2ProtocolInstances <ydk.models.cisco_ios_xr.Cisco_IOS_XR_manageability_perfmgmt_oper.PerfMgmt.Monitor.Ospf.Ospfv2ProtocolInstances>`
.. attribute:: ospfv3_protocol_instances
OSPF v3 instances for which protocol statistics are collected
**type**\: :py:class:`Ospfv3ProtocolInstances <ydk.models.cisco_ios_xr.Cisco_IOS_XR_manageability_perfmgmt_oper.PerfMgmt.Monitor.Ospf.Ospfv3ProtocolInstances>`
"""
_prefix = 'manageability-perfmgmt-oper'
_revision = '2015-11-09'
def __init__(self):
self.parent = None
self.ospfv2_protocol_instances = PerfMgmt.Monitor.Ospf.Ospfv2ProtocolInstances()
self.ospfv2_protocol_instances.parent = self
self.ospfv3_protocol_instances = PerfMgmt.Monitor.Ospf.Ospfv3ProtocolInstances()
self.ospfv3_protocol_instances.parent = self
class Ospfv2ProtocolInstances(object):
"""
OSPF v2 instances for which protocol statistics
are collected
.. attribute:: ospfv2_protocol_instance
Protocol samples for a particular OSPF v2 instance
**type**\: list of :py:class:`Ospfv2ProtocolInstance <ydk.models.cisco_ios_xr.Cisco_IOS_XR_manageability_perfmgmt_oper.PerfMgmt.Monitor.Ospf.Ospfv2ProtocolInstances.Ospfv2ProtocolInstance>`
"""
_prefix = 'manageability-perfmgmt-oper'
_revision = '2015-11-09'
def __init__(self):
self.parent = None
self.ospfv2_protocol_instance = YList()
self.ospfv2_protocol_instance.parent = self
self.ospfv2_protocol_instance.name = 'ospfv2_protocol_instance'
class Ospfv2ProtocolInstance(object):
"""
Protocol samples for a particular OSPF v2
instance
.. attribute:: instance_name <key>
OSPF Instance Name
**type**\: str
**pattern:** [\\w\\\-\\.\:,\_@#%$\\+=\\\|;]+
.. attribute:: samples
Sample Table for an OSPV v2 instance
**type**\: :py:class:`Samples <ydk.models.cisco_ios_xr.Cisco_IOS_XR_manageability_perfmgmt_oper.PerfMgmt.Monitor.Ospf.Ospfv2ProtocolInstances.Ospfv2ProtocolInstance.Samples>`
"""
_prefix = 'manageability-perfmgmt-oper'
_revision = '2015-11-09'
def __init__(self):
self.parent = None
self.instance_name = None
self.samples = PerfMgmt.Monitor.Ospf.Ospfv2ProtocolInstances.Ospfv2ProtocolInstance.Samples()
self.samples.parent = self
class Samples(object):
"""
Sample Table for an OSPV v2 instance
.. attribute:: sample
Generic Counters sample
**type**\: list of :py:class:`Sample <ydk.models.cisco_ios_xr.Cisco_IOS_XR_manageability_perfmgmt_oper.PerfMgmt.Monitor.Ospf.Ospfv2ProtocolInstances.Ospfv2ProtocolInstance.Samples.Sample>`
"""
_prefix = 'manageability-perfmgmt-oper'
_revision = '2015-11-09'
def __init__(self):
self.parent = None
self.sample = YList()
self.sample.parent = self
self.sample.name = 'sample'
class Sample(object):
"""
Generic Counters sample
.. attribute:: sample_id <key>
Sample ID
**type**\: int
**range:** \-2147483648..2147483647
.. attribute:: checksum_errors
Number of packets received with checksum errors
**type**\: int
**range:** 0..4294967295
.. attribute:: input_db_ds
Number of DBD packets received
**type**\: int
**range:** 0..4294967295
.. attribute:: input_db_ds_lsa
Number of LSA received in DBD packets
**type**\: int
**range:** 0..4294967295
.. attribute:: input_hello_packets
Number of Hello packets received
**type**\: int
**range:** 0..4294967295
.. attribute:: input_ls_requests
Number of LS Requests received
**type**\: int
**range:** 0..4294967295
.. attribute:: input_ls_requests_lsa
Number of LSA received in LS Requests
**type**\: int
**range:** 0..4294967295
.. attribute:: input_lsa_acks
Number of LSA Acknowledgements received
**type**\: int
**range:** 0..4294967295
.. attribute:: input_lsa_acks_lsa
Number of LSA received in LSA Acknowledgements
**type**\: int
**range:** 0..4294967295
.. attribute:: input_lsa_updates
Number of LSA Updates received
**type**\: int
**range:** 0..4294967295
.. attribute:: input_lsa_updates_lsa
Number of LSA received in LSA Updates
**type**\: int
**range:** 0..4294967295
.. attribute:: input_packets
Total number of packets received
**type**\: int
**range:** 0..4294967295
.. attribute:: output_db_ds
Number of DBD packets sent
**type**\: int
**range:** 0..4294967295
.. attribute:: output_db_ds_lsa
Number of LSA sent in DBD packets
**type**\: int
**range:** 0..4294967295
.. attribute:: output_hello_packets
Number of Hello packets sent
**type**\: int
**range:** 0..4294967295
.. attribute:: output_ls_requests
Number of LS Requests sent
**type**\: int
**range:** 0..4294967295
.. attribute:: output_ls_requests_lsa
Number of LSA sent in LS Requests
**type**\: int
**range:** 0..4294967295
.. attribute:: output_lsa_acks
Number of LSA Acknowledgements sent
**type**\: int
**range:** 0..4294967295
.. attribute:: output_lsa_acks_lsa
Number of LSA sent in LSA Acknowledgements
**type**\: int
**range:** 0..4294967295
.. attribute:: output_lsa_updates
Number of LSA Updates sent
**type**\: int
**range:** 0..4294967295
.. attribute:: output_lsa_updates_lsa
Number of LSA sent in LSA Updates
**type**\: int
**range:** 0..4294967295
.. attribute:: output_packets
Total number of packets sent
**type**\: int
**range:** 0..4294967295
.. attribute:: time_stamp
Timestamp of sample in seconds drom UCT
**type**\: int
**range:** 0..18446744073709551615
**units**\: second
"""
_prefix = 'manageability-perfmgmt-oper'
_revision = '2015-11-09'
def __init__(self):
self.parent = None
self.sample_id = None
self.checksum_errors = None
self.input_db_ds = None
self.input_db_ds_lsa = None
self.input_hello_packets = None
self.input_ls_requests = None
self.input_ls_requests_lsa = None
self.input_lsa_acks = None
self.input_lsa_acks_lsa = None
self.input_lsa_updates = None
self.input_lsa_updates_lsa = None
self.input_packets = None
self.output_db_ds = None
self.output_db_ds_lsa = None
self.output_hello_packets = None
self.output_ls_requests = None
self.output_ls_requests_lsa = None
self.output_lsa_acks = None
self.output_lsa_acks_lsa = None
self.output_lsa_updates = None
self.output_lsa_updates_lsa = None
self.output_packets = None
self.time_stamp = None
@property
def _common_path(self):
if self.parent is None:
raise YPYModelError('parent is not set . Cannot derive path.')
if self.sample_id is None:
raise YPYModelError('Key property sample_id is None')
return self.parent._common_path +'/Cisco-IOS-XR-manageability-perfmgmt-oper:sample[Cisco-IOS-XR-manageability-perfmgmt-oper:sample-id = ' + str(self.sample_id) + ']'
def is_config(self):
''' Returns True if this instance represents config data else returns False '''
return False
def _has_data(self):
if self.sample_id is not None:
return True
if self.checksum_errors is not None:
return True
if self.input_db_ds is not None:
return True
if self.input_db_ds_lsa is not None:
return True
if self.input_hello_packets is not None:
return True
if self.input_ls_requests is not None:
return True
if self.input_ls_requests_lsa is not None:
return True
if self.input_lsa_acks is not None:
return True
if self.input_lsa_acks_lsa is not None:
return True
if self.input_lsa_updates is not None:
return True
if self.input_lsa_updates_lsa is not None:
return True
if self.input_packets is not None:
return True
if self.output_db_ds is not None:
return True
if self.output_db_ds_lsa is not None:
return True
if self.output_hello_packets is not None:
return True
if self.output_ls_requests is not None:
return True
if self.output_ls_requests_lsa is not None:
return True
if self.output_lsa_acks is not None:
return True
if self.output_lsa_acks_lsa is not None:
return True
if self.output_lsa_updates is not None:
return True
if self.output_lsa_updates_lsa is not None:
return True
if self.output_packets is not None:
return True
if self.time_stamp is not None:
return True
return False
@staticmethod
def _meta_info():
from ydk.models.cisco_ios_xr._meta import _Cisco_IOS_XR_manageability_perfmgmt_oper as meta
return meta._meta_table['PerfMgmt.Monitor.Ospf.Ospfv2ProtocolInstances.Ospfv2ProtocolInstance.Samples.Sample']['meta_info']
@property
def _common_path(self):
if self.parent is None:
raise YPYModelError('parent is not set . Cannot derive path.')
return self.parent._common_path +'/Cisco-IOS-XR-manageability-perfmgmt-oper:samples'
def is_config(self):
''' Returns True if this instance represents config data else returns False '''
return False
def _has_data(self):
if self.sample is not None:
for child_ref in self.sample:
if child_ref._has_data():
return True
return False
@staticmethod
def _meta_info():
from ydk.models.cisco_ios_xr._meta import _Cisco_IOS_XR_manageability_perfmgmt_oper as meta
return meta._meta_table['PerfMgmt.Monitor.Ospf.Ospfv2ProtocolInstances.Ospfv2ProtocolInstance.Samples']['meta_info']
@property
def _common_path(self):
if self.instance_name is None:
raise YPYModelError('Key property instance_name is None')
return '/Cisco-IOS-XR-manageability-perfmgmt-oper:perf-mgmt/Cisco-IOS-XR-manageability-perfmgmt-oper:monitor/Cisco-IOS-XR-manageability-perfmgmt-oper:ospf/Cisco-IOS-XR-manageability-perfmgmt-oper:ospfv2-protocol-instances/Cisco-IOS-XR-manageability-perfmgmt-oper:ospfv2-protocol-instance[Cisco-IOS-XR-manageability-perfmgmt-oper:instance-name = ' + str(self.instance_name) + ']'
def is_config(self):
''' Returns True if this instance represents config data else returns False '''
return False
def _has_data(self):
if self.instance_name is not None:
return True
if self.samples is not None and self.samples._has_data():
return True
return False
@staticmethod
def _meta_info():
from ydk.models.cisco_ios_xr._meta import _Cisco_IOS_XR_manageability_perfmgmt_oper as meta
return meta._meta_table['PerfMgmt.Monitor.Ospf.Ospfv2ProtocolInstances.Ospfv2ProtocolInstance']['meta_info']
@property
def _common_path(self):
return '/Cisco-IOS-XR-manageability-perfmgmt-oper:perf-mgmt/Cisco-IOS-XR-manageability-perfmgmt-oper:monitor/Cisco-IOS-XR-manageability-perfmgmt-oper:ospf/Cisco-IOS-XR-manageability-perfmgmt-oper:ospfv2-protocol-instances'
def is_config(self):
''' Returns True if this instance represents config data else returns False '''
return False
def _has_data(self):
if self.ospfv2_protocol_instance is not None:
for child_ref in self.ospfv2_protocol_instance:
if child_ref._has_data():
return True
return False
@staticmethod
def _meta_info():
from ydk.models.cisco_ios_xr._meta import _Cisco_IOS_XR_manageability_perfmgmt_oper as meta
return meta._meta_table['PerfMgmt.Monitor.Ospf.Ospfv2ProtocolInstances']['meta_info']
class Ospfv3ProtocolInstances(object):
"""
OSPF v3 instances for which protocol statistics
are collected
.. attribute:: ospfv3_protocol_instance
Protocol samples for a particular OSPF v3 instance
**type**\: list of :py:class:`Ospfv3ProtocolInstance <ydk.models.cisco_ios_xr.Cisco_IOS_XR_manageability_perfmgmt_oper.PerfMgmt.Monitor.Ospf.Ospfv3ProtocolInstances.Ospfv3ProtocolInstance>`
"""
_prefix = 'manageability-perfmgmt-oper'
_revision = '2015-11-09'
def __init__(self):
self.parent = None
self.ospfv3_protocol_instance = YList()
self.ospfv3_protocol_instance.parent = self
self.ospfv3_protocol_instance.name = 'ospfv3_protocol_instance'
class Ospfv3ProtocolInstance(object):
"""
Protocol samples for a particular OSPF v3
instance
.. attribute:: instance_name <key>
OSPF Instance Name
**type**\: str
**pattern:** [\\w\\\-\\.\:,\_@#%$\\+=\\\|;]+
.. attribute:: samples
Sample Table for an OSPV v3 instance
**type**\: :py:class:`Samples <ydk.models.cisco_ios_xr.Cisco_IOS_XR_manageability_perfmgmt_oper.PerfMgmt.Monitor.Ospf.Ospfv3ProtocolInstances.Ospfv3ProtocolInstance.Samples>`
"""
_prefix = 'manageability-perfmgmt-oper'
_revision = '2015-11-09'
def __init__(self):
self.parent = None
self.instance_name = None
self.samples = PerfMgmt.Monitor.Ospf.Ospfv3ProtocolInstances.Ospfv3ProtocolInstance.Samples()
self.samples.parent = self
class Samples(object):
"""
Sample Table for an OSPV v3 instance
.. attribute:: sample
Generic Counters sample
**type**\: list of :py:class:`Sample <ydk.models.cisco_ios_xr.Cisco_IOS_XR_manageability_perfmgmt_oper.PerfMgmt.Monitor.Ospf.Ospfv3ProtocolInstances.Ospfv3ProtocolInstance.Samples.Sample>`
"""
_prefix = 'manageability-perfmgmt-oper'
_revision = '2015-11-09'
def __init__(self):
self.parent = None
self.sample = YList()
self.sample.parent = self
self.sample.name = 'sample'
class Sample(object):
"""
Generic Counters sample
.. attribute:: sample_id <key>
Sample ID
**type**\: int
**range:** \-2147483648..2147483647
.. attribute:: input_db_ds
Number of DBD packets received
**type**\: int
**range:** 0..4294967295
.. attribute:: input_db_ds_lsa
Number of LSA received in DBD packets
**type**\: int
**range:** 0..4294967295
.. attribute:: input_hello_packets
Number of Hello packets received
**type**\: int
**range:** 0..4294967295
.. attribute:: input_ls_requests
Number of LS Requests received
**type**\: int
**range:** 0..4294967295
.. attribute:: input_ls_requests_lsa
Number of LSA received in LS Requests
**type**\: int
**range:** 0..4294967295
.. attribute:: input_lsa_acks
Number of LSA Acknowledgements received
**type**\: int
**range:** 0..4294967295
.. attribute:: input_lsa_acks_lsa
Number of LSA received in LSA Acknowledgements
**type**\: int
**range:** 0..4294967295
.. attribute:: input_lsa_updates
Number of LSA Updates received
**type**\: int
**range:** 0..4294967295
.. attribute:: input_lsa_updates_lsa
Number of LSA received in LSA Updates
**type**\: int
**range:** 0..4294967295
.. attribute:: input_packets
Total number of packets received
**type**\: int
**range:** 0..4294967295
.. attribute:: output_db_ds
Number of DBD packets sent
**type**\: int
**range:** 0..4294967295
.. attribute:: output_db_ds_lsa
Number of LSA sent in DBD packets
**type**\: int
**range:** 0..4294967295
.. attribute:: output_hello_packets
Number of Hello packets sent
**type**\: int
**range:** 0..4294967295
.. attribute:: output_ls_requests
Number of LS Requests sent
**type**\: int
**range:** 0..4294967295
.. attribute:: output_ls_requests_lsa
Number of LSA sent in LS Requests
**type**\: int
**range:** 0..4294967295
.. attribute:: output_lsa_acks
Number of LSA Acknowledgements sent
**type**\: int
**range:** 0..4294967295
.. attribute:: output_lsa_acks_lsa
Number of LSA sent in LSA Acknowledgements
**type**\: int
**range:** 0..4294967295
.. attribute:: output_lsa_updates
Number of LSA Updates sent
**type**\: int
**range:** 0..4294967295
.. attribute:: output_lsa_updates_lsa
Number of LSA sent in LSA Updates
**type**\: int
**range:** 0..4294967295
.. attribute:: output_packets
Total number of packets sent
**type**\: int
**range:** 0..4294967295
.. attribute:: time_stamp
Timestamp of sample in seconds drom UCT
**type**\: int
**range:** 0..18446744073709551615
**units**\: second
"""
_prefix = 'manageability-perfmgmt-oper'
_revision = '2015-11-09'
def __init__(self):
self.parent = None
self.sample_id = None
self.input_db_ds = None
self.input_db_ds_lsa = None
self.input_hello_packets = None
self.input_ls_requests = None
self.input_ls_requests_lsa = None
self.input_lsa_acks = None
self.input_lsa_acks_lsa = None
self.input_lsa_updates = None
self.input_lsa_updates_lsa = None
self.input_packets = None
self.output_db_ds = None
self.output_db_ds_lsa = None
self.output_hello_packets = None
self.output_ls_requests = None
self.output_ls_requests_lsa = None
self.output_lsa_acks = None
self.output_lsa_acks_lsa = None
self.output_lsa_updates = None
self.output_lsa_updates_lsa = None
self.output_packets = None
self.time_stamp = None
@property
def _common_path(self):
if self.parent is None:
raise YPYModelError('parent is not set . Cannot derive path.')
if self.sample_id is None:
raise YPYModelError('Key property sample_id is None')
return self.parent._common_path +'/Cisco-IOS-XR-manageability-perfmgmt-oper:sample[Cisco-IOS-XR-manageability-perfmgmt-oper:sample-id = ' + str(self.sample_id) + ']'
def is_config(self):
''' Returns True if this instance represents config data else returns False '''
return False
def _has_data(self):
if self.sample_id is not None:
return True
if self.input_db_ds is not None:
return True
if self.input_db_ds_lsa is not None:
return True
if self.input_hello_packets is not None:
return True
if self.input_ls_requests is not None:
return True
if self.input_ls_requests_lsa is not None:
return True
if self.input_lsa_acks is not None:
return True
if self.input_lsa_acks_lsa is not None:
return True
if self.input_lsa_updates is not None:
return True
if self.input_lsa_updates_lsa is not None:
return True
if self.input_packets is not None:
return True
if self.output_db_ds is not None:
return True
if self.output_db_ds_lsa is not None:
return True
if self.output_hello_packets is not None:
return True
if self.output_ls_requests is not None:
return True
if self.output_ls_requests_lsa is not None:
return True
if self.output_lsa_acks is not None:
return True
if self.output_lsa_acks_lsa is not None:
return True
if self.output_lsa_updates is not None:
return True
if self.output_lsa_updates_lsa is not None:
return True
if self.output_packets is not None:
return True
if self.time_stamp is not None:
return True
return False
@staticmethod
def _meta_info():
from ydk.models.cisco_ios_xr._meta import _Cisco_IOS_XR_manageability_perfmgmt_oper as meta
return meta._meta_table['PerfMgmt.Monitor.Ospf.Ospfv3ProtocolInstances.Ospfv3ProtocolInstance.Samples.Sample']['meta_info']
@property
def _common_path(self):
if self.parent is None:
raise YPYModelError('parent is not set . Cannot derive path.')
return self.parent._common_path +'/Cisco-IOS-XR-manageability-perfmgmt-oper:samples'
def is_config(self):
''' Returns True if this instance represents config data else returns False '''
return False
def _has_data(self):
if self.sample is not None:
for child_ref in self.sample:
if child_ref._has_data():
return True
return False
@staticmethod
def _meta_info():
from ydk.models.cisco_ios_xr._meta import _Cisco_IOS_XR_manageability_perfmgmt_oper as meta
return meta._meta_table['PerfMgmt.Monitor.Ospf.Ospfv3ProtocolInstances.Ospfv3ProtocolInstance.Samples']['meta_info']
@property
def _common_path(self):
if self.instance_name is None:
raise YPYModelError('Key property instance_name is None')
return '/Cisco-IOS-XR-manageability-perfmgmt-oper:perf-mgmt/Cisco-IOS-XR-manageability-perfmgmt-oper:monitor/Cisco-IOS-XR-manageability-perfmgmt-oper:ospf/Cisco-IOS-XR-manageability-perfmgmt-oper:ospfv3-protocol-instances/Cisco-IOS-XR-manageability-perfmgmt-oper:ospfv3-protocol-instance[Cisco-IOS-XR-manageability-perfmgmt-oper:instance-name = ' + str(self.instance_name) + ']'
def is_config(self):
''' Returns True if this instance represents config data else returns False '''
return False
def _has_data(self):
if self.instance_name is not None:
return True
if self.samples is not None and self.samples._has_data():
return True
return False
@staticmethod
def _meta_info():
from ydk.models.cisco_ios_xr._meta import _Cisco_IOS_XR_manageability_perfmgmt_oper as meta
return meta._meta_table['PerfMgmt.Monitor.Ospf.Ospfv3ProtocolInstances.Ospfv3ProtocolInstance']['meta_info']
@property
def _common_path(self):
return '/Cisco-IOS-XR-manageability-perfmgmt-oper:perf-mgmt/Cisco-IOS-XR-manageability-perfmgmt-oper:monitor/Cisco-IOS-XR-manageability-perfmgmt-oper:ospf/Cisco-IOS-XR-manageability-perfmgmt-oper:ospfv3-protocol-instances'
def is_config(self):
''' Returns True if this instance represents config data else returns False '''
return False
def _has_data(self):
if self.ospfv3_protocol_instance is not None:
for child_ref in self.ospfv3_protocol_instance:
if child_ref._has_data():
return True
return False
@staticmethod
def _meta_info():
from ydk.models.cisco_ios_xr._meta import _Cisco_IOS_XR_manageability_perfmgmt_oper as meta
return meta._meta_table['PerfMgmt.Monitor.Ospf.Ospfv3ProtocolInstances']['meta_info']
@property
def _common_path(self):
return '/Cisco-IOS-XR-manageability-perfmgmt-oper:perf-mgmt/Cisco-IOS-XR-manageability-perfmgmt-oper:monitor/Cisco-IOS-XR-manageability-perfmgmt-oper:ospf'
def is_config(self):
''' Returns True if this instance represents config data else returns False '''
return False
def _has_data(self):
if self.ospfv2_protocol_instances is not None and self.ospfv2_protocol_instances._has_data():
return True
if self.ospfv3_protocol_instances is not None and self.ospfv3_protocol_instances._has_data():
return True
return False
@staticmethod
def _meta_info():
from ydk.models.cisco_ios_xr._meta import _Cisco_IOS_XR_manageability_perfmgmt_oper as meta
return meta._meta_table['PerfMgmt.Monitor.Ospf']['meta_info']
class Mpls(object):
"""
Collected MPLS data
.. attribute:: ldp_neighbors
LDP neighbors for which statistics are collected
**type**\: :py:class:`LdpNeighbors <ydk.models.cisco_ios_xr.Cisco_IOS_XR_manageability_perfmgmt_oper.PerfMgmt.Monitor.Mpls.LdpNeighbors>`
"""
_prefix = 'manageability-perfmgmt-oper'
_revision = '2015-11-09'
def __init__(self):
self.parent = None
self.ldp_neighbors = PerfMgmt.Monitor.Mpls.LdpNeighbors()
self.ldp_neighbors.parent = self
class LdpNeighbors(object):
"""
LDP neighbors for which statistics are
collected
.. attribute:: ldp_neighbor
Samples for a particular LDP neighbor
**type**\: list of :py:class:`LdpNeighbor <ydk.models.cisco_ios_xr.Cisco_IOS_XR_manageability_perfmgmt_oper.PerfMgmt.Monitor.Mpls.LdpNeighbors.LdpNeighbor>`
"""
_prefix = 'manageability-perfmgmt-oper'
_revision = '2015-11-09'
def __init__(self):
self.parent = None
self.ldp_neighbor = YList()
self.ldp_neighbor.parent = self
self.ldp_neighbor.name = 'ldp_neighbor'
class LdpNeighbor(object):
"""
Samples for a particular LDP neighbor
.. attribute:: nbr <key>
Neighbor Address
**type**\: str
**pattern:** (([0\-9]\|[1\-9][0\-9]\|1[0\-9][0\-9]\|2[0\-4][0\-9]\|25[0\-5])\\.){3}([0\-9]\|[1\-9][0\-9]\|1[0\-9][0\-9]\|2[0\-4][0\-9]\|25[0\-5])(%[\\p{N}\\p{L}]+)?
.. attribute:: samples
Samples for a particular LDP neighbor
**type**\: :py:class:`Samples <ydk.models.cisco_ios_xr.Cisco_IOS_XR_manageability_perfmgmt_oper.PerfMgmt.Monitor.Mpls.LdpNeighbors.LdpNeighbor.Samples>`
"""
_prefix = 'manageability-perfmgmt-oper'
_revision = '2015-11-09'
def __init__(self):
self.parent = None
self.nbr = None
self.samples = PerfMgmt.Monitor.Mpls.LdpNeighbors.LdpNeighbor.Samples()
self.samples.parent = self
class Samples(object):
"""
Samples for a particular LDP neighbor
.. attribute:: sample
LDP neighbor statistics sample
**type**\: list of :py:class:`Sample <ydk.models.cisco_ios_xr.Cisco_IOS_XR_manageability_perfmgmt_oper.PerfMgmt.Monitor.Mpls.LdpNeighbors.LdpNeighbor.Samples.Sample>`
"""
_prefix = 'manageability-perfmgmt-oper'
_revision = '2015-11-09'
def __init__(self):
self.parent = None
self.sample = YList()
self.sample.parent = self
self.sample.name = 'sample'
class Sample(object):
"""
LDP neighbor statistics sample
.. attribute:: sample_id <key>
Sample ID
**type**\: int
**range:** \-2147483648..2147483647
.. attribute:: address_msgs_rcvd
Address messages received
**type**\: int
**range:** 0..65535
.. attribute:: address_msgs_sent
Address messages sent
**type**\: int
**range:** 0..65535
.. attribute:: address_withdraw_msgs_rcvd
Address withdraw messages received
**type**\: int
**range:** 0..65535
.. attribute:: address_withdraw_msgs_sent
Address withdraw messages sent
**type**\: int
**range:** 0..65535
.. attribute:: init_msgs_rcvd
Tnit messages received
**type**\: int
**range:** 0..65535
.. attribute:: init_msgs_sent
Init messages sent
**type**\: int
**range:** 0..65535
.. attribute:: keepalive_msgs_rcvd
Keepalive messages received
**type**\: int
**range:** 0..65535
.. attribute:: keepalive_msgs_sent
Keepalive messages sent
**type**\: int
**range:** 0..65535
.. attribute:: label_mapping_msgs_rcvd
Label mapping messages received
**type**\: int
**range:** 0..65535
.. attribute:: label_mapping_msgs_sent
Label mapping messages sent
**type**\: int
**range:** 0..65535
.. attribute:: label_release_msgs_rcvd
Label release messages received
**type**\: int
**range:** 0..65535
.. attribute:: label_release_msgs_sent
Label release messages sent
**type**\: int
**range:** 0..65535
.. attribute:: label_withdraw_msgs_rcvd
Label withdraw messages received
**type**\: int
**range:** 0..65535
.. attribute:: label_withdraw_msgs_sent
Label withdraw messages sent
**type**\: int
**range:** 0..65535
.. attribute:: notification_msgs_rcvd
Notification messages received
**type**\: int
**range:** 0..65535
.. attribute:: notification_msgs_sent
Notification messages sent
**type**\: int
**range:** 0..65535
.. attribute:: time_stamp
Timestamp of sample in seconds drom UCT
**type**\: int
**range:** 0..18446744073709551615
**units**\: second
.. attribute:: total_msgs_rcvd
Total messages received
**type**\: int
**range:** 0..65535
.. attribute:: total_msgs_sent
Total messages sent
**type**\: int
**range:** 0..65535
"""
_prefix = 'manageability-perfmgmt-oper'
_revision = '2015-11-09'
def __init__(self):
self.parent = None
self.sample_id = None
self.address_msgs_rcvd = None
self.address_msgs_sent = None
self.address_withdraw_msgs_rcvd = None
self.address_withdraw_msgs_sent = None
self.init_msgs_rcvd = None
self.init_msgs_sent = None
self.keepalive_msgs_rcvd = None
self.keepalive_msgs_sent = None
self.label_mapping_msgs_rcvd = None
self.label_mapping_msgs_sent = None
self.label_release_msgs_rcvd = None
self.label_release_msgs_sent = None
self.label_withdraw_msgs_rcvd = None
self.label_withdraw_msgs_sent = None
self.notification_msgs_rcvd = None
self.notification_msgs_sent = None
self.time_stamp = None
self.total_msgs_rcvd = None
self.total_msgs_sent = None
@property
def _common_path(self):
if self.parent is None:
raise YPYModelError('parent is not set . Cannot derive path.')
if self.sample_id is None:
raise YPYModelError('Key property sample_id is None')
return self.parent._common_path +'/Cisco-IOS-XR-manageability-perfmgmt-oper:sample[Cisco-IOS-XR-manageability-perfmgmt-oper:sample-id = ' + str(self.sample_id) + ']'
def is_config(self):
''' Returns True if this instance represents config data else returns False '''
return False
def _has_data(self):
if self.sample_id is not None:
return True
if self.address_msgs_rcvd is not None:
return True
if self.address_msgs_sent is not None:
return True
if self.address_withdraw_msgs_rcvd is not None:
return True
if self.address_withdraw_msgs_sent is not None:
return True
if self.init_msgs_rcvd is not None:
return True
if self.init_msgs_sent is not None:
return True
if self.keepalive_msgs_rcvd is not None:
return True
if self.keepalive_msgs_sent is not None:
return True
if self.label_mapping_msgs_rcvd is not None:
return True
if self.label_mapping_msgs_sent is not None:
return True
if self.label_release_msgs_rcvd is not None:
return True
if self.label_release_msgs_sent is not None:
return True
if self.label_withdraw_msgs_rcvd is not None:
return True
if self.label_withdraw_msgs_sent is not None:
return True
if self.notification_msgs_rcvd is not None:
return True
if self.notification_msgs_sent is not None:
return True
if self.time_stamp is not None:
return True
if self.total_msgs_rcvd is not None:
return True
if self.total_msgs_sent is not None:
return True
return False
@staticmethod
def _meta_info():
from ydk.models.cisco_ios_xr._meta import _Cisco_IOS_XR_manageability_perfmgmt_oper as meta
return meta._meta_table['PerfMgmt.Monitor.Mpls.LdpNeighbors.LdpNeighbor.Samples.Sample']['meta_info']
@property
def _common_path(self):
if self.parent is None:
raise YPYModelError('parent is not set . Cannot derive path.')
return self.parent._common_path +'/Cisco-IOS-XR-manageability-perfmgmt-oper:samples'
def is_config(self):
''' Returns True if this instance represents config data else returns False '''
return False
def _has_data(self):
if self.sample is not None:
for child_ref in self.sample:
if child_ref._has_data():
return True
return False
@staticmethod
def _meta_info():
from ydk.models.cisco_ios_xr._meta import _Cisco_IOS_XR_manageability_perfmgmt_oper as meta
return meta._meta_table['PerfMgmt.Monitor.Mpls.LdpNeighbors.LdpNeighbor.Samples']['meta_info']
@property
def _common_path(self):
if self.nbr is None:
raise YPYModelError('Key property nbr is None')
return '/Cisco-IOS-XR-manageability-perfmgmt-oper:perf-mgmt/Cisco-IOS-XR-manageability-perfmgmt-oper:monitor/Cisco-IOS-XR-manageability-perfmgmt-oper:mpls/Cisco-IOS-XR-manageability-perfmgmt-oper:ldp-neighbors/Cisco-IOS-XR-manageability-perfmgmt-oper:ldp-neighbor[Cisco-IOS-XR-manageability-perfmgmt-oper:nbr = ' + str(self.nbr) + ']'
def is_config(self):
''' Returns True if this instance represents config data else returns False '''
return False
def _has_data(self):
if self.nbr is not None:
return True
if self.samples is not None and self.samples._has_data():
return True
return False
@staticmethod
def _meta_info():
from ydk.models.cisco_ios_xr._meta import _Cisco_IOS_XR_manageability_perfmgmt_oper as meta
return meta._meta_table['PerfMgmt.Monitor.Mpls.LdpNeighbors.LdpNeighbor']['meta_info']
@property
def _common_path(self):
return '/Cisco-IOS-XR-manageability-perfmgmt-oper:perf-mgmt/Cisco-IOS-XR-manageability-perfmgmt-oper:monitor/Cisco-IOS-XR-manageability-perfmgmt-oper:mpls/Cisco-IOS-XR-manageability-perfmgmt-oper:ldp-neighbors'
def is_config(self):
''' Returns True if this instance represents config data else returns False '''
return False
def _has_data(self):
if self.ldp_neighbor is not None:
for child_ref in self.ldp_neighbor:
if child_ref._has_data():
return True
return False
@staticmethod
def _meta_info():
from ydk.models.cisco_ios_xr._meta import _Cisco_IOS_XR_manageability_perfmgmt_oper as meta
return meta._meta_table['PerfMgmt.Monitor.Mpls.LdpNeighbors']['meta_info']
@property
def _common_path(self):
return '/Cisco-IOS-XR-manageability-perfmgmt-oper:perf-mgmt/Cisco-IOS-XR-manageability-perfmgmt-oper:monitor/Cisco-IOS-XR-manageability-perfmgmt-oper:mpls'
def is_config(self):
''' Returns True if this instance represents config data else returns False '''
return False
def _has_data(self):
if self.ldp_neighbors is not None and self.ldp_neighbors._has_data():
return True
return False
@staticmethod
def _meta_info():
from ydk.models.cisco_ios_xr._meta import _Cisco_IOS_XR_manageability_perfmgmt_oper as meta
return meta._meta_table['PerfMgmt.Monitor.Mpls']['meta_info']
class Nodes(object):
"""
Nodes for which data is collected
.. attribute:: node
Node Instance
**type**\: list of :py:class:`Node <ydk.models.cisco_ios_xr.Cisco_IOS_XR_manageability_perfmgmt_oper.PerfMgmt.Monitor.Nodes.Node>`
"""
_prefix = 'manageability-perfmgmt-oper'
_revision = '2015-11-09'
def __init__(self):
self.parent = None
self.node = YList()
self.node.parent = self
self.node.name = 'node'
class Node(object):
"""
Node Instance
.. attribute:: node_id <key>
Node ID
**type**\: str
**pattern:** ([a\-zA\-Z0\-9\_]\*\\d+/){1,2}([a\-zA\-Z0\-9\_]\*\\d+)
.. attribute:: processes
Processes data
**type**\: :py:class:`Processes <ydk.models.cisco_ios_xr.Cisco_IOS_XR_manageability_perfmgmt_oper.PerfMgmt.Monitor.Nodes.Node.Processes>`
.. attribute:: sample_xr
Node CPU data
**type**\: :py:class:`SampleXr <ydk.models.cisco_ios_xr.Cisco_IOS_XR_manageability_perfmgmt_oper.PerfMgmt.Monitor.Nodes.Node.SampleXr>`
.. attribute:: samples
Node Memory data
**type**\: :py:class:`Samples <ydk.models.cisco_ios_xr.Cisco_IOS_XR_manageability_perfmgmt_oper.PerfMgmt.Monitor.Nodes.Node.Samples>`
"""
_prefix = 'manageability-perfmgmt-oper'
_revision = '2015-11-09'
def __init__(self):
self.parent = None
self.node_id = None
self.processes = PerfMgmt.Monitor.Nodes.Node.Processes()
self.processes.parent = self
self.sample_xr = PerfMgmt.Monitor.Nodes.Node.SampleXr()
self.sample_xr.parent = self
self.samples = PerfMgmt.Monitor.Nodes.Node.Samples()
self.samples.parent = self
class SampleXr(object):
"""
Node CPU data
.. attribute:: sample
Node CPU data sample
**type**\: list of :py:class:`Sample <ydk.models.cisco_ios_xr.Cisco_IOS_XR_manageability_perfmgmt_oper.PerfMgmt.Monitor.Nodes.Node.SampleXr.Sample>`
"""
_prefix = 'manageability-perfmgmt-oper'
_revision = '2015-11-09'
def __init__(self):
self.parent = None
self.sample = YList()
self.sample.parent = self
self.sample.name = 'sample'
class Sample(object):
"""
Node CPU data sample
.. attribute:: sample_id <key>
Sample ID
**type**\: int
**range:** \-2147483648..2147483647
.. attribute:: average_cpu_used
Average system %CPU utilization
**type**\: int
**range:** 0..4294967295
.. attribute:: no_processes
Number of processes in the system
**type**\: int
**range:** 0..4294967295
.. attribute:: time_stamp
Timestamp of sample in seconds drom UCT
**type**\: int
**range:** 0..18446744073709551615
**units**\: second
"""
_prefix = 'manageability-perfmgmt-oper'
_revision = '2015-11-09'
def __init__(self):
self.parent = None
self.sample_id = None
self.average_cpu_used = None
self.no_processes = None
self.time_stamp = None
@property
def _common_path(self):
if self.parent is None:
raise YPYModelError('parent is not set . Cannot derive path.')
if self.sample_id is None:
raise YPYModelError('Key property sample_id is None')
return self.parent._common_path +'/Cisco-IOS-XR-manageability-perfmgmt-oper:sample[Cisco-IOS-XR-manageability-perfmgmt-oper:sample-id = ' + str(self.sample_id) + ']'
def is_config(self):
''' Returns True if this instance represents config data else returns False '''
return False
def _has_data(self):
if self.sample_id is not None:
return True
if self.average_cpu_used is not None:
return True
if self.no_processes is not None:
return True
if self.time_stamp is not None:
return True
return False
@staticmethod
def _meta_info():
from ydk.models.cisco_ios_xr._meta import _Cisco_IOS_XR_manageability_perfmgmt_oper as meta
return meta._meta_table['PerfMgmt.Monitor.Nodes.Node.SampleXr.Sample']['meta_info']
@property
def _common_path(self):
if self.parent is None:
raise YPYModelError('parent is not set . Cannot derive path.')
return self.parent._common_path +'/Cisco-IOS-XR-manageability-perfmgmt-oper:sample-xr'
def is_config(self):
''' Returns True if this instance represents config data else returns False '''
return False
def _has_data(self):
if self.sample is not None:
for child_ref in self.sample:
if child_ref._has_data():
return True
return False
@staticmethod
def _meta_info():
from ydk.models.cisco_ios_xr._meta import _Cisco_IOS_XR_manageability_perfmgmt_oper as meta
return meta._meta_table['PerfMgmt.Monitor.Nodes.Node.SampleXr']['meta_info']
class Processes(object):
"""
Processes data
.. attribute:: process
Process data
**type**\: list of :py:class:`Process <ydk.models.cisco_ios_xr.Cisco_IOS_XR_manageability_perfmgmt_oper.PerfMgmt.Monitor.Nodes.Node.Processes.Process>`
"""
_prefix = 'manageability-perfmgmt-oper'
_revision = '2015-11-09'
def __init__(self):
self.parent = None
self.process = YList()
self.process.parent = self
self.process.name = 'process'
class Process(object):
"""
Process data
.. attribute:: process_id <key>
Process ID
**type**\: int
**range:** \-2147483648..2147483647
.. attribute:: samples
Process data
**type**\: :py:class:`Samples <ydk.models.cisco_ios_xr.Cisco_IOS_XR_manageability_perfmgmt_oper.PerfMgmt.Monitor.Nodes.Node.Processes.Process.Samples>`
"""
_prefix = 'manageability-perfmgmt-oper'
_revision = '2015-11-09'
def __init__(self):
self.parent = None
self.process_id = None
self.samples = PerfMgmt.Monitor.Nodes.Node.Processes.Process.Samples()
self.samples.parent = self
class Samples(object):
"""
Process data
.. attribute:: sample
Process data sample
**type**\: list of :py:class:`Sample <ydk.models.cisco_ios_xr.Cisco_IOS_XR_manageability_perfmgmt_oper.PerfMgmt.Monitor.Nodes.Node.Processes.Process.Samples.Sample>`
"""
_prefix = 'manageability-perfmgmt-oper'
_revision = '2015-11-09'
def __init__(self):
self.parent = None
self.sample = YList()
self.sample.parent = self
self.sample.name = 'sample'
class Sample(object):
"""
Process data sample
.. attribute:: sample_id <key>
Sample ID
**type**\: int
**range:** \-2147483648..2147483647
.. attribute:: average_cpu_used
Average %CPU utilization
**type**\: int
**range:** 0..4294967295
.. attribute:: no_threads
Number of threads
**type**\: int
**range:** 0..4294967295
.. attribute:: peak_memory
Max. dynamic memory (KBytes) used since startup time
**type**\: int
**range:** 0..4294967295
**units**\: kilobyte
.. attribute:: time_stamp
Timestamp of sample in seconds drom UCT
**type**\: int
**range:** 0..18446744073709551615
**units**\: second
"""
_prefix = 'manageability-perfmgmt-oper'
_revision = '2015-11-09'
def __init__(self):
self.parent = None
self.sample_id = None
self.average_cpu_used = None
self.no_threads = None
self.peak_memory = None
self.time_stamp = None
@property
def _common_path(self):
if self.parent is None:
raise YPYModelError('parent is not set . Cannot derive path.')
if self.sample_id is None:
raise YPYModelError('Key property sample_id is None')
return self.parent._common_path +'/Cisco-IOS-XR-manageability-perfmgmt-oper:sample[Cisco-IOS-XR-manageability-perfmgmt-oper:sample-id = ' + str(self.sample_id) + ']'
def is_config(self):
''' Returns True if this instance represents config data else returns False '''
return False
def _has_data(self):
if self.sample_id is not None:
return True
if self.average_cpu_used is not None:
return True
if self.no_threads is not None:
return True
if self.peak_memory is not None:
return True
if self.time_stamp is not None:
return True
return False
@staticmethod
def _meta_info():
from ydk.models.cisco_ios_xr._meta import _Cisco_IOS_XR_manageability_perfmgmt_oper as meta
return meta._meta_table['PerfMgmt.Monitor.Nodes.Node.Processes.Process.Samples.Sample']['meta_info']
@property
def _common_path(self):
if self.parent is None:
raise YPYModelError('parent is not set . Cannot derive path.')
return self.parent._common_path +'/Cisco-IOS-XR-manageability-perfmgmt-oper:samples'
def is_config(self):
''' Returns True if this instance represents config data else returns False '''
return False
def _has_data(self):
if self.sample is not None:
for child_ref in self.sample:
if child_ref._has_data():
return True
return False
@staticmethod
def _meta_info():
from ydk.models.cisco_ios_xr._meta import _Cisco_IOS_XR_manageability_perfmgmt_oper as meta
return meta._meta_table['PerfMgmt.Monitor.Nodes.Node.Processes.Process.Samples']['meta_info']
@property
def _common_path(self):
if self.parent is None:
raise YPYModelError('parent is not set . Cannot derive path.')
if self.process_id is None:
raise YPYModelError('Key property process_id is None')
return self.parent._common_path +'/Cisco-IOS-XR-manageability-perfmgmt-oper:process[Cisco-IOS-XR-manageability-perfmgmt-oper:process-id = ' + str(self.process_id) + ']'
def is_config(self):
''' Returns True if this instance represents config data else returns False '''
return False
def _has_data(self):
if self.process_id is not None:
return True
if self.samples is not None and self.samples._has_data():
return True
return False
@staticmethod
def _meta_info():
from ydk.models.cisco_ios_xr._meta import _Cisco_IOS_XR_manageability_perfmgmt_oper as meta
return meta._meta_table['PerfMgmt.Monitor.Nodes.Node.Processes.Process']['meta_info']
@property
def _common_path(self):
if self.parent is None:
raise YPYModelError('parent is not set . Cannot derive path.')
return self.parent._common_path +'/Cisco-IOS-XR-manageability-perfmgmt-oper:processes'
def is_config(self):
''' Returns True if this instance represents config data else returns False '''
return False
def _has_data(self):
if self.process is not None:
for child_ref in self.process:
if child_ref._has_data():
return True
return False
@staticmethod
def _meta_info():
from ydk.models.cisco_ios_xr._meta import _Cisco_IOS_XR_manageability_perfmgmt_oper as meta
return meta._meta_table['PerfMgmt.Monitor.Nodes.Node.Processes']['meta_info']
class Samples(object):
"""
Node Memory data
.. attribute:: sample
Node Memory data sample
**type**\: list of :py:class:`Sample <ydk.models.cisco_ios_xr.Cisco_IOS_XR_manageability_perfmgmt_oper.PerfMgmt.Monitor.Nodes.Node.Samples.Sample>`
"""
_prefix = 'manageability-perfmgmt-oper'
_revision = '2015-11-09'
def __init__(self):
self.parent = None
self.sample = YList()
self.sample.parent = self
self.sample.name = 'sample'
class Sample(object):
"""
Node Memory data sample
.. attribute:: sample_id <key>
Sample ID
**type**\: int
**range:** \-2147483648..2147483647
.. attribute:: curr_memory
Current application memory (Bytes) in use
**type**\: int
**range:** 0..4294967295
**units**\: byte
.. attribute:: peak_memory
Max. system memory (MBytes) used since bootup
**type**\: int
**range:** 0..4294967295
**units**\: megabyte
.. attribute:: time_stamp
Timestamp of sample in seconds drom UCT
**type**\: int
**range:** 0..18446744073709551615
**units**\: second
"""
_prefix = 'manageability-perfmgmt-oper'
_revision = '2015-11-09'
def __init__(self):
self.parent = None
self.sample_id = None
self.curr_memory = None
self.peak_memory = None
self.time_stamp = None
@property
def _common_path(self):
if self.parent is None:
raise YPYModelError('parent is not set . Cannot derive path.')
if self.sample_id is None:
raise YPYModelError('Key property sample_id is None')
return self.parent._common_path +'/Cisco-IOS-XR-manageability-perfmgmt-oper:sample[Cisco-IOS-XR-manageability-perfmgmt-oper:sample-id = ' + str(self.sample_id) + ']'
def is_config(self):
''' Returns True if this instance represents config data else returns False '''
return False
def _has_data(self):
if self.sample_id is not None:
return True
if self.curr_memory is not None:
return True
if self.peak_memory is not None:
return True
if self.time_stamp is not None:
return True
return False
@staticmethod
def _meta_info():
from ydk.models.cisco_ios_xr._meta import _Cisco_IOS_XR_manageability_perfmgmt_oper as meta
return meta._meta_table['PerfMgmt.Monitor.Nodes.Node.Samples.Sample']['meta_info']
@property
def _common_path(self):
if self.parent is None:
raise YPYModelError('parent is not set . Cannot derive path.')
return self.parent._common_path +'/Cisco-IOS-XR-manageability-perfmgmt-oper:samples'
def is_config(self):
''' Returns True if this instance represents config data else returns False '''
return False
def _has_data(self):
if self.sample is not None:
for child_ref in self.sample:
if child_ref._has_data():
return True
return False
@staticmethod
def _meta_info():
from ydk.models.cisco_ios_xr._meta import _Cisco_IOS_XR_manageability_perfmgmt_oper as meta
return meta._meta_table['PerfMgmt.Monitor.Nodes.Node.Samples']['meta_info']
@property
def _common_path(self):
if self.node_id is None:
raise YPYModelError('Key property node_id is None')
return '/Cisco-IOS-XR-manageability-perfmgmt-oper:perf-mgmt/Cisco-IOS-XR-manageability-perfmgmt-oper:monitor/Cisco-IOS-XR-manageability-perfmgmt-oper:nodes/Cisco-IOS-XR-manageability-perfmgmt-oper:node[Cisco-IOS-XR-manageability-perfmgmt-oper:node-id = ' + str(self.node_id) + ']'
def is_config(self):
''' Returns True if this instance represents config data else returns False '''
return False
def _has_data(self):
if self.node_id is not None:
return True
if self.processes is not None and self.processes._has_data():
return True
if self.sample_xr is not None and self.sample_xr._has_data():
return True
if self.samples is not None and self.samples._has_data():
return True
return False
@staticmethod
def _meta_info():
from ydk.models.cisco_ios_xr._meta import _Cisco_IOS_XR_manageability_perfmgmt_oper as meta
return meta._meta_table['PerfMgmt.Monitor.Nodes.Node']['meta_info']
@property
def _common_path(self):
return '/Cisco-IOS-XR-manageability-perfmgmt-oper:perf-mgmt/Cisco-IOS-XR-manageability-perfmgmt-oper:monitor/Cisco-IOS-XR-manageability-perfmgmt-oper:nodes'
def is_config(self):
''' Returns True if this instance represents config data else returns False '''
return False
def _has_data(self):
if self.node is not None:
for child_ref in self.node:
if child_ref._has_data():
return True
return False
@staticmethod
def _meta_info():
from ydk.models.cisco_ios_xr._meta import _Cisco_IOS_XR_manageability_perfmgmt_oper as meta
return meta._meta_table['PerfMgmt.Monitor.Nodes']['meta_info']
class Bgp(object):
"""
Collected BGP data
.. attribute:: bgp_neighbors
Neighbors for which statistics are collected
**type**\: :py:class:`BgpNeighbors <ydk.models.cisco_ios_xr.Cisco_IOS_XR_manageability_perfmgmt_oper.PerfMgmt.Monitor.Bgp.BgpNeighbors>`
"""
_prefix = 'manageability-perfmgmt-oper'
_revision = '2015-11-09'
def __init__(self):
self.parent = None
self.bgp_neighbors = PerfMgmt.Monitor.Bgp.BgpNeighbors()
self.bgp_neighbors.parent = self
class BgpNeighbors(object):
"""
Neighbors for which statistics are collected
.. attribute:: bgp_neighbor
Samples for particular neighbor
**type**\: list of :py:class:`BgpNeighbor <ydk.models.cisco_ios_xr.Cisco_IOS_XR_manageability_perfmgmt_oper.PerfMgmt.Monitor.Bgp.BgpNeighbors.BgpNeighbor>`
"""
_prefix = 'manageability-perfmgmt-oper'
_revision = '2015-11-09'
def __init__(self):
self.parent = None
self.bgp_neighbor = YList()
self.bgp_neighbor.parent = self
self.bgp_neighbor.name = 'bgp_neighbor'
class BgpNeighbor(object):
"""
Samples for particular neighbor
.. attribute:: ip_address <key>
BGP Neighbor Identifier
**type**\: str
**pattern:** (([0\-9]\|[1\-9][0\-9]\|1[0\-9][0\-9]\|2[0\-4][0\-9]\|25[0\-5])\\.){3}([0\-9]\|[1\-9][0\-9]\|1[0\-9][0\-9]\|2[0\-4][0\-9]\|25[0\-5])(%[\\p{N}\\p{L}]+)?
.. attribute:: samples
Sample Table for a BGP neighbor
**type**\: :py:class:`Samples <ydk.models.cisco_ios_xr.Cisco_IOS_XR_manageability_perfmgmt_oper.PerfMgmt.Monitor.Bgp.BgpNeighbors.BgpNeighbor.Samples>`
"""
_prefix = 'manageability-perfmgmt-oper'
_revision = '2015-11-09'
def __init__(self):
self.parent = None
self.ip_address = None
self.samples = PerfMgmt.Monitor.Bgp.BgpNeighbors.BgpNeighbor.Samples()
self.samples.parent = self
class Samples(object):
"""
Sample Table for a BGP neighbor
.. attribute:: sample
Neighbor statistics sample
**type**\: list of :py:class:`Sample <ydk.models.cisco_ios_xr.Cisco_IOS_XR_manageability_perfmgmt_oper.PerfMgmt.Monitor.Bgp.BgpNeighbors.BgpNeighbor.Samples.Sample>`
"""
_prefix = 'manageability-perfmgmt-oper'
_revision = '2015-11-09'
def __init__(self):
self.parent = None
self.sample = YList()
self.sample.parent = self
self.sample.name = 'sample'
class Sample(object):
"""
Neighbor statistics sample
.. attribute:: sample_id <key>
Sample ID
**type**\: int
**range:** \-2147483648..2147483647
.. attribute:: conn_dropped
Number of times connection was dropped
**type**\: int
**range:** 0..4294967295
.. attribute:: conn_established
Number of times the connection was established
**type**\: int
**range:** 0..4294967295
.. attribute:: errors_received
Number of error notifications received on the connection
**type**\: int
**range:** 0..4294967295
.. attribute:: errors_sent
Number of error notifications sent on the connection
**type**\: int
**range:** 0..4294967295
.. attribute:: input_messages
Number of messages received
**type**\: int
**range:** 0..4294967295
.. attribute:: input_update_messages
Number of update messages received
**type**\: int
**range:** 0..4294967295
.. attribute:: output_messages
Number of messages sent
**type**\: int
**range:** 0..4294967295
.. attribute:: output_update_messages
Number of update messages sent
**type**\: int
**range:** 0..4294967295
.. attribute:: time_stamp
Timestamp of sample in seconds drom UCT
**type**\: int
**range:** 0..18446744073709551615
**units**\: second
"""
_prefix = 'manageability-perfmgmt-oper'
_revision = '2015-11-09'
def __init__(self):
self.parent = None
self.sample_id = None
self.conn_dropped = None
self.conn_established = None
self.errors_received = None
self.errors_sent = None
self.input_messages = None
self.input_update_messages = None
self.output_messages = None
self.output_update_messages = None
self.time_stamp = None
@property
def _common_path(self):
if self.parent is None:
raise YPYModelError('parent is not set . Cannot derive path.')
if self.sample_id is None:
raise YPYModelError('Key property sample_id is None')
return self.parent._common_path +'/Cisco-IOS-XR-manageability-perfmgmt-oper:sample[Cisco-IOS-XR-manageability-perfmgmt-oper:sample-id = ' + str(self.sample_id) + ']'
def is_config(self):
''' Returns True if this instance represents config data else returns False '''
return False
def _has_data(self):
if self.sample_id is not None:
return True
if self.conn_dropped is not None:
return True
if self.conn_established is not None:
return True
if self.errors_received is not None:
return True
if self.errors_sent is not None:
return True
if self.input_messages is not None:
return True
if self.input_update_messages is not None:
return True
if self.output_messages is not None:
return True
if self.output_update_messages is not None:
return True
if self.time_stamp is not None:
return True
return False
@staticmethod
def _meta_info():
from ydk.models.cisco_ios_xr._meta import _Cisco_IOS_XR_manageability_perfmgmt_oper as meta
return meta._meta_table['PerfMgmt.Monitor.Bgp.BgpNeighbors.BgpNeighbor.Samples.Sample']['meta_info']
@property
def _common_path(self):
if self.parent is None:
raise YPYModelError('parent is not set . Cannot derive path.')
return self.parent._common_path +'/Cisco-IOS-XR-manageability-perfmgmt-oper:samples'
def is_config(self):
''' Returns True if this instance represents config data else returns False '''
return False
def _has_data(self):
if self.sample is not None:
for child_ref in self.sample:
if child_ref._has_data():
return True
return False
@staticmethod
def _meta_info():
from ydk.models.cisco_ios_xr._meta import _Cisco_IOS_XR_manageability_perfmgmt_oper as meta
return meta._meta_table['PerfMgmt.Monitor.Bgp.BgpNeighbors.BgpNeighbor.Samples']['meta_info']
@property
def _common_path(self):
if self.ip_address is None:
raise YPYModelError('Key property ip_address is None')
return '/Cisco-IOS-XR-manageability-perfmgmt-oper:perf-mgmt/Cisco-IOS-XR-manageability-perfmgmt-oper:monitor/Cisco-IOS-XR-manageability-perfmgmt-oper:bgp/Cisco-IOS-XR-manageability-perfmgmt-oper:bgp-neighbors/Cisco-IOS-XR-manageability-perfmgmt-oper:bgp-neighbor[Cisco-IOS-XR-manageability-perfmgmt-oper:ip-address = ' + str(self.ip_address) + ']'
def is_config(self):
''' Returns True if this instance represents config data else returns False '''
return False
def _has_data(self):
if self.ip_address is not None:
return True
if self.samples is not None and self.samples._has_data():
return True
return False
@staticmethod
def _meta_info():
from ydk.models.cisco_ios_xr._meta import _Cisco_IOS_XR_manageability_perfmgmt_oper as meta
return meta._meta_table['PerfMgmt.Monitor.Bgp.BgpNeighbors.BgpNeighbor']['meta_info']
@property
def _common_path(self):
return '/Cisco-IOS-XR-manageability-perfmgmt-oper:perf-mgmt/Cisco-IOS-XR-manageability-perfmgmt-oper:monitor/Cisco-IOS-XR-manageability-perfmgmt-oper:bgp/Cisco-IOS-XR-manageability-perfmgmt-oper:bgp-neighbors'
def is_config(self):
''' Returns True if this instance represents config data else returns False '''
return False
def _has_data(self):
if self.bgp_neighbor is not None:
for child_ref in self.bgp_neighbor:
if child_ref._has_data():
return True
return False
@staticmethod
def _meta_info():
from ydk.models.cisco_ios_xr._meta import _Cisco_IOS_XR_manageability_perfmgmt_oper as meta
return meta._meta_table['PerfMgmt.Monitor.Bgp.BgpNeighbors']['meta_info']
@property
def _common_path(self):
return '/Cisco-IOS-XR-manageability-perfmgmt-oper:perf-mgmt/Cisco-IOS-XR-manageability-perfmgmt-oper:monitor/Cisco-IOS-XR-manageability-perfmgmt-oper:bgp'
def is_config(self):
''' Returns True if this instance represents config data else returns False '''
return False
def _has_data(self):
if self.bgp_neighbors is not None and self.bgp_neighbors._has_data():
return True
return False
@staticmethod
def _meta_info():
from ydk.models.cisco_ios_xr._meta import _Cisco_IOS_XR_manageability_perfmgmt_oper as meta
return meta._meta_table['PerfMgmt.Monitor.Bgp']['meta_info']
class Interface(object):
"""
Collected Interface data
.. attribute:: basic_counter_interfaces
Interfaces for which Basic Counters are collected
**type**\: :py:class:`BasicCounterInterfaces <ydk.models.cisco_ios_xr.Cisco_IOS_XR_manageability_perfmgmt_oper.PerfMgmt.Monitor.Interface.BasicCounterInterfaces>`
.. attribute:: data_rate_interfaces
Interfaces for which Data Rates are collected
**type**\: :py:class:`DataRateInterfaces <ydk.models.cisco_ios_xr.Cisco_IOS_XR_manageability_perfmgmt_oper.PerfMgmt.Monitor.Interface.DataRateInterfaces>`
.. attribute:: generic_counter_interfaces
Interfaces for which Generic Counters are collected
**type**\: :py:class:`GenericCounterInterfaces <ydk.models.cisco_ios_xr.Cisco_IOS_XR_manageability_perfmgmt_oper.PerfMgmt.Monitor.Interface.GenericCounterInterfaces>`
"""
_prefix = 'manageability-perfmgmt-oper'
_revision = '2015-11-09'
def __init__(self):
self.parent = None
self.basic_counter_interfaces = PerfMgmt.Monitor.Interface.BasicCounterInterfaces()
self.basic_counter_interfaces.parent = self
self.data_rate_interfaces = PerfMgmt.Monitor.Interface.DataRateInterfaces()
self.data_rate_interfaces.parent = self
self.generic_counter_interfaces = PerfMgmt.Monitor.Interface.GenericCounterInterfaces()
self.generic_counter_interfaces.parent = self
class GenericCounterInterfaces(object):
"""
Interfaces for which Generic Counters are
collected
.. attribute:: generic_counter_interface
Samples for a particular interface
**type**\: list of :py:class:`GenericCounterInterface <ydk.models.cisco_ios_xr.Cisco_IOS_XR_manageability_perfmgmt_oper.PerfMgmt.Monitor.Interface.GenericCounterInterfaces.GenericCounterInterface>`
"""
_prefix = 'manageability-perfmgmt-oper'
_revision = '2015-11-09'
def __init__(self):
self.parent = None
self.generic_counter_interface = YList()
self.generic_counter_interface.parent = self
self.generic_counter_interface.name = 'generic_counter_interface'
class GenericCounterInterface(object):
"""
Samples for a particular interface
.. attribute:: interface_name <key>
Interface Name
**type**\: str
**pattern:** (([a\-zA\-Z0\-9\_]\*\\d+/){3,4}\\d+)\|(([a\-zA\-Z0\-9\_]\*\\d+/){3,4}\\d+\\.\\d+)\|(([a\-zA\-Z0\-9\_]\*\\d+/){2}([a\-zA\-Z0\-9\_]\*\\d+))\|(([a\-zA\-Z0\-9\_]\*\\d+/){2}([a\-zA\-Z0\-9\_]+))\|([a\-zA\-Z0\-9\_\-]\*\\d+)\|([a\-zA\-Z0\-9\_\-]\*\\d+\\.\\d+)\|(mpls)\|(dwdm)
.. attribute:: samples
Generic Counter samples for an interface
**type**\: :py:class:`Samples <ydk.models.cisco_ios_xr.Cisco_IOS_XR_manageability_perfmgmt_oper.PerfMgmt.Monitor.Interface.GenericCounterInterfaces.GenericCounterInterface.Samples>`
"""
_prefix = 'manageability-perfmgmt-oper'
_revision = '2015-11-09'
def __init__(self):
self.parent = None
self.interface_name = None
self.samples = PerfMgmt.Monitor.Interface.GenericCounterInterfaces.GenericCounterInterface.Samples()
self.samples.parent = self
class Samples(object):
"""
Generic Counter samples for an interface
.. attribute:: sample
Generic Counters sample
**type**\: list of :py:class:`Sample <ydk.models.cisco_ios_xr.Cisco_IOS_XR_manageability_perfmgmt_oper.PerfMgmt.Monitor.Interface.GenericCounterInterfaces.GenericCounterInterface.Samples.Sample>`
"""
_prefix = 'manageability-perfmgmt-oper'
_revision = '2015-11-09'
def __init__(self):
self.parent = None
self.sample = YList()
self.sample.parent = self
self.sample.name = 'sample'
class Sample(object):
"""
Generic Counters sample
.. attribute:: sample_id <key>
Sample ID
**type**\: int
**range:** \-2147483648..2147483647
.. attribute:: in_broadcast_pkts
Broadcast packets received
**type**\: int
**range:** 0..18446744073709551615
.. attribute:: in_multicast_pkts
Multicast packets received
**type**\: int
**range:** 0..18446744073709551615
.. attribute:: in_octets
Bytes received
**type**\: int
**range:** 0..18446744073709551615
**units**\: byte
.. attribute:: in_packets
Packets received
**type**\: int
**range:** 0..18446744073709551615
.. attribute:: in_ucast_pkts
Unicast packets received
**type**\: int
**range:** 0..18446744073709551615
.. attribute:: input_crc
Inbound packets discarded with incorrect CRC
**type**\: int
**range:** 0..4294967295
.. attribute:: input_frame
Inbound framing errors
**type**\: int
**range:** 0..4294967295
.. attribute:: input_overrun
Input overruns
**type**\: int
**range:** 0..4294967295
.. attribute:: input_queue_drops
Input queue drops
**type**\: int
**range:** 0..4294967295
.. attribute:: input_total_drops
Inbound correct packets discarded
**type**\: int
**range:** 0..4294967295
.. attribute:: input_total_errors
Inbound incorrect packets discarded
**type**\: int
**range:** 0..4294967295
.. attribute:: input_unknown_proto
Inbound packets discarded with unknown proto
**type**\: int
**range:** 0..4294967295
.. attribute:: out_broadcast_pkts
Broadcast packets sent
**type**\: int
**range:** 0..18446744073709551615
.. attribute:: out_multicast_pkts
Multicast packets sent
**type**\: int
**range:** 0..18446744073709551615
.. attribute:: out_octets
Bytes sent
**type**\: int
**range:** 0..18446744073709551615
**units**\: byte
.. attribute:: out_packets
Packets sent
**type**\: int
**range:** 0..18446744073709551615
.. attribute:: out_ucast_pkts
Unicast packets sent
**type**\: int
**range:** 0..18446744073709551615
.. attribute:: output_total_drops
Outbound correct packets discarded
**type**\: int
**range:** 0..4294967295
.. attribute:: output_total_errors
Outbound incorrect packets discarded
**type**\: int
**range:** 0..4294967295
.. attribute:: output_underrun
Output underruns
**type**\: int
**range:** 0..4294967295
.. attribute:: time_stamp
Timestamp of sample in seconds drom UCT
**type**\: int
**range:** 0..18446744073709551615
**units**\: second
"""
_prefix = 'manageability-perfmgmt-oper'
_revision = '2015-11-09'
def __init__(self):
self.parent = None
self.sample_id = None
self.in_broadcast_pkts = None
self.in_multicast_pkts = None
self.in_octets = None
self.in_packets = None
self.in_ucast_pkts = None
self.input_crc = None
self.input_frame = None
self.input_overrun = None
self.input_queue_drops = None
self.input_total_drops = None
self.input_total_errors = None
self.input_unknown_proto = None
self.out_broadcast_pkts = None
self.out_multicast_pkts = None
self.out_octets = None
self.out_packets = None
self.out_ucast_pkts = None
self.output_total_drops = None
self.output_total_errors = None
self.output_underrun = None
self.time_stamp = None
@property
def _common_path(self):
if self.parent is None:
raise YPYModelError('parent is not set . Cannot derive path.')
if self.sample_id is None:
raise YPYModelError('Key property sample_id is None')
return self.parent._common_path +'/Cisco-IOS-XR-manageability-perfmgmt-oper:sample[Cisco-IOS-XR-manageability-perfmgmt-oper:sample-id = ' + str(self.sample_id) + ']'
def is_config(self):
''' Returns True if this instance represents config data else returns False '''
return False
def _has_data(self):
if self.sample_id is not None:
return True
if self.in_broadcast_pkts is not None:
return True
if self.in_multicast_pkts is not None:
return True
if self.in_octets is not None:
return True
if self.in_packets is not None:
return True
if self.in_ucast_pkts is not None:
return True
if self.input_crc is not None:
return True
if self.input_frame is not None:
return True
if self.input_overrun is not None:
return True
if self.input_queue_drops is not None:
return True
if self.input_total_drops is not None:
return True
if self.input_total_errors is not None:
return True
if self.input_unknown_proto is not None:
return True
if self.out_broadcast_pkts is not None:
return True
if self.out_multicast_pkts is not None:
return True
if self.out_octets is not None:
return True
if self.out_packets is not None:
return True
if self.out_ucast_pkts is not None:
return True
if self.output_total_drops is not None:
return True
if self.output_total_errors is not None:
return True
if self.output_underrun is not None:
return True
if self.time_stamp is not None:
return True
return False
@staticmethod
def _meta_info():
from ydk.models.cisco_ios_xr._meta import _Cisco_IOS_XR_manageability_perfmgmt_oper as meta
return meta._meta_table['PerfMgmt.Monitor.Interface.GenericCounterInterfaces.GenericCounterInterface.Samples.Sample']['meta_info']
@property
def _common_path(self):
if self.parent is None:
raise YPYModelError('parent is not set . Cannot derive path.')
return self.parent._common_path +'/Cisco-IOS-XR-manageability-perfmgmt-oper:samples'
def is_config(self):
''' Returns True if this instance represents config data else returns False '''
return False
def _has_data(self):
if self.sample is not None:
for child_ref in self.sample:
if child_ref._has_data():
return True
return False
@staticmethod
def _meta_info():
from ydk.models.cisco_ios_xr._meta import _Cisco_IOS_XR_manageability_perfmgmt_oper as meta
return meta._meta_table['PerfMgmt.Monitor.Interface.GenericCounterInterfaces.GenericCounterInterface.Samples']['meta_info']
@property
def _common_path(self):
if self.interface_name is None:
raise YPYModelError('Key property interface_name is None')
return '/Cisco-IOS-XR-manageability-perfmgmt-oper:perf-mgmt/Cisco-IOS-XR-manageability-perfmgmt-oper:monitor/Cisco-IOS-XR-manageability-perfmgmt-oper:interface/Cisco-IOS-XR-manageability-perfmgmt-oper:generic-counter-interfaces/Cisco-IOS-XR-manageability-perfmgmt-oper:generic-counter-interface[Cisco-IOS-XR-manageability-perfmgmt-oper:interface-name = ' + str(self.interface_name) + ']'
def is_config(self):
''' Returns True if this instance represents config data else returns False '''
return False
def _has_data(self):
if self.interface_name is not None:
return True
if self.samples is not None and self.samples._has_data():
return True
return False
@staticmethod
def _meta_info():
from ydk.models.cisco_ios_xr._meta import _Cisco_IOS_XR_manageability_perfmgmt_oper as meta
return meta._meta_table['PerfMgmt.Monitor.Interface.GenericCounterInterfaces.GenericCounterInterface']['meta_info']
@property
def _common_path(self):
return '/Cisco-IOS-XR-manageability-perfmgmt-oper:perf-mgmt/Cisco-IOS-XR-manageability-perfmgmt-oper:monitor/Cisco-IOS-XR-manageability-perfmgmt-oper:interface/Cisco-IOS-XR-manageability-perfmgmt-oper:generic-counter-interfaces'
def is_config(self):
''' Returns True if this instance represents config data else returns False '''
return False
def _has_data(self):
if self.generic_counter_interface is not None:
for child_ref in self.generic_counter_interface:
if child_ref._has_data():
return True
return False
@staticmethod
def _meta_info():
from ydk.models.cisco_ios_xr._meta import _Cisco_IOS_XR_manageability_perfmgmt_oper as meta
return meta._meta_table['PerfMgmt.Monitor.Interface.GenericCounterInterfaces']['meta_info']
class BasicCounterInterfaces(object):
"""
Interfaces for which Basic Counters are
collected
.. attribute:: basic_counter_interface
Samples for a particular interface
**type**\: list of :py:class:`BasicCounterInterface <ydk.models.cisco_ios_xr.Cisco_IOS_XR_manageability_perfmgmt_oper.PerfMgmt.Monitor.Interface.BasicCounterInterfaces.BasicCounterInterface>`
"""
_prefix = 'manageability-perfmgmt-oper'
_revision = '2015-11-09'
def __init__(self):
self.parent = None
self.basic_counter_interface = YList()
self.basic_counter_interface.parent = self
self.basic_counter_interface.name = 'basic_counter_interface'
class BasicCounterInterface(object):
"""
Samples for a particular interface
.. attribute:: interface_name <key>
Interface Name
**type**\: str
**pattern:** (([a\-zA\-Z0\-9\_]\*\\d+/){3,4}\\d+)\|(([a\-zA\-Z0\-9\_]\*\\d+/){3,4}\\d+\\.\\d+)\|(([a\-zA\-Z0\-9\_]\*\\d+/){2}([a\-zA\-Z0\-9\_]\*\\d+))\|(([a\-zA\-Z0\-9\_]\*\\d+/){2}([a\-zA\-Z0\-9\_]+))\|([a\-zA\-Z0\-9\_\-]\*\\d+)\|([a\-zA\-Z0\-9\_\-]\*\\d+\\.\\d+)\|(mpls)\|(dwdm)
.. attribute:: samples
Basic Counter samples for an interface
**type**\: :py:class:`Samples <ydk.models.cisco_ios_xr.Cisco_IOS_XR_manageability_perfmgmt_oper.PerfMgmt.Monitor.Interface.BasicCounterInterfaces.BasicCounterInterface.Samples>`
"""
_prefix = 'manageability-perfmgmt-oper'
_revision = '2015-11-09'
def __init__(self):
self.parent = None
self.interface_name = None
self.samples = PerfMgmt.Monitor.Interface.BasicCounterInterfaces.BasicCounterInterface.Samples()
self.samples.parent = self
class Samples(object):
"""
Basic Counter samples for an interface
.. attribute:: sample
Basic Counters sample
**type**\: list of :py:class:`Sample <ydk.models.cisco_ios_xr.Cisco_IOS_XR_manageability_perfmgmt_oper.PerfMgmt.Monitor.Interface.BasicCounterInterfaces.BasicCounterInterface.Samples.Sample>`
"""
_prefix = 'manageability-perfmgmt-oper'
_revision = '2015-11-09'
def __init__(self):
self.parent = None
self.sample = YList()
self.sample.parent = self
self.sample.name = 'sample'
class Sample(object):
"""
Basic Counters sample
.. attribute:: sample_id <key>
Sample ID
**type**\: int
**range:** \-2147483648..2147483647
.. attribute:: in_octets
Bytes received
**type**\: int
**range:** 0..18446744073709551615
**units**\: byte
.. attribute:: in_packets
Packets received
**type**\: int
**range:** 0..18446744073709551615
.. attribute:: input_queue_drops
Input queue drops
**type**\: int
**range:** 0..18446744073709551615
.. attribute:: input_total_drops
Inbound correct packets discarded
**type**\: int
**range:** 0..18446744073709551615
.. attribute:: input_total_errors
Inbound incorrect packets discarded
**type**\: int
**range:** 0..18446744073709551615
.. attribute:: out_octets
Bytes sent
**type**\: int
**range:** 0..18446744073709551615
**units**\: byte
.. attribute:: out_packets
Packets sent
**type**\: int
**range:** 0..18446744073709551615
.. attribute:: output_queue_drops
Output queue drops
**type**\: int
**range:** 0..18446744073709551615
.. attribute:: output_total_drops
Outbound correct packets discarded
**type**\: int
**range:** 0..18446744073709551615
.. attribute:: output_total_errors
Outbound incorrect packets discarded
**type**\: int
**range:** 0..18446744073709551615
.. attribute:: time_stamp
Timestamp of sample in seconds from UCT
**type**\: int
**range:** 0..18446744073709551615
**units**\: second
"""
_prefix = 'manageability-perfmgmt-oper'
_revision = '2015-11-09'
def __init__(self):
self.parent = None
self.sample_id = None
self.in_octets = None
self.in_packets = None
self.input_queue_drops = None
self.input_total_drops = None
self.input_total_errors = None
self.out_octets = None
self.out_packets = None
self.output_queue_drops = None
self.output_total_drops = None
self.output_total_errors = None
self.time_stamp = None
@property
def _common_path(self):
if self.parent is None:
raise YPYModelError('parent is not set . Cannot derive path.')
if self.sample_id is None:
raise YPYModelError('Key property sample_id is None')
return self.parent._common_path +'/Cisco-IOS-XR-manageability-perfmgmt-oper:sample[Cisco-IOS-XR-manageability-perfmgmt-oper:sample-id = ' + str(self.sample_id) + ']'
def is_config(self):
''' Returns True if this instance represents config data else returns False '''
return False
def _has_data(self):
if self.sample_id is not None:
return True
if self.in_octets is not None:
return True
if self.in_packets is not None:
return True
if self.input_queue_drops is not None:
return True
if self.input_total_drops is not None:
return True
if self.input_total_errors is not None:
return True
if self.out_octets is not None:
return True
if self.out_packets is not None:
return True
if self.output_queue_drops is not None:
return True
if self.output_total_drops is not None:
return True
if self.output_total_errors is not None:
return True
if self.time_stamp is not None:
return True
return False
@staticmethod
def _meta_info():
from ydk.models.cisco_ios_xr._meta import _Cisco_IOS_XR_manageability_perfmgmt_oper as meta
return meta._meta_table['PerfMgmt.Monitor.Interface.BasicCounterInterfaces.BasicCounterInterface.Samples.Sample']['meta_info']
@property
def _common_path(self):
if self.parent is None:
raise YPYModelError('parent is not set . Cannot derive path.')
return self.parent._common_path +'/Cisco-IOS-XR-manageability-perfmgmt-oper:samples'
def is_config(self):
''' Returns True if this instance represents config data else returns False '''
return False
def _has_data(self):
if self.sample is not None:
for child_ref in self.sample:
if child_ref._has_data():
return True
return False
@staticmethod
def _meta_info():
from ydk.models.cisco_ios_xr._meta import _Cisco_IOS_XR_manageability_perfmgmt_oper as meta
return meta._meta_table['PerfMgmt.Monitor.Interface.BasicCounterInterfaces.BasicCounterInterface.Samples']['meta_info']
@property
def _common_path(self):
if self.interface_name is None:
raise YPYModelError('Key property interface_name is None')
return '/Cisco-IOS-XR-manageability-perfmgmt-oper:perf-mgmt/Cisco-IOS-XR-manageability-perfmgmt-oper:monitor/Cisco-IOS-XR-manageability-perfmgmt-oper:interface/Cisco-IOS-XR-manageability-perfmgmt-oper:basic-counter-interfaces/Cisco-IOS-XR-manageability-perfmgmt-oper:basic-counter-interface[Cisco-IOS-XR-manageability-perfmgmt-oper:interface-name = ' + str(self.interface_name) + ']'
def is_config(self):
''' Returns True if this instance represents config data else returns False '''
return False
def _has_data(self):
if self.interface_name is not None:
return True
if self.samples is not None and self.samples._has_data():
return True
return False
@staticmethod
def _meta_info():
from ydk.models.cisco_ios_xr._meta import _Cisco_IOS_XR_manageability_perfmgmt_oper as meta
return meta._meta_table['PerfMgmt.Monitor.Interface.BasicCounterInterfaces.BasicCounterInterface']['meta_info']
@property
def _common_path(self):
return '/Cisco-IOS-XR-manageability-perfmgmt-oper:perf-mgmt/Cisco-IOS-XR-manageability-perfmgmt-oper:monitor/Cisco-IOS-XR-manageability-perfmgmt-oper:interface/Cisco-IOS-XR-manageability-perfmgmt-oper:basic-counter-interfaces'
def is_config(self):
''' Returns True if this instance represents config data else returns False '''
return False
def _has_data(self):
if self.basic_counter_interface is not None:
for child_ref in self.basic_counter_interface:
if child_ref._has_data():
return True
return False
@staticmethod
def _meta_info():
from ydk.models.cisco_ios_xr._meta import _Cisco_IOS_XR_manageability_perfmgmt_oper as meta
return meta._meta_table['PerfMgmt.Monitor.Interface.BasicCounterInterfaces']['meta_info']
class DataRateInterfaces(object):
"""
Interfaces for which Data Rates are collected
.. attribute:: data_rate_interface
Samples for a particular interface
**type**\: list of :py:class:`DataRateInterface <ydk.models.cisco_ios_xr.Cisco_IOS_XR_manageability_perfmgmt_oper.PerfMgmt.Monitor.Interface.DataRateInterfaces.DataRateInterface>`
"""
_prefix = 'manageability-perfmgmt-oper'
_revision = '2015-11-09'
def __init__(self):
self.parent = None
self.data_rate_interface = YList()
self.data_rate_interface.parent = self
self.data_rate_interface.name = 'data_rate_interface'
class DataRateInterface(object):
"""
Samples for a particular interface
.. attribute:: interface_name <key>
Interface Name
**type**\: str
**pattern:** (([a\-zA\-Z0\-9\_]\*\\d+/){3,4}\\d+)\|(([a\-zA\-Z0\-9\_]\*\\d+/){3,4}\\d+\\.\\d+)\|(([a\-zA\-Z0\-9\_]\*\\d+/){2}([a\-zA\-Z0\-9\_]\*\\d+))\|(([a\-zA\-Z0\-9\_]\*\\d+/){2}([a\-zA\-Z0\-9\_]+))\|([a\-zA\-Z0\-9\_\-]\*\\d+)\|([a\-zA\-Z0\-9\_\-]\*\\d+\\.\\d+)\|(mpls)\|(dwdm)
.. attribute:: samples
Data Rate samples for an interface
**type**\: :py:class:`Samples <ydk.models.cisco_ios_xr.Cisco_IOS_XR_manageability_perfmgmt_oper.PerfMgmt.Monitor.Interface.DataRateInterfaces.DataRateInterface.Samples>`
"""
_prefix = 'manageability-perfmgmt-oper'
_revision = '2015-11-09'
def __init__(self):
self.parent = None
self.interface_name = None
self.samples = PerfMgmt.Monitor.Interface.DataRateInterfaces.DataRateInterface.Samples()
self.samples.parent = self
class Samples(object):
"""
Data Rate samples for an interface
.. attribute:: sample
Data Rates sample
**type**\: list of :py:class:`Sample <ydk.models.cisco_ios_xr.Cisco_IOS_XR_manageability_perfmgmt_oper.PerfMgmt.Monitor.Interface.DataRateInterfaces.DataRateInterface.Samples.Sample>`
"""
_prefix = 'manageability-perfmgmt-oper'
_revision = '2015-11-09'
def __init__(self):
self.parent = None
self.sample = YList()
self.sample.parent = self
self.sample.name = 'sample'
class Sample(object):
"""
Data Rates sample
.. attribute:: sample_id <key>
Sample ID
**type**\: int
**range:** \-2147483648..2147483647
.. attribute:: bandwidth
Bandwidth (in kbps)
**type**\: int
**range:** 0..4294967295
**units**\: kbit/s
.. attribute:: input_data_rate
Input datarate in 1000's of bps
**type**\: int
**range:** 0..4294967295
**units**\: bit/s
.. attribute:: input_packet_rate
Input packets per second
**type**\: int
**range:** 0..4294967295
**units**\: packet/s
.. attribute:: input_peak_pkts
Peak input packet rate
**type**\: int
**range:** 0..4294967295
.. attribute:: input_peak_rate
Peak input datarate
**type**\: int
**range:** 0..4294967295
.. attribute:: output_data_rate
Output datarate in 1000's of bps
**type**\: int
**range:** 0..4294967295
**units**\: bit/s
.. attribute:: output_packet_rate
Output packets per second
**type**\: int
**range:** 0..4294967295
**units**\: packet/s
.. attribute:: output_peak_pkts
Peak output packet rate
**type**\: int
**range:** 0..4294967295
.. attribute:: output_peak_rate
Peak output datarate
**type**\: int
**range:** 0..4294967295
.. attribute:: time_stamp
Timestamp of sample in seconds drom UCT
**type**\: int
**range:** 0..18446744073709551615
**units**\: second
"""
_prefix = 'manageability-perfmgmt-oper'
_revision = '2015-11-09'
def __init__(self):
self.parent = None
self.sample_id = None
self.bandwidth = None
self.input_data_rate = None
self.input_packet_rate = None
self.input_peak_pkts = None
self.input_peak_rate = None
self.output_data_rate = None
self.output_packet_rate = None
self.output_peak_pkts = None
self.output_peak_rate = None
self.time_stamp = None
@property
def _common_path(self):
if self.parent is None:
raise YPYModelError('parent is not set . Cannot derive path.')
if self.sample_id is None:
raise YPYModelError('Key property sample_id is None')
return self.parent._common_path +'/Cisco-IOS-XR-manageability-perfmgmt-oper:sample[Cisco-IOS-XR-manageability-perfmgmt-oper:sample-id = ' + str(self.sample_id) + ']'
def is_config(self):
''' Returns True if this instance represents config data else returns False '''
return False
def _has_data(self):
if self.sample_id is not None:
return True
if self.bandwidth is not None:
return True
if self.input_data_rate is not None:
return True
if self.input_packet_rate is not None:
return True
if self.input_peak_pkts is not None:
return True
if self.input_peak_rate is not None:
return True
if self.output_data_rate is not None:
return True
if self.output_packet_rate is not None:
return True
if self.output_peak_pkts is not None:
return True
if self.output_peak_rate is not None:
return True
if self.time_stamp is not None:
return True
return False
@staticmethod
def _meta_info():
from ydk.models.cisco_ios_xr._meta import _Cisco_IOS_XR_manageability_perfmgmt_oper as meta
return meta._meta_table['PerfMgmt.Monitor.Interface.DataRateInterfaces.DataRateInterface.Samples.Sample']['meta_info']
@property
def _common_path(self):
if self.parent is None:
raise YPYModelError('parent is not set . Cannot derive path.')
return self.parent._common_path +'/Cisco-IOS-XR-manageability-perfmgmt-oper:samples'
def is_config(self):
''' Returns True if this instance represents config data else returns False '''
return False
def _has_data(self):
if self.sample is not None:
for child_ref in self.sample:
if child_ref._has_data():
return True
return False
@staticmethod
def _meta_info():
from ydk.models.cisco_ios_xr._meta import _Cisco_IOS_XR_manageability_perfmgmt_oper as meta
return meta._meta_table['PerfMgmt.Monitor.Interface.DataRateInterfaces.DataRateInterface.Samples']['meta_info']
@property
def _common_path(self):
if self.interface_name is None:
raise YPYModelError('Key property interface_name is None')
return '/Cisco-IOS-XR-manageability-perfmgmt-oper:perf-mgmt/Cisco-IOS-XR-manageability-perfmgmt-oper:monitor/Cisco-IOS-XR-manageability-perfmgmt-oper:interface/Cisco-IOS-XR-manageability-perfmgmt-oper:data-rate-interfaces/Cisco-IOS-XR-manageability-perfmgmt-oper:data-rate-interface[Cisco-IOS-XR-manageability-perfmgmt-oper:interface-name = ' + str(self.interface_name) + ']'
def is_config(self):
''' Returns True if this instance represents config data else returns False '''
return False
def _has_data(self):
if self.interface_name is not None:
return True
if self.samples is not None and self.samples._has_data():
return True
return False
@staticmethod
def _meta_info():
from ydk.models.cisco_ios_xr._meta import _Cisco_IOS_XR_manageability_perfmgmt_oper as meta
return meta._meta_table['PerfMgmt.Monitor.Interface.DataRateInterfaces.DataRateInterface']['meta_info']
@property
def _common_path(self):
return '/Cisco-IOS-XR-manageability-perfmgmt-oper:perf-mgmt/Cisco-IOS-XR-manageability-perfmgmt-oper:monitor/Cisco-IOS-XR-manageability-perfmgmt-oper:interface/Cisco-IOS-XR-manageability-perfmgmt-oper:data-rate-interfaces'
def is_config(self):
''' Returns True if this instance represents config data else returns False '''
return False
def _has_data(self):
if self.data_rate_interface is not None:
for child_ref in self.data_rate_interface:
if child_ref._has_data():
return True
return False
@staticmethod
def _meta_info():
from ydk.models.cisco_ios_xr._meta import _Cisco_IOS_XR_manageability_perfmgmt_oper as meta
return meta._meta_table['PerfMgmt.Monitor.Interface.DataRateInterfaces']['meta_info']
@property
def _common_path(self):
return '/Cisco-IOS-XR-manageability-perfmgmt-oper:perf-mgmt/Cisco-IOS-XR-manageability-perfmgmt-oper:monitor/Cisco-IOS-XR-manageability-perfmgmt-oper:interface'
def is_config(self):
''' Returns True if this instance represents config data else returns False '''
return False
def _has_data(self):
if self.basic_counter_interfaces is not None and self.basic_counter_interfaces._has_data():
return True
if self.data_rate_interfaces is not None and self.data_rate_interfaces._has_data():
return True
if self.generic_counter_interfaces is not None and self.generic_counter_interfaces._has_data():
return True
return False
@staticmethod
def _meta_info():
from ydk.models.cisco_ios_xr._meta import _Cisco_IOS_XR_manageability_perfmgmt_oper as meta
return meta._meta_table['PerfMgmt.Monitor.Interface']['meta_info']
@property
def _common_path(self):
return '/Cisco-IOS-XR-manageability-perfmgmt-oper:perf-mgmt/Cisco-IOS-XR-manageability-perfmgmt-oper:monitor'
def is_config(self):
''' Returns True if this instance represents config data else returns False '''
return False
def _has_data(self):
if self.bgp is not None and self.bgp._has_data():
return True
if self.interface is not None and self.interface._has_data():
return True
if self.mpls is not None and self.mpls._has_data():
return True
if self.nodes is not None and self.nodes._has_data():
return True
if self.ospf is not None and self.ospf._has_data():
return True
return False
@staticmethod
def _meta_info():
from ydk.models.cisco_ios_xr._meta import _Cisco_IOS_XR_manageability_perfmgmt_oper as meta
return meta._meta_table['PerfMgmt.Monitor']['meta_info']
@property
def _common_path(self):
return '/Cisco-IOS-XR-manageability-perfmgmt-oper:perf-mgmt'
def is_config(self):
''' Returns True if this instance represents config data else returns False '''
return False
def _has_data(self):
if self.monitor is not None and self.monitor._has_data():
return True
if self.periodic is not None and self.periodic._has_data():
return True
return False
@staticmethod
def _meta_info():
from ydk.models.cisco_ios_xr._meta import _Cisco_IOS_XR_manageability_perfmgmt_oper as meta
return meta._meta_table['PerfMgmt']['meta_info']
|
111pontes/ydk-py
|
cisco-ios-xr/ydk/models/cisco_ios_xr/Cisco_IOS_XR_manageability_perfmgmt_oper.py
|
Python
|
apache-2.0
| 316,282 |
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "{}"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright {2015} {name of copyright owner}
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
|
promisejohn/webappdev
|
LICENSE.md
|
Markdown
|
apache-2.0
| 11,324 |
# Psycheneis GENUS
#### Status
ACCEPTED
#### According to
Interim Register of Marine and Nonmarine Genera
#### Published in
null
#### Original name
null
### Remarks
null
|
mdoering/backbone
|
life/Plantae/Bacillariophyta/Bacillariophyceae/Naviculales/Psycheneidaceae/Psycheneis/README.md
|
Markdown
|
apache-2.0
| 174 |
/*
* Copyright (c) 2013 LabKey Corporation
*
* Licensed under the Apache License, Version 2.0: http://www.apache.org/licenses/LICENSE-2.0
*/
/**
* This is the default metadata applied to records in the context of an assay, which currently is used by the ClinPath task.
*/
EHR.Metadata.registerMetadata('Assay', {
allQueries: {
project: {
// parentConfig: {
// storeIdentifier: {queryName: 'Clinpath Runs', schemaName: 'study'},
// recordIdentifier: function(parentRecord, childRecord){
// console.log(parentRecord);
// console.log(childRecord);
// if(!childRecord || !parentRecord){
// return;
// }
// if(childRecord.get('Id') && childRecord.get('Id') == parentRecord.get('Id')){
// return true;
// }
// },
// dataIndex: 'project'
// }
hidden: true
,shownInGrid: false
}
,account: {
// parentConfig: {
// storeIdentifier: {queryName: 'Clinpath Runs', schemaName: 'study'},
// recordIdentifier: function(parentRecord, childRecord){
// console.log(parentRecord);
// console.log(childRecord);
// if(!childRecord || !parentRecord){
// return;
// }
// if(childRecord.get('Id') && childRecord.get('Id') == parentRecord.get('Id')){
// return true;
// }
// },
// dataIndex: 'account'
// }
hidden: true
,shownInGrid: false
}
,performedby: {
hidden: true
}
// ,serviceRequested: {
// xtype: 'displayfield'
// }
},
byQuery: {
'Clinpath Runs': {
parentid: {
parentConfig: false,
allowBlank: true
},
Id: {
parentConfig: null,
hidden: false
},
date: {
parentConfig: null,
hidden: false
},
project: {
parentConfig: null,
hidden: false
},
account: {
parentConfig: null,
hidden: false
}
}
}
});
|
WNPRC-EHR-Services/wnprc-modules
|
WNPRC_EHR/resources/web/ehr/metadata/Assay.js
|
JavaScript
|
apache-2.0
| 2,512 |
'use strict';
var app = angular.module('erpLynCargoApp');
app.factory('Entity', function ($http, Data, $q, $state) {
var hasProp = Object.prototype.hasOwnProperty;
var extend = function (child, parent) {
for (var key in parent) {
if (hasProp.call(parent, key))
child[key] = parent[key];
}
function ctor() {
this.constructor = child;
}
ctor.prototype = parent.prototype;
child.prototype = new ctor;
child.super = parent.prototype;
return child;
};
var Entity;
extend(Entity, Data);
function Entity(propValues) {
Entity.super.constructor.apply(this, arguments);
this.apiPath = "/entity";
}
Entity.properties = function () {
var a = {};
return a;
};
Entity.prototype.save = function () {
return Entity.super.save.call(this);
};
return Entity;
});
|
tavomoya/erp-lyn-cargo
|
public/app/scripts/factories/Entity.js
|
JavaScript
|
apache-2.0
| 807 |
/**
*
* @module Kiwi
* @submodule Geom
*/
module Kiwi.Geom {
/**
* A Kiwi Line object has two meanings depending on the situation you need.
* Either an infinte line through space (this is the usual meaning of a Line)
* OR it can be a Line Segment which just exists between the TWO points you specify.
*
* @class Line
* @namespace Kiwi.Geom
* @constructor
* @param [x1 = 0] {Number} x1 x component of first point.
* @param [y1 = 0]{Number} y1 y component of first point.
* @param [x2 = 0]{Number} x2 x component of second point.
* @param [y2 = 0]{Number} y2 y component of second point.
* @return {Line} This Object
*
*/
export class Line {
constructor(x1: number = 0, y1: number = 0, x2: number = 0, y2: number = 0) {
this.setTo(x1, y1, x2, y2);
}
/**
* Returns the type of this object
* @method objType
* @return {string} The type of this object
* @public
*/
public objType() {
return "Line";
}
/**
* X position of first point in your line.
* @property x1
* @type Number
* @public
*/
public x1: number = 0;
/**
* Y position of first point in your line.
* @property y1
* @type Number
* @public
*/
public y1: number = 0;
/**
* X position of second point.
* @property x2
* @type Number
* @public
*/
public x2: number = 0;
/**
* X position of second point.
* @property y2
* @type Number
* @public
*/
public y2: number = 0;
/**
* Makes a clone of this Line.
* The clone will either be a new Line Object,
* Otherwise you can pass a existing Line Object that you want to be a clone of this one.
* @method clone
* @param [output = Line] {Kiwi.Geom.Line}
* @return {Kiwi.Geom.Line}
* @public
*/
public clone(output: Line = new Line): Line {
return output.setTo(this.x1, this.y1, this.x2, this.y2);
}
/**
* Make this Line a copy of another passed Line.
* @method copyFrom
* @param source {Kiwi.Geom.Line} source
* @return {Kiwi.Geom.Line}
* @public
*/
public copyFrom(source: Line): Line {
return this.setTo(source.x1, source.y1, source.x2, source.y2);
}
/**
* Make another passed Line a copy of this one.
* @method copyTo
* @param target {Kiwi.Geom.Line} target
* @return {Kiwi.Geom.Line}
* @public
*/
public copyTo(target: Line): Line {
return target.copyFrom(this);
}
/**
* Used to set all components on the line.
* @method setTo
* @param [x1 = 0]{Number} X component of first point.
* @param [y1 = 0]{Number} Y component of first point.
* @param [x2 = 0]{Number} X component of second point.
* @param [y2 = 0]{Number} Y component of second point.
* @return {Kiwi.Geom.Line}
* @public
*/
public setTo(x1: number = 0, y1: number = 0, x2: number = 0, y2: number = 0): Line {
this.x1 = x1;
this.y1 = y1;
this.x2 = x2;
this.y2 = y2;
return this;
}
/**
* Get the length of the Line as a Line Segment.
* @property length
* @type number
* @public
*/
public get length(): number {
return Math.sqrt((this.x2 - this.x1) * (this.x2 - this.x1) + (this.y2 - this.y1) * (this.y2 - this.y1));
}
/**
* Get the y of a point on the line for a given x.
* @method getY
* @param {Number} x
* @return {Number}
* @public
*/
public getY(x: number): number {
if (this.x1 == this.x2)
return null;
else
return this.slope * x + this.yIntercept;
}
/**
* Get the angle of the line.
* @property angle
* @return {Number}
*/
public get angle(): number {
return Math.atan2(this.x2 - this.x1, this.y2 - this.y1);
}
/**
* Get the slope of the line (y/x).
* @property slope
* @return {Number}
* @public
*/
public get slope(): number {
return (this.y2 - this.y1) / (this.x2 - this.x1);
}
/**
* Get the perpendicular slope of the line (x/y).
* @propery perpSlope
* @return {Number}
* @public
*/
public get perpSlope(): number {
return -((this.x2 - this.x1) / (this.y2 - this.y1));
}
/**
* Get the y intercept for the line.
* @property yIntercept
* @return {Number}
* @property
*/
public get yIntercept(): number {
return (this.y1 - this.slope * this.x1);
}
/**
* Check if a point is on the line.
* @method isPointOnLine
* @param x {Number}
* @param y {Number}
* @return {boolean}
* @public
*/
public isPointOnLine(x: number, y: number): boolean {
if ((x - this.x1) * (this.y2 - this.y1) === (this.x2 - this.x1) * (y - this.y1))
{
return true;
}
else
{
return false;
}
}
/**
* Check if the point is both on the line and within the line segment.
* @method isPointOnLineSegment
* @param {Number} x
* @param {Number} y
* @return {boolean}
* @public
*/
public isPointOnLineSegment(x: number, y: number): boolean {
var xMin = Math.min(this.x1, this.x2);
var xMax = Math.max(this.x1, this.x2);
var yMin = Math.min(this.y1, this.y2);
var yMax = Math.max(this.y1, this.y2);
if (this.isPointOnLine(x, y) && (x >= xMin && x <= xMax) && (y >= yMin && y <= yMax))
{
return true;
}
else
{
return false;
}
}
/**
* Check to see if this Line object intersects at any point with a passed Line.
* Note: Both are treated as extending infinately through space.
* @method intersectLineLine
* @param line {Kiwi.Geom.Line} The line you want to check for a Intersection with.
* @return {Kiwi.Geom.IntersectResult} The Intersect Result containing the collision information.
* @public
*/
public intersectLineLine(line): IntersectResult {
return Kiwi.Geom.Intersect.lineToLine(this,line);
}
/**
* Get a line perpendicular to the line passing through a given point.
* @method perp
* @param x {Number}
* @param y {Number}
* @param [output = Line] {Kiwi.Geom.Line}
* @return {Kiwi.Geom.Line}
* @public
*/
public perp(x: number, y: number, output?: Line): Line {
if (this.y1 === this.y2)
{
if (output)
{
output.setTo(x, y, x, this.y1);
}
else
{
return new Line(x, y, x, this.y1);
}
}
var yInt: number = (y - this.perpSlope * x);
var pt: any = this.intersectLineLine({ x1: x, y1: y, x2: 0, y2: yInt });
if (output)
{
output.setTo(x, y, pt.x, pt.y);
}
else
{
return new Line(x, y, pt.x, pt.y);
}
}
/**
* Get a string representation of the line.
* @method toString
* @return {String}
* @public
*/
public toString(): string {
return "[{Line (x1=" + this.x1 + " y1=" + this.y1 + " x2=" + this.x2 + " y2=" + this.y2 + ")}]";
}
}
}
|
dfu23/swim-meet
|
lib/kiwi.js/src/geom/Line.ts
|
TypeScript
|
apache-2.0
| 8,315 |
from flowsieve.packet.eap import eap
from flowsieve.packet.eapol import eapol
from nose.tools import eq_
from ryu.lib.packet import packet
EAPOL_TEST_CASES = [
([eapol(version=0x01, type_=0x01)], b"\x01\x01\x00\x00"),
([eapol(version=0x02, type_=0x01)], b"\x02\x01\x00\x00"),
([eapol(version=0x02, type_=0x02)], b"\x02\x02\x00\x00"),
([eapol(version=0x02, type_=0x00, length=4),
eap(code=0x03, length=4, identifier=0x12)],
b"\x02\x00\x00\x04\x03\x12\x00\x04")
]
def test_eapol():
for (protocols, binary) in EAPOL_TEST_CASES:
yield check_parse_eapol, protocols, binary
yield check_serialize_eapol, protocols, binary
def check_parse_eapol(protocols, b):
pkt = packet.Packet(data=b, protocols=None, parse_cls=eapol)
pkt_eapol = pkt.get_protocol(eapol)
eq_(pkt_eapol, protocols[0])
def check_serialize_eapol(protocols, b):
pkt = packet.Packet()
for p in protocols:
pkt.add_protocol(p)
pkt.serialize()
eq_(pkt.data, b)
|
shimojo-lab/flowsieve
|
flowsieve/test/eapol_test.py
|
Python
|
apache-2.0
| 1,008 |
/* Copyright 2017 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/core/framework/partial_tensor_shape.h"
#include "tensorflow/core/framework/tensor.h"
#include "tensorflow/core/kernels/data/dataset.h"
#include "tensorflow/core/lib/io/buffered_inputstream.h"
#include "tensorflow/core/lib/io/inputbuffer.h"
#include "tensorflow/core/lib/io/random_inputstream.h"
#include "tensorflow/core/lib/io/record_reader.h"
#include "tensorflow/core/lib/io/zlib_compression_options.h"
#include "tensorflow/core/lib/io/zlib_inputstream.h"
namespace tensorflow {
namespace {
// See documentation in ../ops/dataset_ops.cc for a high-level
// description of the following ops.
class TextLineDatasetOp : public DatasetOpKernel {
public:
using DatasetOpKernel::DatasetOpKernel;
void MakeDataset(OpKernelContext* ctx, DatasetBase** output) override {
const Tensor* filenames_tensor;
OP_REQUIRES_OK(ctx, ctx->input("filenames", &filenames_tensor));
OP_REQUIRES(
ctx, filenames_tensor->dims() <= 1,
errors::InvalidArgument("`filenames` must be a scalar or a vector."));
string compression_type;
OP_REQUIRES_OK(ctx, ParseScalarArgument<string>(ctx, "compression_type",
&compression_type));
int64 buffer_size = -1;
OP_REQUIRES_OK(
ctx, ParseScalarArgument<int64>(ctx, "buffer_size", &buffer_size));
OP_REQUIRES(
ctx, buffer_size >= 0,
errors::InvalidArgument("`buffer_size` must be >= 0 (0 == default)"));
io::ZlibCompressionOptions zlib_compression_options =
io::ZlibCompressionOptions::DEFAULT();
if (compression_type == "ZLIB") {
zlib_compression_options = io::ZlibCompressionOptions::DEFAULT();
} else if (compression_type == "GZIP") {
zlib_compression_options = io::ZlibCompressionOptions::GZIP();
} else {
OP_REQUIRES(ctx, compression_type.empty(),
errors::InvalidArgument("Unsupported compression_type."));
}
if (buffer_size != 0) {
// Set the override size.
zlib_compression_options.input_buffer_size = buffer_size;
}
std::vector<string> filenames;
filenames.reserve(filenames_tensor->NumElements());
for (int i = 0; i < filenames_tensor->NumElements(); ++i) {
filenames.push_back(filenames_tensor->flat<string>()(i));
}
*output = new Dataset(ctx, std::move(filenames), compression_type,
zlib_compression_options);
}
private:
class Dataset : public GraphDatasetBase {
public:
Dataset(OpKernelContext* ctx, std::vector<string> filenames,
const string& compression_type,
const io::ZlibCompressionOptions& options)
: GraphDatasetBase(ctx),
filenames_(std::move(filenames)),
compression_type_(compression_type),
use_compression_(!compression_type.empty()),
options_(options) {}
std::unique_ptr<IteratorBase> MakeIteratorInternal(
const string& prefix) const override {
return std::unique_ptr<IteratorBase>(
new Iterator({this, strings::StrCat(prefix, "::TextLine")}));
}
const DataTypeVector& output_dtypes() const override {
static DataTypeVector* dtypes = new DataTypeVector({DT_STRING});
return *dtypes;
}
const std::vector<PartialTensorShape>& output_shapes() const override {
static std::vector<PartialTensorShape>* shapes =
new std::vector<PartialTensorShape>({{}});
return *shapes;
}
string DebugString() const override { return "TextLineDatasetOp::Dataset"; }
protected:
Status AsGraphDefInternal(SerializationContext* ctx,
DatasetGraphDefBuilder* b,
Node** output) const override {
Node* filenames = nullptr;
Node* compression_type = nullptr;
Node* buffer_size = nullptr;
TF_RETURN_IF_ERROR(b->AddVector(filenames_, &filenames));
TF_RETURN_IF_ERROR(b->AddScalar(compression_type_, &compression_type));
TF_RETURN_IF_ERROR(
b->AddScalar(options_.input_buffer_size, &buffer_size));
TF_RETURN_IF_ERROR(b->AddDataset(
this, {filenames, compression_type, buffer_size}, output));
return Status::OK();
}
private:
class Iterator : public DatasetIterator<Dataset> {
public:
explicit Iterator(const Params& params)
: DatasetIterator<Dataset>(params) {}
Status GetNextInternal(IteratorContext* ctx,
std::vector<Tensor>* out_tensors,
bool* end_of_sequence) override {
mutex_lock l(mu_);
do {
// We are currently processing a file, so try to read the next line.
if (buffered_input_stream_) {
string line_contents;
Status s = buffered_input_stream_->ReadLine(&line_contents);
if (s.ok()) {
// Produce the line as output.
Tensor line_tensor(ctx->allocator({}), DT_STRING, {});
line_tensor.scalar<string>()() = line_contents;
out_tensors->emplace_back(std::move(line_tensor));
*end_of_sequence = false;
return Status::OK();
} else if (!errors::IsOutOfRange(s)) {
// Report non-EOF errors to the caller.
return s;
}
// We have reached the end of the current file, so maybe
// move on to next file.
ResetStreamsLocked();
++current_file_index_;
}
// Iteration ends when there are no more files to process.
if (current_file_index_ == dataset()->filenames_.size()) {
*end_of_sequence = true;
return Status::OK();
}
TF_RETURN_IF_ERROR(SetupStreamsLocked(ctx->env()));
} while (true);
}
protected:
Status SaveInternal(IteratorStateWriter* writer) override {
mutex_lock l(mu_);
TF_RETURN_IF_ERROR(writer->WriteScalar(full_name("current_file_index"),
current_file_index_));
// `buffered_input_stream_` is empty if
// 1. GetNext has not been called even once.
// 2. All files have been read and iterator has been exhausted.
if (buffered_input_stream_) {
TF_RETURN_IF_ERROR(writer->WriteScalar(
full_name("current_pos"), buffered_input_stream_->Tell()));
}
return Status::OK();
}
Status RestoreInternal(IteratorContext* ctx,
IteratorStateReader* reader) override {
mutex_lock l(mu_);
ResetStreamsLocked();
int64 current_file_index;
TF_RETURN_IF_ERROR(reader->ReadScalar(full_name("current_file_index"),
¤t_file_index));
current_file_index_ = size_t(current_file_index);
// The key "current_pos" is written only if the iterator was saved
// with an open file.
if (reader->Contains(full_name("current_pos"))) {
int64 current_pos;
TF_RETURN_IF_ERROR(
reader->ReadScalar(full_name("current_pos"), ¤t_pos));
TF_RETURN_IF_ERROR(SetupStreamsLocked(ctx->env()));
TF_RETURN_IF_ERROR(buffered_input_stream_->Seek(current_pos));
}
return Status::OK();
}
private:
// Sets up reader streams to read from the file at `current_file_index_`.
Status SetupStreamsLocked(Env* env) EXCLUSIVE_LOCKS_REQUIRED(mu_) {
if (current_file_index_ >= dataset()->filenames_.size()) {
return errors::InvalidArgument(
"current_file_index_:", current_file_index_,
" >= filenames_.size():", dataset()->filenames_.size());
}
// Actually move on to next file.
TF_RETURN_IF_ERROR(env->NewRandomAccessFile(
dataset()->filenames_[current_file_index_], &file_));
input_stream_.reset(
new io::RandomAccessInputStream(file_.get(), false));
if (dataset()->use_compression_) {
zlib_input_stream_.reset(new io::ZlibInputStream(
input_stream_.get(), dataset()->options_.input_buffer_size,
dataset()->options_.input_buffer_size, dataset()->options_));
buffered_input_stream_.reset(new io::BufferedInputStream(
zlib_input_stream_.get(), dataset()->options_.input_buffer_size,
false));
} else {
buffered_input_stream_.reset(new io::BufferedInputStream(
input_stream_.get(), dataset()->options_.input_buffer_size,
false));
}
return Status::OK();
}
// Resets all reader streams.
void ResetStreamsLocked() EXCLUSIVE_LOCKS_REQUIRED(mu_) {
input_stream_.reset();
zlib_input_stream_.reset();
buffered_input_stream_.reset();
file_.reset();
}
mutex mu_;
std::unique_ptr<io::RandomAccessInputStream> input_stream_
GUARDED_BY(mu_);
std::unique_ptr<io::ZlibInputStream> zlib_input_stream_ GUARDED_BY(mu_);
std::unique_ptr<io::BufferedInputStream> buffered_input_stream_
GUARDED_BY(mu_);
size_t current_file_index_ GUARDED_BY(mu_) = 0;
std::unique_ptr<RandomAccessFile> file_
GUARDED_BY(mu_); // must outlive input_stream_
};
const std::vector<string> filenames_;
const string compression_type_;
const bool use_compression_;
const io::ZlibCompressionOptions options_;
};
};
REGISTER_KERNEL_BUILDER(Name("TextLineDataset").Device(DEVICE_CPU),
TextLineDatasetOp);
class FixedLengthRecordDatasetOp : public DatasetOpKernel {
public:
using DatasetOpKernel::DatasetOpKernel;
void MakeDataset(OpKernelContext* ctx, DatasetBase** output) override {
const Tensor* filenames_tensor;
OP_REQUIRES_OK(ctx, ctx->input("filenames", &filenames_tensor));
OP_REQUIRES(
ctx, filenames_tensor->dims() <= 1,
errors::InvalidArgument("`filenames` must be a scalar or a vector."));
std::vector<string> filenames;
filenames.reserve(filenames_tensor->NumElements());
for (int i = 0; i < filenames_tensor->NumElements(); ++i) {
filenames.push_back(filenames_tensor->flat<string>()(i));
}
int64 header_bytes = -1;
OP_REQUIRES_OK(
ctx, ParseScalarArgument<int64>(ctx, "header_bytes", &header_bytes));
OP_REQUIRES(ctx, header_bytes >= 0,
errors::InvalidArgument("`header_bytes` must be >= 0"));
int64 record_bytes = -1;
OP_REQUIRES_OK(
ctx, ParseScalarArgument<int64>(ctx, "record_bytes", &record_bytes));
OP_REQUIRES(ctx, record_bytes > 0,
errors::InvalidArgument("`record_bytes` must be > 0"));
int64 footer_bytes = -1;
OP_REQUIRES_OK(
ctx, ParseScalarArgument<int64>(ctx, "footer_bytes", &footer_bytes));
OP_REQUIRES(ctx, footer_bytes >= 0,
errors::InvalidArgument("`footer_bytes` must be >= 0"));
int64 buffer_size = -1;
OP_REQUIRES_OK(
ctx, ParseScalarArgument<int64>(ctx, "buffer_size", &buffer_size));
OP_REQUIRES(ctx, buffer_size >= 0,
errors::InvalidArgument("`buffer_size` must be >= 0"));
if (buffer_size == 0) {
buffer_size = 256 << 10; // 256 kB as default.
}
*output = new Dataset(ctx, std::move(filenames), header_bytes, record_bytes,
footer_bytes, buffer_size);
}
private:
class Dataset : public GraphDatasetBase {
public:
explicit Dataset(OpKernelContext* ctx, std::vector<string> filenames,
int64 header_bytes, int64 record_bytes, int64 footer_bytes,
int64 buffer_size)
: GraphDatasetBase(ctx),
filenames_(std::move(filenames)),
header_bytes_(header_bytes),
record_bytes_(record_bytes),
footer_bytes_(footer_bytes),
buffer_size_(buffer_size) {}
std::unique_ptr<IteratorBase> MakeIteratorInternal(
const string& prefix) const override {
return std::unique_ptr<IteratorBase>(
new Iterator({this, strings::StrCat(prefix, "::FixedLengthRecord")}));
}
const DataTypeVector& output_dtypes() const override {
static DataTypeVector* dtypes = new DataTypeVector({DT_STRING});
return *dtypes;
}
const std::vector<PartialTensorShape>& output_shapes() const override {
static std::vector<PartialTensorShape>* shapes =
new std::vector<PartialTensorShape>({{}});
return *shapes;
}
string DebugString() const override {
return "FixedLengthRecordDatasetOp::Dataset";
}
protected:
Status AsGraphDefInternal(SerializationContext* ctx,
DatasetGraphDefBuilder* b,
Node** output) const override {
Node* filenames = nullptr;
Node* header_bytes = nullptr;
Node* record_bytes = nullptr;
Node* footer_bytes = nullptr;
Node* buffer_size = nullptr;
TF_RETURN_IF_ERROR(b->AddVector(filenames_, &filenames));
TF_RETURN_IF_ERROR(b->AddScalar(header_bytes_, &header_bytes));
TF_RETURN_IF_ERROR(b->AddScalar(record_bytes_, &record_bytes));
TF_RETURN_IF_ERROR(b->AddScalar(footer_bytes_, &footer_bytes));
TF_RETURN_IF_ERROR(b->AddScalar(buffer_size_, &buffer_size));
TF_RETURN_IF_ERROR(b->AddDataset(
this,
{filenames, header_bytes, record_bytes, footer_bytes, buffer_size},
output));
return Status::OK();
}
private:
class Iterator : public DatasetIterator<Dataset> {
public:
explicit Iterator(const Params& params)
: DatasetIterator<Dataset>(params) {}
Status GetNextInternal(IteratorContext* ctx,
std::vector<Tensor>* out_tensors,
bool* end_of_sequence) override {
mutex_lock l(mu_);
do {
// We are currently processing a file, so try to read the next record.
if (input_buffer_) {
const int64 current_pos = input_buffer_->Tell();
DCHECK_GE(file_pos_limit_, 0);
if (current_pos < file_pos_limit_) {
string record;
TF_RETURN_IF_ERROR(
input_buffer_->ReadNBytes(dataset()->record_bytes_, &record));
// Produce the record as output.
Tensor record_tensor(ctx->allocator({}), DT_STRING, {});
record_tensor.scalar<string>()() = record;
out_tensors->emplace_back(std::move(record_tensor));
*end_of_sequence = false;
return Status::OK();
}
// We have reached the end of the current file, so maybe
// move on to next file.
input_buffer_.reset();
file_.reset();
++current_file_index_;
}
// Iteration ends when there are no more files to process.
if (current_file_index_ == dataset()->filenames_.size()) {
*end_of_sequence = true;
return Status::OK();
}
// Actually move on to next file.
uint64 file_size;
TF_RETURN_IF_ERROR(ctx->env()->GetFileSize(
dataset()->filenames_[current_file_index_], &file_size));
file_pos_limit_ = file_size - dataset()->footer_bytes_;
uint64 body_size =
file_size - (dataset()->header_bytes_ + dataset()->footer_bytes_);
if (body_size % dataset()->record_bytes_ != 0) {
return errors::InvalidArgument(
"Excluding the header (", dataset()->header_bytes_,
" bytes) and footer (", dataset()->footer_bytes_,
" bytes), input file \"",
dataset()->filenames_[current_file_index_],
"\" has body length ", body_size,
" bytes, which is not an exact multiple of the record length (",
dataset()->record_bytes_, " bytes).");
}
TF_RETURN_IF_ERROR(ctx->env()->NewRandomAccessFile(
dataset()->filenames_[current_file_index_], &file_));
input_buffer_.reset(
new io::InputBuffer(file_.get(), dataset()->buffer_size_));
TF_RETURN_IF_ERROR(
input_buffer_->SkipNBytes(dataset()->header_bytes_));
} while (true);
}
protected:
Status SaveInternal(IteratorStateWriter* writer) override {
mutex_lock l(mu_);
TF_RETURN_IF_ERROR(writer->WriteScalar(full_name("current_file_index"),
current_file_index_));
// `input_buffer_` is empty if
// 1. GetNext has not been called even once.
// 2. All files have been read and iterator has been exhausted.
int64 current_pos = input_buffer_ ? input_buffer_->Tell() : -1;
TF_RETURN_IF_ERROR(
writer->WriteScalar(full_name("current_pos"), current_pos));
return Status::OK();
}
Status RestoreInternal(IteratorContext* ctx,
IteratorStateReader* reader) override {
mutex_lock l(mu_);
int64 current_file_index;
TF_RETURN_IF_ERROR(reader->ReadScalar(full_name("current_file_index"),
¤t_file_index));
current_file_index_ = size_t(current_file_index);
int64 current_pos;
TF_RETURN_IF_ERROR(
reader->ReadScalar(full_name("current_pos"), ¤t_pos));
// Seek to current_pos.
input_buffer_.reset();
file_.reset();
if (current_pos >= 0) { // There was an active input_buffer_.
uint64 file_size;
TF_RETURN_IF_ERROR(ctx->env()->GetFileSize(
dataset()->filenames_[current_file_index_], &file_size));
file_pos_limit_ = file_size - dataset()->footer_bytes_;
TF_RETURN_IF_ERROR(ctx->env()->NewRandomAccessFile(
dataset()->filenames_[current_file_index_], &file_));
input_buffer_.reset(
new io::InputBuffer(file_.get(), dataset()->buffer_size_));
TF_RETURN_IF_ERROR(input_buffer_->Seek(current_pos));
}
return Status::OK();
}
private:
mutex mu_;
size_t current_file_index_ GUARDED_BY(mu_) = 0;
std::unique_ptr<RandomAccessFile> file_
GUARDED_BY(mu_); // must outlive input_buffer_
std::unique_ptr<io::InputBuffer> input_buffer_ GUARDED_BY(mu_);
int64 file_pos_limit_ GUARDED_BY(mu_) = -1;
};
const std::vector<string> filenames_;
const int64 header_bytes_;
const int64 record_bytes_;
const int64 footer_bytes_;
const int64 buffer_size_;
};
};
REGISTER_KERNEL_BUILDER(Name("FixedLengthRecordDataset").Device(DEVICE_CPU),
FixedLengthRecordDatasetOp);
class TFRecordDatasetOp : public DatasetOpKernel {
public:
using DatasetOpKernel::DatasetOpKernel;
void MakeDataset(OpKernelContext* ctx, DatasetBase** output) override {
const Tensor* filenames_tensor;
OP_REQUIRES_OK(ctx, ctx->input("filenames", &filenames_tensor));
OP_REQUIRES(
ctx, filenames_tensor->dims() <= 1,
errors::InvalidArgument("`filenames` must be a scalar or a vector."));
std::vector<string> filenames;
filenames.reserve(filenames_tensor->NumElements());
for (int i = 0; i < filenames_tensor->NumElements(); ++i) {
filenames.push_back(filenames_tensor->flat<string>()(i));
}
string compression_type;
OP_REQUIRES_OK(ctx, ParseScalarArgument<string>(ctx, "compression_type",
&compression_type));
int64 buffer_size = -1;
OP_REQUIRES_OK(
ctx, ParseScalarArgument<int64>(ctx, "buffer_size", &buffer_size));
OP_REQUIRES(ctx, buffer_size >= 0,
errors::InvalidArgument(
"`buffer_size` must be >= 0 (0 == no buffering)"));
*output =
new Dataset(ctx, std::move(filenames), compression_type, buffer_size);
}
private:
class Dataset : public GraphDatasetBase {
public:
explicit Dataset(OpKernelContext* ctx, std::vector<string> filenames,
const string& compression_type, int64 buffer_size)
: GraphDatasetBase(ctx),
filenames_(std::move(filenames)),
compression_type_(compression_type),
options_(io::RecordReaderOptions::CreateRecordReaderOptions(
compression_type)) {
if (buffer_size > 0) {
options_.buffer_size = buffer_size;
}
}
std::unique_ptr<IteratorBase> MakeIteratorInternal(
const string& prefix) const override {
return std::unique_ptr<IteratorBase>(
new Iterator({this, strings::StrCat(prefix, "::TFRecord")}));
}
const DataTypeVector& output_dtypes() const override {
static DataTypeVector* dtypes = new DataTypeVector({DT_STRING});
return *dtypes;
}
const std::vector<PartialTensorShape>& output_shapes() const override {
static std::vector<PartialTensorShape>* shapes =
new std::vector<PartialTensorShape>({{}});
return *shapes;
}
string DebugString() const override { return "TFRecordDatasetOp::Dataset"; }
protected:
Status AsGraphDefInternal(SerializationContext* ctx,
DatasetGraphDefBuilder* b,
Node** output) const override {
Node* filenames = nullptr;
TF_RETURN_IF_ERROR(b->AddVector(filenames_, &filenames));
Node* compression_type = nullptr;
TF_RETURN_IF_ERROR(b->AddScalar(compression_type_, &compression_type));
Node* buffer_size = nullptr;
TF_RETURN_IF_ERROR(b->AddScalar(options_.buffer_size, &buffer_size));
TF_RETURN_IF_ERROR(b->AddDataset(
this, {filenames, compression_type, buffer_size}, output));
return Status::OK();
}
private:
class Iterator : public DatasetIterator<Dataset> {
public:
explicit Iterator(const Params& params)
: DatasetIterator<Dataset>(params) {}
Status GetNextInternal(IteratorContext* ctx,
std::vector<Tensor>* out_tensors,
bool* end_of_sequence) override {
mutex_lock l(mu_);
do {
// We are currently processing a file, so try to read the next record.
if (reader_) {
Tensor result_tensor(ctx->allocator({}), DT_STRING, {});
Status s = reader_->ReadRecord(&result_tensor.scalar<string>()());
if (s.ok()) {
out_tensors->emplace_back(std::move(result_tensor));
*end_of_sequence = false;
return Status::OK();
} else if (!errors::IsOutOfRange(s)) {
return s;
}
// We have reached the end of the current file, so maybe
// move on to next file.
ResetStreamsLocked();
++current_file_index_;
}
// Iteration ends when there are no more files to process.
if (current_file_index_ == dataset()->filenames_.size()) {
*end_of_sequence = true;
return Status::OK();
}
TF_RETURN_IF_ERROR(SetupStreamsLocked(ctx->env()));
} while (true);
}
protected:
Status SaveInternal(IteratorStateWriter* writer) override {
mutex_lock l(mu_);
TF_RETURN_IF_ERROR(writer->WriteScalar(full_name("current_file_index"),
current_file_index_));
if (reader_) {
TF_RETURN_IF_ERROR(
writer->WriteScalar(full_name("offset"), reader_->TellOffset()));
}
return Status::OK();
}
Status RestoreInternal(IteratorContext* ctx,
IteratorStateReader* reader) override {
mutex_lock l(mu_);
ResetStreamsLocked();
int64 current_file_index;
TF_RETURN_IF_ERROR(reader->ReadScalar(full_name("current_file_index"),
¤t_file_index));
current_file_index_ = size_t(current_file_index);
if (reader->Contains(full_name("offset"))) {
int64 offset;
TF_RETURN_IF_ERROR(reader->ReadScalar(full_name("offset"), &offset));
TF_RETURN_IF_ERROR(SetupStreamsLocked(ctx->env()));
TF_RETURN_IF_ERROR(reader_->SeekOffset(offset));
}
return Status::OK();
}
private:
// Sets up reader streams to read from the file at `current_file_index_`.
Status SetupStreamsLocked(Env* env) EXCLUSIVE_LOCKS_REQUIRED(mu_) {
if (current_file_index_ >= dataset()->filenames_.size()) {
return errors::InvalidArgument(
"current_file_index_:", current_file_index_,
" >= filenames_.size():", dataset()->filenames_.size());
}
// Actually move on to next file.
const string& next_filename =
dataset()->filenames_[current_file_index_];
TF_RETURN_IF_ERROR(env->NewRandomAccessFile(next_filename, &file_));
reader_.reset(
new io::SequentialRecordReader(file_.get(), dataset()->options_));
return Status::OK();
}
// Resets all reader streams.
void ResetStreamsLocked() EXCLUSIVE_LOCKS_REQUIRED(mu_) {
reader_.reset();
file_.reset();
}
mutex mu_;
size_t current_file_index_ GUARDED_BY(mu_) = 0;
// `reader_` will borrow the object that `file_` points to, so
// we must destroy `reader_` before `file_`.
std::unique_ptr<RandomAccessFile> file_ GUARDED_BY(mu_);
std::unique_ptr<io::SequentialRecordReader> reader_ GUARDED_BY(mu_);
};
const std::vector<string> filenames_;
const string compression_type_;
io::RecordReaderOptions options_;
};
};
REGISTER_KERNEL_BUILDER(Name("TFRecordDataset").Device(DEVICE_CPU),
TFRecordDatasetOp);
} // namespace
} // namespace tensorflow
|
manipopopo/tensorflow
|
tensorflow/core/kernels/data/reader_dataset_ops.cc
|
C++
|
apache-2.0
| 26,849 |
//>>excludeStart("jqmBuildExclude", pragmas.jqmBuildExclude);
//>>description: Popup windows
//>>label: Popups
//>>group: Widgets
//>>css.theme: ../css/themes/default/jquery.mobile.theme.css
//>>css.structure: ../css/structure/jquery.mobile.popup.css,../css/structure/jquery.mobile.transition.css,../css/structure/jquery.mobile.transition.fade.css
// Lessons:
// You must remove nav bindings even if there is no history. Make sure you
// remove nav bindings in the same frame as the beginning of the close process
// if there is no history. If there is history, remove nav bindings from the nav
// bindings handler - that way, only one of them can fire per close process.
define( [
"jquery",
"../jquery.mobile.links",
"../jquery.mobile.widget",
"../jquery.mobile.support",
"../events/navigate",
"../navigation/path",
"../navigation/history",
"../navigation/navigator",
"../navigation/method",
"../jquery.mobile.navigation",
"jquery.hashchange" ], function( jQuery ) {
//>>excludeEnd("jqmBuildExclude");
(function( $, undefined ) {
function fitSegmentInsideSegment( windowSize, segmentSize, offset, desired ) {
var returnValue = desired;
if ( windowSize < segmentSize ) {
// Center segment if it's bigger than the window
returnValue = offset + ( windowSize - segmentSize ) / 2;
} else {
// Otherwise center it at the desired coordinate while keeping it completely inside the window
returnValue = Math.min( Math.max( offset, desired - segmentSize / 2 ), offset + windowSize - segmentSize );
}
return returnValue;
}
function getWindowCoordinates( theWindow ) {
return {
x: theWindow.scrollLeft(),
y: theWindow.scrollTop(),
cx: ( theWindow[ 0 ].innerWidth || theWindow.width() ),
cy: ( theWindow[ 0 ].innerHeight || theWindow.height() )
};
}
$.widget( "mobile.popup", {
options: {
wrapperClass: null,
theme: null,
overlayTheme: null,
shadow: true,
corners: true,
transition: "none",
positionTo: "origin",
tolerance: null,
closeLinkSelector: "a:jqmData(rel='back')",
closeLinkEvents: "click.popup",
navigateEvents: "navigate.popup",
closeEvents: "navigate.popup pagebeforechange.popup",
dismissible: true,
enhanced: false,
// NOTE Windows Phone 7 has a scroll position caching issue that
// requires us to disable popup history management by default
// https://github.com/jquery/jquery-mobile/issues/4784
//
// NOTE this option is modified in _create!
history: !$.mobile.browser.oldIE
},
_create: function() {
var theElement = this.element,
myId = theElement.attr( "id" ),
currentOptions = this.options;
// We need to adjust the history option to be false if there's no AJAX nav.
// We can't do it in the option declarations because those are run before
// it is determined whether there shall be AJAX nav.
currentOptions.history = currentOptions.history && $.mobile.ajaxEnabled && $.mobile.hashListeningEnabled;
// Define instance variables
$.extend( this, {
_scrollTop: 0,
_page: theElement.closest( ".ui-page" ),
_ui: null,
_fallbackTransition: "",
_currentTransition: false,
_prerequisites: null,
_isOpen: false,
_tolerance: null,
_resizeData: null,
_ignoreResizeTo: 0,
_orientationchangeInProgress: false
});
if ( this._page.length === 0 ) {
this._page = $( "body" );
}
if ( currentOptions.enhanced ) {
this._ui = {
container: theElement.parent(),
screen: theElement.parent().prev(),
placeholder: $( this.document[ 0 ].getElementById( myId + "-placeholder" ) )
};
} else {
this._ui = this._enhance( theElement, myId );
this._applyTransition( currentOptions.transition );
}
this
._setTolerance( currentOptions.tolerance )
._ui.focusElement = this._ui.container;
// Event handlers
this._on( this._ui.screen, { "vclick": "_eatEventAndClose" } );
this._on( this.window, {
orientationchange: $.proxy( this, "_handleWindowOrientationchange" ),
resize: $.proxy( this, "_handleWindowResize" ),
keyup: $.proxy( this, "_handleWindowKeyUp" )
});
this._on( this.document, { "focusin": "_handleDocumentFocusIn" } );
},
_enhance: function( theElement, myId ) {
var currentOptions = this.options,
wrapperClass = currentOptions.wrapperClass,
ui = {
screen: $( "<div class='ui-screen-hidden ui-popup-screen " +
this._themeClassFromOption( "ui-overlay-", currentOptions.overlayTheme ) + "'></div>" ),
placeholder: $( "<div style='display: none;'><!-- placeholder --></div>" ),
container: $( "<div class='ui-popup-container ui-popup-hidden ui-popup-truncate" +
( wrapperClass ? ( " " + wrapperClass ) : "" ) + "'></div>" )
},
fragment = this.document[ 0 ].createDocumentFragment();
fragment.appendChild( ui.screen[ 0 ] );
fragment.appendChild( ui.container[ 0 ] );
if ( myId ) {
ui.screen.attr( "id", myId + "-screen" );
ui.container.attr( "id", myId + "-popup" );
ui.placeholder
.attr( "id", myId + "-placeholder" )
.html( "<!-- placeholder for " + myId + " -->" );
}
// Apply the proto
this._page[ 0 ].appendChild( fragment );
// Leave a placeholder where the element used to be
ui.placeholder.insertAfter( theElement );
theElement
.detach()
.addClass( "ui-popup " +
this._themeClassFromOption( "ui-body-", currentOptions.theme ) + " " +
( currentOptions.shadow ? "ui-overlay-shadow " : "" ) +
( currentOptions.corners ? "ui-corner-all " : "" ) )
.appendTo( ui.container );
return ui;
},
_eatEventAndClose: function( theEvent ) {
theEvent.preventDefault();
theEvent.stopImmediatePropagation();
if ( this.options.dismissible ) {
this.close();
}
return false;
},
// Make sure the screen covers the entire document - CSS is sometimes not
// enough to accomplish this.
_resizeScreen: function() {
var screen = this._ui.screen,
popupHeight = this._ui.container.outerHeight( true ),
screenHeight = screen.removeAttr( "style" ).height(),
// Subtracting 1 here is necessary for an obscure Andrdoid 4.0 bug where
// the browser hangs if the screen covers the entire document :/
documentHeight = this.document.height() - 1;
if ( screenHeight < documentHeight ) {
screen.height( documentHeight );
} else if ( popupHeight > screenHeight ) {
screen.height( popupHeight );
}
},
_handleWindowKeyUp: function( theEvent ) {
if ( this._isOpen && theEvent.keyCode === $.mobile.keyCode.ESCAPE ) {
return this._eatEventAndClose( theEvent );
}
},
_expectResizeEvent: function() {
var windowCoordinates = getWindowCoordinates( this.window );
if ( this._resizeData ) {
if ( windowCoordinates.x === this._resizeData.windowCoordinates.x &&
windowCoordinates.y === this._resizeData.windowCoordinates.y &&
windowCoordinates.cx === this._resizeData.windowCoordinates.cx &&
windowCoordinates.cy === this._resizeData.windowCoordinates.cy ) {
// timeout not refreshed
return false;
} else {
// clear existing timeout - it will be refreshed below
clearTimeout( this._resizeData.timeoutId );
}
}
this._resizeData = {
timeoutId: this._delay( "_resizeTimeout", 200 ),
windowCoordinates: windowCoordinates
};
return true;
},
_resizeTimeout: function() {
if ( this._isOpen ) {
if ( !this._expectResizeEvent() ) {
if ( this._ui.container.hasClass( "ui-popup-hidden" ) ) {
// effectively rapid-open the popup while leaving the screen intact
this._ui.container.removeClass( "ui-popup-hidden ui-popup-truncate" );
this.reposition( { positionTo: "window" } );
this._ignoreResizeEvents();
}
this._resizeScreen();
this._resizeData = null;
this._orientationchangeInProgress = false;
}
} else {
this._resizeData = null;
this._orientationchangeInProgress = false;
}
},
_stopIgnoringResizeEvents: function() {
this._ignoreResizeTo = 0;
},
_ignoreResizeEvents: function() {
if ( this._ignoreResizeTo ) {
clearTimeout( this._ignoreResizeTo );
}
this._ignoreResizeTo = this._delay( "_stopIgnoringResizeEvents", 1000 );
},
_handleWindowResize: function(/* theEvent */) {
if ( this._isOpen && this._ignoreResizeTo === 0 ) {
if ( ( this._expectResizeEvent() || this._orientationchangeInProgress ) &&
!this._ui.container.hasClass( "ui-popup-hidden" ) ) {
// effectively rapid-close the popup while leaving the screen intact
this._ui.container
.addClass( "ui-popup-hidden ui-popup-truncate" )
.removeAttr( "style" );
}
}
},
_handleWindowOrientationchange: function(/* theEvent */) {
if ( !this._orientationchangeInProgress && this._isOpen && this._ignoreResizeTo === 0 ) {
this._expectResizeEvent();
this._orientationchangeInProgress = true;
}
},
// When the popup is open, attempting to focus on an element that is not a
// child of the popup will redirect focus to the popup
_handleDocumentFocusIn: function( theEvent ) {
var target,
targetElement = theEvent.target,
ui = this._ui;
if ( !this._isOpen ) {
return;
}
if ( targetElement !== ui.container[ 0 ] ) {
target = $( targetElement );
if ( 0 === target.parents().filter( ui.container[ 0 ] ).length ) {
$( this.document[ 0 ].activeElement ).one( "focus", function(/* theEvent */) {
target.blur();
});
ui.focusElement.focus();
theEvent.preventDefault();
theEvent.stopImmediatePropagation();
return false;
} else if ( ui.focusElement[ 0 ] === ui.container[ 0 ] ) {
ui.focusElement = target;
}
}
this._ignoreResizeEvents();
},
_themeClassFromOption: function( prefix, value ) {
return ( value ? ( value === "none" ? "" : ( prefix + value ) ) : ( prefix + "inherit" ) );
},
_applyTransition: function( value ) {
if ( value ) {
this._ui.container.removeClass( this._fallbackTransition );
if ( value !== "none" ) {
this._fallbackTransition = $.mobile._maybeDegradeTransition( value );
if ( this._fallbackTransition === "none" ) {
this._fallbackTransition = "";
}
this._ui.container.addClass( this._fallbackTransition );
}
}
return this;
},
_setOptions: function( newOptions ) {
var currentOptions = this.options,
theElement = this.element,
screen = this._ui.screen;
if ( newOptions.wrapperClass !== undefined ) {
this._ui.container
.removeClass( currentOptions.wrapperClass )
.addClass( newOptions.wrapperClass );
}
if ( newOptions.theme !== undefined ) {
theElement
.removeClass( this._themeClassFromOption( "ui-body-", currentOptions.theme ) )
.addClass( this._themeClassFromOption( "ui-body-", newOptions.theme ) );
}
if ( newOptions.overlayTheme !== undefined ) {
screen
.removeClass( this._themeClassFromOption( "ui-overlay-", currentOptions.overlayTheme ) )
.addClass( this._themeClassFromOption( "ui-overlay-", newOptions.overlayTheme ) );
if ( this._isOpen ) {
screen.addClass( "in" );
}
}
if ( newOptions.shadow !== undefined ) {
theElement.toggleClass( "ui-overlay-shadow", newOptions.shadow );
}
if ( newOptions.corners !== undefined ) {
theElement.toggleClass( "ui-corner-all", newOptions.corners );
}
if ( newOptions.transition !== undefined ) {
if ( !this._currentTransition ) {
this._applyTransition( newOptions.transition );
}
}
if ( newOptions.tolerance !== undefined ) {
this._setTolerance( newOptions.tolerance );
}
if ( newOptions.disabled !== undefined ) {
if ( newOptions.disabled ) {
this.close();
}
}
return this._super( newOptions );
},
_setTolerance: function( value ) {
var tol = { t: 30, r: 15, b: 30, l: 15 },
ar;
if ( value !== undefined ) {
ar = String( value ).split( "," );
$.each( ar, function( idx, val ) { ar[ idx ] = parseInt( val, 10 ); } );
switch( ar.length ) {
// All values are to be the same
case 1:
if ( !isNaN( ar[ 0 ] ) ) {
tol.t = tol.r = tol.b = tol.l = ar[ 0 ];
}
break;
// The first value denotes top/bottom tolerance, and the second value denotes left/right tolerance
case 2:
if ( !isNaN( ar[ 0 ] ) ) {
tol.t = tol.b = ar[ 0 ];
}
if ( !isNaN( ar[ 1 ] ) ) {
tol.l = tol.r = ar[ 1 ];
}
break;
// The array contains values in the order top, right, bottom, left
case 4:
if ( !isNaN( ar[ 0 ] ) ) {
tol.t = ar[ 0 ];
}
if ( !isNaN( ar[ 1 ] ) ) {
tol.r = ar[ 1 ];
}
if ( !isNaN( ar[ 2 ] ) ) {
tol.b = ar[ 2 ];
}
if ( !isNaN( ar[ 3 ] ) ) {
tol.l = ar[ 3 ];
}
break;
default:
break;
}
}
this._tolerance = tol;
return this;
},
_clampPopupWidth: function( infoOnly ) {
var menuSize,
windowCoordinates = getWindowCoordinates( this.window ),
// rectangle within which the popup must fit
rectangle = {
x: this._tolerance.l,
y: windowCoordinates.y + this._tolerance.t,
cx: windowCoordinates.cx - this._tolerance.l - this._tolerance.r,
cy: windowCoordinates.cy - this._tolerance.t - this._tolerance.b
};
if ( !infoOnly ) {
// Clamp the width of the menu before grabbing its size
this._ui.container.css( "max-width", rectangle.cx );
}
menuSize = {
cx: this._ui.container.outerWidth( true ),
cy: this._ui.container.outerHeight( true )
};
return { rc: rectangle, menuSize: menuSize };
},
_calculateFinalLocation: function( desired, clampInfo ) {
var returnValue,
rectangle = clampInfo.rc,
menuSize = clampInfo.menuSize;
// Center the menu over the desired coordinates, while not going outside
// the window tolerances. This will center wrt. the window if the popup is
// too large.
returnValue = {
left: fitSegmentInsideSegment( rectangle.cx, menuSize.cx, rectangle.x, desired.x ),
top: fitSegmentInsideSegment( rectangle.cy, menuSize.cy, rectangle.y, desired.y )
};
// Make sure the top of the menu is visible
returnValue.top = Math.max( 0, returnValue.top );
// If the height of the menu is smaller than the height of the document
// align the bottom with the bottom of the document
returnValue.top -= Math.min( returnValue.top,
Math.max( 0, returnValue.top + menuSize.cy - this.document.height() ) );
return returnValue;
},
// Try and center the overlay over the given coordinates
_placementCoords: function( desired ) {
return this._calculateFinalLocation( desired, this._clampPopupWidth() );
},
_createPrerequisites: function( screenPrerequisite, containerPrerequisite, whenDone ) {
var prerequisites,
self = this;
// It is important to maintain both the local variable prerequisites and
// self._prerequisites. The local variable remains in the closure of the
// functions which call the callbacks passed in. The comparison between the
// local variable and self._prerequisites is necessary, because once a
// function has been passed to .animationComplete() it will be called next
// time an animation completes, even if that's not the animation whose end
// the function was supposed to catch (for example, if an abort happens
// during the opening animation, the .animationComplete handler is not
// called for that animation anymore, but the handler remains attached, so
// it is called the next time the popup is opened - making it stale.
// Comparing the local variable prerequisites to the widget-level variable
// self._prerequisites ensures that callbacks triggered by a stale
// .animationComplete will be ignored.
prerequisites = {
screen: $.Deferred(),
container: $.Deferred()
};
prerequisites.screen.then( function() {
if ( prerequisites === self._prerequisites ) {
screenPrerequisite();
}
});
prerequisites.container.then( function() {
if ( prerequisites === self._prerequisites ) {
containerPrerequisite();
}
});
$.when( prerequisites.screen, prerequisites.container ).done( function() {
if ( prerequisites === self._prerequisites ) {
self._prerequisites = null;
whenDone();
}
});
self._prerequisites = prerequisites;
},
_animate: function( args ) {
// NOTE before removing the default animation of the screen
// this had an animate callback that would resolve the deferred
// now the deferred is resolved immediately
// TODO remove the dependency on the screen deferred
this._ui.screen
.removeClass( args.classToRemove )
.addClass( args.screenClassToAdd );
args.prerequisites.screen.resolve();
if ( args.transition && args.transition !== "none" ) {
if ( args.applyTransition ) {
this._applyTransition( args.transition );
}
if ( this._fallbackTransition ) {
this._ui.container
.animationComplete( $.proxy( args.prerequisites.container, "resolve" ) )
.addClass( args.containerClassToAdd )
.removeClass( args.classToRemove );
return;
}
}
this._ui.container.removeClass( args.classToRemove );
args.prerequisites.container.resolve();
},
// The desired coordinates passed in will be returned untouched if no reference element can be identified via
// desiredPosition.positionTo. Nevertheless, this function ensures that its return value always contains valid
// x and y coordinates by specifying the center middle of the window if the coordinates are absent.
// options: { x: coordinate, y: coordinate, positionTo: string: "origin", "window", or jQuery selector
_desiredCoords: function( openOptions ) {
var offset,
dst = null,
windowCoordinates = getWindowCoordinates( this.window ),
x = openOptions.x,
y = openOptions.y,
pTo = openOptions.positionTo;
// Establish which element will serve as the reference
if ( pTo && pTo !== "origin" ) {
if ( pTo === "window" ) {
x = windowCoordinates.cx / 2 + windowCoordinates.x;
y = windowCoordinates.cy / 2 + windowCoordinates.y;
} else {
try {
dst = $( pTo );
} catch( err ) {
dst = null;
}
if ( dst ) {
dst.filter( ":visible" );
if ( dst.length === 0 ) {
dst = null;
}
}
}
}
// If an element was found, center over it
if ( dst ) {
offset = dst.offset();
x = offset.left + dst.outerWidth() / 2;
y = offset.top + dst.outerHeight() / 2;
}
// Make sure x and y are valid numbers - center over the window
if ( $.type( x ) !== "number" || isNaN( x ) ) {
x = windowCoordinates.cx / 2 + windowCoordinates.x;
}
if ( $.type( y ) !== "number" || isNaN( y ) ) {
y = windowCoordinates.cy / 2 + windowCoordinates.y;
}
return { x: x, y: y };
},
_reposition: function( openOptions ) {
// We only care about position-related parameters for repositioning
openOptions = {
x: openOptions.x,
y: openOptions.y,
positionTo: openOptions.positionTo
};
this._trigger( "beforeposition", undefined, openOptions );
this._ui.container.offset( this._placementCoords( this._desiredCoords( openOptions ) ) );
},
reposition: function( openOptions ) {
if ( this._isOpen ) {
this._reposition( openOptions );
}
},
_openPrerequisitesComplete: function() {
var id = this.element.attr( "id" );
this._ui.container.addClass( "ui-popup-active" );
this._isOpen = true;
this._resizeScreen();
this._ui.container.attr( "tabindex", "0" ).focus();
this._ignoreResizeEvents();
if ( id ) {
this.document.find( "[aria-haspopup='true'][aria-owns='" + id + "']" ).attr( "aria-expanded", true );
}
this._trigger( "afteropen" );
},
_open: function( options ) {
var openOptions = $.extend( {}, this.options, options ),
// TODO move blacklist to private method
androidBlacklist = ( function() {
var ua = navigator.userAgent,
// Rendering engine is Webkit, and capture major version
wkmatch = ua.match( /AppleWebKit\/([0-9\.]+)/ ),
wkversion = !!wkmatch && wkmatch[ 1 ],
androidmatch = ua.match( /Android (\d+(?:\.\d+))/ ),
andversion = !!androidmatch && androidmatch[ 1 ],
chromematch = ua.indexOf( "Chrome" ) > -1;
// Platform is Android, WebKit version is greater than 534.13 ( Android 3.2.1 ) and not Chrome.
if ( androidmatch !== null && andversion === "4.0" && wkversion && wkversion > 534.13 && !chromematch ) {
return true;
}
return false;
}());
// Count down to triggering "popupafteropen" - we have two prerequisites:
// 1. The popup window animation completes (container())
// 2. The screen opacity animation completes (screen())
this._createPrerequisites(
$.noop,
$.noop,
$.proxy( this, "_openPrerequisitesComplete" ) );
this._currentTransition = openOptions.transition;
this._applyTransition( openOptions.transition );
this._ui.screen.removeClass( "ui-screen-hidden" );
this._ui.container.removeClass( "ui-popup-truncate" );
// Give applications a chance to modify the contents of the container before it appears
this._reposition( openOptions );
this._ui.container.removeClass( "ui-popup-hidden" );
if ( this.options.overlayTheme && androidBlacklist ) {
/* TODO: The native browser on Android 4.0.X ("Ice Cream Sandwich") suffers from an issue where the popup overlay appears to be z-indexed above the popup itself when certain other styles exist on the same page -- namely, any element set to `position: fixed` and certain types of input. These issues are reminiscent of previously uncovered bugs in older versions of Android's native browser: https://github.com/scottjehl/Device-Bugs/issues/3
This fix closes the following bugs ( I use "closes" with reluctance, and stress that this issue should be revisited as soon as possible ):
https://github.com/jquery/jquery-mobile/issues/4816
https://github.com/jquery/jquery-mobile/issues/4844
https://github.com/jquery/jquery-mobile/issues/4874
*/
// TODO sort out why this._page isn't working
this.element.closest( ".ui-page" ).addClass( "ui-popup-open" );
}
this._animate({
additionalCondition: true,
transition: openOptions.transition,
classToRemove: "",
screenClassToAdd: "in",
containerClassToAdd: "in",
applyTransition: false,
prerequisites: this._prerequisites
});
},
_closePrerequisiteScreen: function() {
this._ui.screen
.removeClass( "out" )
.addClass( "ui-screen-hidden" );
},
_closePrerequisiteContainer: function() {
this._ui.container
.removeClass( "reverse out" )
.addClass( "ui-popup-hidden ui-popup-truncate" )
.removeAttr( "style" );
},
_closePrerequisitesDone: function() {
var container = this._ui.container,
id = this.element.attr( "id" );
container.removeAttr( "tabindex" );
// remove the global mutex for popups
$.mobile.popup.active = undefined;
// Blur elements inside the container, including the container
$( ":focus", container[ 0 ] ).add( container[ 0 ] ).blur();
if ( id ) {
this.document.find( "[aria-haspopup='true'][aria-owns='" + id + "']" ).attr( "aria-expanded", false );
}
// alert users that the popup is closed
this._trigger( "afterclose" );
},
_close: function( immediate ) {
this._ui.container.removeClass( "ui-popup-active" );
this._page.removeClass( "ui-popup-open" );
this._isOpen = false;
// Count down to triggering "popupafterclose" - we have two prerequisites:
// 1. The popup window reverse animation completes (container())
// 2. The screen opacity animation completes (screen())
this._createPrerequisites(
$.proxy( this, "_closePrerequisiteScreen" ),
$.proxy( this, "_closePrerequisiteContainer" ),
$.proxy( this, "_closePrerequisitesDone" ) );
this._animate( {
additionalCondition: this._ui.screen.hasClass( "in" ),
transition: ( immediate ? "none" : ( this._currentTransition ) ),
classToRemove: "in",
screenClassToAdd: "out",
containerClassToAdd: "reverse out",
applyTransition: true,
prerequisites: this._prerequisites
});
},
_unenhance: function() {
if ( this.options.enhanced ) {
return;
}
// Put the element back to where the placeholder was and remove the "ui-popup" class
this._setOptions( { theme: $.mobile.popup.prototype.options.theme } );
this.element
// Cannot directly insertAfter() - we need to detach() first, because
// insertAfter() will do nothing if the payload div was not attached
// to the DOM at the time the widget was created, and so the payload
// will remain inside the container even after we call insertAfter().
// If that happens and we remove the container a few lines below, we
// will cause an infinite recursion - #5244
.detach()
.insertAfter( this._ui.placeholder )
.removeClass( "ui-popup ui-overlay-shadow ui-corner-all ui-body-inherit" );
this._ui.screen.remove();
this._ui.container.remove();
this._ui.placeholder.remove();
},
_destroy: function() {
if ( $.mobile.popup.active === this ) {
this.element.one( "popupafterclose", $.proxy( this, "_unenhance" ) );
this.close();
} else {
this._unenhance();
}
return this;
},
_closePopup: function( theEvent, data ) {
var parsedDst, toUrl,
currentOptions = this.options,
immediate = false;
if ( ( theEvent && theEvent.isDefaultPrevented() ) || $.mobile.popup.active !== this ) {
return;
}
// restore location on screen
window.scrollTo( 0, this._scrollTop );
if ( theEvent && theEvent.type === "pagebeforechange" && data ) {
// Determine whether we need to rapid-close the popup, or whether we can
// take the time to run the closing transition
if ( typeof data.toPage === "string" ) {
parsedDst = data.toPage;
} else {
parsedDst = data.toPage.jqmData( "url" );
}
parsedDst = $.mobile.path.parseUrl( parsedDst );
toUrl = parsedDst.pathname + parsedDst.search + parsedDst.hash;
if ( this._myUrl !== $.mobile.path.makeUrlAbsolute( toUrl ) ) {
// Going to a different page - close immediately
immediate = true;
} else {
theEvent.preventDefault();
}
}
// remove nav bindings
this.window.off( currentOptions.closeEvents );
// unbind click handlers added when history is disabled
this.element.undelegate( currentOptions.closeLinkSelector, currentOptions.closeLinkEvents );
this._close( immediate );
},
// any navigation event after a popup is opened should close the popup
// NOTE the pagebeforechange is bound to catch navigation events that don't
// alter the url (eg, dialogs from popups)
_bindContainerClose: function() {
this.window
.on( this.options.closeEvents, $.proxy( this, "_closePopup" ) );
},
widget: function() {
return this._ui.container;
},
// TODO no clear deliniation of what should be here and
// what should be in _open. Seems to be "visual" vs "history" for now
open: function( options ) {
var url, hashkey, activePage, currentIsDialog, hasHash, urlHistory,
self = this,
currentOptions = this.options;
// make sure open is idempotent
if ( $.mobile.popup.active || currentOptions.disabled ) {
return this;
}
// set the global popup mutex
$.mobile.popup.active = this;
this._scrollTop = this.window.scrollTop();
// if history alteration is disabled close on navigate events
// and leave the url as is
if ( !( currentOptions.history ) ) {
self._open( options );
self._bindContainerClose();
// When histoy is disabled we have to grab the data-rel
// back link clicks so we can close the popup instead of
// relying on history to do it for us
self.element
.delegate( currentOptions.closeLinkSelector, currentOptions.closeLinkEvents, function( theEvent ) {
self.close();
theEvent.preventDefault();
});
return this;
}
// cache some values for min/readability
urlHistory = $.mobile.navigate.history;
hashkey = $.mobile.dialogHashKey;
activePage = $.mobile.activePage;
currentIsDialog = ( activePage ? activePage.hasClass( "ui-dialog" ) : false );
this._myUrl = url = urlHistory.getActive().url;
hasHash = ( url.indexOf( hashkey ) > -1 ) && !currentIsDialog && ( urlHistory.activeIndex > 0 );
if ( hasHash ) {
self._open( options );
self._bindContainerClose();
return this;
}
// if the current url has no dialog hash key proceed as normal
// otherwise, if the page is a dialog simply tack on the hash key
if ( url.indexOf( hashkey ) === -1 && !currentIsDialog ) {
url = url + (url.indexOf( "#" ) > -1 ? hashkey : "#" + hashkey);
} else {
url = $.mobile.path.parseLocation().hash + hashkey;
}
// Tack on an extra hashkey if this is the first page and we've just reconstructed the initial hash
if ( urlHistory.activeIndex === 0 && url === urlHistory.initialDst ) {
url += hashkey;
}
// swallow the the initial navigation event, and bind for the next
this.window.one( "beforenavigate", function( theEvent ) {
theEvent.preventDefault();
self._open( options );
self._bindContainerClose();
});
this.urlAltered = true;
$.mobile.navigate( url, { role: "dialog" } );
return this;
},
close: function() {
// make sure close is idempotent
if ( $.mobile.popup.active !== this ) {
return this;
}
this._scrollTop = this.window.scrollTop();
if ( this.options.history && this.urlAltered ) {
$.mobile.back();
this.urlAltered = false;
} else {
// simulate the nav bindings having fired
this._closePopup();
}
return this;
}
});
// TODO this can be moved inside the widget
$.mobile.popup.handleLink = function( $link ) {
var offset,
path = $.mobile.path,
// NOTE make sure to get only the hash from the href because ie7 (wp7)
// returns the absolute href in this case ruining the element selection
popup = $( path.hashToSelector( path.parseUrl( $link.attr( "href" ) ).hash ) ).first();
if ( popup.length > 0 && popup.data( "mobile-popup" ) ) {
offset = $link.offset();
popup.popup( "open", {
x: offset.left + $link.outerWidth() / 2,
y: offset.top + $link.outerHeight() / 2,
transition: $link.jqmData( "transition" ),
positionTo: $link.jqmData( "position-to" )
});
}
//remove after delay
setTimeout( function() {
$link.removeClass( $.mobile.activeBtnClass );
}, 300 );
};
// TODO move inside _create
$.mobile.document.on( "pagebeforechange", function( theEvent, data ) {
if ( data.options.role === "popup" ) {
$.mobile.popup.handleLink( data.options.link );
theEvent.preventDefault();
}
});
})( jQuery );
//>>excludeStart("jqmBuildExclude", pragmas.jqmBuildExclude);
});
//>>excludeEnd("jqmBuildExclude");
|
ronagapitz/matchdrobe-app
|
www/js/widgets/popup.js
|
JavaScript
|
apache-2.0
| 30,392 |
# Cirsium uetsuense Kitam. SPECIES
#### Status
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null
|
mdoering/backbone
|
life/Plantae/Magnoliophyta/Magnoliopsida/Asterales/Asteraceae/Cirsium uetsuense/README.md
|
Markdown
|
apache-2.0
| 174 |
/*
* Copyright (C) 2013-2016 Benjamin Gould, and others
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.thriftee.servlet;
import java.util.Collections;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import javax.naming.InitialContext;
import javax.naming.NameClassPair;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.thriftee.core.DefaultServiceLocator;
import org.thriftee.core.ServiceLocator;
import org.thriftee.core.ServiceLocatorException;
import org.thriftee.core.ServiceLocatorException.Messages;
import org.thriftee.core.util.New;
import org.thriftee.core.util.Strings;
public class DefaultEJBServiceLocator
extends DefaultServiceLocator
implements ServiceLocator {
protected final Logger LOG = LoggerFactory.getLogger(getClass());
private boolean searchAllModules;
private Set<String> modulesToSearch = Collections.emptySet();
public DefaultEJBServiceLocator() {
}
public void setSearchAllModules(boolean searchAllModules) {
this.searchAllModules = searchAllModules;
}
public boolean isSearchAllModules() {
return this.searchAllModules;
}
private static String normalizeModuleName(String moduleName) {
moduleName = Strings.trimToNull(moduleName);
if (moduleName == null) {
// TODO: maybe there is a use case for this... waiting for complaints
throw new IllegalArgumentException("moduleName cannot be empty");
}
if (!moduleName.endsWith("/")) {
moduleName += "/";
}
if (!moduleName.startsWith("/")) {
moduleName = "/" + moduleName;
}
return moduleName;
}
public void setModuleToSearch(String moduleName) {
final Set<String> names = new HashSet<String>();
names.add(moduleName);
setModulesToSearch(names);
}
public void setModulesToSearch(final Set<String> modulesToSearch) {
if (modulesToSearch == null) {
this.modulesToSearch = Collections.emptySet();
} else {
final Set<String> names = new HashSet<String>();
for (final String name : modulesToSearch) {
names.add(normalizeModuleName(name));
}
this.modulesToSearch = names;
}
}
public Set<String> getModulesToSearch() {
return Collections.unmodifiableSet(this.modulesToSearch);
}
private Set<String> findNamesForInterface(
final InitialContext ctx,
final String moduleName,
final Class<?> svcIntf
) throws NamingException {
final String prefix = "java:global" + moduleName;
final NamingEnumeration<NameClassPair> ne = ctx.list(prefix);
final Set<String> matches = new HashSet<String>();
while (ne.hasMoreElements()) {
final NameClassPair ncp = ne.nextElement();
LOG.trace(" jndi entry: {}", ncp);
final String name = ncp.getName();
if (name.endsWith("!" + svcIntf.getName())) {
matches.add(prefix + name);
}
}
return matches;
}
private Set<String> getGlobalModuleNames(
InitialContext ctx
) throws NamingException {
final String prefix = "java:global";
final NamingEnumeration<NameClassPair> ne = ctx.list(prefix);
final Set<String> matches = new HashSet<String>();
while (ne.hasMoreElements()) {
final NameClassPair ncp = ne.nextElement();
final String name = ncp.getName();
LOG.trace(" jndi module: {}", ncp);
matches.add(normalizeModuleName(name));
}
return matches;
}
private Map<String, Set<String>> implMap(
InitialContext ctx,
Class<?> intf
) throws NamingException {
final Set<String> modulesToSearch;
if (isSearchAllModules()) {
modulesToSearch = getGlobalModuleNames(ctx);
} else {
modulesToSearch = getModulesToSearch();
}
final Map<String, Set<String>> matchesInModules = New.sortedMap();
for (final String name : modulesToSearch) {
final Set<String> matches = findNamesForInterface(ctx, name, intf);
matchesInModules.put(name, matches);
}
return matchesInModules;
}
@Override
public <I> I locate(Class<I> svcIntf) throws ServiceLocatorException {
final I parentResult = super.locate(svcIntf);
if (parentResult != null) {
return parentResult;
}
if (!isSearchAllModules() && getModulesToSearch().isEmpty()) {
throw new IllegalStateException(
"Either searchAllModules must be set to true, " +
"or modulesToSearch must be specified."
);
}
final InitialContext ic;
final Map<String, Set<String>> matches;
try {
ic = new InitialContext();
matches = implMap(ic, svcIntf);
} catch (NamingException e) {
throw new ServiceLocatorException(e, Messages.SVCLOC_000);
}
final Set<String> allMatches = new HashSet<>();
for (String moduleName : matches.keySet()) {
allMatches.addAll(matches.get(moduleName));
}
if (allMatches.isEmpty()) {
return null;
}
if (allMatches.size() == 1) {
final String jndiName = allMatches.iterator().next();
final I result;
try {
@SuppressWarnings("unchecked")
final I bean = (I) ic.lookup(jndiName);
result = bean;
} catch (NamingException e) {
throw new ServiceLocatorException(e, Messages.SVCLOC_000);
}
return result;
}
// TODO: make this more intelligent
throw new IllegalStateException(
"More than one implementation found for interface: " + svcIntf);
/*
final ThriftService annotation = svcIntf.getAnnotation(ThriftService.class);
if (annotation == null) {
throw new IllegalArgumentException("Service interface not annotated.");
}
final String prefix = "java:global/" + moduleName;
debugJNDI(prefix);
final String name = annotation.value();
final String svcName = (StringUtils.trimToNull(name) == null) ? svcIntf.getSimpleName() : name;
final String jndiName = prefix + svcName + "Bean";
final I result;
try {
@SuppressWarnings("unchecked")
final I bean = (I) ic.lookup(jndiName);
result = bean;
} catch (NamingException e) {
throw new ServiceLocatorException(e, ServiceLocatorMessage.SVCLOC_000);
}
return result;
}
private void debugJNDI(String prefix) {
//if (!LOG.isDebugEnabled()) {
// return;
//}
try {
LOG.info("Showing JNDI prefix: {}", prefix);
final InitialContext ic = new InitialContext();
final NamingEnumeration<NameClassPair> ne = ic.list(prefix);
while (ne.hasMoreElements()) {
final NameClassPair ncp = ne.nextElement();
LOG.info(" NameClassPair: {}", ncp);
}
} catch (final Exception e) {
e.printStackTrace();
}
*/
}
}
|
bgould/thriftee
|
servlet/src/main/java/org/thriftee/servlet/DefaultEJBServiceLocator.java
|
Java
|
apache-2.0
| 7,309 |
/*
* Copyright © 2014 - 2019 Leipzig University (Database Research Group)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gradoop.flink.model.impl.operators.aggregation.functions.containment;
import org.gradoop.common.model.impl.pojo.Element;
import org.gradoop.common.model.impl.pojo.GraphHead;
import org.gradoop.common.model.impl.properties.PropertyValue;
import org.gradoop.flink.model.api.functions.AggregateFunction;
import org.gradoop.flink.model.impl.functions.filters.CombinableFilter;
import org.gradoop.flink.model.impl.operators.aggregation.functions.BaseAggregateFunction;
import org.gradoop.flink.model.impl.operators.aggregation.functions.bool.Or;
import java.util.Objects;
/**
* Superclass of aggregate and filter functions that check vertex or edge label
* presence in a graph.
*
* <pre>
* Usage:
* <ol>
* <li>aggregate
* <li>filter using the same UDF instance.
* </ol>
* </pre>
*/
public class HasLabel extends BaseAggregateFunction
implements Or, AggregateFunction, CombinableFilter<GraphHead> {
/**
* Label to check presence of.
*/
private final String label;
/**
* Creates a new instance of a HasLabel aggregate function.
*
* @param label element label to check presence of
*/
public HasLabel(String label) {
this(label, "hasLabel_" + label);
}
/**
* Creates a new instance of a HasLabel aggregate function.
*
* @param label label to check presence of
* @param aggregatePropertyKey aggregate property key
*/
public HasLabel(String label, String aggregatePropertyKey) {
super(aggregatePropertyKey);
Objects.requireNonNull(label);
this.label = label;
}
@Override
public PropertyValue getIncrement(Element element) {
return PropertyValue.create(element.getLabel().equals(label));
}
@Override
public boolean filter(GraphHead graphHead) throws Exception {
return graphHead.getPropertyValue(getAggregatePropertyKey()).getBoolean();
}
}
|
rostam/gradoop
|
gradoop-flink/src/main/java/org/gradoop/flink/model/impl/operators/aggregation/functions/containment/HasLabel.java
|
Java
|
apache-2.0
| 2,485 |
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/ads/googleads/v10/resources/ad_group_ad_asset_combination_view.proto
package com.google.ads.googleads.v10.resources;
/**
* <pre>
* A view on the usage of ad group ad asset combination.
* Now we only support AdGroupAdAssetCombinationView for Responsive Search Ads,
* with more ad types planned for the future.
* </pre>
*
* Protobuf type {@code google.ads.googleads.v10.resources.AdGroupAdAssetCombinationView}
*/
public final class AdGroupAdAssetCombinationView extends
com.google.protobuf.GeneratedMessageV3 implements
// @@protoc_insertion_point(message_implements:google.ads.googleads.v10.resources.AdGroupAdAssetCombinationView)
AdGroupAdAssetCombinationViewOrBuilder {
private static final long serialVersionUID = 0L;
// Use AdGroupAdAssetCombinationView.newBuilder() to construct.
private AdGroupAdAssetCombinationView(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private AdGroupAdAssetCombinationView() {
resourceName_ = "";
servedAssets_ = java.util.Collections.emptyList();
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(
UnusedPrivateParameter unused) {
return new AdGroupAdAssetCombinationView();
}
@java.lang.Override
public final com.google.protobuf.UnknownFieldSet
getUnknownFields() {
return this.unknownFields;
}
private AdGroupAdAssetCombinationView(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
this();
if (extensionRegistry == null) {
throw new java.lang.NullPointerException();
}
int mutable_bitField0_ = 0;
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: {
java.lang.String s = input.readStringRequireUtf8();
resourceName_ = s;
break;
}
case 18: {
if (!((mutable_bitField0_ & 0x00000001) != 0)) {
servedAssets_ = new java.util.ArrayList<com.google.ads.googleads.v10.common.AssetUsage>();
mutable_bitField0_ |= 0x00000001;
}
servedAssets_.add(
input.readMessage(com.google.ads.googleads.v10.common.AssetUsage.parser(), extensionRegistry));
break;
}
default: {
if (!parseUnknownField(
input, unknownFields, extensionRegistry, tag)) {
done = true;
}
break;
}
}
}
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.setUnfinishedMessage(this);
} catch (java.io.IOException e) {
throw new com.google.protobuf.InvalidProtocolBufferException(
e).setUnfinishedMessage(this);
} finally {
if (((mutable_bitField0_ & 0x00000001) != 0)) {
servedAssets_ = java.util.Collections.unmodifiableList(servedAssets_);
}
this.unknownFields = unknownFields.build();
makeExtensionsImmutable();
}
}
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return com.google.ads.googleads.v10.resources.AdGroupAdAssetCombinationViewProto.internal_static_google_ads_googleads_v10_resources_AdGroupAdAssetCombinationView_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.ads.googleads.v10.resources.AdGroupAdAssetCombinationViewProto.internal_static_google_ads_googleads_v10_resources_AdGroupAdAssetCombinationView_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.ads.googleads.v10.resources.AdGroupAdAssetCombinationView.class, com.google.ads.googleads.v10.resources.AdGroupAdAssetCombinationView.Builder.class);
}
public static final int RESOURCE_NAME_FIELD_NUMBER = 1;
private volatile java.lang.Object resourceName_;
/**
* <pre>
* Output only. The resource name of the ad group ad asset combination view. The
* combination ID is 128 bits long, where the upper 64 bits are stored in
* asset_combination_id_high, and the lower 64 bits are stored in
* asset_combination_id_low.
* AdGroupAd Asset Combination view resource names have the form:
* `customers/{customer_id}/adGroupAdAssetCombinationViews/{AdGroupAd.ad_group_id}~{AdGroupAd.ad.ad_id}~{AssetCombination.asset_combination_id_low}~{AssetCombination.asset_combination_id_high}`
* </pre>
*
* <code>string resource_name = 1 [(.google.api.field_behavior) = OUTPUT_ONLY, (.google.api.resource_reference) = { ... }</code>
* @return The resourceName.
*/
@java.lang.Override
public java.lang.String getResourceName() {
java.lang.Object ref = resourceName_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
resourceName_ = s;
return s;
}
}
/**
* <pre>
* Output only. The resource name of the ad group ad asset combination view. The
* combination ID is 128 bits long, where the upper 64 bits are stored in
* asset_combination_id_high, and the lower 64 bits are stored in
* asset_combination_id_low.
* AdGroupAd Asset Combination view resource names have the form:
* `customers/{customer_id}/adGroupAdAssetCombinationViews/{AdGroupAd.ad_group_id}~{AdGroupAd.ad.ad_id}~{AssetCombination.asset_combination_id_low}~{AssetCombination.asset_combination_id_high}`
* </pre>
*
* <code>string resource_name = 1 [(.google.api.field_behavior) = OUTPUT_ONLY, (.google.api.resource_reference) = { ... }</code>
* @return The bytes for resourceName.
*/
@java.lang.Override
public com.google.protobuf.ByteString
getResourceNameBytes() {
java.lang.Object ref = resourceName_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
resourceName_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int SERVED_ASSETS_FIELD_NUMBER = 2;
private java.util.List<com.google.ads.googleads.v10.common.AssetUsage> servedAssets_;
/**
* <pre>
* Output only. Served assets.
* </pre>
*
* <code>repeated .google.ads.googleads.v10.common.AssetUsage served_assets = 2 [(.google.api.field_behavior) = OUTPUT_ONLY];</code>
*/
@java.lang.Override
public java.util.List<com.google.ads.googleads.v10.common.AssetUsage> getServedAssetsList() {
return servedAssets_;
}
/**
* <pre>
* Output only. Served assets.
* </pre>
*
* <code>repeated .google.ads.googleads.v10.common.AssetUsage served_assets = 2 [(.google.api.field_behavior) = OUTPUT_ONLY];</code>
*/
@java.lang.Override
public java.util.List<? extends com.google.ads.googleads.v10.common.AssetUsageOrBuilder>
getServedAssetsOrBuilderList() {
return servedAssets_;
}
/**
* <pre>
* Output only. Served assets.
* </pre>
*
* <code>repeated .google.ads.googleads.v10.common.AssetUsage served_assets = 2 [(.google.api.field_behavior) = OUTPUT_ONLY];</code>
*/
@java.lang.Override
public int getServedAssetsCount() {
return servedAssets_.size();
}
/**
* <pre>
* Output only. Served assets.
* </pre>
*
* <code>repeated .google.ads.googleads.v10.common.AssetUsage served_assets = 2 [(.google.api.field_behavior) = OUTPUT_ONLY];</code>
*/
@java.lang.Override
public com.google.ads.googleads.v10.common.AssetUsage getServedAssets(int index) {
return servedAssets_.get(index);
}
/**
* <pre>
* Output only. Served assets.
* </pre>
*
* <code>repeated .google.ads.googleads.v10.common.AssetUsage served_assets = 2 [(.google.api.field_behavior) = OUTPUT_ONLY];</code>
*/
@java.lang.Override
public com.google.ads.googleads.v10.common.AssetUsageOrBuilder getServedAssetsOrBuilder(
int index) {
return servedAssets_.get(index);
}
private byte memoizedIsInitialized = -1;
@java.lang.Override
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) return true;
if (isInitialized == 0) return false;
memoizedIsInitialized = 1;
return true;
}
@java.lang.Override
public void writeTo(com.google.protobuf.CodedOutputStream output)
throws java.io.IOException {
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(resourceName_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 1, resourceName_);
}
for (int i = 0; i < servedAssets_.size(); i++) {
output.writeMessage(2, servedAssets_.get(i));
}
unknownFields.writeTo(output);
}
@java.lang.Override
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) return size;
size = 0;
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(resourceName_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, resourceName_);
}
for (int i = 0; i < servedAssets_.size(); i++) {
size += com.google.protobuf.CodedOutputStream
.computeMessageSize(2, servedAssets_.get(i));
}
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.resources.AdGroupAdAssetCombinationView)) {
return super.equals(obj);
}
com.google.ads.googleads.v10.resources.AdGroupAdAssetCombinationView other = (com.google.ads.googleads.v10.resources.AdGroupAdAssetCombinationView) obj;
if (!getResourceName()
.equals(other.getResourceName())) return false;
if (!getServedAssetsList()
.equals(other.getServedAssetsList())) return false;
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();
hash = (37 * hash) + RESOURCE_NAME_FIELD_NUMBER;
hash = (53 * hash) + getResourceName().hashCode();
if (getServedAssetsCount() > 0) {
hash = (37 * hash) + SERVED_ASSETS_FIELD_NUMBER;
hash = (53 * hash) + getServedAssetsList().hashCode();
}
hash = (29 * hash) + unknownFields.hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.ads.googleads.v10.resources.AdGroupAdAssetCombinationView parseFrom(
java.nio.ByteBuffer data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.ads.googleads.v10.resources.AdGroupAdAssetCombinationView parseFrom(
java.nio.ByteBuffer data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.ads.googleads.v10.resources.AdGroupAdAssetCombinationView parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.ads.googleads.v10.resources.AdGroupAdAssetCombinationView parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.ads.googleads.v10.resources.AdGroupAdAssetCombinationView parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.ads.googleads.v10.resources.AdGroupAdAssetCombinationView parseFrom(
byte[] data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.ads.googleads.v10.resources.AdGroupAdAssetCombinationView parseFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input);
}
public static com.google.ads.googleads.v10.resources.AdGroupAdAssetCombinationView parseFrom(
java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input, extensionRegistry);
}
public static com.google.ads.googleads.v10.resources.AdGroupAdAssetCombinationView parseDelimitedFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.ads.googleads.v10.resources.AdGroupAdAssetCombinationView parseDelimitedFrom(
java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseDelimitedWithIOException(PARSER, input, extensionRegistry);
}
public static com.google.ads.googleads.v10.resources.AdGroupAdAssetCombinationView parseFrom(
com.google.protobuf.CodedInputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input);
}
public static com.google.ads.googleads.v10.resources.AdGroupAdAssetCombinationView parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(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.resources.AdGroupAdAssetCombinationView 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 view on the usage of ad group ad asset combination.
* Now we only support AdGroupAdAssetCombinationView for Responsive Search Ads,
* with more ad types planned for the future.
* </pre>
*
* Protobuf type {@code google.ads.googleads.v10.resources.AdGroupAdAssetCombinationView}
*/
public static final class Builder extends
com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements
// @@protoc_insertion_point(builder_implements:google.ads.googleads.v10.resources.AdGroupAdAssetCombinationView)
com.google.ads.googleads.v10.resources.AdGroupAdAssetCombinationViewOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return com.google.ads.googleads.v10.resources.AdGroupAdAssetCombinationViewProto.internal_static_google_ads_googleads_v10_resources_AdGroupAdAssetCombinationView_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.ads.googleads.v10.resources.AdGroupAdAssetCombinationViewProto.internal_static_google_ads_googleads_v10_resources_AdGroupAdAssetCombinationView_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.ads.googleads.v10.resources.AdGroupAdAssetCombinationView.class, com.google.ads.googleads.v10.resources.AdGroupAdAssetCombinationView.Builder.class);
}
// Construct using com.google.ads.googleads.v10.resources.AdGroupAdAssetCombinationView.newBuilder()
private Builder() {
maybeForceBuilderInitialization();
}
private Builder(
com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
maybeForceBuilderInitialization();
}
private void maybeForceBuilderInitialization() {
if (com.google.protobuf.GeneratedMessageV3
.alwaysUseFieldBuilders) {
getServedAssetsFieldBuilder();
}
}
@java.lang.Override
public Builder clear() {
super.clear();
resourceName_ = "";
if (servedAssetsBuilder_ == null) {
servedAssets_ = java.util.Collections.emptyList();
bitField0_ = (bitField0_ & ~0x00000001);
} else {
servedAssetsBuilder_.clear();
}
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor
getDescriptorForType() {
return com.google.ads.googleads.v10.resources.AdGroupAdAssetCombinationViewProto.internal_static_google_ads_googleads_v10_resources_AdGroupAdAssetCombinationView_descriptor;
}
@java.lang.Override
public com.google.ads.googleads.v10.resources.AdGroupAdAssetCombinationView getDefaultInstanceForType() {
return com.google.ads.googleads.v10.resources.AdGroupAdAssetCombinationView.getDefaultInstance();
}
@java.lang.Override
public com.google.ads.googleads.v10.resources.AdGroupAdAssetCombinationView build() {
com.google.ads.googleads.v10.resources.AdGroupAdAssetCombinationView result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.ads.googleads.v10.resources.AdGroupAdAssetCombinationView buildPartial() {
com.google.ads.googleads.v10.resources.AdGroupAdAssetCombinationView result = new com.google.ads.googleads.v10.resources.AdGroupAdAssetCombinationView(this);
int from_bitField0_ = bitField0_;
result.resourceName_ = resourceName_;
if (servedAssetsBuilder_ == null) {
if (((bitField0_ & 0x00000001) != 0)) {
servedAssets_ = java.util.Collections.unmodifiableList(servedAssets_);
bitField0_ = (bitField0_ & ~0x00000001);
}
result.servedAssets_ = servedAssets_;
} else {
result.servedAssets_ = servedAssetsBuilder_.build();
}
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.resources.AdGroupAdAssetCombinationView) {
return mergeFrom((com.google.ads.googleads.v10.resources.AdGroupAdAssetCombinationView)other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.ads.googleads.v10.resources.AdGroupAdAssetCombinationView other) {
if (other == com.google.ads.googleads.v10.resources.AdGroupAdAssetCombinationView.getDefaultInstance()) return this;
if (!other.getResourceName().isEmpty()) {
resourceName_ = other.resourceName_;
onChanged();
}
if (servedAssetsBuilder_ == null) {
if (!other.servedAssets_.isEmpty()) {
if (servedAssets_.isEmpty()) {
servedAssets_ = other.servedAssets_;
bitField0_ = (bitField0_ & ~0x00000001);
} else {
ensureServedAssetsIsMutable();
servedAssets_.addAll(other.servedAssets_);
}
onChanged();
}
} else {
if (!other.servedAssets_.isEmpty()) {
if (servedAssetsBuilder_.isEmpty()) {
servedAssetsBuilder_.dispose();
servedAssetsBuilder_ = null;
servedAssets_ = other.servedAssets_;
bitField0_ = (bitField0_ & ~0x00000001);
servedAssetsBuilder_ =
com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders ?
getServedAssetsFieldBuilder() : null;
} else {
servedAssetsBuilder_.addAllMessages(other.servedAssets_);
}
}
}
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.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
com.google.ads.googleads.v10.resources.AdGroupAdAssetCombinationView parsedMessage = null;
try {
parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry);
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
parsedMessage = (com.google.ads.googleads.v10.resources.AdGroupAdAssetCombinationView) e.getUnfinishedMessage();
throw e.unwrapIOException();
} finally {
if (parsedMessage != null) {
mergeFrom(parsedMessage);
}
}
return this;
}
private int bitField0_;
private java.lang.Object resourceName_ = "";
/**
* <pre>
* Output only. The resource name of the ad group ad asset combination view. The
* combination ID is 128 bits long, where the upper 64 bits are stored in
* asset_combination_id_high, and the lower 64 bits are stored in
* asset_combination_id_low.
* AdGroupAd Asset Combination view resource names have the form:
* `customers/{customer_id}/adGroupAdAssetCombinationViews/{AdGroupAd.ad_group_id}~{AdGroupAd.ad.ad_id}~{AssetCombination.asset_combination_id_low}~{AssetCombination.asset_combination_id_high}`
* </pre>
*
* <code>string resource_name = 1 [(.google.api.field_behavior) = OUTPUT_ONLY, (.google.api.resource_reference) = { ... }</code>
* @return The resourceName.
*/
public java.lang.String getResourceName() {
java.lang.Object ref = resourceName_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
resourceName_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
* <pre>
* Output only. The resource name of the ad group ad asset combination view. The
* combination ID is 128 bits long, where the upper 64 bits are stored in
* asset_combination_id_high, and the lower 64 bits are stored in
* asset_combination_id_low.
* AdGroupAd Asset Combination view resource names have the form:
* `customers/{customer_id}/adGroupAdAssetCombinationViews/{AdGroupAd.ad_group_id}~{AdGroupAd.ad.ad_id}~{AssetCombination.asset_combination_id_low}~{AssetCombination.asset_combination_id_high}`
* </pre>
*
* <code>string resource_name = 1 [(.google.api.field_behavior) = OUTPUT_ONLY, (.google.api.resource_reference) = { ... }</code>
* @return The bytes for resourceName.
*/
public com.google.protobuf.ByteString
getResourceNameBytes() {
java.lang.Object ref = resourceName_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
resourceName_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
* <pre>
* Output only. The resource name of the ad group ad asset combination view. The
* combination ID is 128 bits long, where the upper 64 bits are stored in
* asset_combination_id_high, and the lower 64 bits are stored in
* asset_combination_id_low.
* AdGroupAd Asset Combination view resource names have the form:
* `customers/{customer_id}/adGroupAdAssetCombinationViews/{AdGroupAd.ad_group_id}~{AdGroupAd.ad.ad_id}~{AssetCombination.asset_combination_id_low}~{AssetCombination.asset_combination_id_high}`
* </pre>
*
* <code>string resource_name = 1 [(.google.api.field_behavior) = OUTPUT_ONLY, (.google.api.resource_reference) = { ... }</code>
* @param value The resourceName to set.
* @return This builder for chaining.
*/
public Builder setResourceName(
java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
resourceName_ = value;
onChanged();
return this;
}
/**
* <pre>
* Output only. The resource name of the ad group ad asset combination view. The
* combination ID is 128 bits long, where the upper 64 bits are stored in
* asset_combination_id_high, and the lower 64 bits are stored in
* asset_combination_id_low.
* AdGroupAd Asset Combination view resource names have the form:
* `customers/{customer_id}/adGroupAdAssetCombinationViews/{AdGroupAd.ad_group_id}~{AdGroupAd.ad.ad_id}~{AssetCombination.asset_combination_id_low}~{AssetCombination.asset_combination_id_high}`
* </pre>
*
* <code>string resource_name = 1 [(.google.api.field_behavior) = OUTPUT_ONLY, (.google.api.resource_reference) = { ... }</code>
* @return This builder for chaining.
*/
public Builder clearResourceName() {
resourceName_ = getDefaultInstance().getResourceName();
onChanged();
return this;
}
/**
* <pre>
* Output only. The resource name of the ad group ad asset combination view. The
* combination ID is 128 bits long, where the upper 64 bits are stored in
* asset_combination_id_high, and the lower 64 bits are stored in
* asset_combination_id_low.
* AdGroupAd Asset Combination view resource names have the form:
* `customers/{customer_id}/adGroupAdAssetCombinationViews/{AdGroupAd.ad_group_id}~{AdGroupAd.ad.ad_id}~{AssetCombination.asset_combination_id_low}~{AssetCombination.asset_combination_id_high}`
* </pre>
*
* <code>string resource_name = 1 [(.google.api.field_behavior) = OUTPUT_ONLY, (.google.api.resource_reference) = { ... }</code>
* @param value The bytes for resourceName to set.
* @return This builder for chaining.
*/
public Builder setResourceNameBytes(
com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
resourceName_ = value;
onChanged();
return this;
}
private java.util.List<com.google.ads.googleads.v10.common.AssetUsage> servedAssets_ =
java.util.Collections.emptyList();
private void ensureServedAssetsIsMutable() {
if (!((bitField0_ & 0x00000001) != 0)) {
servedAssets_ = new java.util.ArrayList<com.google.ads.googleads.v10.common.AssetUsage>(servedAssets_);
bitField0_ |= 0x00000001;
}
}
private com.google.protobuf.RepeatedFieldBuilderV3<
com.google.ads.googleads.v10.common.AssetUsage, com.google.ads.googleads.v10.common.AssetUsage.Builder, com.google.ads.googleads.v10.common.AssetUsageOrBuilder> servedAssetsBuilder_;
/**
* <pre>
* Output only. Served assets.
* </pre>
*
* <code>repeated .google.ads.googleads.v10.common.AssetUsage served_assets = 2 [(.google.api.field_behavior) = OUTPUT_ONLY];</code>
*/
public java.util.List<com.google.ads.googleads.v10.common.AssetUsage> getServedAssetsList() {
if (servedAssetsBuilder_ == null) {
return java.util.Collections.unmodifiableList(servedAssets_);
} else {
return servedAssetsBuilder_.getMessageList();
}
}
/**
* <pre>
* Output only. Served assets.
* </pre>
*
* <code>repeated .google.ads.googleads.v10.common.AssetUsage served_assets = 2 [(.google.api.field_behavior) = OUTPUT_ONLY];</code>
*/
public int getServedAssetsCount() {
if (servedAssetsBuilder_ == null) {
return servedAssets_.size();
} else {
return servedAssetsBuilder_.getCount();
}
}
/**
* <pre>
* Output only. Served assets.
* </pre>
*
* <code>repeated .google.ads.googleads.v10.common.AssetUsage served_assets = 2 [(.google.api.field_behavior) = OUTPUT_ONLY];</code>
*/
public com.google.ads.googleads.v10.common.AssetUsage getServedAssets(int index) {
if (servedAssetsBuilder_ == null) {
return servedAssets_.get(index);
} else {
return servedAssetsBuilder_.getMessage(index);
}
}
/**
* <pre>
* Output only. Served assets.
* </pre>
*
* <code>repeated .google.ads.googleads.v10.common.AssetUsage served_assets = 2 [(.google.api.field_behavior) = OUTPUT_ONLY];</code>
*/
public Builder setServedAssets(
int index, com.google.ads.googleads.v10.common.AssetUsage value) {
if (servedAssetsBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureServedAssetsIsMutable();
servedAssets_.set(index, value);
onChanged();
} else {
servedAssetsBuilder_.setMessage(index, value);
}
return this;
}
/**
* <pre>
* Output only. Served assets.
* </pre>
*
* <code>repeated .google.ads.googleads.v10.common.AssetUsage served_assets = 2 [(.google.api.field_behavior) = OUTPUT_ONLY];</code>
*/
public Builder setServedAssets(
int index, com.google.ads.googleads.v10.common.AssetUsage.Builder builderForValue) {
if (servedAssetsBuilder_ == null) {
ensureServedAssetsIsMutable();
servedAssets_.set(index, builderForValue.build());
onChanged();
} else {
servedAssetsBuilder_.setMessage(index, builderForValue.build());
}
return this;
}
/**
* <pre>
* Output only. Served assets.
* </pre>
*
* <code>repeated .google.ads.googleads.v10.common.AssetUsage served_assets = 2 [(.google.api.field_behavior) = OUTPUT_ONLY];</code>
*/
public Builder addServedAssets(com.google.ads.googleads.v10.common.AssetUsage value) {
if (servedAssetsBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureServedAssetsIsMutable();
servedAssets_.add(value);
onChanged();
} else {
servedAssetsBuilder_.addMessage(value);
}
return this;
}
/**
* <pre>
* Output only. Served assets.
* </pre>
*
* <code>repeated .google.ads.googleads.v10.common.AssetUsage served_assets = 2 [(.google.api.field_behavior) = OUTPUT_ONLY];</code>
*/
public Builder addServedAssets(
int index, com.google.ads.googleads.v10.common.AssetUsage value) {
if (servedAssetsBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureServedAssetsIsMutable();
servedAssets_.add(index, value);
onChanged();
} else {
servedAssetsBuilder_.addMessage(index, value);
}
return this;
}
/**
* <pre>
* Output only. Served assets.
* </pre>
*
* <code>repeated .google.ads.googleads.v10.common.AssetUsage served_assets = 2 [(.google.api.field_behavior) = OUTPUT_ONLY];</code>
*/
public Builder addServedAssets(
com.google.ads.googleads.v10.common.AssetUsage.Builder builderForValue) {
if (servedAssetsBuilder_ == null) {
ensureServedAssetsIsMutable();
servedAssets_.add(builderForValue.build());
onChanged();
} else {
servedAssetsBuilder_.addMessage(builderForValue.build());
}
return this;
}
/**
* <pre>
* Output only. Served assets.
* </pre>
*
* <code>repeated .google.ads.googleads.v10.common.AssetUsage served_assets = 2 [(.google.api.field_behavior) = OUTPUT_ONLY];</code>
*/
public Builder addServedAssets(
int index, com.google.ads.googleads.v10.common.AssetUsage.Builder builderForValue) {
if (servedAssetsBuilder_ == null) {
ensureServedAssetsIsMutable();
servedAssets_.add(index, builderForValue.build());
onChanged();
} else {
servedAssetsBuilder_.addMessage(index, builderForValue.build());
}
return this;
}
/**
* <pre>
* Output only. Served assets.
* </pre>
*
* <code>repeated .google.ads.googleads.v10.common.AssetUsage served_assets = 2 [(.google.api.field_behavior) = OUTPUT_ONLY];</code>
*/
public Builder addAllServedAssets(
java.lang.Iterable<? extends com.google.ads.googleads.v10.common.AssetUsage> values) {
if (servedAssetsBuilder_ == null) {
ensureServedAssetsIsMutable();
com.google.protobuf.AbstractMessageLite.Builder.addAll(
values, servedAssets_);
onChanged();
} else {
servedAssetsBuilder_.addAllMessages(values);
}
return this;
}
/**
* <pre>
* Output only. Served assets.
* </pre>
*
* <code>repeated .google.ads.googleads.v10.common.AssetUsage served_assets = 2 [(.google.api.field_behavior) = OUTPUT_ONLY];</code>
*/
public Builder clearServedAssets() {
if (servedAssetsBuilder_ == null) {
servedAssets_ = java.util.Collections.emptyList();
bitField0_ = (bitField0_ & ~0x00000001);
onChanged();
} else {
servedAssetsBuilder_.clear();
}
return this;
}
/**
* <pre>
* Output only. Served assets.
* </pre>
*
* <code>repeated .google.ads.googleads.v10.common.AssetUsage served_assets = 2 [(.google.api.field_behavior) = OUTPUT_ONLY];</code>
*/
public Builder removeServedAssets(int index) {
if (servedAssetsBuilder_ == null) {
ensureServedAssetsIsMutable();
servedAssets_.remove(index);
onChanged();
} else {
servedAssetsBuilder_.remove(index);
}
return this;
}
/**
* <pre>
* Output only. Served assets.
* </pre>
*
* <code>repeated .google.ads.googleads.v10.common.AssetUsage served_assets = 2 [(.google.api.field_behavior) = OUTPUT_ONLY];</code>
*/
public com.google.ads.googleads.v10.common.AssetUsage.Builder getServedAssetsBuilder(
int index) {
return getServedAssetsFieldBuilder().getBuilder(index);
}
/**
* <pre>
* Output only. Served assets.
* </pre>
*
* <code>repeated .google.ads.googleads.v10.common.AssetUsage served_assets = 2 [(.google.api.field_behavior) = OUTPUT_ONLY];</code>
*/
public com.google.ads.googleads.v10.common.AssetUsageOrBuilder getServedAssetsOrBuilder(
int index) {
if (servedAssetsBuilder_ == null) {
return servedAssets_.get(index); } else {
return servedAssetsBuilder_.getMessageOrBuilder(index);
}
}
/**
* <pre>
* Output only. Served assets.
* </pre>
*
* <code>repeated .google.ads.googleads.v10.common.AssetUsage served_assets = 2 [(.google.api.field_behavior) = OUTPUT_ONLY];</code>
*/
public java.util.List<? extends com.google.ads.googleads.v10.common.AssetUsageOrBuilder>
getServedAssetsOrBuilderList() {
if (servedAssetsBuilder_ != null) {
return servedAssetsBuilder_.getMessageOrBuilderList();
} else {
return java.util.Collections.unmodifiableList(servedAssets_);
}
}
/**
* <pre>
* Output only. Served assets.
* </pre>
*
* <code>repeated .google.ads.googleads.v10.common.AssetUsage served_assets = 2 [(.google.api.field_behavior) = OUTPUT_ONLY];</code>
*/
public com.google.ads.googleads.v10.common.AssetUsage.Builder addServedAssetsBuilder() {
return getServedAssetsFieldBuilder().addBuilder(
com.google.ads.googleads.v10.common.AssetUsage.getDefaultInstance());
}
/**
* <pre>
* Output only. Served assets.
* </pre>
*
* <code>repeated .google.ads.googleads.v10.common.AssetUsage served_assets = 2 [(.google.api.field_behavior) = OUTPUT_ONLY];</code>
*/
public com.google.ads.googleads.v10.common.AssetUsage.Builder addServedAssetsBuilder(
int index) {
return getServedAssetsFieldBuilder().addBuilder(
index, com.google.ads.googleads.v10.common.AssetUsage.getDefaultInstance());
}
/**
* <pre>
* Output only. Served assets.
* </pre>
*
* <code>repeated .google.ads.googleads.v10.common.AssetUsage served_assets = 2 [(.google.api.field_behavior) = OUTPUT_ONLY];</code>
*/
public java.util.List<com.google.ads.googleads.v10.common.AssetUsage.Builder>
getServedAssetsBuilderList() {
return getServedAssetsFieldBuilder().getBuilderList();
}
private com.google.protobuf.RepeatedFieldBuilderV3<
com.google.ads.googleads.v10.common.AssetUsage, com.google.ads.googleads.v10.common.AssetUsage.Builder, com.google.ads.googleads.v10.common.AssetUsageOrBuilder>
getServedAssetsFieldBuilder() {
if (servedAssetsBuilder_ == null) {
servedAssetsBuilder_ = new com.google.protobuf.RepeatedFieldBuilderV3<
com.google.ads.googleads.v10.common.AssetUsage, com.google.ads.googleads.v10.common.AssetUsage.Builder, com.google.ads.googleads.v10.common.AssetUsageOrBuilder>(
servedAssets_,
((bitField0_ & 0x00000001) != 0),
getParentForChildren(),
isClean());
servedAssets_ = null;
}
return servedAssetsBuilder_;
}
@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);
}
// @@protoc_insertion_point(builder_scope:google.ads.googleads.v10.resources.AdGroupAdAssetCombinationView)
}
// @@protoc_insertion_point(class_scope:google.ads.googleads.v10.resources.AdGroupAdAssetCombinationView)
private static final com.google.ads.googleads.v10.resources.AdGroupAdAssetCombinationView DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.ads.googleads.v10.resources.AdGroupAdAssetCombinationView();
}
public static com.google.ads.googleads.v10.resources.AdGroupAdAssetCombinationView getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<AdGroupAdAssetCombinationView>
PARSER = new com.google.protobuf.AbstractParser<AdGroupAdAssetCombinationView>() {
@java.lang.Override
public AdGroupAdAssetCombinationView parsePartialFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return new AdGroupAdAssetCombinationView(input, extensionRegistry);
}
};
public static com.google.protobuf.Parser<AdGroupAdAssetCombinationView> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<AdGroupAdAssetCombinationView> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.ads.googleads.v10.resources.AdGroupAdAssetCombinationView getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
googleads/google-ads-java
|
google-ads-stubs-v10/src/main/java/com/google/ads/googleads/v10/resources/AdGroupAdAssetCombinationView.java
|
Java
|
apache-2.0
| 41,581 |
using NLog;
using PsISEProjectExplorer.UI.Workers;
using System;
using System.Collections.Generic;
using System.ComponentModel;
namespace PsISEProjectExplorer.UI.ViewModel
{
public class IndexingSearchingModel : BaseViewModel
{
private static readonly Logger Logger = LogManager.GetCurrentClassLogger();
private IList<BackgroundIndexer> BackgroundIndexers { get; set; }
private IList<BackgroundSearcher> BackgroundSearchers { get; set; }
private EventHandler<IndexerResult> IndexerResultHandler { get; set; }
private EventHandler<string> IndexerProgressHandler { get; set; }
private EventHandler<SearcherResult> SearcherResultHandler { get; set; }
public IndexingSearchingModel(EventHandler<SearcherResult> searcherResultHandler, EventHandler<IndexerResult> indexerResultHandler, EventHandler<string> indexerProgressHandler)
{
this.SearcherResultHandler = searcherResultHandler;
this.IndexerResultHandler = indexerResultHandler;
this.IndexerProgressHandler = indexerProgressHandler;
this.BackgroundIndexers = new List<BackgroundIndexer>();
this.BackgroundSearchers = new List<BackgroundSearcher>();
}
// running in UI thread
public void ReindexSearchTree(BackgroundIndexerParams indexerParams)
{
if (indexerParams.PathsChanged == null)
{
lock (this.BackgroundIndexers)
{
foreach (var ind in this.BackgroundIndexers)
{
ind.CancelAsync();
}
this.BackgroundIndexers.Clear();
}
}
var indexer = new BackgroundIndexer();
indexer.RunWorkerCompleted += this.BackgroundIndexerWorkCompleted;
indexer.ProgressChanged += this.BackgroundIndexerProgressChanged;
indexer.RunWorkerAsync(indexerParams);
lock (this.BackgroundIndexers)
{
this.BackgroundIndexers.Add(indexer);
}
}
// running in Indexing or UI thread
public void RunSearch(BackgroundSearcherParams searcherParams)
{
if (searcherParams.Path == null)
{
lock (this.BackgroundSearchers)
{
foreach (var sear in this.BackgroundSearchers)
{
sear.CancelAsync();
}
this.BackgroundSearchers.Clear();
}
}
var searcher = new BackgroundSearcher();
searcher.RunWorkerCompleted += this.BackgroundSearcherWorkCompleted;
if (searcherParams.Path != null)
{
searcher.RunWorkerSync(searcherParams);
}
else
{
searcher.RunWorkerAsync(searcherParams);
lock (this.BackgroundSearchers)
{
this.BackgroundSearchers.Add(searcher);
}
}
}
// running in UI thread
private void BackgroundIndexerWorkCompleted(object sender, RunWorkerCompletedEventArgs e)
{
var indexer = sender as BackgroundIndexer;
if (indexer != null)
{
lock (this.BackgroundIndexers)
{
this.BackgroundIndexers.Remove(indexer);
}
}
if (e.Cancelled)
{
this.IndexerResultHandler(this, null);
return;
}
var result = (IndexerResult)e.Result;
if (result == null || !result.IsChanged)
{
this.IndexerResultHandler(this, null);
return;
}
Logger.Debug("Indexing ended");
this.IndexerResultHandler(this, result);
}
// running in Indexing thread
private void BackgroundIndexerProgressChanged(object sender, ProgressChangedEventArgs e)
{
if (this.IndexerProgressHandler != null)
{
Logger.Debug(String.Format("Indexer progress, path: {0}", (string)e.UserState));
this.IndexerProgressHandler(this, (string)e.UserState);
}
}
// running in Indexing or UI thread
private void BackgroundSearcherWorkCompleted(object sender, RunWorkerCompletedEventArgs e)
{
var searcher = sender as BackgroundSearcher;
if (searcher != null)
{
lock (this.BackgroundSearchers)
{
this.BackgroundSearchers.Remove(searcher);
}
}
if (e.Cancelled)
{
this.SearcherResultHandler(this, null);
return;
}
var result = (SearcherResult)e.Result;
if (result == null)
{
this.SearcherResultHandler(this, null);
return;
}
Logger.Debug(String.Format("Searching ended, path: {0}", result.Path ?? "null"));
this.SearcherResultHandler(this, result);
}
}
}
|
lukaszgasior/PsISEProjectExplorer
|
PsISEProjectExplorer/UI/ViewModel/IndexingSearchingModel.cs
|
C#
|
apache-2.0
| 5,468 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace FrameworkLibrary
{
public class URIHelper
{
public static string GetCurrentVirtualPath(bool asAbsPath = false, bool includeQueryString = false)
{
string virtualPath = HttpContext.Current.Request.Path;
if (virtualPath.StartsWith("~/" + HttpContext.Current.Request.Url.Host))
virtualPath = virtualPath.Replace("~/" + HttpContext.Current.Request.Url.Host, "~");
if (HttpContext.Current.Request.ApplicationPath != "/")
{
virtualPath = virtualPath.ToLower().Replace(HttpContext.Current.Request.ApplicationPath.ToLower(), "");
}
if (virtualPath.ToLower().Contains("~/default.aspx"))
virtualPath = "~/";
virtualPath = URIHelper.ConvertAbsUrlToTilda(virtualPath);
if (asAbsPath)
virtualPath = ConvertToAbsUrl(virtualPath);
if (virtualPath == "")
virtualPath = "~/";
/*var details = MediaDetailsMapper.GetByVirtualPath(virtualPath, false);
if (details == null)
{
if (!virtualPath.Contains(FrameworkSettings.RootMediaDetail.VirtualPath))
virtualPath = virtualPath.Replace("~/", FrameworkSettings.RootMediaDetail.VirtualPath);
}*/
return virtualPath;
}
public static string ConvertAbsPathToAbsUrl(string absPath)
{
var absUrl = ConvertToAbsUrl(absPath.Replace(BasePath, "~/"));
return absUrl;
}
public static string RemoveTrailingSlash(string url)
{
if (url.EndsWith("/"))
{
int lastIndex = url.LastIndexOf('/');
return url.Remove(lastIndex);
}
else
return url;
}
public static string Prepair(string url)
{
return RemoveTrailingSlash(url.ToLower());
}
public static string PrepairUri(string uri)
{
uri = StringHelper.RemoveSpecialChars(uri);
return uri.Trim().Replace(" ", "-").ToLower();
}
public static bool IsSame(string url1, string url2)
{
url1 = URIHelper.ConvertToAbsUrl(url1);
url2 = URIHelper.ConvertToAbsUrl(url2);
if (Prepair(url1) == Prepair(url2))
return true;
return false;
}
public static bool Uri1ContainsUri2(string url1, string url2)
{
if (Prepair(url1).Contains(Prepair(url2)))
return true;
return false;
}
public static string UrlEncode(string str)
{
return HttpContext.Current.Server.UrlEncode(str);
}
public static string UrlDecode(string str)
{
return HttpContext.Current.Server.UrlDecode(str);
}
public static IEnumerable<string> GetUriSegments(string url, string ignoreUri = "")
{
IEnumerable<string> uriSegments = new List<string>();
if (ignoreUri != "")
url = url.Replace(ignoreUri, "");
url = url.Replace(ConvertAbsUrlToTilda(BaseUrl), "");
if (url.StartsWith("/"))
url = url.Remove(0, 1);
if (url.EndsWith("/"))
url = url.Remove(url.Length - 1);
if (url != "")
uriSegments = url.Split('/');
return uriSegments;
}
public static string GetParentPath(string url, int levelsUp)
{
var segments = GetParentPathList(url, levelsUp);
var path = String.Join("/", segments);
if (!path.EndsWith("/"))
path += "/";
path = URIHelper.ConvertAbsUrlToTilda(path);
return path;
}
public static IEnumerable<string> GetParentPathList(string url, int levelsUp)
{
var segments = GetUriSegments(url).ToList();
var moveUpBy = (segments.Count - levelsUp);
if (moveUpBy > 0)
{
var count = segments.Count - moveUpBy;
segments.RemoveRange(moveUpBy, count);
}
return segments;
}
public static string ConvertToAbsUrl(string relOrTildaToRootPath)
{
if (relOrTildaToRootPath == null || relOrTildaToRootPath.Trim() == "")
return "";
if (relOrTildaToRootPath.Contains("://"))
return relOrTildaToRootPath;
var segments = GetUriSegments(relOrTildaToRootPath).ToList();
var baseUrlSegments = GetUriSegments(HttpContext.Current.Request.ApplicationPath).ToList();
for (int i = 0; i < segments.Count; i++)
{
if (baseUrlSegments.Count <= i)
break;
if (segments[i] == baseUrlSegments[i])
segments.RemoveAt(i);
}
relOrTildaToRootPath = "";
for (int i = 0; i < segments.Count; i++)
relOrTildaToRootPath += segments[i] + "/";
if (segments.Count > 0)
{
if (segments[segments.Count - 1].Contains("."))
relOrTildaToRootPath = RemoveTrailingSlash(relOrTildaToRootPath);
}
var url = (BaseUrl + relOrTildaToRootPath).Replace("\\", "/");
if((url.Contains("?") || url.Contains("#")) && url.EndsWith("/"))
{
url = url.Substring(0, url.Length - 1);
}
if (url.StartsWith("//"))
{
url = url.Substring(2);
}
else if(url.StartsWith("/"))
{
url = url.Substring(1);
}
return url;
}
public static bool IsCMSLoginRequest(string url)
{
url = url.ToLower();
if (url.Contains("/admin/") || url.Contains("/login/"))
return true;
return false;
}
public static string BaseUrl
{
get
{
var baseUrl = (string)ContextHelper.GetFromRequestContext("BaseUrl");
if (!string.IsNullOrEmpty(baseUrl))
return baseUrl;
string appPath = HttpContext.Current.Request.ApplicationPath;
if (!appPath.EndsWith("/"))
appPath = appPath + "/";
string url = HttpContext.Current.Request.Url.Scheme + "://" + HttpContext.Current.Request.Url.Authority + appPath;
if (IsSSL())
url = url.Replace("http:", "https:");
url = url.ToLower();
ContextHelper.SetToRequestContext("BaseUrl", url);
return url;
}
}
public static string BaseUrlWithLanguage
{
get
{
var baseUrlWithLanguage = (string)ContextHelper.GetFromRequestContext("BaseUrlWithLanguage");
if (!string.IsNullOrEmpty(baseUrlWithLanguage))
return baseUrlWithLanguage;
var url = LanguageBaseUrl(FrameworkSettings.GetCurrentLanguage());
ContextHelper.SetToRequestContext("BaseUrlWithLanguage", url);
return url.ToLower();
}
}
public static string LanguageBaseUrl(Language language)
{
var url = BaseUrl;
if (LanguagesMapper.CountAllActive() > 1)
url += language.UriSegment + "/".ToLower();
return url;
}
public static string GetBaseUrlWithLanguage(Language language)
{
return BaseUrl + language.UriSegment + "/";
}
public static bool StartsWithLanguage(string url)
{
IEnumerable<Language> languages = LanguagesMapper.GetAllActive();
url = ConvertAbsUrlToTilda(url);
foreach (Language language in languages)
{
string url2 = URIHelper.ConvertAbsUrlToTilda(GetBaseUrlWithLanguage(language));
if (url2.EndsWith("/"))
url2 = url2.Remove(url2.Length - 1);
if (url.StartsWith(url2))
return true;
}
return false;
}
private static string _basePath = "";
public static string BasePath
{
get
{
/*string appPath = AppDomain.CurrentDomain.BaseDirectory;
if (!appPath.EndsWith("/"))
appPath = appPath + "/";
return appPath;*/
if (!string.IsNullOrEmpty(_basePath))
return _basePath;
_basePath = HttpContext.Current.Server.MapPath("~/");
return _basePath;
}
}
public static string ConvertAbsUrlToTilda(string absUrl)
{
absUrl = absUrl.ToLower().Trim();
if (absUrl == "")
return "";
if (absUrl.StartsWith("~/"))
return absUrl;
if (!absUrl.Contains("://"))
{
if(absUrl.StartsWith("/"))
{
absUrl = absUrl.Substring(1, absUrl.Length-1);
absUrl = (BaseUrl + absUrl);
}
}
if (absUrl.StartsWith("/"))
absUrl = BaseUrl + absUrl.Remove(0, 1);
absUrl = absUrl.Replace(BaseUrl, "~/").Replace("~//", "~/");
if (!absUrl.EndsWith("/") && !absUrl.Contains("?") && !absUrl.Contains("#") && !absUrl.Contains("."))
{
absUrl = absUrl + "/";
}
if (!absUrl.StartsWith("~/"))
absUrl = "~/" + absUrl;
return absUrl;
}
public static string ConvertToAbsPath(string relOrTildaPath)
{
if (relOrTildaPath.Contains(":/") || relOrTildaPath.Contains(":\\"))
return relOrTildaPath;
return ConvertToAbsUrl(relOrTildaPath).Replace(BaseUrl, BasePath);
}
public static bool IsSSL()
{
bool isSSL = false;
if (HttpContext.Current.Request.ServerVariables["HTTP_CLUSTER_HTTPS"] != null && HttpContext.Current.Request.ServerVariables["HTTP_CLUSTER_HTTPS"] == "on")
isSSL = true;
if (!isSSL)
isSSL = Request.IsSecureConnection;
return isSSL;
}
public static void ForceSSL()
{
if (!IsSSL())
Response.Redirect(Request.Url.AbsoluteUri.Replace("http:", "https:"));
}
public static void ForceNonSSL()
{
if (IsSSL())
Response.Redirect(Request.Url.AbsoluteUri.Replace("https:", "http:"));
}
private static HttpRequest Request
{
get { return HttpContext.Current.Request; }
}
private static HttpResponse Response
{
get { return HttpContext.Current.Response; }
}
}
}
|
MacdonaldRobinson/FlexDotnetCMS
|
FrameworkLibrary/Helpers/URIHelper.cs
|
C#
|
apache-2.0
| 11,376 |
# -*- test-case-name: txdav.caldav.datastore -*-
##
# Copyright (c) 2010-2017 Apple Inc. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
##
"""
Tests for common calendar store API functions.
"""
from StringIO import StringIO
from twisted.internet.defer import Deferred, inlineCallbacks, returnValue, \
maybeDeferred
from twisted.internet.protocol import Protocol
from twext.python.clsprop import classproperty
from twistedcaldav.ical import Component as VComponent
from twext.python.filepath import CachingFilePath as FilePath
from twext.enterprise.ienterprise import AlreadyFinishedError
from txdav.xml.element import WebDAVUnknownElement
from txdav.idav import IPropertyStore, IDataStore
from txdav.base.propertystore.base import PropertyName
from txdav.common.icommondatastore import HomeChildNameAlreadyExistsError, \
ICommonTransaction, InvalidComponentForStoreError, InvalidUIDError, \
ObjectResourceNameNotAllowedError
from txdav.common.icommondatastore import InvalidObjectResourceError
from txdav.common.icommondatastore import NoSuchHomeChildError
from txdav.common.icommondatastore import ObjectResourceNameAlreadyExistsError
from txdav.common.inotifications import INotificationObject
from txdav.common.datastore.test.util import CommonCommonTests
from txdav.caldav.icalendarstore import (
ICalendarObject, ICalendarHome,
ICalendar, ICalendarTransaction,
ComponentUpdateState)
from txdav.common.datastore.test.util import transactionClean
from txdav.common.icommondatastore import ConcurrentModification
from twistedcaldav.ical import Component
from twistedcaldav.config import config
from calendarserver.push.ipush import PushPriority
import hashlib
import json
storePath = FilePath(__file__).parent().child("calendar_store")
homeRoot = storePath.child("ho").child("me").child("home1")
cal1Root = homeRoot.child("calendar_1")
homeSplitsRoot = storePath.child("ho").child("me").child("home_splits")
cal1SplitsRoot = homeSplitsRoot.child("calendar_1")
cal2SplitsRoot = homeSplitsRoot.child("calendar_2")
homeNoSplitsRoot = storePath.child("ho").child("me").child("home_no_splits")
cal1NoSplitsRoot = homeNoSplitsRoot.child("calendar_1")
homeDefaultsRoot = storePath.child("ho").child("me").child("home_defaults")
cal1DefaultsRoot = homeDefaultsRoot.child("calendar_1")
calendar1_objectNames = [
"1.ics",
"2.ics",
"3.ics",
"4.ics",
"5.ics",
]
home1_calendarNames = [
"calendar_1",
"calendar_2",
"calendar_empty",
]
OTHER_HOME_UID = "home_splits"
test_event_text = """BEGIN:VCALENDAR
VERSION:2.0
PRODID:-//Apple Inc.//iCal 4.0.1//EN
CALSCALE:GREGORIAN
BEGIN:VTIMEZONE
TZID:US/Pacific
BEGIN:DAYLIGHT
TZOFFSETFROM:-0800
RRULE:FREQ=YEARLY;BYMONTH=3;BYDAY=2SU
DTSTART:20070311T020000
TZNAME:PDT
TZOFFSETTO:-0700
END:DAYLIGHT
BEGIN:STANDARD
TZOFFSETFROM:-0700
RRULE:FREQ=YEARLY;BYMONTH=11;BYDAY=1SU
DTSTART:20071104T020000
TZNAME:PST
TZOFFSETTO:-0800
END:STANDARD
END:VTIMEZONE
BEGIN:VEVENT
CREATED:20100203T013849Z
UID:uid-test
DTEND;TZID=US/Pacific:20100207T173000
TRANSP:OPAQUE
SUMMARY:New Event
DTSTART;TZID=US/Pacific:20100207T170000
DTSTAMP:20100203T013909Z
SEQUENCE:3
X-APPLE-DROPBOX:/calendars/users/wsanchez/dropbox/uid-test.dropbox
BEGIN:VALARM
X-WR-ALARMUID:1377CCC7-F85C-4610-8583-9513D4B364E1
TRIGGER:-PT20M
ATTACH:Basso
ACTION:AUDIO
END:VALARM
END:VEVENT
END:VCALENDAR
""".replace("\n", "\r\n")
test_event_notCalDAV_text = """BEGIN:VCALENDAR
VERSION:2.0
PRODID:-//Apple Inc.//iCal 4.0.1//EN
CALSCALE:GREGORIAN
BEGIN:VEVENT
CREATED:20100203T013849Z
UID:test-bad1
DTEND:20100207T173000Z
TRANSP:OPAQUE
SUMMARY:New Event
DTSTART:20100207T170000Z
DTSTAMP:20100203T013909Z
SEQUENCE:3
END:VEVENT
BEGIN:VEVENT
CREATED:20100203T013849Z
UID:test-bad2
DTEND:20100207T173000Z
TRANSP:OPAQUE
SUMMARY:New Event
DTSTART:20100207T170000Z
DTSTAMP:20100203T013909Z
SEQUENCE:3
END:VEVENT
END:VCALENDAR
""".replace("\n", "\r\n")
event1modified_text = test_event_text.replace(
"\r\nUID:uid-test\r\n",
"\r\nUID:uid1\r\n"
)
class CaptureProtocol(Protocol):
"""
A proocol that captures the data delivered to it, and calls back a Deferred
with that data.
@ivar deferred: a L{Deferred} which will be called back with all the data
yet delivered to C{dataReceived} when C{connectionLost} is called.
"""
def __init__(self):
self.deferred = Deferred()
self.io = StringIO()
self.dataReceived = self.io.write
def connectionLost(self, reason):
self.deferred.callback(self.io.getvalue())
class CommonTests(CommonCommonTests):
"""
Tests for common functionality of interfaces defined in
L{txdav.caldav.icalendarstore}.
"""
metadata1 = {
"accessMode": "PUBLIC",
"isScheduleObject": True,
"scheduleTag": "abc",
"scheduleEtags": (),
"hasPrivateComment": False,
}
metadata2 = {
"accessMode": "PRIVATE",
"isScheduleObject": False,
"scheduleTag": "",
"scheduleEtags": (),
"hasPrivateComment": False,
}
metadata3 = {
"accessMode": "PUBLIC",
"isScheduleObject": None,
"scheduleTag": "abc",
"scheduleEtags": (),
"hasPrivateComment": True,
}
metadata4 = {
"accessMode": "PUBLIC",
"isScheduleObject": True,
"scheduleTag": "abc4",
"scheduleEtags": (),
"hasPrivateComment": False,
}
metadata5 = {
"accessMode": "PUBLIC",
"isScheduleObject": True,
"scheduleTag": "abc5",
"scheduleEtags": (),
"hasPrivateComment": False,
}
md5Values = (
hashlib.md5("1234").hexdigest(),
hashlib.md5("5678").hexdigest(),
hashlib.md5("9ABC").hexdigest(),
hashlib.md5("DEFG").hexdigest(),
hashlib.md5("HIJK").hexdigest(),
)
@classproperty(cache=False)
def requirements(cls): # @NoSelf
metadata1 = cls.metadata1.copy()
metadata2 = cls.metadata2.copy()
metadata3 = cls.metadata3.copy()
metadata4 = cls.metadata4.copy()
metadata5 = cls.metadata5.copy()
return {
"home1": {
"calendar_1": {
"1.ics": (cal1Root.child("1.ics").getContent(), metadata1),
"2.ics": (cal1Root.child("2.ics").getContent(), metadata2),
"3.ics": (cal1Root.child("3.ics").getContent(), metadata3),
"4.ics": (cal1Root.child("4.ics").getContent(), metadata4),
"5.ics": (cal1Root.child("5.ics").getContent(), metadata5),
},
"calendar_2": {},
"calendar_empty": {},
"not_a_calendar": None
},
"home_splits": {
"calendar_1": {
"1.ics": (cal1SplitsRoot.child("1.ics").getContent(), metadata1),
"2.ics": (cal1SplitsRoot.child("2.ics").getContent(), metadata2),
"3.ics": (cal1SplitsRoot.child("3.ics").getContent(), metadata3),
},
"calendar_2": {
"1.ics": (cal2SplitsRoot.child("1.ics").getContent(), metadata1),
"2.ics": (cal2SplitsRoot.child("2.ics").getContent(), metadata2),
"3.ics": (cal2SplitsRoot.child("3.ics").getContent(), metadata3),
"4.ics": (cal2SplitsRoot.child("4.ics").getContent(), metadata4),
"5.ics": (cal2SplitsRoot.child("5.ics").getContent(), metadata4),
},
},
"home_no_splits": {
"calendar_1": {
"1.ics": (cal1NoSplitsRoot.child("1.ics").getContent(), metadata1),
"2.ics": (cal1NoSplitsRoot.child("2.ics").getContent(), metadata2),
"3.ics": (cal1NoSplitsRoot.child("3.ics").getContent(), metadata3),
},
},
"home_splits_shared": {
"calendar_1": {},
},
"home_defaults": {
"calendar_1": {
"1.ics": (cal1DefaultsRoot.child("1.ics").getContent(), metadata1),
"3.ics": (cal1DefaultsRoot.child("3.ics").getContent(), metadata3),
},
"inbox": {},
},
}
md5s = {
"home1": {
"calendar_1": {
"1.ics": md5Values[0],
"2.ics": md5Values[1],
"3.ics": md5Values[2],
"4.ics": md5Values[3],
},
"calendar_2": {},
"calendar_empty": {},
"not_a_calendar": None
},
"home_splits": {
"calendar_1": {
"1.ics": md5Values[0],
"2.ics": md5Values[1],
"3.ics": md5Values[2],
},
"calendar_2": {
"1.ics": md5Values[0],
"2.ics": md5Values[1],
"3.ics": md5Values[2],
"4.ics": md5Values[3],
"5.ics": md5Values[4],
},
},
"home_no_splits": {
"calendar_1": {
"1.ics": md5Values[0],
"2.ics": md5Values[1],
"3.ics": md5Values[2],
},
},
}
def test_calendarStoreProvides(self):
"""
The calendar store provides L{IDataStore} and its required attributes.
"""
calendarStore = self.storeUnderTest()
self.assertProvides(IDataStore, calendarStore)
def test_transactionProvides(self):
"""
The transactions generated by the calendar store provide
L{ICommonStoreTransaction}, L{ICalendarTransaction}, and their
respectively required attributes.
"""
txn = self.transactionUnderTest()
self.assertProvides(ICommonTransaction, txn)
self.assertProvides(ICalendarTransaction, txn)
@inlineCallbacks
def test_homeProvides(self):
"""
The calendar homes generated by the calendar store provide
L{ICalendarHome} and its required attributes.
"""
self.assertProvides(ICalendarHome, (yield self.homeUnderTest()))
@inlineCallbacks
def test_calendarProvides(self):
"""
The calendars generated by the calendar store provide L{ICalendar} and
its required attributes.
"""
self.assertProvides(ICalendar, (yield self.calendarUnderTest()))
@inlineCallbacks
def test_calendarObjectProvides(self):
"""
The calendar objects generated by the calendar store provide
L{ICalendarObject} and its required attributes.
"""
self.assertProvides(
ICalendarObject, (yield self.calendarObjectUnderTest())
)
@inlineCallbacks
def notificationUnderTest(self):
txn = self.transactionUnderTest()
notifications = yield txn.notificationsWithUID("home1", create=True)
yield notifications.writeNotificationObject(
"abc",
json.loads("{\"notification-type\":\"invite-notification\"}"),
json.loads("{\"notification-type\":\"invite-notification\"}"),
)
notificationObject = yield notifications.notificationObjectWithUID("abc")
returnValue(notificationObject)
@inlineCallbacks
def test_notificationObjectProvides(self):
"""
The objects retrieved from the notification home (the object returned
from L{notificationsWithUID}) provide L{INotificationObject}.
"""
notificationObject = yield self.notificationUnderTest()
self.assertProvides(INotificationObject, notificationObject)
@inlineCallbacks
def test_notificationSyncToken(self):
"""
L{ICalendar.resourceNamesSinceToken} will return the names of calendar
objects changed or deleted since
"""
txn = self.transactionUnderTest()
coll = yield txn.notificationsWithUID("home1", create=True)
yield coll.writeNotificationObject(
"1",
json.loads("{\"notification-type\":\"invite-notification\"}"),
json.loads("{\"notification-type\":\"invite-notification\"}"),
)
st = yield coll.syncToken()
yield coll.writeNotificationObject(
"2",
json.loads("{\"notification-type\":\"invite-notification\"}"),
json.loads("{\"notification-type\":\"invite-notification\"}"),
)
rev = self.token2revision(st)
yield coll.removeNotificationObjectWithUID("1")
st2 = yield coll.syncToken()
rev2 = self.token2revision(st2)
changed, deleted, invalid = yield coll.resourceNamesSinceToken(rev)
self.assertEquals(set(changed), set(["2.xml"]))
self.assertEquals(set(deleted), set(["1.xml"]))
self.assertEquals(len(invalid), 0)
changed, deleted, invalid = yield coll.resourceNamesSinceToken(rev2)
self.assertEquals(set(changed), set([]))
self.assertEquals(set(deleted), set([]))
self.assertEquals(len(invalid), 0)
@inlineCallbacks
def test_replaceNotification(self):
"""
L{INotificationCollection.writeNotificationObject} will silently
overwrite the notification object.
"""
notifications = yield self.transactionUnderTest().notificationsWithUID(
"home1", create=True
)
yield notifications.writeNotificationObject(
"abc",
json.loads("{\"notification-type\":\"invite-notification\"}"),
json.loads("{\"notification-type\":\"invite-notification\"}"),
)
yield notifications.writeNotificationObject(
"abc",
json.loads("{\"notification-type\":\"invite-notification\"}"),
json.loads("{\"notification-type\":\"invite-notification\",\"summary\":\"a summary\"}"),
)
abc = yield notifications.notificationObjectWithUID("abc")
self.assertEquals(
(yield abc.notificationData()),
json.loads("{\"notification-type\":\"invite-notification\",\"summary\":\"a summary\"}"),
)
@inlineCallbacks
def test_addRemoveNotification(self):
"""
L{INotificationCollection.writeNotificationObject} will silently
overwrite the notification object.
"""
# Prime the home collection first
yield self.transactionUnderTest().notificationsWithUID(
"home1", create=True
)
yield self.commit()
notifications = yield self.transactionUnderTest().notificationsWithUID(
"home1"
)
self.notifierFactory.reset()
yield notifications.writeNotificationObject(
"abc",
json.loads("{\"notification-type\":\"invite-notification\"}"),
json.loads("{\"notification-type\":\"invite-notification\"}"),
)
# notify is called prior to commit
self.assertEquals(
set(self.notifierFactory.history),
set([
("/CalDAV/example.com/home1/", PushPriority.high),
("/CalDAV/example.com/home1/notification/", PushPriority.high),
])
)
yield self.commit()
notifications = yield self.transactionUnderTest().notificationsWithUID(
"home1"
)
self.notifierFactory.reset()
yield notifications.removeNotificationObjectWithUID("abc")
abc = yield notifications.notificationObjectWithUID("abc")
self.assertEquals(abc, None)
# notify is called prior to commit
self.assertEquals(
set(self.notifierFactory.history),
set([
("/CalDAV/example.com/home1/", PushPriority.high),
("/CalDAV/example.com/home1/notification/", PushPriority.high),
])
)
yield self.commit()
@inlineCallbacks
def test_loadAllNotifications(self):
"""
L{INotificationCollection.writeNotificationObject} will silently
overwrite the notification object.
"""
notifications = yield self.transactionUnderTest().notificationsWithUID(
"home1", create=True
)
yield notifications.writeNotificationObject(
"abc",
json.loads("{\"notification-type\":\"invite-notification\"}"),
json.loads("{\"notification-type\":\"invite-notification\"}"),
)
yield notifications.writeNotificationObject(
"def",
json.loads("{\"notification-type\":\"invite-notification\"}"),
json.loads("{\"notification-type\":\"invite-notification\",\"summary\":\"a summary\"}"),
)
yield self.commit()
notifications = yield self.transactionUnderTest().notificationsWithUID(
"home1"
)
allObjects = yield notifications.notificationObjects()
self.assertEqual(set([obj.uid() for obj in allObjects]),
set(["abc", "def"]))
@inlineCallbacks
def test_notificationObjectMetaData(self):
"""
The objects retrieved from the notification home have various
methods which return metadata values.
"""
notification = yield self.notificationUnderTest()
self.assertIsInstance(notification.md5(), basestring)
self.assertIsInstance(notification.size(), int)
self.assertIsInstance(notification.created(), int)
self.assertIsInstance(notification.modified(), int)
@inlineCallbacks
def test_notificationObjectParent(self):
"""
L{INotificationObject.notificationCollection} returns the
L{INotificationCollection} that the object was retrieved from.
"""
txn = self.transactionUnderTest()
collection = yield txn.notificationsWithUID("home1", create=True)
notification = yield self.notificationUnderTest()
self.assertIdentical(collection, notification.notificationCollection())
@inlineCallbacks
def test_notifierID(self):
home = yield self.homeUnderTest()
self.assertEquals(home.notifierID(), ("CalDAV", "home1",))
calendar = yield home.calendarWithName("calendar_1")
self.assertEquals(calendar.notifierID(), ("CalDAV", "home1/calendar_1",))
@inlineCallbacks
def test_displayNameNone(self):
"""
L{ICalendarHome.calendarWithName} returns C{None} for calendars which
do not exist.
"""
home = (yield self.homeUnderTest())
calendar = (yield home.calendarWithName("calendar_1"))
name = (yield calendar.displayName())
self.assertEquals(name, None)
@inlineCallbacks
def test_setDisplayName(self):
"""
L{ICalendarHome.calendarWithName} returns C{None} for calendars which
do not exist.
"""
home = (yield self.homeUnderTest())
calendar = (yield home.calendarWithName("calendar_1"))
calendar.setDisplayName(u"quux")
name = calendar.displayName()
self.assertEquals(name, u"quux")
calendar.setDisplayName(None)
name = calendar.displayName()
self.assertEquals(name, None)
@inlineCallbacks
def test_setDisplayNameBytes(self):
"""
L{ICalendarHome.calendarWithName} returns C{None} for calendars which
do not exist.
"""
home = (yield self.homeUnderTest())
calendar = (yield home.calendarWithName("calendar_1"))
self.assertRaises(ValueError, calendar.setDisplayName, "quux")
@inlineCallbacks
def test_calendarHomeWithUID_exists(self):
"""
Finding an existing calendar home by UID results in an object that
provides L{ICalendarHome} and has a C{uid()} method that returns the
same value that was passed in.
"""
calendarHome = (yield self.transactionUnderTest()
.calendarHomeWithUID("home1"))
self.assertEquals(calendarHome.uid(), "home1")
self.assertProvides(ICalendarHome, calendarHome)
@inlineCallbacks
def test_calendarHomeWithUID_absent(self):
"""
L{ICommonStoreTransaction.calendarHomeWithUID} should return C{None}
when asked for a non-existent calendar home.
"""
txn = self.transactionUnderTest()
self.assertEquals((yield txn.calendarHomeWithUID("xyzzy")), None)
@inlineCallbacks
def test_calendarTasks_exists(self):
"""
L{ICalendarHome.createdHome} creates a calendar only, or a calendar and tasks
collection only, in addition to inbox.
"""
self.patch(config, "RestrictCalendarsToOneComponentType", False)
home1 = yield self.transactionUnderTest().calendarHomeWithUID("home_provision1", create=True)
for name in ("calendar", "inbox",):
calendar = yield home1.calendarWithName(name)
if calendar is None:
self.fail("calendar %r didn't exist" % (name,))
self.assertProvides(ICalendar, calendar)
self.assertEquals(calendar.name(), name)
for name in ("tasks",):
calendar = yield home1.calendarWithName(name)
if calendar is not None:
self.fail("calendar %r exists" % (name,))
self.patch(config, "RestrictCalendarsToOneComponentType", True)
home2 = yield self.transactionUnderTest().calendarHomeWithUID("home_provision2", create=True)
for name in ("calendar", "tasks", "inbox",):
calendar = yield home2.calendarWithName(name)
if calendar is None:
self.fail("calendar %r didn't exist" % (name,))
self.assertProvides(ICalendar, calendar)
self.assertEquals(calendar.name(), name)
@inlineCallbacks
def test_calendarWithName_exists(self):
"""
L{ICalendarHome.calendarWithName} returns an L{ICalendar} provider,
whose name matches the one passed in.
"""
home = yield self.homeUnderTest()
for name in home1_calendarNames:
calendar = yield home.calendarWithName(name)
if calendar is None:
self.fail("calendar %r didn't exist" % (name,))
self.assertProvides(ICalendar, calendar)
self.assertEquals(calendar.name(), name)
@inlineCallbacks
def test_calendarRename(self):
"""
L{ICalendar.rename} changes the name of the L{ICalendar}.
"""
home = yield self.homeUnderTest()
calendar = yield home.calendarWithName("calendar_1")
yield calendar.rename("some_other_name")
@inlineCallbacks
def positiveAssertions():
self.assertEquals(calendar.name(), "some_other_name")
self.assertEquals(
calendar, (yield home.calendarWithName("some_other_name")))
self.assertEquals(
None, (yield home.calendarWithName("calendar_1")))
yield positiveAssertions()
yield self.commit()
home = yield self.homeUnderTest()
calendar = yield home.calendarWithName("some_other_name")
yield positiveAssertions()
# FIXME: revert
# FIXME: test for multiple renames
# FIXME: test for conflicting renames (a->b, c->a in the same txn)
@inlineCallbacks
def test_calendarWithName_absent(self):
"""
L{ICalendarHome.calendarWithName} returns C{None} for calendars which
do not exist.
"""
home = yield self.homeUnderTest()
calendar = yield home.calendarWithName("xyzzy")
self.assertEquals(calendar, None)
@inlineCallbacks
def test_createCalendarWithName_absent(self):
"""
L{ICalendarHome.createCalendarWithName} creates a new L{ICalendar} that
can be retrieved with L{ICalendarHome.calendarWithName}.
"""
home = yield self.homeUnderTest()
name = "new"
self.assertIdentical((yield home.calendarWithName(name)), None)
yield home.createCalendarWithName(name)
self.assertNotIdentical((yield home.calendarWithName(name)), None)
calendarProperties = (yield home.calendarWithName(name)).properties()
self.assertEqual(len(calendarProperties), 0)
# notify is called prior to commit
self.assertTrue(("/CalDAV/example.com/home1/", PushPriority.high) in self.notifierFactory.history)
yield self.commit()
# Make sure it's available in a new transaction; i.e. test the commit.
home = yield self.homeUnderTest()
self.assertNotIdentical((yield home.calendarWithName(name)), None)
@inlineCallbacks
def test_createCalendarWithName_exists(self):
"""
L{ICalendarHome.createCalendarWithName} raises
L{CalendarAlreadyExistsError} when the name conflicts with an already-
existing
"""
home = yield self.homeUnderTest()
for name in home1_calendarNames:
yield self.failUnlessFailure(
maybeDeferred(home.createCalendarWithName, name),
HomeChildNameAlreadyExistsError
)
@inlineCallbacks
def test_removeCalendarWithName_exists(self):
"""
L{ICalendarHome.removeCalendarWithName} removes a calendar that already
exists.
"""
home = yield self.homeUnderTest()
trash = yield home.getTrash(create=True)
# FIXME: test transactions
for name in home1_calendarNames:
self.assertNotIdentical((yield home.calendarWithName(name)), None)
yield home.removeCalendarWithName(name)
self.assertEquals((yield home.calendarWithName(name)), None)
yield self.commit()
# Make sure notification fired after commit
expected = [
("/CalDAV/example.com/home1/", PushPriority.high),
("/CalDAV/example.com/home1/calendar_1/", PushPriority.high),
("/CalDAV/example.com/home1/calendar_2/", PushPriority.high),
("/CalDAV/example.com/home1/calendar_empty/", PushPriority.high),
]
if trash:
expected.append(
("/CalDAV/example.com/home1/{}/".format(trash.name()), PushPriority.high),
)
self.assertEquals(
set(self.notifierFactory.history),
set(expected)
)
@inlineCallbacks
def test_removeCalendarWithName_absent(self):
"""
Attempt to remove an non-existing calendar should raise.
"""
home = yield self.homeUnderTest()
yield self.failUnlessFailure(
maybeDeferred(home.removeCalendarWithName, "xyzzy"),
NoSuchHomeChildError
)
@inlineCallbacks
def test_supportedComponentSet(self):
"""
Attempt to remove an non-existing calendar object should raise.
"""
calendar = yield self.calendarUnderTest()
result = yield maybeDeferred(calendar.getSupportedComponents)
self.assertEquals(result, None)
yield maybeDeferred(calendar.setSupportedComponents, "VEVENT,VTODO")
result = yield maybeDeferred(calendar.getSupportedComponents)
self.assertEquals(result, "VEVENT,VTODO")
yield maybeDeferred(calendar.setSupportedComponents, None)
result = yield maybeDeferred(calendar.getSupportedComponents)
self.assertEquals(result, None)
@inlineCallbacks
def test_countComponentTypes(self):
"""
Test Calendar._countComponentTypes to make sure correct counts are returned.
"""
tests = (
("calendar_1", (("VEVENT", 3),)),
("calendar_2", (("VEVENT", 3), ("VTODO", 2))),
)
for calname, results in tests:
testalendar = yield (yield self.transactionUnderTest().calendarHomeWithUID(
"home_splits")).calendarWithName(calname)
result = yield maybeDeferred(testalendar._countComponentTypes)
self.assertEquals(result, results)
@inlineCallbacks
def test_calendarObjects(self):
"""
L{ICalendar.calendarObjects} will enumerate the calendar objects present
in the filesystem, in name order, but skip those with hidden names.
"""
calendar1 = yield self.calendarUnderTest()
calendarObjects = list((yield calendar1.calendarObjects()))
for calendarObject in calendarObjects:
self.assertProvides(ICalendarObject, calendarObject)
self.assertEquals(
(yield calendar1.calendarObjectWithName(calendarObject.name())),
calendarObject
)
self.assertEquals(
set(list(o.name() for o in calendarObjects)),
set(calendar1_objectNames)
)
@inlineCallbacks
def test_calendarObjectsWithRemovedObject(self):
"""
L{ICalendar.calendarObjects} skips those objects which have been
removed by L{CalendarObject.remove} in the same
transaction, even if it has not yet been committed.
"""
calendar1 = yield self.calendarUnderTest()
obj1 = yield calendar1.calendarObjectWithName("2.ics")
yield obj1.remove()
calendarObjects = list((yield calendar1.calendarObjects()))
self.assertEquals(set(o.name() for o in calendarObjects),
set(calendar1_objectNames) - set(["2.ics"]))
@inlineCallbacks
def test_calendarObjectRemoveConcurrent(self):
"""
If a transaction, C{A}, is examining an L{ICalendarObject} C{O} while
another transaction, C{B}, deletes O, L{O.component()} should raise
L{ConcurrentModification}. (This assumes that we are in the default
serialization level, C{READ COMMITTED}. This test might fail if
something changes that.)
"""
calendarObject = yield self.calendarObjectUnderTest()
ctxn = self.concurrentTransaction()
calendar1prime = yield self.calendarUnderTest(ctxn)
obj1 = yield calendar1prime.calendarObjectWithName("1.ics")
yield obj1.purge()
yield ctxn.commit()
try:
retrieval = yield calendarObject.component()
except ConcurrentModification:
pass
else:
self.fail("ConcurrentModification not raised, %r returned." %
(retrieval,))
@inlineCallbacks
def test_ownerCalendarHome(self):
"""
L{ICalendar.ownerCalendarHome} should match the home UID.
"""
self.assertEquals(
(yield self.calendarUnderTest()).ownerCalendarHome().uid(),
(yield self.homeUnderTest()).uid()
)
@inlineCallbacks
def test_calendarObjectWithName_exists(self):
"""
L{ICalendar.calendarObjectWithName} returns an L{ICalendarObject}
provider for calendars which already exist.
"""
calendar1 = yield self.calendarUnderTest()
for name in calendar1_objectNames:
calendarObject = yield calendar1.calendarObjectWithName(name)
self.assertProvides(ICalendarObject, calendarObject)
self.assertEquals(calendarObject.name(), name)
# FIXME: add more tests based on CommonTests.requirements
@inlineCallbacks
def test_calendarObjectWithName_absent(self):
"""
L{ICalendar.calendarObjectWithName} returns C{None} for calendars which
don't exist.
"""
calendar1 = yield self.calendarUnderTest()
self.assertEquals((yield calendar1.calendarObjectWithName("xyzzy")), None)
@inlineCallbacks
def test_CalendarObjectWithUID_remove_exists(self):
"""
Remove an existing calendar object.
"""
home = yield self.homeUnderTest()
trash = yield home.getTrash(create=True)
calendar = yield self.calendarUnderTest()
for name in calendar1_objectNames:
uid = (u'uid' + name.rstrip(".ics"))
obj1 = (yield calendar.calendarObjectWithUID(uid))
self.assertNotIdentical(obj1, None)
yield obj1.remove()
self.assertEquals(
(yield calendar.calendarObjectWithUID(uid)),
None
)
self.assertEquals(
(yield calendar.calendarObjectWithName(name)),
None
)
expected = [
("/CalDAV/example.com/home1/", PushPriority.high),
("/CalDAV/example.com/home1/calendar_1/", PushPriority.high),
]
if trash:
expected.append(
("/CalDAV/example.com/home1/{}/".format(trash.name()), PushPriority.high),
)
# notify is called prior to commit
self.assertEquals(
set(self.notifierFactory.history),
set(expected)
)
yield self.commit()
@inlineCallbacks
def test_CalendarObject_remove(self):
"""
Remove an existing calendar object.
"""
calendar = yield self.calendarUnderTest()
for name in calendar1_objectNames:
obj1 = (yield calendar.calendarObjectWithName(name))
self.assertNotIdentical(obj1, None)
yield obj1.remove()
self.assertIdentical(
(yield calendar.calendarObjectWithName(name)), None
)
@inlineCallbacks
def test_calendarName(self):
"""
L{Calendar.name} reflects the name of the calendar.
"""
self.assertEquals((yield self.calendarUnderTest()).name(), "calendar_1")
@inlineCallbacks
def test_calendar_missingNotifier(self):
"""
L{ICalendarHomeChild.getNotifier} returns L{None} when no notifiers exist
"""
home = yield self.homeUnderTest()
home._notifiers = {}
calendar = yield home.calendarWithName("calendar_1")
result = calendar.getNotifier("push")
self.assertTrue(result is None)
@inlineCallbacks
def test_hasCalendarResourceUIDSomewhereElse(self):
"""
L{ICalendarHome.hasCalendarResourceUIDSomewhereElse} will determine if
a calendar object with a conflicting iCalendar UID is found anywhere
within the calendar home.
"""
home = yield self.homeUnderTest()
object = yield self.calendarObjectUnderTest()
result = (yield home.hasCalendarResourceUIDSomewhereElse("123", object, "schedule"))
self.assertFalse(result)
result = (yield home.hasCalendarResourceUIDSomewhereElse("uid1", object, "schedule"))
self.assertFalse(result is not None)
result = (yield home.hasCalendarResourceUIDSomewhereElse("uid2", object, "schedule"))
self.assertTrue(result is not None)
# FIXME: do this without legacy calls
'''
from twistedcaldav.sharing import SharedCollectionRecord
scr = SharedCollectionRecord(
shareuid="opaque", sharetype="D", summary="ignored",
hosturl="/.../__uids__/home_splits/calendar_2",
localname="shared_other_calendar"
)
yield home.retrieveOldShares().addOrUpdateRecord(scr)
# uid 2-5 is the UID of a VTODO in home_splits/calendar_2.
result = (yield home.hasCalendarResourceUIDSomewhereElse(
"uid2-5", object, "schedule"
))
self.assertFalse(result is not None)
'''
yield None
@inlineCallbacks
def test_getCalendarResourcesForUID(self):
"""
L{ICalendar.calendarObjects} will enumerate the calendar objects present
in the filesystem, in name order, but skip those with hidden names.
"""
home = yield self.homeUnderTest()
calendarObjects = (yield home.getCalendarResourcesForUID("123"))
self.assertEquals(len(calendarObjects), 0)
calendarObjects = (yield home.getCalendarResourcesForUID("uid1"))
self.assertEquals(len(calendarObjects), 1)
@inlineCallbacks
def test_calendarObjectName(self):
"""
L{ICalendarObject.name} reflects the name of the calendar object.
"""
self.assertEquals(
(yield self.calendarObjectUnderTest()).name(),
"1.ics"
)
@inlineCallbacks
def test_calendarObjectMetaData(self):
"""
The objects retrieved from the calendar have a various methods which
return metadata values.
"""
calendar = yield self.calendarObjectUnderTest()
self.assertIsInstance(calendar.name(), basestring)
self.assertIsInstance(calendar.uid(), basestring)
self.assertIsInstance(calendar.accessMode, basestring)
self.assertIsInstance(calendar.isScheduleObject, bool)
self.assertIsInstance(calendar.scheduleEtags, tuple)
self.assertIsInstance(calendar.hasPrivateComment, bool)
self.assertIsInstance(calendar.md5(), basestring)
self.assertIsInstance(calendar.size(), int)
self.assertIsInstance(calendar.created(), int)
self.assertIsInstance(calendar.modified(), int)
self.assertEqual(calendar.accessMode,
CommonTests.metadata1["accessMode"])
self.assertEqual(calendar.isScheduleObject,
CommonTests.metadata1["isScheduleObject"])
self.assertEqual(calendar.scheduleEtags,
CommonTests.metadata1["scheduleEtags"])
self.assertEqual(calendar.hasPrivateComment,
CommonTests.metadata1["hasPrivateComment"])
calendar.accessMode = Component.ACCESS_PRIVATE
calendar.isScheduleObject = True
calendar.scheduleEtags = ("1234", "5678",)
calendar.hasPrivateComment = True
self.assertEqual(calendar.accessMode, Component.ACCESS_PRIVATE)
self.assertEqual(calendar.isScheduleObject, True)
self.assertEqual(calendar.scheduleEtags, ("1234", "5678",))
self.assertEqual(calendar.hasPrivateComment, True)
@inlineCallbacks
def test_usedQuotaAdjustment(self):
"""
Adjust used quota on the calendar home and then verify that it's used.
"""
home = yield self.homeUnderTest()
initialQuota = yield home.quotaUsedBytes()
yield home.adjustQuotaUsedBytes(30)
yield self.commit()
home2 = yield self.homeUnderTest()
afterQuota = yield home2.quotaUsedBytes()
self.assertEqual(afterQuota - initialQuota, 30)
yield home2.adjustQuotaUsedBytes(-100000)
yield self.commit()
home3 = yield self.homeUnderTest()
self.assertEqual((yield home3.quotaUsedBytes()), 0)
@inlineCallbacks
def test_component(self):
"""
L{ICalendarObject.component} returns a L{VComponent} describing the
calendar data underlying that calendar object.
"""
component = yield (yield self.calendarObjectUnderTest()).component()
self.failUnless(
isinstance(component, VComponent),
component
)
self.assertEquals(component.name(), "VCALENDAR")
self.assertEquals(component.mainType(), "VEVENT")
self.assertEquals(component.resourceUID(), "uid1")
perUserComponent = lambda self: VComponent.fromString("""BEGIN:VCALENDAR
PRODID:-//CALENDARSERVER.ORG//NONSGML Version 1//EN
VERSION:2.0
BEGIN:VEVENT
DTSTART:20110101T120000Z
DTEND:20110101T120100Z
DTSTAMP:20080601T120000Z
UID:event-with-some-per-user-data
ATTENDEE:urn:uuid:home1
ORGANIZER:urn:uuid:home1
END:VEVENT
BEGIN:X-CALENDARSERVER-PERUSER
X-CALENDARSERVER-PERUSER-UID:some-other-user
BEGIN:X-CALENDARSERVER-PERINSTANCE
BEGIN:VALARM
ACTION:DISPLAY
DESCRIPTION:somebody else
TRIGGER:-PT20M
END:VALARM
END:X-CALENDARSERVER-PERINSTANCE
END:X-CALENDARSERVER-PERUSER
BEGIN:X-CALENDARSERVER-PERUSER
X-CALENDARSERVER-PERUSER-UID:home1
BEGIN:X-CALENDARSERVER-PERINSTANCE
BEGIN:VALARM
ACTION:DISPLAY
DESCRIPTION:the owner
TRIGGER:-PT20M
END:VALARM
END:X-CALENDARSERVER-PERINSTANCE
END:X-CALENDARSERVER-PERUSER
END:VCALENDAR
""".replace("\n", "\r\n"))
asSeenByOwner = lambda self: VComponent.fromString("""BEGIN:VCALENDAR
PRODID:-//CALENDARSERVER.ORG//NONSGML Version 1//EN
VERSION:2.0
BEGIN:VEVENT
DTSTART:20110101T120000Z
DTEND:20110101T120100Z
DTSTAMP:20080601T120000Z
UID:event-with-some-per-user-data
ATTENDEE:urn:uuid:home1
ORGANIZER:urn:uuid:home1
BEGIN:VALARM
ACTION:DISPLAY
DESCRIPTION:the owner
TRIGGER:-PT20M
END:VALARM
END:VEVENT
END:VCALENDAR
""".replace("\n", "\r\n"))
asSeenByOther = lambda self: VComponent.fromString("""BEGIN:VCALENDAR
PRODID:-//CALENDARSERVER.ORG//NONSGML Version 1//EN
VERSION:2.0
BEGIN:VEVENT
DTSTART:20110101T120000Z
DTEND:20110101T120100Z
DTSTAMP:20080601T120000Z
UID:event-with-some-per-user-data
ATTENDEE:urn:uuid:home1
ORGANIZER:urn:uuid:home1
BEGIN:VALARM
ACTION:DISPLAY
DESCRIPTION:somebody else
TRIGGER:-PT20M
END:VALARM
END:VEVENT
END:VCALENDAR
""".replace("\n", "\r\n"))
@inlineCallbacks
def setUpPerUser(self):
"""
Set up state for testing of per-user components.
"""
cal = yield self.calendarUnderTest()
yield cal._createCalendarObjectWithNameInternal(
"per-user-stuff.ics",
self.perUserComponent(),
internal_state=ComponentUpdateState.RAW)
returnValue((yield cal.calendarObjectWithName("per-user-stuff.ics")))
@inlineCallbacks
def test_filteredComponent(self):
"""
L{ICalendarObject.filteredComponent} returns a L{VComponent} that has
filtered per-user data.
"""
obj = yield self.setUpPerUser()
temp = yield obj.component()
obj._component = temp.duplicate()
otherComp = (yield obj.filteredComponent("some-other-user"))
self.assertEquals(otherComp, self.asSeenByOther())
obj._component = temp.duplicate()
ownerComp = (yield obj.filteredComponent("home1"))
self.assertEquals(ownerComp, self.asSeenByOwner())
@inlineCallbacks
def test_iCalendarText(self):
"""
L{ICalendarObject._text} returns a C{str} describing the same
data provided by L{ICalendarObject.component}.
"""
text = yield (yield self.calendarObjectUnderTest())._text()
self.assertIsInstance(text, str)
self.failUnless(text.startswith("BEGIN:VCALENDAR\r\n"))
self.assertIn("\r\nUID:uid1\r\n", text)
self.failUnless(text.endswith("\r\nEND:VCALENDAR\r\n"))
@inlineCallbacks
def test_calendarObjectUID(self):
"""
L{ICalendarObject.uid} returns a C{str} describing the C{UID} property
of the calendar object's component.
"""
self.assertEquals(
(yield self.calendarObjectUnderTest()).uid(), "uid1"
)
@inlineCallbacks
def test_organizer(self):
"""
L{ICalendarObject.organizer} returns a C{str} describing the calendar
user address of the C{ORGANIZER} property of the calendar object's
component.
"""
calobj = yield self.calendarObjectUnderTest(name="5.ics")
organizer = yield calobj.organizer()
self.assertEquals(
organizer,
"mailto:[email protected]"
)
@inlineCallbacks
def test_calendarObjectWithUID_absent(self):
"""
L{ICalendar.calendarObjectWithUID} returns C{None} for calendars which
don't exist.
"""
calendar1 = yield self.calendarUnderTest()
self.assertEquals((yield calendar1.calendarObjectWithUID("xyzzy")),
None)
@inlineCallbacks
def test_calendars(self):
"""
L{ICalendarHome.calendars} returns an iterable of L{ICalendar}
providers, which are consistent with the results from
L{ICalendar.calendarWithName}.
"""
# Add a dot directory to make sure we don't find it
# self.home1._path.child(".foo").createDirectory()
home = yield self.homeUnderTest()
calendars = list((yield home.calendars()))
for calendar in calendars:
self.assertProvides(ICalendar, calendar)
self.assertEquals(calendar,
(yield home.calendarWithName(calendar.name())))
self.assertEquals(
set(c.name() for c in calendars),
set(home1_calendarNames)
)
@inlineCallbacks
def test_loadAllCalendars(self):
"""
L{ICalendarHome.loadCalendars} returns an iterable of L{ICalendar}
providers, which are consistent with the results from
L{ICalendar.calendarWithName}.
"""
# Add a dot directory to make sure we don't find it
# self.home1._path.child(".foo").createDirectory()
home = yield self.homeUnderTest()
calendars = (yield home.loadCalendars())
for calendar in calendars:
self.assertProvides(ICalendar, calendar)
self.assertEquals(calendar,
(yield home.calendarWithName(calendar.name())))
self.assertEquals(
set(c.name() for c in calendars),
set(home1_calendarNames)
)
for c in calendars:
self.assertTrue(c.properties() is not None)
@inlineCallbacks
def test_calendarsAfterAddCalendar(self):
"""
L{ICalendarHome.calendars} includes calendars recently added with
L{ICalendarHome.createCalendarWithName}.
"""
home = yield self.homeUnderTest()
allCalendars = yield home.calendars()
before = set(x.name() for x in allCalendars)
yield home.createCalendarWithName("new-name")
allCalendars = yield home.calendars()
after = set(x.name() for x in allCalendars)
self.assertEquals(before | set(['new-name']), after)
@inlineCallbacks
def test_createCalendarObjectWithName_absent(self):
"""
L{ICalendar.createCalendarObjectWithName} creates a new
L{ICalendarObject}.
"""
calendar1 = yield self.calendarUnderTest()
name = "test.ics"
self.assertIdentical(
(yield calendar1.calendarObjectWithName(name)), None
)
component = VComponent.fromString(test_event_text)
metadata = {
"accessMode": "PUBLIC",
"isScheduleObject": True,
"scheduleTag": "abc",
"scheduleEtags": (),
"hasPrivateComment": False,
}
yield calendar1._createCalendarObjectWithNameInternal(name, component, internal_state=ComponentUpdateState.RAW, options=metadata)
calendarObject = yield calendar1.calendarObjectWithName(name)
self.assertEquals((yield calendarObject.componentForUser()), component)
self.assertEquals((yield calendarObject.getMetadata()), metadata)
# notify is called prior to commit
self.assertEquals(
set(self.notifierFactory.history),
set([
("/CalDAV/example.com/home1/", PushPriority.high),
("/CalDAV/example.com/home1/calendar_1/", PushPriority.high),
])
)
yield self.commit()
@inlineCallbacks
def test_createCalendarObjectWithName_exists(self):
"""
L{ICalendar.createCalendarObjectWithName} raises
L{CalendarObjectNameAlreadyExistsError} if a calendar object with the
given name already exists in that calendar.
"""
cal = yield self.calendarUnderTest()
comp = VComponent.fromString(test_event_text)
yield self.failUnlessFailure(
maybeDeferred(cal.createCalendarObjectWithName, "1.ics", comp),
ObjectResourceNameAlreadyExistsError,
)
@inlineCallbacks
def test_createCalendarObjectWithName_invalidName(self):
"""
L{ICalendar.createCalendarObjectWithName} raises
L{CalendarObjectNameAlreadyExistsError} if the calendar object name
starts with a ".".
"""
cal = yield self.calendarUnderTest()
comp = VComponent.fromString(test_event_text)
yield self.failUnlessFailure(
maybeDeferred(cal.createCalendarObjectWithName, ".1.ics", comp),
ObjectResourceNameNotAllowedError,
)
@inlineCallbacks
def test_createCalendarObjectWithName_longName(self):
"""
L{ICalendar.createCalendarObjectWithName} raises
L{CalendarObjectNameAlreadyExistsError} if the calendar object name
is too long.
"""
cal = yield self.calendarUnderTest()
comp = VComponent.fromString(test_event_text)
yield self.failUnlessFailure(
maybeDeferred(cal.createCalendarObjectWithName, "A" * 256 + ".ics", comp),
ObjectResourceNameNotAllowedError,
)
@inlineCallbacks
def test_createCalendarObjectWithName_invalid(self):
"""
L{ICalendar.createCalendarObjectWithName} raises
L{InvalidCalendarComponentError} if presented with invalid iCalendar
text.
"""
yield self.failUnlessFailure(
maybeDeferred(
(yield self.calendarUnderTest()).createCalendarObjectWithName,
"new", VComponent.fromString(test_event_notCalDAV_text)),
InvalidObjectResourceError,
InvalidComponentForStoreError,
)
@inlineCallbacks
def test_setComponent_invalid(self):
"""
L{ICalendarObject.setComponent} raises L{InvalidICalendarDataError} if
presented with invalid iCalendar text.
"""
calendarObject = yield self.calendarObjectUnderTest()
yield self.failUnlessFailure(
maybeDeferred(calendarObject.setComponent,
VComponent.fromString(test_event_notCalDAV_text)),
InvalidObjectResourceError,
InvalidComponentForStoreError,
)
@inlineCallbacks
def test_setComponent_uidchanged(self):
"""
L{ICalendarObject.setComponent} raises L{InvalidCalendarComponentError}
when given a L{VComponent} whose UID does not match its existing UID.
"""
calendar1 = yield self.calendarUnderTest()
component = VComponent.fromString(test_event_text)
calendarObject = yield calendar1.calendarObjectWithName("1.ics")
yield self.failUnlessFailure(
maybeDeferred(calendarObject.setComponent, component),
InvalidObjectResourceError,
InvalidUIDError,
)
@inlineCallbacks
def test_calendarHomeWithUID_create(self):
"""
L{ICommonStoreTransaction.calendarHomeWithUID} with C{create=True}
will create a calendar home that doesn't exist yet.
"""
txn = self.transactionUnderTest()
noHomeUID = "xyzzy"
calendarHome = yield txn.calendarHomeWithUID(
noHomeUID,
create=True
)
@inlineCallbacks
def readOtherTxn():
otherTxn = self.savedStore.newTransaction(self.id() + "other txn")
self.addCleanup(otherTxn.commit)
returnValue((yield otherTxn.calendarHomeWithUID(noHomeUID)))
self.assertProvides(ICalendarHome, calendarHome)
# Default calendar should be automatically created.
self.assertProvides(ICalendar,
(yield calendarHome.calendarWithName("calendar")))
# A concurrent transaction shouldn't be able to read it yet:
self.assertIdentical((yield readOtherTxn()), None)
yield self.commit()
# But once it's committed, other transactions should see it.
self.assertProvides(ICalendarHome, (yield readOtherTxn()))
@inlineCallbacks
def test_setComponent(self):
"""
L{CalendarObject.setComponent} changes the result of
L{CalendarObject.component} within the same transaction.
"""
component = VComponent.fromString(event1modified_text)
calendar1 = yield self.calendarUnderTest()
calendarObject = yield calendar1.calendarObjectWithName("1.ics")
oldComponent = yield calendarObject.componentForUser()
self.assertNotEqual(component, oldComponent)
yield calendarObject.setComponent(component)
self.assertEquals((yield calendarObject.componentForUser()), component)
# Also check a new instance
calendarObject = yield calendar1.calendarObjectWithName("1.ics")
self.assertEquals((yield calendarObject.componentForUser()), component)
# notify is called prior to commit
self.assertEquals(
set(self.notifierFactory.history),
set([
("/CalDAV/example.com/home1/", PushPriority.high),
("/CalDAV/example.com/home1/calendar_1/", PushPriority.high),
])
)
yield self.commit()
def checkPropertiesMethod(self, thunk):
"""
Verify that the given object has a properties method that returns an
L{IPropertyStore}.
"""
properties = thunk.properties()
self.assertProvides(IPropertyStore, properties)
@inlineCallbacks
def test_homeProperties(self):
"""
L{ICalendarHome.properties} returns a property store.
"""
self.checkPropertiesMethod((yield self.homeUnderTest()))
@inlineCallbacks
def test_calendarProperties(self):
"""
L{ICalendar.properties} returns a property store.
"""
self.checkPropertiesMethod((yield self.calendarUnderTest()))
@inlineCallbacks
def test_calendarObjectProperties(self):
"""
L{ICalendarObject.properties} returns a property store.
"""
self.checkPropertiesMethod((yield self.calendarObjectUnderTest()))
@inlineCallbacks
def test_newCalendarObjectProperties(self):
"""
L{ICalendarObject.properties} returns an empty property store for a
calendar object which has been created but not committed.
"""
calendar = yield self.calendarUnderTest()
yield calendar.createCalendarObjectWithName(
"test.ics", VComponent.fromString(test_event_text)
)
newEvent = yield calendar.calendarObjectWithName("test.ics")
self.assertEquals(newEvent.properties().items(), [])
@inlineCallbacks
def test_setComponentPreservesProperties(self):
"""
L{ICalendarObject.setComponent} preserves properties.
(Some implementations must go to extra trouble to provide this
behavior; for example, file storage must copy extended attributes from
the existing file to the temporary file replacing it.)
"""
propertyName = PropertyName("http://example.com/ns", "example")
propertyContent = WebDAVUnknownElement("sample content")
propertyContent.name = propertyName.name
propertyContent.namespace = propertyName.namespace
calobject = (yield self.calendarObjectUnderTest())
if calobject._parentCollection.objectResourcesHaveProperties():
(yield self.calendarObjectUnderTest()).properties()[
propertyName] = propertyContent
yield self.commit()
# Sanity check; are properties even readable in a separate transaction?
# Should probably be a separate test.
self.assertEquals(
(yield self.calendarObjectUnderTest()).properties()[propertyName],
propertyContent)
obj = yield self.calendarObjectUnderTest()
event1_text = yield obj._text()
event1_text_withDifferentSubject = event1_text.replace(
"SUMMARY:CalDAV protocol updates",
"SUMMARY:Changed"
)
# Sanity check; make sure the test has the right idea of the subject.
self.assertNotEquals(event1_text, event1_text_withDifferentSubject)
newComponent = VComponent.fromString(event1_text_withDifferentSubject)
yield obj.setComponent(newComponent)
# Putting everything into a separate transaction to account for any
# caching that may take place.
yield self.commit()
self.assertEquals(
(yield self.calendarObjectUnderTest()).properties()[propertyName],
propertyContent
)
def token2revision(self, token):
"""
FIXME: the API names for L{syncToken}() and L{resourceNamesSinceToken}()
are slightly inaccurate; one doesn't produce input for the other.
Actually it should be resource names since I{revision} and you need to
understand the structure of the tokens to extract the revision. Right
now that logic lives in the protocol layer, so this testing method
replicates it.
"""
_ignore_uuid, rev = token.split("_", 1)
rev = int(rev)
return rev
@inlineCallbacks
def test_simpleHomeSyncToken(self):
"""
L{ICalendarHome.resourceNamesSinceToken} will return the names of
calendar objects created since L{ICalendarHome.syncToken} last returned
a particular value.
"""
home = yield self.homeUnderTest()
cal = yield self.calendarUnderTest()
st = yield home.syncToken()
yield cal.createCalendarObjectWithName("new.ics", VComponent.fromString(
test_event_text
))
obj1 = yield cal.calendarObjectWithName("2.ics")
yield obj1.remove()
yield home.createCalendarWithName("other-calendar")
st2 = yield home.syncToken()
self.failIfEquals(st, st2)
home = yield self.homeUnderTest()
expected = [
"calendar_1/",
"calendar_1/new.ics",
"calendar_1/2.ics",
"other-calendar/"
]
trash = yield home.getTrash()
if trash is not None:
trashed = yield trash.calendarObjects()
expected.extend([
"{}/".format(trash.name()),
"{}/{}".format(trash.name(), trashed[0].name()),
])
changed, deleted, invalid = yield home.resourceNamesSinceToken(
self.token2revision(st), "infinity")
self.assertEquals(set(changed), set(expected))
self.assertEquals(set(deleted), set(["calendar_1/2.ics"]))
self.assertEquals(invalid, [])
changed, deleted, invalid = yield home.resourceNamesSinceToken(
self.token2revision(st2), "infinity")
self.assertEquals(changed, [])
self.assertEquals(deleted, [])
self.assertEquals(invalid, [])
@inlineCallbacks
def test_collectionSyncToken(self):
"""
L{ICalendar.resourceNamesSinceToken} will return the names of calendar
objects changed or deleted since
"""
cal = yield self.calendarUnderTest()
st = yield cal.syncToken()
rev = self.token2revision(st)
yield cal.createCalendarObjectWithName("new.ics", VComponent.fromString(
test_event_text
))
obj1 = yield cal.calendarObjectWithName("2.ics")
yield obj1.remove()
st2 = yield cal.syncToken()
rev2 = self.token2revision(st2)
changed, deleted, invalid = yield cal.resourceNamesSinceToken(rev)
self.assertEquals(set(changed), set(["new.ics"]))
self.assertEquals(set(deleted), set(["2.ics"]))
self.assertEquals(len(invalid), 0)
changed, deleted, invalid = yield cal.resourceNamesSinceToken(rev2)
self.assertEquals(set(changed), set([]))
self.assertEquals(set(deleted), set([]))
self.assertEquals(len(invalid), 0)
@inlineCallbacks
def test_finishedOnCommit(self):
"""
Calling L{ITransaction.abort} or L{ITransaction.commit} after
L{ITransaction.commit} has already been called raises an
L{AlreadyFinishedError}.
"""
yield self.calendarObjectUnderTest()
txn = self.lastTransaction
yield self.commit()
yield self.failUnlessFailure(
maybeDeferred(txn.commit),
AlreadyFinishedError
)
yield self.failUnlessFailure(
maybeDeferred(txn.abort),
AlreadyFinishedError
)
@inlineCallbacks
def test_dontLeakCalendars(self):
"""
Calendars in one user's calendar home should not show up in another
user's calendar home.
"""
home2 = yield self.transactionUnderTest().calendarHomeWithUID(
"home2", create=True)
self.assertIdentical(
(yield home2.calendarWithName("calendar_1")), None)
@inlineCallbacks
def test_dontLeakObjects(self):
"""
Calendar objects in one user's calendar should not show up in another
user's via uid or name queries.
"""
home1 = yield self.homeUnderTest()
home2 = yield self.transactionUnderTest().calendarHomeWithUID(
"home2", create=True)
calendar1 = yield home1.calendarWithName("calendar_1")
calendar2 = yield home2.calendarWithName("calendar")
objects = list(
(yield (yield home2.calendarWithName("calendar")).calendarObjects()))
self.assertEquals(objects, [])
for resourceName in self.requirements['home1']['calendar_1'].keys():
obj = yield calendar1.calendarObjectWithName(resourceName)
self.assertIdentical(
(yield calendar2.calendarObjectWithName(resourceName)), None)
self.assertIdentical(
(yield calendar2.calendarObjectWithUID(obj.uid())), None)
@inlineCallbacks
def test_withEachCalendarHomeDo(self):
"""
L{ICalendarStore.withEachCalendarHomeDo} executes its C{action}
argument repeatedly with all homes that have been created.
"""
additionalUIDs = set('user01 home2 home3 uid1'.split())
txn = self.transactionUnderTest()
for name in additionalUIDs:
yield txn.calendarHomeWithUID(name, create=True)
yield self.commit()
store = yield self.storeUnderTest()
def toEachCalendarHome(txn, eachHome):
return eachHome.createCalendarWithName("a-new-calendar")
result = yield store.withEachCalendarHomeDo(toEachCalendarHome)
self.assertEquals(result, None)
txn2 = self.transactionUnderTest()
for uid in additionalUIDs:
home = yield txn2.calendarHomeWithUID(uid)
self.assertNotIdentical(
None, (yield home.calendarWithName("a-new-calendar"))
)
@transactionClean
@inlineCallbacks
def test_withEachCalendarHomeDont(self):
"""
When the function passed to L{ICalendarStore.withEachCalendarHomeDo}
raises an exception, processing is halted and the transaction is
aborted. The exception is re-raised.
"""
# create some calendar homes.
additionalUIDs = set('home2 home3'.split())
txn = self.transactionUnderTest()
for uid in additionalUIDs:
yield txn.calendarHomeWithUID(uid, create=True)
yield self.commit()
# try to create a calendar in all of them, then fail.
class AnException(Exception):
pass
caught = []
@inlineCallbacks
def toEachCalendarHome(txn, eachHome):
caught.append(eachHome.uid())
yield eachHome.createCalendarWithName("wont-be-created")
raise AnException()
store = self.storeUnderTest()
yield self.failUnlessFailure(
store.withEachCalendarHomeDo(toEachCalendarHome), AnException
)
self.assertEquals(len(caught), 1)
@inlineCallbacks
def noNewCalendar(x):
home = yield txn.calendarHomeWithUID(uid, create=False)
self.assertIdentical(
(yield home.calendarWithName("wont-be-created")), None
)
txn = self.transactionUnderTest()
yield noNewCalendar(caught[0])
yield noNewCalendar('home2')
yield noNewCalendar('home3')
|
macosforge/ccs-calendarserver
|
txdav/caldav/datastore/test/common.py
|
Python
|
apache-2.0
| 64,853 |
:- module(money_and,[test/0],[andorra]).
:- use_module(library(prolog_sys),[statistics/2]).
:- use_module(library(write),[write/1]).
test:-
solve(A,B,C,D,E,F,G,H),
print_out(A,B,C,D,E,F,G,H).
do :-
solve(A,B,C,D,E,F,G,H).
%:- determinate(difflist(A),nonvar(A)).
difflist([A|B]) :-
not_el(A,B),
difflist(B).
difflist([]).
%:- determinate(digi(A),nonvar(A)).
digi(9).
digi(8).
digi(7).
digi(6).
digi(5).
digi(4).
digi(3).
digi(2).
digi(1).
digi(0).
go(fn(A,B,C,D,E,F,G,H)) :-
solve(A,B,C,D,E,F,G,H),
print_out(A,B,C,D,E,F,G,H).
%:- determinate( not_el(X,A), nonvar(A) ).
not_el(A,[]).
not_el(A,[B|C]) :-
A\==B,
not_el(A,C).
%:- determinate( carry(A,B,C), ( nonvar(A), nonvar(B), nonvar(C) ) ).
carry(1,1,1).
carry(1,1,0).
carry(1,0,1).
carry(1,0,0).
carry(0,1,1).
carry(0,1,0).
carry(0,0,1).
carry(0,0,0).
generate(A,B,C,D,E,F,G,H) :-
digi(E),
digi(A),
digi(F),
digi(B),
digi(C),
digi(G),
digi(D),
digi(H),
difflist([A,B,C,D,E,F,G,H]).
print_out(A,B,C,D,E,F,G,H) :-
write(' SEND'),
nl,
write(' + MORE'),
nl,
write(-----------),
nl,
write(' MONEY'),
nl,
nl,
write('The solution is:'),
nl,
nl,
write(' '),
write(A),
write(B),
write(C),
write(D),
nl,
write(' + '),
write(E),
write(F),
write(G),
write(B),
nl,
write(-----------),
nl,
write(' '),
write(E),
write(F),
write(C),
write(B),
write(H),
nl.
solve(A,B,C,D,E,F,G,H) :-
carry(I,J,K),
E=1,
generate(A,B,C,D,E,F,G,H),
A>0,
L is D+B,
M is H+10*I,
L=M,
N is I+C+G,
O is B+10*J,
N=O,
P is J+B+F,
Q is C+10*K,
P=Q,
R is K+A+E,
S is F+10*E,
R=S.
%%%%%%%%%%%%%%%%%%%%%
ourmain:-
statistics(runtime,_),
ourdo,
statistics(runtime,[_,T1]),
write(T1).
%:- determinate(ourdo,true).
ourdo:- solve(_A,_B,_C,_D,_E,_F,_G,_H), fail.
ourdo.
|
leuschel/ecce
|
www/CiaoDE/ciao/library/andorra/benchmarks/money_and.pl
|
Perl
|
apache-2.0
| 2,244 |
/*******************************************************************************
* Copyright 2015 MobileMan GmbH
* www.mobileman.com
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
/**
* HaqChartService.java
*
* Project: projecth
*
* @author mobileman
* @date 8.1.2011
* @version 1.0
*
* (c) 2010 MobileMan GmbH
*/
package com.mobileman.projecth.business.chart;
import java.util.List;
import com.mobileman.projecth.business.SearchService;
import com.mobileman.projecth.domain.chart.HaqChart;
/**
* Represents service for the {@link HaqChart} entity.
*
* @author mobileman
*
*/
public interface HaqChartService extends SearchService<HaqChart> {
/**
* Finds all charts defined for a given HAQ
* @param haqId
* @return all charts defined for a given HAQ
*/
List<HaqChart> findByHaq(Long haqId);
}
|
MobileManAG/Project-H-Backend
|
src/main/java/com/mobileman/projecth/business/chart/HaqChartService.java
|
Java
|
apache-2.0
| 1,426 |
require 'rails_helper'
describe 'notifiable_admin/admin/admins/new.html.erb', :type => :view do
let(:account1) { create(:account) }
let(:account2) { create(:account) }
let(:account1_owner) { create(:account_owner, :account => account1) }
let!(:account1_app) { create(:app, :account => account1, :name => "test *** ") }
let!(:account2_app) { create(:app, :account => account2) }
it 'displays correct Apps' do
assign(:account, account1)
assign(:apps, [account1_app])
assign(:admin, NotifiableAdmin::Admin.new)
render
expect(rendered).to have_css("#admin_app_ids_#{account1_app.id}")
expect(rendered).to_not have_css("#admin_app_ids_#{account2_app.id}")
end
end
|
FutureWorkshops/notifiable_admin
|
spec/views/notifiable_admin/admin/admins/new.html.erb_spec.rb
|
Ruby
|
apache-2.0
| 707 |
# AUTOGENERATED FILE
FROM balenalib/parallella-debian:stretch-build
# remove several traces of debian python
RUN apt-get purge -y python.*
# http://bugs.python.org/issue19846
# > At the moment, setting "LANG=C" on a Linux system *fundamentally breaks Python 3*, and that's not OK.
ENV LANG C.UTF-8
# key 63C7CC90: public key "Simon McVittie <[email protected]>" imported
# key 3372DCFA: public key "Donald Stufft (dstufft) <[email protected]>" imported
RUN gpg --batch --keyserver keyring.debian.org --recv-keys 4DE8FF2A63C7CC90 \
&& gpg --batch --keyserver keyserver.ubuntu.com --recv-key 6E3CBCE93372DCFA \
&& gpg --batch --keyserver keyserver.ubuntu.com --recv-keys 0x52a43a1e4b77b059
ENV PYTHON_VERSION 3.7.12
# if this is called "PIP_VERSION", pip explodes with "ValueError: invalid truth value '<VERSION>'"
ENV PYTHON_PIP_VERSION 21.3.1
ENV SETUPTOOLS_VERSION 60.5.4
RUN set -x \
&& curl -SLO "http://resin-packages.s3.amazonaws.com/python/v$PYTHON_VERSION/Python-$PYTHON_VERSION.linux-armv7hf-libffi3.2.tar.gz" \
&& echo "cca21481e4824340e576630e2f19e52532e04ff42c9bc8b88694a7986a50c77c Python-$PYTHON_VERSION.linux-armv7hf-libffi3.2.tar.gz" | sha256sum -c - \
&& tar -xzf "Python-$PYTHON_VERSION.linux-armv7hf-libffi3.2.tar.gz" --strip-components=1 \
&& rm -rf "Python-$PYTHON_VERSION.linux-armv7hf-libffi3.2.tar.gz" \
&& ldconfig \
&& if [ ! -e /usr/local/bin/pip3 ]; then : \
&& curl -SLO "https://raw.githubusercontent.com/pypa/get-pip/430ba37776ae2ad89f794c7a43b90dc23bac334c/get-pip.py" \
&& echo "19dae841a150c86e2a09d475b5eb0602861f2a5b7761ec268049a662dbd2bd0c get-pip.py" | sha256sum -c - \
&& python3 get-pip.py \
&& rm get-pip.py \
; fi \
&& pip3 install --no-cache-dir --upgrade --force-reinstall pip=="$PYTHON_PIP_VERSION" setuptools=="$SETUPTOOLS_VERSION" \
&& find /usr/local \
\( -type d -a -name test -o -name tests \) \
-o \( -type f -a -name '*.pyc' -o -name '*.pyo' \) \
-exec rm -rf '{}' + \
&& cd / \
&& rm -rf /usr/src/python ~/.cache
# install "virtualenv", since the vast majority of users of this image will want it
RUN pip3 install --no-cache-dir virtualenv
ENV PYTHON_DBUS_VERSION 1.2.18
# install dbus-python dependencies
RUN apt-get update && apt-get install -y --no-install-recommends \
libdbus-1-dev \
libdbus-glib-1-dev \
&& rm -rf /var/lib/apt/lists/* \
&& apt-get -y autoremove
# install dbus-python
RUN set -x \
&& mkdir -p /usr/src/dbus-python \
&& curl -SL "http://dbus.freedesktop.org/releases/dbus-python/dbus-python-$PYTHON_DBUS_VERSION.tar.gz" -o dbus-python.tar.gz \
&& curl -SL "http://dbus.freedesktop.org/releases/dbus-python/dbus-python-$PYTHON_DBUS_VERSION.tar.gz.asc" -o dbus-python.tar.gz.asc \
&& gpg --verify dbus-python.tar.gz.asc \
&& tar -xzC /usr/src/dbus-python --strip-components=1 -f dbus-python.tar.gz \
&& rm dbus-python.tar.gz* \
&& cd /usr/src/dbus-python \
&& PYTHON_VERSION=$(expr match "$PYTHON_VERSION" '\([0-9]*\.[0-9]*\)') ./configure \
&& make -j$(nproc) \
&& make install -j$(nproc) \
&& cd / \
&& rm -rf /usr/src/dbus-python
# make some useful symlinks that are expected to exist
RUN cd /usr/local/bin \
&& ln -sf pip3 pip \
&& { [ -e easy_install ] || ln -s easy_install-* easy_install; } \
&& ln -sf idle3 idle \
&& ln -sf pydoc3 pydoc \
&& ln -sf python3 python \
&& ln -sf python3-config python-config
# set PYTHONPATH to point to dist-packages
ENV PYTHONPATH /usr/lib/python3/dist-packages:$PYTHONPATH
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/8accad6af708fca7271c5c65f18a86782e19f877/scripts/assets/tests/[email protected]" \
&& echo "Running test-stack@python" \
&& chmod +x [email protected] \
&& bash [email protected] \
&& rm -rf [email protected]
RUN [ ! -d /.balena/messages ] && mkdir -p /.balena/messages; echo 'Here are a few details about this Docker image (For more information please visit https://www.balena.io/docs/reference/base-images/base-images/): \nArchitecture: ARM v7 \nOS: Debian Stretch \nVariant: build variant \nDefault variable(s): UDEV=off \nThe following software stack is preinstalled: \nPython v3.7.12, Pip v21.3.1, Setuptools v60.5.4 \nExtra features: \n- Easy way to install packages with `install_packages <package-name>` command \n- Run anywhere with cross-build feature (for ARM only) \n- Keep the container idling with `balena-idle` command \n- Show base image details with `balena-info` command' > /.balena/messages/image-info
RUN echo '#!/bin/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
|
resin-io-library/base-images
|
balena-base-images/python/parallella/debian/stretch/3.7.12/build/Dockerfile
|
Dockerfile
|
apache-2.0
| 4,856 |
using System;
using System.Net.Http;
using System.Net.Security;
namespace Checky.Common.Network {
public class HttpClientFactory : IHttpClientFactory {
public HttpClient GetClient(string trustInvalidCertificatesWithSubject = null) {
if (string.IsNullOrEmpty(trustInvalidCertificatesWithSubject)) {
return new HttpClient();
}
var handler = new WebRequestHandler();
handler.ServerCertificateValidationCallback += OnValidation(trustInvalidCertificatesWithSubject);
return new HttpClient(handler);
}
private static RemoteCertificateValidationCallback OnValidation(string certificateSubject) {
return
(sender, certificate, chain, errors) =>
certificate.Subject.Equals(certificateSubject, StringComparison.InvariantCultureIgnoreCase);
}
}
}
|
RichardSlater/CheckyChatbot
|
src/Common/Network/HttpClientFactory.cs
|
C#
|
apache-2.0
| 905 |
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.ide.actions;
import com.intellij.openapi.extensions.ExtensionPointName;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.search.GlobalSearchScope;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import java.awt.*;
import java.util.Objects;
/**
* @author Philipp Smorygo
*/
public interface SearchEverywhereClassifier {
class EP_Manager {
private EP_Manager() {}
public static boolean isClass(@Nullable Object o) {
for (SearchEverywhereClassifier classifier : SearchEverywhereClassifier.EP_NAME.getExtensionList()) {
if (classifier.isClass(o)) return true;
}
return false;
}
public static boolean isSymbol(@Nullable Object o) {
for (SearchEverywhereClassifier classifier : SearchEverywhereClassifier.EP_NAME.getExtensionList()) {
if (classifier.isSymbol(o)) return true;
}
return false;
}
@Nullable
public static VirtualFile getVirtualFile(@NotNull Object o) {
return SearchEverywhereClassifier.EP_NAME.getExtensionList().stream()
.map(classifier -> classifier.getVirtualFile(o))
.filter(Objects::nonNull).findFirst().orElse(null);
}
@Nullable
public static Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
return SearchEverywhereClassifier.EP_NAME.getExtensionList().stream()
.map(classifier -> classifier.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus)).filter(Objects::nonNull)
.findFirst().orElse(null);
}
@Nullable
public static GlobalSearchScope getProjectScope(@NotNull Project project) {
return SearchEverywhereClassifier.EP_NAME.getExtensionList().stream()
.map(classifier -> classifier.getProjectScope(project))
.filter(Objects::nonNull).findFirst().orElse(null);
}
}
ExtensionPointName<SearchEverywhereClassifier> EP_NAME = ExtensionPointName.create("com.intellij.searchEverywhereClassifier");
boolean isClass(@Nullable Object o);
boolean isSymbol(@Nullable Object o);
@Nullable
VirtualFile getVirtualFile(@NotNull Object o);
@Nullable
Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus);
@Nullable
default GlobalSearchScope getProjectScope(@NotNull Project project) { return null; }
}
|
leafclick/intellij-community
|
platform/lang-impl/src/com/intellij/ide/actions/SearchEverywhereClassifier.java
|
Java
|
apache-2.0
| 2,658 |
// Copyright 2000-2017 JetBrains s.r.o.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package org.jetbrains.annotations;
import java.lang.annotation.*;
/**
* An annotation which depicts that method returns a read-only value or a variable
* contains a read-only value. Read-only value means that calling methods which may
* mutate this value (alter visible behavior) either don't have any effect or throw
* an exception. This does not mean that value cannot be altered at all. For example,
* a value could be a read-only wrapper over a mutable value.
* <p>
* This annotation is experimental and may be changed/removed in future
* without additional notice!
* </p>
*/
@Documented
@Retention(RetentionPolicy.CLASS)
@Target({ElementType.METHOD, ElementType.FIELD, ElementType.PARAMETER, ElementType.LOCAL_VARIABLE})
@ApiStatus.Experimental
public @interface ReadOnly {
}
|
ThiagoGarciaAlves/intellij-community
|
platform/util/src/org/jetbrains/annotations/ReadOnly.java
|
Java
|
apache-2.0
| 1,386 |
/*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.index.query;
import com.carrotsearch.hppc.ObjectFloatOpenHashMap;
import com.google.common.collect.Lists;
import org.apache.lucene.queryparser.classic.MapperQueryParser;
import org.apache.lucene.queryparser.classic.QueryParserSettings;
import org.apache.lucene.search.BooleanQuery;
import org.apache.lucene.search.Query;
import org.elasticsearch.common.ParseField;
import org.elasticsearch.common.Strings;
import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.common.lucene.search.Queries;
import org.elasticsearch.common.regex.Regex;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.unit.Fuzziness;
import org.elasticsearch.common.util.LocaleUtils;
import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.index.analysis.NamedAnalyzer;
import org.elasticsearch.index.query.support.QueryParsers;
import org.joda.time.DateTimeZone;
import java.io.IOException;
import java.util.Locale;
import static org.elasticsearch.common.lucene.search.Queries.fixNegativeQueryIfNeeded;
/**
*
*/
public class QueryStringQueryParser implements QueryParser {
public static final String NAME = "query_string";
private static final ParseField FUZZINESS = Fuzziness.FIELD.withDeprecation("fuzzy_min_sim");
private final boolean defaultAnalyzeWildcard;
private final boolean defaultAllowLeadingWildcard;
@Inject
public QueryStringQueryParser(Settings settings) {
this.defaultAnalyzeWildcard = settings.getAsBoolean("indices.query.query_string.analyze_wildcard", QueryParserSettings.DEFAULT_ANALYZE_WILDCARD);
this.defaultAllowLeadingWildcard = settings.getAsBoolean("indices.query.query_string.allowLeadingWildcard", QueryParserSettings.DEFAULT_ALLOW_LEADING_WILDCARD);
}
@Override
public String[] names() {
return new String[]{NAME, Strings.toCamelCase(NAME)};
}
@Override
public Query parse(QueryParseContext parseContext) throws IOException, QueryParsingException {
XContentParser parser = parseContext.parser();
String queryName = null;
QueryParserSettings qpSettings = new QueryParserSettings();
qpSettings.defaultField(parseContext.defaultField());
qpSettings.lenient(parseContext.queryStringLenient());
qpSettings.analyzeWildcard(defaultAnalyzeWildcard);
qpSettings.allowLeadingWildcard(defaultAllowLeadingWildcard);
qpSettings.locale(Locale.ROOT);
String currentFieldName = null;
XContentParser.Token token;
while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
if (token == XContentParser.Token.FIELD_NAME) {
currentFieldName = parser.currentName();
} else if (token == XContentParser.Token.START_ARRAY) {
if ("fields".equals(currentFieldName)) {
while ((token = parser.nextToken()) != XContentParser.Token.END_ARRAY) {
String fField = null;
float fBoost = -1;
char[] text = parser.textCharacters();
int end = parser.textOffset() + parser.textLength();
for (int i = parser.textOffset(); i < end; i++) {
if (text[i] == '^') {
int relativeLocation = i - parser.textOffset();
fField = new String(text, parser.textOffset(), relativeLocation);
fBoost = Float.parseFloat(new String(text, i + 1, parser.textLength() - relativeLocation - 1));
break;
}
}
if (fField == null) {
fField = parser.text();
}
if (qpSettings.fields() == null) {
qpSettings.fields(Lists.<String>newArrayList());
}
if (Regex.isSimpleMatchPattern(fField)) {
for (String field : parseContext.mapperService().simpleMatchToIndexNames(fField)) {
qpSettings.fields().add(field);
if (fBoost != -1) {
if (qpSettings.boosts() == null) {
qpSettings.boosts(new ObjectFloatOpenHashMap<String>());
}
qpSettings.boosts().put(field, fBoost);
}
}
} else {
qpSettings.fields().add(fField);
if (fBoost != -1) {
if (qpSettings.boosts() == null) {
qpSettings.boosts(new ObjectFloatOpenHashMap<String>());
}
qpSettings.boosts().put(fField, fBoost);
}
}
}
} else {
throw new QueryParsingException(parseContext, "[query_string] query does not support [" + currentFieldName
+ "]");
}
} else if (token.isValue()) {
if ("query".equals(currentFieldName)) {
qpSettings.queryString(parser.text());
} else if ("default_field".equals(currentFieldName) || "defaultField".equals(currentFieldName)) {
qpSettings.defaultField(parser.text());
} else if ("default_operator".equals(currentFieldName) || "defaultOperator".equals(currentFieldName)) {
String op = parser.text();
if ("or".equalsIgnoreCase(op)) {
qpSettings.defaultOperator(org.apache.lucene.queryparser.classic.QueryParser.Operator.OR);
} else if ("and".equalsIgnoreCase(op)) {
qpSettings.defaultOperator(org.apache.lucene.queryparser.classic.QueryParser.Operator.AND);
} else {
throw new QueryParsingException(parseContext, "Query default operator [" + op + "] is not allowed");
}
} else if ("analyzer".equals(currentFieldName)) {
NamedAnalyzer analyzer = parseContext.analysisService().analyzer(parser.text());
if (analyzer == null) {
throw new QueryParsingException(parseContext, "[query_string] analyzer [" + parser.text() + "] not found");
}
qpSettings.forcedAnalyzer(analyzer);
} else if ("quote_analyzer".equals(currentFieldName) || "quoteAnalyzer".equals(currentFieldName)) {
NamedAnalyzer analyzer = parseContext.analysisService().analyzer(parser.text());
if (analyzer == null) {
throw new QueryParsingException(parseContext, "[query_string] quote_analyzer [" + parser.text()
+ "] not found");
}
qpSettings.forcedQuoteAnalyzer(analyzer);
} else if ("allow_leading_wildcard".equals(currentFieldName) || "allowLeadingWildcard".equals(currentFieldName)) {
qpSettings.allowLeadingWildcard(parser.booleanValue());
} else if ("auto_generate_phrase_queries".equals(currentFieldName) || "autoGeneratePhraseQueries".equals(currentFieldName)) {
qpSettings.autoGeneratePhraseQueries(parser.booleanValue());
} else if ("max_determinized_states".equals(currentFieldName) || "maxDeterminizedStates".equals(currentFieldName)) {
qpSettings.maxDeterminizedStates(parser.intValue());
} else if ("lowercase_expanded_terms".equals(currentFieldName) || "lowercaseExpandedTerms".equals(currentFieldName)) {
qpSettings.lowercaseExpandedTerms(parser.booleanValue());
} else if ("enable_position_increments".equals(currentFieldName) || "enablePositionIncrements".equals(currentFieldName)) {
qpSettings.enablePositionIncrements(parser.booleanValue());
} else if ("escape".equals(currentFieldName)) {
qpSettings.escape(parser.booleanValue());
} else if ("use_dis_max".equals(currentFieldName) || "useDisMax".equals(currentFieldName)) {
qpSettings.useDisMax(parser.booleanValue());
} else if ("fuzzy_prefix_length".equals(currentFieldName) || "fuzzyPrefixLength".equals(currentFieldName)) {
qpSettings.fuzzyPrefixLength(parser.intValue());
} else if ("fuzzy_max_expansions".equals(currentFieldName) || "fuzzyMaxExpansions".equals(currentFieldName)) {
qpSettings.fuzzyMaxExpansions(parser.intValue());
} else if ("fuzzy_rewrite".equals(currentFieldName) || "fuzzyRewrite".equals(currentFieldName)) {
qpSettings.fuzzyRewriteMethod(QueryParsers.parseRewriteMethod(parser.textOrNull()));
} else if ("phrase_slop".equals(currentFieldName) || "phraseSlop".equals(currentFieldName)) {
qpSettings.phraseSlop(parser.intValue());
} else if (FUZZINESS.match(currentFieldName, parseContext.parseFlags())) {
qpSettings.fuzzyMinSim(Fuzziness.parse(parser).asSimilarity());
} else if ("boost".equals(currentFieldName)) {
qpSettings.boost(parser.floatValue());
} else if ("tie_breaker".equals(currentFieldName) || "tieBreaker".equals(currentFieldName)) {
qpSettings.tieBreaker(parser.floatValue());
} else if ("analyze_wildcard".equals(currentFieldName) || "analyzeWildcard".equals(currentFieldName)) {
qpSettings.analyzeWildcard(parser.booleanValue());
} else if ("rewrite".equals(currentFieldName)) {
qpSettings.rewriteMethod(QueryParsers.parseRewriteMethod(parser.textOrNull()));
} else if ("minimum_should_match".equals(currentFieldName) || "minimumShouldMatch".equals(currentFieldName)) {
qpSettings.minimumShouldMatch(parser.textOrNull());
} else if ("quote_field_suffix".equals(currentFieldName) || "quoteFieldSuffix".equals(currentFieldName)) {
qpSettings.quoteFieldSuffix(parser.textOrNull());
} else if ("lenient".equalsIgnoreCase(currentFieldName)) {
qpSettings.lenient(parser.booleanValue());
} else if ("locale".equals(currentFieldName)) {
String localeStr = parser.text();
qpSettings.locale(LocaleUtils.parse(localeStr));
} else if ("time_zone".equals(currentFieldName)) {
try {
qpSettings.timeZone(DateTimeZone.forID(parser.text()));
} catch (IllegalArgumentException e) {
throw new QueryParsingException(parseContext,
"[query_string] time_zone [" + parser.text() + "] is unknown");
}
} else if ("_name".equals(currentFieldName)) {
queryName = parser.text();
} else {
throw new QueryParsingException(parseContext, "[query_string] query does not support [" + currentFieldName
+ "]");
}
}
}
if (qpSettings.queryString() == null) {
throw new QueryParsingException(parseContext, "query_string must be provided with a [query]");
}
qpSettings.defaultAnalyzer(parseContext.mapperService().searchAnalyzer());
qpSettings.defaultQuoteAnalyzer(parseContext.mapperService().searchQuoteAnalyzer());
if (qpSettings.escape()) {
qpSettings.queryString(org.apache.lucene.queryparser.classic.QueryParser.escape(qpSettings.queryString()));
}
qpSettings.queryTypes(parseContext.queryTypes());
MapperQueryParser queryParser = parseContext.queryParser(qpSettings);
try {
Query query = queryParser.parse(qpSettings.queryString());
if (query == null) {
return null;
}
if (qpSettings.boost() != QueryParserSettings.DEFAULT_BOOST) {
query.setBoost(query.getBoost() * qpSettings.boost());
}
query = fixNegativeQueryIfNeeded(query);
if (query instanceof BooleanQuery) {
Queries.applyMinimumShouldMatch((BooleanQuery) query, qpSettings.minimumShouldMatch());
}
if (queryName != null) {
parseContext.addNamedQuery(queryName, query);
}
return query;
} catch (org.apache.lucene.queryparser.classic.ParseException e) {
throw new QueryParsingException(parseContext, "Failed to parse query [" + qpSettings.queryString() + "]", e);
}
}
}
|
vrkansagara/elasticsearch
|
src/main/java/org/elasticsearch/index/query/QueryStringQueryParser.java
|
Java
|
apache-2.0
| 14,068 |
package com.uppidy.android.sdk.api;
import org.springframework.social.ApiBinding;
import org.springframework.web.client.RestOperations;
public interface Uppidy extends ApiBinding {
/**
* API for performing operations on Uppidy user profiles.
*/
UserOperations userOperations();
/**
* API for performing operations on Uppidy feeds.
*/
FeedOperations feedOperations();
/**
* API for performing backup operations.
*/
BackupOperations backupOperations();
/**
* Returns the underlying {@link RestOperations} object allowing for
* consumption of Uppidy endpoints that may not be otherwise covered by the
* API binding.
*
* The RestOperations object returned is configured to include an OAuth 2
* "Authorization" header on all requests.
*/
RestOperations restOperations();
/**
* Base REST API URL
*/
String getBaseUrl();
}
|
uppidy/uppidy-android-sdk
|
src/main/java/com/uppidy/android/sdk/api/Uppidy.java
|
Java
|
apache-2.0
| 865 |
/*
* Copyright 2012 The Netty Project
*
* The Netty Project licenses this file to you under the Apache License,
* version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package io.netty.channel.socket;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelStateHandler;
/**
* Special event which will be fired and passed to the
* {@link ChannelStateHandler#userEventTriggered(ChannelHandlerContext, Object)} methods once the input of
* a {@link SocketChannel} was shutdown and the {@link SocketChannelConfig#isAllowHalfClosure()} method returns
* {@code true}.
*/
public final class ChannelInputShutdownEvent {
/**
* Instance to use
*/
public static final ChannelInputShutdownEvent INSTANCE = new ChannelInputShutdownEvent();
private ChannelInputShutdownEvent() { }
}
|
menacher/netty
|
transport/src/main/java/io/netty/channel/socket/ChannelInputShutdownEvent.java
|
Java
|
apache-2.0
| 1,289 |
export default {
facebook: {
clientID: '400433857010396',
callbackURL: 'http://localhost:3000/login/facebook',
clientSecret: 'fc4d724594a9090abcae63a3ce04c59d',
},
google: {
clientID: '670852447590-fu46rula0s61gelma71s6o8s1e74f51u.apps.googleusercontent.com',
callbackURL: 'http://localhost:3000/login/google',
clientSecret: 'CsQzXepIfr-oWh-xum1d43ZQ',
}
}
|
KonstantoS/KPIeda
|
packages/kpi-eda/server/src/controllers/config/auth.js
|
JavaScript
|
apache-2.0
| 389 |
# Dryopteris oxyodus (Baker) C Chr. SPECIES
#### Status
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null
|
mdoering/backbone
|
life/Plantae/Pteridophyta/Polypodiopsida/Polypodiales/Dryopteridaceae/Dryopteris/Dryopteris oxyodus/README.md
|
Markdown
|
apache-2.0
| 183 |
// Package profile provides a simple way to manage runtime/pprof
// profiling of your Go application.
package profile
import (
"io/ioutil"
"log"
"os"
"os/signal"
"path/filepath"
"runtime"
"runtime/pprof"
"sync/atomic"
)
const (
cpuMode = iota
memMode
blockMode
traceMode
)
// Profile represents an active profiling session.
type Profile struct {
// quiet suppresses informational messages during profiling.
quiet bool
// noShutdownHook controls whether the profiling package should
// hook SIGINT to write profiles cleanly.
noShutdownHook bool
// mode holds the type of profiling that will be made
mode int
// path holds the base path where various profiling files are written.
// If blank, the base path will be generated by ioutil.TempDir.
path string
// memProfileRate holds the rate for the memory profile.
memProfileRate int
// closer holds a cleanup function that run after each profile
closer func()
// stopped records if a call to profile.Stop has been made
stopped uint32
}
// NoShutdownHook controls whether the profiling package should
// hook SIGINT to write profiles cleanly.
// Programs with more sophisticated signal handling should set
// this to true and ensure the Stop() function returned from Start()
// is called during shutdown.
func NoShutdownHook(p *Profile) { p.noShutdownHook = true }
// Quiet suppresses informational messages during profiling.
func Quiet(p *Profile) { p.quiet = true }
// CPUProfile enables cpu profiling.
// It disables any previous profiling settings.
func CPUProfile(p *Profile) { p.mode = cpuMode }
// DefaultMemProfileRate is the default memory profiling rate.
// See also http://golang.org/pkg/runtime/#pkg-variables
const DefaultMemProfileRate = 4096
// MemProfile enables memory profiling.
// It disables any previous profiling settings.
func MemProfile(p *Profile) {
p.memProfileRate = DefaultMemProfileRate
p.mode = memMode
}
// MemProfileRate enables memory profiling at the preferred rate.
// It disables any previous profiling settings.
func MemProfileRate(rate int) func(*Profile) {
return func(p *Profile) {
p.memProfileRate = rate
p.mode = memMode
}
}
// BlockProfile enables block (contention) profiling.
// It disables any previous profiling settings.
func BlockProfile(p *Profile) { p.mode = blockMode }
// ProfilePath controls the base path where various profiling
// files are written. If blank, the base path will be generated
// by ioutil.TempDir.
func ProfilePath(path string) func(*Profile) {
return func(p *Profile) {
p.path = path
}
}
// Stop stops the profile and flushes any unwritten data.
func (p *Profile) Stop() {
if !atomic.CompareAndSwapUint32(&p.stopped, 0, 1) {
// someone has already called close
return
}
p.closer()
atomic.StoreUint32(&started, 0)
}
// started is non zero if a profile is running.
var started uint32
// Start starts a new profiling session.
// The caller should call the Stop method on the value returned
// to cleanly stop profiling.
func Start(options ...func(*Profile)) interface {
Stop()
} {
if !atomic.CompareAndSwapUint32(&started, 0, 1) {
log.Fatal("profile: Start() already called")
}
var prof Profile
for _, option := range options {
option(&prof)
}
path, err := func() (string, error) {
if p := prof.path; p != "" {
return p, os.MkdirAll(p, 0777)
}
return ioutil.TempDir("", "profile")
}()
if err != nil {
log.Fatalf("profile: could not create initial output directory: %v", err)
}
logf := func(format string, args ...interface{}) {
if !prof.quiet {
log.Printf(format, args...)
}
}
switch prof.mode {
case cpuMode:
fn := filepath.Join(path, "cpu.pprof")
f, err := os.Create(fn)
if err != nil {
log.Fatalf("profile: could not create cpu profile %q: %v", fn, err)
}
logf("profile: cpu profiling enabled, %s", fn)
pprof.StartCPUProfile(f)
prof.closer = func() {
pprof.StopCPUProfile()
f.Close()
logf("profile: cpu profiling disabled, %s", fn)
}
case memMode:
fn := filepath.Join(path, "mem.pprof")
f, err := os.Create(fn)
if err != nil {
log.Fatalf("profile: could not create memory profile %q: %v", fn, err)
}
old := runtime.MemProfileRate
runtime.MemProfileRate = prof.memProfileRate
logf("profile: memory profiling enabled (rate %d), %s", runtime.MemProfileRate, fn)
prof.closer = func() {
pprof.Lookup("heap").WriteTo(f, 0)
f.Close()
runtime.MemProfileRate = old
logf("profile: memory profiling disabled, %s", fn)
}
case blockMode:
fn := filepath.Join(path, "block.pprof")
f, err := os.Create(fn)
if err != nil {
log.Fatalf("profile: could not create block profile %q: %v", fn, err)
}
runtime.SetBlockProfileRate(1)
logf("profile: block profiling enabled, %s", fn)
prof.closer = func() {
pprof.Lookup("block").WriteTo(f, 0)
f.Close()
runtime.SetBlockProfileRate(0)
logf("profile: block profiling disabled, %s", fn)
}
case traceMode:
fn := filepath.Join(path, "trace.out")
f, err := os.Create(fn)
if err != nil {
log.Fatalf("profile: could not create trace output file %q: %v", fn, err)
}
if err := startTrace(f); err != nil {
log.Fatalf("profile: could not start trace: %v", err)
}
logf("profile: trace enabled, %s", fn)
prof.closer = func() {
stopTrace()
logf("profile: trace disabled, %s", fn)
}
}
if !prof.noShutdownHook {
go func() {
c := make(chan os.Signal, 1)
signal.Notify(c, os.Interrupt)
<-c
log.Println("profile: caught interrupt, stopping profiles")
prof.Stop()
os.Exit(0)
}()
}
return &prof
}
|
pandemicsyn/megacfs
|
vendor/github.com/pkg/profile/profile.go
|
GO
|
apache-2.0
| 5,586 |
# Gymnosporangium paraphysatum Vienn.-Bourg., 1961 SPECIES
#### Status
ACCEPTED
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
Gymnosporangium paraphysatum Vienn.-Bourg., 1961
### Remarks
null
|
mdoering/backbone
|
life/Fungi/Basidiomycota/Pucciniomycetes/Pucciniales/Pucciniaceae/Gymnosporangium/Gymnosporangium paraphysatum/README.md
|
Markdown
|
apache-2.0
| 250 |
/*
* Copyright (C) 2017 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.media3.exoplayer.source;
import static com.google.common.truth.Truth.assertThat;
import android.net.Uri;
import android.util.Pair;
import androidx.media3.common.C;
import androidx.media3.common.MediaItem;
import androidx.media3.common.Timeline.Period;
import androidx.media3.common.Timeline.Window;
import androidx.test.ext.junit.runners.AndroidJUnit4;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
/** Unit test for {@link SinglePeriodTimeline}. */
@RunWith(AndroidJUnit4.class)
public final class SinglePeriodTimelineTest {
private Window window;
private Period period;
@Before
public void setUp() throws Exception {
window = new Window();
period = new Period();
}
@Test
public void getPeriodPositionDynamicWindowUnknownDuration() {
SinglePeriodTimeline timeline =
new SinglePeriodTimeline(
/* durationUs= */ C.TIME_UNSET,
/* isSeekable= */ false,
/* isDynamic= */ true,
/* isLive= */ true,
/* manifest= */ null,
MediaItem.fromUri(Uri.EMPTY));
// Should return null with any positive position projection.
Pair<Object, Long> positionUs =
timeline.getPeriodPositionUs(
window,
period,
/* windowIndex= */ 0,
/* windowPositionUs= */ C.TIME_UNSET,
/* defaultPositionProjectionUs= */ 1);
assertThat(positionUs).isNull();
// Should return (0, 0) without a position projection.
positionUs =
timeline.getPeriodPositionUs(
window,
period,
/* windowIndex= */ 0,
/* windowPositionUs= */ C.TIME_UNSET,
/* defaultPositionProjectionUs= */ 0);
assertThat(positionUs.first).isEqualTo(timeline.getUidOfPeriod(0));
assertThat(positionUs.second).isEqualTo(0);
}
@Test
public void getPeriodPositionDynamicWindowKnownDuration() {
long windowDurationUs = 1000;
SinglePeriodTimeline timeline =
new SinglePeriodTimeline(
windowDurationUs,
windowDurationUs,
/* windowPositionInPeriodUs= */ 0,
/* windowDefaultStartPositionUs= */ 0,
/* isSeekable= */ false,
/* isDynamic= */ true,
/* useLiveConfiguration= */ true,
/* manifest= */ null,
MediaItem.fromUri(Uri.EMPTY));
// Should return null with a positive position projection beyond window duration.
Pair<Object, Long> positionUs =
timeline.getPeriodPositionUs(
window,
period,
/* windowIndex= */ 0,
/* windowPositionUs= */ C.TIME_UNSET,
/* defaultPositionProjectionUs= */ windowDurationUs + 1);
assertThat(positionUs).isNull();
// Should return (0, duration) with a projection equal to window duration.
positionUs =
timeline.getPeriodPositionUs(
window,
period,
/* windowIndex= */ 0,
/* windowPositionUs= */ C.TIME_UNSET,
/* defaultPositionProjectionUs= */ windowDurationUs - 1);
assertThat(positionUs.first).isEqualTo(timeline.getUidOfPeriod(0));
assertThat(positionUs.second).isEqualTo(windowDurationUs - 1);
// Should return (0, 0) without a position projection.
positionUs =
timeline.getPeriodPositionUs(
window,
period,
/* windowIndex= */ 0,
/* windowPositionUs= */ C.TIME_UNSET,
/* defaultPositionProjectionUs= */ 0);
assertThat(positionUs.first).isEqualTo(timeline.getUidOfPeriod(0));
assertThat(positionUs.second).isEqualTo(0);
}
@Test
@SuppressWarnings("deprecation") // Testing deprecated Window.tag is still populated correctly.
public void setNullTag_returnsNullTag_butUsesDefaultUid() {
SinglePeriodTimeline timeline =
new SinglePeriodTimeline(
/* durationUs= */ C.TIME_UNSET,
/* isSeekable= */ false,
/* isDynamic= */ false,
/* isLive= */ false,
/* manifest= */ null,
new MediaItem.Builder().setUri(Uri.EMPTY).setTag(null).build());
assertThat(timeline.getWindow(/* windowIndex= */ 0, window).tag).isNull();
assertThat(timeline.getWindow(/* windowIndex= */ 0, window).mediaItem.localConfiguration.tag)
.isNull();
assertThat(timeline.getPeriod(/* periodIndex= */ 0, period, /* setIds= */ false).id).isNull();
assertThat(timeline.getPeriod(/* periodIndex= */ 0, period, /* setIds= */ true).id).isNull();
assertThat(timeline.getPeriod(/* periodIndex= */ 0, period, /* setIds= */ false).uid).isNull();
assertThat(timeline.getPeriod(/* periodIndex= */ 0, period, /* setIds= */ true).uid)
.isNotNull();
}
@Test
@SuppressWarnings("deprecation") // Testing deprecated Window.tag is still populated correctly.
public void getWindow_setsTag() {
Object tag = new Object();
SinglePeriodTimeline timeline =
new SinglePeriodTimeline(
/* durationUs= */ C.TIME_UNSET,
/* isSeekable= */ false,
/* isDynamic= */ false,
/* isLive= */ false,
/* manifest= */ null,
new MediaItem.Builder().setUri(Uri.EMPTY).setTag(tag).build());
assertThat(timeline.getWindow(/* windowIndex= */ 0, window).tag).isEqualTo(tag);
}
// Tests backward compatibility.
@SuppressWarnings("deprecation")
@Test
public void getWindow_setsMediaItemAndTag() {
MediaItem mediaItem = new MediaItem.Builder().setUri(Uri.EMPTY).setTag(new Object()).build();
SinglePeriodTimeline timeline =
new SinglePeriodTimeline(
/* durationUs= */ C.TIME_UNSET,
/* isSeekable= */ false,
/* isDynamic= */ false,
/* isLive= */ false,
/* manifest= */ null,
mediaItem);
Window window = timeline.getWindow(/* windowIndex= */ 0, this.window);
assertThat(window.mediaItem).isEqualTo(mediaItem);
assertThat(window.tag).isEqualTo(mediaItem.localConfiguration.tag);
}
@Test
public void getIndexOfPeriod_returnsPeriod() {
SinglePeriodTimeline timeline =
new SinglePeriodTimeline(
/* durationUs= */ C.TIME_UNSET,
/* isSeekable= */ false,
/* isDynamic= */ false,
/* isLive= */ false,
/* manifest= */ null,
MediaItem.fromUri(Uri.EMPTY));
Object uid = timeline.getPeriod(/* periodIndex= */ 0, period, /* setIds= */ true).uid;
assertThat(timeline.getIndexOfPeriod(uid)).isEqualTo(0);
assertThat(timeline.getIndexOfPeriod(/* uid= */ null)).isEqualTo(C.INDEX_UNSET);
assertThat(timeline.getIndexOfPeriod(/* uid= */ new Object())).isEqualTo(C.INDEX_UNSET);
}
}
|
androidx/media
|
libraries/exoplayer/src/test/java/androidx/media3/exoplayer/source/SinglePeriodTimelineTest.java
|
Java
|
apache-2.0
| 7,399 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.