repo_name
stringlengths
4
116
path
stringlengths
4
379
size
stringlengths
1
7
content
stringlengths
3
1.05M
license
stringclasses
15 values
erwinmombay/amphtml
extensions/amp-story/1.0/amp-story.js
82511
/** * Copyright 2017 The AMP HTML 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. */ /** * @fileoverview Embeds a story * * Example: * <code> * <amp-story standalone> * [...] * </amp-story> * </code> */ import './amp-story-cta-layer'; import './amp-story-grid-layer'; import './amp-story-page'; import { Action, EmbeddedComponentState, InteractiveComponentDef, StateProperty, UIType, getStoreService, } from './amp-story-store-service'; import {ActionTrust} from '../../../src/action-constants'; import {AdvancementConfig, TapNavigationDirection} from './page-advancement'; import { AdvancementMode, StoryAnalyticsEvent, getAnalyticsService, } from './story-analytics'; import {AmpEvents} from '../../../src/amp-events'; import {AmpStoryAccess} from './amp-story-access'; import {AmpStoryBookend} from './bookend/amp-story-bookend'; import {AmpStoryConsent} from './amp-story-consent'; import {AmpStoryCtaLayer} from './amp-story-cta-layer'; import {AmpStoryEmbeddedComponent} from './amp-story-embedded-component'; import {AmpStoryGridLayer} from './amp-story-grid-layer'; import {AmpStoryHint} from './amp-story-hint'; import {AmpStoryPage, NavigationDirection, PageState} from './amp-story-page'; import {AmpStoryPageAttachment} from './amp-story-page-attachment'; import {AmpStoryQuiz} from './amp-story-quiz'; import {AmpStoryRenderService} from './amp-story-render-service'; import {AmpStoryViewerMessagingHandler} from './amp-story-viewer-messaging-handler'; import {AnalyticsVariable, getVariableService} from './variable-service'; import {CSS} from '../../../build/amp-story-1.0.css'; import {CommonSignals} from '../../../src/common-signals'; import {EventType, dispatch} from './events'; import {Gestures} from '../../../src/gesture'; import { HistoryState, getHistoryState, removeAttributeInMutate, setAttributeInMutate, setHistoryState, shouldShowStoryUrlInfo, } from './utils'; import {InfoDialog} from './amp-story-info-dialog'; import {Keys} from '../../../src/utils/key-codes'; import {Layout} from '../../../src/layout'; import {LiveStoryManager} from './live-story-manager'; import {LocalizationService} from '../../../src/service/localization'; import {MediaPool, MediaType} from './media-pool'; import {PaginationButtons} from './pagination-buttons'; import {Services} from '../../../src/services'; import {ShareMenu} from './amp-story-share-menu'; import {SwipeXYRecognizer} from '../../../src/gesture-recognizers'; import {SystemLayer} from './amp-story-system-layer'; import {UnsupportedBrowserLayer} from './amp-story-unsupported-browser-layer'; import {ViewportWarningLayer} from './amp-story-viewport-warning-layer'; import { childElement, childElementByTag, childElements, childNodes, closest, createElementWithAttributes, isRTL, scopedQuerySelectorAll, whenUpgradedToCustomElement, } from '../../../src/dom'; import { computedStyle, px, resetStyles, setImportantStyles, toggle, } from '../../../src/style'; import {createPseudoLocale} from '../../../src/localized-strings'; import {debounce} from '../../../src/utils/rate-limit'; import {dev, devAssert, user} from '../../../src/log'; import {dict, map} from '../../../src/utils/object'; import {endsWith} from '../../../src/string'; import {escapeCssSelectorIdent} from '../../../src/css'; import {findIndex} from '../../../src/utils/array'; import {getConsentPolicyState} from '../../../src/consent'; import {getDetail} from '../../../src/event-helper'; import {getMediaQueryService} from './amp-story-media-query-service'; import {getMode} from '../../../src/mode'; import {getState} from '../../../src/history'; import {isExperimentOn} from '../../../src/experiments'; import {parseQueryString} from '../../../src/url'; import {registerServiceBuilder} from '../../../src/service'; import {upgradeBackgroundAudio} from './audio'; import LocalizedStringsAr from './_locales/ar'; import LocalizedStringsDe from './_locales/de'; import LocalizedStringsDefault from './_locales/default'; import LocalizedStringsEn from './_locales/en'; import LocalizedStringsEnGb from './_locales/en-GB'; import LocalizedStringsEs from './_locales/es'; import LocalizedStringsEs419 from './_locales/es-419'; import LocalizedStringsFr from './_locales/fr'; import LocalizedStringsHi from './_locales/hi'; import LocalizedStringsId from './_locales/id'; import LocalizedStringsIt from './_locales/it'; import LocalizedStringsJa from './_locales/ja'; import LocalizedStringsKo from './_locales/ko'; import LocalizedStringsNl from './_locales/nl'; import LocalizedStringsNo from './_locales/no'; import LocalizedStringsPtBr from './_locales/pt-BR'; import LocalizedStringsPtPt from './_locales/pt-PT'; import LocalizedStringsRu from './_locales/ru'; import LocalizedStringsTr from './_locales/tr'; import LocalizedStringsVi from './_locales/vi'; import LocalizedStringsZhCn from './_locales/zh-CN'; import LocalizedStringsZhTw from './_locales/zh-TW'; /** @private @const {number} */ const DESKTOP_WIDTH_THRESHOLD = 1024; /** @private @const {number} */ const DESKTOP_HEIGHT_THRESHOLD = 550; /** @private @const {number} */ const MIN_SWIPE_FOR_HINT_OVERLAY_PX = 50; /** @enum {string} */ const Attributes = { AD_SHOWING: 'ad-showing', ADVANCE_TO: 'i-amphtml-advance-to', AUTO_ADVANCE_AFTER: 'auto-advance-after', AUTO_ADVANCE_TO: 'auto-advance-to', DESKTOP_POSITION: 'i-amphtml-desktop-position', ORIENTATION: 'orientation', PUBLIC_ADVANCE_TO: 'advance-to', RETURN_TO: 'i-amphtml-return-to', STANDALONE: 'standalone', SUPPORTS_LANDSCAPE: 'supports-landscape', // Attributes that desktop css looks for to decide where pages will be placed VISITED: 'i-amphtml-visited', // stacked offscreen to left }; /** * The duration of time (in milliseconds) to wait for a page to be loaded, * before the story becomes visible. * @const {number} */ const PAGE_LOAD_TIMEOUT_MS = 5000; /** * Single page ads may be injected later. If the original story contains 0 media * elements the mediaPool will not be able to handle the injected audio/video * Therefore we preallocate a minimum here. * @const {number} */ const MINIMUM_AD_MEDIA_ELEMENTS = 2; /** * CSS class for an amp-story that indicates the initial load for the story has * completed. * @const {string} */ const STORY_LOADED_CLASS_NAME = 'i-amphtml-story-loaded'; /** * CSS class for the opacity layer that separates the amp-sidebar and the rest * of the story when the amp-sidebar is entering the screen. * @const {string} */ const OPACITY_MASK_CLASS_NAME = 'i-amphtml-story-opacity-mask'; /** * CSS class for sidebars in stories. * @const {string} */ const SIDEBAR_CLASS_NAME = 'i-amphtml-story-sidebar'; /** @const {!Object<string, number>} */ const MAX_MEDIA_ELEMENT_COUNTS = { [MediaType.AUDIO]: 4, [MediaType.VIDEO]: 8, }; /** @type {string} */ const TAG = 'amp-story'; /** * Selector for elements that should be hidden when the bookend is open on * desktop view. * @private @const {string} */ const HIDE_ON_BOOKEND_SELECTOR = 'amp-story-page, .i-amphtml-story-system-layer'; /** * The default dark gray for chrome supported theme color. * @const {string} */ const DEFAULT_THEME_COLOR = '#202125'; /** * MutationObserverInit options to listen for changes to the `open` attribute. */ const SIDEBAR_OBSERVER_OPTIONS = { attributes: true, attributeFilter: ['open'], }; /** * @implements {./media-pool.MediaPoolRoot} */ export class AmpStory extends AMP.BaseElement { /** @param {!AmpElement} element */ constructor(element) { super(element); /** @private @const {!./amp-story-store-service.AmpStoryStoreService} */ this.storeService_ = getStoreService(this.win); // Check if story is RTL. if (isRTL(this.win.document)) { this.storeService_.dispatch(Action.TOGGLE_RTL, true); } /** @private {!./story-analytics.StoryAnalyticsService} */ this.analyticsService_ = getAnalyticsService(this.win, this.element); /** @private @const {!AdvancementConfig} */ this.advancement_ = AdvancementConfig.forElement(this.win, this.element); this.advancement_.start(); /** @const @private {!../../../src/service/vsync-impl.Vsync} */ this.vsync_ = this.getVsync(); /** @private {?AmpStoryBookend} */ this.bookend_ = null; /** @private @const {!ShareMenu} Preloads and prerenders the share menu. */ this.shareMenu_ = new ShareMenu(this.win, this.element); /** @private @const {!SystemLayer} */ this.systemLayer_ = new SystemLayer(this.win, this.element); /** Instantiate in case there are embedded components. */ new AmpStoryEmbeddedComponent(this.win, this.element); /** @private @const {!UnsupportedBrowserLayer} */ this.unsupportedBrowserLayer_ = new UnsupportedBrowserLayer(this.win); /** Instantiates the viewport warning layer. */ new ViewportWarningLayer( this.win, this.element, DESKTOP_WIDTH_THRESHOLD, DESKTOP_HEIGHT_THRESHOLD ); /** @private {!Array<!./amp-story-page.AmpStoryPage>} */ this.pages_ = []; /** @private @const {!Array<!./amp-story-page.AmpStoryPage>} */ this.adPages_ = []; /** @const @private {!./variable-service.AmpStoryVariableService} */ this.variableService_ = getVariableService(this.win); /** @private {?./amp-story-page.AmpStoryPage} */ this.activePage_ = null; /** @private @const */ this.desktopMedia_ = this.win.matchMedia( `(min-width: ${DESKTOP_WIDTH_THRESHOLD}px) and ` + `(min-height: ${DESKTOP_HEIGHT_THRESHOLD}px)` ); /** @private @const */ this.canRotateToDesktopMedia_ = this.win.matchMedia( `(min-width: ${DESKTOP_HEIGHT_THRESHOLD}px) and ` + `(min-height: ${DESKTOP_WIDTH_THRESHOLD}px)` ); /** @private @const */ this.landscapeOrientationMedia_ = this.win.matchMedia( '(orientation: landscape)' ); /** @private {?HTMLMediaElement} */ this.backgroundAudioEl_ = null; /** @private {?./pagination-buttons.PaginationButtons} */ this.paginationButtons_ = null; /** @private {!AmpStoryHint} */ this.ampStoryHint_ = new AmpStoryHint(this.win, this.element); /** @private {!MediaPool} */ this.mediaPool_ = MediaPool.for(this); /** @private {boolean} */ this.areAccessAuthorizationsCompleted_ = false; /** @private */ this.navigateToPageAfterAccess_ = null; /** @private @const {!../../../src/service/timer-impl.Timer} */ this.timer_ = Services.timerFor(this.win); /** @private @const {!../../../src/service/platform-impl.Platform} */ this.platform_ = Services.platformFor(this.win); /** @private @const {!../../../src/service/viewer-interface.ViewerInterface} */ this.viewer_ = Services.viewerForDoc(this.element); /** @private @const {?AmpStoryViewerMessagingHandler} */ this.viewerMessagingHandler_ = this.viewer_.isEmbedded() ? new AmpStoryViewerMessagingHandler(this.win, this.viewer_) : null; /** * Store the current paused state, to make sure the story does not play on * resume if it was previously paused. * @private {boolean} */ this.pausedStateToRestore_ = false; /** @private {?Element} */ this.sidebar_ = null; /** @private {?MutationObserver} */ this.sidebarObserver_ = null; /** @private {?Element} */ this.maskElement_ = null; /** @private {?LiveStoryManager} */ this.liveStoryManager_ = null; /** @private @const {!LocalizationService} */ this.localizationService_ = new LocalizationService(this.win); this.localizationService_ .registerLocalizedStringBundle('default', LocalizedStringsDefault) .registerLocalizedStringBundle('ar', LocalizedStringsAr) .registerLocalizedStringBundle('de', LocalizedStringsDe) .registerLocalizedStringBundle('en', LocalizedStringsEn) .registerLocalizedStringBundle('en-GB', LocalizedStringsEnGb) .registerLocalizedStringBundle('es', LocalizedStringsEs) .registerLocalizedStringBundle('es-419', LocalizedStringsEs419) .registerLocalizedStringBundle('fr', LocalizedStringsFr) .registerLocalizedStringBundle('hi', LocalizedStringsHi) .registerLocalizedStringBundle('id', LocalizedStringsId) .registerLocalizedStringBundle('it', LocalizedStringsIt) .registerLocalizedStringBundle('ja', LocalizedStringsJa) .registerLocalizedStringBundle('ko', LocalizedStringsKo) .registerLocalizedStringBundle('nl', LocalizedStringsNl) .registerLocalizedStringBundle('no', LocalizedStringsNo) .registerLocalizedStringBundle('pt-PT', LocalizedStringsPtPt) .registerLocalizedStringBundle('pt-BR', LocalizedStringsPtBr) .registerLocalizedStringBundle('ru', LocalizedStringsRu) .registerLocalizedStringBundle('tr', LocalizedStringsTr) .registerLocalizedStringBundle('vi', LocalizedStringsVi) .registerLocalizedStringBundle('zh-CN', LocalizedStringsZhCn) .registerLocalizedStringBundle('zh-TW', LocalizedStringsZhTw); const enXaPseudoLocaleBundle = createPseudoLocale( LocalizedStringsEn, s => `[${s} one two]` ); this.localizationService_.registerLocalizedStringBundle( 'en-xa', enXaPseudoLocaleBundle ); registerServiceBuilder( this.win, 'localization', () => this.localizationService_ ); } /** @override */ buildCallback() { if (this.isStandalone_()) { this.initializeStandaloneStory_(); } // buildCallback already runs in a mutate context. Calling another // mutateElement explicitly will force the runtime to remeasure the // amp-story element, fixing rendering bugs where the story is inactive // (layoutCallback not called) when accessed from any viewer using // prerendering, because of a height incorrectly set to 0. this.mutateElement(() => {}); const pageEl = this.element.querySelector('amp-story-page'); pageEl && pageEl.setAttribute('active', ''); this.initializeStyles_(); this.initializeListeners_(); this.initializeListenersForDev_(); this.initializePageIds_(); this.storeService_.dispatch(Action.TOGGLE_UI, this.getUIType_()); // Disables the bookend entirely if the story is within a group of stories. if (this.viewer_.hasCapability('swipe')) { this.storeService_.dispatch(Action.TOGGLE_CAN_SHOW_BOOKEND, false); } // Removes title in order to prevent incorrect titles appearing on link // hover. (See 17654) this.element.removeAttribute('title'); // Remove text nodes which would be shown outside of the amp-story const textNodes = childNodes( this.element, node => node.nodeType === Node.TEXT_NODE ); textNodes.forEach(node => { this.element.removeChild(node); }); if (isExperimentOn(this.win, 'amp-story-branching')) { this.registerAction('goToPage', invocation => { const {args} = invocation; if (!args) { return; } this.storeService_.dispatch( Action.SET_ADVANCEMENT_MODE, AdvancementMode.GO_TO_PAGE ); // If open, closes the sidebar before navigating. const promise = this.storeService_.get(StateProperty.SIDEBAR_STATE) ? Services.historyForDoc(this.getAmpDoc()).goBack() : Promise.resolve(); promise.then(() => this.switchTo_(args['id'], NavigationDirection.NEXT) ); }); } } /** * Pauses the whole story on viewer visibilityState updates, or tab visibility * updates. * @private */ pause_() { this.pausedStateToRestore_ = !!this.storeService_.get( StateProperty.PAUSED_STATE ); this.storeService_.dispatch(Action.TOGGLE_PAUSED, true); } /** * Resumes the whole story on viewer visibilityState updates, or tab * visibility updates. * @private */ resume_() { this.storeService_.dispatch( Action.TOGGLE_PAUSED, this.pausedStateToRestore_ ); } /** * Note: runs in the buildCallback vsync mutate context. * @private */ initializeStandaloneStory_() { const html = this.win.document.documentElement; html.classList.add('i-amphtml-story-standalone'); // Lock body to prevent overflow. this.lockBody_(); // Standalone CSS affects sizing of the entire page. this.onResize(); } /** @private */ initializeStyles_() { const mediaQueryEls = this.element.querySelectorAll('media-query'); if (mediaQueryEls.length) { this.initializeMediaQueries_(mediaQueryEls); } const styleEl = this.win.document.querySelector('style[amp-custom]'); if (styleEl) { this.rewriteStyles_(styleEl); } } /** * Registers the media queries * @param {!NodeList<!Element>} mediaQueryEls * @private */ initializeMediaQueries_(mediaQueryEls) { const service = getMediaQueryService(this.win); const onMediaQueryMatch = (matches, className) => { this.mutateElement(() => { this.element.classList.toggle(className, matches); }); }; mediaQueryEls.forEach(el => { const className = el.getAttribute('class-name'); const media = el.getAttribute('media'); if (className && media) { service.onMediaQueryMatch(media, matches => onMediaQueryMatch(matches, className) ); } }); } /** * Initializes page ids by deduplicating them. * @private */ initializePageIds_() { const pageEls = this.element.querySelectorAll('amp-story-page'); const pageIds = Array.prototype.map.call( pageEls, el => el.id || 'default-page' ); const idsMap = map(); for (let i = 0; i < pageIds.length; i++) { if (idsMap[pageIds[i]] === undefined) { idsMap[pageIds[i]] = 0; continue; } user().error(TAG, `Duplicate amp-story-page ID ${pageIds[i]}`); const newId = `${pageIds[i]}__${++idsMap[pageIds[i]]}`; pageEls[i].id = newId; pageIds[i] = newId; } this.storeService_.dispatch(Action.SET_PAGE_IDS, pageIds); } /** * @param {!Element} styleEl * @private */ rewriteStyles_(styleEl) { if (!isExperimentOn(this.win, 'amp-story-responsive-units')) { return; } // TODO(#15955): Update this to use CssContext from // ../../../extensions/amp-animation/0.1/web-animations.js this.mutateElement(() => { styleEl.textContent = styleEl.textContent .replace(/(-?[\d.]+)vh/gim, 'calc($1 * var(--story-page-vh))') .replace(/(-?[\d.]+)vw/gim, 'calc($1 * var(--story-page-vw))') .replace(/(-?[\d.]+)vmin/gim, 'calc($1 * var(--story-page-vmin))') .replace(/(-?[\d.]+)vmax/gim, 'calc($1 * var(--story-page-vmax))'); }); } /** * @private */ setThemeColor_() { // Don't override the publisher's tag. if (this.win.document.querySelector('meta[name=theme-color]')) { return; } // The theme color should be copied from the story's primary accent color // if possible, with the fall back being default dark gray. const meta = this.win.document.createElement('meta'); const ampStoryPageEl = this.element.querySelector('amp-story-page'); meta.name = 'theme-color'; meta.content = computedStyle(this.win, this.element).getPropertyValue( '--primary-color' ) || computedStyle( this.win, dev().assertElement(ampStoryPageEl) ).getPropertyValue('background-color') || DEFAULT_THEME_COLOR; this.win.document.head.appendChild(meta); } /** * @private */ updateViewportSizeStyles_() { const pageEl = (this.activePage_ && this.activePage_.element) || this.element.querySelector('amp-story-page'); if (!pageEl || !this.isStandalone_()) { return; } return this.vsync_.runPromise( { measure: state => { state.vh = pageEl./*OK*/ clientHeight / 100; state.vw = pageEl./*OK*/ clientWidth / 100; state.vmin = Math.min(state.vh, state.vw); state.vmax = Math.max(state.vh, state.vw); }, mutate: state => { this.win.document.documentElement.setAttribute( 'style', `--story-page-vh: ${px(state.vh)};` + `--story-page-vw: ${px(state.vw)};` + `--story-page-vmin: ${px(state.vmin)};` + `--story-page-vmax: ${px(state.vmax)};` ); }, }, {} ); } /** * Builds the system layer DOM. * @param {string} initialPageId * @private */ buildSystemLayer_(initialPageId) { this.updateAudioIcon_(); this.element.appendChild(this.systemLayer_.build(initialPageId)); } /** @private */ initializeListeners_() { this.element.addEventListener(EventType.NEXT_PAGE, () => { this.next_(); }); this.element.addEventListener(EventType.PREVIOUS_PAGE, () => { this.previous_(); }); this.storeService_.subscribe( StateProperty.MUTED_STATE, isMuted => { this.onMutedStateUpdate_(isMuted); this.variableService_.onVariableUpdate( AnalyticsVariable.STORY_IS_MUTED, isMuted ); }, true /** callToInitialize */ ); this.storeService_.subscribe( StateProperty.MUTED_STATE, isMuted => { // We do not want to trigger an analytics event for the initialization of // the muted state. this.analyticsService_.triggerEvent( isMuted ? StoryAnalyticsEvent.STORY_MUTED : StoryAnalyticsEvent.STORY_UNMUTED ); }, false /** callToInitialize */ ); this.storeService_.subscribe( StateProperty.SUPPORTED_BROWSER_STATE, isBrowserSupported => { this.onSupportedBrowserStateUpdate_(isBrowserSupported); } ); this.storeService_.subscribe(StateProperty.ADVANCEMENT_MODE, mode => { this.variableService_.onVariableUpdate( AnalyticsVariable.STORY_ADVANCEMENT_MODE, mode ); }); this.element.addEventListener(EventType.SWITCH_PAGE, e => { if (this.storeService_.get(StateProperty.BOOKEND_STATE)) { // Disallow switching pages while the bookend is active. return; } this.switchTo_(getDetail(e)['targetPageId'], getDetail(e)['direction']); this.ampStoryHint_.hideAllNavigationHint(); }); this.element.addEventListener(EventType.PAGE_PROGRESS, e => { const detail = getDetail(e); const pageId = detail['pageId']; const progress = detail['progress']; if (pageId !== this.activePage_.element.id) { // Ignore progress update events from inactive pages. return; } if (!this.activePage_.isAd()) { this.systemLayer_.updateProgress(pageId, progress); } }); this.element.addEventListener(EventType.REPLAY, () => { this.replay_(); }); this.element.addEventListener(EventType.NO_NEXT_PAGE, () => { this.onNoNextPage_(); }); this.element.addEventListener(EventType.NO_PREVIOUS_PAGE, () => { this.onNoPreviousPage_(); }); this.advancement_.addOnTapNavigationListener(direction => { this.performTapNavigation_(direction); }); this.element.addEventListener(EventType.DISPATCH_ACTION, e => { if (!getMode().test) { return; } const action = getDetail(e)['action']; const data = getDetail(e)['data']; this.storeService_.dispatch(action, data); }); // Actions whitelist could be initialized empty, or with some actions some // other components registered. this.storeService_.subscribe( StateProperty.ACTIONS_WHITELIST, actionsWhitelist => { const actions = Services.actionServiceForDoc(this.element); actions.setWhitelist(actionsWhitelist); }, true /** callToInitialize */ ); this.storeService_.subscribe(StateProperty.AD_STATE, isAd => { this.onAdStateUpdate_(isAd); }); this.storeService_.subscribe(StateProperty.BOOKEND_STATE, isActive => { this.onBookendStateUpdate_(isActive); }); this.storeService_.subscribe(StateProperty.CURRENT_PAGE_ID, pageId => { this.onCurrentPageIdUpdate_(pageId); }); this.storeService_.subscribe(StateProperty.PAUSED_STATE, isPaused => { this.onPausedStateUpdate_(isPaused); }); this.storeService_.subscribe(StateProperty.SIDEBAR_STATE, sidebarState => { this.onSidebarStateUpdate_(sidebarState); }); this.storeService_.subscribe( StateProperty.UI_STATE, uiState => { this.onUIStateUpdate_(uiState); }, true /** callToInitialize */ ); this.win.document.addEventListener( 'keydown', e => { this.onKeyDown_(e); }, true ); this.win.document.addEventListener('contextmenu', e => { const uiState = this.storeService_.get(StateProperty.UI_STATE); if (uiState === UIType.MOBILE) { e.preventDefault(); e.stopPropagation(); } }); this.getAmpDoc().onVisibilityChanged(() => this.onVisibilityChanged_()); this.win.addEventListener('hashchange', () => { const maybePageId = parseQueryString(this.win.location.hash)['page']; if (!maybePageId || !this.isActualPage_(maybePageId)) { return; } this.switchTo_(maybePageId, NavigationDirection.NEXT); // Removes the page 'hash' parameter from the URL. let href = this.win.location.href.replace( new RegExp(`page=${maybePageId}&?`), '' ); if (endsWith(href, '#')) { href = href.slice(0, -1); } this.win.history.replaceState( (this.win.history && getState(this.win.history)) || {} /** data */, this.win.document.title /** title */, href /** URL */ ); }); this.getViewport().onResize(debounce(this.win, () => this.onResize(), 300)); this.installGestureRecognizers_(); // TODO(gmajoulet): migrate this to amp-story-viewer-messaging-handler once // there is a way to navigate to pages that does not involve using private // amp-story methods. this.viewer_.onMessage('selectPage', data => this.onSelectPage_(data)); if (this.viewerMessagingHandler_) { this.viewerMessagingHandler_.startListening(); } } /** @private */ installGestureRecognizers_() { // If the story is within a viewer that enabled the swipe capability, this // disables the navigation education overlay to enable: // - horizontal swipe events to the next story // - vertical swipe events to close the viewer, or open a page attachment if (this.viewer_.hasCapability('swipe')) { return; } const {element} = this; const gestures = Gestures.get(element, /* shouldNotPreventDefault */ true); // Shows "tap to navigate" hint when swiping. gestures.onGesture(SwipeXYRecognizer, gesture => { const {deltaX, deltaY} = gesture.data; const embedComponent = /** @type {InteractiveComponentDef} */ (this.storeService_.get( StateProperty.INTERACTIVE_COMPONENT_STATE )); // TODO(enriqe): Move to a separate file if this keeps growing. if ( this.storeService_.get(StateProperty.BOOKEND_STATE) || embedComponent.state !== EmbeddedComponentState.HIDDEN || this.storeService_.get(StateProperty.ACCESS_STATE) || this.storeService_.get(StateProperty.SIDEBAR_STATE) || !this.storeService_.get(StateProperty.SYSTEM_UI_IS_VISIBLE_STATE) || !this.storeService_.get(StateProperty.CAN_SHOW_NAVIGATION_OVERLAY_HINT) ) { // Cancels the event for this gesture entirely, ensuring the hint won't // show even if the user keeps swiping without releasing the touch. if (gesture.event && gesture.event.cancelable !== false) { gesture.event.preventDefault(); } return; } if ( (gesture.event && gesture.event.defaultPrevented) || !this.isSwipeLargeEnoughForHint_(deltaX, deltaY) ) { return; } this.ampStoryHint_.showNavigationOverlay(); }); } /** * @param {number} deltaX * @param {number} deltaY * @return {boolean} * @private */ isSwipeLargeEnoughForHint_(deltaX, deltaY) { const sideSwipe = Math.abs(deltaX) >= MIN_SWIPE_FOR_HINT_OVERLAY_PX; const upSwipe = -1 * deltaY >= MIN_SWIPE_FOR_HINT_OVERLAY_PX; return sideSwipe || upSwipe; } /** @private */ initializeListenersForDev_() { if (!getMode().development) { return; } this.element.addEventListener(EventType.DEV_LOG_ENTRIES_AVAILABLE, e => { this.systemLayer_.logAll(/** @type {?} */ (getDetail(e))); }); } /** @private */ lockBody_() { const {document} = this.win; setImportantStyles(document.documentElement, { 'overflow': 'hidden', }); setImportantStyles(document.body, { 'overflow': 'hidden', }); this.getViewport().resetTouchZoom(); this.getViewport().disableTouchZoom(); this.maybeLockScreenOrientation_(); } /** @private */ maybeLockScreenOrientation_() { const {screen} = this.win; if (!screen || !this.canRotateToDesktopMedia_.matches) { return; } const lockOrientation = screen.lockOrientation || screen.mozLockOrientation || screen.msLockOrientation || (unusedOrientation => {}); try { lockOrientation('portrait'); } catch (e) { dev().warn(TAG, 'Failed to lock screen orientation:', e.message); } } /** @private */ buildPaginationButtons_() { if (this.paginationButtons_) { return; } // TODO(#19768): Avoid passing a private function here. this.paginationButtons_ = PaginationButtons.create(this, () => this.hasBookend_() ); this.paginationButtons_.attach(this.element); } /** @visibleForTesting */ buildPaginationButtonsForTesting() { this.buildPaginationButtons_(); } /** @override */ layoutCallback() { if (!AmpStory.isBrowserSupported(this.win) && !this.platform_.isBot()) { this.storeService_.dispatch(Action.TOGGLE_SUPPORTED_BROWSER, false); return Promise.resolve(); } return this.layoutStory_(); } /** * Renders the layout for the story * @return {!Promise} A promise that is resolved when the story layout is * loaded * @private */ layoutStory_() { const firstPageEl = user().assertElement( this.element.querySelector('amp-story-page'), 'Story must have at least one page.' ); const initialPageId = this.getInitialPageId_(firstPageEl); this.buildSystemLayer_(initialPageId); this.initializeSidebar_(); this.setThemeColor_(); const storyLayoutPromise = Promise.all([ this.getAmpDoc().whenFirstVisible(), // Pauses execution during prerender. this.initializePages_(), ]) .then(() => { this.handleConsentExtension_(); this.initializeStoryAccess_(); this.pages_.forEach((page, index) => { page.setState(PageState.NOT_ACTIVE); this.upgradeCtaAnchorTagsForTracking_(page, index); }); this.initializeStoryNavigationPath_(); }) .then(() => this.initializeBookend_()) .then(() => { const bookendInHistory = !!getHistoryState( this.win, HistoryState.BOOKEND_ACTIVE ); if (bookendInHistory) { return this.hasBookend_().then(hasBookend => { if (hasBookend) { return this.showBookend_(); } }); } }) .then(() => this.switchTo_(initialPageId, NavigationDirection.NEXT)) .then(() => this.updateViewportSizeStyles_()) .then(() => { const shouldReOpenAttachmentForPageId = getHistoryState( this.win, HistoryState.ATTACHMENT_PAGE_ID ); if (shouldReOpenAttachmentForPageId === this.activePage_.element.id) { this.activePage_.openAttachment(false /** shouldAnimate */); } // Preloads and prerenders the share menu. this.shareMenu_.build(); const infoDialog = shouldShowStoryUrlInfo(this.viewer_) ? new InfoDialog(this.win, this.element) : null; if (infoDialog) { infoDialog.build(); } }); // Do not block the layout callback on the completion of these promises, as // that prevents descendents from being laid out (and therefore loaded). storyLayoutPromise .then(() => this.whenPagesLoaded_(PAGE_LOAD_TIMEOUT_MS)) .then(() => { this.markStoryAsLoaded_(); this.initializeLiveStory_(); }); // Story is being prerendered: resolve the layoutCallback when the first // page is built. Other pages will only build if the document becomes // visible. if (!this.getAmpDoc().hasBeenVisible()) { return whenUpgradedToCustomElement(firstPageEl).then(() => { return Promise.all([ firstPageEl.whenBuilt(), this.updateViewportSizeStyles_(), ]); }); } // Will resolve when all pages are built. return storyLayoutPromise; } /** * Initialize LiveStoryManager if this is a live story. * @private */ initializeLiveStory_() { if (this.element.hasAttribute('live-story')) { this.liveStoryManager_ = new LiveStoryManager(this); this.liveStoryManager_.build(); this.storeService_.dispatch(Action.ADD_TO_ACTIONS_WHITELIST, [ {tagOrTarget: 'AMP-LIVE-LIST', method: 'update'}, ]); this.element.addEventListener(AmpEvents.DOM_UPDATE, () => { this.liveStoryManager_.update(); this.initializePages_().then(() => { this.preloadPagesByDistance_(); if ( this.storeService_.get(StateProperty.UI_STATE) === UIType.DESKTOP_PANELS ) { this.setDesktopPositionAttributes_(this.activePage_); } }); }); } } /** * Retrieves the initial pageId to begin the story with. In order, the * initial page for a story should be either a valid page ID in the URL * fragment, the page ID in the history, or the first page of the story. * @param {!Element} firstPageEl * @return {string} * @private */ getInitialPageId_(firstPageEl) { const historyPage = /** @type {string} */ (getHistoryState( this.win, HistoryState.PAGE_ID )); const maybePageId = parseQueryString(this.win.location.hash)['page']; if (maybePageId && this.isActualPage_(maybePageId)) { return maybePageId; } if (historyPage && this.isActualPage_(historyPage)) { return historyPage; } return firstPageEl.id; } /** * Checks if the amp-story-page for a given ID exists. * Note: the `this.pages_` array might not be defined yet. * @param {string} pageId * @return {boolean} * @private */ isActualPage_(pageId) { // TODO(gmajoulet): check from the cached pages array if available, and use // the querySelector as a fallback. return !!this.element.querySelector(`#${escapeCssSelectorIdent(pageId)}`); } /** * @param {number} timeoutMs The maximum amount of time to wait, in * milliseconds. * @return {!Promise} A promise that is resolved when the page is loaded or * the timeout has been exceeded, whichever happens first. * @private */ whenPagesLoaded_(timeoutMs = 0) { const pagesToWaitFor = this.storeService_.get(StateProperty.UI_STATE) === UIType.DESKTOP_PANELS ? [this.pages_[0], this.pages_[1]] : [this.pages_[0]]; const storyLoadPromise = Promise.all( pagesToWaitFor .filter(page => !!page) .map(page => page.element.signals().whenSignal(CommonSignals.LOAD_END)) ); return this.timer_ .timeoutPromise(timeoutMs, storyLoadPromise) .catch(() => {}); } /** @private */ markStoryAsLoaded_() { dispatch( this.win, this.element, EventType.STORY_LOADED, /* payload */ undefined, {bubbles: true} ); this.signals().signal(CommonSignals.INI_LOAD); this.mutateElement(() => { this.element.classList.add(STORY_LOADED_CLASS_NAME); }); } /** * Handles the story consent extension. * @private */ handleConsentExtension_() { const consentEl = this.element.querySelector('amp-consent'); if (!consentEl) { return; } this.pauseStoryUntilConsentIsResolved_(); this.validateConsent_(consentEl); } /** * Pauses the story until the consent is resolved (accepted or rejected). * @private */ pauseStoryUntilConsentIsResolved_() { const policyId = this.getConsentPolicy() || 'default'; const consentPromise = getConsentPolicyState(this.element, policyId); if (!consentPromise) { return; } this.storeService_.dispatch(Action.TOGGLE_PAUSED, true); consentPromise.then(() => { this.storeService_.dispatch(Action.TOGGLE_PAUSED, false); }); } /** * Ensures publishers using amp-consent use amp-story-consent. * @param {!Element} consentEl * @private */ validateConsent_(consentEl) { if (!childElementByTag(consentEl, 'amp-story-consent')) { dev().error(TAG, 'amp-consent must have an amp-story-consent child'); } const allowedTags = ['SCRIPT', 'AMP-STORY-CONSENT']; const toRemoveChildren = childElements( consentEl, el => allowedTags.indexOf(el.tagName) === -1 ); if (toRemoveChildren.length === 0) { return; } dev().error(TAG, 'amp-consent only allows tags: %s', allowedTags); toRemoveChildren.forEach(el => consentEl.removeChild(el)); } /** * @private */ initializeStoryAccess_() { Services.accessServiceForDocOrNull(this.element).then(accessService => { if (!accessService) { return; } this.areAccessAuthorizationsCompleted_ = accessService.areFirstAuthorizationsCompleted(); accessService.onApplyAuthorizations(() => this.onAccessApplyAuthorizations_() ); const firstPage = this.pages_[0].element; // First amp-story-page can't be paywall protected. // Removes the access attributes, and throws an error during development. if ( firstPage.hasAttribute('amp-access') || firstPage.hasAttribute('amp-access-hide') ) { firstPage.removeAttribute('amp-access'); firstPage.removeAttribute('amp-access-hide'); user().error( TAG, 'First amp-story-page cannot have amp-access ' + 'or amp-access-hide attributes' ); } }); } /** * On amp-access document reauthorization, maybe hide the access UI, and maybe * perform navigation. * @private */ onAccessApplyAuthorizations_() { this.areAccessAuthorizationsCompleted_ = true; const nextPage = this.navigateToPageAfterAccess_; // Step out if the next page is still hidden by the access extension. if (nextPage && nextPage.element.hasAttribute('amp-access-hide')) { return; } if (nextPage) { this.navigateToPageAfterAccess_ = null; this.switchTo_(nextPage.element.id, NavigationDirection.NEXT); } this.storeService_.dispatch(Action.TOGGLE_ACCESS, false); } /** @override */ isLayoutSupported(layout) { return layout == Layout.CONTAINER; } /** @override */ prerenderAllowed() { return true; } /** @private */ initializePages_() { const pageImplPromises = Array.prototype.map.call( this.element.querySelectorAll('amp-story-page'), pageEl => pageEl.getImpl() ); return Promise.all(pageImplPromises).then(pages => { this.pages_ = pages; if (isExperimentOn(this.win, 'amp-story-branching')) { this.storeService_.dispatch(Action.ADD_TO_ACTIONS_WHITELIST, [ {tagOrTarget: 'AMP-STORY', method: 'goToPage'}, ]); } }); } /** * Advance to the next screen in the story, if there is one. * @param {boolean=} opt_isAutomaticAdvance Whether this navigation was caused * by an automatic advancement after a timeout. * @private */ next_(opt_isAutomaticAdvance) { const activePage = devAssert( this.activePage_, 'No active page set when navigating to next page.' ); activePage.next(opt_isAutomaticAdvance); } /** * Handles EventType.NO_NEXT_PAGE events. * @private */ onNoNextPage_() { if (this.viewer_.hasCapability('swipe') && this.viewerMessagingHandler_) { this.viewerMessagingHandler_.send('selectDocument', dict({'next': true})); return; } this.hasBookend_().then(hasBookend => { if (hasBookend) { this.showBookend_(); } }); } /** * Go back to the previous screen in the story, if there is one. * @private */ previous_() { const activePage = devAssert( this.activePage_, 'No active page set when navigating to previous page.' ); activePage.previous(); } /** * Handles EventType.NO_PREVIOUS_PAGE events. * @private */ onNoPreviousPage_() { if (this.viewer_.hasCapability('swipe') && this.viewerMessagingHandler_) { this.viewerMessagingHandler_.send( 'selectDocument', dict({'previous': true}) ); return; } if (this.storeService_.get(StateProperty.CAN_SHOW_PREVIOUS_PAGE_HELP)) { this.ampStoryHint_.showFirstPageHintOverlay(); } } /** * @param {number} direction The direction to navigate. * @private */ performTapNavigation_(direction) { if ( this.storeService_.get(StateProperty.UI_STATE) === UIType.DESKTOP_PANELS ) { this.next_(); return; } this.storeService_.dispatch( Action.SET_ADVANCEMENT_MODE, AdvancementMode.MANUAL_ADVANCE ); if (direction === TapNavigationDirection.NEXT) { this.next_(); } else if (direction === TapNavigationDirection.PREVIOUS) { this.previous_(); } } /** * Switches to a particular page. * @param {string} targetPageId * @param {!NavigationDirection} direction * @return {!Promise} * @private */ switchTo_(targetPageId, direction) { const targetPage = this.getPageById(targetPageId); const pageIndex = this.getPageIndex(targetPage); // Step out if trying to navigate to the currently active page. if (this.activePage_ && this.activePage_.element.id === targetPageId) { return Promise.resolve(); } // If the next page might be paywall protected, and the access // authorizations did not resolve yet, wait before navigating. // TODO(gmajoulet): implement a loading state. if ( targetPage.element.hasAttribute('amp-access') && !this.areAccessAuthorizationsCompleted_ ) { this.navigateToPageAfterAccess_ = targetPage; return Promise.resolve(); } // If the next page is paywall protected, display the access UI and wait for // the document to be reauthorized. if (targetPage.element.hasAttribute('amp-access-hide')) { this.storeService_.dispatch(Action.TOGGLE_ACCESS, true); this.navigateToPageAfterAccess_ = targetPage; return Promise.resolve(); } const oldPage = this.activePage_; this.activePage_ = targetPage; if (!targetPage.isAd()) { this.updateNavigationPath_(targetPageId, direction); } // Each step will run in a requestAnimationFrame, and wait for the next // frame before executing the following step. const steps = [ // First step contains the minimum amount of code to display and play the // target page as fast as possible. () => { oldPage && oldPage.element.removeAttribute('active'); if ( this.storeService_.get(StateProperty.UI_STATE) === UIType.DESKTOP_PANELS ) { this.setDesktopPositionAttributes_(targetPage); } // Starts playing the page, if the story is not paused. // Note: navigation is prevented when the story is paused, this test // covers the case where the story is rendered paused (eg: consent). if (!this.storeService_.get(StateProperty.PAUSED_STATE)) { targetPage.setState(PageState.PLAYING); } else { // Even if the page won't be playing, setting the active attribute // ensures it gets visible. targetPage.element.setAttribute('active', ''); } this.forceRepaintForSafari_(); }, // Second step does all the operations that impact the UI/UX: media sound, // progress bar, ... () => { if (oldPage) { oldPage.setState(PageState.NOT_ACTIVE); // Indication to know where to display the page on the desktop // ribbon-like animation. this.getPageIndex(oldPage) < pageIndex ? setAttributeInMutate(oldPage, Attributes.VISITED) : removeAttributeInMutate(oldPage, Attributes.VISITED); if (oldPage.isAd()) { this.storeService_.dispatch( Action.SET_ADVANCEMENT_MODE, AdvancementMode.ADVANCE_TO_ADS ); } } let storePageIndex = pageIndex; if (targetPage.isAd()) { this.storeService_.dispatch(Action.TOGGLE_AD, true); setAttributeInMutate(this, Attributes.AD_SHOWING); // Keep current page index when an ad is shown. Otherwise it messes // up with the progress variable in the VariableService. storePageIndex = this.storeService_.get( StateProperty.CURRENT_PAGE_INDEX ); } else { this.storeService_.dispatch(Action.TOGGLE_AD, false); removeAttributeInMutate(this, Attributes.AD_SHOWING); // Start progress bar update for pages that are not ads or auto- // advance. if (!targetPage.isAutoAdvance()) { this.systemLayer_.updateProgress( targetPageId, this.advancement_.getProgress() ); } } this.storeService_.dispatch(Action.CHANGE_PAGE, { id: targetPageId, index: storePageIndex, }); // If first navigation. if (!oldPage) { this.registerAndPreloadBackgroundAudio_(); } if (!this.storeService_.get(StateProperty.MUTED_STATE)) { oldPage && oldPage.muteAllMedia(); this.activePage_.unmuteAllMedia(); } }, // Third and last step contains all the actions that can be delayed after // the navigation happened, like preloading the following pages, or // sending analytics events. () => { this.preloadPagesByDistance_(); this.maybePreloadBookend_(); this.triggerActiveEventForPage_(); this.systemLayer_.resetDeveloperLogs(); this.systemLayer_.setDeveloperLogContextString( this.activePage_.element.id ); }, ]; return new Promise(resolve => { targetPage.beforeVisible().then(() => { // Recursively executes one step per frame. const unqueueStepInRAF = () => { steps.shift().call(this); if (!steps.length) { return resolve(); } this.win.requestAnimationFrame(() => unqueueStepInRAF()); }; unqueueStepInRAF(); }); }); } /** * Updates the story navigation stack and checks for navigation adherence to * the path a user takes. * @param {string} targetPageId * @param {!NavigationDirection} direction * @private */ updateNavigationPath_(targetPageId, direction) { const navigationPath = /** @type {!Array<string>} */ (this.storeService_.get( StateProperty.NAVIGATION_PATH )); if (direction === NavigationDirection.PREVIOUS) { navigationPath.pop(); } // Ensures the pageId is not at the top of the stack already, which can // happen on initial page load (e.g. reloading a page). if ( direction === NavigationDirection.NEXT && navigationPath[navigationPath.length - 1] !== targetPageId ) { navigationPath.push(targetPageId); } this.storeService_.dispatch(Action.SET_NAVIGATION_PATH, navigationPath); setHistoryState(this.win, HistoryState.NAVIGATION_PATH, navigationPath); } /** * Clear existing preview attributes, Check to see if there is a next or * previous page, set new attributes. * @param {?./amp-story-page.AmpStoryPage} targetPage * @private */ setDesktopPositionAttributes_(targetPage) { if (!targetPage) { return; } const list = [{page: targetPage, position: 0}]; const minusOneId = targetPage.getPreviousPageId(); if (minusOneId) { const minusOnePage = this.getPageById(minusOneId); list.push({page: minusOnePage, position: -1}); const minusTwoId = minusOnePage.getPreviousPageId(); if (minusTwoId) { list.push({page: this.getPageById(minusTwoId), position: -2}); } } const plusOneId = targetPage.getNextPageId(); if (plusOneId) { const plusOnePage = this.getPageById(plusOneId); list.push({page: plusOnePage, position: 1}); const plusTwoId = plusOnePage.getNextPageId(); if (plusTwoId) { list.push({page: this.getPageById(plusTwoId), position: 2}); } } let desktopPositionsToReset; this.measureMutateElement( /** measurer */ () => { desktopPositionsToReset = scopedQuerySelectorAll( this.element, `amp-story-page[ ${escapeCssSelectorIdent(Attributes.DESKTOP_POSITION)}]` ); }, /** mutator */ () => { Array.prototype.forEach.call(desktopPositionsToReset, el => { el.removeAttribute(Attributes.DESKTOP_POSITION); }); list.forEach(entry => { const {page, position} = entry; page.element.setAttribute(Attributes.DESKTOP_POSITION, position); }); } ); } /** @private */ triggerActiveEventForPage_() { // TODO(alanorozco): pass event priority once amphtml-story repo is merged // with upstream. Services.actionServiceForDoc(this.element).trigger( this.activePage_.element, 'active', /* event */ null, ActionTrust.HIGH ); } /** * For some reason, Safari has an issue where sometimes when pages become * visible, some descendants are not painted. This is a hack where we detect * that the browser is Safari and force it to repaint, to avoid this case. * See newmuis/amphtml-story#106 for details. * @private */ forceRepaintForSafari_() { if (!this.platform_.isSafari() && !this.platform_.isIos()) { return; } if ( this.storeService_.get(StateProperty.UI_STATE) === UIType.DESKTOP_PANELS ) { // Force repaint is only needed when transitioning from invisible to // visible return; } this.mutateElement(() => { toggle(this.element, false); // Reading the height is what forces the repaint. The conditional exists // only to workaround the fact that the closure compiler would otherwise // think that only reading the height has no effect. Since the height is // always >= 0, this conditional will always be executed. const height = this.element./*OK*/ offsetHeight; if (height >= 0) { toggle(this.element, true); } }); } /** * Handles all key presses within the story. * @param {!Event} e The keydown event. * @private */ onKeyDown_(e) { if (this.storeService_.get(StateProperty.BOOKEND_STATE)) { return; } this.storeService_.dispatch( Action.SET_ADVANCEMENT_MODE, AdvancementMode.MANUAL_ADVANCE ); const rtlState = this.storeService_.get(StateProperty.RTL_STATE); switch (e.key) { case Keys.LEFT_ARROW: rtlState ? this.next_() : this.previous_(); break; case Keys.RIGHT_ARROW: rtlState ? this.previous_() : this.next_(); break; } } /** * @param {string} pageId new current page id * @private * */ onCurrentPageIdUpdate_(pageId) { // Never save ad pages to history as they are unique to each visit. const page = this.getPageById(pageId); if (page.isAd()) { return; } setHistoryState(this.win, HistoryState.PAGE_ID, pageId); } /** * Handle resize events and set the story's desktop state. * @visibleForTesting */ onResize() { this.updateViewportSizeStyles_(); const uiState = this.getUIType_(); this.storeService_.dispatch(Action.TOGGLE_UI, uiState); const isLandscape = this.isLandscape_(); const isLandscapeSupported = this.isLandscapeSupported_(); this.setOrientationAttribute_(isLandscape, isLandscapeSupported); if (uiState !== UIType.MOBILE || isLandscapeSupported) { // Hides the UI that prevents users from using the LANDSCAPE orientation. this.storeService_.dispatch(Action.TOGGLE_VIEWPORT_WARNING, false); return; } // Only called when the desktop media query is not matched and the landscape // mode is not enabled. this.maybeTriggerViewportWarning_(isLandscape); } /** * Adds an orientation=landscape|portrait attribute. * If the story doesn't explicitly support landscape via the opt-in attribute, * it is always in a portrait orientation. * @param {boolean} isLandscape Whether the viewport is landscape or portrait * @param {boolean} isLandscapeSupported Whether the story supports landscape * @private */ setOrientationAttribute_(isLandscape, isLandscapeSupported) { // TODO(#20832) base this check on the size of the amp-story-page, once it // is stored as a store state. this.mutateElement(() => { this.element.setAttribute( Attributes.ORIENTATION, isLandscapeSupported && isLandscape ? 'landscape' : 'portrait' ); }); } /** * Maybe triggers the viewport warning overlay. * @param {boolean} isLandscape * @private */ maybeTriggerViewportWarning_(isLandscape) { if ( isLandscape === this.storeService_.get(StateProperty.VIEWPORT_WARNING_STATE) ) { return; } this.mutateElement(() => { if (isLandscape) { this.pausedStateToRestore_ = !!this.storeService_.get( StateProperty.PAUSED_STATE ); this.storeService_.dispatch(Action.TOGGLE_PAUSED, true); this.storeService_.dispatch(Action.TOGGLE_VIEWPORT_WARNING, true); } else { this.storeService_.dispatch( Action.TOGGLE_PAUSED, this.pausedStateToRestore_ ); this.storeService_.dispatch(Action.TOGGLE_VIEWPORT_WARNING, false); } }); } /** * Reacts to the browser tab becoming active/inactive. * @private */ onVisibilityChanged_() { this.getAmpDoc().isVisible() ? this.resume_() : this.pause_(); } /** * Reacts to the ad state updates, and pauses the background-audio when an ad * is displayed. * @param {boolean} isAd * @private */ onAdStateUpdate_(isAd) { if (this.storeService_.get(StateProperty.MUTED_STATE)) { return; } isAd ? this.pauseBackgroundAudio_() : this.playBackgroundAudio_(); } /** * Reacts to UI state updates. * @param {!UIType} uiState * @private */ onUIStateUpdate_(uiState) { switch (uiState) { case UIType.MOBILE: this.vsync_.mutate(() => { this.element.removeAttribute('desktop'); this.element.classList.remove('i-amphtml-story-desktop-panels'); this.element.classList.remove('i-amphtml-story-desktop-fullbleed'); }); break; case UIType.DESKTOP_PANELS: this.setDesktopPositionAttributes_(this.activePage_); this.buildPaginationButtons_(); this.vsync_.mutate(() => { this.element.setAttribute('desktop', ''); this.element.classList.add('i-amphtml-story-desktop-panels'); this.element.classList.remove('i-amphtml-story-desktop-fullbleed'); }); break; case UIType.DESKTOP_FULLBLEED: this.buildPaginationButtons_(); this.vsync_.mutate(() => { this.element.setAttribute('desktop', ''); this.element.classList.add('i-amphtml-story-desktop-fullbleed'); this.element.classList.remove('i-amphtml-story-desktop-panels'); }); break; // Because of the DOM mutations, switching from this mode to another is // not allowed, and prevented within the store service. case UIType.VERTICAL: const pageAttachments = scopedQuerySelectorAll( this.element, 'amp-story-page amp-story-page-attachment' ); this.initializeBookend_().then(() => this.showBookend_()); this.vsync_.mutate(() => { this.element.setAttribute('i-amphtml-vertical', ''); setImportantStyles(this.win.document.body, {height: 'auto'}); this.element.removeAttribute('desktop'); this.element.classList.remove('i-amphtml-story-desktop-fullbleed'); this.element.classList.remove('i-amphtml-story-desktop-panels'); for (let i = 0; i < pageAttachments.length; i++) { this.element.appendChild(pageAttachments[i]); } }); this.signals() .whenSignal(CommonSignals.LOAD_END) .then(() => { this.vsync_.mutate(() => { this.pages_.forEach(page => page.element.setAttribute('active', '') ); }); }); break; } } /** * Retrieves the UI type that should be used to view the story. * @return {!UIType} * @private */ getUIType_() { if (this.platform_.isBot()) { return UIType.VERTICAL; } if (!this.isDesktop_()) { return UIType.MOBILE; } if (this.isLandscapeSupported_()) { return UIType.DESKTOP_FULLBLEED; } // Three panels desktop UI (default). return UIType.DESKTOP_PANELS; } /** * @return {boolean} True if the screen size matches the desktop media query. * @private */ isDesktop_() { return this.desktopMedia_.matches && !this.platform_.isBot(); } /** * @return {boolean} True if the screen orientation is landscape. * @private */ isLandscape_() { return this.landscapeOrientationMedia_.matches; } /** * @return {boolean} true if this is a standalone story (i.e. this story is * the only content of the document). * @private */ isStandalone_() { return this.element.hasAttribute(Attributes.STANDALONE); } /** * Whether the story should support landscape orientation: landscape mobile, * or full bleed desktop UI. * @return {boolean} * @private */ isLandscapeSupported_() { return this.element.hasAttribute(Attributes.SUPPORTS_LANDSCAPE); } /** * Reacts to paused state updates. * @param {boolean} isPaused * @private */ onPausedStateUpdate_(isPaused) { if (!this.activePage_) { return; } const pageState = isPaused ? PageState.PAUSED : PageState.PLAYING; isPaused ? this.advancement_.stop() : this.advancement_.start(); this.activePage_.setState(pageState); } /** * Reacts to sidebar state updates. * @param {boolean} sidebarState * @private */ onSidebarStateUpdate_(sidebarState) { this.analyticsService_.triggerEvent( sidebarState ? StoryAnalyticsEvent.OPEN : StoryAnalyticsEvent.CLOSE, this.sidebar_ ); const actions = Services.actionServiceForDoc(this.element); if (this.win.MutationObserver) { if (!this.sidebarObserver_) { this.sidebarObserver_ = new this.win.MutationObserver(() => { this.storeService_.dispatch( Action.TOGGLE_SIDEBAR, this.sidebar_.hasAttribute('open') ); }); } if (this.sidebar_ && sidebarState) { this.sidebarObserver_.observe(this.sidebar_, SIDEBAR_OBSERVER_OPTIONS); this.openOpacityMask_(); actions.execute( this.sidebar_, 'open', /* args */ null, /* source */ null, /* caller */ null, /* event */ null, ActionTrust.HIGH ); } else { this.closeOpacityMask_(); this.sidebarObserver_.disconnect(); } } else if (this.sidebar_ && sidebarState) { this.openOpacityMask_(); actions.execute( this.sidebar_, 'open', /* args */ null, /* source */ null, /* caller */ null, /* event */ null, ActionTrust.HIGH ); this.storeService_.dispatch(Action.TOGGLE_SIDEBAR, false); } } /** * @private */ initializeOpacityMask_() { if (!this.maskElement_) { const maskEl = this.win.document.createElement('div'); maskEl.classList.add(OPACITY_MASK_CLASS_NAME); maskEl.addEventListener('click', () => { const actions = Services.actionServiceForDoc(this.element); if (this.sidebar_) { this.closeOpacityMask_(); actions.execute( this.sidebar_, 'close', /* args */ null, /* source */ null, /* caller */ null, /* event */ null, ActionTrust.HIGH ); } }); this.maskElement_ = maskEl; this.mutateElement(() => { this.element.appendChild(this.maskElement_); toggle(dev().assertElement(this.maskElement_), /* display */ false); }); } } /** * @private */ openOpacityMask_() { this.mutateElement(() => { toggle(dev().assertElement(this.maskElement_), /* display */ true); }); } /** * @private */ closeOpacityMask_() { if (this.maskElement_) { this.mutateElement(() => { toggle(dev().assertElement(this.maskElement_), /* display */ false); }); } } /** * If browser is supported, displays the story. Otherwise, shows either the * default unsupported browser layer or the publisher fallback (if provided). * @param {boolean} isBrowserSupported * @private */ onSupportedBrowserStateUpdate_(isBrowserSupported) { const fallbackEl = this.getFallback(); if (isBrowserSupported) { // Removes the default unsupported browser layer or throws an error // if the publisher has provided their own fallback if (fallbackEl) { dev().error( TAG, 'No handler to exit unsupported browser state on ' + 'publisher provided fallback.' ); } else { this.layoutStory_().then(() => this.mutateElement(() => { this.unsupportedBrowserLayer_.removeLayer(); this.element.classList.remove('i-amphtml-story-fallback'); }) ); } } else { this.mutateElement(() => { this.element.classList.add('i-amphtml-story-fallback'); }); // Displays the publisher provided fallback or fallbacks to the default // unsupported browser layer. if (fallbackEl) { this.toggleFallback(true); } else { this.unsupportedBrowserLayer_.build(); this.mutateElement(() => { this.element.appendChild(this.unsupportedBrowserLayer_.get()); }); } } } /** * Shows the bookend overlay. * @private */ showBookend_() { this.buildAndPreloadBookend_().then(() => { this.storeService_.dispatch(Action.TOGGLE_BOOKEND, true); }); } /** * Hides the bookend overlay. * @private */ hideBookend_() { this.storeService_.dispatch(Action.TOGGLE_BOOKEND, false); } /** * @param {boolean} isActive * @private */ onBookendStateUpdate_(isActive) { this.toggleElementsOnBookend_(/* display */ isActive); this.element.classList.toggle('i-amphtml-story-bookend-active', isActive); } /** * Toggles content when bookend is opened/closed. * @param {boolean} isActive * @private */ toggleElementsOnBookend_(isActive) { if ( this.storeService_.get(StateProperty.UI_STATE) !== UIType.DESKTOP_PANELS ) { return; } const elements = scopedQuerySelectorAll( this.element, HIDE_ON_BOOKEND_SELECTOR ); Array.prototype.forEach.call(elements, el => { if (isActive) { setImportantStyles(el, { opacity: 0, transition: 'opacity 0.1s', }); } else { resetStyles(el, ['opacity', 'transition']); } }); } /** * @return {!Array<!Array<string>>} A 2D array representing lists of pages by * distance. The outer array index represents the distance from the * active page; the inner array is a list of page IDs at the specified * distance. */ getPagesByDistance_() { const distanceMap = this.getPageDistanceMapHelper_( /* distance */ 0, /* map */ {}, this.activePage_.element.id ); // Transpose the map into a 2D array. const pagesByDistance = []; Object.keys(distanceMap).forEach(pageId => { const distance = distanceMap[pageId]; if (!pagesByDistance[distance]) { pagesByDistance[distance] = []; } // There may be other 1 skip away pages due to branching. if (isExperimentOn(this.win, 'amp-story-branching')) { const navigationPath = this.storeService_.get( StateProperty.NAVIGATION_PATH ); const indexInStack = navigationPath.indexOf( this.activePage_.element.id ); const maybePrev = navigationPath[indexInStack - 1]; if (indexInStack > 0 && pageId === this.activePage_.element.id) { if (!pagesByDistance[1]) { pagesByDistance[1] = []; } pagesByDistance[1].push(maybePrev); } // Do not overwrite, branching distance always takes precedence. if (pageId !== maybePrev) { pagesByDistance[distance].push(pageId); } } else { pagesByDistance[distance].push(pageId); } }); return pagesByDistance; } /** * Creates a map of a page and all of the pages reachable from that page, by * distance. * * @param {number} distance The distance that the page with the specified * pageId is from the active page. * @param {!Object<string, number>} map A mapping from pageId to its distance * from the active page. * @param {string} pageId The page to be added to the map. * @return {!Object<string, number>} A mapping from page ID to the priority of * that page. * @private */ getPageDistanceMapHelper_(distance, map, pageId) { if (map[pageId] !== undefined && map[pageId] <= distance) { return map; } map[pageId] = distance; const page = this.getPageById(pageId); page.getAdjacentPageIds().forEach(adjacentPageId => { if ( map[adjacentPageId] !== undefined && map[adjacentPageId] <= distance ) { return; } // TODO(newmuis): Remove the assignment and return, as they're // unnecessary. map = this.getPageDistanceMapHelper_(distance + 1, map, adjacentPageId); }); return map; } /** @private */ preloadPagesByDistance_() { if (this.platform_.isBot()) { this.pages_.forEach(page => { page.setDistance(0); }); return; } const pagesByDistance = this.getPagesByDistance_(); this.mutateElement(() => { pagesByDistance.forEach((pageIds, distance) => { pageIds.forEach(pageId => { const page = this.getPageById(pageId); page.setDistance(distance); }); }); }); } /** * Handles a background-audio attribute set on an <amp-story> tag. * @private */ registerAndPreloadBackgroundAudio_() { let backgroundAudioEl = upgradeBackgroundAudio(this.element); if (!backgroundAudioEl) { return; } // Once the media pool is ready, registers and preloads the background // audio, and then gets the swapped element from the DOM to mute/unmute/play // it programmatically later. this.activePage_.element .signals() .whenSignal(CommonSignals.LOAD_END) .then(() => { backgroundAudioEl = /** @type {!HTMLMediaElement} */ (backgroundAudioEl); this.mediaPool_.register(backgroundAudioEl); return this.mediaPool_.preload(backgroundAudioEl); }) .then(() => { this.backgroundAudioEl_ = /** @type {!HTMLMediaElement} */ (childElement( this.element, el => { return el.tagName.toLowerCase() === 'audio'; } )); }); } /** * Initializes bookend. * @return {!Promise} * @private */ initializeBookend_() { let bookendEl = this.element.querySelector('amp-story-bookend'); if (!bookendEl) { bookendEl = createElementWithAttributes( this.win.document, 'amp-story-bookend', dict({'layout': 'nodisplay'}) ); this.element.appendChild(bookendEl); } return whenUpgradedToCustomElement(bookendEl).then(() => { return bookendEl.getImpl().then(bookendImpl => { this.bookend_ = bookendImpl; }); }); } /** * Preloads the bookend config if on the last page. * @private */ maybePreloadBookend_() { if ( !this.activePage_ || !this.storeService_.get(StateProperty.CAN_SHOW_BOOKEND) ) { return; } const pageIndex = this.getPageIndex(this.activePage_); if (pageIndex + 1 >= this.getPageCount()) { this.buildAndPreloadBookend_(); } } /** * Builds, fetches and sets the bookend publisher configuration. * @return {!Promise<?./bookend/bookend-component.BookendDataDef>} * @private */ buildAndPreloadBookend_() { this.bookend_.build(); return this.bookend_.loadConfigAndMaybeRenderBookend(); } /** * @return {!Promise<boolean>} * @private */ hasBookend_() { if (!this.storeService_.get(StateProperty.CAN_SHOW_BOOKEND)) { return Promise.resolve(false); } // TODO(newmuis): Change this comment. // On mobile there is always a bookend. On desktop, the bookend will only // be shown if related articles have been configured. if (this.storeService_.get(StateProperty.UI_STATE) === UIType.MOBILE) { return Promise.resolve(true); } return this.bookend_ .loadConfigAndMaybeRenderBookend(false /** renderBookend */) .then( config => !!(config && config.components && config.components.length > 0) ); } /** * @param {string} id The ID of the page whose index should be retrieved. * @return {number} The index of the page. */ getPageIndexById(id) { const pageIndex = findIndex(this.pages_, page => page.element.id === id); if (pageIndex < 0) { user().error( TAG, 'Story refers to page "%s", but no such page exists.', id ); } return pageIndex; } /** * @param {string} id The ID of the page to be retrieved. * @return {!./amp-story-page.AmpStoryPage} Retrieves the page with the * specified ID. */ getPageById(id) { const pageIndex = this.getPageIndexById(id); return devAssert( this.pages_[pageIndex], 'Page at index %s exists, but is missing from the array.', pageIndex ); } /** * @return {number} */ getPageCount() { return this.pages_.length - this.adPages_.length; } /** * @param {!./amp-story-page.AmpStoryPage} desiredPage * @return {number} The index of the page. */ getPageIndex(desiredPage) { return findIndex(this.pages_, page => page === desiredPage); } /** * Retrieves the page containing the element, or null. A background audio * set on the <amp-story> tag would not be contained in a page. * @param {!Element} element The element whose containing AmpStoryPage should * be retrieved * @return {?./amp-story-page.AmpStoryPage} The AmpStoryPage containing the * specified element, if any. */ getPageContainingElement_(element) { const pageIndex = findIndex(this.pages_, page => { const pageEl = closest(element, el => { return el === page.element; }); return !!pageEl; }); return this.pages_[pageIndex] || null; } /** @override */ getElementDistance(element) { const page = this.getPageContainingElement_(element); // An element not contained in a page is likely to be global to the story, // like a background audio. Setting the distance to -1 ensures it will not // get evicted from the media pool. if (!page) { return -1; } return page.getDistance(); } /** @override */ getMaxMediaElementCounts() { let audioMediaElementsCount = this.element.querySelectorAll( 'amp-audio, [background-audio]' ).length; const videoMediaElementsCount = this.element.querySelectorAll('amp-video') .length; // The root element (amp-story) might have a background-audio as well. if (this.element.hasAttribute('background-audio')) { audioMediaElementsCount++; } return { [MediaType.AUDIO]: Math.min( audioMediaElementsCount + MINIMUM_AD_MEDIA_ELEMENTS, MAX_MEDIA_ELEMENT_COUNTS[MediaType.AUDIO] ), [MediaType.VIDEO]: Math.min( videoMediaElementsCount + MINIMUM_AD_MEDIA_ELEMENTS, MAX_MEDIA_ELEMENT_COUNTS[MediaType.VIDEO] ), }; } /** @override */ getElement() { return this.element; } /** * Reacts to muted state updates. * @param {boolean} isMuted Whether the story just got muted. * @private */ onMutedStateUpdate_(isMuted) { isMuted ? this.mute_() : this.unmute_(); } /** * Mutes the audio for the story. * @private */ mute_() { this.pauseBackgroundAudio_(); if (this.activePage_) { this.activePage_.muteAllMedia(); } } /** * Pauses the background audio. * @private */ pauseBackgroundAudio_() { if (!this.backgroundAudioEl_) { return; } this.mediaPool_.pause(this.backgroundAudioEl_); } /** * Unmutes the audio for the story. * @private */ unmute_() { const unmuteAllMedia = () => { this.playBackgroundAudio_(); if (this.activePage_) { this.activePage_.unmuteAllMedia(); } }; this.mediaPool_.blessAll().then(unmuteAllMedia, unmuteAllMedia); } /** * Unmutes and plays the background audio. * @private */ playBackgroundAudio_() { if (!this.backgroundAudioEl_) { return; } this.mediaPool_.unmute(this.backgroundAudioEl_); this.mediaPool_.play(this.backgroundAudioEl_); } /** * Shows the audio icon if the story has any media elements containing audio, * or background audio at the story or page level. * @private */ updateAudioIcon_() { const containsMediaElementWithAudio = !!this.element.querySelector( 'amp-audio, amp-video:not([noaudio]), [background-audio]' ); const storyHasBackgroundAudio = this.element.hasAttribute( 'background-audio' ); this.storeService_.dispatch( Action.TOGGLE_STORY_HAS_AUDIO, containsMediaElementWithAudio || storyHasBackgroundAudio ); this.storeService_.dispatch( Action.TOGGLE_STORY_HAS_BACKGROUND_AUDIO, storyHasBackgroundAudio ); } /** * Handles the selectPage viewer event. * @param {!JsonObject} data * @private */ onSelectPage_(data) { if (!data) { return; } this.storeService_.dispatch( Action.SET_ADVANCEMENT_MODE, AdvancementMode.VIEWER_SELECT_PAGE ); if (data['next']) { this.next_(); } else if (data['previous']) { this.previous_(); } } /** * Checks for the presence of a sidebar. If a sidebar does exist, then an icon * permitting for the opening/closing of the sidebar is shown. * @private */ initializeSidebar_() { this.sidebar_ = this.element.querySelector('amp-sidebar'); if (!this.sidebar_) { return; } this.mutateElement(() => { this.sidebar_.classList.add(SIDEBAR_CLASS_NAME); }); this.initializeOpacityMask_(); this.storeService_.dispatch(Action.TOGGLE_HAS_SIDEBAR, !!this.sidebar_); const actions = [ {tagOrTarget: 'AMP-SIDEBAR', method: 'open'}, {tagOrTarget: 'AMP-SIDEBAR', method: 'close'}, {tagOrTarget: 'AMP-SIDEBAR', method: 'toggle'}, ]; this.storeService_.dispatch(Action.ADD_TO_ACTIONS_WHITELIST, actions); } /** * Checks for the the storyNavigationPath stack in the history. * @private */ initializeStoryNavigationPath_() { this.storeService_.dispatch( Action.SET_NAVIGATION_PATH, getHistoryState(this.win, HistoryState.NAVIGATION_PATH) || [] ); } /** @private */ replay_() { if (this.storeService_.get(StateProperty.BOOKEND_STATE)) { this.hideBookend_(); } this.storeService_.dispatch(Action.SET_NAVIGATION_PATH, []); const switchPromise = this.switchTo_( dev().assertElement(this.pages_[0].element).id, NavigationDirection.NEXT ); // Reset all pages so that they are offscreen to right instead of left in // desktop view. switchPromise.then(() => { this.pages_.forEach(page => removeAttributeInMutate(page, Attributes.VISITED) ); }); } /** * @param {!AmpStoryPage} page The page whose CTA anchor tags should be * upgraded. * @param {number} pageIndex The index of the page. * @private */ upgradeCtaAnchorTagsForTracking_(page, pageIndex) { this.mutateElement(() => { const pageId = page.element.id; const ctaAnchorEls = scopedQuerySelectorAll( page.element, 'amp-story-cta-layer a' ); Array.prototype.forEach.call(ctaAnchorEls, ctaAnchorEl => { ctaAnchorEl.setAttribute('data-vars-story-page-id', pageId); ctaAnchorEl.setAttribute('data-vars-story-page-index', pageIndex); }); }); } /** * Add page to back of pages_ array * @param {!./amp-story-page.AmpStoryPage} page */ addPage(page) { this.pages_.push(page); if (page.isAd()) { this.adPages_.push(page); } } /** * Insert a new page in navigation flow by changing the attr pointers * on amp-story-page elements * @param {string} pageBeforeId * @param {string} pageToBeInsertedId * @return {boolean} was page inserted */ insertPage(pageBeforeId, pageToBeInsertedId) { // TODO(ccordry): make sure this method moves to PageManager when // implemented const pageToBeInserted = this.getPageById(pageToBeInsertedId); const pageToBeInsertedEl = pageToBeInserted.element; if ( pageToBeInserted.isAd() && !this.storeService_.get(StateProperty.CAN_INSERT_AUTOMATIC_AD) ) { dev().expectedError(TAG, 'Inserting ads automatically is disallowed.'); return false; } const pageBefore = this.getPageById(pageBeforeId); const pageBeforeEl = pageBefore.element; const nextPage = this.getNextPage(pageBefore); if (!nextPage) { return false; } const advanceAttr = isExperimentOn(this.win, 'amp-story-branching') ? Attributes.PUBLIC_ADVANCE_TO : Attributes.ADVANCE_TO; pageBeforeEl.setAttribute(advanceAttr, pageToBeInsertedId); pageBeforeEl.setAttribute(Attributes.AUTO_ADVANCE_TO, pageToBeInsertedId); pageToBeInsertedEl.setAttribute(Attributes.RETURN_TO, pageBeforeId); const nextPageEl = nextPage.element; const nextPageId = nextPageEl.id; // For a live story, nextPage is the same as pageToBeInserted. But not for // ads since it's inserted between two pages. if (nextPageId !== pageToBeInsertedId) { pageToBeInsertedEl.setAttribute(advanceAttr, nextPageId); pageToBeInsertedEl.setAttribute(Attributes.AUTO_ADVANCE_TO, nextPageId); nextPageEl.setAttribute(Attributes.RETURN_TO, pageToBeInsertedId); } return true; } /** * Get next page object * @param {!./amp-story-page.AmpStoryPage} page * @return {?./amp-story-page.AmpStoryPage} */ getNextPage(page) { const nextPageId = page.getNextPageId(true /*opt_isAutomaticAdvance */); if (!nextPageId) { return null; } return this.getPageById(nextPageId); } /** * @param {!Window} win * @return {boolean} true if the user's browser supports the features needed * for amp-story. */ static isBrowserSupported(win) { return Boolean( win.CSS && win.CSS.supports && win.CSS.supports('display', 'grid') ); } } AMP.extension('amp-story', '1.0', AMP => { AMP.registerElement('amp-story', AmpStory, CSS); AMP.registerElement('amp-story-access', AmpStoryAccess); AMP.registerElement('amp-story-bookend', AmpStoryBookend); AMP.registerElement('amp-story-consent', AmpStoryConsent); AMP.registerElement('amp-story-cta-layer', AmpStoryCtaLayer); AMP.registerElement('amp-story-grid-layer', AmpStoryGridLayer); AMP.registerElement('amp-story-page', AmpStoryPage); AMP.registerElement('amp-story-page-attachment', AmpStoryPageAttachment); AMP.registerElement('amp-story-quiz', AmpStoryQuiz); AMP.registerServiceForDoc('amp-story-render', AmpStoryRenderService); });
apache-2.0
intuit/QuickBooks-V3-PHP-SDK
src/XSD2PHP/lib/ZF/1.10.7/Zend/Soap/Wsdl.php
22940
<?php /** * Zend Framework * * LICENSE * * This source file is subject to the new BSD license that is bundled * with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://framework.zend.com/license/new-bsd * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to license@zend.com so we can send you a copy immediately. * * @category Zend * @package Zend_Soap * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License * @version $Id: Wsdl.php 20096 2010-01-06 02:05:09Z bkarwin $ */ /** * @see Zend_Soap_Wsdl_Strategy_Interface */ require_once "Zend/Soap/Wsdl/Strategy/Interface.php"; /** * @see Zend_Soap_Wsdl_Strategy_Abstract */ require_once "Zend/Soap/Wsdl/Strategy/Abstract.php"; /** * Zend_Soap_Wsdl * * @category Zend * @package Zend_Soap */ class Zend_Soap_Wsdl { /** * @var object DomDocument Instance */ private $_dom; /** * @var object WSDL Root XML_Tree_Node */ private $_wsdl; /** * @var string URI where the WSDL will be available */ private $_uri; /** * @var DOMElement */ private $_schema = null; /** * Types defined on schema * * @var array */ private $_includedTypes = array(); /** * Strategy for detection of complex types */ protected $_strategy = null; /** * Constructor * * @param string $name Name of the Web Service being Described * @param string $uri URI where the WSDL will be available * @param boolean|string|Zend_Soap_Wsdl_Strategy_Interface $strategy */ public function __construct($name, $uri, $strategy = true) { if ($uri instanceof Zend_Uri_Http) { $uri = $uri->getUri(); } $this->_uri = $uri; /** * @todo change DomDocument object creation from cparsing to construxting using API * It also should authomatically escape $name and $uri values if necessary */ $wsdl = "<?xml version='1.0' ?> <definitions name='$name' targetNamespace='$uri' xmlns='http://schemas.xmlsoap.org/wsdl/' xmlns:tns='$uri' xmlns:soap='http://schemas.xmlsoap.org/wsdl/soap/' xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns:soap-enc='http://schemas.xmlsoap.org/soap/encoding/' xmlns:wsdl='http://schemas.xmlsoap.org/wsdl/'></definitions>"; $this->_dom = new DOMDocument(); if (!$this->_dom->loadXML($wsdl)) { require_once 'Zend/Server/Exception.php'; throw new Zend_Server_Exception('Unable to create DomDocument'); } else { $this->_wsdl = $this->_dom->documentElement; } $this->setComplexTypeStrategy($strategy); } /** * Set a new uri for this WSDL * * @param string|Zend_Uri_Http $uri * @return Zend_Server_Wsdl */ public function setUri($uri) { if ($uri instanceof Zend_Uri_Http) { $uri = $uri->getUri(); } $oldUri = $this->_uri; $this->_uri = $uri; if ($this->_dom !== null) { // @todo: This is the worst hack ever, but its needed due to design and non BC issues of WSDL generation $xml = $this->_dom->saveXML(); $xml = str_replace($oldUri, $uri, $xml); $this->_dom = new DOMDocument(); $this->_dom->loadXML($xml); } return $this; } /** * Set a strategy for complex type detection and handling * * @todo Boolean is for backwards compability with extractComplexType object var. Remove it in later versions. * @param boolean|string|Zend_Soap_Wsdl_Strategy_Interface $strategy * @return Zend_Soap_Wsdl */ public function setComplexTypeStrategy($strategy) { if ($strategy === true) { require_once "Zend/Soap/Wsdl/Strategy/DefaultComplexType.php"; $strategy = new Zend_Soap_Wsdl_Strategy_DefaultComplexType(); } elseif ($strategy === false) { require_once "Zend/Soap/Wsdl/Strategy/AnyType.php"; $strategy = new Zend_Soap_Wsdl_Strategy_AnyType(); } elseif (is_string($strategy)) { if (class_exists($strategy)) { $strategy = new $strategy(); } else { require_once "Zend/Soap/Wsdl/Exception.php"; throw new Zend_Soap_Wsdl_Exception( sprintf("Strategy with name '%s does not exist.", $strategy )); } } if (!($strategy instanceof Zend_Soap_Wsdl_Strategy_Interface)) { require_once "Zend/Soap/Wsdl/Exception.php"; throw new Zend_Soap_Wsdl_Exception("Set a strategy that is not of type 'Zend_Soap_Wsdl_Strategy_Interface'"); } $this->_strategy = $strategy; return $this; } /** * Get the current complex type strategy * * @return Zend_Soap_Wsdl_Strategy_Interface */ public function getComplexTypeStrategy() { return $this->_strategy; } /** * Add a {@link http://www.w3.org/TR/wsdl#_messages message} element to the WSDL * * @param string $name Name for the {@link http://www.w3.org/TR/wsdl#_messages message} * @param array $parts An array of {@link http://www.w3.org/TR/wsdl#_message parts} * The array is constructed like: 'name of part' => 'part xml schema data type' * or 'name of part' => array('type' => 'part xml schema type') * or 'name of part' => array('element' => 'part xml element name') * @return object The new message's XML_Tree_Node for use in {@link function addDocumentation} */ public function addMessage($name, $parts) { $message = $this->_dom->createElement('message'); $message->setAttribute('name', $name); if (sizeof($parts) > 0) { foreach ($parts as $name => $type) { $part = $this->_dom->createElement('part'); $part->setAttribute('name', $name); if (is_array($type)) { foreach ($type as $key => $value) { $part->setAttribute($key, $value); } } else { $part->setAttribute('type', $type); } $message->appendChild($part); } } $this->_wsdl->appendChild($message); return $message; } /** * Add a {@link http://www.w3.org/TR/wsdl#_porttypes portType} element to the WSDL * * @param string $name portType element's name * @return object The new portType's XML_Tree_Node for use in {@link function addPortOperation} and {@link function addDocumentation} */ public function addPortType($name) { $portType = $this->_dom->createElement('portType'); $portType->setAttribute('name', $name); $this->_wsdl->appendChild($portType); return $portType; } /** * Add an {@link http://www.w3.org/TR/wsdl#_request-response operation} element to a portType element * * @param object $portType a portType XML_Tree_Node, from {@link function addPortType} * @param string $name Operation name * @param string $input Input Message * @param string $output Output Message * @param string $fault Fault Message * @return object The new operation's XML_Tree_Node for use in {@link function addDocumentation} */ public function addPortOperation($portType, $name, $input = false, $output = false, $fault = false) { $operation = $this->_dom->createElement('operation'); $operation->setAttribute('name', $name); if (is_string($input) && (strlen(trim($input)) >= 1)) { $node = $this->_dom->createElement('input'); $node->setAttribute('message', $input); $operation->appendChild($node); } if (is_string($output) && (strlen(trim($output)) >= 1)) { $node= $this->_dom->createElement('output'); $node->setAttribute('message', $output); $operation->appendChild($node); } if (is_string($fault) && (strlen(trim($fault)) >= 1)) { $node = $this->_dom->createElement('fault'); $node->setAttribute('message', $fault); $operation->appendChild($node); } $portType->appendChild($operation); return $operation; } /** * Add a {@link http://www.w3.org/TR/wsdl#_bindings binding} element to WSDL * * @param string $name Name of the Binding * @param string $type name of the portType to bind * @return object The new binding's XML_Tree_Node for use with {@link function addBindingOperation} and {@link function addDocumentation} */ public function addBinding($name, $portType) { $binding = $this->_dom->createElement('binding'); $binding->setAttribute('name', $name); $binding->setAttribute('type', $portType); $this->_wsdl->appendChild($binding); return $binding; } /** * Add an operation to a binding element * * @param object $binding A binding XML_Tree_Node returned by {@link function addBinding} * @param array $input An array of attributes for the input element, allowed keys are: 'use', 'namespace', 'encodingStyle'. {@link http://www.w3.org/TR/wsdl#_soap:body More Information} * @param array $output An array of attributes for the output element, allowed keys are: 'use', 'namespace', 'encodingStyle'. {@link http://www.w3.org/TR/wsdl#_soap:body More Information} * @param array $fault An array of attributes for the fault element, allowed keys are: 'name', 'use', 'namespace', 'encodingStyle'. {@link http://www.w3.org/TR/wsdl#_soap:body More Information} * @return object The new Operation's XML_Tree_Node for use with {@link function addSoapOperation} and {@link function addDocumentation} */ public function addBindingOperation($binding, $name, $input = false, $output = false, $fault = false) { $operation = $this->_dom->createElement('operation'); $operation->setAttribute('name', $name); if (is_array($input)) { $node = $this->_dom->createElement('input'); $soap_node = $this->_dom->createElement('soap:body'); foreach ($input as $name => $value) { $soap_node->setAttribute($name, $value); } $node->appendChild($soap_node); $operation->appendChild($node); } if (is_array($output)) { $node = $this->_dom->createElement('output'); $soap_node = $this->_dom->createElement('soap:body'); foreach ($output as $name => $value) { $soap_node->setAttribute($name, $value); } $node->appendChild($soap_node); $operation->appendChild($node); } if (is_array($fault)) { $node = $this->_dom->createElement('fault'); if (isset($fault['name'])) { $node->setAttribute('name', $fault['name']); } $soap_node = $this->_dom->createElement('soap:body'); foreach ($output as $name => $value) { $soap_node->setAttribute($name, $value); } $node->appendChild($soap_node); $operation->appendChild($node); } $binding->appendChild($operation); return $operation; } /** * Add a {@link http://www.w3.org/TR/wsdl#_soap:binding SOAP binding} element to a Binding element * * @param object $binding A binding XML_Tree_Node returned by {@link function addBinding} * @param string $style binding style, possible values are "rpc" (the default) and "document" * @param string $transport Transport method (defaults to HTTP) * @return boolean */ public function addSoapBinding($binding, $style = 'document', $transport = 'http://schemas.xmlsoap.org/soap/http') { $soap_binding = $this->_dom->createElement('soap:binding'); $soap_binding->setAttribute('style', $style); $soap_binding->setAttribute('transport', $transport); $binding->appendChild($soap_binding); return $soap_binding; } /** * Add a {@link http://www.w3.org/TR/wsdl#_soap:operation SOAP operation} to an operation element * * @param object $operation An operation XML_Tree_Node returned by {@link function addBindingOperation} * @param string $soap_action SOAP Action * @return boolean */ public function addSoapOperation($binding, $soap_action) { if ($soap_action instanceof Zend_Uri_Http) { $soap_action = $soap_action->getUri(); } $soap_operation = $this->_dom->createElement('soap:operation'); $soap_operation->setAttribute('soapAction', $soap_action); $binding->insertBefore($soap_operation, $binding->firstChild); return $soap_operation; } /** * Add a {@link http://www.w3.org/TR/wsdl#_services service} element to the WSDL * * @param string $name Service Name * @param string $port_name Name of the port for the service * @param string $binding Binding for the port * @param string $location SOAP Address for the service * @return object The new service's XML_Tree_Node for use with {@link function addDocumentation} */ public function addService($name, $port_name, $binding, $location) { if ($location instanceof Zend_Uri_Http) { $location = $location->getUri(); } $service = $this->_dom->createElement('service'); $service->setAttribute('name', $name); $port = $this->_dom->createElement('port'); $port->setAttribute('name', $port_name); $port->setAttribute('binding', $binding); $soap_address = $this->_dom->createElement('soap:address'); $soap_address->setAttribute('location', $location); $port->appendChild($soap_address); $service->appendChild($port); $this->_wsdl->appendChild($service); return $service; } /** * Add a documentation element to any element in the WSDL. * * Note that the WSDL {@link http://www.w3.org/TR/wsdl#_documentation specification} uses 'document', * but the WSDL {@link http://schemas.xmlsoap.org/wsdl/ schema} uses 'documentation' instead. * The {@link http://www.ws-i.org/Profiles/BasicProfile-1.1-2004-08-24.html#WSDL_documentation_Element WS-I Basic Profile 1.1} recommends using 'documentation'. * * @param object $input_node An XML_Tree_Node returned by another method to add the documentation to * @param string $documentation Human readable documentation for the node * @return DOMElement The documentation element */ public function addDocumentation($input_node, $documentation) { if ($input_node === $this) { $node = $this->_dom->documentElement; } else { $node = $input_node; } $doc = $this->_dom->createElement('documentation'); $doc_cdata = $this->_dom->createTextNode($documentation); $doc->appendChild($doc_cdata); if ($node->hasChildNodes()) { $node->insertBefore($doc, $node->firstChild); } else { $node->appendChild($doc); } return $doc; } /** * Add WSDL Types element * * @param object $types A DomDocument|DomNode|DomElement|DomDocumentFragment with all the XML Schema types defined in it */ public function addTypes($types) { if ($types instanceof DomDocument) { $dom = $this->_dom->importNode($types->documentElement); $this->_wsdl->appendChild($types->documentElement); } elseif ($types instanceof DomNode || $types instanceof DomElement || $types instanceof DomDocumentFragment) { $dom = $this->_dom->importNode($types); $this->_wsdl->appendChild($dom); } } /** * Add a complex type name that is part of this WSDL and can be used in signatures. * * @param string $type * @return Zend_Soap_Wsdl */ public function addType($type) { if (!in_array($type, $this->_includedTypes)) { $this->_includedTypes[] = $type; } return $this; } /** * Return an array of all currently included complex types * * @return array */ public function getTypes() { return $this->_includedTypes; } /** * Return the Schema node of the WSDL * * @return DOMElement */ public function getSchema() { if ($this->_schema == null) { $this->addSchemaTypeSection(); } return $this->_schema; } /** * Return the WSDL as XML * * @return string WSDL as XML */ public function toXML() { return $this->_dom->saveXML(); } /** * Return DOM Document * * @return DomDocument ent */ public function toDomDocument() { return $this->_dom; } /** * Echo the WSDL as XML * * @return boolean */ public function dump($filename = false) { if (!$filename) { echo $this->toXML(); return true; } else { return file_put_contents($filename, $this->toXML()); } } /** * Returns an XSD Type for the given PHP type * * @param string $type PHP Type to get the XSD type for * @return string */ public function getType($type) { switch (strtolower($type)) { case 'string': case 'str': return 'xsd:string'; break; case 'int': case 'integer': return 'xsd:int'; break; case 'float': case 'double': return 'xsd:float'; break; case 'boolean': case 'bool': return 'xsd:boolean'; break; case 'array': return 'soap-enc:Array'; break; case 'object': return 'xsd:struct'; break; case 'mixed': return 'xsd:anyType'; break; case 'void': return ''; default: // delegate retrieval of complex type to current strategy return $this->addComplexType($type); } } /** * This function makes sure a complex types section and schema additions are set. * * @return Zend_Soap_Wsdl */ public function addSchemaTypeSection() { if ($this->_schema === null) { $this->_schema = $this->_dom->createElement('xsd:schema'); $this->_schema->setAttribute('targetNamespace', $this->_uri); $types = $this->_dom->createElement('types'); $types->appendChild($this->_schema); $this->_wsdl->appendChild($types); } return $this; } /** * Add a {@link http://www.w3.org/TR/wsdl#_types types} data type definition * * @param string $type Name of the class to be specified * @return string XSD Type for the given PHP type */ public function addComplexType($type) { if (in_array($type, $this->getTypes())) { return "tns:$type"; } $this->addSchemaTypeSection(); $strategy = $this->getComplexTypeStrategy(); $strategy->setContext($this); // delegates the detection of a complex type to the current strategy return $strategy->addComplexType($type); } /** * Parse an xsd:element represented as an array into a DOMElement. * * @param array $element an xsd:element represented as an array * @return DOMElement parsed element */ private function _parseElement($element) { if (!is_array($element)) { require_once "Zend/Soap/Wsdl/Exception.php"; throw new Zend_Soap_Wsdl_Exception("The 'element' parameter needs to be an associative array."); } $elementXml = $this->_dom->createElement('xsd:element'); foreach ($element as $key => $value) { if (in_array($key, array('sequence', 'all', 'choice'))) { if (is_array($value)) { $complexType = $this->_dom->createElement('xsd:complexType'); if (count($value) > 0) { $container = $this->_dom->createElement('xsd:' . $key); foreach ($value as $subelement) { $subelementXml = $this->_parseElement($subelement); $container->appendChild($subelementXml); } $complexType->appendChild($container); } $elementXml->appendChild($complexType); } } else { $elementXml->setAttribute($key, $value); } } return $elementXml; } /** * Add an xsd:element represented as an array to the schema. * * Array keys represent attribute names and values their respective value. * The 'sequence', 'all' and 'choice' keys must have an array of elements as their value, * to add them to a nested complexType. * * Example: array( 'name' => 'MyElement', * 'sequence' => array( array('name' => 'myString', 'type' => 'string'), * array('name' => 'myInteger', 'type' => 'int') ) ); * Resulting XML: <xsd:element name="MyElement"><xsd:complexType><xsd:sequence> * <xsd:element name="myString" type="string"/> * <xsd:element name="myInteger" type="int"/> * </xsd:sequence></xsd:complexType></xsd:element> * * @param array $element an xsd:element represented as an array * @return string xsd:element for the given element array */ public function addElement($element) { $schema = $this->getSchema(); $elementXml = $this->_parseElement($element); $schema->appendChild($elementXml); return 'tns:' . $element['name']; } }
apache-2.0
jentfoo/aws-sdk-java
aws-java-sdk-s3/src/main/java/com/amazonaws/services/s3/model/replication/ReplicationPrefixPredicate.java
1351
/* * Copyright 2011-2019 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. * You may obtain a copy of the License at: * * http://aws.amazon.com/apache2.0 * * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES * OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and * limitations under the License. */ package com.amazonaws.services.s3.model.replication; /** * A {@link ReplicationFilterPredicate} class to represent the * prefix identifying one or more objects to which the * {@link com.amazonaws.services.s3.model.ReplicationRule} applies. */ public final class ReplicationPrefixPredicate extends ReplicationFilterPredicate { private final String prefix; public ReplicationPrefixPredicate(String prefix) { this.prefix = prefix; } /** * Returns the key prefix for which the * {@link com.amazonaws.services.s3.model.ReplicationRule} will apply. */ public String getPrefix() { return prefix; } @Override public void accept(ReplicationPredicateVisitor replicationPredicateVisitor) { replicationPredicateVisitor.visit(this); } }
apache-2.0
tanhaichao/leopard-data
leopard-jdbc/src/test/java/io/leopard/jdbc/RequestStat.java
2787
package io.leopard.jdbc; import java.util.Date; public class RequestStat { // 数量 总耗时 平均 数量 总耗时 平均 数量 总耗时 平均 发生时间 private Date time;// 时间段 private String projectId; private String url;// private String server;// APP服务器 // 新连接 private int allCount;// 数量 private double allTime;// 总耗时 // private Long newAvgTime;// 平均 // 慢连接 private int slowCount;// 数量 private double slowTime;// 总耗时 // private Long slowAvgTime;// 平均 // 特慢连接 private int verySlowCount;// 数量 private double verySlowTime;// 总耗时 // private Long verySlowAvgTime;// 平均 // 一分钟最大连接 private int maxCount;// 数量 private double maxTime;// 总耗时 // private Long maxAvgTime;// 平均 private Date maxDate;// 发生时间 private Date lmodify;// 记录最后修改时间 public RequestStat() { } public RequestStat(String url, String server) { this.url = url; this.server = server; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public int getAllCount() { return allCount; } public void setAllCount(int allCount) { this.allCount = allCount; } public double getAllTime() { return allTime; } public void setAllTime(double allTime) { this.allTime = allTime; } public String getServer() { return server; } public void setServer(String server) { this.server = server; } public int getSlowCount() { return slowCount; } public void setSlowCount(int slowCount) { this.slowCount = slowCount; } public double getSlowTime() { return slowTime; } public void setSlowTime(double slowTime) { this.slowTime = slowTime; } public int getVerySlowCount() { return verySlowCount; } public void setVerySlowCount(int verySlowCount) { this.verySlowCount = verySlowCount; } public double getVerySlowTime() { return verySlowTime; } public void setVerySlowTime(double verySlowTime) { this.verySlowTime = verySlowTime; } public int getMaxCount() { return maxCount; } public void setMaxCount(int maxCount) { this.maxCount = maxCount; } public double getMaxTime() { return maxTime; } public void setMaxTime(double maxTime) { this.maxTime = maxTime; } public Date getMaxDate() { return maxDate; } public void setMaxDate(Date maxDate) { this.maxDate = maxDate; } public Date getTime() { return time; } public void setTime(Date time) { this.time = time; } public Date getLmodify() { return lmodify; } public void setLmodify(Date lmodify) { this.lmodify = lmodify; } public String getProjectId() { return projectId; } public void setProjectId(String projectId) { this.projectId = projectId; } }
apache-2.0
bozimmerman/CoffeeMud
com/planet_ink/coffee_mud/Abilities/Prayers/Prayer_AuraStrife.java
5673
package com.planet_ink.coffee_mud.Abilities.Prayers; import com.planet_ink.coffee_mud.core.interfaces.*; import com.planet_ink.coffee_mud.core.*; import com.planet_ink.coffee_mud.core.collections.*; import com.planet_ink.coffee_mud.Abilities.interfaces.*; import com.planet_ink.coffee_mud.Areas.interfaces.*; import com.planet_ink.coffee_mud.Behaviors.interfaces.*; import com.planet_ink.coffee_mud.CharClasses.interfaces.*; import com.planet_ink.coffee_mud.Commands.interfaces.*; import com.planet_ink.coffee_mud.Common.interfaces.*; import com.planet_ink.coffee_mud.Exits.interfaces.*; import com.planet_ink.coffee_mud.Items.interfaces.*; import com.planet_ink.coffee_mud.Libraries.interfaces.*; import com.planet_ink.coffee_mud.Locales.interfaces.*; import com.planet_ink.coffee_mud.MOBS.interfaces.*; import com.planet_ink.coffee_mud.Races.interfaces.*; import java.util.*; /* Copyright 2003-2022 Bo Zimmerman Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ public class Prayer_AuraStrife extends Prayer { @Override public String ID() { return "Prayer_AuraStrife"; } private final static String localizedName = CMLib.lang().L("Aura of Strife"); @Override public String name() { return localizedName; } private final static String localizedStaticDisplay = CMLib.lang().L("(Aura of Strife)"); @Override public String displayText() { return localizedStaticDisplay; } @Override protected int canAffectCode() { return Ability.CAN_MOBS; } @Override protected int canTargetCode() { return 0; } @Override public int classificationCode() { return Ability.ACODE_PRAYER|Ability.DOMAIN_COMMUNING; } @Override public int abstractQuality() { return Ability.QUALITY_INDIFFERENT; } @Override public long flags() { return Ability.FLAG_UNHOLY; } @Override public void affectCharStats(final MOB affected, final CharStats affectableStats) { super.affectCharStats(affected,affectableStats); if((invoker()!=null)&&(affected!=invoker())&&(CMLib.flags().isEvil(invoker()))) { affectableStats.setStat(CharStats.STAT_CHARISMA,affectableStats.getStat(CharStats.STAT_CHARISMA)-(adjustedLevel(invoker(),0)/5)); if(affectableStats.getStat(CharStats.STAT_CHARISMA)<=0) affectableStats.setStat(CharStats.STAT_CHARISMA,1); } } @Override public boolean okMessage(final Environmental myHost, final CMMsg msg) { if((affected instanceof MOB) &&(msg.amISource((MOB)affected)) &&(msg.sourceMinor()==CMMsg.TYP_QUIT)) unInvoke(); else if(msg.sourceMinor()==CMMsg.TYP_SHUTDOWN) unInvoke(); return super.okMessage(myHost,msg); } @Override public void unInvoke() { // undo the affects of this spell if(!(affected instanceof MOB)) return; final MOB M=(MOB)affected; super.unInvoke(); if((canBeUninvoked())&&(M!=null)&&(!M.amDead())&&(M.location()!=null)) M.location().show(M,null,CMMsg.MSG_OK_VISUAL,L("The aura of strife around <S-NAME> fades.")); } @Override public boolean tick(final Tickable ticking, final int tickID) { if(!super.tick(ticking,tickID)) return false; if((tickID==Tickable.TICKID_MOB) &&(invoker()!=null) &&(affected instanceof MOB)) { final MOB mob=(MOB)affected; final Set<MOB> invokerGroup=invoker().getGroupMembers(new HashSet<MOB>()); if(mob!=invoker()) { if(mob.location()!=invoker().location()) unInvoke(); else { if(invokerGroup.contains(mob)) unInvoke(); else if(mob.isInCombat()) { int levels=invoker().charStats().getClassLevel("Templar"); if(levels<0) levels=invoker().phyStats().level(); if(CMLib.dice().rollPercentage()>=levels) { final MOB newvictim=mob.location().fetchRandomInhabitant(); if(newvictim!=mob) mob.setVictim(newvictim); } } } } else if((mob.location()!=null)&&(CMLib.flags().isEvil(invoker()))) { for(int m=0;m<mob.location().numInhabitants();m++) { final MOB M=mob.location().fetchInhabitant(m); if((M!=null)&&(M!=invoker())&&(!invokerGroup.contains(M))&&(!M.Name().equals(mob.getLiegeID()))) beneficialAffect(invoker,M,0,Ability.TICKS_FOREVER); } } } return true; } @Override public boolean invoke(final MOB mob, final List<String> commands, final Physical givenTarget, final boolean auto, final int asLevel) { final MOB target=getTarget(mob,commands,givenTarget); if(target==null) return false; final Room targetRoom=target.location(); if(targetRoom==null) return false; if(!super.invoke(mob,commands,givenTarget,auto,asLevel)) return false; final boolean success=proficiencyCheck(mob,0,auto); if(success) { beneficialAffect(mob,target,asLevel,0); target.recoverPhyStats(); targetRoom.recoverRoomStats(); } // return whether it worked return success; } @Override public boolean autoInvocation(final MOB mob, final boolean force) { return super.autoInvocation(mob, force); } }
apache-2.0
AquaticInformatics/Examples
TimeSeries/PublicApis/SdkExamples/SharpShooterReportsRunner/TimeSeries.cs
329
namespace SharpShooterReportsRunner { public class TimeSeries : DataSetBase { public string Identifier { get; set; } public string OutputUnitId { get; set; } public string QueryFrom { get; set; } public string QueryTo { get; set; } public GroupBy? GroupBy { get; set; } } }
apache-2.0
pravega/pravega
controller/src/main/java/io/pravega/controller/store/stream/InMemoryBucketStore.java
4750
/** * Copyright Pravega Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.pravega.controller.store.stream; import com.google.common.collect.ImmutableMap; import io.pravega.controller.store.client.StoreType; import java.util.Collections; import java.util.Set; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.ConcurrentSkipListSet; import java.util.concurrent.Executor; public class InMemoryBucketStore implements BucketStore { private final ImmutableMap<ServiceType, Integer> bucketCountMap; private final ConcurrentMap<String, ConcurrentSkipListSet<String>> bucketedStreams; private final ConcurrentMap<String, BucketChangeListener> listeners; InMemoryBucketStore(ImmutableMap<ServiceType, Integer> bucketCountMap) { this.bucketCountMap = bucketCountMap; bucketedStreams = new ConcurrentHashMap<>(); listeners = new ConcurrentHashMap<>(); } private String getBucketName(ServiceType serviceType, int bucket) { return serviceType.getName() + "/" + bucket; } @Override public StoreType getStoreType() { return StoreType.InMemory; } @Override public int getBucketCount(ServiceType serviceType) { return bucketCountMap.get(serviceType); } @Override public CompletableFuture<Set<String>> getStreamsForBucket(ServiceType serviceType, int bucket, Executor executor) { String bucketName = getBucketName(serviceType, bucket); if (bucketedStreams.containsKey(bucketName)) { return CompletableFuture.completedFuture(Collections.unmodifiableSet(bucketedStreams.get(bucketName))); } else { return CompletableFuture.completedFuture(Collections.emptySet()); } } @Override public CompletableFuture<Void> addStreamToBucketStore(ServiceType serviceType, String scope, String stream, Executor executor) { int bucketCount = bucketCountMap.get(serviceType); int bucket = BucketStore.getBucket(scope, stream, bucketCount); String bucketName = getBucketName(serviceType, bucket); ConcurrentSkipListSet<String> set = bucketedStreams.compute(bucketName, (x, y) -> { if (y == null) { return new ConcurrentSkipListSet<>(); } else { return y; } }); String scopedStreamName = BucketStore.getScopedStreamName(scope, stream); set.add(scopedStreamName); listeners.computeIfPresent(bucketName, (b, listener) -> { listener.notify(scope, stream, true); return listener; }); return CompletableFuture.completedFuture(null); } @Override public CompletableFuture<Void> removeStreamFromBucketStore(ServiceType serviceType, String scope, String stream, Executor executor) { int bucketCount = bucketCountMap.get(serviceType); int bucket = BucketStore.getBucket(scope, stream, bucketCount); String bucketName = getBucketName(serviceType, bucket); String scopedStreamName = BucketStore.getScopedStreamName(scope, stream); bucketedStreams.computeIfPresent(bucketName, (b, set) -> { set.remove(scopedStreamName); return set; }); listeners.computeIfPresent(getBucketName(serviceType, bucket), (b, listener) -> { listener.notify(scope, stream, false); return listener; }); return CompletableFuture.completedFuture(null); } public void registerBucketChangeListener(ServiceType serviceType, int bucketId, BucketChangeListener listener) { String bucketName = getBucketName(serviceType, bucketId); listeners.putIfAbsent(bucketName, listener); } public void unregisterBucketChangeListener(ServiceType serviceType, int bucketId) { String bucketName = getBucketName(serviceType, bucketId); listeners.remove(bucketName); } @FunctionalInterface public interface BucketChangeListener { void notify(String scope, String stream, boolean add); } }
apache-2.0
davidmigloz/supermarket-agent-system
src/main/java/com/davidflex/supermarket/ontologies/company/concepts/Warehouse.java
911
package com.davidflex.supermarket.ontologies.company.concepts; import com.davidflex.supermarket.ontologies.ecommerce.concepts.Location; import jade.content.Concept; import jade.core.AID; /** * Warehouse. */ @SuppressWarnings("unused") public class Warehouse implements Concept { private AID warehouseAgent; private Location location; public Warehouse() { } public Warehouse(AID warehouseAgent, Location location) { this.warehouseAgent = warehouseAgent; this.location = location; } public AID getWarehouseAgent() { return warehouseAgent; } public void setWarehouseAgent(AID warehouseAgent) { this.warehouseAgent = warehouseAgent; } public Location getLocation() { return location; } public void setLocation(Location location) { this.location = location; } }
apache-2.0
neowu/core-ng-project
core-ng/src/test/java/core/framework/internal/web/route/PathTest.java
1893
package core.framework.internal.web.route; import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNull; /** * @author neo */ class PathTest { @Test void parseRootURL() { Path path = Path.parse("/"); assertThat(path.value).isEqualTo("/"); assertThat(path.next).isNull(); } @Test void parseOneLevelURL() { Path path = Path.parse("/path1"); assertEquals("/", path.value); assertEquals("path1", path.next.value); assertNull(path.next.next); } @Test void parseOneLevelURLWithTrailingSlash() { Path path = Path.parse("/path1/"); assertEquals("/", path.value); assertEquals("path1", path.next.value); assertEquals("/", path.next.next.value); assertNull(path.next.next.next); } @Test void parseURL() { Path path = Path.parse("/path1/path2"); assertEquals("/", path.value); assertEquals("path1", path.next.value); assertEquals("path2", path.next.next.value); assertNull(path.next.next.next); } @Test void parseURLWithTrailingSlash() { Path path = Path.parse("/path1/path2/"); assertEquals("/", path.value); assertEquals("path1", path.next.value); assertEquals("path2", path.next.next.value); assertEquals("/", path.next.next.next.value); assertNull(path.next.next.next.next); } @Test void subPath() { Path path = Path.parse("/path1/path2/"); assertEquals("/path1/path2/", path.subPath()); assertEquals("path1/path2/", path.next.subPath()); assertEquals("path2/", path.next.next.subPath()); assertEquals("/", path.next.next.next.subPath()); } }
apache-2.0
AlSidorenko/Junior
chapter_003/src/test/java/ru/job4j/sorting/comparator/SortUserTest.java
1825
package ru.job4j.sorting.comparator; import org.junit.Test; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import static org.hamcrest.core.Is.is; import static org.junit.Assert.assertThat; /** * Created on 05.06.2018. * * @author Aleks Sidorenko (alek.sidorenko1979@gmail.com). * @version $Id$. * @since 0.1. */ public class SortUserTest { /** * Test sorting by name length. */ @Test public void whenSortNameLength() { List<User> users = new ArrayList<>(); users.addAll(Arrays.asList( new User("Sergey", 25), new User("Ivan", 30), new User("Sergey", 20), new User("Ivan", 25) )); List<User> result = new SortUser().sortNameLength(users); List<User> expected = new ArrayList<>(); expected.addAll(Arrays.asList( new User("Ivan", 30), new User("Ivan", 25), new User("Sergey", 25), new User("Sergey", 20) )); assertThat(result, is(expected)); } /** * Test sorting by all fields. */ @Test public void whenSortByAllFields() { List<User> users = new ArrayList<>(); users.addAll(Arrays.asList( new User("Sergey", 25), new User("Ivan", 30), new User("Sergey", 20), new User("Ivan", 25) )); List<User> result = new SortUser().sortByAllFields(users); List<User> expected = new ArrayList<>(); expected.addAll(Arrays.asList( new User("Ivan", 25), new User("Ivan", 30), new User("Sergey", 20), new User("Sergey", 25) )); assertThat(result, is(expected)); } }
apache-2.0
xorware/android_frameworks_base
packages/SystemUI/src/com/android/systemui/tuner/ColorAndAppearanceActivity.java
3983
/* * Copyright (C) 2015 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 com.android.systemui.tuner; import android.app.Fragment; import android.app.FragmentTransaction; import android.os.Bundle; import android.support.v14.preference.PreferenceFragment; import android.support.v7.preference.Preference; import android.support.v7.preference.PreferenceScreen; import android.util.Log; import android.view.MenuItem; import com.android.settingslib.drawer.SettingsDrawerActivity; import com.android.systemui.R; public class ColorAndAppearanceActivity extends SettingsDrawerActivity implements PreferenceFragment.OnPreferenceStartFragmentCallback, PreferenceFragment.OnPreferenceStartScreenCallback { private static final String TAG_COLOR = "color"; protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (getFragmentManager().findFragmentByTag(TAG_COLOR) == null) { final String action = getIntent().getAction(); final PreferenceFragment fragment = new ColorAndAppearanceFragment(); getFragmentManager().beginTransaction().replace(R.id.content_frame, fragment, TAG_COLOR).commit(); } } @Override public void onBackPressed() { if (!getFragmentManager().popBackStackImmediate()) { super.onBackPressed(); } } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: onBackPressed(); return true; } return super.onOptionsItemSelected(item); } @Override public boolean onPreferenceStartFragment(PreferenceFragment caller, Preference pref) { try { Class<?> cls = Class.forName(pref.getFragment()); Fragment fragment = (Fragment) cls.newInstance(); FragmentTransaction transaction = getFragmentManager().beginTransaction(); setTitle(pref.getTitle()); transaction.replace(R.id.content_frame, fragment); transaction.addToBackStack("PreferenceFragment"); transaction.commit(); return true; } catch (ClassNotFoundException | InstantiationException | IllegalAccessException e) { Log.d("ColorAndAppearanceActivity", "Problem launching fragment", e); return false; } } @Override public boolean onPreferenceStartScreen(PreferenceFragment caller, PreferenceScreen pref) { FragmentTransaction transaction = getFragmentManager().beginTransaction(); SubSettingsFragment fragment = new SubSettingsFragment(); final Bundle b = new Bundle(1); b.putString(PreferenceFragment.ARG_PREFERENCE_ROOT, pref.getKey()); fragment.setArguments(b); fragment.setTargetFragment(caller, 0); transaction.replace(R.id.content_frame, fragment); transaction.addToBackStack("PreferenceFragment"); transaction.commit(); return true; } public static class SubSettingsFragment extends PreferenceFragment { @Override public void onCreatePreferences(Bundle savedInstanceState, String rootKey) { setPreferenceScreen((PreferenceScreen) ((PreferenceFragment) getTargetFragment()) .getPreferenceScreen().findPreference(rootKey)); } } }
apache-2.0
google/gps-babel-tower
examples/sentiment.py
1382
# coding=utf-8 # Copyright 2021 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 # # 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. from gps_babel_tower.tasks.sentiment import SentimentClient examples = ['I hate you', "It's ok", 'I like this app but it has minor issues'] # Explore models here: # https://huggingface.co/models?search=sentiment models = [ 'distilbert-base-uncased-finetuned-sst-2-english', 'nlptown/bert-base-multilingual-uncased-sentiment', 'cardiffnlp/twitter-roberta-base-sentiment', 'm3hrdadfi/albert-fa-base-v2-sentiment-multi' ] # Using HuggingFace models (fast, cheap) s = SentimentClient( model='nlptown/bert-base-multilingual-uncased-sentiment', use_fast=True) print('local model') for ex in examples: print(ex, s.score(ex)) # Using GCP API (more accurate) s = SentimentClient(engine='gcp') print('gcp') for ex in examples: print(ex, s.score(ex, score_range=(0, 100)))
apache-2.0
google/end-to-end
src/javascript/crypto/e2e/extension/preferences.js
2939
/** * @license * Copyright 2013 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. */ /** * @fileoverview Handles the user's preferences inside the extension. */ goog.provide('e2e.ext.Preferences'); goog.require('e2e.ext.constants.StorageKey'); goog.requireType('goog.storage.mechanism.Mechanism'); /** * Class to handle user's preferences. * @constructor * @param {!goog.storage.mechanism.Mechanism} storage mechanism for storing * preferences data. */ e2e.ext.Preferences = function(storage) { /** * Mechanism for storing preferences. * @type {!goog.storage.mechanism.Mechanism} * @private */ this.storage_ = storage; }; goog.scope(function() { var constants = e2e.ext.constants; /** * @param {string} key * @return {?string} * @export */ e2e.ext.Preferences.prototype.getItem = function(key) { return this.storage_.get(key); }; /** * Initializes the default preferences. * @export */ e2e.ext.Preferences.prototype.initDefaults = function() { if (null === this.getItem( constants.StorageKey.ENABLE_WELCOME_SCREEN)) { this.setWelcomePageEnabled(true); } if (null === this.getItem( constants.StorageKey.ENABLE_LOOKING_GLASS)) { this.setLookingGlassEnabled(false); } }; /** * Enables/disables the welcome page. * @param {boolean} enable True if the page is to be enabled. * @export */ e2e.ext.Preferences.prototype.setWelcomePageEnabled = function(enable) { this.storage_.set( constants.StorageKey.ENABLE_WELCOME_SCREEN, enable.toString()); }; /** * Indicates whether the welcome page is enabled. * @return {boolean} True if the welcome is enabled. * @export */ e2e.ext.Preferences.prototype.isWelcomePageEnabled = function() { return 'true' == this.storage_.get( constants.StorageKey.ENABLE_WELCOME_SCREEN); }; /** * Enables/disables the looking glass. * @param {boolean} enable True if the looking glass is to be enabled. * @export */ e2e.ext.Preferences.prototype.setLookingGlassEnabled = function(enable) { this.storage_.set( constants.StorageKey.ENABLE_LOOKING_GLASS, enable.toString()); }; /** * Indicates whether the looking glass is enabled. * @return {boolean} True if enabled. * @export */ e2e.ext.Preferences.prototype.isLookingGlassEnabled = function() { return 'true' == this.storage_.get( constants.StorageKey.ENABLE_LOOKING_GLASS); }; }); // goog.scope
apache-2.0
ImABradley/Peach
src/main/java/imabradley/peach/util/yaml/Setting.java
1243
/* * Copyright 2017 Bradley Steele * * 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 imabradley.peach.util.yaml; /** * @version 1.0 * @author Bradley Steele */ public enum Setting { CONFIG_VERSION("config-version", "1"), ; private String path; private String def; /** * @param path path in the config.yml. * @param def default value if path/value does not exist. */ Setting(String path, String def) { this.path = path; this.def = def; } /** * @return path to the value. */ public String getPath() { return path; } /** * @return default value. */ public String getDefault() { return def; } }
apache-2.0
HuaweiSNC/OpsDev
src/plugins/com.huawei.networkos.ops/src/com/huawei/networkos/ops/views/OpsServerHandelWizard.java
1012
package com.huawei.networkos.ops.views; import org.eclipse.core.resources.IProject; import org.eclipse.jface.wizard.Wizard; import com.huawei.tools.xml.config.OpsService; import com.huawei.tools.xml.config.OpsServiceUrlHandle; public class OpsServerHandelWizard extends Wizard { private OpsServiceUrlHandle handle; private OpsService opsService; private OpsServerHandelPage handelPage; private IProject iproject; public OpsServerHandelWizard(IProject iproject,OpsService opsService) { setWindowTitle("Add OPS Device Handel"); this.iproject = iproject; handelPage = new OpsServerHandelPage(iproject); this.opsService = opsService; } public void addPages() { addPage(handelPage); } public boolean performFinish() { handle = handelPage.getOpsServiceUrlHandle(); opsService.getHandles().add(handle); return true; } public OpsService getOpsService(){ return opsService; } public OpsServiceUrlHandle getOpsServiceUrlHandle(){ return handle; } }
apache-2.0
tokee/lucene
contrib/benchmark/src/java/org/apache/lucene/benchmark/byTask/tasks/TaskSequence.java
14775
package org.apache.lucene.benchmark.byTask.tasks; /** * 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 java.util.ArrayList; import java.util.List; import java.text.NumberFormat; import org.apache.lucene.benchmark.byTask.PerfRunData; import org.apache.lucene.benchmark.byTask.feeds.NoMoreDataException; import org.apache.lucene.benchmark.byTask.stats.TaskStats; import org.apache.lucene.util.ArrayUtil; /** * Sequence of parallel or sequential tasks. */ public class TaskSequence extends PerfTask { public static int REPEAT_EXHAUST = -2; private ArrayList<PerfTask> tasks; private int repetitions = 1; private boolean parallel; private TaskSequence parent; private boolean letChildReport = true; private int rate = 0; private boolean perMin = false; // rate, if set, is, by default, be sec. private String seqName; private boolean exhausted = false; private boolean resetExhausted = false; private PerfTask[] tasksArray; private boolean anyExhaustibleTasks; private boolean collapsable = false; // to not collapse external sequence named in alg. private boolean fixedTime; // true if we run for fixed time private double runTimeSec; // how long to run for private final long logByTimeMsec; public TaskSequence (PerfRunData runData, String name, TaskSequence parent, boolean parallel) { super(runData); collapsable = (name == null); name = (name!=null ? name : (parallel ? "Par" : "Seq")); setName(name); setSequenceName(); this.parent = parent; this.parallel = parallel; tasks = new ArrayList<PerfTask>(); logByTimeMsec = runData.getConfig().get("report.time.step.msec", 0); } @Override public void close() throws Exception { initTasksArray(); for(int i=0;i<tasksArray.length;i++) { tasksArray[i].close(); } getRunData().getDocMaker().close(); } private void initTasksArray() { if (tasksArray == null) { final int numTasks = tasks.size(); tasksArray = new PerfTask[numTasks]; for(int k=0;k<numTasks;k++) { tasksArray[k] = tasks.get(k); anyExhaustibleTasks |= tasksArray[k] instanceof ResetInputsTask; anyExhaustibleTasks |= tasksArray[k] instanceof TaskSequence; } } if (!parallel && logByTimeMsec != 0 && !letChildReport) { countsByTime = new int[1]; } } /** * @return Returns the parallel. */ public boolean isParallel() { return parallel; } /** * @return Returns the repetitions. */ public int getRepetitions() { return repetitions; } private int[] countsByTime; public void setRunTime(double sec) throws Exception { runTimeSec = sec; fixedTime = true; } /** * @param repetitions The repetitions to set. * @throws Exception */ public void setRepetitions(int repetitions) throws Exception { fixedTime = false; this.repetitions = repetitions; if (repetitions==REPEAT_EXHAUST) { if (isParallel()) { throw new Exception("REPEAT_EXHAUST is not allowed for parallel tasks"); } } setSequenceName(); } /** * @return Returns the parent. */ public TaskSequence getParent() { return parent; } /* * (non-Javadoc) * @see org.apache.lucene.benchmark.byTask.tasks.PerfTask#doLogic() */ @Override public int doLogic() throws Exception { exhausted = resetExhausted = false; return ( parallel ? doParallelTasks() : doSerialTasks()); } private static class RunBackgroundTask extends Thread { private final PerfTask task; private final boolean letChildReport; private volatile int count; public RunBackgroundTask(PerfTask task, boolean letChildReport) { this.task = task; this.letChildReport = letChildReport; } public void stopNow() throws InterruptedException { task.stopNow(); } public int getCount() { return count; } @Override public void run() { try { count = task.runAndMaybeStats(letChildReport); } catch (Exception e) { throw new RuntimeException(e); } } } private int doSerialTasks() throws Exception { if (rate > 0) { return doSerialTasksWithRate(); } initTasksArray(); int count = 0; final long runTime = (long) (runTimeSec*1000); List<RunBackgroundTask> bgTasks = null; final long t0 = System.currentTimeMillis(); for (int k=0; fixedTime || (repetitions==REPEAT_EXHAUST && !exhausted) || k<repetitions; k++) { if (stopNow) { break; } for(int l=0;l<tasksArray.length;l++) { final PerfTask task = tasksArray[l]; if (task.getRunInBackground()) { if (bgTasks == null) { bgTasks = new ArrayList<RunBackgroundTask>(); } RunBackgroundTask bgTask = new RunBackgroundTask(task, letChildReport); bgTask.setPriority(task.getBackgroundDeltaPriority() + Thread.currentThread().getPriority()); bgTask.start(); bgTasks.add(bgTask); } else { try { final int inc = task.runAndMaybeStats(letChildReport); count += inc; if (countsByTime != null) { final int slot = (int) ((System.currentTimeMillis()-t0)/logByTimeMsec); if (slot >= countsByTime.length) { countsByTime = ArrayUtil.grow(countsByTime, 1+slot); } countsByTime[slot] += inc; } if (anyExhaustibleTasks) updateExhausted(task); } catch (NoMoreDataException e) { exhausted = true; } } } if (fixedTime && System.currentTimeMillis()-t0 > runTime) { repetitions = k+1; break; } } if (bgTasks != null) { for(RunBackgroundTask bgTask : bgTasks) { bgTask.stopNow(); } for(RunBackgroundTask bgTask : bgTasks) { bgTask.join(); count += bgTask.getCount(); } } if (countsByTime != null) { getRunData().getPoints().getCurrentStats().setCountsByTime(countsByTime, logByTimeMsec); } stopNow = false; return count; } private int doSerialTasksWithRate() throws Exception { initTasksArray(); long delayStep = (perMin ? 60000 : 1000) /rate; long nextStartTime = System.currentTimeMillis(); int count = 0; final long t0 = System.currentTimeMillis(); for (int k=0; (repetitions==REPEAT_EXHAUST && !exhausted) || k<repetitions; k++) { if (stopNow) { break; } for (int l=0;l<tasksArray.length;l++) { final PerfTask task = tasksArray[l]; while(!stopNow) { long waitMore = nextStartTime - System.currentTimeMillis(); if (waitMore > 0) { // TODO: better to use condition to notify Thread.sleep(1); } else { break; } } if (stopNow) { break; } nextStartTime += delayStep; // this aims at avarage rate. try { final int inc = task.runAndMaybeStats(letChildReport); count += inc; if (countsByTime != null) { final int slot = (int) ((System.currentTimeMillis()-t0)/logByTimeMsec); if (slot >= countsByTime.length) { countsByTime = ArrayUtil.grow(countsByTime, 1+slot); } countsByTime[slot] += inc; } if (anyExhaustibleTasks) updateExhausted(task); } catch (NoMoreDataException e) { exhausted = true; } } } stopNow = false; return count; } // update state regarding exhaustion. private void updateExhausted(PerfTask task) { if (task instanceof ResetInputsTask) { exhausted = false; resetExhausted = true; } else if (task instanceof TaskSequence) { TaskSequence t = (TaskSequence) task; if (t.resetExhausted) { exhausted = false; resetExhausted = true; t.resetExhausted = false; } else { exhausted |= t.exhausted; } } } private class ParallelTask extends Thread { public int count; public final PerfTask task; public ParallelTask(PerfTask task) { this.task = task; } @Override public void run() { try { int n = task.runAndMaybeStats(letChildReport); if (anyExhaustibleTasks) { updateExhausted(task); } count += n; } catch (NoMoreDataException e) { exhausted = true; } catch (Exception e) { throw new RuntimeException(e); } } } @Override public void stopNow() { super.stopNow(); // Forwards top request to children if (runningParallelTasks != null) { for(ParallelTask t : runningParallelTasks) { t.task.stopNow(); } } } ParallelTask[] runningParallelTasks; private int doParallelTasks() throws Exception { final TaskStats stats = getRunData().getPoints().getCurrentStats(); initTasksArray(); ParallelTask t[] = runningParallelTasks = new ParallelTask[repetitions * tasks.size()]; // prepare threads int index = 0; for (int k=0; k<repetitions; k++) { for (int i = 0; i < tasksArray.length; i++) { final PerfTask task = (PerfTask) tasksArray[i].clone(); t[index++] = new ParallelTask(task); } } // run threads startThreads(t); // wait for all threads to complete int count = 0; for (int i = 0; i < t.length; i++) { t[i].join(); count += t[i].count; if (t[i].task instanceof TaskSequence) { TaskSequence sub = (TaskSequence) t[i].task; if (sub.countsByTime != null) { if (countsByTime == null) { countsByTime = new int[sub.countsByTime.length]; } else if (countsByTime.length < sub.countsByTime.length) { countsByTime = ArrayUtil.grow(countsByTime, sub.countsByTime.length); } for(int j=0;j<sub.countsByTime.length;j++) { countsByTime[j] += sub.countsByTime[j]; } } } } if (countsByTime != null) { stats.setCountsByTime(countsByTime, logByTimeMsec); } // return total count return count; } // run threads private void startThreads(ParallelTask[] t) throws InterruptedException { if (rate > 0) { startlThreadsWithRate(t); return; } for (int i = 0; i < t.length; i++) { t[i].start(); } } // run threads with rate private void startlThreadsWithRate(ParallelTask[] t) throws InterruptedException { long delayStep = (perMin ? 60000 : 1000) /rate; long nextStartTime = System.currentTimeMillis(); for (int i = 0; i < t.length; i++) { long waitMore = nextStartTime - System.currentTimeMillis(); if (waitMore > 0) { Thread.sleep(waitMore); } nextStartTime += delayStep; // this aims at average rate of starting threads. t[i].start(); } } public void addTask(PerfTask task) { tasks.add(task); task.setDepth(getDepth()+1); } /* (non-Javadoc) * @see java.lang.Object#toString() */ @Override public String toString() { String padd = getPadding(); StringBuffer sb = new StringBuffer(super.toString()); sb.append(parallel ? " [" : " {"); sb.append(NEW_LINE); for (final PerfTask task : tasks) { sb.append(task.toString()); sb.append(NEW_LINE); } sb.append(padd); sb.append(!letChildReport ? ">" : (parallel ? "]" : "}")); if (fixedTime) { sb.append(" " + NumberFormat.getNumberInstance().format(runTimeSec) + "s"); } else if (repetitions>1) { sb.append(" * " + repetitions); } else if (repetitions==REPEAT_EXHAUST) { sb.append(" * EXHAUST"); } if (rate>0) { sb.append(", rate: " + rate+"/"+(perMin?"min":"sec")); } if (getRunInBackground()) { sb.append(" &"); int x = getBackgroundDeltaPriority(); if (x != 0) { sb.append(x); } } return sb.toString(); } /** * Execute child tasks in a way that they do not report their time separately. */ public void setNoChildReport() { letChildReport = false; for (final PerfTask task : tasks) { if (task instanceof TaskSequence) { ((TaskSequence)task).setNoChildReport(); } } } /** * Returns the rate per minute: how many operations should be performed in a minute. * If 0 this has no effect. * @return the rate per min: how many operations should be performed in a minute. */ public int getRate() { return (perMin ? rate : 60*rate); } /** * @param rate The rate to set. */ public void setRate(int rate, boolean perMin) { this.rate = rate; this.perMin = perMin; setSequenceName(); } private void setSequenceName() { seqName = super.getName(); if (repetitions==REPEAT_EXHAUST) { seqName += "_Exhaust"; } else if (repetitions>1) { seqName += "_"+repetitions; } if (rate>0) { seqName += "_" + rate + (perMin?"/min":"/sec"); } if (parallel && seqName.toLowerCase().indexOf("par")<0) { seqName += "_Par"; } } @Override public String getName() { return seqName; // override to include more info } /** * @return Returns the tasks. */ public ArrayList<PerfTask> getTasks() { return tasks; } /* (non-Javadoc) * @see java.lang.Object#clone() */ @Override protected Object clone() throws CloneNotSupportedException { TaskSequence res = (TaskSequence) super.clone(); res.tasks = new ArrayList<PerfTask>(); for (int i = 0; i < tasks.size(); i++) { res.tasks.add((PerfTask)tasks.get(i).clone()); } return res; } /** * Return true if can be collapsed in case it is outermost sequence */ public boolean isCollapsable() { return collapsable; } }
apache-2.0
stuffer2325/Makagiga
src/org/makagiga/commons/swing/border/MBorder.java
1771
// Copyright 2010 Konrad Twardowski // // 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.makagiga.commons.swing.border; import java.awt.Component; import java.awt.Insets; import javax.swing.border.AbstractBorder; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; /** * @since 3.8.8, 4.0 (org.makagiga.commons.swing.border package) */ public abstract class MBorder extends AbstractBorder { // private private final boolean opaque; private final Insets insets; // public @Override public Insets getBorderInsets(final Component c) { return getBorderInsets(c, insets); } @Override @SuppressFBWarnings("CFS_CONFUSING_FUNCTION_SEMANTICS") public Insets getBorderInsets(final Component c, final Insets insets) { insets.set(this.insets.top, this.insets.left, this.insets.bottom, this.insets.right); return insets; } @Override public boolean isBorderOpaque() { return opaque; } // protected protected MBorder(final boolean opaque, final Insets insets) { this.opaque = opaque; this.insets = (Insets)insets.clone(); } protected MBorder(final boolean opaque, final int top, final int left, final int bottom, final int right) { this.opaque = opaque; this.insets = new Insets(top, left, bottom, right); } }
apache-2.0
topie/topie-oa
src/main/java/com/topie/internal/delegate/support/DelegateConnectorImpl.java
1259
package com.topie.internal.delegate.support; import javax.annotation.Resource; import com.topie.api.delegate.DelegateConnector; import com.topie.internal.delegate.persistence.domain.DelegateInfo; import com.topie.internal.delegate.service.DelegateService; public class DelegateConnectorImpl implements DelegateConnector { private DelegateService delegateService; public String findAttorney(String userId, String processDefinitionId, String taskDefinitionKey, String tenantId) { DelegateInfo delegateInfo = delegateService.getDelegateInfo(userId, processDefinitionId, taskDefinitionKey, tenantId); if (delegateInfo == null) { return null; } return delegateInfo.getAttorney(); } public void recordDelegate(String userId, String attorney, String taskId, String tenantId) { delegateService.saveRecord(userId, attorney, taskId, tenantId); } public void cancel(String taskId, String userId, String tenantId) { } public void complete(String taskId, String complete, String tenantId) { } @Resource public void setDelegateService(DelegateService delegateService) { this.delegateService = delegateService; } }
apache-2.0
cmmanish/OldUITempTest
examples/v201109/DeleteAdGroup.java
2766
// Copyright 2011, Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package v201109; import com.google.api.adwords.lib.AdWordsService; import com.google.api.adwords.lib.AdWordsServiceLogger; import com.google.api.adwords.lib.AdWordsUser; import com.google.api.adwords.v201109.cm.AdGroup; import com.google.api.adwords.v201109.cm.AdGroupOperation; import com.google.api.adwords.v201109.cm.AdGroupReturnValue; import com.google.api.adwords.v201109.cm.AdGroupServiceInterface; import com.google.api.adwords.v201109.cm.AdGroupStatus; import com.google.api.adwords.v201109.cm.Operator; /** * This example deletes an ad group by setting the status to 'DELETED'. * To get ad groups, run GetAllAdGroups.java. * * Tags: AdGroupService.mutate * * @author api.arogal@gmail.com (Adam Rogal) */ public class DeleteAdGroup { public static void main(String[] args) { try { // Log SOAP XML request and response. AdWordsServiceLogger.log(); // Get AdWordsUser from "~/adwords.properties". AdWordsUser user = new AdWordsUser(); // Get the AdGroupService. AdGroupServiceInterface adGroupService = user.getService(AdWordsService.V201109.ADGROUP_SERVICE); long adGroupId = Long.parseLong("INSERT_AD_GROUP_ID_HERE"); // Create ad group with DELETED status. AdGroup adGroup = new AdGroup(); adGroup.setId(adGroupId); adGroup.setStatus(AdGroupStatus.DELETED); // Create operations. AdGroupOperation operation = new AdGroupOperation(); operation.setOperand(adGroup); operation.setOperator(Operator.SET); AdGroupOperation[] operations = new AdGroupOperation[]{operation}; // Delete ad group. AdGroupReturnValue result = adGroupService.mutate(operations); // Display ad groups. if (result != null && result.getValue() != null) { for (AdGroup adGroupResult : result.getValue()) { System.out.println("Ad group with name \"" + adGroupResult.getName() + "\" and id \"" + adGroupResult.getId() + "\" was deleted."); } } else { System.out.println("No ad groups were deleted."); } } catch (Exception e) { e.printStackTrace(); } } }
apache-2.0
dufangyu1990/NewFarmTool
app/src/main/java/com/example/newframtool/view/TongjiView.java
9648
package com.example.newframtool.view; import android.app.Activity; import android.os.Handler; import android.view.Gravity; import android.view.LayoutInflater; import android.view.View; import android.view.animation.AnimationUtils; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.PopupWindow; import android.widget.RelativeLayout; import android.widget.TextView; import com.example.newframtool.R; import com.example.newframtool.adapter.TongjiRecyclerViewAdapter; import com.example.newframtool.bean.WeMonBean; import com.example.newframtool.helper.EventHelper; import com.example.newframtool.time.WheelMain; import com.example.newframtool.util.CustomDialog; import com.example.newframtool.util.LogUtil; import com.example.newframtool.util.MyPopupWin; import com.example.newframtool.util.MyToast; import com.example.newframtool.util.SpaceItemDecoratio; import com.example.newframtool.util.Util; import com.wuxiaolong.pullloadmorerecyclerview.PullLoadMoreRecyclerView; import java.util.ArrayList; import java.util.Date; import java.util.List; /** * Created by dufangyu on 2017/6/17. */ public class TongjiView extends ViewImpl implements PullLoadMoreRecyclerView.PullLoadMoreListener{ private ImageView backImg; private TextView title,submittext,startTimeTv,endTimeTv,chooseTimeTv; private PullLoadMoreRecyclerView tongjiRecyclerView; private TongjiRecyclerViewAdapter mRecyclerViewAdapter; private RelativeLayout startTimelayout,endTimelayout; private RelativeLayout OKlayout; private static Handler mHandler = new Handler(); private LinearLayout rililayout; private List<WeMonBean.DataBeanX.DataBean> dataList = new ArrayList<>(); private int mCount = 1; private boolean isMutiChoseFlag = false; private PopupWindow popupWindow; private WheelMain wheelMain; private StringBuffer stringBuffer = new StringBuffer(); @Override public void initView() { chooseTimeTv = findViewById(R.id.choosetimetv); rililayout = findViewById(R.id.rili_layout); startTimelayout = findViewById(R.id.starttimelayout); endTimelayout = findViewById(R.id.endtimelayout); backImg = findViewById(R.id.backImage); submittext = findViewById(R.id.submittext); title = findViewById(R.id.titletext); submittext.setVisibility(View.VISIBLE); submittext.setText(mRootView.getContext().getString(R.string.tongjitext)); backImg.setVisibility(View.VISIBLE); title.setVisibility(View.INVISIBLE); startTimeTv = findViewById(R.id.starttimetv); endTimeTv = findViewById(R.id.endtimetv); startTimeTv.setText(Util.getToady2(new Date())); endTimeTv.setText(Util.getTomorrowDay(new Date())); tongjiRecyclerView = findViewById(R.id.tongjiRecyclerView); tongjiRecyclerView.setLinearLayout(); tongjiRecyclerView.setRefreshing(true); tongjiRecyclerView.setPullRefreshEnable(false); tongjiRecyclerView.setPushRefreshEnable(true); tongjiRecyclerView.setOnPullLoadMoreListener(this); int spacingInPixels = mRootView.getContext().getResources().getDimensionPixelSize(R.dimen.space); tongjiRecyclerView.addItemDecoration(new SpaceItemDecoratio(spacingInPixels)); mRecyclerViewAdapter = new TongjiRecyclerViewAdapter(mRootView.getContext()); tongjiRecyclerView.setAdapter(mRecyclerViewAdapter); // mRecyclerViewAdapter.setListenr(new TongjiRecyclerViewAdapter.ClickListenr() { @Override public void onClickEvent(int positon) { WeMonBean.DataBeanX.DataBean dataBean = dataList.get(positon); mPresent.logicItemClickHandler(dataBean); } @Override public void onMutiItemClick(int position) { TongjiRecyclerViewAdapter.ViewHolder holder = (TongjiRecyclerViewAdapter.ViewHolder)tongjiRecyclerView.getRecyclerView().findViewHolderForAdapterPosition(position); holder.carChooseImg.toggle(); TongjiRecyclerViewAdapter.getIsSelected().put(position,holder.carChooseImg.isChecked()); } }); } @Override public int getLayoutId() { return R.layout.activity_tongji; } @Override public void bindEvent() { EventHelper.click(mPresent,backImg,submittext,startTimelayout,endTimelayout,chooseTimeTv); } public void setData(List<WeMonBean.DataBeanX.DataBean> list, int totalCount) { //设置滑动监听 tongjiRecyclerView.setScrollListener(0,totalCount); if(list.size()>0) { dataList.addAll(list); }else{ CustomDialog.show(mRootView.getContext(), "无更多数据", false, null, R.layout.nocache_dialog); CustomDialog.setAutoDismiss(true, 1500); } mRecyclerViewAdapter.addAllData(dataList); cancleAnim(); } public void cancleAnim() { tongjiRecyclerView.setPullLoadMoreCompleted(); } public void initMyTimePicker(View view) { View mview = LayoutInflater.from(mRootView.getContext()).inflate(R.layout.timepicker, null); OKlayout = (RelativeLayout) mview.findViewById(R.id.tOK); EventHelper.click(mPresent, OKlayout); TextView tv_time = (TextView) mview.findViewById(R.id.cur_time); tv_time.setText(Util.getToady(new Date())); MyPopupWin win = new MyPopupWin(); popupWindow = win.getPopup((Activity) mPresent,mview,true,0,mRootView.getContext()); popupWindow.showAtLocation(view, Gravity.CENTER, 0, 0); wheelMain = win.getWheelMain(); } //时间控件赋值 public void setTimeValue(int type) { popupWindow.dismiss(); if (type == 1) { endTimeTv.setText(wheelMain.getTime1()); }else if(type == 0) { startTimeTv.setText(wheelMain.getTime1()); } } //点击了统计按钮 public void changeToTongjiView() { if(isMutiChoseFlag) { //重新变回去 isMutiChoseFlag = false; mRecyclerViewAdapter.changeView(isMutiChoseFlag); if(rililayout.getVisibility()==View.VISIBLE) { rililayout.startAnimation(AnimationUtils.loadAnimation(mRootView.getContext(), R.anim.rili_anim_exit)); rililayout.setVisibility(View.GONE); } return; } isMutiChoseFlag = true;//变成多选布局 mRecyclerViewAdapter.changeView(isMutiChoseFlag); if(rililayout.getVisibility()==View.GONE) { rililayout.startAnimation(AnimationUtils.loadAnimation(mRootView.getContext(), R.anim.rili_anim_from)); rililayout.setVisibility(View.VISIBLE); } } @Override public void onRefresh() { } @Override public void onScrolling(int state) { if(state == 0)//停止 { if(isMutiChoseFlag) { if(rililayout.getVisibility()==View.GONE) { mHandler.postDelayed(new Runnable() { @Override public void run() { rililayout.startAnimation(AnimationUtils.loadAnimation(mRootView.getContext(), R.anim.rili_anim_from)); rililayout.setVisibility(View.VISIBLE); } },1000); } } }else if(state == 1)//滑动 { if(isMutiChoseFlag) { if(rililayout.getVisibility()==View.VISIBLE) { rililayout.startAnimation(AnimationUtils.loadAnimation(mRootView.getContext(), R.anim.rili_anim_exit)); rililayout.setVisibility(View.GONE); } } } } @Override public void onHide() { } @Override public void onShow() { } @Override public void onLoadMore() { mPresent.pullRefresh(); } public boolean checkValid() { String startTime = startTimeTv.getText().toString().trim(); String endTime = endTimeTv.getText().toString().trim(); String days = Util.differDaysBetweenDates(startTime,endTime); if(Integer.parseInt(days)>180) { MyToast.showTextToast(mRootView.getContext(),"时间间隔不能超过6个月"); return false; } if(Integer.parseInt(days)<0) { MyToast.showTextToast(mRootView.getContext(),"开始时间不能大于结束时间"); return false; } return true; } public void getSelectItems() { int selectNum = 0; stringBuffer.delete(0,stringBuffer.length()); int size = dataList.size(); for(int i =0;i<size;i++) { if (TongjiRecyclerViewAdapter.getIsSelected().get(i)) { selectNum++; stringBuffer.append(dataList.get(i).getTerminalNo()).append(","); } } if(selectNum==0) { MyToast.showTextToast(mRootView.getContext(), "请选择车辆"); return; } stringBuffer.deleteCharAt(stringBuffer.length()-1); // LogUtil.d("dfy","stringBuffer = "+stringBuffer.toString()); mPresent.callBackActivity(stringBuffer.toString(),startTimeTv.getText().toString(),endTimeTv.getText().toString(),"",""); } }
apache-2.0
datastax/java-driver
core/src/main/java/com/datastax/oss/driver/internal/core/metadata/DefaultNodeInfo.java
5705
/* * Copyright DataStax, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.datastax.oss.driver.internal.core.metadata; import com.datastax.oss.driver.api.core.metadata.EndPoint; import edu.umd.cs.findbugs.annotations.NonNull; import edu.umd.cs.findbugs.annotations.Nullable; import java.net.InetSocketAddress; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.UUID; import net.jcip.annotations.Immutable; import net.jcip.annotations.NotThreadSafe; @Immutable public class DefaultNodeInfo implements NodeInfo { public static Builder builder() { return new Builder(); } private final EndPoint endPoint; private final InetSocketAddress broadcastRpcAddress; private final InetSocketAddress broadcastAddress; private final InetSocketAddress listenAddress; private final String datacenter; private final String rack; private final String cassandraVersion; private final String partitioner; private final Set<String> tokens; private final Map<String, Object> extras; private final UUID hostId; private final UUID schemaVersion; private DefaultNodeInfo(Builder builder) { this.endPoint = builder.endPoint; this.broadcastRpcAddress = builder.broadcastRpcAddress; this.broadcastAddress = builder.broadcastAddress; this.listenAddress = builder.listenAddress; this.datacenter = builder.datacenter; this.rack = builder.rack; this.cassandraVersion = builder.cassandraVersion; this.partitioner = builder.partitioner; this.tokens = (builder.tokens == null) ? Collections.emptySet() : builder.tokens; this.hostId = builder.hostId; this.schemaVersion = builder.schemaVersion; this.extras = (builder.extras == null) ? Collections.emptyMap() : builder.extras; } @NonNull @Override public EndPoint getEndPoint() { return endPoint; } @NonNull @Override public Optional<InetSocketAddress> getBroadcastRpcAddress() { return Optional.ofNullable(broadcastRpcAddress); } @NonNull @Override public Optional<InetSocketAddress> getBroadcastAddress() { return Optional.ofNullable(broadcastAddress); } @NonNull @Override public Optional<InetSocketAddress> getListenAddress() { return Optional.ofNullable(listenAddress); } @Override public String getDatacenter() { return datacenter; } @Override public String getRack() { return rack; } @Override public String getCassandraVersion() { return cassandraVersion; } @Override public String getPartitioner() { return partitioner; } @Override public Set<String> getTokens() { return tokens; } @Override public Map<String, Object> getExtras() { return extras; } @NonNull @Override public UUID getHostId() { return hostId; } @Override public UUID getSchemaVersion() { return schemaVersion; } @NotThreadSafe public static class Builder { private EndPoint endPoint; private InetSocketAddress broadcastRpcAddress; private InetSocketAddress broadcastAddress; private InetSocketAddress listenAddress; private String datacenter; private String rack; private String cassandraVersion; private String partitioner; private Set<String> tokens; private Map<String, Object> extras; private UUID hostId; private UUID schemaVersion; public Builder withEndPoint(@NonNull EndPoint endPoint) { this.endPoint = endPoint; return this; } public Builder withBroadcastRpcAddress(@Nullable InetSocketAddress address) { this.broadcastRpcAddress = address; return this; } public Builder withBroadcastAddress(@Nullable InetSocketAddress address) { this.broadcastAddress = address; return this; } public Builder withListenAddress(@Nullable InetSocketAddress address) { this.listenAddress = address; return this; } public Builder withDatacenter(@Nullable String datacenter) { this.datacenter = datacenter; return this; } public Builder withRack(@Nullable String rack) { this.rack = rack; return this; } public Builder withCassandraVersion(@Nullable String cassandraVersion) { this.cassandraVersion = cassandraVersion; return this; } public Builder withPartitioner(@Nullable String partitioner) { this.partitioner = partitioner; return this; } public Builder withTokens(@Nullable Set<String> tokens) { this.tokens = tokens; return this; } public Builder withHostId(@NonNull UUID hostId) { this.hostId = hostId; return this; } public Builder withSchemaVersion(@Nullable UUID schemaVersion) { this.schemaVersion = schemaVersion; return this; } public Builder withExtra(@NonNull String key, @Nullable Object value) { if (value != null) { if (this.extras == null) { this.extras = new HashMap<>(); } this.extras.put(key, value); } return this; } public DefaultNodeInfo build() { return new DefaultNodeInfo(this); } } }
apache-2.0
lei-xia/helix
helix-core/src/test/java/org/apache/helix/manager/zk/TestAddBuiltInStateModelDef.java
3378
package org.apache.helix.manager.zk; /* * 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 java.util.Date; import org.apache.helix.BaseDataAccessor; import org.apache.helix.HelixAdmin; import org.apache.helix.PropertyKey; import org.apache.helix.TestHelper; import org.apache.helix.zookeeper.datamodel.ZNRecord; import org.apache.helix.ZkUnitTestBase; import org.apache.helix.integration.manager.ClusterControllerManager; import org.apache.helix.model.BuiltInStateModelDefinitions; import org.apache.zookeeper.data.Stat; import org.testng.Assert; import org.testng.annotations.Test; public class TestAddBuiltInStateModelDef extends ZkUnitTestBase { @Test public void test() throws Exception { String className = TestHelper.getTestClassName(); String methodName = TestHelper.getTestMethodName(); String clusterName = className + "_" + methodName; System.out.println("START " + clusterName + " at " + new Date(System.currentTimeMillis())); HelixAdmin admin = new ZKHelixAdmin(_gZkClient); admin.addCluster(clusterName); admin.addStateModelDef(clusterName, BuiltInStateModelDefinitions.MasterSlave.getStateModelDefinition().getId(), BuiltInStateModelDefinitions.MasterSlave.getStateModelDefinition()); ClusterControllerManager controller = new ClusterControllerManager(ZK_ADDR, clusterName); controller.syncStart(); // controller shall create all built-in state model definitions final BaseDataAccessor<ZNRecord> baseAccessor = new ZkBaseDataAccessor<ZNRecord>(_gZkClient); final PropertyKey.Builder keyBuilder = new PropertyKey.Builder(clusterName); boolean ret = TestHelper.verify(new TestHelper.Verifier() { @Override public boolean verify() throws Exception { for (BuiltInStateModelDefinitions def : BuiltInStateModelDefinitions.values()) { String path = keyBuilder.stateModelDef(def.getStateModelDefinition().getId()).getPath(); boolean exist = baseAccessor.exists(path, 0); if (!exist) { return false; } // make sure MasterSlave is not over-written if (def == BuiltInStateModelDefinitions.MasterSlave) { Stat stat = new Stat(); baseAccessor.get(path, stat, 0); if (stat.getVersion() != 0) { return false; } } } return true; } }, 10 * 1000); Assert.assertTrue(ret); controller.syncStop(); admin.dropCluster(clusterName); System.out.println("END " + clusterName + " at " + new Date(System.currentTimeMillis())); } }
apache-2.0
dongpf/hadoop-0.19.1
src/mapred/org/apache/hadoop/mapred/MapFileOutputFormat.java
4083
/** * 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.hadoop.mapred; import java.io.IOException; import java.util.Arrays; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.fs.FileUtil; import org.apache.hadoop.io.MapFile; import org.apache.hadoop.io.WritableComparable; import org.apache.hadoop.io.Writable; import org.apache.hadoop.io.SequenceFile.CompressionType; import org.apache.hadoop.io.compress.CompressionCodec; import org.apache.hadoop.io.compress.DefaultCodec; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.util.Progressable; import org.apache.hadoop.util.ReflectionUtils; /** An {@link OutputFormat} that writes {@link MapFile}s. */ public class MapFileOutputFormat extends FileOutputFormat<WritableComparable, Writable> { public RecordWriter<WritableComparable, Writable> getRecordWriter(FileSystem ignored, JobConf job, String name, Progressable progress) throws IOException { // get the path of the temporary output file Path file = FileOutputFormat.getTaskOutputPath(job, name); FileSystem fs = file.getFileSystem(job); CompressionCodec codec = null; CompressionType compressionType = CompressionType.NONE; if (getCompressOutput(job)) { // find the kind of compression to do compressionType = SequenceFileOutputFormat.getOutputCompressionType(job); // find the right codec Class<? extends CompressionCodec> codecClass = getOutputCompressorClass(job, DefaultCodec.class); codec = ReflectionUtils.newInstance(codecClass, job); } // ignore the progress parameter, since MapFile is local final MapFile.Writer out = new MapFile.Writer(job, fs, file.toString(), job.getOutputKeyClass().asSubclass( WritableComparable.class), job.getOutputValueClass().asSubclass(Writable.class), compressionType, codec, progress); return new RecordWriter<WritableComparable, Writable>() { public void write(WritableComparable key, Writable value) throws IOException { out.append(key, value); } public void close(Reporter reporter) throws IOException { out.close(); } }; } /** Open the output generated by this format. */ public static MapFile.Reader[] getReaders(FileSystem ignored, Path dir, Configuration conf) throws IOException { FileSystem fs = dir.getFileSystem(conf); Path[] names = FileUtil.stat2Paths(fs.listStatus(dir)); // sort names, so that hash partitioning works Arrays.sort(names); MapFile.Reader[] parts = new MapFile.Reader[names.length]; for (int i = 0; i < names.length; i++) { parts[i] = new MapFile.Reader(fs, names[i].toString(), conf); } return parts; } /** Get an entry from output generated by this class. */ public static <K extends WritableComparable, V extends Writable> Writable getEntry(MapFile.Reader[] readers, Partitioner<K, V> partitioner, K key, V value) throws IOException { int part = partitioner.getPartition(key, value, readers.length); return readers[part].get(key, value); } }
apache-2.0
cityindex-attic/CIAPI.Samples
STREAMINGALL_adapter/STREAMINGALL_adapter/Properties/AssemblyInfo.cs
1000
using System.Reflection; using System.Runtime.CompilerServices; // Information about this assembly is defined by the following attributes. // Change them to the values specific to your project. [assembly: AssemblyTitle ("STREAMINGALL_adapter")] [assembly: AssemblyDescription ("")] [assembly: AssemblyConfiguration ("")] [assembly: AssemblyCompany ("")] [assembly: AssemblyProduct ("")] [assembly: AssemblyCopyright ("mrdavidlaing")] [assembly: AssemblyTrademark ("")] [assembly: AssemblyCulture ("")] // The assembly version has the format "{Major}.{Minor}.{Build}.{Revision}". // The form "{Major}.{Minor}.*" will automatically update the build and revision, // and "{Major}.{Minor}.{Build}.*" will update just the revision. [assembly: AssemblyVersion ("1.0.*")] // The following attributes are used to specify the signing key for the assembly, // if desired. See the Mono documentation for more information about signing. //[assembly: AssemblyDelaySign(false)] //[assembly: AssemblyKeyFile("")]
apache-2.0
WdWeaver/openid4java-gae-hacks
src/org/openid4java/httpclient/spi/commons/CommonsGetMethod.java
415
package org.openid4java.httpclient.spi.commons; import org.apache.commons.httpclient.methods.GetMethod; import org.openid4java.httpclient.StringRequestEntity; class CommonsGetMethod extends CommonsHttpMethod { CommonsGetMethod(String url) { super(new GetMethod(url)); } @Override public void setRequestEntity(StringRequestEntity entity) { throw new UnsupportedOperationException(); } }
apache-2.0
eevans/newts
api/src/main/java/org/opennms/newts/api/Timestamp.java
4892
/* * Copyright 2014, The OpenNMS 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.opennms.newts.api; import java.io.Serializable; import java.util.Date; import java.util.Objects; import java.util.concurrent.TimeUnit; public class Timestamp implements Comparable<Timestamp>, Serializable { private static final long serialVersionUID = 8827895112055791967L; public final long m_time; public final TimeUnit m_unit; public Timestamp(long time, TimeUnit unit) { m_time = time; m_unit = unit; } private long convert(TimeUnit unit) { return unit.convert(m_time, m_unit); } public long asSeconds() { return convert(TimeUnit.SECONDS); } public long asMillis() { return convert(TimeUnit.MILLISECONDS); } public Date asDate() { return new Date(convert(TimeUnit.MILLISECONDS)); } public TimeUnit getUnit() { return m_unit; } public Timestamp plus(long value, TimeUnit units) { TimeUnit finest = finest(m_unit, units); return new Timestamp(convert(finest) + finest.convert(value, units), finest); } public Timestamp plus(Duration d) { TimeUnit finest = finest(m_unit, d.getUnit()); return new Timestamp(convert(finest) + d.convert(finest), finest); } public Timestamp minus(long value, TimeUnit units) { TimeUnit finest = finest(m_unit, units); return new Timestamp(convert(finest) - finest.convert(value, units), finest); } public Timestamp minus(Duration d) { TimeUnit finest = finest(m_unit, d.getUnit()); return new Timestamp(convert(finest) - d.convert(finest), finest); } public Duration minus(Timestamp t) { if (t.gt(this)) throw new IllegalArgumentException("you can only subtract an earlier date from a later one... negative durations don't make sense"); TimeUnit finest = finest(m_unit, t.getUnit()); return new Duration(convert(finest) - t.convert(finest), finest); } public boolean lt(Timestamp other) { return compareTo(other) < 0; } public boolean lte(Timestamp other) { return (lt(other) || equals(other)); } public boolean gt(Timestamp other) { return compareTo(other) > 0; } public boolean gte(Timestamp other) { return (gt(other) || equals(other)); } public Timestamp stepFloor(long stepSize, TimeUnit units) { return new Timestamp((convert(units) / stepSize) * stepSize, units); } public Timestamp stepFloor(Duration d) { return stepFloor(d.getDuration(), d.getUnit()); } public Timestamp stepCeiling(long stepSize, TimeUnit units) { long v = convert(units); return ((v % stepSize) == 0) ? new Timestamp(v, units) : new Timestamp(((v / stepSize) + 1) * stepSize, units); } public Timestamp stepCeiling(Duration d) { return stepCeiling(d.getDuration(), d.getUnit()); } @Override public boolean equals(Object other) { if (!(other instanceof Timestamp)) return false; return compareTo((Timestamp) other) == 0; } @Override public int hashCode() { return Objects.hashCode(Long.valueOf(convert(TimeUnit.NANOSECONDS))); } @Override public int compareTo(Timestamp o) { TimeUnit unit = finest(getUnit(), o.getUnit()); return convert(unit) < o.convert(unit) ? -1 : (convert(unit) > o.convert(unit) ? 1 : 0); } @Override public String toString() { return String.format("%s[%s]", getClass().getSimpleName(), asDate()); } public static Timestamp now() { return new Timestamp(System.currentTimeMillis(), TimeUnit.MILLISECONDS); } public static Timestamp fromEpochMillis(long millis) { return new Timestamp(millis, TimeUnit.MILLISECONDS); } public static Timestamp fromEpochSeconds(long seconds) { return new Timestamp(seconds, TimeUnit.SECONDS); } public static Timestamp fromDate(Date d) { return fromEpochMillis(d.getTime()); } static boolean isFiner(TimeUnit unit1, TimeUnit unit2) { long c = unit2.convert(1, unit1); return c == 0; } static TimeUnit finest(TimeUnit unit1, TimeUnit unit2) { return isFiner(unit1, unit2) ? unit1 : unit2; } }
apache-2.0
SENA-CEET/1349397-Trimestre-4
java/JSF/ejemploJSF2/src/main/java/co/edu/sena/ejemplojsf2/model/entities/TipoInstructor.java
3591
/* * 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 co.edu.sena.ejemplojsf2.model.entities; import java.io.Serializable; import java.util.Collection; import javax.persistence.Basic; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.Id; import javax.persistence.NamedQueries; import javax.persistence.NamedQuery; import javax.persistence.OneToMany; import javax.persistence.Table; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlTransient; /** * * @author Enrique */ @Entity @Table(name = "tipo_instructor") @XmlRootElement @NamedQueries({ @NamedQuery(name = "TipoInstructor.findAll", query = "SELECT t FROM TipoInstructor t") , @NamedQuery(name = "TipoInstructor.findByModalidad", query = "SELECT t FROM TipoInstructor t WHERE t.modalidad = :modalidad") , @NamedQuery(name = "TipoInstructor.findByEstado", query = "SELECT t FROM TipoInstructor t WHERE t.estado = :estado")}) public class TipoInstructor implements Serializable { private static final long serialVersionUID = 1L; @Id @Basic(optional = false) @NotNull @Size(min = 1, max = 30) @Column(name = "modalidad", nullable = false, length = 30) private String modalidad; @Basic(optional = false) @NotNull @Column(name = "estado", nullable = false) private boolean estado; @OneToMany(cascade = CascadeType.ALL, mappedBy = "tipoInstructor1", fetch = FetchType.LAZY) private Collection<InstructorHasTrimestre> instructorHasTrimestreCollection; public TipoInstructor() { } public TipoInstructor(String modalidad) { this.modalidad = modalidad; } public TipoInstructor(String modalidad, boolean estado) { this.modalidad = modalidad; this.estado = estado; } public String getModalidad() { return modalidad; } public void setModalidad(String modalidad) { this.modalidad = modalidad; } public boolean getEstado() { return estado; } public void setEstado(boolean estado) { this.estado = estado; } @XmlTransient public Collection<InstructorHasTrimestre> getInstructorHasTrimestreCollection() { return instructorHasTrimestreCollection; } public void setInstructorHasTrimestreCollection(Collection<InstructorHasTrimestre> instructorHasTrimestreCollection) { this.instructorHasTrimestreCollection = instructorHasTrimestreCollection; } @Override public int hashCode() { int hash = 0; hash += (modalidad != null ? modalidad.hashCode() : 0); return hash; } @Override public boolean equals(Object object) { // TODO: Warning - this method won't work in the case the id fields are not set if (!(object instanceof TipoInstructor)) { return false; } TipoInstructor other = (TipoInstructor) object; if ((this.modalidad == null && other.modalidad != null) || (this.modalidad != null && !this.modalidad.equals(other.modalidad))) { return false; } return true; } @Override public String toString() { return "co.edu.sena.ejemplojsf2.model.entities.TipoInstructor[ modalidad=" + modalidad + " ]"; } }
apache-2.0
moreus/hadoop
hadoop-0.10.0/src/java/org/apache/hadoop/mapred/InputFormatBase.java
6829
/** * 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.hadoop.mapred; import java.io.FileNotFoundException; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import org.apache.commons.logging.*; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.fs.PathFilter; /** A base class for {@link InputFormat}. */ public abstract class InputFormatBase implements InputFormat { public static final Log LOG = LogFactory.getLog("org.apache.hadoop.mapred.InputFormatBase"); private static final double SPLIT_SLOP = 1.1; // 10% slop private long minSplitSize = 1; private static final PathFilter hiddenFileFilter = new PathFilter(){ public boolean accept( Path p ){ String name = p.getName(); return !name.startsWith("_") && !name.startsWith("."); } }; protected void setMinSplitSize(long minSplitSize) { this.minSplitSize = minSplitSize; } /** * Is the given filename splitable? Usually, true, but if the file is * stream compressed, it will not be. * @param fs the file system that the file is on * @param filename the file name to check * @return is this file splitable? */ protected boolean isSplitable(FileSystem fs, Path filename) { return true; } public abstract RecordReader getRecordReader(InputSplit split, JobConf job, Reporter reporter) throws IOException; /** List input directories. * Subclasses may override to, e.g., select only files matching a regular * expression. * * @param job the job to list input paths for * @return array of Path objects * @throws IOException if zero items. */ protected Path[] listPaths(JobConf job) throws IOException { Path[] dirs = job.getInputPaths(); if (dirs.length == 0) { throw new IOException("No input paths specified in job"); } List<Path> result = new ArrayList(); for (Path p: dirs) { FileSystem fs = p.getFileSystem(job); Path[] matches = fs.listPaths(fs.globPaths(p, hiddenFileFilter),hiddenFileFilter); for (Path match: matches) { result.add(fs.makeQualified(match)); } } return (Path[])result.toArray(new Path[result.size()]); } public void validateInput(JobConf job) throws IOException { Path[] inputDirs = job.getInputPaths(); if (inputDirs.length == 0) { throw new IOException("No input paths specified in input"); } List<IOException> result = new ArrayList(); int totalFiles = 0; for (Path p: inputDirs) { FileSystem fs = p.getFileSystem(job); if (fs.exists(p)) { // make sure all paths are files to avoid exception // while generating splits for (Path subPath : fs.listPaths(p, hiddenFileFilter)) { FileSystem subFS = subPath.getFileSystem(job); if (!subFS.isFile(subPath)) { result.add(new IOException( "Input path is not a file : " + subPath)); } else { totalFiles++; } } } else { Path [] paths = fs.globPaths(p, hiddenFileFilter); if (paths.length == 0) { result.add( new IOException("Input Pattern " + p + " matches 0 files")); } else { // validate globbed paths for (Path gPath : paths) { FileSystem gPathFS = gPath.getFileSystem(job); if (!gPathFS.exists(gPath)) { result.add( new FileNotFoundException( "Input path doesnt exist : " + gPath)); } } totalFiles += paths.length ; } } } if (!result.isEmpty()) { throw new InvalidInputException(result); } // send output to client. LOG.info("Total input paths to process : " + totalFiles); } /** Splits files returned by {@link #listPaths(JobConf)} when * they're too big.*/ public InputSplit[] getSplits(JobConf job, int numSplits) throws IOException { Path[] files = listPaths(job); long totalSize = 0; // compute total size for (int i = 0; i < files.length; i++) { // check we have valid files Path file = files[i]; FileSystem fs = file.getFileSystem(job); if (fs.isDirectory(file) || !fs.exists(file)) { throw new IOException("Not a file: "+files[i]); } totalSize += fs.getLength(files[i]); } long goalSize = totalSize / (numSplits == 0 ? 1 : numSplits); long minSize = Math.max(job.getLong("mapred.min.split.size", 1), minSplitSize); ArrayList splits = new ArrayList(numSplits); // generate splits for (int i = 0; i < files.length; i++) { Path file = files[i]; FileSystem fs = file.getFileSystem(job); long length = fs.getLength(file); if (isSplitable(fs, file)) { long blockSize = fs.getBlockSize(file); long splitSize = computeSplitSize(goalSize, minSize, blockSize); long bytesRemaining = length; while (((double) bytesRemaining)/splitSize > SPLIT_SLOP) { splits.add(new FileSplit(file, length-bytesRemaining, splitSize, job)); bytesRemaining -= splitSize; } if (bytesRemaining != 0) { splits.add(new FileSplit(file, length-bytesRemaining, bytesRemaining, job)); } } else { if (length != 0) { splits.add(new FileSplit(file, 0, length, job)); } } } LOG.debug( "Total # of splits: " + splits.size() ); return (FileSplit[])splits.toArray(new FileSplit[splits.size()]); } private static long computeSplitSize(long goalSize, long minSize, long blockSize) { return Math.max(minSize, Math.min(goalSize, blockSize)); } }
apache-2.0
mokelab/android-RecyclerViewUtils
lib/src/main/java/com/mokelab/libs/recyclerview/BaseViewHolder.java
828
package com.mokelab.libs.recyclerview; import android.support.v7.widget.RecyclerView; import android.view.View; /** * Base ViewHolder. This holder has section and position in section */ public class BaseViewHolder extends RecyclerView.ViewHolder { public int mSection; public int mPositionInSection; public OnItemClickListener mListener; public BaseViewHolder(View itemView) { super(itemView); } public BaseViewHolder(View itemView, OnItemClickListener l) { super(itemView); mListener = l; itemView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (mListener == null) { return; } mListener.onItemClick(mSection, mPositionInSection); } }); } }
apache-2.0
yevhen/Orleankka
Samples/CSharp/EventSourcing/Idiomatic/Infrastructure.cs
1615
using System; using System.Collections.Generic; using System.Threading.Tasks; using Orleankka; using Orleankka.Meta; namespace Example { public abstract class EventSourcedActor : DispatchActorGrain { StreamRef stream; public override Task<object> Receive(object message) { switch (message) { case Activate _: stream = System.StreamOf("sms", $"{GetType().Name}-{Id}"); return Result(Done); case Command cmd: return HandleCommand(cmd); case Query query: return HandleQuery(query); default: return base.Receive(message); } } Task<object> HandleQuery(Query query) => Result(Dispatcher.DispatchResult(this, query)); async Task<object> HandleCommand(Command cmd) { var events = Dispatcher.DispatchResult<IEnumerable<Event>>(this, cmd); foreach (var @event in events) { Dispatcher.Dispatch(this, @event); await Project(@event); } return events; } Task Project(Event @event) { var envelope = Wrap(@event); return stream.Push(envelope); } object Wrap(Event @event) { var envelopeType = typeof(EventEnvelope<>).MakeGenericType(@event.GetType()); return Activator.CreateInstance(envelopeType, Id, @event); } } }
apache-2.0
AspiroTV/Connect-SDK-Android-Core
test/src/com/connectsdk/service/NetCastTVServiceTest.java
1525
package com.connectsdk.service; import com.connectsdk.service.config.ServiceConfig; import com.connectsdk.service.config.ServiceDescription; import junit.framework.Assert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mockito; import org.robolectric.RobolectricTestRunner; import org.robolectric.annotation.Config; @RunWith(RobolectricTestRunner.class) @Config(manifest = Config.NONE) public class NetCastTVServiceTest { private NetcastTVService service; private ServiceDescription serviceDescription; private ServiceConfig serviceConfig; @Before public void setUp() { serviceDescription = Mockito.mock(ServiceDescription.class); serviceConfig = Mockito.mock(ServiceConfig.class); service = new NetcastTVService(serviceDescription, serviceConfig); } @Test public void testDecToHex() { Assert.assertEquals("0000000000000010", service.decToHex("16")); } @Test public void testDecToHexWithNullArgument() { Assert.assertEquals(null, service.decToHex(null)); } @Test public void testDecToHexWithEmptyArgument() { Assert.assertEquals(null, service.decToHex("")); } @Test public void testDecToHexWithWrongArgument() { Assert.assertEquals(null, service.decToHex("Not a number")); } @Test public void testDecToHexWithWrongCharactersArgument() { Assert.assertEquals("0000000000000010", service.decToHex(" 16\r\n")); } }
apache-2.0
theodi/odi-chef
site-cookbooks/odc-tools/metadata.rb
277
name 'odc-tools' maintainer 'The Open Data Institute' maintainer_email 'tech@theodi.org' license 'MIT' description 'Installs/Configures odc-tools' long_description IO.read(File.join(File.dirname(__FILE__), 'README.md')) version '0.1.0'
apache-2.0
aslanbekirov/crate
sql/src/main/java/io/crate/analyze/CopyToAnalyzedStatement.java
4924
/* * Licensed to Crate under one or more contributor license agreements. * See the NOTICE file distributed with this work for additional * information regarding copyright ownership. Crate 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. * * However, if you have executed another commercial license agreement * with Crate these terms will supersede the license and you may use the * software solely pursuant to the terms of the relevant commercial * agreement. */ package io.crate.analyze; import com.google.common.base.MoreObjects; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import io.crate.analyze.relations.AnalyzedRelation; import io.crate.analyze.relations.AnalyzedRelationVisitor; import io.crate.analyze.relations.QueriedDocTable; import io.crate.analyze.symbol.Field; import io.crate.analyze.symbol.Symbol; import io.crate.exceptions.ColumnUnknownException; import io.crate.metadata.ColumnIdent; import io.crate.metadata.Path; import io.crate.planner.projection.WriterProjection; import org.elasticsearch.common.settings.Settings; import javax.annotation.Nullable; import javax.print.attribute.standard.Compression; import java.util.List; import java.util.Map; public class CopyToAnalyzedStatement extends AbstractCopyAnalyzedStatement implements AnalyzedRelation { private final QueriedDocTable subQueryRelation; private final boolean columnsDefined; @Nullable private final WriterProjection.CompressionType compressionType; @Nullable private final WriterProjection.OutputFormat outputFormat; @Nullable private final List<String> outputNames; private final boolean isDirectoryUri; /* * add values that should be added or overwritten * all symbols must normalize to literals on the shard level. */ private final Map<ColumnIdent, Symbol> overwrites; public CopyToAnalyzedStatement(QueriedDocTable subQueryRelation, Settings settings, Symbol uri, boolean isDirectoryUri, @Nullable WriterProjection.CompressionType compressionType, @Nullable WriterProjection.OutputFormat outputFormat, @Nullable List<String> outputNames, boolean columnsDefined, @Nullable Map<ColumnIdent, Symbol> overwrites) { super(settings, uri); this.subQueryRelation = subQueryRelation; this.columnsDefined = columnsDefined; this.compressionType = compressionType; this.outputNames = outputNames; this.outputFormat = outputFormat; this.isDirectoryUri = isDirectoryUri; this.overwrites = MoreObjects.firstNonNull(overwrites, ImmutableMap.<ColumnIdent, Symbol>of()); } public QueriedDocTable subQueryRelation() { return subQueryRelation; } public boolean columnsDefined() { return columnsDefined; } @Nullable public WriterProjection.CompressionType compressionType() { return compressionType; } @Nullable public WriterProjection.OutputFormat outputFormat() { return outputFormat; } @Nullable public List<String> outputNames() { return outputNames; } public boolean isDirectoryUri() { return isDirectoryUri; } public Map<ColumnIdent, Symbol> overwrites() { return this.overwrites; } @Override public <C, R> R accept(AnalyzedStatementVisitor<C, R> analyzedStatementVisitor, C context) { return analyzedStatementVisitor.visitCopyToStatement(this, context); } @Nullable @Override public Field getField(Path path) { throw new UnsupportedOperationException("getField not implemented on CopyToAnalyzedStatement"); } @Nullable @Override public Field getWritableField(Path path) throws UnsupportedOperationException, ColumnUnknownException { throw new UnsupportedOperationException("CopyToAnalyzedStatement is not writable"); } @Override public List<Field> fields() { return ImmutableList.of(); } @Override public <C, R> R accept(AnalyzedRelationVisitor<C, R> visitor, C context) { return visitor.visitCopyToAnalyzedStatement(this, context); } }
apache-2.0
mhdSid/gulp
gulp.config.js
963
(function() { module.exports = function () { var GlobalConfig = { env: process.env.NODE_ENV, appName: 'App', appPath: 'app/', // configuration used in the app depending on the development environment inAppConfig: require('./config/' + process.env.NODE_ENV + '.json') }; return { inAppConfig: GlobalConfig.inAppConfig, appName: GlobalConfig.appName, environment: GlobalConfig.env, localBuild: 'build', appPath: GlobalConfig.appPath, lessPath: GlobalConfig.appPath + "_public/styles/less/*.less", cssPath: "build/_public/styles/*.css", fontsPath: GlobalConfig.appPath + "_public/styles/fonts/*.*", htmlPath: GlobalConfig.appPath + "**/*.html", imagesPath: GlobalConfig.appPath + "_public/images/*.*", tsPath: GlobalConfig.appPath + "**/*.ts", jsPath: ["build/*.module.js", "build/app.*.js", "build/**/*.js"], index: "index.html", serverBuild: "./public/build/" }; }; }());
apache-2.0
unchartedsoftware/salt
src/main/scala/software/uncharted/salt/core/generation/output/SeriesData.scala
3351
/* * Copyright 2016 Uncharted Software Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package software.uncharted.salt.core.generation.output import software.uncharted.salt.core.projection.Projection import software.uncharted.salt.core.util.SparseArray import scala.reflect.ClassTag /** * A thin wrapper class for the output of a tile generation, * for a single Series * * @param coords the tile coordinates for this aggregator * @param bins the output values of bin aggregators * @param tileMeta the output value of the tile aggregator * @tparam TC the abstract type representing a tile coordinate. * @tparam BC the abstract type representing a bin coordinate. Must be something that can be represented in 1 dimension. * @tparam V Output data type for bin aggregators, and input for tile aggregator * @tparam X Output data type for tile aggregators */ class SeriesData[ TC, BC, @specialized(Int, Long, Double) V, @specialized(Int, Long, Double) X ] ( val projection: Projection[_, TC, BC], val maxBin: BC, val coords: TC, val bins: SparseArray[V], val tileMeta: Option[X] ) extends Serializable { /** * Retrieve a value from this SeriesData's bins using a bin coordinate * @param bin A bin coordinate * @return the corresponding value */ def apply(bin: BC): V = { bins(projection.binTo1D(bin, maxBin)) } /** * Combine this SeriesData with another congruent one. Congruent SeriesData have an identical * tile coordinate and the same bin dimensions. The new SeriesData will inherit this SeriesData's * Projection. * * @param that the SeriesData to merge with * @param binMerge the function for merging bin values * @param tileMetaMerge the Optional function for merging tile metadata * @tparam OV other's bin value type * @tparam OX other's tile metadata type * @tparam NV output bin value type * @tparam NX output tile metadata type */ @throws(classOf[SeriesDataMergeException]) def merge[OV, OX, NV: ClassTag, NX]( that: SeriesData[TC, BC, OV, OX], binMerge: (V, OV) => NV, tileMetaMerge: Option[(X, OX) => NX] = None ): SeriesData[TC, BC, NV, NX] = { if (this.bins.length != that.bins.length) { throw new SeriesDataMergeException("Two Series with different bin dimensions cannot be merged.") } else if (this.coords != that.coords) { throw new SeriesDataMergeException("SeriesData with nonmatching tile coordinates cannot be merged.") } val newBins = SparseArray.merge(binMerge)(this.bins, that.bins) // compute new meta val newMeta: Option[NX] = for ( mergeFcn <- tileMetaMerge; thisMeta <- this.tileMeta; thatMeta <- that.tileMeta ) yield { mergeFcn(thisMeta, thatMeta) } new SeriesData(projection, maxBin, coords, newBins, newMeta) } }
apache-2.0
m-m-m/client
impl-gwt/src/main/java/net/sf/mmm/client/impl/base/place/package-info.java
418
/* Copyright (c) The m-m-m Team, Licensed under the Apache License, Version 2.0 * http://www.apache.org/licenses/LICENSE-2.0 */ /** * Contains the place related base classes for this client framework. * <a name="documentation"></a><h2>Client Base Place (GWT)</h2> * This package contains the {@link net.sf.mmm.client.ui.api.dialog.DialogPlace} related base classes. */ package net.sf.mmm.client.impl.base.place;
apache-2.0
trane/finch
demo/src/main/scala/io/finch/demo/package.scala
2559
/* * Copyright 2015, by Vladimir Kostyukov and Contributors. * * This file is a part of a Finch library that may be found at * * https://github.com/finagle/finch * * 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. * * Contributor(s): - */ package io.finch import java.util.concurrent.ConcurrentHashMap import java.util.concurrent.atomic.AtomicLong import scala.collection.JavaConverters._ import com.twitter.util.Future /** * The ''demo'' project shows the usage of Finch's basic blocks for building a purely functional REST API backend * emulating a set of services working with ''users'' and their ''tickets'' (i.e., cinema tickets). * * The following packages represent the backend: * * - [[demo.model]] - domain model classes: `User` and `Ticket` * - [[demo.reader]] - [[io.finch.request.RequestReader]]s for models * - [[demo.service]] - the application services * - [[demo.endpoint]] - [[io.finch.route.Router]]s for services (endpoints) */ package object demo { import model._ // A custom request type that wraps an `HttpRequest`. // We prefer composition over inheritance. case class AuthRequest(http: HttpRequest) // We define an implicit view from `AuthRequest to `HttpRequest`, // so we can get two benefits: // 1. We can treat an `Endpoint` as a `Service`, since it will be implicitly converted. // 2. We can treat an `AuthRequest` as ''HttpRequest'' and pass it to `RequestReader`. implicit val authReqEv = (req: AuthRequest) => req.http // A thread-safe ids generator. object Id { private val self = new AtomicLong(0) def apply(): Long = self.getAndIncrement } // An abstraction that represents an async interface to a database. object Db { // An underlying map. private val map = new ConcurrentHashMap[Long, User]().asScala def select(id: Long): Future[Option[User]] = map.get(id).toFuture def all: Future[Seq[User]] = map.values.toSeq.toFuture def insert(id: Long, u: User): Future[User] = { map += (id -> u) u.toFuture } } }
apache-2.0
BigBoss424/portfolio
v6/node_modules/sitemap/index.d.ts
159
export * from './lib/sitemap'; import errors = require('./lib/errors'); export { errors }; /** * Framework version. */ export declare const version: string;
apache-2.0
priimak/cloudkeeper
cloudkeeper-core/cloudkeeper-interpreter/src/test/java/com/svbio/cloudkeeper/interpreter/DependencyGraphTest.java
9730
package com.svbio.cloudkeeper.interpreter; import com.svbio.cloudkeeper.interpreter.DependencyGraph.DependencyGraphNode; import com.svbio.cloudkeeper.interpreter.DependencyGraph.InPortNode; import com.svbio.cloudkeeper.interpreter.DependencyGraph.OutPortNode; import com.svbio.cloudkeeper.interpreter.DependencyGraph.SubmoduleNode; import com.svbio.cloudkeeper.model.immutable.execution.ExecutionTrace; import com.svbio.cloudkeeper.model.runtime.element.module.RuntimeInPort; import com.svbio.cloudkeeper.model.runtime.element.module.RuntimeModule; import com.svbio.cloudkeeper.model.runtime.element.module.RuntimeParentModule; import com.svbio.cloudkeeper.model.runtime.element.module.RuntimePort; import com.svbio.cloudkeeper.model.runtime.execution.RuntimeExecutionTrace.Type; import org.testng.Assert; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import javax.annotation.Nullable; import java.util.Arrays; import java.util.BitSet; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.stream.Collectors; import java.util.stream.Stream; public class DependencyGraphTest { /** * Composite-module context of the following form, where each child module has two in-ports {@code <name>x} and * {@code <name>y}. Submodule {@code a} has two out-ports {@code ap} and {@code aq}, submodule {@code b} has one * out-port {@code bp}, and submodule {@code c} has no out-ports. * * {@code * ------------ * x --|------ b ---- p * | \ / | * | a | * | / \ | * y --|------ c | * | \ | * | ----------- q * ------------ * } */ private static final RuntimeParentModule COMPOSITE_MODULE = (RuntimeParentModule) CompositeModuleContext.fromConnections(Arrays.asList( "x -> a.ax", "y -> a.ay", "x -> b.bx", "a.ap -> b.by", "a.aq -> c.cx", "y -> c.cy", "b.bp -> p", "y -> q" )) .getModule(); private DependencyGraph diamondGraph; @BeforeClass public void setup() { BitSet allOutPorts = new BitSet(); allOutPorts.set(0, COMPOSITE_MODULE.getOutPorts().size()); diamondGraph = new DependencyGraph(COMPOSITE_MODULE, allOutPorts); } @Test public void nodeStream() { Set<String> executionTracesOnPath = diamondGraph.nodeStream() .map(DependencyGraphNode::getExecutionTrace) .map(ExecutionTrace::toString) .collect(Collectors.toSet()); Assert.assertEquals( executionTracesOnPath, new HashSet<>(Arrays.asList( ":in:x", ":in:y", "/a", "/a:in:ax", "/a:in:ay", "/b", "/b:in:bx", "/b:in:by", "/c", "/c:in:cx", "/c:in:cy", ":out:p", ":out:q" )) ); } @Test public void inPortNodes() { List<InPortNode> inPortNodes = diamondGraph.inPortNodes(); Assert.assertEquals(COMPOSITE_MODULE.getInPorts().size(), 2); Assert.assertEquals( inPortNodes.stream().map(InPortNode::getElement).collect(Collectors.toList()), COMPOSITE_MODULE.getInPorts() ); Assert.assertTrue( COMPOSITE_MODULE.getInPorts().stream() .allMatch(inPort -> inPortNodes.get(inPort.getInIndex()) == diamondGraph.sourceNode(inPort)) ); } @Test public void outPortNodes() { List<OutPortNode> outPortNodes = diamondGraph.outPortNodes(); Assert.assertEquals(COMPOSITE_MODULE.getOutPorts().size(), 2); Assert.assertEquals( outPortNodes.stream().map(OutPortNode::getElement).collect(Collectors.toList()), COMPOSITE_MODULE.getOutPorts() ); Assert.assertTrue( COMPOSITE_MODULE.getOutPorts().stream() .allMatch(outPort -> outPortNodes.get(outPort.getOutIndex()) == diamondGraph.targetNode(outPort)) ); } @Test public void submoduleNode() { List<SubmoduleNode> submoduleNodes = diamondGraph.submoduleNodes(); Assert.assertEquals(COMPOSITE_MODULE.getModules().size(), 3); Assert.assertEquals( submoduleNodes.stream().map(SubmoduleNode::getElement).collect(Collectors.toList()), COMPOSITE_MODULE.getModules() ); } @Test public void onPathToOutPort() { Set<String> executionTracesOnPath = diamondGraph.nodeStream() .filter(DependencyGraphNode::isOnPathToOutPort) .map(DependencyGraphNode::getExecutionTrace) .map(ExecutionTrace::toString) .collect(Collectors.toSet()); Assert.assertEquals( executionTracesOnPath, new HashSet<>(Arrays.asList( ":in:x", ":in:y", "/a", "/a:in:ax", "/a:in:ay", "/b", "/b:in:bx", "/b:in:by", ":out:p", ":out:q" )) ); } private DependencyGraphNode node(String trace) { ExecutionTrace nodeTrace = ExecutionTrace.valueOf(trace); int traceSize = nodeTrace.size(); Type type = nodeTrace.getType(); assert (traceSize == 1 && (type == Type.IN_PORT || type == Type.OUT_PORT)) || (traceSize == 2 && type == Type.MODULE) || (traceSize == 3 && type == Type.IN_PORT); boolean isSourceNode; @Nullable RuntimePort port; if (traceSize == 1) { isSourceNode = type == Type.IN_PORT; port = COMPOSITE_MODULE.getEnclosedElement(RuntimePort.class, nodeTrace.getSimpleName()); } else if (traceSize == 2) { @Nullable RuntimeModule submodule = COMPOSITE_MODULE.getEnclosedElement(RuntimeModule.class, nodeTrace.getSimpleName()); assert submodule != null; return diamondGraph.submodule(submodule); } else { isSourceNode = true; @Nullable RuntimeModule submodule = COMPOSITE_MODULE.getEnclosedElement( RuntimeModule.class, nodeTrace.asElementList().get(1).getSimpleName()); assert submodule != null; port = submodule.getEnclosedElement(RuntimeInPort.class, nodeTrace.getSimpleName()); } assert port != null; return isSourceNode ? diamondGraph.sourceNode(port) : diamondGraph.targetNode(port); } private void assertPredecessors(String node, String... predecessors) { Assert.assertEquals( node(node).predecessorStream().collect(Collectors.toSet()), Stream.of(predecessors).map(this::node).collect(Collectors.toSet()) ); } private void assertSuccessors(String node, String... successors) { Assert.assertEquals( node(node).successorStream().collect(Collectors.toSet()), Stream.of(successors).map(this::node).collect(Collectors.toSet()) ); } @Test public void predecessors() { assertPredecessors(":in:x"); assertPredecessors(":in:y"); assertPredecessors("/a"); assertPredecessors("/a:in:ax", ":in:x"); assertPredecessors("/a:in:ay", ":in:y"); assertPredecessors("/b"); assertPredecessors("/b:in:bx", ":in:x"); assertPredecessors("/b:in:by", "/a", "/a:in:ax", "/a:in:ay"); assertPredecessors("/c"); assertPredecessors("/c:in:cx"); assertPredecessors("/c:in:cy"); assertPredecessors(":out:p", "/b", "/b:in:bx", "/b:in:by"); assertPredecessors(":out:q", ":in:y"); } @Test public void successors() { assertSuccessors(":in:x", "/a:in:ax", "/b:in:bx"); assertSuccessors(":in:y", "/a:in:ay", ":out:q"); assertSuccessors("/a", "/b:in:by"); assertSuccessors("/a:in:ax", "/b:in:by"); assertSuccessors("/a:in:ay", "/b:in:by"); assertSuccessors("/b", ":out:p"); assertSuccessors("/b:in:bx", ":out:p"); assertSuccessors("/b:in:by", ":out:p"); assertSuccessors("/c"); assertSuccessors("/c:in:cx"); assertSuccessors("/c:in:cy"); assertSuccessors(":out:p"); assertSuccessors(":out:q"); } @Test public void setHasValue() { DependencyGraph dependencyGraph = new DependencyGraph(COMPOSITE_MODULE, new BitSet()); InPortNode inPortNode = dependencyGraph.inPortNodes().get(0); Assert.assertEquals(inPortNode.getHasValue(), DependencyGraph.HasValue.UNKNOWN); inPortNode.setHasValue(DependencyGraph.HasValue.UNKNOWN); Assert.assertEquals(inPortNode.getHasValue(), DependencyGraph.HasValue.UNKNOWN); inPortNode.setHasValue(DependencyGraph.HasValue.PENDING_VALUE_CHECK); inPortNode.setHasValue(DependencyGraph.HasValue.PENDING_VALUE_CHECK); try { inPortNode.setHasValue(DependencyGraph.HasValue.UNKNOWN); Assert.fail(); } catch (IllegalArgumentException ignore) { } Assert.assertEquals(inPortNode.getHasValue(), DependencyGraph.HasValue.PENDING_VALUE_CHECK); inPortNode.setHasValue(DependencyGraph.HasValue.HAS_VALUE); try { inPortNode.setHasValue(DependencyGraph.HasValue.UNKNOWN); Assert.fail(); } catch (IllegalArgumentException ignore) { } try { inPortNode.setHasValue(DependencyGraph.HasValue.PENDING_VALUE_CHECK); Assert.fail(); } catch (IllegalArgumentException ignore) { } try { inPortNode.setHasValue(DependencyGraph.HasValue.NO_VALUE); Assert.fail(); } catch (IllegalArgumentException ignore) { } } }
apache-2.0
schmittjoh/jmsDoctrinePlugin
lib/Template/Passwordable.class.php
10672
<?php /* * Copyright 2010 Johannes M. Schmitt * * 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. */ /** * Adds the ability to set passwords for a record. * * @package jmsDoctrinePlugin * @subpackage Template * @author Johannes M. Schmitt <schmittjoh@gmail.com> */ class Passwordable extends Doctrine_Template { /** * Our default options * @var array */ protected $_options = array( 'password' => array( 'name' => 'password', 'type' => 'string', 'length' => 255, 'options' => array('default' => null, 'notnull' => false), ) ); /** * Make sure mandatory templates are loaded and add a password column */ public function setTableDefinition() { if ($this->getInvoker()->getTable()->hasTemplate('Timestampable') === false) throw new RuntimeException('Your '.get_class($this->getInvoker()).' model must implement the Timestampable template.'); $tmplOptions = $this->getInvoker()->getTable()->getTemplate('Timestampable')->getOptions(); if ($tmplOptions['created']['disabled'] !== false) throw new RuntimeException('The created field must be enabled in the Timestampable template.'); $this->hasColumn( $this->_options['password']['name'], $this->_options['password']['type'], $this->_options['password']['length'], $this->_options['password']['options'] ); } /** * Verifies if the given password matches this model * @author Johannes * @param string $password The password to verify * @return boolean Whether the password matches or not */ public function verifyPassword($password) { $r = $this->getInvoker(); $passwordName = $this->_options['password']['name']; $created = $r->getTable()->getTemplate('Timestampable')->getOption('created'); $created_at = $created['name']; // extract algorithm and fingerprint if (($pos = strpos($r->$passwordName, '-')) === false) throw new RuntimeException('Password format is incorrect.'); $algo = substr($r->$passwordName, 0, $pos); $fingerprint = substr($r->$passwordName, $pos+1); // set some variables $createdAt = $algo === 'tHash'? 0 : strtotime($r->$created_at); $saltLength = bcmod($r->id * $createdAt, $this->getMaxSaltLength() - $this->getMinSaltLength()) + $this->getMinSaltLength(); if ($saltLength <= $this->getMinSaltLength()) $saltLength = $this->getMinSaltLength(); // check if algorithm is available and re-generate fingerprint $fingerprintLength = strlen($this->callAlgorithm($algo, 't')); $saltPositionInFingerprint = bcmod($r->id * $createdAt, $fingerprintLength - $saltLength); $salt = substr($fingerprint, $saltPositionInFingerprint, $saltLength); $saltPositionInPassword = strlen($password)==0? 0 : bcmod($r->id * $createdAt, strlen($password)); $cFingerprint = $this->callAlgorithm($algo, substr($password, 0, $saltPositionInPassword).$salt.(substr($password, $saltPositionInPassword)).$this->getSalt(), 2); // compare fingerprints return substr($cFingerprint, 0, $saltPositionInFingerprint).$salt.substr($cFingerprint, $saltPositionInFingerprint) === $fingerprint; } /** * This is called when someone changes the password, and encrypts it. * @param string $password * @return void */ public function setPlainPassword($password) { if ($password === '') throw new InvalidArgumentException('$password cannot be empty.'); $this->getInvoker()->{$this->_options['password']['name']} = $this->generateFingerprint($password); } /** * Alias for sha1 * @param string $string * @return string */ public function tHash($string) { return sha1($string); } private function getMinSaltLength() { $length = sfConfig::get('app_jmsDoctrinePlugin_minSaltLength'); if ($length === null) throw new RuntimeException('No min salt length configured.'); $length = intval($length); if ($length <= 0) throw new RuntimeException('Min salt length must be greater than 0.'); return $length; } private function getMaxSaltLength() { $length = sfConfig::get('app_jmsDoctrinePlugin_maxSaltLength'); if ($length === null) throw new RuntimeException('No max salt length configured.'); $length = intval($length); if ($length <= 0) throw new RuntimeException('Max salt length must be greater than 0.'); if ($length <= $this->getMinSaltLength()) throw new RuntimeException('Max salt length must be greater than min salt length.'); return $length; } private function getSalt() { $salt = sfConfig::get('app_jmsDoctrinePlugin_salt'); if ($salt === null) throw new RuntimeException('No project salt configured.'); return $salt; } private function getAlgorithms() { $algos = sfConfig::get('app_jmsDoctrinePlugin_algorithms'); if ($algos === null) throw new RuntimeException('No algorithms configured.'); if (!is_array($algos)) $algos = array($algos); return $algos; } /** * Returns an array with available algorithms * @return array available algorithms */ private function getAvailableAlgorithms() { return function_exists('hash_algos')? hash_algos() : array(); } /** * Calls an algorithm and returns the generated hash * * @param string $algorithm The algorithm to use for generating a hash * @param string $string The string to generate a hash for * @param integer $times The number of times to apply the algorithm * @return string The hash after passing it to the algorithm * @throws RuntimeException */ private function callAlgorithm($algorithm, $string, $times = 1) { if (!is_int($times)) throw new InvalidArgumentException('times must be an integer.'); if ($times <= 0 || $times > 10) throw new InvalidArgumentException('times must be between 1 and 10.'); // check if this algorithm is supported by the hash() function $hashAlgos = $this->getAvailableAlgorithms(); if (in_array($algorithm, $hashAlgos, true)) { for ($i=0;$i<$times;$i++) $string = hash($algorithm, $string); return $string; } // check if model has a method with the algorithm's name $r = $this->getInvoker(); try { for ($i=0;$i<$times;$i++) $string = $r->$algorithm($string); return $string; } catch (Exception $e) {} // check if there is a function with the algorithm's name if (function_exists($algorithm)) { for ($i=0;$i<$times;$i++) $string = $algorithm($string); return $string; } throw new InvalidAlgorithmException(sprintf("The algorithm '%s' is not available.", $algorithm)); } /** * Generates a fingerprint for a password * * @param string $password The plain password * @param array|string $algos Algorithms to use for generating the fingerprint * @return string The fingerprint for the password */ private function generateFingerprint($password, $algos = null) { if ($algos === null) $algos = $this->getAlgorithms(); if (is_string($algos)) $algos = array($algos); if (!is_array($algos)) throw new RuntimeException('algos must be an array with algorithms.'); if (strlen($password) == 0) throw new InvalidArgumentException('Password cannot be empty.'); $r = $this->getInvoker(); $created = $r->getTable()->getTemplate('Timestampable')->getOption('created'); $created_at = $created['name']; $passwordName = $this->_options['password']['name']; // generate salt $createdAt = ($r->$created_at === null || $r->id === null)? 0 : strtotime($r->$created_at); $saltLength = bcmod($r->id*$createdAt, $this->getMaxSaltLength() - $this->getMinSaltLength()) + $this->getMinSaltLength(); if ($saltLength <= $this->getMinSaltLength()) $saltLength = $this->getMinSaltLength(); $salt = $this->getRandomString($saltLength); $saltPosition = bcmod($r->id * $createdAt, strlen($password)); if ($createdAt === 0) $algos = array('tHash'); // generate basic fingerprint $fingerprint = null; foreach ($algos as $algo) { try { $length = strlen($this->callAlgorithm($algo, $password)); $fingerprint = $this->callAlgorithm($algo, substr($password, 0, $saltPosition).$salt.substr($password, $saltPosition) . $this->getSalt(), 2); break; } catch (InvalidAlgorithmException $e) {} } // add salt and used algorithm to the fingerprint if ($fingerprint !== null) { $saltPosition = bcmod($r->id*$createdAt, strlen($fingerprint)-strlen($salt)); $fingerprint = $algo.'-'.substr($fingerprint, 0, $saltPosition).$salt.substr($fingerprint, $saltPosition); } else throw new RuntimeException(sprintf("None of the algorithms '%s' exists.", implode(',', $algos))); return $fingerprint; } /** * Generates a random string. Several different algorithms are used to try to * get a cryptographically strong, and actually random result. * * @param int $length The length of the generated string. * @return string The generated string. */ private function getRandomString($length) { if (!is_int($length)) throw new InvalidArgumentException('length must be an integer.'); if ($length <= 0) throw new InvalidArgumentException('length must be greater than zero.'); // try OpenSSL's random pseudo bytes function if (function_exists('openssl_random_pseudo_bytes')) { $bytes = openssl_random_pseudo_bytes($length, $strong); if ($strong === true && $bytes !== false) { $hex = bin2hex($bytes); return substr($hex, 0, $length); } } // use mt_rand to generate our random string $chars = 'abcdef0123456789'; $max = strlen($chars)-1; $string = ''; while (strlen($string) < $length) $string .= substr($chars, mt_rand(0, $max), 1); return $string; } }
apache-2.0
vam-google/google-cloud-java
google-api-grpc/proto-google-cloud-bigquerydatatransfer-v1/src/main/java/com/google/cloud/bigquery/datatransfer/v1/GetDataSourceRequestOrBuilder.java
907
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/cloud/bigquery/datatransfer/v1/datatransfer.proto package com.google.cloud.bigquery.datatransfer.v1; public interface GetDataSourceRequestOrBuilder extends // @@protoc_insertion_point(interface_extends:google.cloud.bigquery.datatransfer.v1.GetDataSourceRequest) com.google.protobuf.MessageOrBuilder { /** * * * <pre> * The field will contain name of the resource requested, for example: * `projects/{project_id}/dataSources/{data_source_id}` * </pre> * * <code>string name = 1;</code> */ java.lang.String getName(); /** * * * <pre> * The field will contain name of the resource requested, for example: * `projects/{project_id}/dataSources/{data_source_id}` * </pre> * * <code>string name = 1;</code> */ com.google.protobuf.ByteString getNameBytes(); }
apache-2.0
adriancl1/AK-Engine
ModuleInput.cpp
4329
#include "Globals.h" #include "Application.h" #include "Brofiler-1.1.2\Brofiler.h" #include "ModuleInput.h" #define MAX_KEYS 300 ModuleInput::ModuleInput(Application* app, bool start_enabled) : Module(app, start_enabled) { keyboard = new KEY_STATE[MAX_KEYS]; memset(keyboard, KEY_IDLE, sizeof(KEY_STATE) * MAX_KEYS); memset(mouse_buttons, KEY_IDLE, sizeof(KEY_STATE) * MAX_MOUSE_BUTTONS); name = "input"; } // Destructor ModuleInput::~ModuleInput() { delete[] keyboard; } // Called before render is available bool ModuleInput::Init(Configuration data) { BROFILER_CATEGORY("Module Input Init", Profiler::Color::AliceBlue); LOG("Init SDL input event system"); bool ret = true; SDL_Init(0); if(SDL_InitSubSystem(SDL_INIT_EVENTS) < 0) { LOG("SDL_EVENTS could not initialize! SDL_Error: %s\n", SDL_GetError()); ret = false; } return ret; } // Called every draw update update_status ModuleInput::PreUpdate(float dt) { BROFILER_CATEGORY("Module Input PreUpdate", Profiler::Color::AliceBlue); SDL_PumpEvents(); const Uint8* keys = SDL_GetKeyboardState(NULL); for(int i = 0; i < MAX_KEYS; ++i) { if(keys[i] == 1) { if(keyboard[i] == KEY_IDLE) keyboard[i] = KEY_DOWN; else keyboard[i] = KEY_REPEAT; } else { if(keyboard[i] == KEY_REPEAT || keyboard[i] == KEY_DOWN) keyboard[i] = KEY_UP; else keyboard[i] = KEY_IDLE; } } Uint32 buttons = SDL_GetMouseState(&mouse_x, &mouse_y); mouse_x /= SCREEN_SIZE; mouse_y /= SCREEN_SIZE; mouse_z = 0; for(int i = 0; i < 5; ++i) { if(buttons & SDL_BUTTON(i)) { if(mouse_buttons[i] == KEY_IDLE) mouse_buttons[i] = KEY_DOWN; else mouse_buttons[i] = KEY_REPEAT; } else { if(mouse_buttons[i] == KEY_REPEAT || mouse_buttons[i] == KEY_DOWN) mouse_buttons[i] = KEY_UP; else mouse_buttons[i] = KEY_IDLE; } } mouse_x_motion = mouse_y_motion = 0; bool quit = false; char* fileDir = nullptr; SDL_Event e; uint length; while(SDL_PollEvent(&e)) { App->imGui->ProcessEvent(&e); switch(e.type) { case SDL_MOUSEWHEEL: if (e.wheel.y == 1) { App->camera->ZoomIn(); } if (e.wheel.y == -1) { App->camera->ZoomOut(); } break; case SDL_MOUSEMOTION: mouse_x = e.motion.x / SCREEN_SIZE; mouse_y = e.motion.y / SCREEN_SIZE; mouse_x_motion = e.motion.xrel / SCREEN_SIZE; mouse_y_motion = e.motion.yrel / SCREEN_SIZE; break; case SDL_QUIT: quit = true; break; case SDL_DROPFILE: // In case if dropped file fileDir = e.drop.file; // Shows directory of dropped file LOG("%s dropped on window.", fileDir); length = strlen(fileDir); if (strcmp(&fileDir[length - 4], ".fbx") == 0 || strcmp(&fileDir[length - 4], ".FBX") == 0 || strcmp(&fileDir[length - 4], ".dae") == 0 || strcmp(&fileDir[length - 4], ".DAE") == 0) { App->sceneEditor->CreateNewGameObject(fileDir); } else if (strcmp(&fileDir[length - 4], ".wav") == 0 || strcmp(&fileDir[length - 4], ".WAV") == 0) { App->audio->PlayMusic(fileDir); } else if (strcmp(&fileDir[length - 4], ".png") == 0 || strcmp(&fileDir[length - 4], ".PNG") == 0) { App->resources->ImportFile(fileDir); } else if (strcmp(&fileDir[length - 4], ".akS") == 0) { App->sceneEditor->WantToLoadScene(fileDir); } else { LOG("Unknown file format!"); } SDL_free(fileDir); // Free dropped_filedir memory break; case SDL_WINDOWEVENT: if(e.window.event == SDL_WINDOWEVENT_RESIZED) App->renderer3D->OnResize(e.window.data1, e.window.data2); break; } } if(quit == true || keyboard[SDL_SCANCODE_ESCAPE] == KEY_UP) return UPDATE_STOP; return UPDATE_CONTINUE; } // Called before quitting bool ModuleInput::CleanUp(Configuration data) { LOG("Quitting SDL input event subsystem."); SDL_QuitSubSystem(SDL_INIT_EVENTS); return true; } void ModuleInput::OnConfiguration() { if (ImGui::CollapsingHeader("Input")) { ImGui::Text("Mouse X: %i | Mouse Y: %i", GetMouseX(), GetMouseY()); } } float ModuleInput::GetNormalizedMouseX() const { int w, h; App->window->GetWindowSize(w, h); return (float)(mouse_x / (float)w); } float ModuleInput::GetNormalizedMouseY() const { int w, h; App->window->GetWindowSize(w, h); return (float)(mouse_y / (float)h); }
apache-2.0
rdo-management/instack
setup.py
791
#!/usr/bin/env python # Copyright (c) 2013 Hewlett-Packard Development Company, L.P. # # 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. # THIS FILE IS MANAGED BY THE GLOBAL REQUIREMENTS REPO - DO NOT EDIT import setuptools setuptools.setup( setup_requires=['pbr>=1.3,<2.0'], pbr=True)
apache-2.0
radiodan/radiodan.js
test/state-emitters/test-player.js
631
'use strict'; describe('state-emitter/player', function (){ beforeEach(function(){ this.subject = require(libDir + 'state-emitters/player'); }); it('returns a object per non-matching key', function(done) { var newData = {a: '1', b: '2'}, oldData = {a: '2', b: '2'}, promise; promise = this.subject(oldData, newData); assert.isFulfilled(promise) .then(function(eventList) { assert.equal(1, eventList.length); assert.deepEqual({ eventName: 'player.a', data: { old: '2', new: '1'} }, eventList[0]); }) .then(done,done); }); });
apache-2.0
meruvian/workshop
jee/jaxrs/src/main/java/org/meruvian/workshop/jaxrs/entity/News.java
649
package org.meruvian.workshop.jaxrs.entity; import java.util.Date; public class News { private long id; private String title; private String content; private Date createDate; public long getId() { return id; } public void setId(long id) { this.id = id; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } public Date getCreateDate() { return createDate; } public void setCreateDate(Date createDate) { this.createDate = createDate; } }
apache-2.0
google/flax
examples/sst2/train.py
9394
# Copyright 2022 The Flax Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Trains an SST2 text classifier.""" from typing import Any, Callable, Dict, Iterable, Optional, Sequence, Tuple, Union from absl import logging from flax import struct from flax.metrics import tensorboard from flax.training import train_state import jax import jax.numpy as jnp import ml_collections import numpy as np import optax import tensorflow as tf import input_pipeline import models Array = jnp.ndarray Example = Dict[str, Array] TrainState = train_state.TrainState class Metrics(struct.PyTreeNode): """Computed metrics.""" loss: float accuracy: float count: Optional[int] = None @jax.vmap def sigmoid_cross_entropy_with_logits(*, labels: Array, logits: Array) -> Array: """Sigmoid cross entropy loss.""" zeros = jnp.zeros_like(logits, dtype=logits.dtype) condition = (logits >= zeros) relu_logits = jnp.where(condition, logits, zeros) neg_abs_logits = jnp.where(condition, -logits, logits) return relu_logits - logits * labels + jnp.log1p(jnp.exp(neg_abs_logits)) def get_initial_params(rng, model): """Returns randomly initialized parameters.""" token_ids = jnp.ones((2, 3), jnp.int32) lengths = jnp.ones((2,), dtype=jnp.int32) variables = model.init(rng, token_ids, lengths, deterministic=True) return variables['params'] def create_train_state(rng, config: ml_collections.ConfigDict, model): """Create initial training state.""" params = get_initial_params(rng, model) tx = optax.chain( optax.sgd(learning_rate=config.learning_rate, momentum=config.momentum), optax.additive_weight_decay(weight_decay=config.weight_decay)) state = TrainState.create(apply_fn=model.apply, params=params, tx=tx) return state def compute_metrics(*, labels: Array, logits: Array) -> Metrics: """Computes the metrics, summed across the batch if a batch is provided.""" if labels.ndim == 1: # Prevent the labels from broadcasting over the logits. labels = jnp.expand_dims(labels, axis=1) loss = sigmoid_cross_entropy_with_logits(labels=labels, logits=logits) binary_predictions = (logits >= 0.) binary_accuracy = jnp.equal(binary_predictions, labels) return Metrics( loss=jnp.sum(loss), accuracy=jnp.sum(binary_accuracy), count=logits.shape[0]) def model_from_config(config: ml_collections.ConfigDict): """Builds a text classification model from a config.""" model = models.TextClassifier( embedding_size=config.embedding_size, hidden_size=config.hidden_size, vocab_size=config.vocab_size, output_size=config.output_size, dropout_rate=config.dropout_rate, word_dropout_rate=config.word_dropout_rate, unk_idx=config.unk_idx) return model def train_step( state: TrainState, batch: Dict[str, Array], rngs: Dict[str, Any], ) -> Tuple[TrainState, Metrics]: """Train for a single step.""" # Make sure to get a new RNG at every step. step = state.step rngs = {name: jax.random.fold_in(rng, step) for name, rng in rngs.items()} def loss_fn(params): variables = {'params': params} logits = state.apply_fn( variables, batch['token_ids'], batch['length'], deterministic=False, rngs=rngs) labels = batch['label'] if labels.ndim == 1: labels = jnp.expand_dims(labels, 1) loss = jnp.mean( sigmoid_cross_entropy_with_logits(labels=labels, logits=logits)) return loss, logits grad_fn = jax.value_and_grad(loss_fn, has_aux=True) value, grads = grad_fn(state.params) (_, logits) = value new_state = state.apply_gradients(grads=grads) metrics = compute_metrics(labels=batch['label'], logits=logits) return new_state, metrics def eval_step(state: TrainState, batch: Dict[str, Array], rngs: Dict[str, Any]) -> Metrics: """Evaluate for a single step. Model should be in deterministic mode.""" variables = {'params': state.params} logits = state.apply_fn( variables, batch['token_ids'], batch['length'], deterministic=True, rngs=rngs) metrics = compute_metrics(labels=batch['label'], logits=logits) return metrics def normalize_batch_metrics( batch_metrics: Sequence[Metrics]) -> Metrics: """Consolidates and normalizes a list of per-batch metrics dicts.""" # Here we sum the metrics that were already summed per batch. total_loss = np.sum([metrics.loss for metrics in batch_metrics]) total_accuracy = np.sum([metrics.accuracy for metrics in batch_metrics]) total = np.sum([metrics.count for metrics in batch_metrics]) # Divide each metric by the total number of items in the data set. return Metrics( loss=total_loss.item() / total, accuracy=total_accuracy.item() / total) def batch_to_numpy(batch: Dict[str, tf.Tensor]) -> Dict[str, Array]: """Converts a batch with TF tensors to a batch of NumPy arrays.""" # _numpy() reuses memory, does not make a copy. # pylint: disable=protected-access return jax.tree_map(lambda x: x._numpy(), batch) def evaluate_model( eval_step_fn: Callable[..., Any], state: TrainState, batches: Union[Iterable[Example], tf.data.Dataset], epoch: int, rngs: Optional[Dict[str, Any]] = None ) -> Metrics: """Evaluate a model on a dataset.""" batch_metrics = [] for i, batch in enumerate(batches): batch = batch_to_numpy(batch) if rngs is not None: # New RNG for each step. rngs = {name: jax.random.fold_in(rng, i) for name, rng in rngs.items()} metrics = eval_step_fn(state, batch, rngs) batch_metrics.append(metrics) batch_metrics = jax.device_get(batch_metrics) metrics = normalize_batch_metrics(batch_metrics) logging.info('eval epoch %03d loss %.4f accuracy %.2f', epoch, metrics.loss, metrics.accuracy * 100) return metrics def train_epoch(train_step_fn: Callable[..., Tuple[TrainState, Metrics]], state: TrainState, train_batches: tf.data.Dataset, epoch: int, rngs: Optional[Dict[str, Any]] = None ) -> Tuple[TrainState, Metrics]: """Train for a single epoch.""" batch_metrics = [] for batch in train_batches: batch = batch_to_numpy(batch) state, metrics = train_step_fn(state, batch, rngs) batch_metrics.append(metrics) # Compute the metrics for this epoch. batch_metrics = jax.device_get(batch_metrics) metrics = normalize_batch_metrics(batch_metrics) logging.info('train epoch %03d loss %.4f accuracy %.2f', epoch, metrics.loss, metrics.accuracy * 100) return state, metrics def train_and_evaluate(config: ml_collections.ConfigDict, workdir: str) -> TrainState: """Execute model training and evaluation loop. Args: config: Hyperparameter configuration for training and evaluation. workdir: Directory where the tensorboard summaries are written to. Returns: The final train state that includes the trained parameters. """ # Prepare datasets. train_dataset = input_pipeline.TextDataset( tfds_name='glue/sst2', split='train') eval_dataset = input_pipeline.TextDataset( tfds_name='glue/sst2', split='validation') train_batches = train_dataset.get_bucketed_batches( config.batch_size, config.bucket_size, max_input_length=config.max_input_length, drop_remainder=True, shuffle=True, shuffle_seed=config.seed) eval_batches = eval_dataset.get_batches(batch_size=config.batch_size) # Keep track of vocab size in the config so that the embedder knows it. config.vocab_size = len(train_dataset.vocab) # Compile step functions. train_step_fn = jax.jit(train_step) eval_step_fn = jax.jit(eval_step) # Create model and a state that contains the parameters. rng = jax.random.PRNGKey(config.seed) model = model_from_config(config) state = create_train_state(rng, config, model) summary_writer = tensorboard.SummaryWriter(workdir) summary_writer.hparams(dict(config)) # Main training loop. logging.info('Starting training...') for epoch in range(1, config.num_epochs + 1): # Train for one epoch. rng, epoch_rng = jax.random.split(rng) rngs = {'dropout': epoch_rng} state, train_metrics = train_epoch( train_step_fn, state, train_batches, epoch, rngs) # Evaluate current model on the validation data. eval_metrics = evaluate_model(eval_step_fn, state, eval_batches, epoch) # Write metrics to TensorBoard. summary_writer.scalar('train_loss', train_metrics.loss, epoch) summary_writer.scalar( 'train_accuracy', train_metrics.accuracy * 100, epoch) summary_writer.scalar('eval_loss', eval_metrics.loss, epoch) summary_writer.scalar( 'eval_accuracy', eval_metrics.accuracy * 100, epoch) summary_writer.flush() return state
apache-2.0
bozimmerman/CoffeeMud
com/planet_ink/coffee_mud/Abilities/Spells/Spell_DivineBeauty.java
4424
package com.planet_ink.coffee_mud.Abilities.Spells; import com.planet_ink.coffee_mud.core.interfaces.*; import com.planet_ink.coffee_mud.core.*; import com.planet_ink.coffee_mud.core.collections.*; import com.planet_ink.coffee_mud.Abilities.interfaces.*; import com.planet_ink.coffee_mud.Areas.interfaces.*; import com.planet_ink.coffee_mud.Behaviors.interfaces.*; import com.planet_ink.coffee_mud.CharClasses.interfaces.*; import com.planet_ink.coffee_mud.Commands.interfaces.*; import com.planet_ink.coffee_mud.Common.interfaces.*; import com.planet_ink.coffee_mud.Exits.interfaces.*; import com.planet_ink.coffee_mud.Items.interfaces.*; import com.planet_ink.coffee_mud.Libraries.interfaces.*; import com.planet_ink.coffee_mud.Locales.interfaces.*; import com.planet_ink.coffee_mud.MOBS.interfaces.*; import com.planet_ink.coffee_mud.Races.interfaces.*; import java.util.*; /* Copyright 2003-2022 Bo Zimmerman Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ public class Spell_DivineBeauty extends Spell { @Override public String ID() { return "Spell_DivineBeauty"; } private final static String localizedName = CMLib.lang().L("Divine Beauty"); @Override public String name() { return localizedName; } private final static String localizedStaticDisplay = CMLib.lang().L("(Divine Beauty)"); @Override public String displayText() { return localizedStaticDisplay; } @Override public int abstractQuality() { return Ability.QUALITY_BENEFICIAL_OTHERS; } @Override protected int canAffectCode() { return CAN_MOBS; } @Override public int classificationCode() { return Ability.ACODE_SPELL|Ability.DOMAIN_ILLUSION; } @Override public void affectCharStats(final MOB affected, final CharStats affectableStats) { super.affectCharStats(affected,affectableStats); if(affectableStats.getStat(CharStats.STAT_CHARISMA)>=30) affectableStats.setStat(CharStats.STAT_CHARISMA,affectableStats.getStat(CharStats.STAT_CHARISMA)+1); else affectableStats.setStat(CharStats.STAT_CHARISMA,30); } @Override public void unInvoke() { if(!(affected instanceof MOB)) return; final MOB mob=(MOB)affected; super.unInvoke(); if(canBeUninvoked()) if((mob.location()!=null)&&(!mob.amDead())) mob.location().show(mob,null,CMMsg.MSG_OK_VISUAL,L("<S-NAME> begin(s) to look like <S-HIS-HER> old ugly self.")); } @Override public int castingQuality(final MOB mob, final Physical target) { if(mob!=null) { if(target instanceof MOB) { if((((MOB)target).isInCombat()) &&(!((MOB)target).charStats().getCurrentClass().baseClass().equalsIgnoreCase("Bard"))) return Ability.QUALITY_INDIFFERENT; } } return super.castingQuality(mob,target); } @Override public boolean invoke(final MOB mob, final List<String> commands, final Physical givenTarget, final boolean auto, final int asLevel) { final MOB target=this.getTarget(mob,commands,givenTarget); if(target==null) return false; if(!super.invoke(mob,commands,givenTarget,auto,asLevel)) return false; // now see if it worked final boolean success=proficiencyCheck(mob,0,auto); if(success) { final CMMsg msg=CMClass.getMsg(mob,target,this,verbalCastCode(mob,target,auto),auto?"":L("^S<S-NAME> speak(s) beautifully to <T-NAMESELF>.^?")); if(mob.location().okMessage(mob,msg)) { mob.location().send(mob,msg); if(target.location()==mob.location()) { target.location().show(target,null,CMMsg.MSG_OK_ACTION,L("<S-NAME> become(s) divinely beautiful!!!")); beneficialAffect(mob,target,asLevel,0); } } } else return beneficialWordsFizzle(mob,target,L("<S-NAME> speak(s) beautifully to <T-NAMESELF>, but nothing more happens.")); // return whether it worked return success; } }
apache-2.0
mikefero/cpp-driver
gtests/src/integration/scassandra/server/java-it-tests/driver30/src/test/java/queries/DelayTest30.java
823
/* * Copyright (C) 2016 Christopher Batey and Dogan Narinc * * 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 queries; import cassandra.CassandraExecutor30; public class DelayTest30 extends DelayTest { public DelayTest30() { super(new CassandraExecutor30(scassandra.getBinaryPort())); } }
apache-2.0
ST-DDT/CrazySpawner
src/main/java/de/st_ddt/crazyspawner/entities/meta/CustomDamage.java
295
package de.st_ddt.crazyspawner.entities.meta; import org.bukkit.metadata.MetadataValue; public interface CustomDamage extends MetadataValue { public static final String METAHEADER = "DamageMeta"; public double getMinDamage(); public double getMaxDamage(); public double getDamage(); }
apache-2.0
oehme/analysing-gradle-performance
my-app/src/test/java/org/gradle/test/performance/mediummonolithicjavaproject/p482/Test9657.java
2111
package org.gradle.test.performance.mediummonolithicjavaproject.p482; import org.junit.Test; import static org.junit.Assert.*; public class Test9657 { Production9657 objectUnderTest = new Production9657(); @Test public void testProperty0() { String value = "value"; objectUnderTest.setProperty0(value); assertEquals(value, objectUnderTest.getProperty0()); } @Test public void testProperty1() { String value = "value"; objectUnderTest.setProperty1(value); assertEquals(value, objectUnderTest.getProperty1()); } @Test public void testProperty2() { String value = "value"; objectUnderTest.setProperty2(value); assertEquals(value, objectUnderTest.getProperty2()); } @Test public void testProperty3() { String value = "value"; objectUnderTest.setProperty3(value); assertEquals(value, objectUnderTest.getProperty3()); } @Test public void testProperty4() { String value = "value"; objectUnderTest.setProperty4(value); assertEquals(value, objectUnderTest.getProperty4()); } @Test public void testProperty5() { String value = "value"; objectUnderTest.setProperty5(value); assertEquals(value, objectUnderTest.getProperty5()); } @Test public void testProperty6() { String value = "value"; objectUnderTest.setProperty6(value); assertEquals(value, objectUnderTest.getProperty6()); } @Test public void testProperty7() { String value = "value"; objectUnderTest.setProperty7(value); assertEquals(value, objectUnderTest.getProperty7()); } @Test public void testProperty8() { String value = "value"; objectUnderTest.setProperty8(value); assertEquals(value, objectUnderTest.getProperty8()); } @Test public void testProperty9() { String value = "value"; objectUnderTest.setProperty9(value); assertEquals(value, objectUnderTest.getProperty9()); } }
apache-2.0
googleads/google-ads-dotnet
src/V9/Services/MutateCampaignFeedsResponsePartialFailureSupport.cs
1604
// Copyright 2020 Google LLC. 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. // Generated code - do not edit using Google.Ads.GoogleAds.V9.Errors; using System.Collections.Generic; using Google.Protobuf.WellKnownTypes; namespace Google.Ads.GoogleAds.V9.Services { public sealed partial class MutateCampaignFeedsResponse { /// <summary> /// Gets a GoogleAdsFailure instance that combines all the errors /// from a failed API call. /// </summary> public GoogleAdsFailure PartialFailure { get { if (this.PartialFailureError == null) { return null; } GoogleAdsFailure retval = new GoogleAdsFailure(); foreach (Any any in this.PartialFailureError.Details) { GoogleAdsFailure failure = any.Unpack<GoogleAdsFailure>(); retval.Errors.AddRange(failure.Errors); } return retval; } } } }
apache-2.0
httpchannel/httpchannel
httpchannel-util/src/main/java/com/rogiel/httpchannel/http/PostRequest.java
2232
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package com.rogiel.httpchannel.http; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.List; import org.apache.http.Header; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpPost; import org.apache.http.message.BasicNameValuePair; public class PostRequest extends Request { protected final List<NameValuePair> params = new ArrayList<NameValuePair>(); public PostRequest(HttpContext ctx, String uri) { super(ctx, uri); } @Override public HttpResponse request() throws IOException { final HttpPost post = new HttpPost(uri); for(final Header header : headers) { post.addHeader(header); } post.setEntity(new UrlEncodedFormEntity(params)); return ctx.client.execute(post); } public PostRequest parameter(String name, String value) throws UnsupportedEncodingException { params.add(new BasicNameValuePair(name, value)); return this; } public PostRequest parameter(String name, int value) throws UnsupportedEncodingException { return parameter(name, Integer.toString(value)); } public PostRequest parameter(String name, boolean value) throws UnsupportedEncodingException { return parameter(name, (value ? "1" : "0")); } }
apache-2.0
111pontes/ydk-py
cisco-ios-xr/ydk/models/cisco_ios_xr/_meta/_Cisco_IOS_XR_ip_daps_oper.py
63098
import re import collections from enum import Enum from ydk._core._dm_meta_info import _MetaInfoClassMember, _MetaInfoClass, _MetaInfoEnum from ydk.types import Empty, YList, YLeafList, DELETE, Decimal64, FixedBitsDict from ydk._core._dm_meta_info import ATTRIBUTE, REFERENCE_CLASS, REFERENCE_LIST, REFERENCE_LEAFLIST, REFERENCE_IDENTITY_CLASS, REFERENCE_ENUM_CLASS, REFERENCE_BITS, REFERENCE_UNION, ANYXML_CLASS from ydk.errors import YPYError, YPYModelError from ydk.providers._importer import _yang_ns _meta_table = { 'IpAddrEnum' : _MetaInfoEnum('IpAddrEnum', 'ydk.models.cisco_ios_xr.Cisco_IOS_XR_ip_daps_oper', { 'ipv4':'ipv4', 'ipv6':'ipv6', }, 'Cisco-IOS-XR-ip-daps-oper', _yang_ns._namespaces['Cisco-IOS-XR-ip-daps-oper']), 'DapsClientEnum' : _MetaInfoEnum('DapsClientEnum', 'ydk.models.cisco_ios_xr.Cisco_IOS_XR_ip_daps_oper', { 'none':'none', 'ppp':'ppp', 'dhcp':'dhcp', 'dhcpv6':'dhcpv6', 'ipv6nd':'ipv6nd', }, 'Cisco-IOS-XR-ip-daps-oper', _yang_ns._namespaces['Cisco-IOS-XR-ip-daps-oper']), 'AddressPoolService.Nodes.Node.Pools.Pool.AddressRanges.AddressRange.StartAddressXr.Address' : { 'meta_info' : _MetaInfoClass('AddressPoolService.Nodes.Node.Pools.Pool.AddressRanges.AddressRange.StartAddressXr.Address', False, [ _MetaInfoClassMember('address-family', REFERENCE_ENUM_CLASS, 'IpAddrEnum' , 'ydk.models.cisco_ios_xr.Cisco_IOS_XR_ip_daps_oper', 'IpAddrEnum', [], [], ''' AddressFamily ''', 'address_family', 'Cisco-IOS-XR-ip-daps-oper', False), _MetaInfoClassMember('ipv4-address', ATTRIBUTE, 'str' , None, None, [], [b'(([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}]+)?'], ''' IPv4 address ''', 'ipv4_address', 'Cisco-IOS-XR-ip-daps-oper', False), _MetaInfoClassMember('ipv6-address', ATTRIBUTE, 'str' , None, None, [], [b'((:|[0-9a-fA-F]{0,4}):)([0-9a-fA-F]{0,4}:){0,5}((([0-9a-fA-F]{0,4}:)?(:|[0-9a-fA-F]{0,4}))|(((25[0-5]|2[0-4][0-9]|[01]?[0-9]?[0-9])\\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9]?[0-9])))(%[\\p{N}\\p{L}]+)?'], ''' IPv6 address ''', 'ipv6_address', 'Cisco-IOS-XR-ip-daps-oper', False), ], 'Cisco-IOS-XR-ip-daps-oper', 'address', _yang_ns._namespaces['Cisco-IOS-XR-ip-daps-oper'], 'ydk.models.cisco_ios_xr.Cisco_IOS_XR_ip_daps_oper' ), }, 'AddressPoolService.Nodes.Node.Pools.Pool.AddressRanges.AddressRange.StartAddressXr' : { 'meta_info' : _MetaInfoClass('AddressPoolService.Nodes.Node.Pools.Pool.AddressRanges.AddressRange.StartAddressXr', False, [ _MetaInfoClassMember('address', REFERENCE_CLASS, 'Address' , 'ydk.models.cisco_ios_xr.Cisco_IOS_XR_ip_daps_oper', 'AddressPoolService.Nodes.Node.Pools.Pool.AddressRanges.AddressRange.StartAddressXr.Address', [], [], ''' Address ''', 'address', 'Cisco-IOS-XR-ip-daps-oper', False), ], 'Cisco-IOS-XR-ip-daps-oper', 'start-address-xr', _yang_ns._namespaces['Cisco-IOS-XR-ip-daps-oper'], 'ydk.models.cisco_ios_xr.Cisco_IOS_XR_ip_daps_oper' ), }, 'AddressPoolService.Nodes.Node.Pools.Pool.AddressRanges.AddressRange.EndAddress.Address' : { 'meta_info' : _MetaInfoClass('AddressPoolService.Nodes.Node.Pools.Pool.AddressRanges.AddressRange.EndAddress.Address', False, [ _MetaInfoClassMember('address-family', REFERENCE_ENUM_CLASS, 'IpAddrEnum' , 'ydk.models.cisco_ios_xr.Cisco_IOS_XR_ip_daps_oper', 'IpAddrEnum', [], [], ''' AddressFamily ''', 'address_family', 'Cisco-IOS-XR-ip-daps-oper', False), _MetaInfoClassMember('ipv4-address', ATTRIBUTE, 'str' , None, None, [], [b'(([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}]+)?'], ''' IPv4 address ''', 'ipv4_address', 'Cisco-IOS-XR-ip-daps-oper', False), _MetaInfoClassMember('ipv6-address', ATTRIBUTE, 'str' , None, None, [], [b'((:|[0-9a-fA-F]{0,4}):)([0-9a-fA-F]{0,4}:){0,5}((([0-9a-fA-F]{0,4}:)?(:|[0-9a-fA-F]{0,4}))|(((25[0-5]|2[0-4][0-9]|[01]?[0-9]?[0-9])\\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9]?[0-9])))(%[\\p{N}\\p{L}]+)?'], ''' IPv6 address ''', 'ipv6_address', 'Cisco-IOS-XR-ip-daps-oper', False), ], 'Cisco-IOS-XR-ip-daps-oper', 'address', _yang_ns._namespaces['Cisco-IOS-XR-ip-daps-oper'], 'ydk.models.cisco_ios_xr.Cisco_IOS_XR_ip_daps_oper' ), }, 'AddressPoolService.Nodes.Node.Pools.Pool.AddressRanges.AddressRange.EndAddress' : { 'meta_info' : _MetaInfoClass('AddressPoolService.Nodes.Node.Pools.Pool.AddressRanges.AddressRange.EndAddress', False, [ _MetaInfoClassMember('address', REFERENCE_CLASS, 'Address' , 'ydk.models.cisco_ios_xr.Cisco_IOS_XR_ip_daps_oper', 'AddressPoolService.Nodes.Node.Pools.Pool.AddressRanges.AddressRange.EndAddress.Address', [], [], ''' Address ''', 'address', 'Cisco-IOS-XR-ip-daps-oper', False), ], 'Cisco-IOS-XR-ip-daps-oper', 'end-address', _yang_ns._namespaces['Cisco-IOS-XR-ip-daps-oper'], 'ydk.models.cisco_ios_xr.Cisco_IOS_XR_ip_daps_oper' ), }, 'AddressPoolService.Nodes.Node.Pools.Pool.AddressRanges.AddressRange.DefaultRouter.Address' : { 'meta_info' : _MetaInfoClass('AddressPoolService.Nodes.Node.Pools.Pool.AddressRanges.AddressRange.DefaultRouter.Address', False, [ _MetaInfoClassMember('address-family', REFERENCE_ENUM_CLASS, 'IpAddrEnum' , 'ydk.models.cisco_ios_xr.Cisco_IOS_XR_ip_daps_oper', 'IpAddrEnum', [], [], ''' AddressFamily ''', 'address_family', 'Cisco-IOS-XR-ip-daps-oper', False), _MetaInfoClassMember('ipv4-address', ATTRIBUTE, 'str' , None, None, [], [b'(([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}]+)?'], ''' IPv4 address ''', 'ipv4_address', 'Cisco-IOS-XR-ip-daps-oper', False), _MetaInfoClassMember('ipv6-address', ATTRIBUTE, 'str' , None, None, [], [b'((:|[0-9a-fA-F]{0,4}):)([0-9a-fA-F]{0,4}:){0,5}((([0-9a-fA-F]{0,4}:)?(:|[0-9a-fA-F]{0,4}))|(((25[0-5]|2[0-4][0-9]|[01]?[0-9]?[0-9])\\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9]?[0-9])))(%[\\p{N}\\p{L}]+)?'], ''' IPv6 address ''', 'ipv6_address', 'Cisco-IOS-XR-ip-daps-oper', False), ], 'Cisco-IOS-XR-ip-daps-oper', 'address', _yang_ns._namespaces['Cisco-IOS-XR-ip-daps-oper'], 'ydk.models.cisco_ios_xr.Cisco_IOS_XR_ip_daps_oper' ), }, 'AddressPoolService.Nodes.Node.Pools.Pool.AddressRanges.AddressRange.DefaultRouter' : { 'meta_info' : _MetaInfoClass('AddressPoolService.Nodes.Node.Pools.Pool.AddressRanges.AddressRange.DefaultRouter', False, [ _MetaInfoClassMember('address', REFERENCE_CLASS, 'Address' , 'ydk.models.cisco_ios_xr.Cisco_IOS_XR_ip_daps_oper', 'AddressPoolService.Nodes.Node.Pools.Pool.AddressRanges.AddressRange.DefaultRouter.Address', [], [], ''' Address ''', 'address', 'Cisco-IOS-XR-ip-daps-oper', False), ], 'Cisco-IOS-XR-ip-daps-oper', 'default-router', _yang_ns._namespaces['Cisco-IOS-XR-ip-daps-oper'], 'ydk.models.cisco_ios_xr.Cisco_IOS_XR_ip_daps_oper' ), }, 'AddressPoolService.Nodes.Node.Pools.Pool.AddressRanges.AddressRange' : { 'meta_info' : _MetaInfoClass('AddressPoolService.Nodes.Node.Pools.Pool.AddressRanges.AddressRange', False, [ _MetaInfoClassMember('start-address', REFERENCE_UNION, 'str' , None, None, [], [], ''' IP Address ''', 'start_address', 'Cisco-IOS-XR-ip-daps-oper', True, [ _MetaInfoClassMember('start-address', ATTRIBUTE, 'str' , None, None, [], [b'(([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}]+)?'], ''' IP Address ''', 'start_address', 'Cisco-IOS-XR-ip-daps-oper', True), _MetaInfoClassMember('start-address', ATTRIBUTE, 'str' , None, None, [], [b'((:|[0-9a-fA-F]{0,4}):)([0-9a-fA-F]{0,4}:){0,5}((([0-9a-fA-F]{0,4}:)?(:|[0-9a-fA-F]{0,4}))|(((25[0-5]|2[0-4][0-9]|[01]?[0-9]?[0-9])\\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9]?[0-9])))(%[\\p{N}\\p{L}]+)?'], ''' IP Address ''', 'start_address', 'Cisco-IOS-XR-ip-daps-oper', True), ]), _MetaInfoClassMember('allocated-addresses', ATTRIBUTE, 'int' , None, None, [('0', '4294967295')], [], ''' Number of addresses allocated ''', 'allocated_addresses', 'Cisco-IOS-XR-ip-daps-oper', False), _MetaInfoClassMember('default-router', REFERENCE_CLASS, 'DefaultRouter' , 'ydk.models.cisco_ios_xr.Cisco_IOS_XR_ip_daps_oper', 'AddressPoolService.Nodes.Node.Pools.Pool.AddressRanges.AddressRange.DefaultRouter', [], [], ''' Default router ''', 'default_router', 'Cisco-IOS-XR-ip-daps-oper', False), _MetaInfoClassMember('end-address', REFERENCE_CLASS, 'EndAddress' , 'ydk.models.cisco_ios_xr.Cisco_IOS_XR_ip_daps_oper', 'AddressPoolService.Nodes.Node.Pools.Pool.AddressRanges.AddressRange.EndAddress', [], [], ''' Range end ''', 'end_address', 'Cisco-IOS-XR-ip-daps-oper', False), _MetaInfoClassMember('excluded-addresses', ATTRIBUTE, 'int' , None, None, [('0', '4294967295')], [], ''' Number of addresses excluded ''', 'excluded_addresses', 'Cisco-IOS-XR-ip-daps-oper', False), _MetaInfoClassMember('free-addresses', ATTRIBUTE, 'int' , None, None, [('0', '4294967295')], [], ''' Number of addresses free ''', 'free_addresses', 'Cisco-IOS-XR-ip-daps-oper', False), _MetaInfoClassMember('network-blocked-status', ATTRIBUTE, 'int' , None, None, [('0', '4294967295')], [], ''' Is network blocked ''', 'network_blocked_status', 'Cisco-IOS-XR-ip-daps-oper', False), _MetaInfoClassMember('network-blocked-status-trp', ATTRIBUTE, 'int' , None, None, [('0', '4294967295')], [], ''' Is network blocked trap send ''', 'network_blocked_status_trp', 'Cisco-IOS-XR-ip-daps-oper', False), _MetaInfoClassMember('pool-name', ATTRIBUTE, 'str' , None, None, [(0, 64)], [], ''' Pool name ''', 'pool_name', 'Cisco-IOS-XR-ip-daps-oper', False), _MetaInfoClassMember('pool-scope', ATTRIBUTE, 'str' , None, None, [(0, 64)], [], ''' Pool scope ''', 'pool_scope', 'Cisco-IOS-XR-ip-daps-oper', False), _MetaInfoClassMember('start-address-xr', REFERENCE_CLASS, 'StartAddressXr' , 'ydk.models.cisco_ios_xr.Cisco_IOS_XR_ip_daps_oper', 'AddressPoolService.Nodes.Node.Pools.Pool.AddressRanges.AddressRange.StartAddressXr', [], [], ''' Range start ''', 'start_address_xr', 'Cisco-IOS-XR-ip-daps-oper', False), _MetaInfoClassMember('vrf-name', ATTRIBUTE, 'str' , None, None, [(0, 64)], [], ''' VRF name ''', 'vrf_name', 'Cisco-IOS-XR-ip-daps-oper', False), ], 'Cisco-IOS-XR-ip-daps-oper', 'address-range', _yang_ns._namespaces['Cisco-IOS-XR-ip-daps-oper'], 'ydk.models.cisco_ios_xr.Cisco_IOS_XR_ip_daps_oper' ), }, 'AddressPoolService.Nodes.Node.Pools.Pool.AddressRanges' : { 'meta_info' : _MetaInfoClass('AddressPoolService.Nodes.Node.Pools.Pool.AddressRanges', False, [ _MetaInfoClassMember('address-range', REFERENCE_LIST, 'AddressRange' , 'ydk.models.cisco_ios_xr.Cisco_IOS_XR_ip_daps_oper', 'AddressPoolService.Nodes.Node.Pools.Pool.AddressRanges.AddressRange', [], [], ''' Start Address of the Range ''', 'address_range', 'Cisco-IOS-XR-ip-daps-oper', False), ], 'Cisco-IOS-XR-ip-daps-oper', 'address-ranges', _yang_ns._namespaces['Cisco-IOS-XR-ip-daps-oper'], 'ydk.models.cisco_ios_xr.Cisco_IOS_XR_ip_daps_oper' ), }, 'AddressPoolService.Nodes.Node.Pools.Pool.AllocatedAddresses.PoolAllocations.HighThreshold' : { 'meta_info' : _MetaInfoClass('AddressPoolService.Nodes.Node.Pools.Pool.AllocatedAddresses.PoolAllocations.HighThreshold', False, [ _MetaInfoClassMember('threshold', ATTRIBUTE, 'int' , None, None, [('0', '4294967295')], [], ''' Threshold in percentage ''', 'threshold', 'Cisco-IOS-XR-ip-daps-oper', False), _MetaInfoClassMember('time-last-crossed', ATTRIBUTE, 'str' , None, None, [], [], ''' Last time at which threshold crossed in DDD MMM DD HH:MM:SS YYYY format eg: Tue Apr 11 21:30:47 2011 ''', 'time_last_crossed', 'Cisco-IOS-XR-ip-daps-oper', False), _MetaInfoClassMember('triggers', ATTRIBUTE, 'int' , None, None, [('0', '4294967295')], [], ''' Number of Triggers ''', 'triggers', 'Cisco-IOS-XR-ip-daps-oper', False), ], 'Cisco-IOS-XR-ip-daps-oper', 'high-threshold', _yang_ns._namespaces['Cisco-IOS-XR-ip-daps-oper'], 'ydk.models.cisco_ios_xr.Cisco_IOS_XR_ip_daps_oper' ), }, 'AddressPoolService.Nodes.Node.Pools.Pool.AllocatedAddresses.PoolAllocations.LowThreshold' : { 'meta_info' : _MetaInfoClass('AddressPoolService.Nodes.Node.Pools.Pool.AllocatedAddresses.PoolAllocations.LowThreshold', False, [ _MetaInfoClassMember('threshold', ATTRIBUTE, 'int' , None, None, [('0', '4294967295')], [], ''' Threshold in percentage ''', 'threshold', 'Cisco-IOS-XR-ip-daps-oper', False), _MetaInfoClassMember('time-last-crossed', ATTRIBUTE, 'str' , None, None, [], [], ''' Last time at which threshold crossed in DDD MMM DD HH:MM:SS YYYY format eg: Tue Apr 11 21:30:47 2011 ''', 'time_last_crossed', 'Cisco-IOS-XR-ip-daps-oper', False), _MetaInfoClassMember('triggers', ATTRIBUTE, 'int' , None, None, [('0', '4294967295')], [], ''' Number of Triggers ''', 'triggers', 'Cisco-IOS-XR-ip-daps-oper', False), ], 'Cisco-IOS-XR-ip-daps-oper', 'low-threshold', _yang_ns._namespaces['Cisco-IOS-XR-ip-daps-oper'], 'ydk.models.cisco_ios_xr.Cisco_IOS_XR_ip_daps_oper' ), }, 'AddressPoolService.Nodes.Node.Pools.Pool.AllocatedAddresses.PoolAllocations' : { 'meta_info' : _MetaInfoClass('AddressPoolService.Nodes.Node.Pools.Pool.AllocatedAddresses.PoolAllocations', False, [ _MetaInfoClassMember('excluded', ATTRIBUTE, 'int' , None, None, [('0', '4294967295')], [], ''' Excluded allocations ''', 'excluded', 'Cisco-IOS-XR-ip-daps-oper', False), _MetaInfoClassMember('free', ATTRIBUTE, 'int' , None, None, [('0', '4294967295')], [], ''' Free allocations ''', 'free', 'Cisco-IOS-XR-ip-daps-oper', False), _MetaInfoClassMember('high-threshold', REFERENCE_CLASS, 'HighThreshold' , 'ydk.models.cisco_ios_xr.Cisco_IOS_XR_ip_daps_oper', 'AddressPoolService.Nodes.Node.Pools.Pool.AllocatedAddresses.PoolAllocations.HighThreshold', [], [], ''' High threshold data ''', 'high_threshold', 'Cisco-IOS-XR-ip-daps-oper', False), _MetaInfoClassMember('low-threshold', REFERENCE_CLASS, 'LowThreshold' , 'ydk.models.cisco_ios_xr.Cisco_IOS_XR_ip_daps_oper', 'AddressPoolService.Nodes.Node.Pools.Pool.AllocatedAddresses.PoolAllocations.LowThreshold', [], [], ''' Low threshold data ''', 'low_threshold', 'Cisco-IOS-XR-ip-daps-oper', False), _MetaInfoClassMember('total', ATTRIBUTE, 'int' , None, None, [('0', '4294967295')], [], ''' Total allocations ''', 'total', 'Cisco-IOS-XR-ip-daps-oper', False), _MetaInfoClassMember('used', ATTRIBUTE, 'int' , None, None, [('0', '4294967295')], [], ''' Used allocations ''', 'used', 'Cisco-IOS-XR-ip-daps-oper', False), _MetaInfoClassMember('utilization', ATTRIBUTE, 'int' , None, None, [('0', '4294967295')], [], ''' Current utilization in percentage ''', 'utilization', 'Cisco-IOS-XR-ip-daps-oper', False), _MetaInfoClassMember('vrf-name', ATTRIBUTE, 'str' , None, None, [(0, 64)], [], ''' VRF name ''', 'vrf_name', 'Cisco-IOS-XR-ip-daps-oper', False), ], 'Cisco-IOS-XR-ip-daps-oper', 'pool-allocations', _yang_ns._namespaces['Cisco-IOS-XR-ip-daps-oper'], 'ydk.models.cisco_ios_xr.Cisco_IOS_XR_ip_daps_oper' ), }, 'AddressPoolService.Nodes.Node.Pools.Pool.AllocatedAddresses.AddressRange.StartAddress.Address' : { 'meta_info' : _MetaInfoClass('AddressPoolService.Nodes.Node.Pools.Pool.AllocatedAddresses.AddressRange.StartAddress.Address', False, [ _MetaInfoClassMember('address-family', REFERENCE_ENUM_CLASS, 'IpAddrEnum' , 'ydk.models.cisco_ios_xr.Cisco_IOS_XR_ip_daps_oper', 'IpAddrEnum', [], [], ''' AddressFamily ''', 'address_family', 'Cisco-IOS-XR-ip-daps-oper', False), _MetaInfoClassMember('ipv4-address', ATTRIBUTE, 'str' , None, None, [], [b'(([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}]+)?'], ''' IPv4 address ''', 'ipv4_address', 'Cisco-IOS-XR-ip-daps-oper', False), _MetaInfoClassMember('ipv6-address', ATTRIBUTE, 'str' , None, None, [], [b'((:|[0-9a-fA-F]{0,4}):)([0-9a-fA-F]{0,4}:){0,5}((([0-9a-fA-F]{0,4}:)?(:|[0-9a-fA-F]{0,4}))|(((25[0-5]|2[0-4][0-9]|[01]?[0-9]?[0-9])\\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9]?[0-9])))(%[\\p{N}\\p{L}]+)?'], ''' IPv6 address ''', 'ipv6_address', 'Cisco-IOS-XR-ip-daps-oper', False), ], 'Cisco-IOS-XR-ip-daps-oper', 'address', _yang_ns._namespaces['Cisco-IOS-XR-ip-daps-oper'], 'ydk.models.cisco_ios_xr.Cisco_IOS_XR_ip_daps_oper' ), }, 'AddressPoolService.Nodes.Node.Pools.Pool.AllocatedAddresses.AddressRange.StartAddress' : { 'meta_info' : _MetaInfoClass('AddressPoolService.Nodes.Node.Pools.Pool.AllocatedAddresses.AddressRange.StartAddress', False, [ _MetaInfoClassMember('address', REFERENCE_CLASS, 'Address' , 'ydk.models.cisco_ios_xr.Cisco_IOS_XR_ip_daps_oper', 'AddressPoolService.Nodes.Node.Pools.Pool.AllocatedAddresses.AddressRange.StartAddress.Address', [], [], ''' Address ''', 'address', 'Cisco-IOS-XR-ip-daps-oper', False), ], 'Cisco-IOS-XR-ip-daps-oper', 'start-address', _yang_ns._namespaces['Cisco-IOS-XR-ip-daps-oper'], 'ydk.models.cisco_ios_xr.Cisco_IOS_XR_ip_daps_oper' ), }, 'AddressPoolService.Nodes.Node.Pools.Pool.AllocatedAddresses.AddressRange.EndAddress.Address' : { 'meta_info' : _MetaInfoClass('AddressPoolService.Nodes.Node.Pools.Pool.AllocatedAddresses.AddressRange.EndAddress.Address', False, [ _MetaInfoClassMember('address-family', REFERENCE_ENUM_CLASS, 'IpAddrEnum' , 'ydk.models.cisco_ios_xr.Cisco_IOS_XR_ip_daps_oper', 'IpAddrEnum', [], [], ''' AddressFamily ''', 'address_family', 'Cisco-IOS-XR-ip-daps-oper', False), _MetaInfoClassMember('ipv4-address', ATTRIBUTE, 'str' , None, None, [], [b'(([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}]+)?'], ''' IPv4 address ''', 'ipv4_address', 'Cisco-IOS-XR-ip-daps-oper', False), _MetaInfoClassMember('ipv6-address', ATTRIBUTE, 'str' , None, None, [], [b'((:|[0-9a-fA-F]{0,4}):)([0-9a-fA-F]{0,4}:){0,5}((([0-9a-fA-F]{0,4}:)?(:|[0-9a-fA-F]{0,4}))|(((25[0-5]|2[0-4][0-9]|[01]?[0-9]?[0-9])\\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9]?[0-9])))(%[\\p{N}\\p{L}]+)?'], ''' IPv6 address ''', 'ipv6_address', 'Cisco-IOS-XR-ip-daps-oper', False), ], 'Cisco-IOS-XR-ip-daps-oper', 'address', _yang_ns._namespaces['Cisco-IOS-XR-ip-daps-oper'], 'ydk.models.cisco_ios_xr.Cisco_IOS_XR_ip_daps_oper' ), }, 'AddressPoolService.Nodes.Node.Pools.Pool.AllocatedAddresses.AddressRange.EndAddress' : { 'meta_info' : _MetaInfoClass('AddressPoolService.Nodes.Node.Pools.Pool.AllocatedAddresses.AddressRange.EndAddress', False, [ _MetaInfoClassMember('address', REFERENCE_CLASS, 'Address' , 'ydk.models.cisco_ios_xr.Cisco_IOS_XR_ip_daps_oper', 'AddressPoolService.Nodes.Node.Pools.Pool.AllocatedAddresses.AddressRange.EndAddress.Address', [], [], ''' Address ''', 'address', 'Cisco-IOS-XR-ip-daps-oper', False), ], 'Cisco-IOS-XR-ip-daps-oper', 'end-address', _yang_ns._namespaces['Cisco-IOS-XR-ip-daps-oper'], 'ydk.models.cisco_ios_xr.Cisco_IOS_XR_ip_daps_oper' ), }, 'AddressPoolService.Nodes.Node.Pools.Pool.AllocatedAddresses.AddressRange' : { 'meta_info' : _MetaInfoClass('AddressPoolService.Nodes.Node.Pools.Pool.AllocatedAddresses.AddressRange', False, [ _MetaInfoClassMember('end-address', REFERENCE_CLASS, 'EndAddress' , 'ydk.models.cisco_ios_xr.Cisco_IOS_XR_ip_daps_oper', 'AddressPoolService.Nodes.Node.Pools.Pool.AllocatedAddresses.AddressRange.EndAddress', [], [], ''' Range end ''', 'end_address', 'Cisco-IOS-XR-ip-daps-oper', False), _MetaInfoClassMember('excluded', ATTRIBUTE, 'int' , None, None, [('0', '4294967295')], [], ''' Excluded allocations ''', 'excluded', 'Cisco-IOS-XR-ip-daps-oper', False), _MetaInfoClassMember('free', ATTRIBUTE, 'int' , None, None, [('0', '4294967295')], [], ''' Free allocations ''', 'free', 'Cisco-IOS-XR-ip-daps-oper', False), _MetaInfoClassMember('start-address', REFERENCE_CLASS, 'StartAddress' , 'ydk.models.cisco_ios_xr.Cisco_IOS_XR_ip_daps_oper', 'AddressPoolService.Nodes.Node.Pools.Pool.AllocatedAddresses.AddressRange.StartAddress', [], [], ''' Range start ''', 'start_address', 'Cisco-IOS-XR-ip-daps-oper', False), _MetaInfoClassMember('used', ATTRIBUTE, 'int' , None, None, [('0', '4294967295')], [], ''' Used allocations ''', 'used', 'Cisco-IOS-XR-ip-daps-oper', False), ], 'Cisco-IOS-XR-ip-daps-oper', 'address-range', _yang_ns._namespaces['Cisco-IOS-XR-ip-daps-oper'], 'ydk.models.cisco_ios_xr.Cisco_IOS_XR_ip_daps_oper' ), }, 'AddressPoolService.Nodes.Node.Pools.Pool.AllocatedAddresses.InUseAddress.Address.Address_' : { 'meta_info' : _MetaInfoClass('AddressPoolService.Nodes.Node.Pools.Pool.AllocatedAddresses.InUseAddress.Address.Address_', False, [ _MetaInfoClassMember('address-family', REFERENCE_ENUM_CLASS, 'IpAddrEnum' , 'ydk.models.cisco_ios_xr.Cisco_IOS_XR_ip_daps_oper', 'IpAddrEnum', [], [], ''' AddressFamily ''', 'address_family', 'Cisco-IOS-XR-ip-daps-oper', False), _MetaInfoClassMember('ipv4-address', ATTRIBUTE, 'str' , None, None, [], [b'(([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}]+)?'], ''' IPv4 address ''', 'ipv4_address', 'Cisco-IOS-XR-ip-daps-oper', False), _MetaInfoClassMember('ipv6-address', ATTRIBUTE, 'str' , None, None, [], [b'((:|[0-9a-fA-F]{0,4}):)([0-9a-fA-F]{0,4}:){0,5}((([0-9a-fA-F]{0,4}:)?(:|[0-9a-fA-F]{0,4}))|(((25[0-5]|2[0-4][0-9]|[01]?[0-9]?[0-9])\\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9]?[0-9])))(%[\\p{N}\\p{L}]+)?'], ''' IPv6 address ''', 'ipv6_address', 'Cisco-IOS-XR-ip-daps-oper', False), ], 'Cisco-IOS-XR-ip-daps-oper', 'address', _yang_ns._namespaces['Cisco-IOS-XR-ip-daps-oper'], 'ydk.models.cisco_ios_xr.Cisco_IOS_XR_ip_daps_oper' ), }, 'AddressPoolService.Nodes.Node.Pools.Pool.AllocatedAddresses.InUseAddress.Address' : { 'meta_info' : _MetaInfoClass('AddressPoolService.Nodes.Node.Pools.Pool.AllocatedAddresses.InUseAddress.Address', False, [ _MetaInfoClassMember('address', REFERENCE_CLASS, 'Address_' , 'ydk.models.cisco_ios_xr.Cisco_IOS_XR_ip_daps_oper', 'AddressPoolService.Nodes.Node.Pools.Pool.AllocatedAddresses.InUseAddress.Address.Address_', [], [], ''' Address ''', 'address', 'Cisco-IOS-XR-ip-daps-oper', False), ], 'Cisco-IOS-XR-ip-daps-oper', 'address', _yang_ns._namespaces['Cisco-IOS-XR-ip-daps-oper'], 'ydk.models.cisco_ios_xr.Cisco_IOS_XR_ip_daps_oper' ), }, 'AddressPoolService.Nodes.Node.Pools.Pool.AllocatedAddresses.InUseAddress' : { 'meta_info' : _MetaInfoClass('AddressPoolService.Nodes.Node.Pools.Pool.AllocatedAddresses.InUseAddress', False, [ _MetaInfoClassMember('address', REFERENCE_CLASS, 'Address' , 'ydk.models.cisco_ios_xr.Cisco_IOS_XR_ip_daps_oper', 'AddressPoolService.Nodes.Node.Pools.Pool.AllocatedAddresses.InUseAddress.Address', [], [], ''' Client address ''', 'address', 'Cisco-IOS-XR-ip-daps-oper', False), _MetaInfoClassMember('client-type', REFERENCE_ENUM_CLASS, 'DapsClientEnum' , 'ydk.models.cisco_ios_xr.Cisco_IOS_XR_ip_daps_oper', 'DapsClientEnum', [], [], ''' Client type ''', 'client_type', 'Cisco-IOS-XR-ip-daps-oper', False), ], 'Cisco-IOS-XR-ip-daps-oper', 'in-use-address', _yang_ns._namespaces['Cisco-IOS-XR-ip-daps-oper'], 'ydk.models.cisco_ios_xr.Cisco_IOS_XR_ip_daps_oper' ), }, 'AddressPoolService.Nodes.Node.Pools.Pool.AllocatedAddresses' : { 'meta_info' : _MetaInfoClass('AddressPoolService.Nodes.Node.Pools.Pool.AllocatedAddresses', False, [ _MetaInfoClassMember('address-range', REFERENCE_LIST, 'AddressRange' , 'ydk.models.cisco_ios_xr.Cisco_IOS_XR_ip_daps_oper', 'AddressPoolService.Nodes.Node.Pools.Pool.AllocatedAddresses.AddressRange', [], [], ''' Address ranges ''', 'address_range', 'Cisco-IOS-XR-ip-daps-oper', False), _MetaInfoClassMember('in-use-address', REFERENCE_LIST, 'InUseAddress' , 'ydk.models.cisco_ios_xr.Cisco_IOS_XR_ip_daps_oper', 'AddressPoolService.Nodes.Node.Pools.Pool.AllocatedAddresses.InUseAddress', [], [], ''' In-use addresses ''', 'in_use_address', 'Cisco-IOS-XR-ip-daps-oper', False), _MetaInfoClassMember('pool-allocations', REFERENCE_CLASS, 'PoolAllocations' , 'ydk.models.cisco_ios_xr.Cisco_IOS_XR_ip_daps_oper', 'AddressPoolService.Nodes.Node.Pools.Pool.AllocatedAddresses.PoolAllocations', [], [], ''' Pool allocations ''', 'pool_allocations', 'Cisco-IOS-XR-ip-daps-oper', False), ], 'Cisco-IOS-XR-ip-daps-oper', 'allocated-addresses', _yang_ns._namespaces['Cisco-IOS-XR-ip-daps-oper'], 'ydk.models.cisco_ios_xr.Cisco_IOS_XR_ip_daps_oper' ), }, 'AddressPoolService.Nodes.Node.Pools.Pool.Configuration' : { 'meta_info' : _MetaInfoClass('AddressPoolService.Nodes.Node.Pools.Pool.Configuration', False, [ _MetaInfoClassMember('current-utilization', ATTRIBUTE, 'int' , None, None, [('0', '255')], [], ''' Current utilization ''', 'current_utilization', 'Cisco-IOS-XR-ip-daps-oper', False), _MetaInfoClassMember('high-utilization-mark', ATTRIBUTE, 'int' , None, None, [('0', '255')], [], ''' High utilization mark ''', 'high_utilization_mark', 'Cisco-IOS-XR-ip-daps-oper', False), _MetaInfoClassMember('low-utilization-mark', ATTRIBUTE, 'int' , None, None, [('0', '255')], [], ''' Low utilization mark ''', 'low_utilization_mark', 'Cisco-IOS-XR-ip-daps-oper', False), _MetaInfoClassMember('pool-id', ATTRIBUTE, 'int' , None, None, [('0', '4294967295')], [], ''' Pool ID for MIBS ''', 'pool_id', 'Cisco-IOS-XR-ip-daps-oper', False), _MetaInfoClassMember('pool-name', ATTRIBUTE, 'str' , None, None, [(0, 64)], [], ''' Pool name ''', 'pool_name', 'Cisco-IOS-XR-ip-daps-oper', False), _MetaInfoClassMember('pool-prefix-length', ATTRIBUTE, 'int' , None, None, [('0', '4294967295')], [], ''' Prefix length ''', 'pool_prefix_length', 'Cisco-IOS-XR-ip-daps-oper', False), _MetaInfoClassMember('pool-scope', ATTRIBUTE, 'str' , None, None, [(0, 64)], [], ''' Pool Scope ''', 'pool_scope', 'Cisco-IOS-XR-ip-daps-oper', False), _MetaInfoClassMember('utilization-high-count', ATTRIBUTE, 'int' , None, None, [('0', '4294967295')], [], ''' Number of times High utilization threshold was crossed ''', 'utilization_high_count', 'Cisco-IOS-XR-ip-daps-oper', False), _MetaInfoClassMember('utilization-low-count', ATTRIBUTE, 'int' , None, None, [('0', '4294967295')], [], ''' Number of times Low utilization threshold was crossed ''', 'utilization_low_count', 'Cisco-IOS-XR-ip-daps-oper', False), _MetaInfoClassMember('vrf-name', ATTRIBUTE, 'str' , None, None, [(0, 64)], [], ''' VRF name ''', 'vrf_name', 'Cisco-IOS-XR-ip-daps-oper', False), ], 'Cisco-IOS-XR-ip-daps-oper', 'configuration', _yang_ns._namespaces['Cisco-IOS-XR-ip-daps-oper'], 'ydk.models.cisco_ios_xr.Cisco_IOS_XR_ip_daps_oper' ), }, 'AddressPoolService.Nodes.Node.Pools.Pool' : { 'meta_info' : _MetaInfoClass('AddressPoolService.Nodes.Node.Pools.Pool', False, [ _MetaInfoClassMember('pool-name', ATTRIBUTE, 'str' , None, None, [], [b'[\\w\\-\\.:,_@#%$\\+=\\|;]+'], ''' The pool name ''', 'pool_name', 'Cisco-IOS-XR-ip-daps-oper', True), _MetaInfoClassMember('address-ranges', REFERENCE_CLASS, 'AddressRanges' , 'ydk.models.cisco_ios_xr.Cisco_IOS_XR_ip_daps_oper', 'AddressPoolService.Nodes.Node.Pools.Pool.AddressRanges', [], [], ''' Summary info for pool ''', 'address_ranges', 'Cisco-IOS-XR-ip-daps-oper', False), _MetaInfoClassMember('allocated-addresses', REFERENCE_CLASS, 'AllocatedAddresses' , 'ydk.models.cisco_ios_xr.Cisco_IOS_XR_ip_daps_oper', 'AddressPoolService.Nodes.Node.Pools.Pool.AllocatedAddresses', [], [], ''' Detailed info for the Pool ''', 'allocated_addresses', 'Cisco-IOS-XR-ip-daps-oper', False), _MetaInfoClassMember('configuration', REFERENCE_CLASS, 'Configuration' , 'ydk.models.cisco_ios_xr.Cisco_IOS_XR_ip_daps_oper', 'AddressPoolService.Nodes.Node.Pools.Pool.Configuration', [], [], ''' Configuration info for pool ''', 'configuration', 'Cisco-IOS-XR-ip-daps-oper', False), ], 'Cisco-IOS-XR-ip-daps-oper', 'pool', _yang_ns._namespaces['Cisco-IOS-XR-ip-daps-oper'], 'ydk.models.cisco_ios_xr.Cisco_IOS_XR_ip_daps_oper' ), }, 'AddressPoolService.Nodes.Node.Pools' : { 'meta_info' : _MetaInfoClass('AddressPoolService.Nodes.Node.Pools', False, [ _MetaInfoClassMember('pool', REFERENCE_LIST, 'Pool' , 'ydk.models.cisco_ios_xr.Cisco_IOS_XR_ip_daps_oper', 'AddressPoolService.Nodes.Node.Pools.Pool', [], [], ''' Pool data by pool name ''', 'pool', 'Cisco-IOS-XR-ip-daps-oper', False), ], 'Cisco-IOS-XR-ip-daps-oper', 'pools', _yang_ns._namespaces['Cisco-IOS-XR-ip-daps-oper'], 'ydk.models.cisco_ios_xr.Cisco_IOS_XR_ip_daps_oper' ), }, 'AddressPoolService.Nodes.Node.TotalUtilization' : { 'meta_info' : _MetaInfoClass('AddressPoolService.Nodes.Node.TotalUtilization', False, [ _MetaInfoClassMember('current-total-utilization', ATTRIBUTE, 'int' , None, None, [('0', '255')], [], ''' Current utilization ''', 'current_total_utilization', 'Cisco-IOS-XR-ip-daps-oper', False), _MetaInfoClassMember('total-utilization-high-mark', ATTRIBUTE, 'int' , None, None, [('0', '255')], [], ''' High utilization mark ''', 'total_utilization_high_mark', 'Cisco-IOS-XR-ip-daps-oper', False), _MetaInfoClassMember('total-utilization-low-mark', ATTRIBUTE, 'int' , None, None, [('0', '255')], [], ''' Low utilization mark ''', 'total_utilization_low_mark', 'Cisco-IOS-XR-ip-daps-oper', False), ], 'Cisco-IOS-XR-ip-daps-oper', 'total-utilization', _yang_ns._namespaces['Cisco-IOS-XR-ip-daps-oper'], 'ydk.models.cisco_ios_xr.Cisco_IOS_XR_ip_daps_oper' ), }, 'AddressPoolService.Nodes.Node.Vrfs.Vrf.Ipv4.AllocationSummary' : { 'meta_info' : _MetaInfoClass('AddressPoolService.Nodes.Node.Vrfs.Vrf.Ipv4.AllocationSummary', False, [ _MetaInfoClassMember('excluded', ATTRIBUTE, 'int' , None, None, [('0', '4294967295')], [], ''' Excluded allocations ''', 'excluded', 'Cisco-IOS-XR-ip-daps-oper', False), _MetaInfoClassMember('free', ATTRIBUTE, 'int' , None, None, [('0', '4294967295')], [], ''' Free allocations ''', 'free', 'Cisco-IOS-XR-ip-daps-oper', False), _MetaInfoClassMember('high-utilization-threshold', ATTRIBUTE, 'int' , None, None, [('0', '255')], [], ''' High utilization threshold in percentage ''', 'high_utilization_threshold', 'Cisco-IOS-XR-ip-daps-oper', False), _MetaInfoClassMember('low-utilization-threshold', ATTRIBUTE, 'int' , None, None, [('0', '255')], [], ''' Low utilization threshold in percentage ''', 'low_utilization_threshold', 'Cisco-IOS-XR-ip-daps-oper', False), _MetaInfoClassMember('total', ATTRIBUTE, 'int' , None, None, [('0', '4294967295')], [], ''' Total allocations ''', 'total', 'Cisco-IOS-XR-ip-daps-oper', False), _MetaInfoClassMember('used', ATTRIBUTE, 'int' , None, None, [('0', '4294967295')], [], ''' Used allocations ''', 'used', 'Cisco-IOS-XR-ip-daps-oper', False), _MetaInfoClassMember('utilization', ATTRIBUTE, 'int' , None, None, [('0', '255')], [], ''' Current utilization in percentage ''', 'utilization', 'Cisco-IOS-XR-ip-daps-oper', False), ], 'Cisco-IOS-XR-ip-daps-oper', 'allocation-summary', _yang_ns._namespaces['Cisco-IOS-XR-ip-daps-oper'], 'ydk.models.cisco_ios_xr.Cisco_IOS_XR_ip_daps_oper' ), }, 'AddressPoolService.Nodes.Node.Vrfs.Vrf.Ipv4.Pools' : { 'meta_info' : _MetaInfoClass('AddressPoolService.Nodes.Node.Vrfs.Vrf.Ipv4.Pools', False, [ _MetaInfoClassMember('excluded', ATTRIBUTE, 'int' , None, None, [('0', '4294967295')], [], ''' Excluded allocations ''', 'excluded', 'Cisco-IOS-XR-ip-daps-oper', False), _MetaInfoClassMember('free', ATTRIBUTE, 'int' , None, None, [('0', '4294967295')], [], ''' Free allocations ''', 'free', 'Cisco-IOS-XR-ip-daps-oper', False), _MetaInfoClassMember('pool-name', ATTRIBUTE, 'str' , None, None, [(0, 64)], [], ''' Pool name ''', 'pool_name', 'Cisco-IOS-XR-ip-daps-oper', False), _MetaInfoClassMember('total', ATTRIBUTE, 'int' , None, None, [('0', '4294967295')], [], ''' Total allocations ''', 'total', 'Cisco-IOS-XR-ip-daps-oper', False), _MetaInfoClassMember('used', ATTRIBUTE, 'int' , None, None, [('0', '4294967295')], [], ''' Used allocations ''', 'used', 'Cisco-IOS-XR-ip-daps-oper', False), _MetaInfoClassMember('vrf-name', ATTRIBUTE, 'str' , None, None, [(0, 64)], [], ''' VRF name ''', 'vrf_name', 'Cisco-IOS-XR-ip-daps-oper', False), ], 'Cisco-IOS-XR-ip-daps-oper', 'pools', _yang_ns._namespaces['Cisco-IOS-XR-ip-daps-oper'], 'ydk.models.cisco_ios_xr.Cisco_IOS_XR_ip_daps_oper' ), }, 'AddressPoolService.Nodes.Node.Vrfs.Vrf.Ipv4' : { 'meta_info' : _MetaInfoClass('AddressPoolService.Nodes.Node.Vrfs.Vrf.Ipv4', False, [ _MetaInfoClassMember('allocation-summary', REFERENCE_CLASS, 'AllocationSummary' , 'ydk.models.cisco_ios_xr.Cisco_IOS_XR_ip_daps_oper', 'AddressPoolService.Nodes.Node.Vrfs.Vrf.Ipv4.AllocationSummary', [], [], ''' Allocation summary ''', 'allocation_summary', 'Cisco-IOS-XR-ip-daps-oper', False), _MetaInfoClassMember('pools', REFERENCE_LIST, 'Pools' , 'ydk.models.cisco_ios_xr.Cisco_IOS_XR_ip_daps_oper', 'AddressPoolService.Nodes.Node.Vrfs.Vrf.Ipv4.Pools', [], [], ''' Pools data ''', 'pools', 'Cisco-IOS-XR-ip-daps-oper', False), ], 'Cisco-IOS-XR-ip-daps-oper', 'ipv4', _yang_ns._namespaces['Cisco-IOS-XR-ip-daps-oper'], 'ydk.models.cisco_ios_xr.Cisco_IOS_XR_ip_daps_oper' ), }, 'AddressPoolService.Nodes.Node.Vrfs.Vrf.Ipv6.AllocationSummary' : { 'meta_info' : _MetaInfoClass('AddressPoolService.Nodes.Node.Vrfs.Vrf.Ipv6.AllocationSummary', False, [ _MetaInfoClassMember('excluded', ATTRIBUTE, 'int' , None, None, [('0', '4294967295')], [], ''' Excluded allocations ''', 'excluded', 'Cisco-IOS-XR-ip-daps-oper', False), _MetaInfoClassMember('free', ATTRIBUTE, 'int' , None, None, [('0', '4294967295')], [], ''' Free allocations ''', 'free', 'Cisco-IOS-XR-ip-daps-oper', False), _MetaInfoClassMember('high-utilization-threshold', ATTRIBUTE, 'int' , None, None, [('0', '255')], [], ''' High utilization threshold in percentage ''', 'high_utilization_threshold', 'Cisco-IOS-XR-ip-daps-oper', False), _MetaInfoClassMember('low-utilization-threshold', ATTRIBUTE, 'int' , None, None, [('0', '255')], [], ''' Low utilization threshold in percentage ''', 'low_utilization_threshold', 'Cisco-IOS-XR-ip-daps-oper', False), _MetaInfoClassMember('total', ATTRIBUTE, 'int' , None, None, [('0', '4294967295')], [], ''' Total allocations ''', 'total', 'Cisco-IOS-XR-ip-daps-oper', False), _MetaInfoClassMember('used', ATTRIBUTE, 'int' , None, None, [('0', '4294967295')], [], ''' Used allocations ''', 'used', 'Cisco-IOS-XR-ip-daps-oper', False), _MetaInfoClassMember('utilization', ATTRIBUTE, 'int' , None, None, [('0', '255')], [], ''' Current utilization in percentage ''', 'utilization', 'Cisco-IOS-XR-ip-daps-oper', False), ], 'Cisco-IOS-XR-ip-daps-oper', 'allocation-summary', _yang_ns._namespaces['Cisco-IOS-XR-ip-daps-oper'], 'ydk.models.cisco_ios_xr.Cisco_IOS_XR_ip_daps_oper' ), }, 'AddressPoolService.Nodes.Node.Vrfs.Vrf.Ipv6.Pools' : { 'meta_info' : _MetaInfoClass('AddressPoolService.Nodes.Node.Vrfs.Vrf.Ipv6.Pools', False, [ _MetaInfoClassMember('excluded', ATTRIBUTE, 'int' , None, None, [('0', '4294967295')], [], ''' Excluded allocations ''', 'excluded', 'Cisco-IOS-XR-ip-daps-oper', False), _MetaInfoClassMember('free', ATTRIBUTE, 'int' , None, None, [('0', '4294967295')], [], ''' Free allocations ''', 'free', 'Cisco-IOS-XR-ip-daps-oper', False), _MetaInfoClassMember('pool-name', ATTRIBUTE, 'str' , None, None, [(0, 64)], [], ''' Pool name ''', 'pool_name', 'Cisco-IOS-XR-ip-daps-oper', False), _MetaInfoClassMember('total', ATTRIBUTE, 'int' , None, None, [('0', '4294967295')], [], ''' Total allocations ''', 'total', 'Cisco-IOS-XR-ip-daps-oper', False), _MetaInfoClassMember('used', ATTRIBUTE, 'int' , None, None, [('0', '4294967295')], [], ''' Used allocations ''', 'used', 'Cisco-IOS-XR-ip-daps-oper', False), _MetaInfoClassMember('vrf-name', ATTRIBUTE, 'str' , None, None, [(0, 64)], [], ''' VRF name ''', 'vrf_name', 'Cisco-IOS-XR-ip-daps-oper', False), ], 'Cisco-IOS-XR-ip-daps-oper', 'pools', _yang_ns._namespaces['Cisco-IOS-XR-ip-daps-oper'], 'ydk.models.cisco_ios_xr.Cisco_IOS_XR_ip_daps_oper' ), }, 'AddressPoolService.Nodes.Node.Vrfs.Vrf.Ipv6' : { 'meta_info' : _MetaInfoClass('AddressPoolService.Nodes.Node.Vrfs.Vrf.Ipv6', False, [ _MetaInfoClassMember('allocation-summary', REFERENCE_CLASS, 'AllocationSummary' , 'ydk.models.cisco_ios_xr.Cisco_IOS_XR_ip_daps_oper', 'AddressPoolService.Nodes.Node.Vrfs.Vrf.Ipv6.AllocationSummary', [], [], ''' Allocation summary ''', 'allocation_summary', 'Cisco-IOS-XR-ip-daps-oper', False), _MetaInfoClassMember('pools', REFERENCE_LIST, 'Pools' , 'ydk.models.cisco_ios_xr.Cisco_IOS_XR_ip_daps_oper', 'AddressPoolService.Nodes.Node.Vrfs.Vrf.Ipv6.Pools', [], [], ''' Pools data ''', 'pools', 'Cisco-IOS-XR-ip-daps-oper', False), ], 'Cisco-IOS-XR-ip-daps-oper', 'ipv6', _yang_ns._namespaces['Cisco-IOS-XR-ip-daps-oper'], 'ydk.models.cisco_ios_xr.Cisco_IOS_XR_ip_daps_oper' ), }, 'AddressPoolService.Nodes.Node.Vrfs.Vrf' : { 'meta_info' : _MetaInfoClass('AddressPoolService.Nodes.Node.Vrfs.Vrf', False, [ _MetaInfoClassMember('vrf-name', ATTRIBUTE, 'str' , None, None, [], [b'[\\w\\-\\.:,_@#%$\\+=\\|;]+'], ''' The VRF name ''', 'vrf_name', 'Cisco-IOS-XR-ip-daps-oper', True), _MetaInfoClassMember('ipv4', REFERENCE_CLASS, 'Ipv4' , 'ydk.models.cisco_ios_xr.Cisco_IOS_XR_ip_daps_oper', 'AddressPoolService.Nodes.Node.Vrfs.Vrf.Ipv4', [], [], ''' IPv4 pool VRF data ''', 'ipv4', 'Cisco-IOS-XR-ip-daps-oper', False), _MetaInfoClassMember('ipv6', REFERENCE_CLASS, 'Ipv6' , 'ydk.models.cisco_ios_xr.Cisco_IOS_XR_ip_daps_oper', 'AddressPoolService.Nodes.Node.Vrfs.Vrf.Ipv6', [], [], ''' IPv6 Pool VRF data ''', 'ipv6', 'Cisco-IOS-XR-ip-daps-oper', False), ], 'Cisco-IOS-XR-ip-daps-oper', 'vrf', _yang_ns._namespaces['Cisco-IOS-XR-ip-daps-oper'], 'ydk.models.cisco_ios_xr.Cisco_IOS_XR_ip_daps_oper' ), }, 'AddressPoolService.Nodes.Node.Vrfs' : { 'meta_info' : _MetaInfoClass('AddressPoolService.Nodes.Node.Vrfs', False, [ _MetaInfoClassMember('vrf', REFERENCE_LIST, 'Vrf' , 'ydk.models.cisco_ios_xr.Cisco_IOS_XR_ip_daps_oper', 'AddressPoolService.Nodes.Node.Vrfs.Vrf', [], [], ''' VRF level Pool information ''', 'vrf', 'Cisco-IOS-XR-ip-daps-oper', False), ], 'Cisco-IOS-XR-ip-daps-oper', 'vrfs', _yang_ns._namespaces['Cisco-IOS-XR-ip-daps-oper'], 'ydk.models.cisco_ios_xr.Cisco_IOS_XR_ip_daps_oper' ), }, 'AddressPoolService.Nodes.Node' : { 'meta_info' : _MetaInfoClass('AddressPoolService.Nodes.Node', False, [ _MetaInfoClassMember('node-name', ATTRIBUTE, 'str' , None, None, [], [b'([a-zA-Z0-9_]*\\d+/){1,2}([a-zA-Z0-9_]*\\d+)'], ''' Node name ''', 'node_name', 'Cisco-IOS-XR-ip-daps-oper', True), _MetaInfoClassMember('pools', REFERENCE_CLASS, 'Pools' , 'ydk.models.cisco_ios_xr.Cisco_IOS_XR_ip_daps_oper', 'AddressPoolService.Nodes.Node.Pools', [], [], ''' List of IPv4/IPv6 pool data ''', 'pools', 'Cisco-IOS-XR-ip-daps-oper', False), _MetaInfoClassMember('total-utilization', REFERENCE_CLASS, 'TotalUtilization' , 'ydk.models.cisco_ios_xr.Cisco_IOS_XR_ip_daps_oper', 'AddressPoolService.Nodes.Node.TotalUtilization', [], [], ''' Show total utilization for pool ''', 'total_utilization', 'Cisco-IOS-XR-ip-daps-oper', False), _MetaInfoClassMember('vrfs', REFERENCE_CLASS, 'Vrfs' , 'ydk.models.cisco_ios_xr.Cisco_IOS_XR_ip_daps_oper', 'AddressPoolService.Nodes.Node.Vrfs', [], [], ''' Pool VRF data ''', 'vrfs', 'Cisco-IOS-XR-ip-daps-oper', False), ], 'Cisco-IOS-XR-ip-daps-oper', 'node', _yang_ns._namespaces['Cisco-IOS-XR-ip-daps-oper'], 'ydk.models.cisco_ios_xr.Cisco_IOS_XR_ip_daps_oper' ), }, 'AddressPoolService.Nodes' : { 'meta_info' : _MetaInfoClass('AddressPoolService.Nodes', False, [ _MetaInfoClassMember('node', REFERENCE_LIST, 'Node' , 'ydk.models.cisco_ios_xr.Cisco_IOS_XR_ip_daps_oper', 'AddressPoolService.Nodes.Node', [], [], ''' Location. For eg., 0/1/CPU0 ''', 'node', 'Cisco-IOS-XR-ip-daps-oper', False), ], 'Cisco-IOS-XR-ip-daps-oper', 'nodes', _yang_ns._namespaces['Cisco-IOS-XR-ip-daps-oper'], 'ydk.models.cisco_ios_xr.Cisco_IOS_XR_ip_daps_oper' ), }, 'AddressPoolService' : { 'meta_info' : _MetaInfoClass('AddressPoolService', False, [ _MetaInfoClassMember('nodes', REFERENCE_CLASS, 'Nodes' , 'ydk.models.cisco_ios_xr.Cisco_IOS_XR_ip_daps_oper', 'AddressPoolService.Nodes', [], [], ''' Pool operational data for a particular location ''', 'nodes', 'Cisco-IOS-XR-ip-daps-oper', False), ], 'Cisco-IOS-XR-ip-daps-oper', 'address-pool-service', _yang_ns._namespaces['Cisco-IOS-XR-ip-daps-oper'], 'ydk.models.cisco_ios_xr.Cisco_IOS_XR_ip_daps_oper' ), }, } _meta_table['AddressPoolService.Nodes.Node.Pools.Pool.AddressRanges.AddressRange.StartAddressXr.Address']['meta_info'].parent =_meta_table['AddressPoolService.Nodes.Node.Pools.Pool.AddressRanges.AddressRange.StartAddressXr']['meta_info'] _meta_table['AddressPoolService.Nodes.Node.Pools.Pool.AddressRanges.AddressRange.EndAddress.Address']['meta_info'].parent =_meta_table['AddressPoolService.Nodes.Node.Pools.Pool.AddressRanges.AddressRange.EndAddress']['meta_info'] _meta_table['AddressPoolService.Nodes.Node.Pools.Pool.AddressRanges.AddressRange.DefaultRouter.Address']['meta_info'].parent =_meta_table['AddressPoolService.Nodes.Node.Pools.Pool.AddressRanges.AddressRange.DefaultRouter']['meta_info'] _meta_table['AddressPoolService.Nodes.Node.Pools.Pool.AddressRanges.AddressRange.StartAddressXr']['meta_info'].parent =_meta_table['AddressPoolService.Nodes.Node.Pools.Pool.AddressRanges.AddressRange']['meta_info'] _meta_table['AddressPoolService.Nodes.Node.Pools.Pool.AddressRanges.AddressRange.EndAddress']['meta_info'].parent =_meta_table['AddressPoolService.Nodes.Node.Pools.Pool.AddressRanges.AddressRange']['meta_info'] _meta_table['AddressPoolService.Nodes.Node.Pools.Pool.AddressRanges.AddressRange.DefaultRouter']['meta_info'].parent =_meta_table['AddressPoolService.Nodes.Node.Pools.Pool.AddressRanges.AddressRange']['meta_info'] _meta_table['AddressPoolService.Nodes.Node.Pools.Pool.AddressRanges.AddressRange']['meta_info'].parent =_meta_table['AddressPoolService.Nodes.Node.Pools.Pool.AddressRanges']['meta_info'] _meta_table['AddressPoolService.Nodes.Node.Pools.Pool.AllocatedAddresses.PoolAllocations.HighThreshold']['meta_info'].parent =_meta_table['AddressPoolService.Nodes.Node.Pools.Pool.AllocatedAddresses.PoolAllocations']['meta_info'] _meta_table['AddressPoolService.Nodes.Node.Pools.Pool.AllocatedAddresses.PoolAllocations.LowThreshold']['meta_info'].parent =_meta_table['AddressPoolService.Nodes.Node.Pools.Pool.AllocatedAddresses.PoolAllocations']['meta_info'] _meta_table['AddressPoolService.Nodes.Node.Pools.Pool.AllocatedAddresses.AddressRange.StartAddress.Address']['meta_info'].parent =_meta_table['AddressPoolService.Nodes.Node.Pools.Pool.AllocatedAddresses.AddressRange.StartAddress']['meta_info'] _meta_table['AddressPoolService.Nodes.Node.Pools.Pool.AllocatedAddresses.AddressRange.EndAddress.Address']['meta_info'].parent =_meta_table['AddressPoolService.Nodes.Node.Pools.Pool.AllocatedAddresses.AddressRange.EndAddress']['meta_info'] _meta_table['AddressPoolService.Nodes.Node.Pools.Pool.AllocatedAddresses.AddressRange.StartAddress']['meta_info'].parent =_meta_table['AddressPoolService.Nodes.Node.Pools.Pool.AllocatedAddresses.AddressRange']['meta_info'] _meta_table['AddressPoolService.Nodes.Node.Pools.Pool.AllocatedAddresses.AddressRange.EndAddress']['meta_info'].parent =_meta_table['AddressPoolService.Nodes.Node.Pools.Pool.AllocatedAddresses.AddressRange']['meta_info'] _meta_table['AddressPoolService.Nodes.Node.Pools.Pool.AllocatedAddresses.InUseAddress.Address.Address_']['meta_info'].parent =_meta_table['AddressPoolService.Nodes.Node.Pools.Pool.AllocatedAddresses.InUseAddress.Address']['meta_info'] _meta_table['AddressPoolService.Nodes.Node.Pools.Pool.AllocatedAddresses.InUseAddress.Address']['meta_info'].parent =_meta_table['AddressPoolService.Nodes.Node.Pools.Pool.AllocatedAddresses.InUseAddress']['meta_info'] _meta_table['AddressPoolService.Nodes.Node.Pools.Pool.AllocatedAddresses.PoolAllocations']['meta_info'].parent =_meta_table['AddressPoolService.Nodes.Node.Pools.Pool.AllocatedAddresses']['meta_info'] _meta_table['AddressPoolService.Nodes.Node.Pools.Pool.AllocatedAddresses.AddressRange']['meta_info'].parent =_meta_table['AddressPoolService.Nodes.Node.Pools.Pool.AllocatedAddresses']['meta_info'] _meta_table['AddressPoolService.Nodes.Node.Pools.Pool.AllocatedAddresses.InUseAddress']['meta_info'].parent =_meta_table['AddressPoolService.Nodes.Node.Pools.Pool.AllocatedAddresses']['meta_info'] _meta_table['AddressPoolService.Nodes.Node.Pools.Pool.AddressRanges']['meta_info'].parent =_meta_table['AddressPoolService.Nodes.Node.Pools.Pool']['meta_info'] _meta_table['AddressPoolService.Nodes.Node.Pools.Pool.AllocatedAddresses']['meta_info'].parent =_meta_table['AddressPoolService.Nodes.Node.Pools.Pool']['meta_info'] _meta_table['AddressPoolService.Nodes.Node.Pools.Pool.Configuration']['meta_info'].parent =_meta_table['AddressPoolService.Nodes.Node.Pools.Pool']['meta_info'] _meta_table['AddressPoolService.Nodes.Node.Pools.Pool']['meta_info'].parent =_meta_table['AddressPoolService.Nodes.Node.Pools']['meta_info'] _meta_table['AddressPoolService.Nodes.Node.Vrfs.Vrf.Ipv4.AllocationSummary']['meta_info'].parent =_meta_table['AddressPoolService.Nodes.Node.Vrfs.Vrf.Ipv4']['meta_info'] _meta_table['AddressPoolService.Nodes.Node.Vrfs.Vrf.Ipv4.Pools']['meta_info'].parent =_meta_table['AddressPoolService.Nodes.Node.Vrfs.Vrf.Ipv4']['meta_info'] _meta_table['AddressPoolService.Nodes.Node.Vrfs.Vrf.Ipv6.AllocationSummary']['meta_info'].parent =_meta_table['AddressPoolService.Nodes.Node.Vrfs.Vrf.Ipv6']['meta_info'] _meta_table['AddressPoolService.Nodes.Node.Vrfs.Vrf.Ipv6.Pools']['meta_info'].parent =_meta_table['AddressPoolService.Nodes.Node.Vrfs.Vrf.Ipv6']['meta_info'] _meta_table['AddressPoolService.Nodes.Node.Vrfs.Vrf.Ipv4']['meta_info'].parent =_meta_table['AddressPoolService.Nodes.Node.Vrfs.Vrf']['meta_info'] _meta_table['AddressPoolService.Nodes.Node.Vrfs.Vrf.Ipv6']['meta_info'].parent =_meta_table['AddressPoolService.Nodes.Node.Vrfs.Vrf']['meta_info'] _meta_table['AddressPoolService.Nodes.Node.Vrfs.Vrf']['meta_info'].parent =_meta_table['AddressPoolService.Nodes.Node.Vrfs']['meta_info'] _meta_table['AddressPoolService.Nodes.Node.Pools']['meta_info'].parent =_meta_table['AddressPoolService.Nodes.Node']['meta_info'] _meta_table['AddressPoolService.Nodes.Node.TotalUtilization']['meta_info'].parent =_meta_table['AddressPoolService.Nodes.Node']['meta_info'] _meta_table['AddressPoolService.Nodes.Node.Vrfs']['meta_info'].parent =_meta_table['AddressPoolService.Nodes.Node']['meta_info'] _meta_table['AddressPoolService.Nodes.Node']['meta_info'].parent =_meta_table['AddressPoolService.Nodes']['meta_info'] _meta_table['AddressPoolService.Nodes']['meta_info'].parent =_meta_table['AddressPoolService']['meta_info']
apache-2.0
Maccimo/commons-bcel
src/main/java/org/apache/bcel/verifier/VerifierFactoryListModel.java
2556
/* * 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.bcel.verifier; import java.util.ArrayList; import java.util.List; import java.util.Set; import java.util.TreeSet; import javax.swing.event.ListDataEvent; import javax.swing.event.ListDataListener; /** * This class implements an adapter; it implements both a Swing ListModel and * a VerifierFactoryObserver. * * @version $Id$ * @author Enver Haase */ public class VerifierFactoryListModel implements org.apache.bcel.verifier.VerifierFactoryObserver, javax.swing.ListModel { private final List<ListDataListener> listeners = new ArrayList<ListDataListener>(); private final Set<String> cache = new TreeSet<String>(); public VerifierFactoryListModel() { VerifierFactory.attach(this); update(null); // fill cache. } public synchronized void update( String s ) { Verifier[] verifiers = VerifierFactory.getVerifiers(); int num_of_verifiers = verifiers.length; cache.clear(); for (Verifier verifier : verifiers) { cache.add(verifier.getClassName()); } for (ListDataListener listener : listeners) { ListDataEvent e = new ListDataEvent(this, ListDataEvent.CONTENTS_CHANGED, 0, num_of_verifiers - 1); listener.contentsChanged(e); } } public synchronized void addListDataListener( ListDataListener l ) { listeners.add(l); } public synchronized void removeListDataListener( javax.swing.event.ListDataListener l ) { listeners.remove(l); } public synchronized int getSize() { return cache.size(); } public synchronized Object getElementAt( int index ) { return (cache.toArray(new String[cache.size()]))[index]; } }
apache-2.0
dagnir/aws-sdk-java
aws-java-sdk-rds/src/main/java/com/amazonaws/services/rds/model/transform/ModifyDBClusterParameterGroupRequestMarshaller.java
5453
/* * Copyright 2012-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. */ package com.amazonaws.services.rds.model.transform; import javax.annotation.Generated; import com.amazonaws.SdkClientException; import com.amazonaws.Request; import com.amazonaws.DefaultRequest; import com.amazonaws.http.HttpMethodName; import com.amazonaws.services.rds.model.*; import com.amazonaws.transform.Marshaller; import com.amazonaws.util.StringUtils; /** * ModifyDBClusterParameterGroupRequest Marshaller */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class ModifyDBClusterParameterGroupRequestMarshaller implements Marshaller<Request<ModifyDBClusterParameterGroupRequest>, ModifyDBClusterParameterGroupRequest> { public Request<ModifyDBClusterParameterGroupRequest> marshall(ModifyDBClusterParameterGroupRequest modifyDBClusterParameterGroupRequest) { if (modifyDBClusterParameterGroupRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } Request<ModifyDBClusterParameterGroupRequest> request = new DefaultRequest<ModifyDBClusterParameterGroupRequest>(modifyDBClusterParameterGroupRequest, "AmazonRDS"); request.addParameter("Action", "ModifyDBClusterParameterGroup"); request.addParameter("Version", "2014-10-31"); request.setHttpMethod(HttpMethodName.POST); if (modifyDBClusterParameterGroupRequest.getDBClusterParameterGroupName() != null) { request.addParameter("DBClusterParameterGroupName", StringUtils.fromString(modifyDBClusterParameterGroupRequest.getDBClusterParameterGroupName())); } com.amazonaws.internal.SdkInternalList<Parameter> parametersList = (com.amazonaws.internal.SdkInternalList<Parameter>) modifyDBClusterParameterGroupRequest .getParameters(); if (!parametersList.isEmpty() || !parametersList.isAutoConstruct()) { int parametersListIndex = 1; for (Parameter parametersListValue : parametersList) { if (parametersListValue.getParameterName() != null) { request.addParameter("Parameters.Parameter." + parametersListIndex + ".ParameterName", StringUtils.fromString(parametersListValue.getParameterName())); } if (parametersListValue.getParameterValue() != null) { request.addParameter("Parameters.Parameter." + parametersListIndex + ".ParameterValue", StringUtils.fromString(parametersListValue.getParameterValue())); } if (parametersListValue.getDescription() != null) { request.addParameter("Parameters.Parameter." + parametersListIndex + ".Description", StringUtils.fromString(parametersListValue.getDescription())); } if (parametersListValue.getSource() != null) { request.addParameter("Parameters.Parameter." + parametersListIndex + ".Source", StringUtils.fromString(parametersListValue.getSource())); } if (parametersListValue.getApplyType() != null) { request.addParameter("Parameters.Parameter." + parametersListIndex + ".ApplyType", StringUtils.fromString(parametersListValue.getApplyType())); } if (parametersListValue.getDataType() != null) { request.addParameter("Parameters.Parameter." + parametersListIndex + ".DataType", StringUtils.fromString(parametersListValue.getDataType())); } if (parametersListValue.getAllowedValues() != null) { request.addParameter("Parameters.Parameter." + parametersListIndex + ".AllowedValues", StringUtils.fromString(parametersListValue.getAllowedValues())); } if (parametersListValue.getIsModifiable() != null) { request.addParameter("Parameters.Parameter." + parametersListIndex + ".IsModifiable", StringUtils.fromBoolean(parametersListValue.getIsModifiable())); } if (parametersListValue.getMinimumEngineVersion() != null) { request.addParameter("Parameters.Parameter." + parametersListIndex + ".MinimumEngineVersion", StringUtils.fromString(parametersListValue.getMinimumEngineVersion())); } if (parametersListValue.getApplyMethod() != null) { request.addParameter("Parameters.Parameter." + parametersListIndex + ".ApplyMethod", StringUtils.fromString(parametersListValue.getApplyMethod())); } parametersListIndex++; } } return request; } }
apache-2.0
ericholscher/dropwizard
dropwizard-jdbi/src/main/java/com/yammer/dropwizard/jdbi/OptionalContainerFactory.java
967
package com.yammer.dropwizard.jdbi; import com.google.common.base.Optional; import org.skife.jdbi.v2.ContainerBuilder; import org.skife.jdbi.v2.tweak.ContainerFactory; public class OptionalContainerFactory implements ContainerFactory<Optional<?>> { @Override public boolean accepts(Class<?> type) { return Optional.class.isAssignableFrom(type); } @Override public ContainerBuilder<Optional<?>> newContainerBuilderFor(Class<?> type) { return new OptionalContainerBuilder(); } private static class OptionalContainerBuilder implements ContainerBuilder<Optional<?>> { Optional<?> optional = Optional.absent(); @Override public ContainerBuilder<Optional<?>> add(Object it) { optional = Optional.fromNullable(it); return this; } @Override public Optional<?> build() { return optional; } } }
apache-2.0
MobilityData/gtfs-validator
core/src/main/java/org/mobilitydata/gtfsvalidator/notice/StartAndEndRangeEqualNotice.java
1987
/* * Copyright 2021 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 * * 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.mobilitydata.gtfsvalidator.notice; import javax.annotation.Nullable; /** * Start and end range fields are equal for a certain GTFS entity. * * <p>Example: {@code start_time == end_time} for {@code frequencies.txt}. * * <p>Severity: {@code SeverityLevel.ERROR} */ public class StartAndEndRangeEqualNotice extends ValidationNotice { private final String filename; private final long csvRowNumber; @Nullable private final String entityId; private final String startFieldName; private final String endFieldName; private final String value; public StartAndEndRangeEqualNotice( String filename, long csvRowNumber, String entityId, String startFieldName, String endFieldName, String value) { super(SeverityLevel.ERROR); this.filename = filename; this.csvRowNumber = csvRowNumber; this.entityId = entityId; this.startFieldName = startFieldName; this.endFieldName = endFieldName; this.value = value; } public StartAndEndRangeEqualNotice( String filename, long csvRowNumber, String startFieldName, String endFieldName, String value) { super(SeverityLevel.ERROR); this.filename = filename; this.csvRowNumber = csvRowNumber; this.entityId = null; this.startFieldName = startFieldName; this.endFieldName = endFieldName; this.value = value; } }
apache-2.0
AttwellBrian/dagger
compiler/src/main/java/dagger/internal/codegen/MultibindingsProcessingStep.java
1966
/* * Copyright (C) 2015 The Dagger Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dagger.internal.codegen; import static javax.lang.model.util.ElementFilter.typesIn; import com.google.auto.common.BasicAnnotationProcessor.ProcessingStep; import com.google.common.collect.ImmutableSet; import com.google.common.collect.SetMultimap; import dagger.Multibindings; import java.lang.annotation.Annotation; import java.util.Set; import javax.annotation.processing.Messager; import javax.lang.model.element.Element; import javax.lang.model.element.TypeElement; /** * Processes elements annotated with {@link Multibindings @Multibindings}. */ class MultibindingsProcessingStep implements ProcessingStep { private final Messager messager; private final MultibindingsValidator multibindingsValidator; MultibindingsProcessingStep(Messager messager, MultibindingsValidator multibindingsValidator) { this.messager = messager; this.multibindingsValidator = multibindingsValidator; } @Override public Set<? extends Class<? extends Annotation>> annotations() { return ImmutableSet.of(Multibindings.class); } @Override public Set<Element> process( SetMultimap<Class<? extends Annotation>, Element> elementsByAnnotation) { for (TypeElement element : typesIn(elementsByAnnotation.values())) { multibindingsValidator.validate(element).printMessagesTo(messager); } return ImmutableSet.of(); } }
apache-2.0
ctomc/jboss-modules
src/main/java/org/jboss/modules/JarFileResourceLoader.java
19317
/* * JBoss, Home of Professional Open Source. * Copyright 2014 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * 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.jboss.modules; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.net.MalformedURLException; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.net.URLStreamHandler; import java.security.CodeSigner; import java.security.CodeSource; import java.util.Arrays; import java.util.Collection; import java.util.Enumeration; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.Map; import java.util.NoSuchElementException; import java.util.TreeSet; import java.util.jar.JarEntry; import java.util.jar.JarFile; import java.util.jar.Manifest; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; /** * * @author <a href="mailto:david.lloyd@redhat.com">David M. Lloyd</a> * @author Thomas.Diesler@jboss.com * @author <a href="mailto:ropalka@redhat.com">Richard Opalka</a> */ final class JarFileResourceLoader extends AbstractResourceLoader implements IterableResourceLoader { private static final String INDEX_FILE = "META-INF/PATHS.LIST"; private final JarFile jarFile; private final String rootName; private final URL rootUrl; private final String relativePath; private final File fileOfJar; // protected by {@code this} private final Map<CodeSigners, CodeSource> codeSources = new HashMap<>(); JarFileResourceLoader(final String rootName, final JarFile jarFile) { this(rootName, jarFile, null); } JarFileResourceLoader(final String rootName, final JarFile jarFile, final String relativePath) { if (jarFile == null) { throw new IllegalArgumentException("jarFile is null"); } if (rootName == null) { throw new IllegalArgumentException("rootName is null"); } fileOfJar = new File(jarFile.getName()); this.jarFile = jarFile; this.rootName = rootName; String realPath = relativePath == null ? null : PathUtils.canonicalize(relativePath); if (realPath != null && realPath.endsWith("/")) realPath = realPath.substring(0, realPath.length() - 1); this.relativePath = realPath; try { rootUrl = getJarURI(fileOfJar.toURI(), realPath).toURL(); } catch (URISyntaxException e) { throw new IllegalArgumentException("Invalid root file specified", e); } catch (MalformedURLException e) { throw new IllegalArgumentException("Invalid root file specified", e); } } private static URI getJarURI(final URI original, final String nestedPath) throws URISyntaxException { final StringBuilder b = new StringBuilder(); b.append("file:"); assert original.getScheme().equals("file"); final String path = original.getPath(); assert path != null; final String host = original.getHost(); if (host != null) { final String userInfo = original.getRawUserInfo(); b.append("//"); if (userInfo != null) { b.append(userInfo).append('@'); } b.append(host); } b.append(path).append("!/"); if (nestedPath != null) { b.append(nestedPath); } return new URI("jar", b.toString(), null); } public String getRootName() { return rootName; } public synchronized ClassSpec getClassSpec(final String fileName) throws IOException { final ClassSpec spec = new ClassSpec(); final JarEntry entry = getJarEntry(fileName); if (entry == null) { // no such entry return null; } final long size = entry.getSize(); final InputStream is = jarFile.getInputStream(entry); try { if (size == -1) { // size unknown final ByteArrayOutputStream baos = new ByteArrayOutputStream(); final byte[] buf = new byte[16384]; int res; while ((res = is.read(buf)) > 0) { baos.write(buf, 0, res); } // done CodeSource codeSource = createCodeSource(entry); baos.close(); is.close(); spec.setBytes(baos.toByteArray()); spec.setCodeSource(codeSource); return spec; } else if (size <= (long) Integer.MAX_VALUE) { final int castSize = (int) size; byte[] bytes = new byte[castSize]; int a = 0, res; while ((res = is.read(bytes, a, castSize - a)) > 0) { a += res; } // consume remainder so that cert check doesn't fail in case of wonky JARs while (is.read() != -1) { // } // done CodeSource codeSource = createCodeSource(entry); is.close(); spec.setBytes(bytes); spec.setCodeSource(codeSource); return spec; } else { throw new IOException("Resource is too large to be a valid class file"); } } finally { StreamUtil.safeClose(is); } } // this MUST only be called after the input stream is fully read (see MODULES-201) private CodeSource createCodeSource(final JarEntry entry) { final CodeSigner[] entryCodeSigners = entry.getCodeSigners(); final CodeSigners codeSigners = entryCodeSigners == null || entryCodeSigners.length == 0 ? EMPTY_CODE_SIGNERS : new CodeSigners(entryCodeSigners); CodeSource codeSource = codeSources.get(codeSigners); if (codeSource == null) { codeSources.put(codeSigners, codeSource = new CodeSource(rootUrl, entryCodeSigners)); } return codeSource; } private JarEntry getJarEntry(final String fileName) { return relativePath == null ? jarFile.getJarEntry(fileName) : jarFile.getJarEntry(relativePath + "/" + fileName); } public PackageSpec getPackageSpec(final String name) throws IOException { final Manifest manifest; if (relativePath == null) { manifest = jarFile.getManifest(); } else { JarEntry jarEntry = getJarEntry("META-INF/MANIFEST.MF"); if (jarEntry == null) { manifest = null; } else { InputStream inputStream = jarFile.getInputStream(jarEntry); try { manifest = new Manifest(inputStream); } finally { StreamUtil.safeClose(inputStream); } } } return getPackageSpec(name, manifest, rootUrl); } public String getLibrary(final String name) { // JARs cannot have libraries in them return null; } public Resource getResource(String name) { try { final JarFile jarFile = this.jarFile; name = PathUtils.canonicalize(PathUtils.relativize(name)); final JarEntry entry = getJarEntry(name); if (entry == null) { return null; } final URI uri; try { File absoluteFile = new File(jarFile.getName()).getAbsoluteFile(); String path = absoluteFile.getPath(); path = PathUtils.canonicalize(path); if (File.separatorChar != '/') { // optimizes away on platforms with / path = path.replace(File.separatorChar, '/'); } if (PathUtils.isRelative(path)) { // should not be possible, but the JDK thinks this might happen sometimes..? path = "/" + path; } if (path.startsWith("//")) { // UNC path URIs have loads of leading slashes path = "//" + path; } uri = new URI("file", null, path, null); } catch (URISyntaxException x) { throw new IllegalStateException(x); } return new JarEntryResource(jarFile, entry, relativePath, new URL(null, getJarURI(uri, entry.getName()).toString(), (URLStreamHandler) null)); } catch (MalformedURLException e) { // must be invalid...? (todo: check this out) return null; } catch (URISyntaxException e) { // must be invalid...? (todo: check this out) return null; } } public Iterator<Resource> iterateResources(String startPath, final boolean recursive) { final JarFile jarFile = this.jarFile; if (relativePath != null) startPath = startPath.equals("") ? relativePath : relativePath + "/" + startPath; final String startName = PathUtils.canonicalize(PathUtils.relativize(startPath)); final Enumeration<JarEntry> entries = jarFile.entries(); return new Iterator<Resource>() { private Resource next; public boolean hasNext() { while (next == null) { if (! entries.hasMoreElements()) { return false; } final JarEntry entry = entries.nextElement(); final String name = entry.getName(); if ((recursive ? PathUtils.isChild(startName, name) : PathUtils.isDirectChild(startName, name))) { if (!entry.isDirectory()) { try { next = new JarEntryResource(jarFile, entry, relativePath, getJarURI(new File(jarFile.getName()).toURI(), entry.getName()).toURL()); } catch (Exception ignored) { } } } } return true; } public Resource next() { if (! hasNext()) { throw new NoSuchElementException(); } try { return next; } finally { next = null; } } public void remove() { throw new UnsupportedOperationException(); } }; } public Collection<String> getPaths() { final Collection<String> index = new HashSet<String>(); index.add(""); String relativePath = this.relativePath; // First check for an external index final JarFile jarFile = this.jarFile; final String jarFileName = jarFile.getName(); final long jarModified = fileOfJar.lastModified(); final File indexFile = new File(jarFileName + ".index"); if (ResourceLoaders.USE_INDEXES) { if (indexFile.exists()) { final long indexModified = indexFile.lastModified(); if (indexModified != 0L && jarModified != 0L && indexModified >= jarModified) try { return readIndex(new FileInputStream(indexFile), index, relativePath); } catch (IOException e) { index.clear(); } } } // Next check for an internal index JarEntry listEntry = jarFile.getJarEntry(INDEX_FILE); if (listEntry != null) { try { return readIndex(jarFile.getInputStream(listEntry), index, relativePath); } catch (IOException e) { index.clear(); } } // Next just read the JAR extractJarPaths(jarFile, relativePath, index); if (ResourceLoaders.WRITE_INDEXES && relativePath == null) { writeExternalIndex(indexFile, index); } return index; } @Override public void close() { try { super.close(); } finally { try { jarFile.close(); } catch (IOException e) { // ignored } } } public URI getLocation() { try { return getJarURI(fileOfJar.toURI(), ""); } catch (URISyntaxException e) { return null; } } static void extractJarPaths(final JarFile jarFile, String relativePath, final Collection<String> index) { index.add(""); final Enumeration<JarEntry> entries = jarFile.entries(); while (entries.hasMoreElements()) { final JarEntry jarEntry = entries.nextElement(); final String name = jarEntry.getName(); final int idx = name.lastIndexOf('/'); if (idx == -1) continue; final String path = name.substring(0, idx); if (path.length() == 0 || path.endsWith("/")) { // invalid name, just skip... continue; } if (relativePath == null) { index.add(path); } else { if (path.startsWith(relativePath + "/")) { index.add(path.substring(relativePath.length() + 1)); } } } } static void writeExternalIndex(final File indexFile, final Collection<String> index) { // Now try to write it boolean ok = false; try { final BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(indexFile))); try { for (String name : index) { writer.write(name); writer.write('\n'); } writer.close(); ok = true; } finally { StreamUtil.safeClose(writer); } } catch (IOException e) { // failed, ignore } finally { if (! ok) { // well, we tried... indexFile.delete(); } } } static Collection<String> readIndex(final InputStream stream, final Collection<String> index, final String relativePath) throws IOException { final BufferedReader r = new BufferedReader(new InputStreamReader(stream)); try { String s; while ((s = r.readLine()) != null) { String name = s.trim(); if (relativePath == null) { index.add(name); } else { if (name.startsWith(relativePath + "/")) { index.add(name.substring(relativePath.length() + 1)); } } } return index; } finally { // if exception is thrown, undo index creation r.close(); } } static void addInternalIndex(File file, boolean modify) throws IOException { final JarFile oldJarFile = new JarFile(file, false); try { final Collection<String> index = new TreeSet<String>(); final File outputFile; outputFile = new File(file.getAbsolutePath().replace(".jar", "-indexed.jar")); final ZipOutputStream zo = new ZipOutputStream(new FileOutputStream(outputFile)); try { Enumeration<JarEntry> entries = oldJarFile.entries(); while (entries.hasMoreElements()) { final JarEntry entry = entries.nextElement(); // copy data, unless we're replacing the index if (!entry.getName().equals(INDEX_FILE)) { final JarEntry clone = (JarEntry) entry.clone(); // Compression level and format can vary across implementations if (clone.getMethod() != ZipEntry.STORED) clone.setCompressedSize(-1); zo.putNextEntry(clone); StreamUtil.copy(oldJarFile.getInputStream(entry), zo); } // add to the index final String name = entry.getName(); final int idx = name.lastIndexOf('/'); if (idx == -1) continue; final String path = name.substring(0, idx); if (path.length() == 0 || path.endsWith("/")) { // invalid name, just skip... continue; } index.add(path); } // write index zo.putNextEntry(new ZipEntry(INDEX_FILE)); final BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(zo)); try { for (String name : index) { writer.write(name); writer.write('\n'); } writer.close(); } finally { StreamUtil.safeClose(writer); } zo.close(); oldJarFile.close(); if (modify) { file.delete(); if (!outputFile.renameTo(file)) { throw new IOException("failed to rename " + outputFile.getAbsolutePath() + " to " + file.getAbsolutePath()); } } } finally { StreamUtil.safeClose(zo); } } finally { StreamUtil.safeClose(oldJarFile); } } private static final CodeSigners EMPTY_CODE_SIGNERS = new CodeSigners(new CodeSigner[0]); static final class CodeSigners { private final CodeSigner[] codeSigners; private final int hashCode; CodeSigners(final CodeSigner[] codeSigners) { this.codeSigners = codeSigners; hashCode = Arrays.hashCode(codeSigners); } public boolean equals(final Object obj) { return obj instanceof CodeSigners && equals((CodeSigners) obj); } private boolean equals(final CodeSigners other) { return Arrays.equals(codeSigners, other.codeSigners); } public int hashCode() { return hashCode; } } }
apache-2.0
stdlib-js/stdlib
lib/node_modules/@stdlib/random/base/poisson/docs/types/index.d.ts
5396
/* * @license Apache-2.0 * * Copyright (c) 2019 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // TypeScript Version: 2.0 /// <reference types="@stdlib/types"/> import * as random from '@stdlib/types/random'; /** * Interface defining `factory` options. */ interface Options { /** * Pseudorandom number generator which generates uniformly distributed pseudorandom numbers. */ prng?: random.PRNG; /** * Pseudorandom number generator seed. */ seed?: random.PRNGSeedMT19937; /** * Pseudorandom number generator state. */ state?: random.PRNGStateMT19937; /** * Specifies whether to copy a provided pseudorandom number generator state. */ copy?: boolean; } /** * Interface for PRNG properties and methods. */ interface PRNG { /** * Generator name. */ readonly NAME: string; /** * Underlying pseudorandom number generator. */ readonly PRNG: random.PRNG; /** * PRNG seed. */ readonly seed: random.PRNGSeedMT19937; /** * PRNG seed length. */ readonly seedLength: number; /** * PRNG state. */ state: random.PRNGStateMT19937; /** * PRNG state length. */ readonly stateLength: number; /** * PRNG state size (in bytes). */ readonly byteLength: number; /** * Serializes the pseudorandom number generator as a JSON object. * * @returns JSON representation */ toJSON(): string; } /** * Interface for generating Poisson distributed pseudorandom numbers with pre-specified parameter values. */ interface NullaryFunction extends PRNG { /** * Returns a Poisson distributed pseudorandom number. * * @returns pseudorandom number */ (): number; } /** * Interface for generating Poisson distributed pseudorandom numbers without pre-specified parameter values. */ interface BinaryFunction extends PRNG { /** * Returns a Poisson distributed pseudorandom number. * * @param lambda - mean * @returns pseudorandom number */ ( lambda: number ): number; } /** * Interface for generating pseudorandom numbers drawn from a Poisson distribution. */ interface Random extends PRNG { /** * Returns a Poisson distributed pseudorandom number. * * ## Notes * * - If `lambda <= 0`, the function returns `NaN`. * - If `lambda` is `NaN`, the function returns `NaN`. * * @param lambda - mean * @returns pseudorandom number * * @example * var v = poisson( 1.5 ); * // returns <number> */ ( lambda: number ): number; /** * Returns a pseudorandom number generator for generating Poisson distributed random numbers. * * ## Notes * * - When provided `lambda`, the returned PRNG returns random variates drawn from the specified distribution. * * @param lambda - mean * @param options - function options * @param options.prng - pseudorandom number generator which generates uniformly distributed pseudorandom numbers * @param options.seed - pseudorandom number generator seed * @param options.state - pseudorandom number generator state * @param options.copy - boolean indicating whether to copy a provided pseudorandom number generator state (default: true) * @throws must provide a valid state * @returns pseudorandom number generator * * @example * var mypoisson = poisson.factory( 1.5 ); * * var v = mypoisson(); * // returns <number> * * @example * var mypoisson = poisson.factory( 2.3, { * 'seed': 297 * }); * var v = mypoisson(); * // returns <number> */ factory( lambda: number, options?: Options ): NullaryFunction; /** * Returns a pseudorandom number generator for generating Poisson distributed random numbers. * * ## Notes * * - When not provided `lambda`, the returned PRNG requires that `lambda` be provided at each invocation. * * @param options - function options * @param options.prng - pseudorandom number generator which generates uniformly distributed pseudorandom numbers * @param options.seed - pseudorandom number generator seed * @param options.state - pseudorandom number generator state * @param options.copy - boolean indicating whether to copy a provided pseudorandom number generator state (default: true) * @throws must provide a valid state * @returns pseudorandom number generator * * @example * var mypoisson = poisson.factory(); * * var v = mypoisson( 1.5 ); * // returns <number> * * @example * var mypoisson = poisson.factory({ * 'seed': 297 * }); * var v = mypoisson( 2.3 ); * // returns <number> */ factory( options?: Options ): BinaryFunction; } /** * Returns a Poisson distributed pseudorandom number. * * ## Notes * * - If `lambda <= 0`, the function returns `NaN`. * - If `lambda` is `NaN`, the function returns `NaN`. * * @param lambda - mean * @returns pseudorandom number * * @example * var v = poisson( 1.5 ); * // returns <number> * * @example * var mypoisson = poisson.factory( 1.5 ); * * var v = mypoisson(); * // returns <number> */ declare var poisson: Random; // EXPORTS // export = poisson;
apache-2.0
ShardPhoenix/SapiClient
src/au/com/sensis/sapi/requestmodel/SortBy.java
92
package au.com.sensis.sapi.requestmodel; public enum SortBy { RELEVANCE, NAME, DISTANCE }
apache-2.0
SAP/openui5
src/sap.ui.testrecorder/src/sap/ui/testrecorder/inspector/ControlInspector.js
10217
/*! * ${copyright} */ sap.ui.define([ "sap/ui/base/Object", "sap/ui/thirdparty/jquery", "sap/ui/testrecorder/CommunicationBus", "sap/ui/testrecorder/CommunicationChannels", "sap/ui/testrecorder/mutationObservers/AppMutationObserver", "sap/ui/testrecorder/mutationObservers/ElementMutationObserver", "sap/ui/support/supportRules/ui/external/Highlighter", "sap/ui/test/_ControlFinder", "sap/ui/testrecorder/inspector/ControlAPI", "sap/ui/testrecorder/inspector/ControlInspectorRepo", "sap/ui/testrecorder/Constants", "sap/ui/testrecorder/DialectRegistry", "sap/ui/testrecorder/Dialects", "sap/ui/testrecorder/controlSelectors/ControlSelectorGenerator", "sap/ui/testrecorder/codeSnippets/POMethodUtil", "sap/ui/testrecorder/codeSnippets/RawSnippetUtil", "sap/ui/testrecorder/codeSnippets/CodeSnippetProvider", "sap/ui/testrecorder/ui/models/SharedModel" ], function (BaseObject, $, CommunicationBus, CommunicationChannels, AppMutationObserver, ElementMutationObserver, Highlighter, _ControlFinder, ControlAPI, ControlInspectorRepo, constants, DialectRegistry, Dialects, ControlSelectorGenerator, POMethodUtil, RawSnippetUtil, CodeSnippetProvider, SharedModel) { "use strict"; var oControlInspector = null; var oHighlighter = new Highlighter(constants.HIGHLIGHTER_ID); var mSelectorSettings = Object.assign({}, SharedModel.getData().settings); /** * @class retrieves data about controls - both readily available and generated. * the data is formatted in a specific way convenient for the recorder UI */ var ControlInspector = BaseObject.extend("sap.ui.testrecorder.inspector.ControlInspector", { constructor: function () { // better to be singleton because of the mutation observer if (!oControlInspector) { BaseObject.apply(this, arguments); this._appObserver = new AppMutationObserver(this.getAllControlData.bind(this)); this._selectedElementObserver = new ElementMutationObserver(this.getControlData.bind(this)); } else { return oControlInspector; } } }); /** * initialize listeners for DOM changes and for events from the test recorder frame */ ControlInspector.prototype.init = function () { this._appObserver.start(); CommunicationBus.subscribe(CommunicationChannels.REQUEST_ALL_CONTROLS_DATA, this.getAllControlData.bind(this)); CommunicationBus.subscribe(CommunicationChannels.REQUEST_CONTROL_DATA, this.getControlData.bind(this)); CommunicationBus.subscribe(CommunicationChannels.REQUEST_CODE_SNIPPET, this.getCodeSnippet.bind(this)); CommunicationBus.subscribe(CommunicationChannels.HIGHLIGHT_CONTROL, this.highlightControl.bind(this)); CommunicationBus.subscribe(CommunicationChannels.SET_DIALECT, this.setDialect.bind(this)); CommunicationBus.subscribe(CommunicationChannels.UPDATE_SETTINGS, this.updateSettings.bind(this)); CommunicationBus.subscribe(CommunicationChannels.CLEAR_SNIPPETS, this.clearSnippets.bind(this)); }; /** * send an event to the test recorder frame that has as payload: * the most basic data about the app - framework name + version and control IDs */ ControlInspector.prototype.getAllControlData = function () { CommunicationBus.publish(CommunicationChannels.RECEIVE_ALL_CONTROLS_DATA, { renderedControls: ControlAPI.getAllControlData().renderedControls, framework: ControlAPI.getFrameworkData().framework }); ControlInspectorRepo.clear(); }; /** * send an event to the test recorder frame that has as payload: * detailed information about a user-selected control - properties and bindings * @param {object} mData control identifier * @param {string} mData.controlId ID of the control to inspect * @param {string} mData.domElementId ID of a dom element from which the control is found (e.g. dom ref) */ ControlInspector.prototype.getControlData = function (mData) { var oDomElement = mData.domElementId ? document.getElementById(mData.domElementId) : sap.ui.getCore().byId(mData.controlId).getDomRef(); this._selectedElementObserver.stop(); this._selectedElementObserver.start(oDomElement); // observe future updates in the control's properties var mControlData = ControlAPI.getControlData(mData); CommunicationBus.publish(CommunicationChannels.RECEIVE_CONTROL_DATA, mControlData); }; /** * send an event to the test recorder frame that has as payload: * a generated code snippet for locating controls * @param {object} mData object containing control identifiers and actions * @param {string} mData.domElementId ID of a dom element from which the control is found (e.g. dom ref) * @param {string} mData.action name of an action to record in the snippet (e.g. press, enter text) * @param {object} mData.assertion assertion details - property name, type and expected value */ ControlInspector.prototype.getCodeSnippet = function (mData) { var mDataForGenerator = Object.assign({}, mData, { settings: mSelectorSettings }); // find a cached selector or generate a new one var mControlSelector = ControlInspectorRepo.findSelector(mData.domElementId); var oSelectorPromise = mControlSelector ? Promise.resolve(mControlSelector) : ControlSelectorGenerator.getSelector(mDataForGenerator); return oSelectorPromise.then(function (mSelector) { mControlSelector = mSelector; // given the selector, generate a dialect-specific code snippet return CodeSnippetProvider.getSnippet({ controlSelector: mSelector, action: mDataForGenerator.action, assertion: mDataForGenerator.assertion, settings: mSelectorSettings }); }).then(function (sSnippet) { // cache the selector and snippet for future use ControlInspectorRepo.save(mData, mControlSelector, sSnippet); // when recording multiple snippets, combine the snippets for all controls // that have been selected since the multi-snippet setting was enabled. var aSnippets = mSelectorSettings.multipleSnippets ? ControlInspectorRepo.getSnippets() : [sSnippet]; // format all snippets and pass them to the test recorder frame as one whole snippet if (DialectRegistry.getActiveDialect() === Dialects.RAW) { return RawSnippetUtil.getJSON(aSnippets, mSelectorSettings); } else { return POMethodUtil.getPOMethod(aSnippets, $.extend({ action: mData.action, assertion: mData.assertion }, mSelectorSettings)); } }).then(function (sSnippet) { // here sSnippet contains the snippets for one or multiple controls CommunicationBus.publish(CommunicationChannels.RECEIVE_CODE_SNIPPET, { codeSnippet: sSnippet }); }).catch(function (oError) { CommunicationBus.publish(CommunicationChannels.RECEIVE_CODE_SNIPPET, { error: "Could not generate code snippet for " + JSON.stringify(mData) + ". Details: " + oError, domElementId: mDataForGenerator.domElementId }); }); }; /** * given a control identifier, highlight the control in the app * @param {object} mData control identifier * @param {string} mData.controlId ID of the control to inspect * @param {string} mData.domElementId ID of a dom element from which the control is found (e.g. dom ref) */ ControlInspector.prototype.highlightControl = function (mData) { if (mData.domElementId) { oHighlighter.highlight(mData.domElementId); } else if (mData.controlId) { var domElement = _ControlFinder._findElements({id: mData.controlId})[0]; if (domElement) { oHighlighter.highlight(domElement.id); } } }; /** * given a dialect name, change the "global" dialect setting and update any already generated snippets * @param {string} sDialect name of the dialect */ ControlInspector.prototype.setDialect = function (sDialect) { if (DialectRegistry.getActiveDialect() !== sDialect) { DialectRegistry.setActiveDialect(sDialect); CommunicationBus.publish(CommunicationChannels.DIALECT_CHANGED, { dialect: sDialect }); ControlInspectorRepo.getRequests().forEach(this.getCodeSnippet.bind(this)); } }; /** * given a dom ID, return the selector for its corresponding control, if it has already been generated * @param {object} mSettings settings * @param {boolean} preferViewId should selectors with view IDs should be preferred over those with global IDs * @param {boolean} formatAsPOMethod should the snippets be wrapped in a page object method definition * @param {boolean} multipleSnippets whether the snippets for multiple controls should be combined, or * the snippet is cleared when a new control is selected */ ControlInspector.prototype.updateSettings = function (mSettings) { // only update the new values Object.assign(mSelectorSettings, mSettings); var aRequests = ControlInspectorRepo.getRequests(); if (_isAnySet(mSettings, "multipleSnippets")) { this.clearSnippets(); if (aRequests.length) { // only regenerate the latest snippet // (e.g. once 'multi' is switched off, we expect only 1 snippet, even if we switch back to 'multi' again) this.getCodeSnippet(aRequests[aRequests.length - 1]); } } if (_isAnySet(mSettings, ["preferViewId"])) { ControlInspectorRepo.clear(); } if (_isAnySet(mSettings, ["formatAsPOMethod", "preferViewId"])) { if (mSelectorSettings.multipleSnippets) { aRequests.forEach(this.getCodeSnippet.bind(this)); } else if (aRequests.length) { // when a single snippet should be shown, only update the value for the latest snippet this.getCodeSnippet(aRequests[aRequests.length - 1]); } } }; /** * clear cached data about snippets - on user request */ ControlInspector.prototype.clearSnippets = function () { ControlInspectorRepo.clear(); CommunicationBus.publish(CommunicationChannels.RECEIVE_CODE_SNIPPET, { codeSnippet: "" }); }; /** * stop listening for changes in the app */ ControlInspector.prototype.stop = function () { this._appObserver.stop(); this._selectedElementObserver.stop(); }; function _isAnySet(mData, vKey) { // are the vKey properties defined in the mData object var aKey = Array.isArray(vKey) ? vKey : [vKey]; return aKey.filter(function (sKey) { return mData[sKey] !== null && mData[sKey] !== undefined; }).length; } oControlInspector = new ControlInspector(); return oControlInspector; }, true);
apache-2.0
DimkaGorhover/zaremba
src/main/java/com/travelport/schema/air_v29_0/TicketEndorsement.java
1443
package com.travelport.schema.air_v29_0; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for anonymous complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;attribute name="Value" use="required" type="{http://www.travelport.com/schema/common_v29_0}typeEndorsement" /> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "") @XmlRootElement(name = "TicketEndorsement") public class TicketEndorsement { @XmlAttribute(name = "Value", required = true) protected String value; /** * Gets the value of the value property. * * @return * possible object is * {@link String } * */ public String getValue() { return value; } /** * Sets the value of the value property. * * @param value * allowed object is * {@link String } * */ public void setValue(String value) { this.value = value; } }
apache-2.0
thbonk/electron-openui5-boilerplate
libs/openui5-runtime/resources/sap/ui/commons/TextArea-dbg.js
10930
/*! * UI development toolkit for HTML5 (OpenUI5) * (c) Copyright 2009-2017 SAP SE or an SAP affiliate company. * Licensed under the Apache License, Version 2.0 - see LICENSE.txt. */ // Provides control sap.ui.commons.TextArea. sap.ui.define(['jquery.sap.global', './TextField', './library'], function(jQuery, TextField, library) { "use strict"; /** * Constructor for a new TextArea. * * @param {string} [sId] id for the new control, generated automatically if no id is given * @param {object} [mSettings] initial settings for the new control * * @class * Control to enter or display multible row text. * @extends sap.ui.commons.TextField * @version 1.50.8 * * @constructor * @public * @deprecated Since version 1.38. Instead, use the <code>sap.m.TextArea</code> control. * @alias sap.ui.commons.TextArea * @ui5-metamodel This control/element also will be described in the UI5 (legacy) designtime metamodel */ var TextArea = TextField.extend("sap.ui.commons.TextArea", /** @lends sap.ui.commons.TextArea.prototype */ { metadata : { library : "sap.ui.commons", properties : { /** * Height of text field. When it is set (CSS-size such as % or px), this is the exact size. */ height : {type : "sap.ui.core.CSSSize", group : "Dimension", defaultValue : null}, /** * Number of Columns. Cols means number of characters per row. This proprty is only used if Width is not used. */ cols : {type : "int", group : "Dimension", defaultValue : null}, /** * Number of Rows. This proprty is only used if Height is not used. */ rows : {type : "int", group : "Dimension", defaultValue : null}, /** * Text wrapping. Possible values are: Soft, Hard, Off. */ wrapping : {type : "sap.ui.core.Wrapping", group : "Appearance", defaultValue : null}, /** * Position of cursor, e.g., to let the user re-start typing at the same position as before the server roundtrip */ cursorPos : {type : "int", group : "Appearance", defaultValue : null}, /** * text which appears, in case quick-help is switched on */ explanation : {type : "string", group : "Misc", defaultValue : null}, /** * ID of label control * @deprecated Since version 1.5.2. * Please use association AriaLabelledBy instead. */ labeledBy : {type : "string", group : "Identification", defaultValue : null, deprecated: true} } }}); ///** // * This file defines the control behavior. // */ //.TextArea.prototype.init = function(){ // // do something for initialization... //}; /** * Exit handler */ TextArea.prototype.exit = function() { this._detachEventHandler(); }; /** * Event handler called before control is rendered */ TextArea.prototype.onBeforeRendering = function() { this._detachEventHandler(); }; /** * Event handler called after control is rendered */ TextArea.prototype.onAfterRendering = function () { TextField.prototype.onAfterRendering.apply(this, arguments); this._attachEventHandler(); }; /** * attaches the native event handlers */ TextArea.prototype._attachEventHandler = function() { var $this = this.$(); this.proChHandlerId = $this.bind('propertychange', jQuery.proxy(this.oninput, this)); // for IE }; /** * detaches the native event handlers */ TextArea.prototype._detachEventHandler = function() { // Unbind events var $this = this.$(); if (this.proChHandlerId) { $this.unbind('propertychange', this.oninput); this.proChHandlerId = null; } }; /** * Event handler called when control is getting the focus * * @param {jQuery.Event} oEvent The event object * @private */ TextArea.prototype.onfocusin = function(oEvent){ TextField.prototype.onfocusin.apply(this, arguments); // Set focus flag this.bFocus = true; oEvent.preventDefault(); }; /* * Event handler called when control is loosing the focus * * @param {jQuery.Event} oEvent * @private */ TextArea.prototype.onsapfocusleave = function(oEvent){ TextField.prototype.onsapfocusleave.apply(this, arguments); var oFocusDomRef = this.getFocusDomRef(); if (oFocusDomRef && !!sap.ui.Device.browser.firefox) { // Only for FF -> deselect text if (oFocusDomRef.selectionStart != oFocusDomRef.selectionEnd) { jQuery(oFocusDomRef).selectText(oFocusDomRef.selectionStart, oFocusDomRef.selectionStart); } } // Clear focus flag this.bFocus = false; oEvent.preventDefault(); oEvent.stopPropagation(); }; /* * Applies the focus info. * Overwrites the standard function. * @param {object} oFocusInfo Focusinfo object * @private */ TextArea.prototype.applyFocusInfo = function (oFocusInfo) { TextField.prototype.applyFocusInfo.apply(this, arguments); return this; }; /** * Event handler called on Key press * * @param {jQuery.Event} oEvent The event object * @private */ TextArea.prototype.onkeypress = function(oEvent){ TextField.prototype.onkeypress.apply(this, arguments); if (!this.getEditable() || !this.getEnabled() || this.getMaxLength() <= 0) { return; } var oKC = jQuery.sap.KeyCodes; var iKC = oEvent.which || oEvent.keyCode; var oDom = this.getDomRef(); // Check if some text is selected since this is different in Internet Explorer and FireFox // If some text is selected, it is overwritten by a key press -> Value will not get too large if (document.selection) { //IE var oSel = document.selection.createRange(); if (oSel.text.length > 0) { return; } } else { // FF if (oDom.selectionStart != oDom.selectionEnd) { return; } } // Only real characters and ENTER, no backspace if (oDom.value.length >= this.getMaxLength() && ( iKC > oKC.DELETE || iKC == oKC.ENTER || iKC == oKC.SPACE) && !oEvent.ctrlKey) { oEvent.preventDefault(); oEvent.stopPropagation(); } }; /** * Event handler called on Key up * * @param {jQuery.Event} oEvent The event object * @private */ TextArea.prototype.onkeyup = function(oEvent){ // save cursor position var oDomRef = this.getDomRef(); this.setProperty('cursorPos', jQuery(oDomRef).cursorPos(), true); // no re-rendering! // call keyup function of TextField to get liveChange event TextField.prototype.onkeyup.apply(this, arguments); }; /** * Event handler called when the enter key is pressed. * @see sap.ui.commons.TextField#onsapenter * @param {jQuery.Event} oEvent The event object * @private */ TextArea.prototype.onsapenter = function (oEvent) { // stop bubbling of event when in the textarea so other actions of parent control handlers won't be called. // don't do a prevent default because we want the default browser behavior...e.g. new line when pressing enter in the text area. oEvent.stopPropagation(); }; TextArea.prototype.onsapnext = function(oEvent) { if (jQuery(this.getFocusDomRef()).data("sap.InNavArea") && oEvent.keyCode != jQuery.sap.KeyCodes.END) { // parent handles arrow navigation oEvent.preventDefault(); return; } this._checkCursorPosForNav(oEvent, true); }; TextArea.prototype.onsapprevious = function(oEvent) { if (jQuery(this.getFocusDomRef()).data("sap.InNavArea") && oEvent.keyCode != jQuery.sap.KeyCodes.HOME) { // parent handles arrow navigation oEvent.preventDefault(); return; } this._checkCursorPosForNav(oEvent, false); }; TextArea.prototype.onsapnextmodifiers = TextArea.prototype.onsapnext; TextArea.prototype.onsappreviousmodifiers = TextArea.prototype.onsapprevious; TextArea.prototype.onsapend = TextArea.prototype.onsapnext; TextArea.prototype.onsaphome = TextArea.prototype.onsapprevious; /** * Event handler called on Mouse up * * @param {jQuery.Event} oEvent The event object * @private */ TextArea.prototype.onmouseup = function(oEvent){ // Save cursor position var oDomRef = this.getDomRef(); this.setProperty('cursorPos', jQuery(oDomRef).cursorPos(), true); // no re-rendering! }; /** * Event handler called on Paste * * @param {jQuery.Event} oEvent The event object * @private */ TextArea.prototype.onpaste = function(oEvent){ if (!this.getEditable() || !this.getEnabled() || this.getMaxLength() <= 0) { return; } var oDom = this.getDomRef(); if (oDom.value.length >= this.getMaxLength() && oDom.selectionStart == oDom.selectionEnd) { // already maxLenght reached and nothing selected -> no paste possible oEvent.preventDefault(); oEvent.stopPropagation(); } }; /** * Event handler called on Input * * @param {jQuery.Event} oEvent The event object * @private */ TextArea.prototype.oninput = function(oEvent){ if (oEvent.originalEvent && oEvent.originalEvent.propertyName && oEvent.originalEvent.propertyName.toLowerCase() != "value") { // In Internet Explorer, check for correct property return; } if (this.getEditable() && this.getEnabled() && this.getMaxLength() > 0) { var oDom = this.getDomRef(); // If text is entered or pasted, cut it if is too long if (oDom.value.length > this.getMaxLength()) { oDom.value = oDom.value.substring(0,this.getMaxLength()); } // The result is if text is pasted via clipboard or drag and drop the result is cut to fit the // maxLength. It's not easy to cut only the pasted text because in FireFox there is no access to the clipboard. // An option would be to store the old value after each change and compare it after each change. // Then the pasted text must be determined and cut. But this would need a lot of effort and script on // every change. } TextField.prototype.oninput.apply(this, arguments); // save cursor position var oDomRef = this.getDomRef(); this.setProperty('cursorPos', jQuery(oDomRef).cursorPos(), true); // no re-rendering! }; /** * Property setter for MaxLength * * @param {int} iMaxLength maximal length of text * @return {sap.ui.commons.TextArea} <code>this</code> to allow method chaining * @public */ TextArea.prototype.setMaxLength = function(iMaxLength) { this.setProperty('maxLength', iMaxLength, true); // No re-rendering var oDom = this.getDomRef(); if (oDom && oDom.value.length > iMaxLength && iMaxLength > 0 ) { oDom.value = oDom.value.substring(0,iMaxLength); } var sValue = this.getValue(); if (sValue.length > iMaxLength && iMaxLength > 0 ) { this.setProperty('value', sValue.substring(0,iMaxLength)); } return this; }; /** * Property setter for the cursor position * * @param {int} iCursorPos cursor position * @return {sap.ui.commons.TextArea} <code>this</code> to allow method chaining * @public */ TextArea.prototype.setCursorPos = function(iCursorPos) { this.setProperty('cursorPos', iCursorPos, true); // no re-rendering! if (this.bFocus) { jQuery(this.getDomRef()).cursorPos(iCursorPos); } return this; }; return TextArea; }, /* bExport= */ true);
apache-2.0
VladoLavor/vpp-agent
proto/ligato/annotations.pb.go
13252
// Code generated by protoc-gen-go. DO NOT EDIT. // versions: // protoc-gen-go v1.25.0 // protoc v3.12.4 // source: ligato/annotations.proto package ligato import ( proto "github.com/golang/protobuf/proto" descriptor "github.com/golang/protobuf/protoc-gen-go/descriptor" protoreflect "google.golang.org/protobuf/reflect/protoreflect" protoimpl "google.golang.org/protobuf/runtime/protoimpl" reflect "reflect" sync "sync" ) const ( // Verify that this generated code is sufficiently up-to-date. _ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion) // Verify that runtime/protoimpl is sufficiently up-to-date. _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) ) // This is a compile-time assertion that a sufficiently up-to-date version // of the legacy proto package is being used. const _ = proto.ProtoPackageIsVersion4 type LigatoOptions_Type int32 const ( LigatoOptions_UNSPECIFIED LigatoOptions_Type = 0 LigatoOptions_IP LigatoOptions_Type = 1 LigatoOptions_IPV4 LigatoOptions_Type = 2 LigatoOptions_IPV6 LigatoOptions_Type = 3 LigatoOptions_IP_WITH_MASK LigatoOptions_Type = 4 LigatoOptions_IPV4_WITH_MASK LigatoOptions_Type = 5 LigatoOptions_IPV6_WITH_MASK LigatoOptions_Type = 6 LigatoOptions_IP_OPTIONAL_MASK LigatoOptions_Type = 7 LigatoOptions_IPV4_OPTIONAL_MASK LigatoOptions_Type = 8 LigatoOptions_IPV6_OPTIONAL_MASK LigatoOptions_Type = 9 ) // Enum value maps for LigatoOptions_Type. var ( LigatoOptions_Type_name = map[int32]string{ 0: "UNSPECIFIED", 1: "IP", 2: "IPV4", 3: "IPV6", 4: "IP_WITH_MASK", 5: "IPV4_WITH_MASK", 6: "IPV6_WITH_MASK", 7: "IP_OPTIONAL_MASK", 8: "IPV4_OPTIONAL_MASK", 9: "IPV6_OPTIONAL_MASK", } LigatoOptions_Type_value = map[string]int32{ "UNSPECIFIED": 0, "IP": 1, "IPV4": 2, "IPV6": 3, "IP_WITH_MASK": 4, "IPV4_WITH_MASK": 5, "IPV6_WITH_MASK": 6, "IP_OPTIONAL_MASK": 7, "IPV4_OPTIONAL_MASK": 8, "IPV6_OPTIONAL_MASK": 9, } ) func (x LigatoOptions_Type) Enum() *LigatoOptions_Type { p := new(LigatoOptions_Type) *p = x return p } func (x LigatoOptions_Type) String() string { return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x)) } func (LigatoOptions_Type) Descriptor() protoreflect.EnumDescriptor { return file_ligato_annotations_proto_enumTypes[0].Descriptor() } func (LigatoOptions_Type) Type() protoreflect.EnumType { return &file_ligato_annotations_proto_enumTypes[0] } func (x LigatoOptions_Type) Number() protoreflect.EnumNumber { return protoreflect.EnumNumber(x) } // Deprecated: Use LigatoOptions_Type.Descriptor instead. func (LigatoOptions_Type) EnumDescriptor() ([]byte, []int) { return file_ligato_annotations_proto_rawDescGZIP(), []int{0, 0} } type LigatoOptions struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields Type LigatoOptions_Type `protobuf:"varint,1,opt,name=type,proto3,enum=ligato.LigatoOptions_Type" json:"type,omitempty"` IntRange *LigatoOptions_IntRange `protobuf:"bytes,2,opt,name=int_range,json=intRange,proto3" json:"int_range,omitempty"` } func (x *LigatoOptions) Reset() { *x = LigatoOptions{} if protoimpl.UnsafeEnabled { mi := &file_ligato_annotations_proto_msgTypes[0] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *LigatoOptions) String() string { return protoimpl.X.MessageStringOf(x) } func (*LigatoOptions) ProtoMessage() {} func (x *LigatoOptions) ProtoReflect() protoreflect.Message { mi := &file_ligato_annotations_proto_msgTypes[0] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use LigatoOptions.ProtoReflect.Descriptor instead. func (*LigatoOptions) Descriptor() ([]byte, []int) { return file_ligato_annotations_proto_rawDescGZIP(), []int{0} } func (x *LigatoOptions) GetType() LigatoOptions_Type { if x != nil { return x.Type } return LigatoOptions_UNSPECIFIED } func (x *LigatoOptions) GetIntRange() *LigatoOptions_IntRange { if x != nil { return x.IntRange } return nil } type LigatoOptions_IntRange struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields Minimum int64 `protobuf:"varint,1,opt,name=minimum,proto3" json:"minimum,omitempty"` Maximum uint64 `protobuf:"varint,2,opt,name=maximum,proto3" json:"maximum,omitempty"` } func (x *LigatoOptions_IntRange) Reset() { *x = LigatoOptions_IntRange{} if protoimpl.UnsafeEnabled { mi := &file_ligato_annotations_proto_msgTypes[1] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *LigatoOptions_IntRange) String() string { return protoimpl.X.MessageStringOf(x) } func (*LigatoOptions_IntRange) ProtoMessage() {} func (x *LigatoOptions_IntRange) ProtoReflect() protoreflect.Message { mi := &file_ligato_annotations_proto_msgTypes[1] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use LigatoOptions_IntRange.ProtoReflect.Descriptor instead. func (*LigatoOptions_IntRange) Descriptor() ([]byte, []int) { return file_ligato_annotations_proto_rawDescGZIP(), []int{0, 0} } func (x *LigatoOptions_IntRange) GetMinimum() int64 { if x != nil { return x.Minimum } return 0 } func (x *LigatoOptions_IntRange) GetMaximum() uint64 { if x != nil { return x.Maximum } return 0 } var file_ligato_annotations_proto_extTypes = []protoimpl.ExtensionInfo{ { ExtendedType: (*descriptor.FieldOptions)(nil), ExtensionType: (*LigatoOptions)(nil), Field: 2000, Name: "ligato.ligato_options", Tag: "bytes,2000,opt,name=ligato_options", Filename: "ligato/annotations.proto", }, } // Extension fields to descriptor.FieldOptions. var ( // NOTE: used option field index(2000) is in extension index range of descriptor.proto, but is not registered // in protobuf global extension registry (https://github.com/protocolbuffers/protobuf/blob/master/docs/options.md) // // optional ligato.LigatoOptions ligato_options = 2000; E_LigatoOptions = &file_ligato_annotations_proto_extTypes[0] ) var File_ligato_annotations_proto protoreflect.FileDescriptor var file_ligato_annotations_proto_rawDesc = []byte{ 0x0a, 0x18, 0x6c, 0x69, 0x67, 0x61, 0x74, 0x6f, 0x2f, 0x61, 0x6e, 0x6e, 0x6f, 0x74, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x12, 0x06, 0x6c, 0x69, 0x67, 0x61, 0x74, 0x6f, 0x1a, 0x20, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2f, 0x64, 0x65, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x6f, 0x72, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x22, 0xf2, 0x02, 0x0a, 0x0d, 0x4c, 0x69, 0x67, 0x61, 0x74, 0x6f, 0x4f, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x12, 0x2e, 0x0a, 0x04, 0x74, 0x79, 0x70, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0e, 0x32, 0x1a, 0x2e, 0x6c, 0x69, 0x67, 0x61, 0x74, 0x6f, 0x2e, 0x4c, 0x69, 0x67, 0x61, 0x74, 0x6f, 0x4f, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x2e, 0x54, 0x79, 0x70, 0x65, 0x52, 0x04, 0x74, 0x79, 0x70, 0x65, 0x12, 0x3b, 0x0a, 0x09, 0x69, 0x6e, 0x74, 0x5f, 0x72, 0x61, 0x6e, 0x67, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1e, 0x2e, 0x6c, 0x69, 0x67, 0x61, 0x74, 0x6f, 0x2e, 0x4c, 0x69, 0x67, 0x61, 0x74, 0x6f, 0x4f, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x2e, 0x49, 0x6e, 0x74, 0x52, 0x61, 0x6e, 0x67, 0x65, 0x52, 0x08, 0x69, 0x6e, 0x74, 0x52, 0x61, 0x6e, 0x67, 0x65, 0x1a, 0x3e, 0x0a, 0x08, 0x49, 0x6e, 0x74, 0x52, 0x61, 0x6e, 0x67, 0x65, 0x12, 0x18, 0x0a, 0x07, 0x6d, 0x69, 0x6e, 0x69, 0x6d, 0x75, 0x6d, 0x18, 0x01, 0x20, 0x01, 0x28, 0x03, 0x52, 0x07, 0x6d, 0x69, 0x6e, 0x69, 0x6d, 0x75, 0x6d, 0x12, 0x18, 0x0a, 0x07, 0x6d, 0x61, 0x78, 0x69, 0x6d, 0x75, 0x6d, 0x18, 0x02, 0x20, 0x01, 0x28, 0x04, 0x52, 0x07, 0x6d, 0x61, 0x78, 0x69, 0x6d, 0x75, 0x6d, 0x22, 0xb3, 0x01, 0x0a, 0x04, 0x54, 0x79, 0x70, 0x65, 0x12, 0x0f, 0x0a, 0x0b, 0x55, 0x4e, 0x53, 0x50, 0x45, 0x43, 0x49, 0x46, 0x49, 0x45, 0x44, 0x10, 0x00, 0x12, 0x06, 0x0a, 0x02, 0x49, 0x50, 0x10, 0x01, 0x12, 0x08, 0x0a, 0x04, 0x49, 0x50, 0x56, 0x34, 0x10, 0x02, 0x12, 0x08, 0x0a, 0x04, 0x49, 0x50, 0x56, 0x36, 0x10, 0x03, 0x12, 0x10, 0x0a, 0x0c, 0x49, 0x50, 0x5f, 0x57, 0x49, 0x54, 0x48, 0x5f, 0x4d, 0x41, 0x53, 0x4b, 0x10, 0x04, 0x12, 0x12, 0x0a, 0x0e, 0x49, 0x50, 0x56, 0x34, 0x5f, 0x57, 0x49, 0x54, 0x48, 0x5f, 0x4d, 0x41, 0x53, 0x4b, 0x10, 0x05, 0x12, 0x12, 0x0a, 0x0e, 0x49, 0x50, 0x56, 0x36, 0x5f, 0x57, 0x49, 0x54, 0x48, 0x5f, 0x4d, 0x41, 0x53, 0x4b, 0x10, 0x06, 0x12, 0x14, 0x0a, 0x10, 0x49, 0x50, 0x5f, 0x4f, 0x50, 0x54, 0x49, 0x4f, 0x4e, 0x41, 0x4c, 0x5f, 0x4d, 0x41, 0x53, 0x4b, 0x10, 0x07, 0x12, 0x16, 0x0a, 0x12, 0x49, 0x50, 0x56, 0x34, 0x5f, 0x4f, 0x50, 0x54, 0x49, 0x4f, 0x4e, 0x41, 0x4c, 0x5f, 0x4d, 0x41, 0x53, 0x4b, 0x10, 0x08, 0x12, 0x16, 0x0a, 0x12, 0x49, 0x50, 0x56, 0x36, 0x5f, 0x4f, 0x50, 0x54, 0x49, 0x4f, 0x4e, 0x41, 0x4c, 0x5f, 0x4d, 0x41, 0x53, 0x4b, 0x10, 0x09, 0x3a, 0x5c, 0x0a, 0x0e, 0x6c, 0x69, 0x67, 0x61, 0x74, 0x6f, 0x5f, 0x6f, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x12, 0x1d, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x46, 0x69, 0x65, 0x6c, 0x64, 0x4f, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x18, 0xd0, 0x0f, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x15, 0x2e, 0x6c, 0x69, 0x67, 0x61, 0x74, 0x6f, 0x2e, 0x4c, 0x69, 0x67, 0x61, 0x74, 0x6f, 0x4f, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x52, 0x0d, 0x6c, 0x69, 0x67, 0x61, 0x74, 0x6f, 0x4f, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x42, 0x28, 0x5a, 0x26, 0x67, 0x6f, 0x2e, 0x6c, 0x69, 0x67, 0x61, 0x74, 0x6f, 0x2e, 0x69, 0x6f, 0x2f, 0x76, 0x70, 0x70, 0x2d, 0x61, 0x67, 0x65, 0x6e, 0x74, 0x2f, 0x76, 0x33, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2f, 0x6c, 0x69, 0x67, 0x61, 0x74, 0x6f, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, } var ( file_ligato_annotations_proto_rawDescOnce sync.Once file_ligato_annotations_proto_rawDescData = file_ligato_annotations_proto_rawDesc ) func file_ligato_annotations_proto_rawDescGZIP() []byte { file_ligato_annotations_proto_rawDescOnce.Do(func() { file_ligato_annotations_proto_rawDescData = protoimpl.X.CompressGZIP(file_ligato_annotations_proto_rawDescData) }) return file_ligato_annotations_proto_rawDescData } var file_ligato_annotations_proto_enumTypes = make([]protoimpl.EnumInfo, 1) var file_ligato_annotations_proto_msgTypes = make([]protoimpl.MessageInfo, 2) var file_ligato_annotations_proto_goTypes = []interface{}{ (LigatoOptions_Type)(0), // 0: ligato.LigatoOptions.Type (*LigatoOptions)(nil), // 1: ligato.LigatoOptions (*LigatoOptions_IntRange)(nil), // 2: ligato.LigatoOptions.IntRange (*descriptor.FieldOptions)(nil), // 3: google.protobuf.FieldOptions } var file_ligato_annotations_proto_depIdxs = []int32{ 0, // 0: ligato.LigatoOptions.type:type_name -> ligato.LigatoOptions.Type 2, // 1: ligato.LigatoOptions.int_range:type_name -> ligato.LigatoOptions.IntRange 3, // 2: ligato.ligato_options:extendee -> google.protobuf.FieldOptions 1, // 3: ligato.ligato_options:type_name -> ligato.LigatoOptions 4, // [4:4] is the sub-list for method output_type 4, // [4:4] is the sub-list for method input_type 3, // [3:4] is the sub-list for extension type_name 2, // [2:3] is the sub-list for extension extendee 0, // [0:2] is the sub-list for field type_name } func init() { file_ligato_annotations_proto_init() } func file_ligato_annotations_proto_init() { if File_ligato_annotations_proto != nil { return } if !protoimpl.UnsafeEnabled { file_ligato_annotations_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*LigatoOptions); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_ligato_annotations_proto_msgTypes[1].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*LigatoOptions_IntRange); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } } type x struct{} out := protoimpl.TypeBuilder{ File: protoimpl.DescBuilder{ GoPackagePath: reflect.TypeOf(x{}).PkgPath(), RawDescriptor: file_ligato_annotations_proto_rawDesc, NumEnums: 1, NumMessages: 2, NumExtensions: 1, NumServices: 0, }, GoTypes: file_ligato_annotations_proto_goTypes, DependencyIndexes: file_ligato_annotations_proto_depIdxs, EnumInfos: file_ligato_annotations_proto_enumTypes, MessageInfos: file_ligato_annotations_proto_msgTypes, ExtensionInfos: file_ligato_annotations_proto_extTypes, }.Build() File_ligato_annotations_proto = out.File file_ligato_annotations_proto_rawDesc = nil file_ligato_annotations_proto_goTypes = nil file_ligato_annotations_proto_depIdxs = nil }
apache-2.0
iljaosintsev/Apress-Gists
app/src/main/java/com/turlir/abakgists/allgists/view/listing/ErrorModelHolder.java
541
package com.turlir.abakgists.allgists.view.listing; import android.view.View; import android.widget.TextView; import com.turlir.abakgists.model.ErrorModel; import butterknife.BindView; import butterknife.ButterKnife; class ErrorModelHolder extends ModelViewHolder<ErrorModel> { @BindView(android.R.id.text1) TextView errorTv; ErrorModelHolder(View view) { super(view); ButterKnife.bind(this, view); } @Override void bind(ErrorModel model) { errorTv.setText(model.description); } }
apache-2.0
CredentialTransparencyInitiative/CredentialFinderSearch
Data/Counts_SiteTotals.cs
833
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated from a template. // // Manual changes to this file may cause unexpected behavior in your application. // Manual changes to this file will be overwritten if the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace Data { using System; using System.Collections.Generic; public partial class Counts_SiteTotals { public int Id { get; set; } public int CategoryId { get; set; } public int EntityTypeId { get; set; } public Nullable<int> CodeId { get; set; } public string Description { get; set; } public Nullable<int> Totals { get; set; } } }
apache-2.0
batumi/KartuliSpeechRecognition
jni/edu/cmu/pocketsphinx/Lattice.java
1022
/* ---------------------------------------------------------------------------- * This file was automatically generated by SWIG (http://www.swig.org). * Version 1.3.40 * * Do not make changes to this file unless you know what you are doing--modify * the SWIG interface file instead. * ----------------------------------------------------------------------------- */ package edu.cmu.pocketsphinx; public class Lattice { private long swigCPtr; protected boolean swigCMemOwn; protected Lattice(long cPtr, boolean cMemoryOwn) { swigCMemOwn = cMemoryOwn; swigCPtr = cPtr; } protected static long getCPtr(Lattice obj) { return (obj == null) ? 0 : obj.swigCPtr; } protected void finalize() { delete(); } public synchronized void delete() { if (swigCPtr != 0) { if (swigCMemOwn) { swigCMemOwn = false; pocketsphinxJNI.delete_Lattice(swigCPtr); } swigCPtr = 0; } } public Lattice() { this(pocketsphinxJNI.new_Lattice(), true); } }
apache-2.0
dbeaver/dbeaver
plugins/org.jkiss.dbeaver.ui/src/org/jkiss/dbeaver/ui/controls/folders/TabbedFolderList.java
36146
/* * Copyright (c) 2001, 2012 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation * Mariot Chauvin <mariot.chauvin@obeo.fr> - bug 259553 * Amit Joglekar <joglekar@us.ibm.com> - Support for dynamic images (bug 385795) * * DBeaver - Universal Database Manager * Copyright (C) 2010-2022 DBeaver Corp 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.jkiss.dbeaver.ui.controls.folders; import org.eclipse.jface.resource.JFaceResources; import org.eclipse.jface.text.source.ISharedTextColors; import org.eclipse.swt.SWT; import org.eclipse.swt.accessibility.*; import org.eclipse.swt.events.*; import org.eclipse.swt.graphics.*; import org.eclipse.swt.layout.FormAttachment; import org.eclipse.swt.layout.FormData; import org.eclipse.swt.layout.FormLayout; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.widgets.*; import org.jkiss.dbeaver.ui.DBeaverIcons; import org.jkiss.dbeaver.ui.UIStyles; import org.jkiss.dbeaver.ui.UIUtils; import java.util.IdentityHashMap; import java.util.Map; /** * Shows the list of tabs in the tabbed property sheet page. * * @author Anthony Hunter * @author Serge Rider */ public class TabbedFolderList extends Composite { private static final ListElement[] ELEMENTS_EMPTY = new ListElement[0]; protected static final int NONE = -1; protected static final int INDENT_LEFT = 7; protected static final int INDENT_RIGHT = 10; public static final String LABEL_NA = "N/A"; public static final int SECTION_DIV_HEIGHT = 7; private final boolean section; private boolean focus = false; private ListElement[] elements; private int selectedElementIndex = NONE; private int topVisibleIndex = NONE; private int bottomVisibleIndex = NONE; private TopNavigationElement topNavigationElement; private BottomNavigationElement bottomNavigationElement; private int widestLabelIndex = NONE; private int tabsThatFitInComposite = NONE; Color widgetForeground; Color widgetNormalShadow; Color widgetDarkShadow; private Color listBackground; private Color hoverGradientStart; private Color hoverGradientEnd; private Color elementBackground; private Color indentedDefaultBackground; private Color indentedHoverBackground; private Color navigationElementShadowStroke; private Color bottomNavigationElementShadowStroke1; private Color bottomNavigationElementShadowStroke2; private final Map<Image, Image> grayedImages = new IdentityHashMap<>(); /** * One of the tabs in the tabbed property list. */ public class ListElement extends Canvas { private TabbedFolderInfo tab; private int index; private boolean selected; private boolean hover; /** * Constructor for ListElement. * * @param parent the parent Composite. * @param tab the tab item for the element. * @param index the index in the list. */ public ListElement(Composite parent, final TabbedFolderInfo tab, int index) { super(parent, SWT.NO_FOCUS); this.tab = tab; hover = false; selected = false; this.index = index; addPaintListener(this::paint); addMouseListener(new MouseAdapter() { public void mouseUp(MouseEvent e) { if (!selected) { select(getIndex(ListElement.this)); /* * We set focus to the tabbed property composite so that * focus is moved to the appropriate widget in the * section. */ Composite tabbedPropertyComposite = getParent(); tabbedPropertyComposite.setFocus(); } } }); addMouseMoveListener(e -> { String tooltip = tab.getTooltip(); if (tooltip != null) { setToolTipText(tooltip); } if (!hover) { hover = true; redraw(); } }); addMouseTrackListener(new MouseTrackAdapter() { public void mouseExit(MouseEvent e) { hover = false; redraw(); } }); } /** * Set selected value for this element. * * @param selected the selected value. */ public void setSelected(boolean selected) { this.selected = selected; redraw(); } /** * Paint the element. * * @param e the paint event. */ private void paint(PaintEvent e) { /* * draw the top two lines of the tab, same for selected, hover and * default */ Rectangle bounds = getBounds(); e.gc.setForeground(widgetNormalShadow); e.gc.drawLine(0, 0, bounds.width - 1, 0); e.gc.setForeground(listBackground); e.gc.drawLine(0, 1, bounds.width - 1, 1); /* draw the fill in the tab */ if (selected) { e.gc.setBackground(listBackground); e.gc.fillRectangle(0, 2, bounds.width, bounds.height - 1); } else if (hover && tab.isIndented()) { e.gc.setBackground(indentedHoverBackground); e.gc.fillRectangle(0, 2, bounds.width - 1, bounds.height - 1); } else if (hover) { e.gc.setForeground(hoverGradientStart); e.gc.setBackground(hoverGradientEnd); e.gc.fillGradientRectangle(0, 2, bounds.width - 1, bounds.height - 1, true); } else if (tab.isIndented()) { e.gc.setBackground(indentedDefaultBackground); e.gc.fillRectangle(0, 2, bounds.width - 1, bounds.height - 1); } else { e.gc.setBackground(elementBackground); e.gc.fillRectangle(0, 2, bounds.width - 1, bounds.height - 1); //e.gc.setBackground(defaultGradientEnd); //e.gc.fillGradientRectangle(0, 2, bounds.width - 1, bounds.height - 1, true); } if (!selected) { e.gc.setForeground(widgetNormalShadow); e.gc.drawLine(bounds.width - 1, 1, bounds.width - 1, bounds.height + 1); } /* * Add INDENT_LEFT pixels to the left as a margin. */ int textIndent = INDENT_LEFT; FontMetrics fm = e.gc.getFontMetrics(); int height = fm.getHeight(); int textMiddle = (bounds.height - height) / 2; if (tab.getImage() != null) { /* draw the icon for the selected tab */ if (tab.isIndented()) { textIndent = textIndent + INDENT_LEFT; } else { textIndent = textIndent - 3; } Image image = DBeaverIcons.getImage(tab.getImage()); if (selected || hover) { e.gc.drawImage(image, textIndent, textMiddle - 1); } else { e.gc.drawImage(getGrayedImage(image), textIndent, textMiddle - 1); } textIndent = textIndent + image.getBounds().width + 4; } else if (tab.isIndented()) { textIndent = textIndent + INDENT_LEFT; } /* draw the text */ e.gc.setForeground(widgetForeground); if (selected) { /* selected tab is bold font */ e.gc.setFont(JFaceResources.getFontRegistry().getBold(JFaceResources.DEFAULT_FONT)); } e.gc.drawText(tab.getText(), textIndent, textMiddle, true); if (((TabbedFolderList) getParent()).focus && selected) { /* draw a line if the tab has focus */ Point point = e.gc.textExtent(tab.getText()); e.gc.drawLine(textIndent, bounds.height - 4, textIndent + point.x, bounds.height - 4); } /* draw the bottom line on the tab for selected and default */ if (!hover) { e.gc.setForeground(listBackground); e.gc.drawLine(0, bounds.height - 1, bounds.width - 2, bounds.height - 1); } } /** * Get the tab item. * * @return the tab item. */ public TabbedFolderInfo getInfo() { return tab; } public String toString() { return tab.getText(); } } private Image getGrayedImage(Image image) { Image disabledImage = grayedImages.get(image); if (disabledImage == null) { disabledImage = new Image(image.getDevice(), image, SWT.IMAGE_GRAY); grayedImages.put(image, disabledImage); } return disabledImage; } /** * The top navigation element in the tabbed property list. It looks like a * scroll button when scrolling is needed or is just a spacer when no * scrolling is required. */ public class TopNavigationElement extends Canvas { /** * Constructor for TopNavigationElement. * * @param parent the parent Composite. */ public TopNavigationElement(Composite parent) { super(parent, SWT.NO_FOCUS); addPaintListener(this::paint); addMouseListener(new MouseAdapter() { public void mouseUp(MouseEvent e) { if (isUpScrollRequired()) { bottomVisibleIndex--; if (topVisibleIndex != 0) { topVisibleIndex--; } layoutTabs(); topNavigationElement.redraw(); bottomNavigationElement.redraw(); } } }); } /** * Paint the element. * * @param e the paint event. */ private void paint(PaintEvent e) { e.gc.setForeground(widgetForeground); Rectangle bounds = getBounds(); if (elements.length != 0) { e.gc.fillRectangle(0, 0, bounds.width, bounds.height); e.gc.setForeground(widgetNormalShadow); e.gc.drawLine(bounds.width - 1, 0, bounds.width - 1, bounds.height - 1); } else { e.gc.setBackground(listBackground); e.gc.fillRectangle(0, 0, bounds.width, bounds.height); int textIndent = INDENT_LEFT; FontMetrics fm = e.gc.getFontMetrics(); int height = fm.getHeight(); int textMiddle = (bounds.height - height) / 2; e.gc.setForeground(widgetForeground); e.gc.drawText(LABEL_NA, textIndent, textMiddle); } if (isUpScrollRequired()) { e.gc.setForeground(widgetDarkShadow); int middle = bounds.width / 2; e.gc.drawLine(middle + 1, 3, middle + 5, 7); e.gc.drawLine(middle, 3, middle - 4, 7); e.gc.drawLine(middle - 3, 7, middle + 4, 7); e.gc.setForeground(listBackground); e.gc.drawLine(middle, 4, middle + 1, 4); e.gc.drawLine(middle - 1, 5, middle + 2, 5); e.gc.drawLine(middle - 2, 6, middle + 3, 6); e.gc.setForeground(widgetNormalShadow); e.gc.drawLine(0, 0, bounds.width - 2, 0); e.gc.setForeground(navigationElementShadowStroke); e.gc.drawLine(0, 1, bounds.width - 2, 1); e.gc.drawLine(0, bounds.height - 1, bounds.width - 2, bounds.height - 1); } } } /** * The top navigation element in the tabbed property list. It looks like a * scroll button when scrolling is needed or is just a spacer when no * scrolling is required. */ public class BottomNavigationElement extends Canvas { /** * Constructor for BottomNavigationElement. * * @param parent the parent Composite. */ public BottomNavigationElement(Composite parent) { super(parent, SWT.NO_FOCUS); addPaintListener(this::paint); addMouseListener(new MouseAdapter() { public void mouseUp(MouseEvent e) { if (isDownScrollRequired()) { topVisibleIndex++; if (bottomVisibleIndex != elements.length - 1) { bottomVisibleIndex++; } layoutTabs(); topNavigationElement.redraw(); bottomNavigationElement.redraw(); } } }); } /** * Paint the element. * * @param e the paint event. */ private void paint(PaintEvent e) { e.gc.setForeground(widgetForeground); Rectangle bounds = getBounds(); if (elements.length != 0) { e.gc.fillRectangle(0, 0, bounds.width, bounds.height); e.gc.setForeground(widgetNormalShadow); if (!section || isDownScrollRequired()) { e.gc.drawLine(bounds.width - 1, 0, bounds.width - 1, bounds.height - 1); } else { e.gc.drawLine(bounds.width - 1, 0, bounds.width - 1, bounds.height - SECTION_DIV_HEIGHT); e.gc.drawPoint(bounds.width - 1, bounds.height - 1); } e.gc.drawLine(0, 0, bounds.width - 1, 0); e.gc.setForeground(bottomNavigationElementShadowStroke1); e.gc.drawLine(0, 1, bounds.width - 2, 1); e.gc.setForeground(bottomNavigationElementShadowStroke2); e.gc.drawLine(0, 2, bounds.width - 2, 2); } else { e.gc.setBackground(listBackground); e.gc.fillRectangle(0, 0, bounds.width, bounds.height); } if (isDownScrollRequired()) { e.gc.setForeground(widgetDarkShadow); int middle = bounds.width / 2; int bottom = bounds.height - 3; e.gc.drawLine(middle + 1, bottom, middle + 5, bottom - 4); e.gc.drawLine(middle, bottom, middle - 4, bottom - 4); e.gc.drawLine(middle - 3, bottom - 4, middle + 4, bottom - 4); e.gc.setForeground(listBackground); e.gc.drawLine(middle, bottom - 1, middle + 1, bottom - 1); e.gc.drawLine(middle - 1, bottom - 2, middle + 2, bottom - 2); e.gc.drawLine(middle - 2, bottom - 3, middle + 3, bottom - 3); e.gc.setForeground(widgetNormalShadow); e.gc.drawLine(0, bottom - 7, bounds.width - 2, bottom - 7); e.gc.setForeground(navigationElementShadowStroke); e.gc.drawLine(0, bottom + 2, bounds.width - 2, bottom + 2); e.gc.drawLine(0, bottom - 6, bounds.width - 2, bottom - 6); } } } public TabbedFolderList(Composite parent, boolean section) { super(parent, SWT.NO_FOCUS); //CSSUtils.setCSSClass(this, "MPartStack"); this.section = section; removeAll(); setLayout(new FormLayout()); topNavigationElement = new TopNavigationElement(this); bottomNavigationElement = new BottomNavigationElement(this); initColours(); initAccessible(); this.addFocusListener(new FocusListener() { public void focusGained(FocusEvent e) { focus = true; int i = getSelectionIndex(); if (i >= 0) { elements[i].redraw(); } } public void focusLost(FocusEvent e) { focus = false; int i = getSelectionIndex(); if (i >= 0) { elements[i].redraw(); } } }); this.addControlListener(new ControlAdapter() { public void controlResized(ControlEvent e) { computeTopAndBottomTab(); } }); this.addTraverseListener(this::handleTraverse); addDisposeListener(e -> { for (Image di : grayedImages.values()) { UIUtils.dispose(di); } grayedImages.clear(); }); } /** * Calculate the number of tabs that will fit in the tab list composite. */ protected void computeTabsThatFitInComposite() { tabsThatFitInComposite = Math .round((getSize().y - 22) / getTabHeight()); if (tabsThatFitInComposite <= 0) { tabsThatFitInComposite = 1; } } /** * Returns the number of elements in this list viewer. * * @return number of elements */ public int getNumberOfElements() { return elements.length; } /** * Returns the element with the given index from this list viewer. Returns * <code>null</code> if the index is out of range. * * @param index the zero-based index * @return the element at the given index, or <code>null</code> if the * index is out of range */ public ListElement getElementAt(int index) { if (index >= 0 && index < elements.length) { return elements[index]; } return null; } public TabbedFolderInfo[] getElements() { TabbedFolderInfo[] tabs = new TabbedFolderInfo[elements.length]; for (int i = 0; i < elements.length; i++) { tabs[i] = elements[i].getInfo(); } return tabs; } /** * Returns the zero-relative index of the item which is currently selected * in the receiver, or -1 if no item is selected. * * @return the index of the selected item */ public int getSelectionIndex() { return selectedElementIndex; } /** * Removes all elements from this list. */ public void removeAll() { if (elements != null) { for (ListElement element : elements) { element.dispose(); } } elements = ELEMENTS_EMPTY; selectedElementIndex = NONE; widestLabelIndex = NONE; topVisibleIndex = NONE; bottomVisibleIndex = NONE; } /** * Sets the new list elements. */ public void setFolders(TabbedFolderInfo[] children) { if (elements != ELEMENTS_EMPTY) { removeAll(); } elements = new ListElement[children.length]; if (children.length == 0) { widestLabelIndex = NONE; } else { widestLabelIndex = 0; for (int i = 0; i < children.length; i++) { elements[i] = new ListElement(this, children[i], i); elements[i].setVisible(false); elements[i].setLayoutData(null); if (i != widestLabelIndex) { int width = getTabWidth(children[i]); if (width > getTabWidth(children[widestLabelIndex])) { widestLabelIndex = i; } } } } int maxTabWidth = getTabWidth(children[widestLabelIndex]); Object layoutData = getLayoutData(); if (layoutData instanceof GridData) { ((GridData) layoutData).widthHint = maxTabWidth + INDENT_LEFT + INDENT_RIGHT; } computeTopAndBottomTab(); } private int getTabWidth(TabbedFolderInfo folderInfo) { int width = getTextDimension(folderInfo.getText()).x; /* * To anticipate for the icon placement we should always keep the * space available after the label. So when the active tab includes * an icon the width of the tab doesn't change. */ if (folderInfo.getImage() != null) { Image image = DBeaverIcons.getImage(folderInfo.getImage()); width = width + image.getBounds().width + 4; } if (folderInfo.isIndented()) { width = width + INDENT_LEFT; } return width; } /** * Selects one of the elements in the list. * * @param index the index of the element to select. */ public void select(int index) { select(index, true); } public void select(int index, boolean setFocus) { if (index >= 0 && index < elements.length) { int lastSelected = getSelectionIndex(); if (index == lastSelected) { return; } elements[index].setSelected(true); selectedElementIndex = index; if (lastSelected != NONE) { elements[lastSelected].setSelected(false); if (getSelectionIndex() != elements.length - 1) { /* * redraw the next tab to fix the border by calling * setSelected() */ elements[getSelectionIndex() + 1].setSelected(false); } } topNavigationElement.redraw(); bottomNavigationElement.redraw(); if (selectedElementIndex < topVisibleIndex || selectedElementIndex > bottomVisibleIndex) { computeTopAndBottomTab(); } } notifyListeners(SWT.Selection, new Event()); if (setFocus) { elements[index].getInfo().getContents().setFocus(); } } /** * Deselects all the elements in the list. */ public void deselectAll() { if (getSelectionIndex() != NONE) { elements[getSelectionIndex()].setSelected(false); selectedElementIndex = NONE; } } private int getIndex(ListElement element) { return element.index; } public Point computeSize(int wHint, int hHint, boolean changed) { Point result = super.computeSize(wHint, hHint, changed); Object layoutData = getLayoutData(); if (layoutData instanceof GridData && ((GridData) layoutData).widthHint != -1) { result.x = ((GridData) layoutData).widthHint; } else if (widestLabelIndex == -1) { result.x = getTextDimension(LABEL_NA).x + INDENT_LEFT; } else { /* * Add INDENT_LEFT pixels to the left of the longest tab as a margin. */ int width = getTabWidth(elements[widestLabelIndex].getInfo()) + INDENT_LEFT; /* * Add INDENT_RIGHT pixels to the right of the longest tab as a margin. */ result.x = width + INDENT_RIGHT; } return result; } /** * Get the dimensions of the provided string. * * @param text the string. * @return the dimensions of the provided string. */ private Point getTextDimension(String text) { GC gc = new GC(this); gc.setFont(JFaceResources.getFontRegistry().getBold( JFaceResources.DEFAULT_FONT)); Point point = gc.textExtent(text); point.x++; gc.dispose(); return point; } /** * Initialize the colours used in the list. */ private void initColours() { Display display = Display.getCurrent(); ISharedTextColors sharedColors = UIUtils.getSharedTextColors(); listBackground = UIStyles.getDefaultTextBackground(); Color widgetBackground; if (UIStyles.isDarkTheme()) { // By some reason E4 sets white background in dark theme. widgetBackground = UIStyles.getDefaultTextBackground(); super.setBackground(widgetBackground); topNavigationElement.setBackground(widgetBackground); bottomNavigationElement.setBackground(widgetBackground); } else { widgetBackground = getBackground(); } widgetForeground = UIStyles.getDefaultTextForeground(); widgetDarkShadow = display.getSystemColor(SWT.COLOR_WIDGET_DARK_SHADOW); widgetNormalShadow = display.getSystemColor(SWT.COLOR_WIDGET_NORMAL_SHADOW); RGB white = display.getSystemColor(SWT.COLOR_WHITE).getRGB(); RGB black = display.getSystemColor(SWT.COLOR_BLACK).getRGB(); /* * gradient in the default tab: start colour WIDGET_NORMAL_SHADOW 100% + * white 20% + INFO_BACKGROUND 60% end colour WIDGET_NORMAL_SHADOW 100% + * INFO_BACKGROUND 40% */ /* defaultGradientStart = sharedColors.getColor( UIUtils.blend(infoBackground, UIUtils.blend(white, widgetNormalShadow.getRGB(), 20), 60) ); defaultGradientEnd = sharedColors.getColor(UIUtils.blend(infoBackground, widgetNormalShadow.getRGB(), 40)); */ if (widgetNormalShadow.hashCode() < widgetBackground.hashCode()) { // Foreground darker than background - make element background darker elementBackground = sharedColors.getColor(UIUtils.blend(black, widgetBackground.getRGB(), 15)); } else { // Make element background lighter elementBackground = sharedColors.getColor(UIUtils.blend(white, widgetBackground.getRGB(), 15)); } navigationElementShadowStroke = sharedColors.getColor(UIUtils.blend(white, widgetNormalShadow.getRGB(), 55)); bottomNavigationElementShadowStroke1 = sharedColors.getColor(UIUtils.blend(black, widgetBackground.getRGB(), 10)); bottomNavigationElementShadowStroke2 = sharedColors.getColor(UIUtils.blend(black, widgetBackground.getRGB(), 5)); /* * gradient in the hover tab: start colour WIDGET_BACKGROUND 100% + * white 20% end colour WIDGET_BACKGROUND 100% + WIDGET_NORMAL_SHADOW * 10% */ hoverGradientStart = sharedColors.getColor(UIUtils.blend(white, widgetBackground.getRGB(), 20)); hoverGradientEnd = sharedColors.getColor(UIUtils.blend(widgetNormalShadow.getRGB(), widgetBackground.getRGB(), 10)); indentedDefaultBackground = sharedColors.getColor(UIUtils.blend(white, widgetBackground.getRGB(), 10)); indentedHoverBackground = sharedColors.getColor(UIUtils.blend(white, widgetBackground.getRGB(), 75)); } @Override public void setBackground(Color color) { super.setBackground(color); UIUtils.asyncExec(() -> { if (isDisposed()) { return; } initColours(); for (ListElement e : elements) { e.redraw(); } topNavigationElement.redraw(); bottomNavigationElement.redraw(); }); } /** * Get the height of a tab. The height of the tab is the height of the text * plus buffer. * * @return the height of a tab. */ int getTabHeight() { int tabHeight = getTextDimension("").y + INDENT_LEFT; //$NON-NLS-1$ if (tabsThatFitInComposite == 1) { /* * if only one tab will fix, reduce the size of the tab height so * that the navigation elements fit. */ int ret = getBounds().height - 20; return (ret > tabHeight) ? tabHeight : Math.max(ret, 5); } return tabHeight; } /** * Determine if a downward scrolling is required. * * @return true if downward scrolling is required. */ private boolean isDownScrollRequired() { return elements.length > tabsThatFitInComposite && bottomVisibleIndex != elements.length - 1; } /** * Determine if an upward scrolling is required. * * @return true if upward scrolling is required. */ private boolean isUpScrollRequired() { return elements.length > tabsThatFitInComposite && topVisibleIndex != 0; } /** * Based on available space, figure out the top and bottom tabs in the list. */ private void computeTopAndBottomTab() { computeTabsThatFitInComposite(); if (elements.length == 0) { /* * no tabs to display. */ topVisibleIndex = 0; bottomVisibleIndex = 0; } else if (tabsThatFitInComposite >= elements.length) { /* * all the tabs fit. */ topVisibleIndex = 0; bottomVisibleIndex = elements.length - 1; } else if (getSelectionIndex() == NONE) { /* * there is no selected tab yet, assume that tab one would * be selected for now. */ topVisibleIndex = 0; bottomVisibleIndex = tabsThatFitInComposite - 1; } else if (getSelectionIndex() + tabsThatFitInComposite > elements.length) { /* * the selected tab is near the bottom. */ bottomVisibleIndex = elements.length - 1; topVisibleIndex = bottomVisibleIndex - tabsThatFitInComposite + 1; } else { /* * the selected tab is near the top. */ topVisibleIndex = selectedElementIndex; bottomVisibleIndex = selectedElementIndex + tabsThatFitInComposite - 1; } layoutTabs(); } /** * Layout the tabs. */ private void layoutTabs() { if (tabsThatFitInComposite == NONE || elements.length == 0) { FormData formData = new FormData(); formData.left = new FormAttachment(0, 0); formData.right = new FormAttachment(100, 0); formData.top = new FormAttachment(0, 0); formData.height = getTabHeight(); topNavigationElement.setLayoutData(formData); formData = new FormData(); formData.left = new FormAttachment(0, 0); formData.right = new FormAttachment(100, 0); formData.top = new FormAttachment(topNavigationElement, 0); formData.bottom = new FormAttachment(100, 0); bottomNavigationElement.setLayoutData(formData); } else { FormData formData = new FormData(); formData.left = new FormAttachment(0, 0); formData.right = new FormAttachment(100, 0); formData.top = new FormAttachment(0, 0); formData.height = 10; topNavigationElement.setLayoutData(formData); /* * use nextElement to attach the layout to the previous canvas * widget in the list. */ Canvas nextElement = topNavigationElement; for (int i = 0; i < elements.length; i++) { if (i < topVisibleIndex || i > bottomVisibleIndex) { /* * this tab is not visible */ elements[i].setLayoutData(null); elements[i].setVisible(false); } else { /* * this tab is visible. */ formData = new FormData(); formData.height = getTabHeight(); formData.left = new FormAttachment(0, 0); formData.right = new FormAttachment(100, 0); formData.top = new FormAttachment(nextElement, 0); nextElement = elements[i]; elements[i].setLayoutData(formData); elements[i].setVisible(true); } } formData = new FormData(); formData.left = new FormAttachment(0, 0); formData.right = new FormAttachment(100, 0); formData.top = new FormAttachment(nextElement, 0); formData.bottom = new FormAttachment(100, 0); formData.height = 10; bottomNavigationElement.setLayoutData(formData); } // layout so that we have enough space for the new labels Composite grandparent = getParent().getParent(); grandparent.layout(true); layout(true); } /** * Initialize the accessibility adapter. */ private void initAccessible() { final Accessible accessible = getAccessible(); accessible.addAccessibleListener(new AccessibleAdapter() { public void getName(AccessibleEvent e) { if (getSelectionIndex() != NONE) { e.result = elements[getSelectionIndex()].getInfo().getText(); } } public void getHelp(AccessibleEvent e) { if (getSelectionIndex() != NONE) { e.result = elements[getSelectionIndex()].getInfo().getText(); } } }); accessible.addAccessibleControlListener(new AccessibleControlAdapter() { public void getChildAtPoint(AccessibleControlEvent e) { Point pt = toControl(new Point(e.x, e.y)); e.childID = (getBounds().contains(pt)) ? ACC.CHILDID_SELF : ACC.CHILDID_NONE; } public void getLocation(AccessibleControlEvent e) { if (getSelectionIndex() != NONE) { Rectangle location = elements[getSelectionIndex()].getBounds(); Point pt = toDisplay(new Point(location.x, location.y)); e.x = pt.x; e.y = pt.y; e.width = location.width; e.height = location.height; } } public void getChildCount(AccessibleControlEvent e) { e.detail = 0; } public void getRole(AccessibleControlEvent e) { e.detail = ACC.ROLE_TABITEM; } public void getState(AccessibleControlEvent e) { e.detail = ACC.STATE_SELECTABLE | ACC.STATE_SELECTED | ACC.STATE_FOCUSED | ACC.STATE_FOCUSABLE; } }); addListener(SWT.Selection, event -> { if (isFocusControl()) { accessible.setFocus(ACC.CHILDID_SELF); } }); addListener(SWT.FocusIn, event -> accessible.setFocus(ACC.CHILDID_SELF)); } public void addSelectionListener(SelectionListener listener) { checkWidget (); TypedListener typedListener = new TypedListener (listener); addListener (SWT.Selection,typedListener); addListener (SWT.DefaultSelection,typedListener); } public void handleTraverse(TraverseEvent e) { if (e.detail == SWT.TRAVERSE_PAGE_PREVIOUS || e.detail == SWT.TRAVERSE_PAGE_NEXT) { if ((e.stateMask & SWT.ALT) != SWT.ALT) { // Only in case of CTRL+ALT+PG return; } e.doit = false; int nMax = elements.length - 1; int nCurrent = getSelectionIndex(); if (e.detail == SWT.TRAVERSE_PAGE_PREVIOUS) { nCurrent -= 1; if (nCurrent < 0) { return; } } else { nCurrent += 1; if (nCurrent > nMax) { return; } } select(nCurrent); redraw(); } else { e.doit = true; } } }
apache-2.0
Waldrus/AssertDroid
library/src/java/ru/waldrus/assertdroid/AssertDroidConfig.java
1639
package ru.waldrus.assertdroid; import android.content.Context; import android.content.pm.ApplicationInfo; import ru.waldrus.assertdroid.handlers.AggregateHandler; /** * Created by Wald on 13.04.2014. */ public class AssertDroidConfig { /* package */ AssertDroidConfig(Context context){ this((context.getApplicationInfo().flags & ApplicationInfo.FLAG_DEBUGGABLE) > 0); } /* package */ AssertDroidConfig(boolean debug){ Assert.DEBUG = debug; } /* package */ AssertDroidConfig(){ } public AssertDroidConfig setHandleOnDebug(boolean handle){ if (handle){ Assert.HANDLE_LEVEL |= Assert.HANDLE_DEBUG; } else { Assert.HANDLE_LEVEL &= ~Assert.HANDLE_DEBUG; } return this; } public AssertDroidConfig setHandle(boolean handle){ if (handle){ Assert.HANDLE_LEVEL |= Assert.HANDLE_NORMAL; } else { Assert.HANDLE_LEVEL &= ~Assert.HANDLE_NORMAL; } return this; } public AssertDroidConfig setHandler(Handler handler){ Assert.HANDLER = handler; return this; } public AssertDroidConfig appendHandler(Handler handler){ if (null == Assert.HANDLER){ setHandler(handler); } else if (Assert.HANDLER instanceof AggregateHandler){ Assert.HANDLER.add(handler); } else { AggregateHandler aggregate = new AggregateHandler(); aggregate.add(Assert.HANDLER); aggregate.add(handler); Assert.HANDLER = aggregate; } return this; } }
apache-2.0
eliogrin/CISEN
project-java/cisen-core/src/main/java/com/epam/cisen/core/api/AbstractConnector.java
2770
package com.epam.cisen.core.api; import java.io.IOException; import java.util.Map; import org.apache.felix.scr.annotations.Component; import org.jongo.MongoCollection; import org.jongo.MongoCursor; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.epam.cisen.core.api.dto.CiReport; import com.epam.cisen.core.api.dto.ConfigDTO; import com.epam.cisen.core.api.dto.Constants; import com.google.common.collect.Maps; @Component(componentAbstract = true) public abstract class AbstractConnector<T extends ConfigDTO> extends AbstractPlugin<T> implements Connector { private static final Logger LOGGER = LoggerFactory.getLogger(AbstractConnector.class); @Override protected Constants.DB getTemplateTableName() { return Constants.DB.CI_PLUGINS; } @Override protected Constants.DB getConfigTableName() { return Constants.DB.CI_CONFIGS; } /** * Get build unique key. * * @param config * plugin configuration. * * @return * unique build key which help to find record in DB. */ protected abstract String getBuildKey(T config); @Override public void check() { MongoCollection collection = mongoDBService.getCollection(Constants.DB.BUILDS); Map<String, CiReport> resultsMap = Maps.newHashMap(); for (Map.Entry<String, T> entry : getJobs().entrySet()) { // Get build unique key String key = getBuildKey(entry.getValue()); try { // If build already checked CiReport report = resultsMap.get(key); if (report != null) { // Clone build report = report.clone(); } else { // Else check build info report = check(entry.getValue()); resultsMap.put(key, report); } // Set job id and add to reports list. report.setJobId(entry.getKey()); if (buildInDB(collection, report.getJobId(), report.getBuildId())) { collection.insert(report); } } catch (Exception ex) { LOGGER.error("Cannot check build.", ex); } } } private boolean buildInDB(MongoCollection collection, String jobId, String buildId) { try (MongoCursor cursor = collection.find("{ $and [ {jobId:#}, {buildId:#} ] }", jobId, buildId).as( CiReport.class)) { return !cursor.hasNext(); } catch (IOException e) { LOGGER.error("Fail to check Build Id", e); } return false; } protected abstract CiReport check(T config) throws Exception; }
apache-2.0
tellproject/telljava
java/src/main/ch/ethz/tell/ClientManager.java
4187
/* * (C) Copyright 2015 ETH Zurich Systems Group (http://www.systems.ethz.ch/) 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. * * Contributors: * Markus Pilman <mpilman@inf.ethz.ch> * Simon Loesing <sloesing@inf.ethz.ch> * Thomas Etter <etterth@gmail.com> * Kevin Bocksrocker <kevin.bocksrocker@gmail.com> * Lucas Braun <braunl@inf.ethz.ch> */ package ch.ethz.tell; public class ClientManager { public static String tellLib = "telljavaimpl"; static { System.loadLibrary(tellLib); } private long mImplPtr; private static native long getClientManagerPtr(long implPtr); final long getClientManagerPtr() { return getClientManagerPtr(mImplPtr); } public ClientManager(String commitManager, String tellStore) { mImplPtr = init(commitManager, tellStore); } public final long getImplPtr() { return mImplPtr; } private native long init(String commitManager, String tellStore); private native void shutdown(long ptr); public final void close() { shutdown(mImplPtr); } //private native void setMaxPendingResponsesImpl(long ptr, long value); //private native long getMaxPendingResponsesImpl(long ptr); //private native void setNumNetworkThreadsImpl(long ptr, long value); //private native long getNumNetworkThreadsImpl(long ptr); //private native void setReceiveBufferCountImpl(long ptr, long value); //private native long getReceiveBufferCountImpl(long ptr); //private native void setSendBufferCountImpl(long ptr, long value); //private native long getSendBufferCountImpl(long ptr); //private native void setBufferLengthImpl(long ptr, long value); //private native long getBufferLengthImpl(long ptr); //private native void setCompletionQueueLengthImpl(long ptr, long value); //private native long getCompletionQueueLengthImpl(long ptr); //private native void setSendQueueLengthImpl(long ptr, long value); //private native long getSendQueueLengthImpl(long ptr); //public final void setMaxPendingResponses(long value) { // setMaxPendingResponsesImpl(mImplPtr, value); //} //public final long getMaxPendingResponses() { // return getMaxPendingResponsesImpl(mImplPtr); //} //public final void setNumNetworkThreads(long value) { // setNumNetworkThreadsImpl(mImplPtr, value); //} //public final long getNumNetworkThreads() { // return getNumNetworkThreadsImpl(mImplPtr); //} //public final void setReceiveBufferCount(long value) { // setReceiveBufferCountImpl(mImplPtr, value); //} //public final long getReceiveBufferCount() { // return getReceiveBufferCountImpl(mImplPtr); //} //public final void setSendBufferCount(long value) { // setSendBufferCountImpl(mImplPtr, value); //} //public final long getSendBufferCount() { // return getSendBufferCountImpl(mImplPtr); //} //public final void setBufferLength(long value) { // setBufferLengthImpl(mImplPtr, value); //} //public final long getBufferLength() { // return getBufferLengthImpl(mImplPtr); //} //public final void setCompletionQueueLength(long value) { // setCompletionQueueLengthImpl(mImplPtr, value); //} //public final long getCompletionQueueLength() { // return getCompletionQueueLengthImpl(mImplPtr); //} //public final void setSendQueueLength(long value) { // setSendQueueLengthImpl(mImplPtr, value); //} //public final long getSendQueueLength() { // return getSendQueueLengthImpl(mImplPtr); //} }
apache-2.0
chrisekelley/zeprs
src/zeprs/org/cidrz/project/zeprs/valueobject/report/gen/PostnatalMaternalVisitReport.java
33395
package org.cidrz.project.zeprs.valueobject.report.gen; import org.cidrz.project.zeprs.valueobject.EncounterData; import org.cidrz.webapp.dynasite.valueobject.Patient; import java.sql.Date; import java.util.Set; import java.sql.Time; import java.sql.Timestamp; import org.cidrz.webapp.dynasite.valueobject.AuditInfo; import java.util.TreeSet; /** * JavaBean PostnatalMaternalVisitReport generated from database; * generated by DynasiteSourceGenerator, inspired by XslBeanGenerator by Klaus Berg. * * @author Chris Kelley * Date: 2014-10-27 * Time: 17:44:31 * Form Name: Postnatal Maternal Visit * Form Id: 28 */ /** * @hibernate.joined-subclass table="postnatalmaternalvisit" * @hibernate.joined-subclass-key column="id" */ public class PostnatalMaternalVisitReport extends EncounterData { private transient Integer postnatal_visit_601; //postnatal_visit_601 private String postnatal_visit_601R; private transient Integer day_of_puerperium_611; //day_of_puerperium_611 private String day_of_puerperium_611R; private transient Integer pulse_171; //pulse_171 private String pulse_171R; private transient Integer bp_systolic_224; //bp_systolic_224 private String bp_systolic_224R; private transient Integer bp_diastolic_225; //bp_diastolic_225 private String bp_diastolic_225R; private transient Integer hb_235; //hb_235 private String hb_235R; private transient Integer urinalysis_240; //urinalysis_240 private String urinalysis_240R; private transient Integer urinalysis_alb_242; //urinalysis_alb_242 private String urinalysis_alb_242R; private transient Integer urinalysis_glu_243; //urinalysis_glu_243 private String urinalysis_glu_243R; private transient Integer urinalysis_ace_244; //urinalysis_ace_244 private String urinalysis_ace_244R; private transient Byte anti_d_given_621; //anti_d_given_621 private String anti_d_given_621R; private transient String other_complaints_622; //other_complaints_622 private String other_complaints_622R; private transient Integer breast_feeding_623; //breast_feeding_623 private String breast_feeding_623R; private transient Integer hair_625; //hair_625 private String hair_625R; private transient Integer eyes_626; //eyes_626 private String eyes_626R; private transient String eyes_other_627; //eyes_other_627 private String eyes_other_627R; private transient Integer mouth_628; //mouth_628 private String mouth_628R; private transient String mouth_other_1191; //mouth_other_1191 private String mouth_other_1191R; private transient Integer teeth_163; //teeth_163 private String teeth_163R; private transient String teeth_other_164; //teeth_other_164 private String teeth_other_164R; private transient Integer thyroid_165; //thyroid_165 private String thyroid_165R; private transient Integer breasts_166; //breasts_166 private String breasts_166R; private transient Integer nipples_633; //nipples_633 private String nipples_633R; private transient Integer lymphadenopa_1208; //lymphadenopa_1208 private String lymphadenopa_1208R; private transient String lymphadenopa_desc_1209; //lymphadenopa_desc_1209 private String lymphadenopa_desc_1209R; private transient Integer uterus_187; //uterus_187 private String uterus_187R; private transient Integer perineum_580; //perineum_580 private String perineum_580R; private transient String perineum_other_1199; //perineum_other_1199 private String perineum_other_1199R; private transient String perineum_infect_desc_1198; //perineum_infect_desc_1198 private String perineum_infect_desc_1198R; private transient Integer anus_638; //anus_638 private String anus_638R; private transient Integer bowels_639; //bowels_639 private String bowels_639R; private transient String bowels_abno_640; //bowels_abno_640 private String bowels_abno_640R; private transient Integer micturition_641; //micturition_641 private String micturition_641R; private transient String micturition_desc_642; //micturition_desc_642 private String micturition_desc_642R; private transient Integer wound_643; //wound_643 private String wound_643R; private transient String wound_abnor_644; //wound_abnor_644 private String wound_abnor_644R; private transient Integer lochia_flow_645; //lochia_flow_645 private String lochia_flow_645R; private transient Integer lochia_colou_646; //lochia_colou_646 private String lochia_colou_646R; private transient Integer lochia_odor_647; //lochia_odor_647 private String lochia_odor_647R; private transient Integer legs_649; //legs_649 private String legs_649R; private transient Integer cervix_per_spec_666; //cervix_per_spec_666 private String cervix_per_spec_666R; private transient Integer cervix_per_spec_result_667; //cervix_per_spec_result_667 private String cervix_per_spec_result_667R; private transient Byte patient_received_arv; //patient_received_arv private String patient_received_arvR; private transient Boolean is_problem; //is_problem private String is_problemR; private transient Byte contraceptive_advice_669; //contraceptive_advice_669 private String contraceptive_advice_669R; private transient Byte using_contraception_670; //using_contraception_670 private String using_contraception_670R; private transient Integer contraceptive_choice_137; //contraceptive_choice_137 private String contraceptive_choice_137R; private transient String contraceptive_other_138; //contraceptive_other_138 private String contraceptive_other_138R; private transient Integer education1; //education1 private String education1R; private transient Integer education2; //education2 private String education2R; private transient Integer education3; //education3 private String education3R; private transient Integer education4; //education4 private String education4R; private transient Integer education5; //education5 private String education5R; private transient Integer education6; //education6 private String education6R; private transient Integer education7; //education7 private String education7R; private transient String health_educa_discussed_other_674; //health_educa_discussed_other_674 private String health_educa_discussed_other_674R; private transient String postnatal_comments; //postnatal_comments private String postnatal_commentsR; /** * @return * @hibernate.property column="postnatal_visit_601" */ public Integer getPostnatal_visit_601() { return this.postnatal_visit_601; } public void setPostnatal_visit_601(Integer postnatal_visit_601) { this.postnatal_visit_601 = postnatal_visit_601; } public String getPostnatal_visit_601R() { return this.postnatal_visit_601R; } public void setPostnatal_visit_601R(String postnatal_visit_601R) { this.postnatal_visit_601R = postnatal_visit_601R; } public String getDay_of_puerperium_611R() { return this.day_of_puerperium_611R; } public void setDay_of_puerperium_611R(String day_of_puerperium_611R) { this.day_of_puerperium_611R = day_of_puerperium_611R; } /** * @return * @hibernate.property column="pulse_171" */ public Integer getPulse_171() { return this.pulse_171; } public void setPulse_171(Integer pulse_171) { this.pulse_171 = pulse_171; } public String getPulse_171R() { return this.pulse_171R; } public void setPulse_171R(String pulse_171R) { this.pulse_171R = pulse_171R; } /** * @return * @hibernate.property column="bp_systolic_224" */ public Integer getBp_systolic_224() { return this.bp_systolic_224; } public void setBp_systolic_224(Integer bp_systolic_224) { this.bp_systolic_224 = bp_systolic_224; } public String getBp_systolic_224R() { return this.bp_systolic_224R; } public void setBp_systolic_224R(String bp_systolic_224R) { this.bp_systolic_224R = bp_systolic_224R; } /** * @return * @hibernate.property column="bp_diastolic_225" */ public Integer getBp_diastolic_225() { return this.bp_diastolic_225; } public void setBp_diastolic_225(Integer bp_diastolic_225) { this.bp_diastolic_225 = bp_diastolic_225; } public String getBp_diastolic_225R() { return this.bp_diastolic_225R; } public void setBp_diastolic_225R(String bp_diastolic_225R) { this.bp_diastolic_225R = bp_diastolic_225R; } /** * @return * @hibernate.property column="hb_235" */ public Integer getHb_235() { return this.hb_235; } public void setHb_235(Integer hb_235) { this.hb_235 = hb_235; } public String getHb_235R() { return this.hb_235R; } public void setHb_235R(String hb_235R) { this.hb_235R = hb_235R; } /** * @return * @hibernate.property column="urinalysis_240" */ public Integer getUrinalysis_240() { return this.urinalysis_240; } public void setUrinalysis_240(Integer urinalysis_240) { this.urinalysis_240 = urinalysis_240; } public String getUrinalysis_240R() { return this.urinalysis_240R; } public void setUrinalysis_240R(String urinalysis_240R) { this.urinalysis_240R = urinalysis_240R; } /** * @return * @hibernate.property column="urinalysis_alb_242" */ public Integer getUrinalysis_alb_242() { return this.urinalysis_alb_242; } public void setUrinalysis_alb_242(Integer urinalysis_alb_242) { this.urinalysis_alb_242 = urinalysis_alb_242; } public String getUrinalysis_alb_242R() { return this.urinalysis_alb_242R; } public void setUrinalysis_alb_242R(String urinalysis_alb_242R) { this.urinalysis_alb_242R = urinalysis_alb_242R; } /** * @return * @hibernate.property column="urinalysis_glu_243" */ public Integer getUrinalysis_glu_243() { return this.urinalysis_glu_243; } public void setUrinalysis_glu_243(Integer urinalysis_glu_243) { this.urinalysis_glu_243 = urinalysis_glu_243; } public String getUrinalysis_glu_243R() { return this.urinalysis_glu_243R; } public void setUrinalysis_glu_243R(String urinalysis_glu_243R) { this.urinalysis_glu_243R = urinalysis_glu_243R; } /** * @return * @hibernate.property column="urinalysis_ace_244" */ public Integer getUrinalysis_ace_244() { return this.urinalysis_ace_244; } public void setUrinalysis_ace_244(Integer urinalysis_ace_244) { this.urinalysis_ace_244 = urinalysis_ace_244; } public String getUrinalysis_ace_244R() { return this.urinalysis_ace_244R; } public void setUrinalysis_ace_244R(String urinalysis_ace_244R) { this.urinalysis_ace_244R = urinalysis_ace_244R; } /** * @return * @hibernate.property column="anti_d_given_621" */ public Byte getAnti_d_given_621() { return this.anti_d_given_621; } public void setAnti_d_given_621(Byte anti_d_given_621) { this.anti_d_given_621 = anti_d_given_621; } public String getAnti_d_given_621R() { return this.anti_d_given_621R; } public void setAnti_d_given_621R(String anti_d_given_621R) { this.anti_d_given_621R = anti_d_given_621R; } /** * @return * @hibernate.property column="other_complaints_622" type="text" */ public String getOther_complaints_622() { return this.other_complaints_622; } public void setOther_complaints_622(String other_complaints_622) { this.other_complaints_622 = other_complaints_622; } public String getOther_complaints_622R() { return this.other_complaints_622R; } public void setOther_complaints_622R(String other_complaints_622R) { this.other_complaints_622R = other_complaints_622R; } public String getBreast_feeding_623R() { return this.breast_feeding_623R; } public void setBreast_feeding_623R(String breast_feeding_623R) { this.breast_feeding_623R = breast_feeding_623R; } /** * @return * @hibernate.property column="hair_625" */ public Integer getHair_625() { return this.hair_625; } public void setHair_625(Integer hair_625) { this.hair_625 = hair_625; } public String getHair_625R() { return this.hair_625R; } public void setHair_625R(String hair_625R) { this.hair_625R = hair_625R; } /** * @return * @hibernate.property column="eyes_626" */ public Integer getEyes_626() { return this.eyes_626; } public void setEyes_626(Integer eyes_626) { this.eyes_626 = eyes_626; } public String getEyes_626R() { return this.eyes_626R; } public void setEyes_626R(String eyes_626R) { this.eyes_626R = eyes_626R; } /** * @return * @hibernate.property column="eyes_other_627" type="text" */ public String getEyes_other_627() { return this.eyes_other_627; } public void setEyes_other_627(String eyes_other_627) { this.eyes_other_627 = eyes_other_627; } public String getEyes_other_627R() { return this.eyes_other_627R; } public void setEyes_other_627R(String eyes_other_627R) { this.eyes_other_627R = eyes_other_627R; } /** * @return * @hibernate.property column="mouth_628" */ public Integer getMouth_628() { return this.mouth_628; } public void setMouth_628(Integer mouth_628) { this.mouth_628 = mouth_628; } public String getMouth_628R() { return this.mouth_628R; } public void setMouth_628R(String mouth_628R) { this.mouth_628R = mouth_628R; } /** * @return * @hibernate.property column="mouth_other_1191" type="text" */ public String getMouth_other_1191() { return this.mouth_other_1191; } public void setMouth_other_1191(String mouth_other_1191) { this.mouth_other_1191 = mouth_other_1191; } public String getMouth_other_1191R() { return this.mouth_other_1191R; } public void setMouth_other_1191R(String mouth_other_1191R) { this.mouth_other_1191R = mouth_other_1191R; } /** * @return * @hibernate.property column="teeth_163" */ public Integer getTeeth_163() { return this.teeth_163; } public void setTeeth_163(Integer teeth_163) { this.teeth_163 = teeth_163; } public String getTeeth_163R() { return this.teeth_163R; } public void setTeeth_163R(String teeth_163R) { this.teeth_163R = teeth_163R; } /** * @return * @hibernate.property column="teeth_other_164" type="text" */ public String getTeeth_other_164() { return this.teeth_other_164; } public void setTeeth_other_164(String teeth_other_164) { this.teeth_other_164 = teeth_other_164; } public String getTeeth_other_164R() { return this.teeth_other_164R; } public void setTeeth_other_164R(String teeth_other_164R) { this.teeth_other_164R = teeth_other_164R; } /** * @return * @hibernate.property column="thyroid_165" */ public Integer getThyroid_165() { return this.thyroid_165; } public void setThyroid_165(Integer thyroid_165) { this.thyroid_165 = thyroid_165; } public String getThyroid_165R() { return this.thyroid_165R; } public void setThyroid_165R(String thyroid_165R) { this.thyroid_165R = thyroid_165R; } /** * @return * @hibernate.property column="breasts_166" */ public Integer getBreasts_166() { return this.breasts_166; } public void setBreasts_166(Integer breasts_166) { this.breasts_166 = breasts_166; } public String getBreasts_166R() { return this.breasts_166R; } public void setBreasts_166R(String breasts_166R) { this.breasts_166R = breasts_166R; } /** * @return * @hibernate.property column="nipples_633" */ public Integer getNipples_633() { return this.nipples_633; } public void setNipples_633(Integer nipples_633) { this.nipples_633 = nipples_633; } public String getNipples_633R() { return this.nipples_633R; } public void setNipples_633R(String nipples_633R) { this.nipples_633R = nipples_633R; } /** * @return * @hibernate.property column="lymphadenopa_1208" */ public Integer getLymphadenopa_1208() { return this.lymphadenopa_1208; } public void setLymphadenopa_1208(Integer lymphadenopa_1208) { this.lymphadenopa_1208 = lymphadenopa_1208; } public String getLymphadenopa_1208R() { return this.lymphadenopa_1208R; } public void setLymphadenopa_1208R(String lymphadenopa_1208R) { this.lymphadenopa_1208R = lymphadenopa_1208R; } /** * @return * @hibernate.property column="lymphadenopa_desc_1209" type="text" */ public String getLymphadenopa_desc_1209() { return this.lymphadenopa_desc_1209; } public void setLymphadenopa_desc_1209(String lymphadenopa_desc_1209) { this.lymphadenopa_desc_1209 = lymphadenopa_desc_1209; } public String getLymphadenopa_desc_1209R() { return this.lymphadenopa_desc_1209R; } public void setLymphadenopa_desc_1209R(String lymphadenopa_desc_1209R) { this.lymphadenopa_desc_1209R = lymphadenopa_desc_1209R; } /** * @return * @hibernate.property column="uterus_187" */ public Integer getUterus_187() { return this.uterus_187; } public void setUterus_187(Integer uterus_187) { this.uterus_187 = uterus_187; } public String getUterus_187R() { return this.uterus_187R; } public void setUterus_187R(String uterus_187R) { this.uterus_187R = uterus_187R; } /** * @return * @hibernate.property column="perineum_580" */ public Integer getPerineum_580() { return this.perineum_580; } public void setPerineum_580(Integer perineum_580) { this.perineum_580 = perineum_580; } public String getPerineum_580R() { return this.perineum_580R; } public void setPerineum_580R(String perineum_580R) { this.perineum_580R = perineum_580R; } /** * @return * @hibernate.property column="perineum_other_1199" type="text" */ public String getPerineum_other_1199() { return this.perineum_other_1199; } public void setPerineum_other_1199(String perineum_other_1199) { this.perineum_other_1199 = perineum_other_1199; } public String getPerineum_other_1199R() { return this.perineum_other_1199R; } public void setPerineum_other_1199R(String perineum_other_1199R) { this.perineum_other_1199R = perineum_other_1199R; } /** * @return * @hibernate.property column="perineum_infect_desc_1198" type="text" */ public String getPerineum_infect_desc_1198() { return this.perineum_infect_desc_1198; } public void setPerineum_infect_desc_1198(String perineum_infect_desc_1198) { this.perineum_infect_desc_1198 = perineum_infect_desc_1198; } public String getPerineum_infect_desc_1198R() { return this.perineum_infect_desc_1198R; } public void setPerineum_infect_desc_1198R(String perineum_infect_desc_1198R) { this.perineum_infect_desc_1198R = perineum_infect_desc_1198R; } /** * @return * @hibernate.property column="anus_638" */ public Integer getAnus_638() { return this.anus_638; } public void setAnus_638(Integer anus_638) { this.anus_638 = anus_638; } public String getAnus_638R() { return this.anus_638R; } public void setAnus_638R(String anus_638R) { this.anus_638R = anus_638R; } /** * @return * @hibernate.property column="bowels_639" */ public Integer getBowels_639() { return this.bowels_639; } public void setBowels_639(Integer bowels_639) { this.bowels_639 = bowels_639; } public String getBowels_639R() { return this.bowels_639R; } public void setBowels_639R(String bowels_639R) { this.bowels_639R = bowels_639R; } /** * @return * @hibernate.property column="bowels_abno_640" type="text" */ public String getBowels_abno_640() { return this.bowels_abno_640; } public void setBowels_abno_640(String bowels_abno_640) { this.bowels_abno_640 = bowels_abno_640; } public String getBowels_abno_640R() { return this.bowels_abno_640R; } public void setBowels_abno_640R(String bowels_abno_640R) { this.bowels_abno_640R = bowels_abno_640R; } /** * @return * @hibernate.property column="micturition_641" */ public Integer getMicturition_641() { return this.micturition_641; } public void setMicturition_641(Integer micturition_641) { this.micturition_641 = micturition_641; } public String getMicturition_641R() { return this.micturition_641R; } public void setMicturition_641R(String micturition_641R) { this.micturition_641R = micturition_641R; } /** * @return * @hibernate.property column="micturition_desc_642" type="text" */ public String getMicturition_desc_642() { return this.micturition_desc_642; } public void setMicturition_desc_642(String micturition_desc_642) { this.micturition_desc_642 = micturition_desc_642; } public String getMicturition_desc_642R() { return this.micturition_desc_642R; } public void setMicturition_desc_642R(String micturition_desc_642R) { this.micturition_desc_642R = micturition_desc_642R; } /** * @return * @hibernate.property column="wound_643" */ public Integer getWound_643() { return this.wound_643; } public void setWound_643(Integer wound_643) { this.wound_643 = wound_643; } public String getWound_643R() { return this.wound_643R; } public void setWound_643R(String wound_643R) { this.wound_643R = wound_643R; } /** * @return * @hibernate.property column="wound_abnor_644" type="text" */ public String getWound_abnor_644() { return this.wound_abnor_644; } public void setWound_abnor_644(String wound_abnor_644) { this.wound_abnor_644 = wound_abnor_644; } public String getWound_abnor_644R() { return this.wound_abnor_644R; } public void setWound_abnor_644R(String wound_abnor_644R) { this.wound_abnor_644R = wound_abnor_644R; } /** * @return * @hibernate.property column="lochia_flow_645" */ public Integer getLochia_flow_645() { return this.lochia_flow_645; } public void setLochia_flow_645(Integer lochia_flow_645) { this.lochia_flow_645 = lochia_flow_645; } public String getLochia_flow_645R() { return this.lochia_flow_645R; } public void setLochia_flow_645R(String lochia_flow_645R) { this.lochia_flow_645R = lochia_flow_645R; } /** * @return * @hibernate.property column="lochia_colou_646" */ public Integer getLochia_colou_646() { return this.lochia_colou_646; } public void setLochia_colou_646(Integer lochia_colou_646) { this.lochia_colou_646 = lochia_colou_646; } public String getLochia_colou_646R() { return this.lochia_colou_646R; } public void setLochia_colou_646R(String lochia_colou_646R) { this.lochia_colou_646R = lochia_colou_646R; } /** * @return * @hibernate.property column="lochia_odor_647" */ public Integer getLochia_odor_647() { return this.lochia_odor_647; } public void setLochia_odor_647(Integer lochia_odor_647) { this.lochia_odor_647 = lochia_odor_647; } public String getLochia_odor_647R() { return this.lochia_odor_647R; } public void setLochia_odor_647R(String lochia_odor_647R) { this.lochia_odor_647R = lochia_odor_647R; } /** * @return * @hibernate.property column="legs_649" */ public Integer getLegs_649() { return this.legs_649; } public void setLegs_649(Integer legs_649) { this.legs_649 = legs_649; } public String getLegs_649R() { return this.legs_649R; } public void setLegs_649R(String legs_649R) { this.legs_649R = legs_649R; } /** * @return * @hibernate.property column="cervix_per_spec_666" */ public Integer getCervix_per_spec_666() { return this.cervix_per_spec_666; } public void setCervix_per_spec_666(Integer cervix_per_spec_666) { this.cervix_per_spec_666 = cervix_per_spec_666; } public String getCervix_per_spec_666R() { return this.cervix_per_spec_666R; } public void setCervix_per_spec_666R(String cervix_per_spec_666R) { this.cervix_per_spec_666R = cervix_per_spec_666R; } /** * @return * @hibernate.property column="cervix_per_spec_result_667" */ public Integer getCervix_per_spec_result_667() { return this.cervix_per_spec_result_667; } public void setCervix_per_spec_result_667(Integer cervix_per_spec_result_667) { this.cervix_per_spec_result_667 = cervix_per_spec_result_667; } public String getCervix_per_spec_result_667R() { return this.cervix_per_spec_result_667R; } public void setCervix_per_spec_result_667R(String cervix_per_spec_result_667R) { this.cervix_per_spec_result_667R = cervix_per_spec_result_667R; } /** * @return * @hibernate.property column="patient_received_arv" */ public Byte getPatient_received_arv() { return this.patient_received_arv; } public void setPatient_received_arv(Byte patient_received_arv) { this.patient_received_arv = patient_received_arv; } public String getPatient_received_arvR() { return this.patient_received_arvR; } public void setPatient_received_arvR(String patient_received_arvR) { this.patient_received_arvR = patient_received_arvR; } /** * @return * @hibernate.property column="is_problem" */ public Boolean getIs_problem() { return this.is_problem; } public void setIs_problem(Boolean is_problem) { this.is_problem = is_problem; } public String getIs_problemR() { return this.is_problemR; } public void setIs_problemR(String is_problemR) { this.is_problemR = is_problemR; } /** * @return * @hibernate.property column="contraceptive_advice_669" */ public Byte getContraceptive_advice_669() { return this.contraceptive_advice_669; } public void setContraceptive_advice_669(Byte contraceptive_advice_669) { this.contraceptive_advice_669 = contraceptive_advice_669; } public String getContraceptive_advice_669R() { return this.contraceptive_advice_669R; } public void setContraceptive_advice_669R(String contraceptive_advice_669R) { this.contraceptive_advice_669R = contraceptive_advice_669R; } /** * @return * @hibernate.property column="using_contraception_670" */ public Byte getUsing_contraception_670() { return this.using_contraception_670; } public void setUsing_contraception_670(Byte using_contraception_670) { this.using_contraception_670 = using_contraception_670; } public String getUsing_contraception_670R() { return this.using_contraception_670R; } public void setUsing_contraception_670R(String using_contraception_670R) { this.using_contraception_670R = using_contraception_670R; } /** * @return * @hibernate.property column="contraceptive_choice_137" */ public Integer getContraceptive_choice_137() { return this.contraceptive_choice_137; } public void setContraceptive_choice_137(Integer contraceptive_choice_137) { this.contraceptive_choice_137 = contraceptive_choice_137; } public String getContraceptive_choice_137R() { return this.contraceptive_choice_137R; } public void setContraceptive_choice_137R(String contraceptive_choice_137R) { this.contraceptive_choice_137R = contraceptive_choice_137R; } /** * @return * @hibernate.property column="contraceptive_other_138" type="text" */ public String getContraceptive_other_138() { return this.contraceptive_other_138; } public void setContraceptive_other_138(String contraceptive_other_138) { this.contraceptive_other_138 = contraceptive_other_138; } public String getContraceptive_other_138R() { return this.contraceptive_other_138R; } public void setContraceptive_other_138R(String contraceptive_other_138R) { this.contraceptive_other_138R = contraceptive_other_138R; } /** * @return * @hibernate.property column="education1" */ public Integer getEducation1() { return this.education1; } public void setEducation1(Integer education1) { this.education1 = education1; } public String getEducation1R() { return this.education1R; } public void setEducation1R(String education1R) { this.education1R = education1R; } /** * @return * @hibernate.property column="education2" */ public Integer getEducation2() { return this.education2; } public void setEducation2(Integer education2) { this.education2 = education2; } public String getEducation2R() { return this.education2R; } public void setEducation2R(String education2R) { this.education2R = education2R; } /** * @return * @hibernate.property column="education3" */ public Integer getEducation3() { return this.education3; } public void setEducation3(Integer education3) { this.education3 = education3; } public String getEducation3R() { return this.education3R; } public void setEducation3R(String education3R) { this.education3R = education3R; } /** * @return * @hibernate.property column="education4" */ public Integer getEducation4() { return this.education4; } public void setEducation4(Integer education4) { this.education4 = education4; } public String getEducation4R() { return this.education4R; } public void setEducation4R(String education4R) { this.education4R = education4R; } /** * @return * @hibernate.property column="education5" */ public Integer getEducation5() { return this.education5; } public void setEducation5(Integer education5) { this.education5 = education5; } public String getEducation5R() { return this.education5R; } public void setEducation5R(String education5R) { this.education5R = education5R; } /** * @return * @hibernate.property column="education6" */ public Integer getEducation6() { return this.education6; } public void setEducation6(Integer education6) { this.education6 = education6; } public String getEducation6R() { return this.education6R; } public void setEducation6R(String education6R) { this.education6R = education6R; } /** * @return * @hibernate.property column="education7" */ public Integer getEducation7() { return this.education7; } public void setEducation7(Integer education7) { this.education7 = education7; } public String getEducation7R() { return this.education7R; } public void setEducation7R(String education7R) { this.education7R = education7R; } /** * @return * @hibernate.property column="health_educa_discussed_other_674" type="text" */ public String getHealth_educa_discussed_other_674() { return this.health_educa_discussed_other_674; } public void setHealth_educa_discussed_other_674(String health_educa_discussed_other_674) { this.health_educa_discussed_other_674 = health_educa_discussed_other_674; } public String getHealth_educa_discussed_other_674R() { return this.health_educa_discussed_other_674R; } public void setHealth_educa_discussed_other_674R(String health_educa_discussed_other_674R) { this.health_educa_discussed_other_674R = health_educa_discussed_other_674R; } /** * @return * @hibernate.property column="postnatal_comments" type="text" */ public String getPostnatal_comments() { return this.postnatal_comments; } public void setPostnatal_comments(String postnatal_comments) { this.postnatal_comments = postnatal_comments; } public String getPostnatal_commentsR() { return this.postnatal_commentsR; } public void setPostnatal_commentsR(String postnatal_commentsR) { this.postnatal_commentsR = postnatal_commentsR; } }
apache-2.0
funtl/framework
funtl-framework-tools/paypal-sdk/src/main/java/com/funtl/framework/paypal/base/exception/BaseException.java
1000
/* * Copyright 2015-2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.funtl.framework.paypal.base.exception; /** * BaseException for SDK */ public class BaseException extends Exception { /** * Serial version UID */ private static final long serialVersionUID = -5345825923487658213L; public BaseException(String msg) { super(msg); } public BaseException(String msg, Throwable exception) { super(msg, exception); } }
apache-2.0
Panda-Programming-Language/Panda
panda-framework/src/main/java/org/panda_lang/panda/framework/design/interpreter/source/Source.java
888
/* * Copyright (c) 2015-2019 Dzikoysk * * 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.panda_lang.panda.framework.design.interpreter.source; /** * Source representation */ public interface Source { /** * @return source */ String getContent(); /** * @return e.g. a name of file or generated name */ String getTitle(); }
apache-2.0
UltraCart/rest_api_v2_sdk_csharp
src/com.ultracart.admin.v2/Model/UserGroupMembership.cs
5602
/* * UltraCart Rest API V2 * * UltraCart REST API Version 2 * * OpenAPI spec version: 2.0.0 * Contact: support@ultracart.com * Generated by: https://github.com/swagger-api/swagger-codegen.git */ using System; using System.Linq; using System.IO; using System.Text; using System.Text.RegularExpressions; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Runtime.Serialization; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using System.ComponentModel.DataAnnotations; using SwaggerDateConverter = com.ultracart.admin.v2.Client.SwaggerDateConverter; namespace com.ultracart.admin.v2.Model { /// <summary> /// UserGroupMembership /// </summary> [DataContract] public partial class UserGroupMembership : IEquatable<UserGroupMembership>, IValidatableObject { /// <summary> /// Initializes a new instance of the <see cref="UserGroupMembership" /> class. /// </summary> /// <param name="groupOid">The unique object identifier (oid for short) for this group.</param> /// <param name="member">True if this user is a member of the group..</param> /// <param name="name">The name of this group..</param> public UserGroupMembership(int? groupOid = default(int?), bool? member = default(bool?), string name = default(string)) { this.GroupOid = groupOid; this.Member = member; this.Name = name; } /// <summary> /// The unique object identifier (oid for short) for this group /// </summary> /// <value>The unique object identifier (oid for short) for this group</value> [DataMember(Name="group_oid", EmitDefaultValue=false)] public int? GroupOid { get; set; } /// <summary> /// True if this user is a member of the group. /// </summary> /// <value>True if this user is a member of the group.</value> [DataMember(Name="member", EmitDefaultValue=false)] public bool? Member { get; set; } /// <summary> /// The name of this group. /// </summary> /// <value>The name of this group.</value> [DataMember(Name="name", EmitDefaultValue=false)] public string Name { get; set; } /// <summary> /// Returns the string presentation of the object /// </summary> /// <returns>String presentation of the object</returns> public override string ToString() { var sb = new StringBuilder(); sb.Append("class UserGroupMembership {\n"); sb.Append(" GroupOid: ").Append(GroupOid).Append("\n"); sb.Append(" Member: ").Append(Member).Append("\n"); sb.Append(" Name: ").Append(Name).Append("\n"); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Returns the JSON string presentation of the object /// </summary> /// <returns>JSON string presentation of the object</returns> public virtual string ToJson() { return JsonConvert.SerializeObject(this, Formatting.Indented); } /// <summary> /// Returns true if objects are equal /// </summary> /// <param name="input">Object to be compared</param> /// <returns>Boolean</returns> public override bool Equals(object input) { return this.Equals(input as UserGroupMembership); } /// <summary> /// Returns true if UserGroupMembership instances are equal /// </summary> /// <param name="input">Instance of UserGroupMembership to be compared</param> /// <returns>Boolean</returns> public bool Equals(UserGroupMembership input) { if (input == null) return false; return ( this.GroupOid == input.GroupOid || (this.GroupOid != null && this.GroupOid.Equals(input.GroupOid)) ) && ( this.Member == input.Member || (this.Member != null && this.Member.Equals(input.Member)) ) && ( this.Name == input.Name || (this.Name != null && this.Name.Equals(input.Name)) ); } /// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { unchecked // Overflow is fine, just wrap { int hashCode = 41; if (this.GroupOid != null) hashCode = hashCode * 59 + this.GroupOid.GetHashCode(); if (this.Member != null) hashCode = hashCode * 59 + this.Member.GetHashCode(); if (this.Name != null) hashCode = hashCode * 59 + this.Name.GetHashCode(); return hashCode; } } /// <summary> /// To validate all properties of the instance /// </summary> /// <param name="validationContext">Validation context</param> /// <returns>Validation Result</returns> IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> IValidatableObject.Validate(ValidationContext validationContext) { yield break; } } }
apache-2.0
orange-buffalo/dozer
core/src/test/java/com/github/dozermapper/core/vo/deepindex/C.java
806
/* * Copyright 2005-2018 Dozer 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 com.github.dozermapper.core.vo.deepindex; public class C { private int id; public int getId() { return id; } public void setId(int id) { this.id = id; } }
apache-2.0
ccfish86/sctalk
android/app/src/main/java/com/mogujie/tt/imservice/entity/MixMessage.java
4589
package com.mogujie.tt.imservice.entity; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.mogujie.tt.DB.entity.MessageEntity; import com.mogujie.tt.config.DBConstant; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.List; /** * @author : yingmu on 15-1-14. * @email : yingmu@mogujie.com. */ public class MixMessage extends MessageEntity { public List<MessageEntity> msgList ; /** * 从net端解析需要 * @param entityList */ public MixMessage(List<MessageEntity> entityList){ if(entityList ==null || entityList.size()<=1){ throw new RuntimeException("MixMessage# type is error!"); } MessageEntity justOne = entityList.get(0); id = justOne.getId(); msgId = justOne.getMsgId(); fromId = justOne.getFromId(); toId = justOne.getToId(); sessionKey = justOne.getSessionKey(); msgType = justOne.getMsgType(); status = justOne.getStatus(); created = justOne.getCreated(); updated = justOne.getUpdated(); msgList = entityList; displayType= DBConstant.SHOW_MIX_TEXT; /**分配主键Id * 图文混排的之间全部从-1开始 * 在messageAdapter中 结合msgId进行更新 * * dbinterface 结合id sessionKey msgid来替换具体的消息 * {insertOrUpdateMix} * */ long index = -1; for(MessageEntity msg:entityList){ msg.setId(index); index --; } } /** * Not-null value. */ @Override public String getContent() { return getSerializableContent(msgList); } /** *sessionKey是在外边设定的,所以子对象是没有的 * 所以在设定的时候,都需要加上 * */ @Override public void setSessionKey(String sessionKey) { super.setSessionKey(sessionKey); for(MessageEntity msg:msgList){ msg.setSessionKey(sessionKey); } } @Override public void setToId(long toId) { super.setToId(toId); for(MessageEntity msg:msgList){ msg.setToId(toId); } } public MixMessage(MessageEntity dbEntity){ id = dbEntity.getId(); msgId = dbEntity.getMsgId(); fromId = dbEntity.getFromId(); toId = dbEntity.getToId(); msgType = dbEntity.getMsgType(); status = dbEntity.getStatus(); created = dbEntity.getCreated(); updated = dbEntity.getUpdated(); content = dbEntity.getContent(); displayType = dbEntity.getDisplayType(); sessionKey = dbEntity.getSessionKey(); } private String getSerializableContent(List<MessageEntity> entityList){ Gson gson = new Gson(); String json = gson.toJson(entityList); return json; } public static MixMessage parseFromDB(MessageEntity entity) throws JSONException { if(entity.getDisplayType() != DBConstant.SHOW_MIX_TEXT){ throw new RuntimeException("#MixMessage# parseFromDB,not SHOW_MIX_TEXT"); } Gson gson = new GsonBuilder().create(); MixMessage mixMessage = new MixMessage(entity); List<MessageEntity> msgList = new ArrayList<>(); JSONArray jsonArray = new JSONArray(entity.getContent()); for (int i = 0, length = jsonArray.length(); i < length; i++) { JSONObject jsonOb = (JSONObject) jsonArray.opt(i); int displayType = jsonOb.getInt("displayType"); String jsonMessage = jsonOb.toString(); switch (displayType){ case DBConstant.SHOW_ORIGIN_TEXT_TYPE:{ TextMessage textMessage = gson.fromJson(jsonMessage,TextMessage.class); textMessage.setSessionKey(entity.getSessionKey()); msgList.add(textMessage); }break; case DBConstant.SHOW_IMAGE_TYPE: ImageMessage imageMessage = gson.fromJson(jsonMessage,ImageMessage.class); imageMessage.setSessionKey(entity.getSessionKey()); msgList.add(imageMessage); break; } } mixMessage.setMsgList(msgList); return mixMessage; } public List<MessageEntity> getMsgList() { return msgList; } public void setMsgList(List<MessageEntity> msgList) { this.msgList = msgList; } }
apache-2.0
scouter-project/scouter
scouter.server/src/main/scala/scouter/server/db/ZipkinSpanWR.scala
4530
/* * Copyright 2015 the original author or authors. * @https://github.com/scouter-project/scouter * * 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 scouter.server.db import java.io.File import scouter.server.core.ServerStat import scouter.server.db.span.{ZipkinSpanDataWriter, ZipkinSpanIndex} import scouter.server.util.{OftenAction, ThreadScala} import scouter.server.{Configure, Logger} import scouter.util.{DateUtil, FileUtil, RequestQueue, ThreadUtil} import scala.collection.mutable object ZipkinSpanWR { case class SpanData(time: Long, gxid: Long, data: Array[Byte]) case class StorageContainer(idleLimit: Long, lastAccess: Long, index: ZipkinSpanIndex, writer: ZipkinSpanDataWriter) val MAX_IDLE = 30 * 60 * 1000L val SPAN_DIR = "/span" val SPAN_PREFIX = "span" val queue = new RequestQueue[SpanData](Configure.getInstance().span_queue_size) val dailyContainer = mutable.Map[Long, StorageContainer]() ThreadScala.start("scouter.server.db.ZipkinSpanDataFileWatcher") { while (DBCtr.running) { ThreadUtil.sleep(5 * 60 * 1000) val now = System.currentTimeMillis() dailyContainer .filter(kv => now - kv._2.lastAccess > kv._2.idleLimit) .keys.foreach(k => close(k)) } } ThreadScala.start("scouter.server.db.ZipkinSpanWR") { while (DBCtr.running) { val m = queue.get() ServerStat.put("zipkin-span.db.queue", queue.size()) try { val currentDateUnit = DateUtil.getDateUnit(m.time) val container = dailyContainer.getOrElseUpdate(currentDateUnit, { val (index, writer) = open(m.time) StorageContainer(MAX_IDLE, System.currentTimeMillis(), index, writer) }) if (container.index == null) { OftenAction.act("ZipkinSpanWR", 10) { dailyContainer.remove(currentDateUnit) queue.clear() } Logger.println("SZ143", 10, "can't open ZipkinSpanWR") } else { val location = container.writer.write(m.data) container.index.setByTime(m.time, location) container.index.setByGxid(m.gxid, location) } } catch { case t: Throwable => t.printStackTrace() } } closeAll() } def add(time: Long, gid: Long, data: Array[Byte]): Unit = { val ok = queue.put(SpanData(time, gid, data)) if (!ok) { Logger.println("SZ144", 10, "queue exceeded!! - ZipkinSpanWR") } } def closeAll(): Unit = { dailyContainer.values.foreach (container => { FileUtil.close(container.index) FileUtil.close(container.writer) }) dailyContainer.clear() } def close(time: Long): Unit = { dailyContainer.get(time).foreach(container => { FileUtil.close(container.index) FileUtil.close(container.writer) }) dailyContainer.remove(time) } def open(time: Long): (ZipkinSpanIndex, ZipkinSpanDataWriter) = { val date = DateUtil.yyyymmdd(time) try { val path = getDBPath(date) val f = new File(path) if (!f.exists()) f.mkdirs() val file = path + "/" + SPAN_PREFIX val index = ZipkinSpanIndex.open(file) val writer = ZipkinSpanDataWriter.open(date, file) return (index, writer) } catch { case e: Throwable => { e.printStackTrace() close(time) } } (null, null) } def getDBPath(date: String): String = { val sb = new StringBuffer() sb.append(DBCtr.getRootPath()) sb.append("/").append(date).append(SPAN_DIR) sb.toString } }
apache-2.0
rennman/copfvtci
cli/server/spi/group_test.go
1219
/* Copyright IBM Corp. 2016 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. */ /* * This file contains interfaces for the COP library. * COP provides police-like security functions for Hyperledger Fabric. */ package spi import "testing" func TestGetName(t *testing.T) { groupInfo := &GroupInfo{Name: "Bank_a", ParentID: "Bank"} group := NewGroup(groupInfo) name := group.GetName() if name != "Bank_a" { t.Error("Name does not match, expected 'Bank_a'") } } func TestGetParent(t *testing.T) { groupInfo := &GroupInfo{Name: "Bank_a", ParentID: "Bank"} group := NewGroup(groupInfo) name := group.GetParent() if name != "Bank" { t.Error("Parent name does not match, expected 'Bank'") } }
apache-2.0
bgp1984/WeixinShop
Application/Runtime/Cache/Admin/7fde83f59b7fe9a3399b547aa6382214.php
4197
<?php if (!defined('THINK_PATH')) exit();?><!doctype html> <html> <head> <meta charset="utf-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" /> <link href="/Public/css/admin/style.css" rel="stylesheet"/> <title><?php echo L('website_manage');?></title> <script> var URL = '/index.php/admin-seo'; var SELF = '/index.php?g=admin&m=seo&a=url&menuid=282'; var ROOT_PATH = ''; var APP = '/index.php'; //语言项目 var lang = new Object(); <?php $_result=L('js_lang');if(is_array($_result)): $i = 0; $__LIST__ = $_result;if( count($__LIST__)==0 ) : echo "" ;else: foreach($__LIST__ as $key=>$val): $mod = ($i % 2 );++$i;?>lang.<?php echo ($key); ?> = "<?php echo ($val); ?>";<?php endforeach; endif; else: echo "" ;endif; ?> </script> <script charset="utf-8" src="/Public/js/jquery.js" type="text/javascript"></script> </head> <body> <div id="J_ajax_loading" class="ajax_loading"><?php echo L('ajax_loading');?></div> <?php if(($sub_menu != '') OR ($big_menu != '')): ?><div class="subnav"> <div class="content_menu ib_a blue line_x"> <?php if(!empty($big_menu)): ?><a class="add fb J_showdialog" href="javascript:void(0);" data-uri="<?php echo ($big_menu["iframe"]); ?>" data-title="<?php echo ($big_menu["title"]); ?>" data-id="<?php echo ($big_menu["id"]); ?>" data-width="<?php echo ($big_menu["width"]); ?>" data-height="<?php echo ($big_menu["height"]); ?>"><em><?php echo ($big_menu["title"]); ?></em></a> <?php endif; ?> <?php if(!empty($sub_menu)): if(is_array($sub_menu)): $key = 0; $__LIST__ = $sub_menu;if( count($__LIST__)==0 ) : echo "" ;else: foreach($__LIST__ as $key=>$val): $mod = ($key % 2 );++$key; if($key != 1): ?><span>|</span><?php endif; ?> <a href="<?php echo U($val['module_name'].'/'.$val['action_name'],array('menuid'=>$menuid)); echo ($val["data"]); ?>" class="<?php echo ($val["class"]); ?>"><em><?php echo ($val['name']); ?></em></a><?php endforeach; endif; else: echo "" ;endif; endif; ?> </div> </div><?php endif; ?> <!--SEO设置--> <div class="pad_lr_10"> <form id="info_form" action="<?php echo u('seo/url');?>" method="post"> <table width="100%" class="table_form"> <tr> <th width="150"><?php echo L('url_model');?> :</th> <td> <select name="url_model"> <option value="0" <?php if($config['URL_MODEL'] == 0): ?>selected="selected"<?php endif; ?>> <?php echo L('url_model_0');?> </option> <option value="1" <?php if($config['URL_MODEL'] == 1): ?>selected="selected"<?php endif; ?>> <?php echo L('url_model_1');?> </option> <option value="2" <?php if($config['URL_MODEL'] == 2): ?>selected="selected"<?php endif; ?>> <?php echo L('url_model_2');?> </option> </select> </td> </tr> <tr> <th><?php echo L('url_suffix');?> :</th> <td><input type="text" name="url_suffix" class="input-text" size="10" value="<?php echo ($config["URL_HTML_SUFFIX"]); ?>"></td> </tr> <tr> <th><?php echo L('url_depr');?> :</th> <td><input type="text" name="url_depr" class="input-text" size="4" value="<?php echo ($config["URL_PATHINFO_DEPR"]); ?>"></td> </tr> <tr> <th></th> <td><input type="hidden" name="menuid" value="<?php echo ($menuid); ?>"/><input type="submit" class="btn btn_submit" name="do" value="<?php echo L('submit');?>"/></td> </tr> </table> </form> </div> <script src="/Public/js/jquery/plugins/jquery.tools.min.js"></script> <script src="/Public/js/jquery/plugins/formvalidator.js"></script> <script src="/Public/js/pinphp.js"></script> <script src="/Public/js/admin.js"></script> <script> //初始化弹窗 (function (d) { d['okValue'] = lang.dialog_ok; d['cancelValue'] = lang.dialog_cancel; d['title'] = lang.dialog_title; })($.dialog.defaults); </script> <?php if(isset($list_table)): ?><script src="/Public/js/jquery/plugins/listTable.js"></script> <script> $(function(){ $('.J_tablelist').listTable(); }); </script><?php endif; ?> </body> </html>
apache-2.0
LorenzReinhart/ONOSnew
apps/restconf/api/src/main/java/org/onosproject/restconf/api/RestconfService.java
6618
/* * Copyright 2016-present Open Networking Laboratory * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.onosproject.restconf.api; import com.fasterxml.jackson.databind.node.ObjectNode; import org.glassfish.jersey.server.ChunkedOutput; import java.net.URI; import java.util.concurrent.CompletableFuture; /** * Abstraction of RESTCONF Server functionality according to the * RESTCONF RFC (no official RFC number yet). */ public interface RestconfService { /** * Processes a GET request against a data resource. The * target data resource is identified by its URI. If the * GET operation cannot be fulfilled due to reasons such * as the nonexistence of the target resource, then a * RestconfException exception is raised. The proper * HTTP error status code is enclosed in the exception, so * that the caller may return it to the RESTCONF client to * display. * * @param uri URI of the target data resource * @return JSON representation of the data resource * @throws RestconfException if the GET operation cannot be fulfilled */ ObjectNode runGetOperationOnDataResource(URI uri) throws RestconfException; /** * Processes a POST request against a data resource. The location of * the target resource is passed in as a URI. And the resource's * content is passed in as a JSON ObjectNode. If the POST operation * cannot be fulfilled due to reasons such as wrong input URIs or * syntax errors in the JSON payloads, a RestconfException exception * is raised. The proper HTTP error status code is enclosed in the * exception. * * @param uri URI of the data resource to be created * @param rootNode JSON representation of the data resource * @throws RestconfException if the POST operation cannot be fulfilled */ void runPostOperationOnDataResource(URI uri, ObjectNode rootNode) throws RestconfException; /** * Processes a PUT request against a data resource. The location of * the target resource is passed in as a URI. And the resource's * content is passed in as a JSON ObjectNode. If the PUT operation * cannot be fulfilled due to reasons such as wrong input URIs or * syntax errors in the JSON payloads, a RestconfException exception * is raised. The proper HTTP error status code is enclosed in the * exception. * * @param uri URI of the data resource to be created or updated * @param rootNode JSON representation of the data resource * @throws RestconfException if the PUT operation cannot be fulfilled */ void runPutOperationOnDataResource(URI uri, ObjectNode rootNode) throws RestconfException; /** * Processes the DELETE operation against a data resource. The target * data resource is identified by its URI. If the DELETE operation * cannot be fulfilled due reasons such as the nonexistence of the * target resource, a RestconfException exception is raised. The * proper HTTP error status code is enclosed in the exception. * * @param uri URI of the data resource to be deleted * @throws RestconfException if the DELETE operation cannot be fulfilled */ void runDeleteOperationOnDataResource(URI uri) throws RestconfException; /** * Processes a PATCH operation on a data resource. The target data * resource is identified by its URI passed in by the caller. * And the content of the data resource is passed in as a JSON ObjectNode. * If the PATCH operation cannot be fulfilled due reasons such as * the nonexistence of the target resource, a RestconfException * exception is raised. The proper HTTP error status code is * enclosed in the exception. * * @param uri URI of the data resource to be patched * @param rootNode JSON representation of the data resource * @throws RestconfException if the PATCH operation cannot be fulfilled */ void runPatchOperationOnDataResource(URI uri, ObjectNode rootNode) throws RestconfException; /** * Retrieves the RESTCONF Root directory. * * @return the RESTCONF Root directory */ String getRestconfRootPath(); /** * Handles an Event Stream subscription request. This function creates * a worker thread to listen to events and writes to a ChunkedOutput, * which is passed in from the caller. (The worker thread blocks if * no events arrive.) The ChuckedOutput is a pipe to which this * function acts as the writer and the caller the reader. * <p> * If the Event Stream cannot be subscribed due to reasons such as * the nonexistence of the target stream or failure to allocate * worker thread to handle the request, a RestconfException exception * is raised. The proper HTTP error status code is enclosed in the * exception, so that the caller may return it to the RESTCONF client * to display. * * @param streamId ID of the RESTCONF stream to subscribe * @param clientIpAddr IP address of the RESTCONF client sending the request * @param output A string data stream * @throws RestconfException if the Event Stream cannot be subscribed */ void subscribeEventStream(String streamId, String clientIpAddr, ChunkedOutput<String> output) throws RestconfException; /** * Handles a RESTCONF RPC request. This function executes the RPC in * the target application's context and returns the results as a Future. * * @param uri URI corresponding to the Name of the RPC * @param rpcInput Input parameters * @param clientIpAddr IP address of the RESTCONF client calling the RPC * @return RPC output */ CompletableFuture<RestconfRpcOutput> runRpc(URI uri, ObjectNode rpcInput, String clientIpAddr); }
apache-2.0
Dreamxiaoxuan/AndroidTvDemo
app/src/main/java/com/xiaoxuan/demo/tv/widget/view/SurfaceRenderView.java
9226
package com.xiaoxuan.demo.tv.widget.view; import java.lang.ref.WeakReference; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import android.annotation.TargetApi; import android.content.Context; import android.graphics.SurfaceTexture; import android.os.Build; import android.util.AttributeSet; import android.util.Log; import android.view.Surface; import android.view.SurfaceHolder; import android.view.SurfaceView; import android.view.View; import android.view.accessibility.AccessibilityEvent; import android.view.accessibility.AccessibilityNodeInfo; import com.xiaoxuan.demo.tv.widget.MeasureHelper; import tv.danmaku.ijk.media.player.IMediaPlayer; import tv.danmaku.ijk.media.player.ISurfaceTextureHolder; public class SurfaceRenderView extends SurfaceView implements IRenderView { private MeasureHelper mMeasureHelper; public SurfaceRenderView(Context context) { super(context); initView(context); } public SurfaceRenderView(Context context, AttributeSet attrs) { super(context, attrs); initView(context); } public SurfaceRenderView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); initView(context); } @TargetApi(Build.VERSION_CODES.LOLLIPOP) public SurfaceRenderView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) { super(context, attrs, defStyleAttr, defStyleRes); initView(context); } private void initView(Context context) { mMeasureHelper = new MeasureHelper(this); mSurfaceCallback = new SurfaceCallback(this); getHolder().addCallback(mSurfaceCallback); // noinspection deprecation getHolder().setType(SurfaceHolder.SURFACE_TYPE_NORMAL); } @Override public View getView() { return this; } @Override public boolean shouldWaitForResize() { return true; } // Layout & Measure @Override public void setVideoSize(int videoWidth, int videoHeight) { if (videoWidth > 0 && videoHeight > 0) { mMeasureHelper.setVideoSize(videoWidth, videoHeight); getHolder().setFixedSize(videoWidth, videoHeight); requestLayout(); } } @Override public void setVideoSampleAspectRatio(int videoSarNum, int videoSarDen) { if (videoSarNum > 0 && videoSarDen > 0) { mMeasureHelper.setVideoSampleAspectRatio(videoSarNum, videoSarDen); requestLayout(); } } @Override public void setVideoRotation(int degree) { Log.e("", "SurfaceView doesn't support rotation (" + degree + ")!\n"); } @Override public void setAspectRatio(int aspectRatio) { mMeasureHelper.setAspectRatio(aspectRatio); requestLayout(); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { mMeasureHelper.doMeasure(widthMeasureSpec, heightMeasureSpec); setMeasuredDimension(mMeasureHelper.getMeasuredWidth(), mMeasureHelper.getMeasuredHeight()); } // SurfaceViewHolder private static final class InternalSurfaceHolder implements IRenderView.ISurfaceHolder { private SurfaceRenderView mSurfaceView; private SurfaceHolder mSurfaceHolder; public InternalSurfaceHolder(SurfaceRenderView surfaceView, SurfaceHolder surfaceHolder) { mSurfaceView = surfaceView; mSurfaceHolder = surfaceHolder; } public void bindToMediaPlayer(IMediaPlayer mp) { if (mp != null) { if ((Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) && (mp instanceof ISurfaceTextureHolder)) { ISurfaceTextureHolder textureHolder = (ISurfaceTextureHolder)mp; textureHolder.setSurfaceTexture(null); } mp.setDisplay(mSurfaceHolder); } } @Override public IRenderView getRenderView() { return mSurfaceView; } @Override public SurfaceHolder getSurfaceHolder() { return mSurfaceHolder; } @Override public SurfaceTexture getSurfaceTexture() { return null; } @Override public Surface openSurface() { if (mSurfaceHolder == null) return null; return mSurfaceHolder.getSurface(); } } // SurfaceHolder.Callback @Override public void addRenderCallback(IRenderCallback callback) { mSurfaceCallback.addRenderCallback(callback); } @Override public void removeRenderCallback(IRenderCallback callback) { mSurfaceCallback.removeRenderCallback(callback); } private SurfaceCallback mSurfaceCallback; private static final class SurfaceCallback implements SurfaceHolder.Callback { private SurfaceHolder mSurfaceHolder; private boolean mIsFormatChanged; private int mFormat; private int mWidth; private int mHeight; private WeakReference<SurfaceRenderView> mWeakSurfaceView; private Map<IRenderCallback, Object> mRenderCallbackMap = new ConcurrentHashMap<IRenderCallback, Object>(); public SurfaceCallback(SurfaceRenderView surfaceView) { mWeakSurfaceView = new WeakReference<SurfaceRenderView>(surfaceView); } public void addRenderCallback(IRenderCallback callback) { mRenderCallbackMap.put(callback, callback); ISurfaceHolder surfaceHolder = null; if (mSurfaceHolder != null) { if (surfaceHolder == null) surfaceHolder = new InternalSurfaceHolder(mWeakSurfaceView.get(), mSurfaceHolder); callback.onSurfaceCreated(surfaceHolder, mWidth, mHeight); } if (mIsFormatChanged) { if (surfaceHolder == null) surfaceHolder = new InternalSurfaceHolder(mWeakSurfaceView.get(), mSurfaceHolder); callback.onSurfaceChanged(surfaceHolder, mFormat, mWidth, mHeight); } } public void removeRenderCallback(IRenderCallback callback) { mRenderCallbackMap.remove(callback); } @Override public void surfaceCreated(SurfaceHolder holder) { mSurfaceHolder = holder; mIsFormatChanged = false; mFormat = 0; mWidth = 0; mHeight = 0; ISurfaceHolder surfaceHolder = new InternalSurfaceHolder(mWeakSurfaceView.get(), mSurfaceHolder); for (IRenderCallback renderCallback : mRenderCallbackMap.keySet()) { renderCallback.onSurfaceCreated(surfaceHolder, 0, 0); } } @Override public void surfaceDestroyed(SurfaceHolder holder) { mSurfaceHolder = null; mIsFormatChanged = false; mFormat = 0; mWidth = 0; mHeight = 0; ISurfaceHolder surfaceHolder = new InternalSurfaceHolder(mWeakSurfaceView.get(), mSurfaceHolder); for (IRenderCallback renderCallback : mRenderCallbackMap.keySet()) { renderCallback.onSurfaceDestroyed(surfaceHolder); } } @Override public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) { mSurfaceHolder = holder; mIsFormatChanged = true; mFormat = format; mWidth = width; mHeight = height; // mMeasureHelper.setVideoSize(width, height); ISurfaceHolder surfaceHolder = new InternalSurfaceHolder(mWeakSurfaceView.get(), mSurfaceHolder); for (IRenderCallback renderCallback : mRenderCallbackMap.keySet()) { renderCallback.onSurfaceChanged(surfaceHolder, format, width, height); } } } // -------------------- // Accessibility // -------------------- @Override public void onInitializeAccessibilityEvent(AccessibilityEvent event) { super.onInitializeAccessibilityEvent(event); event.setClassName(SurfaceRenderView.class.getName()); } @TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH) @Override public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) { super.onInitializeAccessibilityNodeInfo(info); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) { info.setClassName(SurfaceRenderView.class.getName()); } } }
apache-2.0
gawkermedia/googleads-java-lib
modules/adwords_axis/src/main/java/com/google/api/ads/adwords/axis/v201601/cm/ConversionTrackerServiceLocator.java
6308
/** * ConversionTrackerServiceLocator.java * * This file was auto-generated from WSDL * by the Apache Axis 1.4 Mar 02, 2009 (07:08:06 PST) WSDL2Java emitter. */ package com.google.api.ads.adwords.axis.v201601.cm; public class ConversionTrackerServiceLocator extends org.apache.axis.client.Service implements com.google.api.ads.adwords.axis.v201601.cm.ConversionTrackerService { public ConversionTrackerServiceLocator() { } public ConversionTrackerServiceLocator(org.apache.axis.EngineConfiguration config) { super(config); } public ConversionTrackerServiceLocator(java.lang.String wsdlLoc, javax.xml.namespace.QName sName) throws javax.xml.rpc.ServiceException { super(wsdlLoc, sName); } // Use to get a proxy class for ConversionTrackerServiceInterfacePort private java.lang.String ConversionTrackerServiceInterfacePort_address = "https://adwords.google.com/api/adwords/cm/v201601/ConversionTrackerService"; public java.lang.String getConversionTrackerServiceInterfacePortAddress() { return ConversionTrackerServiceInterfacePort_address; } // The WSDD service name defaults to the port name. private java.lang.String ConversionTrackerServiceInterfacePortWSDDServiceName = "ConversionTrackerServiceInterfacePort"; public java.lang.String getConversionTrackerServiceInterfacePortWSDDServiceName() { return ConversionTrackerServiceInterfacePortWSDDServiceName; } public void setConversionTrackerServiceInterfacePortWSDDServiceName(java.lang.String name) { ConversionTrackerServiceInterfacePortWSDDServiceName = name; } public com.google.api.ads.adwords.axis.v201601.cm.ConversionTrackerServiceInterface getConversionTrackerServiceInterfacePort() throws javax.xml.rpc.ServiceException { java.net.URL endpoint; try { endpoint = new java.net.URL(ConversionTrackerServiceInterfacePort_address); } catch (java.net.MalformedURLException e) { throw new javax.xml.rpc.ServiceException(e); } return getConversionTrackerServiceInterfacePort(endpoint); } public com.google.api.ads.adwords.axis.v201601.cm.ConversionTrackerServiceInterface getConversionTrackerServiceInterfacePort(java.net.URL portAddress) throws javax.xml.rpc.ServiceException { try { com.google.api.ads.adwords.axis.v201601.cm.ConversionTrackerServiceSoapBindingStub _stub = new com.google.api.ads.adwords.axis.v201601.cm.ConversionTrackerServiceSoapBindingStub(portAddress, this); _stub.setPortName(getConversionTrackerServiceInterfacePortWSDDServiceName()); return _stub; } catch (org.apache.axis.AxisFault e) { return null; } } public void setConversionTrackerServiceInterfacePortEndpointAddress(java.lang.String address) { ConversionTrackerServiceInterfacePort_address = address; } /** * For the given interface, get the stub implementation. * If this service has no port for the given interface, * then ServiceException is thrown. */ public java.rmi.Remote getPort(Class serviceEndpointInterface) throws javax.xml.rpc.ServiceException { try { if (com.google.api.ads.adwords.axis.v201601.cm.ConversionTrackerServiceInterface.class.isAssignableFrom(serviceEndpointInterface)) { com.google.api.ads.adwords.axis.v201601.cm.ConversionTrackerServiceSoapBindingStub _stub = new com.google.api.ads.adwords.axis.v201601.cm.ConversionTrackerServiceSoapBindingStub(new java.net.URL(ConversionTrackerServiceInterfacePort_address), this); _stub.setPortName(getConversionTrackerServiceInterfacePortWSDDServiceName()); return _stub; } } catch (java.lang.Throwable t) { throw new javax.xml.rpc.ServiceException(t); } throw new javax.xml.rpc.ServiceException("There is no stub implementation for the interface: " + (serviceEndpointInterface == null ? "null" : serviceEndpointInterface.getName())); } /** * For the given interface, get the stub implementation. * If this service has no port for the given interface, * then ServiceException is thrown. */ public java.rmi.Remote getPort(javax.xml.namespace.QName portName, Class serviceEndpointInterface) throws javax.xml.rpc.ServiceException { if (portName == null) { return getPort(serviceEndpointInterface); } java.lang.String inputPortName = portName.getLocalPart(); if ("ConversionTrackerServiceInterfacePort".equals(inputPortName)) { return getConversionTrackerServiceInterfacePort(); } else { java.rmi.Remote _stub = getPort(serviceEndpointInterface); ((org.apache.axis.client.Stub) _stub).setPortName(portName); return _stub; } } public javax.xml.namespace.QName getServiceName() { return new javax.xml.namespace.QName("https://adwords.google.com/api/adwords/cm/v201601", "ConversionTrackerService"); } private java.util.HashSet ports = null; public java.util.Iterator getPorts() { if (ports == null) { ports = new java.util.HashSet(); ports.add(new javax.xml.namespace.QName("https://adwords.google.com/api/adwords/cm/v201601", "ConversionTrackerServiceInterfacePort")); } return ports.iterator(); } /** * Set the endpoint address for the specified port name. */ public void setEndpointAddress(java.lang.String portName, java.lang.String address) throws javax.xml.rpc.ServiceException { if ("ConversionTrackerServiceInterfacePort".equals(portName)) { setConversionTrackerServiceInterfacePortEndpointAddress(address); } else { // Unknown Port Name throw new javax.xml.rpc.ServiceException(" Cannot set Endpoint Address for Unknown Port" + portName); } } /** * Set the endpoint address for the specified port name. */ public void setEndpointAddress(javax.xml.namespace.QName portName, java.lang.String address) throws javax.xml.rpc.ServiceException { setEndpointAddress(portName.getLocalPart(), address); } }
apache-2.0
lei-xia/helix
helix-core/src/test/java/org/apache/helix/integration/TestDisablePartition.java
8499
package org.apache.helix.integration; /* * 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 java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import org.apache.helix.HelixAdmin; import org.apache.helix.HelixDataAccessor; import org.apache.helix.PropertyKey; import org.apache.helix.TestHelper; import org.apache.helix.controller.rebalancer.AutoRebalancer; import org.apache.helix.controller.rebalancer.DelayedAutoRebalancer; import org.apache.helix.integration.common.ZkStandAloneCMTestBase; import org.apache.helix.integration.manager.ClusterControllerManager; import org.apache.helix.integration.manager.MockParticipantManager; import org.apache.helix.manager.zk.ZKHelixAdmin; import org.apache.helix.model.ExternalView; import org.apache.helix.model.IdealState; import org.apache.helix.model.IdealState.RebalanceMode; import org.apache.helix.tools.ClusterSetup; import org.apache.helix.tools.ClusterStateVerifier; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.testng.Assert; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; public class TestDisablePartition extends ZkStandAloneCMTestBase { private static Logger LOG = LoggerFactory.getLogger(TestDisablePartition.class); @Test() public void testDisablePartition() throws Exception { LOG.info("START testDisablePartition() at " + new Date(System.currentTimeMillis())); // localhost_12919 is MASTER for TestDB_0 String command = "--zkSvr " + ZK_ADDR + " --enablePartition false " + CLUSTER_NAME + " localhost_12919 TestDB TestDB_0 TestDB_9"; ClusterSetup.processCommandLineArgs(command.split("\\s+")); Map<String, Set<String>> map = new HashMap<>(); map.put("TestDB_0", TestHelper.setOf("localhost_12919")); map.put("TestDB_9", TestHelper.setOf("localhost_12919")); boolean result = ClusterStateVerifier.verifyByPolling( new ClusterStateVerifier.BestPossAndExtViewZkVerifier(ZK_ADDR, CLUSTER_NAME)); Assert.assertTrue(result); TestHelper.verifyState(CLUSTER_NAME, ZK_ADDR, map, "OFFLINE"); ZKHelixAdmin tool = new ZKHelixAdmin(_gZkClient); tool.enablePartition(true, CLUSTER_NAME, "localhost_12919", "TestDB", Collections.singletonList("TestDB_9")); result = ClusterStateVerifier.verifyByPolling( new ClusterStateVerifier.BestPossAndExtViewZkVerifier(ZK_ADDR, CLUSTER_NAME)); Assert.assertTrue(result); map.clear(); map.put("TestDB_0", TestHelper.setOf("localhost_12919")); TestHelper.verifyState(CLUSTER_NAME, ZK_ADDR, map, "OFFLINE"); map.clear(); map.put("TestDB_9", TestHelper.setOf("localhost_12919")); TestHelper.verifyState(CLUSTER_NAME, ZK_ADDR, map, "MASTER"); LOG.info("STOP testDisablePartition() at " + new Date(System.currentTimeMillis())); } @DataProvider(name = "rebalancer") public static String[][] rebalancers() { return new String[][] { { AutoRebalancer.class.getName() }, { DelayedAutoRebalancer.class.getName() } }; } @Test(dataProvider = "rebalancer", enabled = true) public void testDisableFullAuto(String rebalancerName) throws Exception { final int NUM_PARTITIONS = 8; final int NUM_PARTICIPANTS = 2; final int NUM_REPLICAS = 1; String className = TestHelper.getTestClassName(); String methodName = TestHelper.getTestMethodName(); String clusterName = className + "_" + methodName; ClusterSetup clusterSetup = new ClusterSetup(ZK_ADDR); clusterSetup.addCluster(clusterName, true); for (int i = 0; i < NUM_PARTICIPANTS; i++) { String instanceName = "localhost_" + (11420 + i); clusterSetup.addInstanceToCluster(clusterName, instanceName); } // Create a known problematic scenario HelixAdmin admin = clusterSetup.getClusterManagementTool(); String resourceName = "MailboxDB"; IdealState idealState = new IdealState(resourceName + "DR"); idealState.setRebalanceMode(RebalanceMode.SEMI_AUTO); idealState.setStateModelDefRef("LeaderStandby"); idealState.setReplicas(String.valueOf(NUM_REPLICAS)); idealState.setNumPartitions(NUM_PARTITIONS); for (int i = 0; i < NUM_PARTITIONS; i++) { String partitionName = resourceName + '_' + i; List<String> assignmentList = Lists.newArrayList(); if (i < NUM_PARTITIONS / 2) { assignmentList.add("localhost_11420"); } else { assignmentList.add("localhost_11421"); } Map<String, String> emptyMap = Maps.newHashMap(); idealState.getRecord().setListField(partitionName, assignmentList); idealState.getRecord().setMapField(partitionName, emptyMap); } admin.addResource(clusterName, idealState.getResourceName(), idealState); // Start everything MockParticipantManager[] participants = new MockParticipantManager[NUM_PARTICIPANTS]; for (int i = 0; i < NUM_PARTICIPANTS; i++) { String instanceName = "localhost_" + (11420 + i); participants[i] = new MockParticipantManager(ZK_ADDR, clusterName, instanceName); participants[i].syncStart(); } ClusterControllerManager controller = new ClusterControllerManager(ZK_ADDR, clusterName, "controller_1"); controller.syncStart(); Thread.sleep(1000); // Switch to full auto idealState.setRebalanceMode(RebalanceMode.FULL_AUTO); idealState.setRebalancerClassName(rebalancerName); for (int i = 0; i < NUM_PARTITIONS; i++) { List<String> emptyList = Collections.emptyList(); idealState.getRecord().setListField(resourceName + '_' + i, emptyList); } admin.setResourceIdealState(clusterName, idealState.getResourceName(), idealState); Thread.sleep(1000); // Get the external view HelixDataAccessor accessor = controller.getHelixDataAccessor(); PropertyKey.Builder keyBuilder = accessor.keyBuilder(); ExternalView externalView = accessor.getProperty(keyBuilder.externalView(idealState.getResourceName())); // Disable the partitions in an order known to cause problems int[] pid = { 0, 7 }; for (int value : pid) { String partitionName = resourceName + '_' + value; Map<String, String> stateMap = externalView.getStateMap(partitionName); String leader = null; for (String participantName : stateMap.keySet()) { String state = stateMap.get(participantName); if (state.equals("LEADER")) { leader = participantName; } } List<String> partitionNames = Lists.newArrayList(partitionName); admin.enablePartition(false, clusterName, leader, idealState.getResourceName(), partitionNames); Thread.sleep(1000); } // Ensure that nothing was reassigned and the disabled are offline externalView = accessor.getProperty(keyBuilder.externalView(idealState.getResourceName())); Map<String, String> p0StateMap = externalView.getStateMap(resourceName + "_0"); Assert.assertEquals(p0StateMap.size(), 1); String p0Participant = p0StateMap.keySet().iterator().next(); Assert.assertEquals(p0StateMap.get(p0Participant), "OFFLINE"); Map<String, String> p7StateMap = externalView.getStateMap(resourceName + "_7"); Assert.assertEquals(p7StateMap.size(), 1); String p7Participant = p7StateMap.keySet().iterator().next(); Assert.assertEquals(p7StateMap.get(p7Participant), "OFFLINE"); // Cleanup controller.syncStop(); for (MockParticipantManager participant : participants) { participant.syncStop(); } deleteCluster(clusterName); } }
apache-2.0
LQJJ/demo
126-go-common-master/app/interface/main/dm2/http/manage.go
2893
package http import ( "strconv" "go-common/app/interface/main/dm2/model" "go-common/app/interface/main/dm2/model/oplog" "go-common/library/ecode" "go-common/library/log" bm "go-common/library/net/http/blademaster" "go-common/library/xstr" ) // editState edit dm state. // 0:正常1:删除 2:保护 3:取消保护 func editState(c *bm.Context) { var ( p = c.Request.Form dmids = make([]int64, 0) ) mid, _ := c.Get("mid") oid, err := strconv.ParseInt(p.Get("oid"), 10, 64) if err != nil { c.JSON(nil, ecode.RequestErr) return } tp, err := strconv.ParseInt(p.Get("type"), 10, 64) if err != nil { c.JSON(nil, ecode.RequestErr) return } state, err := strconv.ParseInt(p.Get("state"), 10, 64) if err != nil { c.JSON(nil, ecode.RequestErr) return } ids, err := xstr.SplitInts(p.Get("dmids")) if err != nil { c.JSON(nil, ecode.RequestErr) return } for _, dmid := range ids { if dmid == 0 { log.Warn("dmid is zero") continue } dmids = append(dmids, dmid) } if len(dmids) == 0 { c.JSON(nil, ecode.RequestErr) return } switch state { case 0, 1: err = dmSvc.EditDMState(c, int32(tp), mid.(int64), oid, int32(state), dmids, oplog.SourceUp, oplog.OperatorUp) if err != nil { log.Error("dmSvc.EditDMState(mid:%d, oid:%d, state:%d, dmids:%v) error(%v)", mid.(int64), oid, state, dmids, err) c.JSON(nil, err) return } err = dmSvc.UptSearchDMState(c, dmids, oid, int32(state), int32(tp)) case 2, 3: var ( affectIds []int64 ) attr := model.AttrYes if state == 3 { attr = model.AttrNo } affectIds, err = dmSvc.EditDMAttr(c, int32(tp), mid.(int64), oid, model.AttrProtect, attr, dmids, oplog.SourceUp, oplog.OperatorUp) if err != nil { log.Error("dmSvc.EditDMAttr(mid:%d, oid:%d, attr:%d, dmids:%v) error(%v)", mid.(int64), oid, attr, dmids, err) c.JSON(nil, err) return } if len(affectIds) > 0 { err = dmSvc.UptSearchDMAttr(c, affectIds, oid, attr, int32(tp)) } default: err = ecode.RequestErr } c.JSON(nil, err) } func editPool(c *bm.Context) { p := c.Request.Form mid, _ := c.Get("mid") oid, err := strconv.ParseInt(p.Get("oid"), 10, 64) if err != nil { c.JSON(nil, ecode.RequestErr) return } tp, err := strconv.ParseInt(p.Get("type"), 10, 64) if err != nil { c.JSON(nil, ecode.RequestErr) return } pool, err := strconv.ParseInt(p.Get("pool"), 10, 64) if err != nil { c.JSON(nil, ecode.RequestErr) return } dmids, err := xstr.SplitInts(p.Get("dmids")) if err != nil || len(dmids) == 0 { c.JSON(nil, ecode.RequestErr) return } err = dmSvc.EditDMPool(c, int32(tp), mid.(int64), oid, int32(pool), dmids, oplog.SourceUp, oplog.OperatorUp) if err != nil { log.Error("dmSvc.EditDMStat(oid:%d dmids:%v) error(%v)", oid, dmids, err) c.JSON(nil, err) return } err = dmSvc.UptSearchDMPool(c, dmids, oid, int32(pool), int32(tp)) c.JSON(nil, err) }
apache-2.0
googleads/google-ads-dotnet
src/V9/Types/VanityPharmaDisplayUrlMode.g.cs
9643
// <auto-generated> // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/ads/googleads/v9/enums/vanity_pharma_display_url_mode.proto // </auto-generated> #pragma warning disable 1591, 0612, 3021 #region Designer generated code using pb = global::Google.Protobuf; using pbc = global::Google.Protobuf.Collections; using pbr = global::Google.Protobuf.Reflection; using scg = global::System.Collections.Generic; namespace Google.Ads.GoogleAds.V9.Enums { /// <summary>Holder for reflection information generated from google/ads/googleads/v9/enums/vanity_pharma_display_url_mode.proto</summary> public static partial class VanityPharmaDisplayUrlModeReflection { #region Descriptor /// <summary>File descriptor for google/ads/googleads/v9/enums/vanity_pharma_display_url_mode.proto</summary> public static pbr::FileDescriptor Descriptor { get { return descriptor; } } private static pbr::FileDescriptor descriptor; static VanityPharmaDisplayUrlModeReflection() { byte[] descriptorData = global::System.Convert.FromBase64String( string.Concat( "CkJnb29nbGUvYWRzL2dvb2dsZWFkcy92OS9lbnVtcy92YW5pdHlfcGhhcm1h", "X2Rpc3BsYXlfdXJsX21vZGUucHJvdG8SHWdvb2dsZS5hZHMuZ29vZ2xlYWRz", "LnY5LmVudW1zGhxnb29nbGUvYXBpL2Fubm90YXRpb25zLnByb3RvIpMBCh5W", "YW5pdHlQaGFybWFEaXNwbGF5VXJsTW9kZUVudW0icQoaVmFuaXR5UGhhcm1h", "RGlzcGxheVVybE1vZGUSDwoLVU5TUEVDSUZJRUQQABILCgdVTktOT1dOEAES", "HAoYTUFOVUZBQ1RVUkVSX1dFQlNJVEVfVVJMEAISFwoTV0VCU0lURV9ERVND", "UklQVElPThADQvQBCiFjb20uZ29vZ2xlLmFkcy5nb29nbGVhZHMudjkuZW51", "bXNCH1Zhbml0eVBoYXJtYURpc3BsYXlVcmxNb2RlUHJvdG9QAVpCZ29vZ2xl", "LmdvbGFuZy5vcmcvZ2VucHJvdG8vZ29vZ2xlYXBpcy9hZHMvZ29vZ2xlYWRz", "L3Y5L2VudW1zO2VudW1zogIDR0FBqgIdR29vZ2xlLkFkcy5Hb29nbGVBZHMu", "VjkuRW51bXPKAh1Hb29nbGVcQWRzXEdvb2dsZUFkc1xWOVxFbnVtc+oCIUdv", "b2dsZTo6QWRzOjpHb29nbGVBZHM6OlY5OjpFbnVtc2IGcHJvdG8z")); descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData, new pbr::FileDescriptor[] { global::Google.Api.AnnotationsReflection.Descriptor, }, new pbr::GeneratedClrTypeInfo(null, null, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::Google.Ads.GoogleAds.V9.Enums.VanityPharmaDisplayUrlModeEnum), global::Google.Ads.GoogleAds.V9.Enums.VanityPharmaDisplayUrlModeEnum.Parser, null, null, new[]{ typeof(global::Google.Ads.GoogleAds.V9.Enums.VanityPharmaDisplayUrlModeEnum.Types.VanityPharmaDisplayUrlMode) }, null, null) })); } #endregion } #region Messages /// <summary> /// The display mode for vanity pharma URLs. /// </summary> public sealed partial class VanityPharmaDisplayUrlModeEnum : pb::IMessage<VanityPharmaDisplayUrlModeEnum> #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE , pb::IBufferMessage #endif { private static readonly pb::MessageParser<VanityPharmaDisplayUrlModeEnum> _parser = new pb::MessageParser<VanityPharmaDisplayUrlModeEnum>(() => new VanityPharmaDisplayUrlModeEnum()); private pb::UnknownFieldSet _unknownFields; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public static pb::MessageParser<VanityPharmaDisplayUrlModeEnum> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public static pbr::MessageDescriptor Descriptor { get { return global::Google.Ads.GoogleAds.V9.Enums.VanityPharmaDisplayUrlModeReflection.Descriptor.MessageTypes[0]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public VanityPharmaDisplayUrlModeEnum() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public VanityPharmaDisplayUrlModeEnum(VanityPharmaDisplayUrlModeEnum other) : this() { _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public VanityPharmaDisplayUrlModeEnum Clone() { return new VanityPharmaDisplayUrlModeEnum(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public override bool Equals(object other) { return Equals(other as VanityPharmaDisplayUrlModeEnum); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public bool Equals(VanityPharmaDisplayUrlModeEnum other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } return Equals(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public override int GetHashCode() { int hash = 1; if (_unknownFields != null) { hash ^= _unknownFields.GetHashCode(); } return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void WriteTo(pb::CodedOutputStream output) { #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE output.WriteRawMessage(this); #else if (_unknownFields != null) { _unknownFields.WriteTo(output); } #endif } #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { if (_unknownFields != null) { _unknownFields.WriteTo(ref output); } } #endif [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public int CalculateSize() { int size = 0; if (_unknownFields != null) { size += _unknownFields.CalculateSize(); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void MergeFrom(VanityPharmaDisplayUrlModeEnum other) { if (other == null) { return; } _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void MergeFrom(pb::CodedInputStream input) { #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE input.ReadRawMessage(this); #else uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); break; } } #endif } #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); break; } } } #endif #region Nested types /// <summary>Container for nested types declared in the VanityPharmaDisplayUrlModeEnum message type.</summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public static partial class Types { /// <summary> /// Enum describing possible display modes for vanity pharma URLs. /// </summary> public enum VanityPharmaDisplayUrlMode { /// <summary> /// Not specified. /// </summary> [pbr::OriginalName("UNSPECIFIED")] Unspecified = 0, /// <summary> /// Used for return value only. Represents value unknown in this version. /// </summary> [pbr::OriginalName("UNKNOWN")] Unknown = 1, /// <summary> /// Replace vanity pharma URL with manufacturer website url. /// </summary> [pbr::OriginalName("MANUFACTURER_WEBSITE_URL")] ManufacturerWebsiteUrl = 2, /// <summary> /// Replace vanity pharma URL with description of the website. /// </summary> [pbr::OriginalName("WEBSITE_DESCRIPTION")] WebsiteDescription = 3, } } #endregion } #endregion } #endregion Designer generated code
apache-2.0
jdgwartney/vsphere-ws
java/JAXWS/samples/com/vmware/vim25/UpdateServiceMessageRequestType.java
2242
package com.vmware.vim25; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for UpdateServiceMessageRequestType complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="UpdateServiceMessageRequestType"> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="_this" type="{urn:vim25}ManagedObjectReference"/> * &lt;element name="message" type="{http://www.w3.org/2001/XMLSchema}string"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "UpdateServiceMessageRequestType", propOrder = { "_this", "message" }) public class UpdateServiceMessageRequestType { @XmlElement(required = true) protected ManagedObjectReference _this; @XmlElement(required = true) protected String message; /** * Gets the value of the this property. * * @return * possible object is * {@link ManagedObjectReference } * */ public ManagedObjectReference getThis() { return _this; } /** * Sets the value of the this property. * * @param value * allowed object is * {@link ManagedObjectReference } * */ public void setThis(ManagedObjectReference value) { this._this = value; } /** * Gets the value of the message property. * * @return * possible object is * {@link String } * */ public String getMessage() { return message; } /** * Sets the value of the message property. * * @param value * allowed object is * {@link String } * */ public void setMessage(String value) { this.message = value; } }
apache-2.0
jan-molak/serenity-js
packages/core/src/screenplay/activities/TrackedActivity.ts
2122
import { InteractionFinished, InteractionStarts, TaskFinished, TaskStarts } from '../../events'; import { ActivityDetails, ExecutionSuccessful } from '../../model'; import { Stage } from '../../stage'; import { Activity } from '../Activity'; import { AnswersQuestions, PerformsActivities, UsesAbilities } from '../actor'; import { Interaction } from '../Interaction'; import { ActivityDescriber } from './ActivityDescriber'; import { OutcomeMatcher } from './OutcomeMatcher'; /** @package */ export class TrackedActivity implements Activity { protected static readonly describer = new ActivityDescriber(); protected static readonly outcomes = new OutcomeMatcher(); constructor( protected readonly activity: Activity, protected readonly stage: Stage, ) { } performAs(actor: (PerformsActivities | UsesAbilities | AnswersQuestions) & { name: string }): PromiseLike<void> { const sceneId = this.stage.currentSceneId(), activityId = this.stage.assignNewActivityId(), details = new ActivityDetails(TrackedActivity.describer.describe(this.activity, actor)); const [ activityStarts, activityFinished] = this.activity instanceof Interaction ? [ InteractionStarts, InteractionFinished ] : [ TaskStarts, TaskFinished ]; return Promise.resolve() .then(() => this.stage.announce(new activityStarts(sceneId, activityId, details, this.stage.currentTime()))) .then(() => this.activity.performAs(actor)) .then(() => { const outcome = new ExecutionSuccessful(); this.stage.announce(new activityFinished(sceneId, activityId, details, outcome, this.stage.currentTime())); }) .catch(error => { const outcome = TrackedActivity.outcomes.outcomeFor(error); this.stage.announce(new activityFinished(sceneId, activityId, details, outcome, this.stage.currentTime())); throw error; }); } toString(): string { return this.activity.toString(); } }
apache-2.0
FITeagle/fusecoplayground
source/conf.py
10969
# -*- coding: utf-8 -*- # # FUSECO Playground documentation build configuration file, created by # sphinx-quickstart on Sun May 25 21:19:07 2014. # # This file is execfile()d with the current directory set to its # containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All configuration values have a default; values that are commented out # serve to show the default. import sys import os # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. #sys.path.insert(0, os.path.abspath('.')) # -- General configuration ------------------------------------------------ # If your documentation needs a minimal Sphinx version, state it here. #needs_sphinx = '1.0' # Add any Sphinx extension module names here, as strings. They can be # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom # ones. extensions = [ 'sphinx.ext.autodoc', 'sphinx.ext.doctest', 'sphinx.ext.intersphinx', 'sphinx.ext.todo', 'sphinx.ext.coverage', 'sphinx.ext.mathjax', 'sphinx.ext.ifconfig', 'sphinx.ext.viewcode', ] # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # The suffix of source filenames. source_suffix = '.rst' # The encoding of source files. #source_encoding = 'utf-8-sig' # The master toctree document. master_doc = 'index' # General information about the project. project = u'FUSECO Playground' copyright = u'2014, Alexander Willner <alexander.willner@tu-berlin.de>' todo_include_todos = True # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # # The short X.Y version. version = '1.0.0' # The full version, including alpha/beta/rc tags. release = '1.0.0' # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. #language = None # There are two options for replacing |today|: either, you set today to some # non-false value, then it is used: #today = '' # Else, today_fmt is used as the format for a strftime call. #today_fmt = '%B %d, %Y' # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. exclude_patterns = [] # The reST default role (used for this markup: `text`) to use for all # documents. #default_role = None # If true, '()' will be appended to :func: etc. cross-reference text. #add_function_parentheses = True # If true, the current module name will be prepended to all description # unit titles (such as .. function::). #add_module_names = True # If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by default. #show_authors = False # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'sphinx' # A list of ignored prefixes for module index sorting. #modindex_common_prefix = [] # If true, keep warnings as "system message" paragraphs in the built documents. #keep_warnings = False # -- Options for HTML output ---------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. html_theme = 'nature' # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. #html_theme_options = {} # Add any paths that contain custom themes here, relative to this directory. #html_theme_path = [] # The name for this set of Sphinx documents. If None, it defaults to # "<project> v<release> documentation". #html_title = None # A shorter title for the navigation bar. Default is the same as html_title. #html_short_title = None # The name of an image file (relative to this directory) to place at the top # of the sidebar. #html_logo = None # The name of an image file (within the static path) to use as favicon of the # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 # pixels large. #html_favicon = None # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = ['_static'] # Add any extra paths that contain custom files (such as robots.txt or # .htaccess) here, relative to this directory. These files are copied # directly to the root of the documentation. #html_extra_path = [] # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, # using the given strftime format. #html_last_updated_fmt = '%b %d, %Y' # If true, SmartyPants will be used to convert quotes and dashes to # typographically correct entities. #html_use_smartypants = True # Custom sidebar templates, maps document names to template names. #html_sidebars = {} # Additional templates that should be rendered to pages, maps page names to # template names. #html_additional_pages = {} # If false, no module index is generated. #html_domain_indices = True # If false, no index is generated. #html_use_index = True # If true, the index is split into individual pages for each letter. #html_split_index = False # If true, links to the reST sources are added to the pages. #html_show_sourcelink = True # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. #html_show_sphinx = True # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. #html_show_copyright = True # If true, an OpenSearch description file will be output, and all pages will # contain a <link> tag referring to it. The value of this option must be the # base URL from which the finished HTML is served. #html_use_opensearch = '' # This is the file name suffix for HTML files (e.g. ".xhtml"). #html_file_suffix = None # Output file base name for HTML help builder. htmlhelp_basename = 'FUSECOPlaygrounddoc' # -- Options for LaTeX output --------------------------------------------- latex_elements = { # The paper size ('letterpaper' or 'a4paper'). #'papersize': 'letterpaper', # The font size ('10pt', '11pt' or '12pt'). #'pointsize': '10pt', # Additional stuff for the LaTeX preamble. #'preamble': '', } # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, # author, documentclass [howto, manual, or own class]). latex_documents = [ ('index', 'FUSECOPlayground.tex', u'FUSECO Playground Documentation', u'Alexander Willner \\textless{}alexander.willner@tu-berlin.de\\textgreater{}', 'manual'), ] # The name of an image file (relative to this directory) to place at the top of # the title page. #latex_logo = None # For "manual" documents, if this is true, then toplevel headings are parts, # not chapters. #latex_use_parts = False # If true, show page references after internal links. #latex_show_pagerefs = False # If true, show URL addresses after external links. #latex_show_urls = False # Documents to append as an appendix to all manuals. #latex_appendices = [] # If false, no module index is generated. #latex_domain_indices = True # -- Options for manual page output --------------------------------------- # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ ('index', 'fusecoplayground', u'FUSECO Playground Documentation', [u'Alexander Willner <alexander.willner@tu-berlin.de>'], 1) ] # If true, show URL addresses after external links. #man_show_urls = False # -- Options for Texinfo output ------------------------------------------- # Grouping the document tree into Texinfo files. List of tuples # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ ('index', 'FUSECOPlayground', u'FUSECO Playground Documentation', u'Alexander Willner <alexander.willner@tu-berlin.de>', 'FUSECOPlayground', 'One line description of project.', 'Miscellaneous'), ] # Documents to append as an appendix to all manuals. #texinfo_appendices = [] # If false, no module index is generated. #texinfo_domain_indices = True # How to display URL addresses: 'footnote', 'no', or 'inline'. #texinfo_show_urls = 'footnote' # If true, do not generate a @detailmenu in the "Top" node's menu. #texinfo_no_detailmenu = False # -- Options for Epub output ---------------------------------------------- # Bibliographic Dublin Core info. epub_title = u'FUSECO Playground' epub_author = u'Alexander Willner <alexander.willner@tu-berlin.de>' epub_publisher = u'Alexander Willner <alexander.willner@tu-berlin.de>' epub_copyright = u'2014, Alexander Willner <alexander.willner@tu-berlin.de>' # The basename for the epub file. It defaults to the project name. #epub_basename = u'FUSECO Playground' # The HTML theme for the epub output. Since the default themes are not optimized # for small screen space, using the same theme for HTML and epub output is # usually not wise. This defaults to 'epub', a theme designed to save visual # space. #epub_theme = 'epub' # The language of the text. It defaults to the language option # or en if the language is not set. #epub_language = '' # The scheme of the identifier. Typical schemes are ISBN or URL. #epub_scheme = '' # The unique identifier of the text. This can be a ISBN number # or the project homepage. #epub_identifier = '' # A unique identification for the text. #epub_uid = '' # A tuple containing the cover image and cover page html template filenames. #epub_cover = () # A sequence of (type, uri, title) tuples for the guide element of content.opf. #epub_guide = () # HTML files that should be inserted before the pages created by sphinx. # The format is a list of tuples containing the path and title. #epub_pre_files = [] # HTML files shat should be inserted after the pages created by sphinx. # The format is a list of tuples containing the path and title. #epub_post_files = [] # A list of files that should not be packed into the epub file. epub_exclude_files = ['search.html'] # The depth of the table of contents in toc.ncx. #epub_tocdepth = 3 # Allow duplicate toc entries. #epub_tocdup = True # Choose between 'default' and 'includehidden'. #epub_tocscope = 'default' # Fix unsupported image types using the PIL. #epub_fix_images = False # Scale large images. #epub_max_image_width = 0 # How to display URL addresses: 'footnote', 'no', or 'inline'. #epub_show_urls = 'inline' # If false, no index is generated. #epub_use_index = True # Example configuration for intersphinx: refer to the Python standard library. intersphinx_mapping = {'http://docs.python.org/': None}
apache-2.0
bertilmuth/requirementsascode
requirementsascodeexamples/helloworld/src/main/java/helloworld/commandhandler/SaveName.java
379
package helloworld.commandhandler; import java.util.function.Consumer; import helloworld.command.EnterText; import helloworld.domain.Person; public class SaveName implements Consumer<EnterText> { private Person person; public SaveName(Person person) { this.person = person; } @Override public void accept(EnterText t) { person.saveName(t.getText()); } }
apache-2.0
django-fluent/django-fluent-contents
fluent_contents/plugins/sharedcontent/managers.py
1787
from django.conf import settings from django.db.models import Manager, Q from parler.managers import TranslatableQuerySet from fluent_contents import appsettings from fluent_contents.plugins.sharedcontent import appsettings as sharedcontent_appsettings class SharedContentQuerySet(TranslatableQuerySet): """ The QuerySet for SharedContent models. """ def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self._parent_site = None def _clone(self): c = super()._clone() c._parent_site = self._parent_site return c def parent_site(self, site): """ Filter to the given site, only give content relevant for that site. """ # Avoid auto filter if site is already set. self._parent_site = site if sharedcontent_appsettings.FLUENT_SHARED_CONTENT_ENABLE_CROSS_SITE: # Allow content to be shared between all sites: return self.filter(Q(parent_site=site) | Q(is_cross_site=True)) else: return self.filter(parent_site=site) def _single_site(self): """ Make sure the queryset is filtered on a parent site, if that didn't happen already. """ if appsettings.FLUENT_CONTENTS_FILTER_SITE_ID and self._parent_site is None: return self.parent_site(settings.SITE_ID) else: return self def get_for_slug(self, slug): """ .. versionadded:: 1.0 Return the content for the given slug. """ return self._single_site().get(slug=slug) class SharedContentManager(Manager.from_queryset(SharedContentQuerySet)): """ Extra methods attached to ``SharedContent.objects``, see :class:`SharedContentQuerySet`. """ pass
apache-2.0
arkanister/minitickets
src/conf/menu.py
1323
# coding: utf-8 from django.utils.translation import ugettext as _ MAIN_NAV = [{ "verbose_name": _('Home'), "action": "home", "icon": "home", "pattern": r"^/$", }, { "verbose_name": _('Dashboard'), "action": "minitickets:dashboard", "icon": "dashboard", "permissions": ["minitickets.view_funcionario"], "pattern": r"^/dashboard/", }, { "verbose_name": u"Tickets", "action": "minitickets:list-ticket", "icon": "ticket", "permissions": ["minitickets.view_ticket"], "pattern": r"^/tickets/", }, { "verbose_name": u"Cadastro", "icon": "edit", "submenus": [{ "verbose_name": u"Cliente", "action": "minitickets:list-cliente", "icon": "building-o", "permissions": ["minitickets.view_cliente"], "pattern": r"^/clientes/", }, { "verbose_name": u"Produto", "action": "minitickets:list-produto", "icon": "puzzle-piece", "permissions": ["minitickets.view_produto"], "pattern": r"^/produtos/", }, { "verbose_name": u"Funcionário", "icon": "user", "action": "minitickets:list-funcionario", "permissions": ["minitickets.view_funcionario"], "pattern": r"^/funcionarios/", }] }]
apache-2.0
mebigfatguy/java-driver
driver-mapping/src/main/java/com/datastax/driver/mapping/Mapper.java
47634
/* * Copyright (C) 2012-2015 DataStax Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.datastax.driver.mapping; import com.datastax.driver.core.*; import com.datastax.driver.core.querybuilder.Delete; import com.datastax.driver.core.querybuilder.Insert; import com.datastax.driver.core.querybuilder.QueryBuilder; import com.datastax.driver.mapping.Mapper.Option.SaveNullFields; import com.datastax.driver.mapping.annotations.Accessor; import com.datastax.driver.mapping.annotations.Computed; import com.google.common.base.Function; import com.google.common.base.Functions; import com.google.common.base.Objects; import com.google.common.base.Preconditions; import com.google.common.util.concurrent.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.*; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.ExecutionException; import static com.datastax.driver.mapping.Mapper.Option.Type.SAVE_NULL_FIELDS; import static com.google.common.base.Preconditions.checkArgument; /** * An object handling the mapping of a particular class. * <p/> * A {@code Mapper} object is obtained from a {@code MappingManager} using the * {@link MappingManager#mapper} method. */ public class Mapper<T> { private static final Logger logger = LoggerFactory.getLogger(Mapper.class); private static final Function<Object, Void> TO_NULL = Functions.constant(null); private final MappingManager manager; private final Class<T> klass; private final EntityMapper<T> mapper; private final TableMetadata tableMetadata; // Cache prepared statements for each type of query we use. private final ConcurrentMap<MapperQueryKey, ListenableFuture<PreparedStatement>> preparedQueries = new ConcurrentHashMap<MapperQueryKey, ListenableFuture<PreparedStatement>>(); private volatile EnumMap<Option.Type, Option> defaultSaveOptions; private volatile EnumMap<Option.Type, Option> defaultGetOptions; private volatile EnumMap<Option.Type, Option> defaultDeleteOptions; private static final EnumMap<Option.Type, Option> NO_OPTIONS = new EnumMap<Option.Type, Option>(Option.Type.class); private final Function<ResultSet, T> mapOneFunction; final Function<ResultSet, T> mapOneFunctionWithoutAliases; final Function<ResultSet, Result<T>> mapAllFunctionWithoutAliases; Mapper(MappingManager manager, Class<T> klass, EntityMapper<T> mapper) { this.manager = manager; this.klass = klass; this.mapper = mapper; KeyspaceMetadata keyspace = session().getCluster().getMetadata().getKeyspace(mapper.keyspace); this.tableMetadata = keyspace == null ? null : keyspace.getTable(mapper.table); this.mapOneFunction = new Function<ResultSet, T>() { @Override public T apply(ResultSet rs) { return Mapper.this.map(rs).one(); } }; this.mapOneFunctionWithoutAliases = new Function<ResultSet, T>() { @Override public T apply(ResultSet rs) { return Mapper.this.map(rs).one(); } }; this.mapAllFunctionWithoutAliases = new Function<ResultSet, Result<T>>() { @Override public Result<T> apply(ResultSet rs) { return Mapper.this.map(rs); } }; this.defaultSaveOptions = NO_OPTIONS; this.defaultGetOptions = NO_OPTIONS; this.defaultDeleteOptions = NO_OPTIONS; } Session session() { return manager.getSession(); } ListenableFuture<PreparedStatement> getPreparedQueryAsync(QueryType type, Set<PropertyMapper> columns, EnumMap<Option.Type, Option> options) { final MapperQueryKey pqk = new MapperQueryKey(type, columns, options); ListenableFuture<PreparedStatement> existingFuture = preparedQueries.get(pqk); if (existingFuture == null) { final SettableFuture<PreparedStatement> future = SettableFuture.create(); ListenableFuture<PreparedStatement> old = preparedQueries.putIfAbsent(pqk, future); if (old != null) { return old; } else { String queryString = type.makePreparedQueryString(tableMetadata, mapper, manager, columns, options.values()); logger.debug("Preparing query {}", queryString); SimpleStatement s = new SimpleStatement(queryString); // all queries generated by the mapper are idempotent s.setIdempotent(true); Futures.addCallback(session().prepareAsync(s), new FutureCallback<PreparedStatement>() { @Override public void onSuccess(PreparedStatement stmt) { future.set(stmt); } @Override public void onFailure(Throwable t) { future.setException(t); } }); return future; } } else { return existingFuture; } } ListenableFuture<PreparedStatement> getPreparedQueryAsync(QueryType type, EnumMap<Option.Type, Option> options) { return getPreparedQueryAsync(type, Collections.<PropertyMapper>emptySet(), options); } Class<T> getMappedClass() { return klass; } /** * The {@code TableMetadata} for this mapper. * * @return the {@code TableMetadata} for this mapper or {@code null} if keyspace is not set. */ public TableMetadata getTableMetadata() { return tableMetadata; } /** * The {@code MappingManager} managing this mapper. * * @return the {@code MappingManager} managing this mapper. */ public MappingManager getManager() { return manager; } /** * Creates a query that can be used to save the provided entity. * <p/> * This method is useful if you want to setup a number of options (tracing, * conistency level, ...) of the returned statement before executing it manually * or need access to the {@code ResultSet} object after execution (to get the * trace, the execution info, ...), but in other cases, calling {@link #save} * or {@link #saveAsync} is shorter. * * @param entity the entity to save. * @return a query that saves {@code entity} (based on it's defined mapping). */ public Statement saveQuery(T entity) { try { return Uninterruptibles.getUninterruptibly(saveQueryAsync(entity, this.defaultSaveOptions)); } catch (ExecutionException e) { throw DriverThrowables.propagateCause(e); } } /** * Creates a query that can be used to save the provided entity. * <p/> * This method is useful if you want to setup a number of options (tracing, * conistency level, ...) of the returned statement before executing it manually * or need access to the {@code ResultSet} object after execution (to get the * trace, the execution info, ...), but in other cases, calling {@link #save} * or {@link #saveAsync} is shorter. * This method allows you to provide a suite of {@link Option} to include in * the SAVE query. Options currently supported for SAVE are : * <ul> * <li>Timestamp</li> * <li>Time-to-live (ttl)</li> * <li>Consistency level</li> * <li>Tracing</li> * </ul> * * @param entity the entity to save. * @return a query that saves {@code entity} (based on it's defined mapping). */ public Statement saveQuery(T entity, Option... options) { try { return Uninterruptibles.getUninterruptibly(saveQueryAsync(entity, toMapWithDefaults(options, this.defaultSaveOptions))); } catch (ExecutionException e) { throw DriverThrowables.propagateCause(e); } } private ListenableFuture<BoundStatement> saveQueryAsync(T entity, final EnumMap<Option.Type, Option> options) { final Map<PropertyMapper, Object> values = new HashMap<PropertyMapper, Object>(); boolean saveNullFields = shouldSaveNullFields(options); for (PropertyMapper col : mapper.allColumns) { Object value = col.getValue(entity); if (!col.isComputed() && (saveNullFields || value != null)) { values.put(col, value); } } return Futures.transform(getPreparedQueryAsync(QueryType.SAVE, values.keySet(), options), new Function<PreparedStatement, BoundStatement>() { @Override public BoundStatement apply(PreparedStatement input) { BoundStatement bs = input.bind(); int i = 0; for (Map.Entry<PropertyMapper, Object> entry : values.entrySet()) { PropertyMapper mapper = entry.getKey(); Object value = entry.getValue(); setObject(bs, i++, value, mapper); } if (mapper.writeConsistency != null) bs.setConsistencyLevel(mapper.writeConsistency); for (Option opt : options.values()) { opt.checkValidFor(QueryType.SAVE, manager); opt.addToPreparedStatement(bs, i++); } return bs; } }); } private static boolean shouldSaveNullFields(EnumMap<Option.Type, Option> options) { SaveNullFields option = (SaveNullFields) options.get(SAVE_NULL_FIELDS); return option == null || option.saveNullFields; } private static void setObject(BoundStatement bs, int i, Object value, PropertyMapper mapper) { TypeCodec<Object> customCodec = mapper.customCodec; if (customCodec != null) bs.set(i, value, customCodec); else bs.set(i, value, mapper.javaType); } /** * Saves an entity mapped by this mapper. * <p/> * This method is basically equivalent to: {@code getManager().getSession().execute(saveQuery(entity))}. * * @param entity the entity to save. */ public void save(T entity) { try { Uninterruptibles.getUninterruptibly(saveAsync(entity)); } catch (ExecutionException e) { throw DriverThrowables.propagateCause(e); } } /** * Saves an entity mapped by this mapper and using special options for save. * This method allows you to provide a suite of {@link Option} to include in * the SAVE query. Options currently supported for SAVE are : * <ul> * <li>Timestamp</li> * <li>Time-to-live (ttl)</li> * <li>Consistency level</li> * <li>Tracing</li> * </ul> * * @param entity the entity to save. * @param options the options object specified defining special options when saving. */ public void save(T entity, Option... options) { try { Uninterruptibles.getUninterruptibly(saveAsync(entity, options)); } catch (ExecutionException e) { throw DriverThrowables.propagateCause(e); } } /** * Saves an entity mapped by this mapper asynchronously. * <p/> * This method is basically equivalent to: {@code getManager().getSession().executeAsync(saveQuery(entity))}. * * @param entity the entity to save. * @return a future on the completion of the save operation. */ public ListenableFuture<Void> saveAsync(T entity) { return submitVoidQueryAsync(saveQueryAsync(entity, this.defaultSaveOptions)); } /** * Save an entity mapped by this mapper asynchronously using special options for save. * <p/> * This method is basically equivalent to: {@code getManager().getSession().executeAsync(saveQuery(entity, options))}. * * @param entity the entity to save. * @param options the options object specified defining special options when saving. * @return a future on the completion of the save operation. */ public ListenableFuture<Void> saveAsync(T entity, Option... options) { return submitVoidQueryAsync(saveQueryAsync(entity, toMapWithDefaults(options, this.defaultSaveOptions))); } private ListenableFuture<Void> submitVoidQueryAsync(ListenableFuture<BoundStatement> bsFuture) { ListenableFuture<ResultSet> rsFuture = Futures.transform(bsFuture, new AsyncFunction<BoundStatement, ResultSet>() { @Override public ListenableFuture<ResultSet> apply(BoundStatement bs) throws Exception { return session().executeAsync(bs); } }); return Futures.transform(rsFuture, TO_NULL); } /** * Creates a query to fetch entity given its PRIMARY KEY. * <p/> * The values provided must correspond to the columns composing the PRIMARY * KEY (in the order of said primary key). * <p/> * This method is useful if you want to setup a number of options (tracing, * conistency level, ...) of the returned statement before executing it manually, * but in other cases, calling {@link #get} or {@link #getAsync} is shorter. * <p/> * This method allows you to provide a suite of {@link Option} to include in * the GET query. Options currently supported for GET are : * <ul> * <li>Consistency level</li> * <li>Tracing</li> * </ul> * * @param objects the primary key of the entity to fetch, or more precisely * the values for the columns of said primary key in the order of the primary key. * Can be followed by {@link Option} to include in the DELETE query. * @return a query that fetch the entity of PRIMARY KEY {@code objects}. * @throws IllegalArgumentException if the number of value provided differ from * the number of columns composing the PRIMARY KEY of the mapped class, or if * at least one of those values is {@code null}. */ public Statement getQuery(Object... objects) { try { return Uninterruptibles.getUninterruptibly(getQueryAsync(objects)); } catch (ExecutionException e) { throw DriverThrowables.propagateCause(e); } } private ListenableFuture<BoundStatement> getQueryAsync(Object... objects) { // Order and duplicates matter for primary keys List<Object> pks = new ArrayList<Object>(); EnumMap<Option.Type, Option> options = new EnumMap<Option.Type, Option>(defaultGetOptions); for (Object o : objects) { if (o instanceof Option) { Option option = (Option) o; options.put(option.type, option); } else { pks.add(o); } } return getQueryAsync(pks, options); } private ListenableFuture<BoundStatement> getQueryAsync(final List<Object> primaryKeys, final EnumMap<Option.Type, Option> options) { if (primaryKeys.size() != mapper.primaryKeySize()) throw new IllegalArgumentException(String.format("Invalid number of PRIMARY KEY columns provided, %d expected but got %d", mapper.primaryKeySize(), primaryKeys.size())); return Futures.transform(getPreparedQueryAsync(QueryType.GET, options), new Function<PreparedStatement, BoundStatement>() { @Override public BoundStatement apply(PreparedStatement input) { BoundStatement bs = new MapperBoundStatement(input); int i = 0; for (Object value : primaryKeys) { PropertyMapper column = mapper.getPrimaryKeyColumn(i); if (value == null) { throw new IllegalArgumentException(String.format("Invalid null value for PRIMARY KEY column %s (argument %d)", column.columnName, i)); } setObject(bs, i++, value, column); } if (mapper.readConsistency != null) bs.setConsistencyLevel(mapper.readConsistency); for (Option opt : options.values()) { opt.checkValidFor(QueryType.GET, manager); opt.addToPreparedStatement(bs, i); if (opt.isIncludedInQuery()) i++; } return bs; } }); } /** * Fetch an entity based on its primary key. * <p/> * This method is basically equivalent to: {@code map(getManager().getSession().execute(getQuery(objects))).one()}. * * @param objects the primary key of the entity to fetch, or more precisely * the values for the columns of said primary key in the order of the primary key. * Can be followed by {@link Option} to include in the DELETE query. * @return the entity fetched or {@code null} if it doesn't exist. * @throws IllegalArgumentException if the number of value provided differ from * the number of columns composing the PRIMARY KEY of the mapped class, or if * at least one of those values is {@code null}. */ public T get(Object... objects) { try { return Uninterruptibles.getUninterruptibly(getAsync(objects)); } catch (ExecutionException e) { throw DriverThrowables.propagateCause(e); } } /** * Fetch an entity based on its primary key asynchronously. * <p/> * This method is basically equivalent to mapping the result of: {@code getManager().getSession().executeAsync(getQuery(objects))}. * * @param objects the primary key of the entity to fetch, or more precisely * the values for the columns of said primary key in the order of the primary key. * Can be followed by {@link Option} to include in the DELETE query. * @return a future on the fetched entity. The return future will yield * {@code null} if said entity doesn't exist. * @throws IllegalArgumentException if the number of value provided differ from * the number of columns composing the PRIMARY KEY of the mapped class, or if * at least one of those values is {@code null}. */ public ListenableFuture<T> getAsync(final Object... objects) { ListenableFuture<BoundStatement> bsFuture = getQueryAsync(objects); ListenableFuture<ResultSet> rsFuture = Futures.transform(bsFuture, new AsyncFunction<BoundStatement, ResultSet>() { @Override public ListenableFuture<ResultSet> apply(BoundStatement bs) throws Exception { return session().executeAsync(bs); } }); return Futures.transform(rsFuture, mapOneFunction); } /** * Creates a query that can be used to delete the provided entity. * <p/> * This method is a shortcut that extract the PRIMARY KEY from the * provided entity and call {@link #deleteQuery(Object...)} with it. * This method allows you to provide a suite of {@link Option} to include in * the DELETE query. Note : currently, only {@link com.datastax.driver.mapping.Mapper.Option.Timestamp} * is supported for DELETE queries. * <p/> * This method is useful if you want to setup a number of options (tracing, * conistency level, ...) of the returned statement before executing it manually * or need access to the {@code ResultSet} object after execution (to get the * trace, the execution info, ...), but in other cases, calling {@link #delete} * or {@link #deleteAsync} is shorter. * <p/> * This method allows you to provide a suite of {@link Option} to include in * the DELETE query. Options currently supported for DELETE are : * <ul> * <li>Timestamp</li> * <li>Consistency level</li> * <li>Tracing</li> * </ul> * * @param entity the entity to delete. * @param options the options to add to the DELETE query. * @return a query that delete {@code entity} (based on it's defined mapping) with * provided USING options. */ public Statement deleteQuery(T entity, Option... options) { try { return Uninterruptibles.getUninterruptibly(deleteQueryAsync(entity, toMapWithDefaults(options, defaultDeleteOptions))); } catch (ExecutionException e) { throw DriverThrowables.propagateCause(e); } } /** * Creates a query that can be used to delete the provided entity. * <p/> * This method is a shortcut that extract the PRIMARY KEY from the * provided entity and call {@link #deleteQuery(Object...)} with it. * <p/> * This method is useful if you want to setup a number of options (tracing, * conistency level, ...) of the returned statement before executing it manually * or need access to the {@code ResultSet} object after execution (to get the * trace, the execution info, ...), but in other cases, calling {@link #delete} * or {@link #deleteAsync} is shorter. * * @param entity the entity to delete. * @return a query that delete {@code entity} (based on it's defined mapping). */ public Statement deleteQuery(T entity) { try { return Uninterruptibles.getUninterruptibly(deleteQueryAsync(entity, defaultDeleteOptions)); } catch (ExecutionException e) { throw DriverThrowables.propagateCause(e); } } /** * Creates a query that can be used to delete an entity given its PRIMARY KEY. * <p/> * The values provided must correspond to the columns composing the PRIMARY * KEY (in the order of said primary key). The values can also contain, after * specifying the primary keys columns, a suite of {@link Option} to include in * the DELETE query. Note : currently, only {@link com.datastax.driver.mapping.Mapper.Option.Timestamp} * is supported for DELETE queries. * <p/> * This method is useful if you want to setup a number of options (tracing, * conistency level, ...) of the returned statement before executing it manually * or need access to the {@code ResultSet} object after execution (to get the * trace, the execution info, ...), but in other cases, calling {@link #delete} * or {@link #deleteAsync} is shorter. * This method allows you to provide a suite of {@link Option} to include in * the DELETE query. Options currently supported for DELETE are : * <ul> * <li>Timestamp</li> * <li>Consistency level</li> * <li>Tracing</li> * </ul> * * @param objects the primary key of the entity to delete, or more precisely * the values for the columns of said primary key in the order of the primary key. * Can be followed by {@link Option} to include in the DELETE * query. * @return a query that delete the entity of PRIMARY KEY {@code primaryKey}. * @throws IllegalArgumentException if the number of value provided differ from * the number of columns composing the PRIMARY KEY of the mapped class, or if * at least one of those values is {@code null}. */ public Statement deleteQuery(Object... objects) { try { return Uninterruptibles.getUninterruptibly(deleteQueryAsync(objects)); } catch (ExecutionException e) { throw DriverThrowables.propagateCause(e); } } private ListenableFuture<BoundStatement> deleteQueryAsync(T entity, EnumMap<Option.Type, Option> options) { List<Object> pks = new ArrayList<Object>(); for (int i = 0; i < mapper.primaryKeySize(); i++) { pks.add(mapper.getPrimaryKeyColumn(i).getValue(entity)); } return deleteQueryAsync(pks, options); } private ListenableFuture<BoundStatement> deleteQueryAsync(Object... objects) { // Order and duplicates matter for primary keys List<Object> pks = new ArrayList<Object>(); EnumMap<Option.Type, Option> options = new EnumMap<Option.Type, Option>(defaultDeleteOptions); for (Object o : objects) { if (o instanceof Option) { Option option = (Option) o; options.put(option.type, option); } else { pks.add(o); } } return deleteQueryAsync(pks, options); } private ListenableFuture<BoundStatement> deleteQueryAsync(final List<Object> primaryKey, final EnumMap<Option.Type, Option> options) { if (primaryKey.size() != mapper.primaryKeySize()) throw new IllegalArgumentException(String.format("Invalid number of PRIMARY KEY columns provided, %d expected but got %d", mapper.primaryKeySize(), primaryKey.size())); return Futures.transform(getPreparedQueryAsync(QueryType.DEL, options), new Function<PreparedStatement, BoundStatement>() { @Override public BoundStatement apply(PreparedStatement input) { BoundStatement bs = input.bind(); if (mapper.writeConsistency != null) bs.setConsistencyLevel(mapper.writeConsistency); int i = 0; for (Option opt : options.values()) { opt.checkValidFor(QueryType.DEL, manager); opt.addToPreparedStatement(bs, i); if (opt.isIncludedInQuery()) i++; } int columnNumber = 0; for (Object value : primaryKey) { PropertyMapper column = mapper.getPrimaryKeyColumn(columnNumber); if (value == null) { throw new IllegalArgumentException(String.format("Invalid null value for PRIMARY KEY column %s (argument %d)", column.columnName, i)); } setObject(bs, i++, value, column); columnNumber++; } return bs; } }); } /** * Deletes an entity mapped by this mapper. * <p/> * This method is basically equivalent to: {@code getManager().getSession().execute(deleteQuery(entity))}. * * @param entity the entity to delete. */ public void delete(T entity) { try { Uninterruptibles.getUninterruptibly(deleteAsync(entity)); } catch (ExecutionException e) { throw DriverThrowables.propagateCause(e); } } /** * Deletes an entity mapped by this mapper using provided options. * <p/> * This method is basically equivalent to: {@code getManager().getSession().execute(deleteQuery(entity, options))}. * * @param entity the entity to delete. * @param options the options to add to the DELETE query. */ public void delete(T entity, Option... options) { try { Uninterruptibles.getUninterruptibly(deleteAsync(entity, options)); } catch (ExecutionException e) { throw DriverThrowables.propagateCause(e); } } /** * Deletes an entity mapped by this mapper asynchronously. * <p/> * This method is basically equivalent to: {@code getManager().getSession().executeAsync(deleteQuery(entity))}. * * @param entity the entity to delete. * @return a future on the completion of the deletion. */ public ListenableFuture<Void> deleteAsync(T entity) { return submitVoidQueryAsync(deleteQueryAsync(entity, defaultDeleteOptions)); } /** * Deletes an entity mapped by this mapper asynchronously using provided options. * <p/> * This method is basically equivalent to: {@code getManager().getSession().executeAsync(deleteQuery(entity, options))}. * * @param entity the entity to delete. * @param options the options to add to the DELETE query. * @return a future on the completion of the deletion. */ public ListenableFuture<Void> deleteAsync(T entity, Option... options) { return submitVoidQueryAsync(deleteQueryAsync(entity, toMapWithDefaults(options, defaultDeleteOptions))); } /** * Deletes an entity based on its primary key. * <p/> * This method is basically equivalent to: {@code getManager().getSession().execute(deleteQuery(objects))}. * * @param objects the primary key of the entity to delete, or more precisely * the values for the columns of said primary key in the order * of the primary key.Can be followed by {@link Option} to include * in the DELETE query. * @throws IllegalArgumentException if the number of value provided differ from * the number of columns composing the PRIMARY KEY of the mapped class, or if * at least one of those values is {@code null}. */ public void delete(Object... objects) { try { Uninterruptibles.getUninterruptibly(deleteAsync(objects)); } catch (ExecutionException e) { throw DriverThrowables.propagateCause(e); } } /** * Deletes an entity based on its primary key asynchronously. * <p/> * This method is basically equivalent to: {@code getManager().getSession().executeAsync(deleteQuery(objects))}. * * @param objects the primary key of the entity to delete, or more precisely * the values for the columns of said primary key in the order * of the primary key. Can be followed by {@link Option} to include * in the DELETE query. * @throws IllegalArgumentException if the number of value provided differ from * the number of columns composing the PRIMARY KEY of the mapped class, or if * at least one of those values is {@code null}. */ public ListenableFuture<Void> deleteAsync(Object... objects) { return submitVoidQueryAsync(deleteQueryAsync(objects)); } /** * Maps the rows from a {@code ResultSet} into the class this is a mapper of. * <p/> * If the query was user-generated (that is, passed directly to {@code session.execute()} or configured with * {@link com.datastax.driver.mapping.annotations.Query @Query} in an * {@link com.datastax.driver.mapping.annotations.Accessor @Accessor}-annotated interface), then only the columns * present in the result set will be mapped to the corresponding fields, and {@link Computed} fields will not be * populated. * <p/> * If the query was generated by the mapper (for example with {@link #getQuery(Object...)}), all fields will be * mapped, as if the object came from a direct {@link #get(Object...)} call. * * @param resultSet the {@code ResultSet} to map. * @return the mapped result set. Note that the returned mapped result set * will encapsulate {@code resultSet} and so consuming results from this * returned mapped result set will consume results from {@code resultSet} * and vice-versa. */ public Result<T> map(ResultSet resultSet) { boolean useAlias = !manager.isCassandraV1 && isFromMapperQuery(resultSet); return new Result<T>(resultSet, mapper, useAlias); } /** * Asynchronously maps the rows from a {@link ResultSetFuture} into the class this is a mapper of. * <p/> * Use this method to map a {@link ResultSetFuture} that was not generated by the mapper * (e.g. a {@link ResultSetFuture} coming from a manual query or an {@link Accessor} method). * It expects that the result set contains all column mapped in the target class, * and that they are not aliased. {@link Computed} fields will not be filled in mapped objects. * * @param resultSetFuture the {@link ResultSetFuture} to map. * @return the mapped result set future. Note that the returned mapped result set * will encapsulate the result set returned by {@code resultSetFuture} and so consuming results from this * returned mapped result set will consume results from that result set * and vice-versa. */ public ListenableFuture<Result<T>> mapAsync(ResultSetFuture resultSetFuture) { return Futures.transform(resultSetFuture, new Function<ResultSet, Result<T>>() { @Override public Result<T> apply(ResultSet rs) { return map(rs); } }); } private boolean isFromMapperQuery(ResultSet resultSet) { return resultSet.getExecutionInfo().getStatement() instanceof MapperBoundStatement; } /** * @deprecated you no longer need to specify whether a result set is aliased, it will be detected automatically. Use * {@link #map(ResultSet)} instead of this method. */ @Deprecated public Result<T> mapAliased(ResultSet resultSet) { return (manager.isCassandraV1) ? map(resultSet) // no aliases : new Result<T>(resultSet, mapper, true); } /** * Set the default save {@link Option} for this object mapper, that will be used * in all save operations unless overridden. Refer to {@link Mapper#save(Object, Option...)})} * to check available save options. * * @param options the options to set. To reset, use {@link Mapper#resetDefaultSaveOptions}. */ public void setDefaultSaveOptions(Option... options) { this.defaultSaveOptions = toMap(options); } /** * Reset the default save options for this object mapper. */ public void resetDefaultSaveOptions() { this.defaultSaveOptions = NO_OPTIONS; } /** * Set the default get {@link Option} for this object mapper, that will be used * in all get operations unless overridden. Refer to {@link Mapper#get(Object...)} )} to check available * get options. * * @param options the options to set. To reset, use {@link Mapper#resetDefaultGetOptions}. */ public void setDefaultGetOptions(Option... options) { this.defaultGetOptions = toMap(options); } /** * Reset the default save options for this object mapper. */ public void resetDefaultGetOptions() { this.defaultGetOptions = NO_OPTIONS; } /** * Set the default delete {@link Option} for this object mapper, that will be used * in all delete operations unless overridden. Refer to {@link Mapper#delete(Object...)} )} * to check available delete options. * * @param options the options to set. To reset, use {@link Mapper#resetDefaultDeleteOptions}. */ public void setDefaultDeleteOptions(Option... options) { this.defaultDeleteOptions = toMap(options); } /** * Reset the default delete options for this object mapper. */ public void resetDefaultDeleteOptions() { this.defaultDeleteOptions = NO_OPTIONS; } private static EnumMap<Option.Type, Option> toMap(Option[] options) { EnumMap<Option.Type, Option> result = new EnumMap<Option.Type, Option>(Option.Type.class); for (Option option : options) { result.put(option.type, option); } return result; } private static EnumMap<Option.Type, Option> toMapWithDefaults(Option[] options, EnumMap<Option.Type, Option> defaults) { EnumMap<Option.Type, Option> result = new EnumMap<Option.Type, Option>(defaults); for (Option option : options) { result.put(option.type, option); } return result; } /** * An option for a mapper operation. * <p/> * Options can be passed to individual operations: * <pre> * mapper.save(myObject, Option.ttl(3600)); * </pre> * <p/> * The mapper can also have defaults, that will apply to all operations that do not * override these particular option: * <pre> * mapper.setDefaultSaveOptions(Option.ttl(3600)); * mapper.save(myObject); * </pre> * <p/> * <p/> * See the static methods in this class for available options. */ public static abstract class Option { enum Type {TTL, TIMESTAMP, CL, TRACING, SAVE_NULL_FIELDS} final Type type; protected Option(Type type) { this.type = type; } /** * Creates a new Option object to add time-to-live to a mapper operation. This is * only valid for save operations. * <p/> * Note that this option is only available if using {@link ProtocolVersion#V2} or above. * * @param ttl the TTL (in seconds). * @return the option. */ public static Option ttl(int ttl) { return new Ttl(ttl); } /** * Creates a new Option object to add a timestamp to a mapper operation. This is * only valid for save and delete operations. * <p/> * Note that this option is only available if using {@link ProtocolVersion#V2} or above. * * @param timestamp the timestamp (in microseconds). * @return the option. */ public static Option timestamp(long timestamp) { return new Timestamp(timestamp); } /** * Creates a new Option object to add a consistency level value to a mapper operation. This * is valid for save, delete and get operations. * <p/> * Note that the consistency level can also be defined at the mapper level, as a parameter * of the {@link com.datastax.driver.mapping.annotations.Table} annotation (this is redundant * for backward compatibility). This option, whether defined on a specific call or as the * default, will always take precedence over the annotation. * * @param cl the {@link com.datastax.driver.core.ConsistencyLevel} to use for the operation. * @return the option. */ public static Option consistencyLevel(ConsistencyLevel cl) { return new ConsistencyLevelOption(cl); } /** * Creates a new Option object to enable query tracing for a mapper operation. This * is valid for save, delete and get operations. * * @param enabled whether to enable tracing. * @return the option. */ public static Option tracing(boolean enabled) { return new Tracing(enabled); } /** * Creates a new Option object to specify whether null entity fields should be included in * insert queries. This option is valid only for save operations. * <p/> * If this option is not specified, it defaults to {@code true} (null fields are saved). * * @param enabled whether to include null fields in queries. * @return the option. */ public static Option saveNullFields(boolean enabled) { return new SaveNullFields(enabled); } public Type getType() { return this.type; } abstract void appendTo(Insert.Options usings); abstract void appendTo(Delete.Options usings); abstract void addToPreparedStatement(BoundStatement bs, int i); abstract void checkValidFor(QueryType qt, MappingManager manager) throws IllegalArgumentException; abstract boolean isIncludedInQuery(); static class Ttl extends Option { private final int ttlValue; Ttl(int value) { super(Type.TTL); this.ttlValue = value; } @Override void appendTo(Insert.Options usings) { usings.and(QueryBuilder.ttl(QueryBuilder.bindMarker())); } @Override void appendTo(Delete.Options usings) { throw new UnsupportedOperationException("shouldn't be called"); } @Override void addToPreparedStatement(BoundStatement bs, int i) { bs.setInt(i, this.ttlValue); } @Override void checkValidFor(QueryType qt, MappingManager manager) { checkArgument(!manager.isCassandraV1, "TTL option requires native protocol v2 or above"); checkArgument(qt == QueryType.SAVE, "TTL option is only allowed in save queries"); } @Override boolean isIncludedInQuery() { return true; } } static class Timestamp extends Option { private final long tsValue; Timestamp(long value) { super(Type.TIMESTAMP); this.tsValue = value; } @Override void appendTo(Insert.Options usings) { usings.and(QueryBuilder.timestamp(QueryBuilder.bindMarker())); } @Override void appendTo(Delete.Options usings) { usings.and(QueryBuilder.timestamp(QueryBuilder.bindMarker())); } @Override void checkValidFor(QueryType qt, MappingManager manager) { checkArgument(!manager.isCassandraV1, "Timestamp option requires native protocol v2 or above"); checkArgument(qt == QueryType.SAVE || qt == QueryType.DEL, "Timestamp option is only allowed in save and delete queries"); } @Override void addToPreparedStatement(BoundStatement bs, int i) { bs.setLong(i, this.tsValue); } @Override boolean isIncludedInQuery() { return true; } } static class ConsistencyLevelOption extends Option { private final ConsistencyLevel cl; ConsistencyLevelOption(ConsistencyLevel cl) { super(Type.CL); this.cl = cl; } @Override void appendTo(Insert.Options usings) { throw new UnsupportedOperationException("shouldn't be called"); } @Override void appendTo(Delete.Options usings) { throw new UnsupportedOperationException("shouldn't be called"); } @Override void addToPreparedStatement(BoundStatement bs, int i) { bs.setConsistencyLevel(cl); } @Override void checkValidFor(QueryType qt, MappingManager manager) { checkArgument(qt == QueryType.SAVE || qt == QueryType.DEL || qt == QueryType.GET, "Consistency level option is only allowed in save, delete and get queries"); } @Override boolean isIncludedInQuery() { return false; } } static class Tracing extends Option { private final boolean tracing; Tracing(boolean tracing) { super(Type.TRACING); this.tracing = tracing; } @Override void appendTo(Insert.Options usings) { throw new UnsupportedOperationException("shouldn't be called"); } @Override void appendTo(Delete.Options usings) { throw new UnsupportedOperationException("shouldn't be called"); } @Override void addToPreparedStatement(BoundStatement bs, int i) { if (this.tracing) bs.enableTracing(); } @Override void checkValidFor(QueryType qt, MappingManager manager) { checkArgument(qt == QueryType.SAVE || qt == QueryType.DEL || qt == QueryType.GET, "Tracing option is only allowed in save, delete and get queries"); } @Override boolean isIncludedInQuery() { return false; } } static class SaveNullFields extends Option { private final boolean saveNullFields; SaveNullFields(boolean saveNullFields) { super(SAVE_NULL_FIELDS); this.saveNullFields = saveNullFields; } @Override void appendTo(Insert.Options usings) { throw new UnsupportedOperationException("shouldn't be called"); } @Override void appendTo(Delete.Options usings) { throw new UnsupportedOperationException("shouldn't be called"); } @Override void addToPreparedStatement(BoundStatement bs, int i) { // nothing to do } @Override void checkValidFor(QueryType qt, MappingManager manager) { checkArgument(qt == QueryType.SAVE, "SaveNullFields option is only allowed in save queries"); } @Override boolean isIncludedInQuery() { return false; } } } private static class MapperQueryKey { private final QueryType queryType; private final EnumSet<Option.Type> optionTypes; private final Set<PropertyMapper> columns; MapperQueryKey(QueryType queryType, Set<PropertyMapper> propertyMappers, EnumMap<Option.Type, Option> options) { Preconditions.checkNotNull(queryType); Preconditions.checkNotNull(options); Preconditions.checkNotNull(propertyMappers); this.queryType = queryType; this.columns = propertyMappers; this.optionTypes = EnumSet.noneOf(Option.Type.class); for (Option opt : options.values()) { if (opt.isIncludedInQuery()) this.optionTypes.add(opt.type); } } @Override public boolean equals(Object other) { if (this == other) return true; if (other instanceof MapperQueryKey) { MapperQueryKey that = (MapperQueryKey) other; return this.queryType.equals(that.queryType) && this.optionTypes.equals(that.optionTypes) && this.columns.equals(that.columns); } return false; } @Override public int hashCode() { return Objects.hashCode(queryType, optionTypes, columns); } } }
apache-2.0
ArloL/liquibase
liquibase-core/src/main/java/liquibase/datatype/core/NumberType.java
918
package liquibase.datatype.core; import liquibase.database.Database; import liquibase.database.core.*; import liquibase.datatype.DataTypeInfo; import liquibase.datatype.DatabaseDataType; import liquibase.datatype.LiquibaseDataType; @DataTypeInfo(name="number", aliases = {"numeric", "java.sql.Types.NUMERIC"}, minParameters = 0, maxParameters = 0, priority = LiquibaseDataType.PRIORITY_DEFAULT) public class NumberType extends LiquibaseDataType { @Override public DatabaseDataType toDatabaseDataType(Database database) { if (database instanceof MySQLDatabase || database instanceof DB2Database|| database instanceof MSSQLDatabase || database instanceof HsqlDatabase || database instanceof DerbyDatabase || database instanceof PostgresDatabase) { return new DatabaseDataType("numeric", getParameters()); } return super.toDatabaseDataType(database); } }
apache-2.0
dev-sirius/smart-home-controller
smarthouse/apps.py
95
from django.apps import AppConfig class SmarthouseConfig(AppConfig): name = 'smarthouse'
apache-2.0
FINRAOS/herd
herd-code/herd-tools/herd-spark-data-source/src/main/scala/org/apache/spark/sql/herd/HerdFileIndex.scala
9237
/* * Copyright 2015 herd contributors * * 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.apache.spark.sql.herd import java.util.TimeZone import org.apache.commons.lang3.StringUtils import org.apache.hadoop.conf.Configuration import org.apache.hadoop.fs.{FileStatus, Path} import org.apache.spark.internal.Logging import org.apache.spark.sql.SparkSession import org.apache.spark.sql.catalyst.InternalRow import org.apache.spark.sql.catalyst.catalog.ExternalCatalogUtils.unescapePathName import org.apache.spark.sql.catalyst.expressions._ import org.apache.spark.sql.execution.datasources.{FileIndex, PartitionPath, PartitionSpec} import org.apache.spark.sql.types._ import org.apache.spark.util.SerializableConfiguration import scala.collection.JavaConverters._ import scala.collection.mutable import scala.collection.mutable.ArrayBuffer import org.finra.herd.sdk.model.Partition /** A custom [[org.apache.spark.sql.execution.datasources.FileIndex]] to use the partition paths provided by Herd, vs Spark's auto-discovery * * The custom data source abstracts the logic of querying Herd and defining DataFrames from the source data, or writing and creating * data sets. From an end-user's perspective using the Herd data source would be very similar to standard Spark data sources, using the DataFrameReader/Write * interfaces. * * @param sparkSession The spark session * @param api The ApiClient instance needed by Herd SDK * @param herdPartitions The list of partitions * @param namespace The namespace * @param businessObjectName The business object definition name * @param formatUsage The business object format usage (e.g. PRC). * @param formatFileType The business object format file type (e.g. GZ). * @param partitionKey The business object format partition key. * @param herdPartitionSchema The schema associated with the business object format */ private[sql] abstract class HerdFileIndexBase( sparkSession: SparkSession, api: () => HerdApi, herdPartitions: Seq[(Integer, String, Seq[String], Integer, String)], namespace: String, businessObjectName: String, formatUsage: String, formatFileType: String, partitionKey: String, herdPartitionSchema: StructType, storagePathPrefix: String) extends FileIndex with Logging with Serializable { import HerdFileIndexBase._ @transient protected val hadoopConf = sparkSession.sessionState.newHadoopConf() @transient protected val partitionSpec = { val partitions = herdPartitions.map { case (formatVersion, partitionValue, subPartitionValues, dataVersion, partitionLocation) => val row = if (herdPartitionSchema.nonEmpty) { val partValues = partitionValue +: subPartitionValues val values = partValues.zipWithIndex.map { case (rawValue, index) => val field = herdPartitionSchema(index) Cast(Literal.create(unescapePathName(rawValue), StringType), field.dataType, Option(TimeZone.getDefault.getID)).eval() } InternalRow.fromSeq(values) } else { InternalRow.empty } val pathSettings = Array( s"namespace=$namespace", s"businessObjectName=$businessObjectName", s"formatUsage=$formatUsage", s"formatFileType=$formatFileType", s"formatVersion=$formatVersion", s"partitionKey=$partitionKey", s"partitionValue=$partitionValue", s"subPartitionValues=${subPartitionValues.mkString(",")}", s"dataVersion=$dataVersion" ) val path = partitionLocation PartitionPath(row, path) } PartitionSpec(herdPartitionSchema, partitions) } @transient protected val cachedAllFiles = mutable.LinkedHashMap[Path, Array[FileStatus]]() override def rootPaths: Seq[Path] = partitionSpec.partitions.map(_.path) /** * List all files for the specified herd paths * * @param paths list of paths * @return The list of files under herd paths */ protected def bulkListLeafFiles(paths: Seq[Path], formatFileType: String): Seq[(Path, Array[FileStatus])] = { val localApiFactory = api val fileStatuses = if (paths.size < sparkSession.sessionState.conf.parallelPartitionDiscoveryThreshold) { listS3KeyPrefixes(localApiFactory(), paths.map(_.toString), storagePathPrefix) .map { case (path, s3KeyPrefixes) => (path, getAllFilesUnderS3KeyPrefixes(hadoopConf, s3KeyPrefixes, formatFileType).toArray) } .map { case (path, statuses) => (path, statuses.map { s => (s.getPath.toString, s.getLen) }) } .toArray } else { val serializableConfiguration = new SerializableConfiguration(hadoopConf) val parallelPartitionDiscoveryParallelism = sparkSession.sessionState.conf.parallelPartitionDiscoveryParallelism val numParallelism = Math.min(paths.size, parallelPartitionDiscoveryParallelism) sparkSession.sparkContext .parallelize(paths.map(_.toString), numParallelism) .mapPartitions { pathStrings => listS3KeyPrefixes(localApiFactory(), pathStrings.toList, storagePathPrefix).iterator } .map { case (path, s3KeyPrefixes) => (path, getAllFilesUnderS3KeyPrefixes(serializableConfiguration.value, s3KeyPrefixes, formatFileType).toArray) } .map { case (path, statuses) => (path, statuses.map { s => (s.getPath.toString, s.getLen) }) } .collect() } fileStatuses.map { case (path, statuses) => val newPath = new Path(path) val newStatuses = statuses.map { case (filePath, size) => new FileStatus(size, false, 0, 0, 0, new Path(filePath)) }.toArray (newPath, newStatuses) } } override def inputFiles: Array[String] = Array.empty override def refresh(): Unit = { cachedAllFiles.clear() } override def sizeInBytes: Long = Long.MaxValue override def partitionSchema: StructType = herdPartitionSchema override def toString: String = { s"HerdFileIndex[" + s"namespace=$namespace," + s"businessObjectName=$businessObjectName," + s"formatUsage=$formatUsage," + s"formatFileType=$formatFileType" + "]" } def filterPartitions(filters: Seq[Expression]): FileIndex } private object HerdFileIndexBase extends Logging with Serializable { def parsePartitionPath(path: String): Map[String, Option[String]] = { path.split("/").map(_.split("=")).map(i => i.head -> i.drop(1).headOption).toMap } def getPathByAddingStoragePrefix(path: String, storagePathPrefix: String): String = { if (StringUtils.isNotEmpty(storagePathPrefix) && !storagePathPrefix.toLowerCase().startsWith("s3a")) { "/" + storagePathPrefix + "/" + path } else { "s3a://" + path } } /** * Find all S3 directories(aka s3 key prefixes) specified by the paths * * @param api The ApiClient instance needed by Herd SDK * @param paths List of herd paths * @return list of s3 key prefixes */ def listS3KeyPrefixes(api: HerdApi, paths: Seq[String], storagePathPrefix: String): Seq[(String, Seq[String])] = { if (paths.isEmpty) { return Seq.empty } paths.map ( path => (path, Seq(getPathByAddingStoragePrefix(path, storagePathPrefix))) ) } /** * List all files under the s3 directories(aka S3 key prefixes) * * @param hadoopConf hadoop configuration * @param s3KeyPrefixes all s3 key prefixes * @return list of files */ private def getAllFilesUnderS3KeyPrefixes(hadoopConf: Configuration, s3KeyPrefixes: Seq[String], formatFileType: String): Seq[FileStatus] = { s3KeyPrefixes.flatMap { s3KeyPrefix => { val s3Path = new Path(s3KeyPrefix) val fs = s3Path.getFileSystem(hadoopConf) var iterator = fs.listFiles(s3Path, true) var fileStatusList = new ArrayBuffer[FileStatus]() // Find all files under each directory while (iterator.hasNext) { val file = iterator.next() // ignore _committed_ file if (!file.getPath.getName.matches("^_committed_.*$")) { fileStatusList += file } } fileStatusList.toList } } } }
apache-2.0
erwelch/jolokia
agent/core/src/main/java/org/jolokia/backend/LocalRequestDispatcher.java
7510
package org.jolokia.backend; /* * Copyright 2009-2013 Roland Huss * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import java.util.UUID; import javax.management.*; import org.jolokia.backend.executor.NotChangedException; import org.jolokia.config.ConfigKey; import org.jolokia.config.Configuration; import org.jolokia.converter.Converters; import org.jolokia.detector.ServerHandle; import org.jolokia.discovery.JolokiaDiscovery; import org.jolokia.discovery.JolokiaDiscoveryMBean; import org.jolokia.handler.JsonRequestHandler; import org.jolokia.handler.RequestHandlerManager; import org.jolokia.history.HistoryStore; import org.jolokia.request.JmxRequest; import org.jolokia.restrictor.Restrictor; import org.jolokia.util.DebugStore; import org.jolokia.util.LogHandler; /** * Dispatcher which dispatches to one or more local {@link javax.management.MBeanServer}. * * @author roland * @since Nov 11, 2009 */ public class LocalRequestDispatcher implements RequestDispatcher { // Agent ID private final String agentId; // Handler for finding and merging the various MBeanHandler private MBeanServerHandler mBeanServerHandler; private RequestHandlerManager requestHandlerManager; // An (optional) qualifier for registering MBeans. private String qualifier; // Logger private LogHandler log; /** * Create a new local dispatcher which accesses local MBeans. * * @param pConverters object/string converters * @param pRestrictor restrictor which checks the access for various operations * @param pConfig agent configuration * @param pLogHandler local handler used for logging out errors and warnings */ public LocalRequestDispatcher(Converters pConverters, Restrictor pRestrictor, Configuration pConfig, LogHandler pLogHandler) { // Get all MBean servers we can find. This is done by a dedicated // handler object mBeanServerHandler = new MBeanServerHandler(pConfig,pLogHandler); qualifier = pConfig.get(ConfigKey.MBEAN_QUALIFIER); log = pLogHandler; agentId = pConfig.get(ConfigKey.AGENT_ID); // Request handling manager requestHandlerManager = new RequestHandlerManager(pConfig,pConverters,mBeanServerHandler.getServerHandle(),pRestrictor); } // Can handle any request /** {@inheritDoc} */ public boolean canHandle(JmxRequest pJmxRequest) { return true; } /** {@inheritDoc} */ public boolean useReturnValueWithPath(JmxRequest pJmxRequest) { JsonRequestHandler handler = requestHandlerManager.getRequestHandler(pJmxRequest.getType()); return handler.useReturnValueWithPath(); } /** {@inheritDoc} */ public Object dispatchRequest(JmxRequest pJmxReq) throws InstanceNotFoundException, AttributeNotFoundException, ReflectionException, MBeanException, NotChangedException { JsonRequestHandler handler = requestHandlerManager.getRequestHandler(pJmxReq.getType()); return mBeanServerHandler.dispatchRequest(handler, pJmxReq); } /** * Initialise this request dispatcher, which will register a {@link ConfigMBean} for easy external * access to the {@link HistoryStore} and {@link DebugStore}. Also a {@link JolokiaDiscoveryMBean} * is registered * * @param pHistoryStore history store to be managed from within an MBean * @param pDebugStore managed debug store * @throws MalformedObjectNameException if our MBean's name is wrong (which cannot happen) * @throws MBeanRegistrationException if registration fails * @throws NotCompliantMBeanException if we have a non compliant MBean (cannot happen, too) */ public void initMBeans(HistoryStore pHistoryStore, DebugStore pDebugStore) throws MalformedObjectNameException, MBeanRegistrationException, NotCompliantMBeanException { // Register the Config MBean String oName = createObjectNameWithQualifier(Config.OBJECT_NAME); try { Config config = new Config(pHistoryStore,pDebugStore,oName); mBeanServerHandler.registerMBean(config,oName); } catch (InstanceAlreadyExistsException exp) { String alternativeOName = oName + ",uuid=" + UUID.randomUUID(); try { // Another instance has already started a Jolokia agent within the JVM. We are trying to add the MBean nevertheless with // a dynamically generated ObjectName. Of course, it would be good to have a more semantic meaning instead of // a random number, but this can already be performed with a qualifier log.info(oName + " is already registered. Adding it with " + alternativeOName + ", but you should revise your setup in " + "order to either use a qualifier or ensure, that only a single agent gets registered (otherwise history functionality might not work)"); Config config = new Config(pHistoryStore,pDebugStore,alternativeOName); mBeanServerHandler.registerMBean(config,alternativeOName); } catch (InstanceAlreadyExistsException e) { log.error("Cannot even register fallback MBean with name " + alternativeOName + ". Should never happen. Really.",e); } } // Register another Config MBean (which dispatched to the stores anyway) for access by // jmx4perl version < 0.80 String legacyOName = createObjectNameWithQualifier(Config.LEGACY_OBJECT_NAME); try { Config legacyConfig = new Config(pHistoryStore,pDebugStore,legacyOName); mBeanServerHandler.registerMBean(legacyConfig,legacyOName); } catch (InstanceAlreadyExistsException exp) { log.info("Cannot register (legacy) MBean handler for config store with name " + legacyOName + " since it already exists. " + "This is the case if another agent has been already started within the same JVM. The registration is skipped."); } try { mBeanServerHandler.registerMBean(new JolokiaDiscovery(agentId,log),JolokiaDiscoveryMBean.OBJECT_NAME); } catch (InstanceAlreadyExistsException e) { // Ignore since there is already one registered. log.info("Jolokia Discovery MBean registration is skipped because there is already one registered."); } } /** * Unregister the config MBean * * @throws JMException if unregistration fails */ public void destroy() throws JMException { mBeanServerHandler.destroy(); } /** * Get information about the current server * @return the server information */ public ServerHandle getServerHandle() { return mBeanServerHandler.getServerHandle(); } private String createObjectNameWithQualifier(String pOName) { return pOName + (qualifier != null ? "," + qualifier : ""); } }
apache-2.0
davidzchen/tensorflow
tensorflow/python/keras/engine/base_layer_test.py
56362
# Copyright 2018 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. # ============================================================================== """Tests for TensorFlow 2.0 layer behavior.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import copy import os import sys import traceback import numpy as np from tensorflow.python.eager import context from tensorflow.python.eager import def_function from tensorflow.python.framework import constant_op from tensorflow.python.framework import dtypes from tensorflow.python.framework import errors_impl from tensorflow.python.framework import ops from tensorflow.python.framework import sparse_tensor from tensorflow.python.framework import tensor_spec from tensorflow.python.keras import backend from tensorflow.python.keras import combinations from tensorflow.python.keras import keras_parameterized from tensorflow.python.keras import layers from tensorflow.python.keras import regularizers from tensorflow.python.keras import testing_utils from tensorflow.python.keras.engine import base_layer from tensorflow.python.keras.engine import input_layer from tensorflow.python.keras.engine import sequential from tensorflow.python.keras.engine import training as training_lib from tensorflow.python.keras.optimizer_v2 import rmsprop from tensorflow.python.keras.utils import control_flow_util from tensorflow.python.layers import core as legacy_core from tensorflow.python.ops import array_ops from tensorflow.python.ops import math_ops from tensorflow.python.ops import state_ops from tensorflow.python.ops import summary_ops_v2 from tensorflow.python.ops import tensor_array_ops from tensorflow.python.ops import variables from tensorflow.python.ops.ragged import ragged_tensor from tensorflow.python.platform import gfile from tensorflow.python.platform import test from tensorflow.python.summary import summary_iterator from tensorflow.python.util import nest class DynamicLayer(base_layer.Layer): def __init__(self, dynamic=False, **kwargs): super(DynamicLayer, self).__init__(dynamic=dynamic, **kwargs) def call(self, inputs): samples = tensor_array_ops.TensorArray( dtype=dtypes.float32, size=array_ops.shape(inputs)[0]) for idx, sample in enumerate(inputs): samples = samples.write(idx, math_ops.square(sample)) return samples.stack() def compute_output_shape(self, input_shape): return input_shape class InvalidLayer(base_layer.Layer): def call(self, inputs): raise ValueError('You did something wrong!') class BaseLayerTest(keras_parameterized.TestCase): @combinations.generate(combinations.times( combinations.keras_model_type_combinations(), combinations.keras_tensor_combinations())) def test_dynamic_layer(self): model = testing_utils.get_model_from_layers([DynamicLayer(dynamic=True)], input_shape=(3,)) self.assertEqual(model.dynamic, True) model.compile(rmsprop.RMSprop(0.001), loss='mse') self.assertEqual(model.run_eagerly, True) model.train_on_batch(np.random.random((2, 3)), np.random.random((2, 3))) @combinations.generate(combinations.times( combinations.keras_model_type_combinations(), combinations.keras_tensor_combinations())) def test_dynamic_layer_error(self): # Functional Models hit the `dyanamic=True` error during construction. # Subclass Models should just throw the original autograph error during # execution. raised_error = False try: model = testing_utils.get_model_from_layers([DynamicLayer()], input_shape=(3,)) model.compile(rmsprop.RMSprop(0.001), loss='mse') model.train_on_batch(np.random.random((2, 3)), np.random.random((2, 3))) except errors_impl.OperatorNotAllowedInGraphError as e: if 'iterating over `tf.Tensor` is not allowed' in str(e): raised_error = True except TypeError as e: if 'attempting to use Python control flow' in str(e): raised_error = True self.assertTrue(raised_error) @combinations.generate(combinations.times( combinations.keras_model_type_combinations(), combinations.keras_tensor_combinations())) def test_dynamic_layer_error_running_in_graph_mode(self): with ops.get_default_graph().as_default(): model = testing_utils.get_model_from_layers([DynamicLayer(dynamic=True)], input_shape=(3,)) self.assertEqual(model.dynamic, True) # But then you cannot run the model since you're in a graph scope. with self.assertRaisesRegex(ValueError, 'You must enable eager execution'): model.compile(rmsprop.RMSprop(0.001), loss='mse') def test_manual_compute_output_shape(self): class BuildCounter(base_layer.Layer): def __init__(self, *args, **kwargs): # pylint: disable=redefined-outer-name super(BuildCounter, self).__init__(*args, **kwargs) self.build_counter = 0 def build(self, input_shape): self.build_counter += 1 self.build_shape = input_shape def call(self, inputs): return inputs layer = BuildCounter(dtype=dtypes.float64) output_shape = layer.compute_output_shape((None, 10)) self.assertEqual(layer.build_counter, 1) self.assertEqual(layer.build_shape.as_list(), [None, 10]) self.assertEqual(output_shape.as_list(), [None, 10]) output_signature = layer.compute_output_signature( tensor_spec.TensorSpec(dtype=dtypes.float64, shape=[None, 10])) self.assertEqual(layer.build_counter, 1) self.assertEqual(layer.build_shape.as_list(), [None, 10]) self.assertEqual(output_signature.dtype, dtypes.float64) self.assertEqual(output_signature.shape.as_list(), [None, 10]) layer(np.ones((5, 10))) self.assertEqual(layer.build_counter, 1) self.assertEqual(layer.build_shape.as_list(), [None, 10]) def test_dynamic_layer_with_deferred_sequential_model(self): model = sequential.Sequential([DynamicLayer(dynamic=True), layers.Dense(3)]) self.assertEqual(model.dynamic, True) model.compile(rmsprop.RMSprop(0.001), loss='mse') self.assertEqual(model.run_eagerly, True) model.train_on_batch(np.random.random((2, 3)), np.random.random((2, 3))) def test_nested_dynamic_layers_in_eager_mode(self): inputs = input_layer.Input((3,)) outputs = DynamicLayer(dynamic=True)(inputs) inner_model = training_lib.Model(inputs, outputs) self.assertEqual(inner_model.dynamic, True) inputs = input_layer.Input((3,)) x = DynamicLayer(dynamic=True)(inputs) outputs = inner_model(x) model = training_lib.Model(inputs, outputs) self.assertEqual(model.dynamic, True) model.compile(rmsprop.RMSprop(0.001), loss='mse') self.assertEqual(model.run_eagerly, True) model.train_on_batch(np.random.random((2, 3)), np.random.random((2, 3))) def test_dynamic_subclassed_model_no_shape_inference(self): class MyModel(training_lib.Model): def __init__(self): super(MyModel, self).__init__(dynamic=True) self.layer1 = layers.Dense(3) self.layer2 = layers.Dense(3) def call(self, inputs): if math_ops.reduce_sum(inputs) > 0: return self.layer1(inputs) else: return self.layer2(inputs) model = MyModel() self.assertEqual(model.dynamic, True) model.compile(rmsprop.RMSprop(0.001), loss='mse') self.assertEqual(model.run_eagerly, True) model.train_on_batch(np.random.random((2, 3)), np.random.random((2, 3))) self.assertEqual(model.outputs, None) def test_dynamic_subclassed_model_with_shape_inference(self): class MyModel(training_lib.Model): def __init__(self): super(MyModel, self).__init__(dynamic=True) self.layer1 = layers.Dense(3) self.layer2 = layers.Dense(3) def call(self, inputs): if math_ops.reduce_sum(inputs) > 0: return self.layer1(inputs) else: return self.layer2(inputs) def compute_output_shape(self, input_shape): return tuple(input_shape[:-1].as_list()) + (3,) model = MyModel() self.assertEqual(model.dynamic, True) model.compile(rmsprop.RMSprop(0.001), loss='mse') x, y = np.random.random((2, 3)), np.random.random((2, 3)) model.train_on_batch(x, y) outputs = model(x) self.assertEqual(outputs.shape.as_list(), [2, 3]) def test_deepcopy(self): bias_reg = lambda x: 1e-3 * math_ops.reduce_sum(x) layer = layers.Conv2D(32, (3, 3), bias_regularizer=bias_reg) # Call the Layer on data to generate regularize losses. layer(array_ops.ones((1, 10, 10, 3))) self.assertLen(layer.losses, 1) new_layer = copy.deepcopy(layer) self.assertEqual(new_layer.bias_regularizer, bias_reg) self.assertEqual(layer.get_config(), new_layer.get_config()) @combinations.generate(combinations.combine(mode=['graph', 'eager'])) def test_invalid_forward_pass(self): inputs = input_layer.Input((3,)) with self.assertRaisesRegex(ValueError, 'You did something wrong!'): _ = InvalidLayer()(inputs) def test_no_legacy_model(self): inputs = input_layer.Input((1,)) legacy_dense_0 = legacy_core.Dense(1, name='legacy_dense_0') legacy_dense_1 = legacy_core.Dense(1, name='legacy_dense_1') layer = legacy_dense_0(inputs) layer = layers.Dense(1)(layer) layer = legacy_dense_1(layer) expected_regex = (r'The following are legacy tf\.layers\.Layers:\n ' '{}\n {}'.format(legacy_dense_0, legacy_dense_1)) with self.assertRaisesRegex(TypeError, expected_regex): _ = training_lib.Model(inputs=[inputs], outputs=[layer]) model = training_lib.Model(inputs=[inputs], outputs=[inputs]) with self.assertRaisesRegex(TypeError, expected_regex): model._insert_layers([legacy_dense_0, legacy_dense_1]) def test_no_legacy_sequential(self): layer = [layers.Dense(1), legacy_core.Dense(1, name='legacy_dense_0')] expected_regex = r'legacy tf\.layers\.Layers:\n {}'.format(layer[1]) with self.assertRaisesRegex(TypeError, expected_regex): _ = sequential.Sequential(layer) with self.assertRaisesRegex(TypeError, expected_regex): _ = sequential.Sequential([input_layer.Input(shape=(4,))] + layer) model = sequential.Sequential() with self.assertRaisesRegex(TypeError, expected_regex): for l in layer: model.add(l) @combinations.generate( combinations.times( combinations.keras_model_type_combinations(), combinations.keras_tensor_combinations(), combinations.combine(mode=['graph', 'eager']))) def test_build_with_numpy_data(self): model_layers = [ layers.Dense(3, activation='relu', kernel_initializer='ones'), layers.Dense(1, activation='sigmoid', kernel_initializer='ones') ] model = testing_utils.get_model_from_layers(model_layers, input_shape=(4,)) model(np.zeros((2, 4), dtype='float32')) self.assertTrue(model.built) @combinations.generate(combinations.combine(mode=['graph', 'eager'])) def test_default_add_weight(self): class TestLayer(base_layer.Layer): def __init__(self): super(TestLayer, self).__init__() self.default_weight = self.add_weight() self.weight_without_name = self.add_weight(shape=(3, 4)) self.regularized_weight_without_name = self.add_weight( shape=(3, 4), regularizer='l2') layer = TestLayer() self.assertEqual(layer.default_weight.shape.as_list(), []) self.assertEqual(layer.weight_without_name.shape.as_list(), [3, 4]) self.assertEqual(layer.default_weight.dtype.name, 'float32') self.assertEqual(layer.weight_without_name.dtype.name, 'float32') self.assertEqual(len(layer.losses), 1) if not context.executing_eagerly(): # Cannot access tensor.name in eager execution. self.assertIn('Variable_2/Regularizer', layer.losses[0].name) @combinations.generate(combinations.keras_mode_combinations(mode=['eager'])) def test_learning_phase_freezing_for_layers(self): class LearningPhaseLayer(base_layer.Layer): def call(self, inputs): return backend.in_train_phase(lambda: array_ops.ones_like(inputs), lambda: array_ops.zeros_like(inputs)) def get_learning_phase_value(): model = sequential.Sequential([LearningPhaseLayer(input_shape=(1,))]) model._run_eagerly = testing_utils.should_run_eagerly() return np.sum(model(np.ones((1, 1)))) self.assertEqual(get_learning_phase_value(), 0) # Test scope. with backend.learning_phase_scope(1): self.assertEqual(get_learning_phase_value(), 1) # The effects of the scope end after exiting it. self.assertEqual(get_learning_phase_value(), 0) # Test setting. backend.set_learning_phase(1) self.assertEqual(get_learning_phase_value(), 1) backend.set_learning_phase(0) self.assertEqual(get_learning_phase_value(), 0) # Cannot be enabled with `run_eagerly=True`, see b/123904578 @combinations.generate(combinations.combine(mode=['graph', 'eager'])) def test_layer_can_return_variable(self): class ComputeSum(base_layer.Layer): def __init__(self): super(ComputeSum, self).__init__() self.total = variables.Variable( initial_value=array_ops.zeros((1, 1)), trainable=False) if not context.executing_eagerly(): backend.get_session().run(self.total.initializer) def call(self, inputs): self.total.assign_add(inputs) return self.total inputs = input_layer.Input(shape=(1,)) model = training_lib.Model(inputs, ComputeSum()(inputs)) model.predict(np.ones((1, 1))) def _get_layer_with_training_arg(self): class TrainingLayer(base_layer.Layer): """A layer with a `training` argument in a defuned `call`.""" @def_function.function def call(self, inputs, training=None): if training is None: training = backend.learning_phase() return control_flow_util.smart_cond( training, lambda: array_ops.ones_like(inputs), lambda: array_ops.zeros_like(inputs)) return TrainingLayer() # b/124459427: can't test with `run_eagerly=True` for now. @combinations.generate( combinations.times(combinations.keras_mode_combinations(), combinations.keras_model_type_combinations(), combinations.keras_tensor_combinations())) def test_training_arg_in_defun(self): layer = self._get_layer_with_training_arg() model = testing_utils.get_model_from_layers([layer], input_shape=(1,)) model.compile(rmsprop.RMSprop(0.), loss='mae') history = model.fit(np.zeros((1, 1)), np.zeros((1, 1))) self.assertEqual(history.history['loss'][0], 1.) loss = model.evaluate(np.zeros((1, 1)), np.zeros((1, 1))) self.assertEqual(loss, 0.) # Test that the argument injection performed in `call` is not active # when the argument is passed explicitly. layer = self._get_layer_with_training_arg() inputs = input_layer.Input(shape=(1,)) # Pass `training` by name outputs = layer(inputs, training=False) model = training_lib.Model(inputs, outputs) model.compile(rmsprop.RMSprop(0.), loss='mae') history = model.fit(np.zeros((1, 1)), np.zeros((1, 1))) self.assertEqual(history.history['loss'][0], 0.) @combinations.generate( combinations.times(combinations.keras_mode_combinations(), combinations.keras_model_type_combinations(), combinations.keras_tensor_combinations())) def test_raw_variable_assignment(self): class RawVariableLayer(base_layer.Layer): def __init__(self, **kwargs): super(RawVariableLayer, self).__init__(**kwargs) # Test variables in nested structure. self.var_list = [variables.Variable(1.), {'a': variables.Variable(2.)}] def call(self, inputs): return inputs * self.var_list[0] * self.var_list[1]['a'] model = testing_utils.get_model_from_layers([RawVariableLayer()], input_shape=(10,)) model.compile( 'sgd', 'mse', run_eagerly=testing_utils.should_run_eagerly()) x, y = np.ones((10, 10)), np.ones((10, 10)) # Checks that variables get initialized. model.fit(x, y, batch_size=2, epochs=2) @combinations.generate(combinations.combine(mode=['graph', 'eager'])) def test_layer_names(self): with testing_utils.use_keras_tensors_scope(False): inputs = input_layer.Input(shape=[2]) add1 = inputs + inputs add2 = layers.Add()([inputs, inputs]) add3 = inputs + inputs add4 = layers.Add()([inputs, inputs]) model = training_lib.Model( inputs=[inputs], outputs=[add1, add2, add3, add4]) actual_names = [l.name for l in model.layers] graph_names = [ 'input_1', 'tf_op_layer_AddV2', 'add', 'tf_op_layer_AddV2_1', 'add_1' ] eager_names = [ 'input_1', 'tf_op_layer_add', 'add', 'tf_op_layer_add_2', 'add_1' ] for actual, eager, graph in zip(actual_names, graph_names, eager_names): self.assertIn(actual, {eager, graph}) if context.executing_eagerly(): backend.clear_session() with testing_utils.use_keras_tensors_scope(True): inputs = input_layer.Input(shape=[2]) add1 = inputs + inputs add2 = layers.Add()([inputs, inputs]) add3 = inputs + inputs add4 = layers.Add()([inputs, inputs]) model = training_lib.Model( inputs=[inputs], outputs=[add1, add2, add3, add4]) actual_names = [l.name for l in model.layers] expected_names = [ 'input_1', 'tf.__operators__.add', 'add', 'tf.__operators__.add_1', 'add_1' ] self.assertAllEqual(actual_names, expected_names) def test_add_trainable_weight_on_frozen_layer(self): class TestLayer(base_layer.Layer): def build(self, input_shape): self.w = self.add_weight(shape=(), trainable=True) def call(self, inputs): return self.w * inputs layer = TestLayer() layer.trainable = False layer.build(None) layer.trainable = True self.assertListEqual(layer.trainable_weights, [layer.w]) @combinations.generate( combinations.times(combinations.keras_mode_combinations(), combinations.keras_model_type_combinations())) def test_passing_initial_weights_values(self): kernel_value = np.random.random((10, 2)) layer_with_weights = layers.Dense(2, use_bias=False, weights=[kernel_value]) model = testing_utils.get_model_from_layers([layer_with_weights], input_shape=(10,)) model.compile( 'sgd', 'mse', run_eagerly=testing_utils.should_run_eagerly()) inputs = np.random.random((3, 10)) out = model.predict(inputs) self.assertAllClose(model.layers[-1].get_weights()[0], kernel_value) self.assertAllClose(out, np.dot(inputs, kernel_value)) @combinations.generate(combinations.combine(mode=['graph', 'eager'])) def test_set_weights_and_get_weights(self): layer = layers.Dense(2) layer.build((None, 10)) kernel = np.random.random((10, 2)) bias = np.random.random((2,)) layer.set_weights([kernel, bias]) weights = layer.get_weights() self.assertEqual(len(weights), 2) self.assertAllClose(weights[0], kernel) self.assertAllClose(weights[1], bias) with self.assertRaisesRegex(ValueError, 'but the layer was expecting 2 weights'): layer.set_weights([1, 2, 3]) with self.assertRaisesRegex(ValueError, 'not compatible with provided weight shape'): layer.set_weights([kernel.T, bias]) def test_get_config_error(self): class MyLayer(base_layer.Layer): def __init__(self, my_kwarg='default', **kwargs): super(MyLayer, self).__init__(**kwargs) self.my_kwarg = my_kwarg # `__init__` includes kwargs but `get_config` is not overridden, so # an error should be thrown: with self.assertRaisesRegex(NotImplementedError, 'Layer MyLayer has'): MyLayer('custom').get_config() class MyLayerNew(base_layer.Layer): def __init__(self, my_kwarg='default', **kwargs): super(MyLayerNew, self).__init__(**kwargs) self.my_kwarg = my_kwarg def get_config(self): config = super(MyLayerNew, self).get_config() config['my_kwarg'] = self.my_kwarg return config # Test to make sure that error is not raised if the method call is # from an overridden `get_config`: self.assertEqual(MyLayerNew('custom').get_config()['my_kwarg'], 'custom') class MyLayerNew2(base_layer.Layer): def __init__(self, name='MyLayerName', dtype=None, **kwargs): # pylint:disable=redefined-outer-name super(MyLayerNew2, self).__init__(name=name, dtype=dtype, **kwargs) # Check that if the kwargs in `__init__` are base layer constructor # arguments, no error is thrown: self.assertEqual(MyLayerNew2(name='New').get_config()['name'], 'New') @combinations.generate(combinations.combine(mode=['graph', 'eager'])) def test_count_params(self): dense = layers.Dense(16) dense.build((None, 4)) self.assertEqual(dense.count_params(), 16 * 4 + 16) dense = layers.Dense(16) with self.assertRaisesRegex(ValueError, 'call `count_params`'): dense.count_params() model = sequential.Sequential(layers.Dense(16)) with self.assertRaisesRegex(ValueError, 'call `count_params`'): model.count_params() dense = layers.Dense(16, input_dim=4) model = sequential.Sequential(dense) self.assertEqual(model.count_params(), 16 * 4 + 16) def test_super_not_called(self): class CustomLayerNotCallingSuper(base_layer.Layer): def __init__(self): pass layer = CustomLayerNotCallingSuper() with self.assertRaisesRegex(RuntimeError, 'You must call `super()'): layer(np.random.random((10, 2))) @combinations.generate(combinations.combine(mode=['graph', 'eager'])) def test_first_arg_not_called_inputs(self): x, y = array_ops.ones((10, 1)), array_ops.ones((10, 1)) class ArgLayer(base_layer.Layer): def call(self, x, y): return x + y layer = ArgLayer() out = self.evaluate(layer(x=x, y=y)) self.assertAllClose(out, 2 * np.ones((10, 1))) class KwargLayer(base_layer.Layer): def call(self, x=None, y=None): return x + y layer = KwargLayer() out = self.evaluate(layer(x=x, y=y)) self.assertAllClose(out, 2 * np.ones((10, 1))) with self.assertRaisesRegex(ValueError, 'must always be passed'): layer(y=y) class TFFunctionLayer(base_layer.Layer): @def_function.function def call(self, x, y=None): if y is None: return x return x + y layer = TFFunctionLayer() out = self.evaluate(layer(x=x, y=y)) self.assertAllClose(out, 2 * np.ones((10, 1))) def test_build_input_shape(self): class CustomLayer(base_layer.Layer): def build(self, input_shape): self.add_weight('w', shape=input_shape[1:]) super(CustomLayer, self).build(input_shape) layer = CustomLayer() self.assertFalse(layer.built) layer.build([None, 1, 2, 3]) self.assertTrue(layer.built) self.assertEqual([None, 1, 2, 3], layer._build_input_shape) layer = CustomLayer() layer(input_layer.Input((3,))) self.assertTrue(layer.built) self.assertEqual([None, 3], layer._build_input_shape.as_list()) @combinations.generate(combinations.combine(mode=['eager'])) def custom_layer_training_arg(self): class CustomLayerNoTrainingArg(base_layer.Layer): def __init__(self, nested_layer=None): self._nested_layer = nested_layer or array_ops.identity def call(self, inputs): return self._nested_layer(inputs) class CustomLayerDefaultTrainingMissing(base_layer.Layer): def __init__(self, nested_layer=None): self._nested_layer = nested_layer or array_ops.identity def call(self, inputs, training): if training: return self._nested_layer(inputs) else: return self._nested_layer(inputs) * 0.5 class CustomLayerDefaultTrainingNone(base_layer.Layer): def __init__(self, nested_layer=None): self._nested_layer = nested_layer or array_ops.identity def call(self, inputs, training=None): if training: return self._nested_layer(inputs) else: return self._nested_layer(inputs) * 0.5 class CustomLayerDefaultTrainingFalse(base_layer.Layer): def __init__(self, nested_layer=None): self._nested_layer = nested_layer or array_ops.identity def call(self, inputs, training=False): if training: return self._nested_layer(inputs) else: return self._nested_layer(inputs) * 0.5 class CustomLayerDefaultTrainingTrue(base_layer.Layer): def __init__(self, nested_layer=None): self._nested_layer = nested_layer or array_ops.identity def call(self, inputs, training=True): if training: return self._nested_layer(inputs) else: return self._nested_layer(inputs) * 0.5 x = array_ops.ones(shape=(1, 1)) # If the layer signature doesn't specify a default training arg, # run it in inference mode when to training arg is passed # to __call__ layer = CustomLayerDefaultTrainingMissing() self.assertAllEqual(layer(x), x * 0.5) self.assertAllEqual(layer(x, training=False), x * 0.5) self.assertAllEqual(layer(x, training=True), x) # If the layer signature specifies `False` as the default training arg, # run it in inference mode when no training arg is passed # to __call__ layer = CustomLayerDefaultTrainingFalse() self.assertAllEqual(layer(x), x * 0.5) self.assertAllEqual(layer(x, training=False), x * 0.5) self.assertAllEqual(layer(x, training=True), x) # If the layer signature specifies `True` as the default training arg, # explicitly run it in training mode when no training arg is passed # to __call__ layer = CustomLayerDefaultTrainingTrue() self.assertAllEqual(layer(x), x) self.assertAllEqual(layer(x, training=False), x * 0.5) self.assertAllEqual(layer(x, training=True), x) # Outer layers/models should set the training context implicitly for all # nested layers, respecting whatever mode the outer layer was run with. layer = CustomLayerDefaultTrainingTrue(CustomLayerDefaultTrainingFalse()) # No outer value passed: use local defaults self.assertAllEqual(layer(x), x * 0.25) # Use local default False # Outer value passed: override local defaults self.assertAllEqual(layer(x, training=False), x * 0.25) self.assertAllEqual(layer(x, training=True), x) layer = CustomLayerDefaultTrainingFalse(CustomLayerDefaultTrainingTrue()) # No outer value passed: use local defaults self.assertAllEqual(layer(x), x) # Use local default True # Outer value passed: override local defaults self.assertAllEqual(layer(x, training=False), x * 0.25) self.assertAllEqual(layer(x, training=True), x) # If the outer layer `call` doesn't take a training argument at all, # it'll set the nested scope as None when no training arg is passed in. # If a training arg is passed in it won't use it directly in `call`, but # it will set the nested training mode. layer = CustomLayerNoTrainingArg(CustomLayerDefaultTrainingTrue()) self.assertAllEqual(layer(x), x) # Use local default True self.assertAllEqual(layer(x, training=False), x * 0.5) self.assertAllEqual(layer(x, training=True), x) layer = CustomLayerDefaultTrainingNone(CustomLayerDefaultTrainingTrue()) self.assertAllEqual(layer(x), x) # Use local default True self.assertAllEqual(layer(x, training=False), x * 0.5) self.assertAllEqual(layer(x, training=True), x) def test_activity_regularizer_string(self): class MyLayer(base_layer.Layer): pass layer = MyLayer(activity_regularizer='l2') self.assertIsInstance(layer.activity_regularizer, regularizers.L2) class SymbolicSupportTest(keras_parameterized.TestCase): def test_using_symbolic_tensors_with_tf_ops(self): # Single-input. x = input_layer.Input((3,)) math_ops.square(x) # Multi-inputs. x1, x2 = input_layer.Input((3,)), input_layer.Input((3,)) array_ops.concat([x1, x2], axis=1) # Mixing Keras symbolic tensors and graph tensors from the same graph works. with backend.get_graph().as_default(): x1 = input_layer.Input((3,)) x2 = input_layer.Input((3,)) math_ops.matmul(x1, x2) # Creating same op type (matmul) multiple times in the Keras graph works. x1 = input_layer.Input((3,)) x2 = input_layer.Input((3,)) math_ops.matmul(x1, x2) def test_mixing_eager_and_graph_tensors(self): with ops.Graph().as_default(): x1 = array_ops.ones((3, 3)) x2 = array_ops.ones((3, 3)) self.assertIsInstance(x2, ops.EagerTensor) with self.assertRaisesRegex(TypeError, 'Graph tensors'): math_ops.matmul(x1, x2) def test_mixing_numpy_arrays_and_graph_tensors(self): with ops.Graph().as_default(): x1 = array_ops.ones((3, 3)) x2 = np.ones((3, 3), dtype='float32') with self.assertRaisesRegex(TypeError, 'Graph tensors'): math_ops.matmul(x1, x2) @combinations.generate(combinations.combine(mode=['graph', 'eager'])) def test_mixing_keras_symbolic_tensors_and_eager_tensors(self): x1 = input_layer.Input((3,)) x2 = array_ops.ones((3, 3)) y = math_ops.matmul(x1, x2) fn = backend.function(inputs=[x1], outputs=[y]) x_val = np.random.random((3, 3)) y_val = np.ones((3, 3)) self.assertAllClose(fn([x_val])[0], np.matmul(x_val, y_val), atol=1e-5) @combinations.generate(combinations.combine(mode=['graph', 'eager'])) def test_mixing_keras_symbolic_tensors_and_numpy_arrays(self): x1 = input_layer.Input((3,)) x2 = np.ones((3, 3), dtype='float32') y = math_ops.matmul(x1, x2) fn = backend.function(inputs=[x1], outputs=[y]) x_val = np.random.random((3, 3)) y_val = np.ones((3, 3)) self.assertAllClose(fn([x_val])[0], np.matmul(x_val, y_val), atol=1e-5) @combinations.generate(combinations.combine(mode=['graph', 'eager'])) def test_reraising_exception(self): # When layer is not dynamic, we have some pattern matching during exception # handling to detect when the user is trying to use python control flow. # When an exception is thrown but the pattern doesn't match, we want to # preserve the originating stack trace. An early implementation of this # logic lost the stack trace. We test the correct behavior here. class TypeErrorLayer(base_layer.Layer): def call(self, inputs): def easily_identifiable_name(): raise TypeError('Non-matching TypeError message.') easily_identifiable_name() inputs = input_layer.Input((3,)) try: _ = TypeErrorLayer()(inputs) except TypeError as e: if hasattr(e, 'ag_error_metadata'): self.assertIn('easily_identifiable_name', str(e)) # See ErrorMetadataBase in autograph/pyct/errors.py function_name = e.ag_error_metadata.translated_stack[-1].function_name else: tb = traceback.extract_tb(sys.exc_info()[2]) last_entry = tb[-1] function_name = last_entry[2] self.assertEqual(function_name, 'easily_identifiable_name') @combinations.generate(combinations.combine(mode=['graph', 'eager'])) def test_summaries_in_tf_function(self): if not context.executing_eagerly(): return class MyLayer(base_layer.Layer): def call(self, inputs): summary_ops_v2.scalar('mean', math_ops.reduce_mean(inputs)) return inputs tmp_dir = self.get_temp_dir() writer = summary_ops_v2.create_file_writer_v2(tmp_dir) with writer.as_default(), summary_ops_v2.always_record_summaries(): my_layer = MyLayer() x = array_ops.ones((10, 10)) def my_fn(x): return my_layer(x) _ = my_fn(x) event_file = gfile.Glob(os.path.join(tmp_dir, 'events*')) self.assertLen(event_file, 1) event_file = event_file[0] tags = set() for e in summary_iterator.summary_iterator(event_file): for val in e.summary.value: tags.add(val.tag) self.assertEqual(set(['my_layer/mean']), tags) @combinations.generate(combinations.combine(mode=['graph', 'eager'])) def test_error_when_passing_non_tensor(self): # layers that have an `input_spec` will raise an error when called on # non-tensors. This covers all built-in layers. layer = layers.Dense(3) x = object() with self.assertRaisesRegex(TypeError, r'should be tensors'): layer(x) @combinations.generate(combinations.combine(mode=['graph', 'eager'])) class NestedTrackingTest(test.TestCase): def test_nested_layer_variable_tracking(self): # Test that variables from nested sublayers are # being tracked by subclassed layers. class MyLayer(base_layer.Layer): def __init__(self): super(MyLayer, self).__init__() self.dense1 = layers.Dense(1) self.dense2 = layers.BatchNormalization() def build(self, input_shape): self.v1 = self.add_weight('v1', shape=input_shape[1:].as_list()) self.v2 = variables.Variable( name='v2', initial_value=np.zeros(input_shape[1:].as_list(), dtype='float32'), trainable=False) def call(self, inputs): x = self.dense1(inputs) + self.dense2(inputs) return x + self.v1 + self.v2 layer = MyLayer() inputs = input_layer.Input((1,)) _ = layer(inputs) self.assertEqual(len(layer.weights), 8) self.assertEqual(len(layer.trainable_weights), 5) self.assertEqual(len(layer.non_trainable_weights), 3) layer.dense1.trainable = False self.assertEqual(len(layer.weights), 8) self.assertEqual(len(layer.trainable_weights), 3) self.assertEqual(len(layer.non_trainable_weights), 5) layer.trainable = False self.assertEqual(len(layer.weights), 8) self.assertEqual(len(layer.trainable_weights), 0) self.assertEqual(len(layer.non_trainable_weights), 8) self.assertEqual( {id(v) for v in [layer.dense1, layer.dense2, layer.v1, layer.v2]}, {id(v) for _, v in layer._checkpoint_dependencies}) def test_nested_layer_updates_losses_tracking(self): # Test that updates and losses from nested sublayers are # being tracked by subclassed layers. class UpdateAndLossLayer(base_layer.Layer): def build(self, _): self.v1 = self.add_weight('v1', shape=()) def call(self, inputs): self.add_loss(math_ops.reduce_sum(inputs)) self.add_update(state_ops.assign_add(self.v1, 1)) return inputs + 1 class MyLayer(base_layer.Layer): def build(self, _): self.v1 = self.add_weight('v1', shape=()) def __init__(self): super(MyLayer, self).__init__() self.ul1 = UpdateAndLossLayer() self.ul2 = UpdateAndLossLayer() def call(self, inputs): self.add_loss(math_ops.reduce_sum(inputs)) self.add_update(state_ops.assign_add(self.v1, 1)) x = self.ul1(inputs) return self.ul2(x) layer = MyLayer() if context.executing_eagerly(): inputs = array_ops.ones((3, 1)) _ = layer(inputs) self.assertEqual(len(layer.losses), 3) self.assertLen(layer.get_losses_for(None), 3) else: inputs = input_layer.Input((1,)) _ = layer(inputs) self.assertEqual(len(layer.losses), 3) self.assertEqual(len(layer.updates), 3) self.assertLen(layer.get_losses_for(None), 3) def test_attribute_reassignment(self): l = base_layer.Layer() l.a = base_layer.Layer() l.a = [] l.a = variables.Variable(1.) l.a = base_layer.Layer() last_assignment = base_layer.Layer() l.a = last_assignment l.b = variables.Variable(1.) del l.b l.c = base_layer.Layer() del l.c l.d = last_assignment del l.d self.assertEqual([last_assignment], l._layers) self.assertEqual([], l.trainable_weights) self.assertEqual([], l.non_trainable_weights) self.assertEqual([], l.weights) del l.a self.assertEqual([], l._layers) def test_assign_op_not_tracked_as_variable(self): class LayerWithAssignAttr(base_layer.Layer): def build(self, input_shape): self.v = variables.Variable(1.) self.v_assign = self.v.assign_add(2.) layer = LayerWithAssignAttr() layer.build((10, 10)) self.assertEqual([layer.v], layer.variables) def test_layer_class_not_tracked_as_sublayer(self): # See https://github.com/tensorflow/tensorflow/issues/27431 for details. class LayerWithClassAttribute(base_layer.Layer): def __init__(self): super(LayerWithClassAttribute, self).__init__() self.layer_fn = layers.Dense layer = LayerWithClassAttribute() self.assertEmpty(layer.variables) self.assertEmpty(layer.submodules) def test_layer_call_fn_args(self): class NonDefunLayer(base_layer.Layer): def call(self, inputs, a, mask, b=None, training=None): return inputs class DefunLayer(base_layer.Layer): @def_function.function def call(self, x, mask, a, training=None, b=None): return x nondefun_layer = NonDefunLayer() self.assertEqual(nondefun_layer._call_fn_args, ['inputs', 'a', 'mask', 'b', 'training']) defun_layer = DefunLayer() self.assertEqual(defun_layer._call_fn_args, ['x', 'mask', 'a', 'training', 'b']) def test_sequential_model(self): model = sequential.Sequential( [layers.Dense(10, input_shape=(10,)), layers.Dense(5)]) self.assertLen(model.layers, 2) self.assertLen(model.weights, 4) # Make sure a subclass model also works when it is called 'Sequential'. class Sequential(training_lib.Model): def __init__(self): super(Sequential, self).__init__() self.dense_layers = [layers.Dense(10), layers.Dense(5)] def call(self, inputs): x = inputs for d in self.dense_layers: x = d(x) return x s = Sequential() self.assertLen(s.layers, 2) self.assertLen(s.weights, 0) s(input_layer.Input((10,))) self.assertLen(s.weights, 4) @combinations.generate(combinations.combine(mode=['graph', 'eager'])) class NameScopingTest(keras_parameterized.TestCase): def test_name_scope_layer(self): x = backend.placeholder(shape=(10, 10)) layer = layers.Dense(10, name='MyName') layer(x) self.assertEqual(layer.bias.name, 'MyName/bias:0') self.assertEqual(layer.kernel.name, 'MyName/kernel:0') def test_name_scope_functional_api(self): inputs = input_layer.Input((3,)) layer = layers.Dense(10, name='MyName') _ = layer(inputs) self.assertEqual(layer.bias.name, 'MyName/bias:0') self.assertEqual(layer.kernel.name, 'MyName/kernel:0') def test_name_scope_functional_api_nested(self): class NestedLayer(base_layer.Layer): def __init__(self, name='OuterName'): super(NestedLayer, self).__init__(name=name) self.dense = layers.Dense(10, name='InnerName') def call(self, inputs): return self.dense(inputs) inputs = input_layer.Input((3,)) layer = NestedLayer() _ = layer(inputs) self.assertEqual(layer.dense.bias.name, 'OuterName/InnerName/bias:0') self.assertEqual(layer.dense.kernel.name, 'OuterName/InnerName/kernel:0') def test_name_scope_sublayer(self): class NameScopeTracker(base_layer.Layer): def call(self, inputs): self.active_name_scope = ops.get_name_scope() return inputs x = backend.placeholder(shape=(10, 10)) sublayer = NameScopeTracker(name='Sublayer') layer = layers.Dense(10, activation=sublayer, name='MyName2') layer(x) self.assertEqual(layer.bias.name, 'MyName2/bias:0') self.assertEqual(layer.kernel.name, 'MyName2/kernel:0') self.assertEqual(sublayer.active_name_scope, 'MyName2/Sublayer') def test_name_scope_tf_tensor(self): x = ops.convert_to_tensor_v2_with_dispatch(np.ones((10, 10))) layer = layers.Dense( 10, activation=layers.ReLU(name='MyAct'), name='MyName3') layer(x) self.assertEqual(layer.bias.name, 'MyName3/bias:0') self.assertEqual(layer.kernel.name, 'MyName3/kernel:0') @combinations.generate(combinations.keras_mode_combinations(mode=['eager'])) class AutographControlFlowTest(keras_parameterized.TestCase): def test_disabling_in_context_is_matched(self): test_obj = self class MyLayer(base_layer.Layer): def call(self, inputs, training=None): with test_obj.assertRaisesRegex(TypeError, 'Tensor.*as.*bool'): if constant_op.constant(False): return inputs * 1. return inputs * 0. @def_function.function(autograph=False) def test_fn(): return MyLayer()(constant_op.constant([[1., 2., 3.]])) test_fn() def test_if_training_pattern_output(self): class MyLayer(base_layer.Layer): def call(self, inputs, training=None): if training: return inputs * 1. return inputs * 0. inputs = input_layer.Input((3,)) outputs = MyLayer()(inputs) model = training_lib.Model(inputs, outputs) model.compile( 'sgd', 'mse', run_eagerly=testing_utils.should_run_eagerly()) train_loss = model.train_on_batch(np.ones((2, 3)), np.ones((2, 3))) self.assertEqual(train_loss, 0.) test_loss = model.test_on_batch(np.ones((2, 3)), np.ones((2, 3))) self.assertEqual(test_loss, 1.) def test_if_training_pattern_loss(self): class MyLayer(base_layer.Layer): def call(self, inputs, training=None): if training: loss = math_ops.reduce_sum(inputs) else: loss = 0. self.add_loss(loss) return inputs inputs = input_layer.Input((3,)) outputs = MyLayer()(inputs) model = training_lib.Model(inputs, outputs) model.compile( 'sgd', 'mse', run_eagerly=testing_utils.should_run_eagerly()) train_loss = model.train_on_batch(np.ones((2, 3)), np.ones((2, 3))) self.assertEqual(train_loss, 2 * 3) test_loss = model.test_on_batch(np.ones((2, 3)), np.ones((2, 3))) self.assertEqual(test_loss, 0) def test_if_training_pattern_metric(self): class MyLayer(base_layer.Layer): def call(self, inputs, training=None): if training: metric = math_ops.reduce_sum(inputs) else: metric = 0. self.add_metric(metric, name='my_metric', aggregation='mean') return inputs inputs = input_layer.Input((3,)) outputs = MyLayer()(inputs) model = training_lib.Model(inputs, outputs) model.compile( 'sgd', 'mse', run_eagerly=testing_utils.should_run_eagerly()) for _ in range(3): _, train_metric = model.train_on_batch(np.ones((2, 3)), np.ones((2, 3))) self.assertEqual(train_metric, 2 * 3) _, test_metric = model.test_on_batch(np.ones((2, 3)), np.ones((2, 3))) self.assertEqual(test_metric, 0) def test_if_training_pattern_update(self): class MyLayer(base_layer.Layer): def build(self, input_shape): self.counter = self.add_weight( shape=(), trainable=False, initializer='zeros') def call(self, inputs, training=None): if training: increment = 1. else: increment = 0. self.counter.assign_add(increment) return inputs inputs = input_layer.Input((3,)) layer = MyLayer() outputs = layer(inputs) model = training_lib.Model(inputs, outputs) model.compile( 'sgd', 'mse', run_eagerly=testing_utils.should_run_eagerly()) model.train_on_batch(np.ones((2, 3)), np.ones((2, 3))) self.assertEqual(backend.get_value(layer.counter), 1.) def test_conditional_losses_in_call(self): class MyLayer(base_layer.Layer): def __init__(self): super(MyLayer, self).__init__(dynamic=testing_utils.should_run_eagerly()) def call(self, inputs, training=None): if training: self.add_loss(math_ops.reduce_sum(inputs)) return inputs def compute_output_shape(self, input_shape): return input_shape inputs = input_layer.Input((3,)) layer = MyLayer() outputs = layer(inputs) model = training_lib.Model(inputs, outputs) model.compile('sgd', 'mse', run_eagerly=testing_utils.should_run_eagerly()) loss = model.train_on_batch(np.ones((2, 3)), np.ones((2, 3))) self.assertEqual(loss, 2 * 3) def test_conditional_callable_losses(self): model = sequential.Sequential([ layers.Dense( 1, kernel_regularizer=regularizers.l2(1e-4), input_shape=(1,)) ]) model._run_eagerly = testing_utils.should_run_eagerly() def assert_graph(t): if not context.executing_eagerly(): self.assertEqual(t.graph, ops.get_default_graph()) @def_function.function def get_losses(t): if t < 0: return math_ops.reduce_sum(model.losses) * t else: return math_ops.reduce_sum(model.losses) assert_graph(get_losses(constant_op.constant(2.))) assert_graph(get_losses(constant_op.constant(0.5))) def test_conditional_metrics_in_call(self): class MyLayer(base_layer.Layer): def __init__(self): super(MyLayer, self).__init__(dynamic=testing_utils.should_run_eagerly()) def call(self, inputs, training=None): if training: self.add_metric(math_ops.reduce_sum(inputs), name='sum', aggregation='mean') return inputs def compute_output_shape(self, input_shape): return input_shape inputs = input_layer.Input((3,)) layer = MyLayer() outputs = layer(inputs) model = training_lib.Model(inputs, outputs) model.compile('sgd', 'mse', run_eagerly=testing_utils.should_run_eagerly()) history = model.fit(np.ones((2, 3)), np.ones((2, 3))) self.assertEqual(history.history['sum'][-1], 2 * 3) def test_conditional_activity_regularizer_in_call(self): class TestModel(training_lib.Model): def __init__(self): super(TestModel, self).__init__( name='test_model', dynamic=testing_utils.should_run_eagerly()) self.layer = layers.Dense(2, activity_regularizer='l2') def call(self, x, training=None): if math_ops.greater(math_ops.reduce_sum(x), 0.0): return self.layer(x) else: return self.layer(x) model = TestModel() model.compile( loss='mse', optimizer='sgd', run_eagerly=testing_utils.should_run_eagerly()) x = np.ones(shape=(10, 1)) y = np.ones(shape=(10, 2)) if testing_utils.should_run_eagerly(): model.fit(x, y, epochs=2, batch_size=5) else: with self.assertRaisesRegex(errors_impl.InaccessibleTensorError, 'ActivityRegularizer'): model.fit(x, y, epochs=2, batch_size=5) def test_conditional_activity_regularizer_with_wrappers_in_call(self): class TestModel(training_lib.Model): def __init__(self): super(TestModel, self).__init__( name='test_model', dynamic=testing_utils.should_run_eagerly()) self.layer = layers.TimeDistributed( layers.Dense(2, activity_regularizer='l2'), input_shape=(3, 4)) def call(self, x, training=None): if math_ops.greater(math_ops.reduce_sum(x), 0.0): return self.layer(x) else: return self.layer(x) model = TestModel() model.compile( loss='mse', optimizer='sgd', run_eagerly=testing_utils.should_run_eagerly()) x = np.ones(shape=(10, 3, 4)) y = np.ones(shape=(10, 3, 2)) if testing_utils.should_run_eagerly(): model.fit(x, y, epochs=2, batch_size=5) else: with self.assertRaisesRegex(errors_impl.InaccessibleTensorError, 'ActivityRegularizer'): model.fit(x, y, epochs=2, batch_size=5) class AddLayer(base_layer.Layer): """A layer which adds its input to a variable. Useful for testing a layer with a variable """ def build(self, _): self.v = self.add_weight('v', (), initializer='ones') self.built = True def call(self, inputs): return inputs + self.v class IdentityLayer(base_layer.Layer): """A layer that returns its input. Useful for testing a layer without a variable. """ def call(self, inputs): return inputs @combinations.generate(combinations.combine(mode=['graph', 'eager'])) class DTypeTest(keras_parameterized.TestCase): # This class only have tests relating to layer.dtype. Tests for dtype policies # are in mixed_precision/experimental/keras_test.py # TODO(reedwm): Maybe have a separate test file for input casting tests. def _const(self, dtype): return array_ops.constant(1, dtype=dtype) @testing_utils.enable_v2_dtype_behavior def test_dtype_defaults_to_floatx(self): layer = AddLayer() self.assertEqual(layer.dtype, 'float32') layer(self._const('float64')) self.assertEqual(layer.dtype, 'float32') # dtype should not change try: backend.set_floatx('float64') layer = AddLayer() self.assertEqual(layer.dtype, 'float64') finally: backend.set_floatx('float32') @testing_utils.enable_v2_dtype_behavior def test_passing_dtype_to_constructor(self): layer = IdentityLayer(dtype='float64') layer(self._const('float32')) self.assertEqual(layer.dtype, 'float64') layer = IdentityLayer(dtype='int32') layer(self._const('float32')) self.assertEqual(layer.dtype, 'int32') layer = IdentityLayer(dtype=dtypes.float64) layer(self._const('float32')) self.assertEqual(layer.dtype, 'float64') @testing_utils.enable_v2_dtype_behavior def input_cast_to_dtype(self): layer = AddLayer() # Input should be cast to layer.dtype, so output should also be layer.dtype self.assertEqual(layer(self._const('float64')).dtype, 'float32') layer = AddLayer(dtype='float64') self.assertEqual(layer(self._const('float32')).dtype, 'float64') # Test inputs are not casted if layer.dtype is not floating-point layer = IdentityLayer(dtype='int32') self.assertEqual(layer(self._const('float64')).dtype, 'float64') # Test inputs are not casted if the inputs are not floating-point layer = IdentityLayer(dtype='float32') self.assertEqual(layer(self._const('int32')).dtype, 'int32') # Test Numpy arrays are casted layer = IdentityLayer(dtype='float64') self.assertEqual(layer(np.array(1, dtype='float32')).dtype, 'float64') # Test Python floats are casted layer = IdentityLayer(dtype='float64') self.assertEqual(layer(1.).dtype, 'float64') @testing_utils.enable_v2_dtype_behavior def multiple_inputs_cast_to_dtype(self): class MultiIdentityLayer(base_layer.Layer): def call(self, inputs): return [array_ops.identity(x) for x in inputs] # Testing layer with default dtype of float32 layer = MultiIdentityLayer() x, y = layer([self._const('float16'), self._const('float32')]) self.assertEqual(x.dtype, 'float32') self.assertEqual(y.dtype, 'float32') # Test passing dtype to the constructor layer = MultiIdentityLayer(dtype='float64') x, y = layer([self._const('float16'), self._const('float32')]) self.assertEqual(x.dtype, 'float64') self.assertEqual(y.dtype, 'float64') # Test several non-floating point types layer = MultiIdentityLayer(dtype='float64') x, y, z, w = layer([self._const('float16'), self._const('bool'), self._const('float64'), self._constant('complex64')]) self.assertEqual(x.dtype, 'float64') self.assertEqual(y.dtype, 'bool') self.assertEqual(z.dtype, 'float64') self.assertEqual(w.dtype, 'complex64') @testing_utils.enable_v2_dtype_behavior def test_extra_args_and_kwargs_not_casted(self): class IdentityLayerWithArgs(base_layer.Layer): def call(self, inputs, *args, **kwargs): kwargs.pop('training', None) return nest.flatten([inputs, args, kwargs]) layer = IdentityLayerWithArgs(dtype='float64') x, y, z = layer(self._const('float16'), self._const('float16'), kwarg=self._const('float16')) self.assertEqual(x.dtype, 'float64') self.assertEqual(y.dtype, 'float16') self.assertEqual(z.dtype, 'float16') @testing_utils.enable_v2_dtype_behavior def test_layer_without_autocast(self): class IdentityLayerWithoutAutocast(IdentityLayer): def __init__(self, *args, **kwargs): kwargs['autocast'] = False super(IdentityLayerWithoutAutocast, self).__init__(*args, **kwargs) layer = IdentityLayerWithoutAutocast(dtype='float64') self.assertEqual(layer(self._const('float32')).dtype, 'float32') @testing_utils.enable_v2_dtype_behavior def test_compute_output_signature(self): class IdentityLayerWithOutputShape(IdentityLayer): def compute_output_shape(self, input_shape): return input_shape layer = IdentityLayerWithOutputShape(dtype='float64') output_signature = layer.compute_output_signature( tensor_spec.TensorSpec(shape=(), dtype='float32')) self.assertEqual(output_signature.shape, ()) self.assertEqual(output_signature.dtype, 'float64') @testing_utils.enable_v2_dtype_behavior def test_composite_tensors_input_casting(self): sparse = sparse_tensor.SparseTensor( indices=array_ops.constant([[0, 1], [2, 3]], dtype='int64'), values=array_ops.constant([0., 1.], dtype='float32'), dense_shape=array_ops.constant([4, 4], dtype='int64')) ragged = ragged_tensor.RaggedTensor.from_row_splits( values=array_ops.constant([1., 2., 3.], dtype='float32'), row_splits=array_ops.constant([0, 2, 2, 3], dtype='int64')) layer = IdentityLayer(dtype='float16') for x in sparse, ragged: self.assertEqual(x.dtype, 'float32') y = layer(x) self.assertEqual(y.dtype, 'float16') self.assertEqual(type(x), type(y)) @testing_utils.enable_v2_dtype_behavior def test_passing_non_tensor(self): layer = IdentityLayer() x = object() y = layer(x) # Layer should not cast 'x', as it's not a tensor self.assertIs(x, y) @testing_utils.disable_v2_dtype_behavior def test_v1_behavior(self): # Test dtype defaults to None and inferred from input layer = IdentityLayer() self.assertIsNone(layer.dtype) layer(self._const('float64')) self.assertEqual(layer.dtype, 'float64') # Test layer does not cast to dtype self.assertEqual(layer(self._const('float32')).dtype, 'float32') if __name__ == '__main__': ops.enable_eager_execution() test.main()
apache-2.0
sacloud/libsacloud
v2/helper/service/server/service.go
902
// Copyright 2016-2022 The Libsacloud Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package server import "github.com/sacloud/libsacloud/v2/sacloud" // Service provides a high-level API of for Server type Service struct { caller sacloud.APICaller } // New returns new service instance of Server func New(caller sacloud.APICaller) *Service { return &Service{caller: caller} }
apache-2.0