blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
4
201
content_id
stringlengths
40
40
detected_licenses
sequencelengths
0
85
license_type
stringclasses
2 values
repo_name
stringlengths
7
100
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
260 values
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
11.4k
681M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
17 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
80 values
src_encoding
stringclasses
28 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
8
9.86M
extension
stringclasses
52 values
content
stringlengths
8
9.86M
authors
sequencelengths
1
1
author
stringlengths
0
119
97f464e6544ff9ea3ddce25f2b05d00a66b6bb9d
275ec6905a664e6d50f6f7593d62066740b241a0
/10_9.cpp
6c5e8a859e4e2fc4e4c0398a881a22f8c3d1ee80
[]
no_license
huangjiahua/cppLearningFiles
0f135624d5d7d2256e8fd55146a408170737b603
7000ac6111b33c880a66c2c3cc2e4f41390aff9e
refs/heads/master
2021-09-10T15:11:48.991007
2018-03-28T08:57:41
2018-03-28T08:57:41
122,352,150
0
0
null
null
null
null
UTF-8
C++
false
false
615
cpp
#include <iostream> #include <string> #include <vector> #include <algorithm> using namespace std; void elimDups(vector<string> &words) { sort(words.begin(), words.end()); cout << words.size() << endl; auto end_unique = unique(words.begin(), words.end()); for (vector<string>::iterator i = words.begin(); i != words.end(); ++i) cout << *i << " "; cout << endl; cout << words.size() << endl; words.erase(end_unique, words.end()); } int main() { vector<string> vs{"the", "the", "a", "a", "b", "b"}; elimDups(vs); for (auto i : vs) cout << i << " "; }
fee5b2289aea637d107aae1a3c6d6c161f7d9e5d
e98b265914ec3dbdc5eefe443505e58321ef5c00
/third_party/WebKit/Source/web/WebSettingsImpl.cpp
deabcf8efb682a5ba9e5ce884683e1dc9699a625
[ "LGPL-2.0-or-later", "GPL-1.0-or-later", "MIT", "Apache-2.0", "BSD-3-Clause", "LicenseRef-scancode-warranty-disclaimer", "LGPL-2.1-only", "GPL-2.0-only", "LGPL-2.0-only", "BSD-2-Clause", "LicenseRef-scancode-other-copyleft" ]
permissive
zhouyige/chrome4sdp
d223f33cf45889bf9437ad9614e1c414c6c37faf
a9655c8758922ec2ff07400f6be8c448749a8c64
refs/heads/master
2022-12-17T17:36:19.467887
2017-01-04T07:35:25
2017-01-04T07:35:25
78,020,809
0
1
BSD-3-Clause
2022-11-17T18:58:27
2017-01-04T14:05:31
null
UTF-8
C++
false
false
24,064
cpp
/* * Copyright (C) 2009 Google Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * Neither the name of Google Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "web/WebSettingsImpl.h" #include "core/frame/Settings.h" #include "platform/graphics/DeferredImageDecoder.h" #include "public/platform/WebString.h" #include "public/platform/WebURL.h" #include "web/DevToolsEmulator.h" #include "web/WebDevToolsAgentImpl.h" namespace blink { WebSettingsImpl::WebSettingsImpl(Settings* settings, DevToolsEmulator* devToolsEmulator) : m_settings(settings), m_devToolsEmulator(devToolsEmulator), m_showFPSCounter(false), m_showPaintRects(false), m_renderVSyncNotificationEnabled(false), m_autoZoomFocusedNodeToLegibleScale(false), m_supportDeprecatedTargetDensityDPI(false), m_shrinksViewportContentToFit(false), m_viewportMetaLayoutSizeQuirk(false), m_viewportMetaNonUserScalableQuirk(false), m_clobberUserAgentInitialScaleQuirk(false), m_expensiveBackgroundThrottlingCPUBudget(-1), m_expensiveBackgroundThrottlingInitialBudget(-1), m_expensiveBackgroundThrottlingMaxBudget(-1), m_expensiveBackgroundThrottlingMaxDelay(-1) { DCHECK(settings); } void WebSettingsImpl::setFromStrings(const WebString& name, const WebString& value) { m_settings->setFromStrings(name, value); } void WebSettingsImpl::setStandardFontFamily(const WebString& font, UScriptCode script) { if (m_settings->genericFontFamilySettings().updateStandard(font, script)) m_settings->notifyGenericFontFamilyChange(); } void WebSettingsImpl::setFixedFontFamily(const WebString& font, UScriptCode script) { if (m_settings->genericFontFamilySettings().updateFixed(font, script)) m_settings->notifyGenericFontFamilyChange(); } void WebSettingsImpl::setForcePreloadNoneForMediaElements(bool enabled) { m_settings->setForcePreloadNoneForMediaElements(enabled); } void WebSettingsImpl::setForceZeroLayoutHeight(bool enabled) { m_settings->setForceZeroLayoutHeight(enabled); } void WebSettingsImpl::setFullscreenSupported(bool enabled) { m_settings->setFullscreenSupported(enabled); } void WebSettingsImpl::setSerifFontFamily(const WebString& font, UScriptCode script) { if (m_settings->genericFontFamilySettings().updateSerif(font, script)) m_settings->notifyGenericFontFamilyChange(); } void WebSettingsImpl::setSansSerifFontFamily(const WebString& font, UScriptCode script) { if (m_settings->genericFontFamilySettings().updateSansSerif(font, script)) m_settings->notifyGenericFontFamilyChange(); } void WebSettingsImpl::setCursiveFontFamily(const WebString& font, UScriptCode script) { if (m_settings->genericFontFamilySettings().updateCursive(font, script)) m_settings->notifyGenericFontFamilyChange(); } void WebSettingsImpl::setFantasyFontFamily(const WebString& font, UScriptCode script) { if (m_settings->genericFontFamilySettings().updateFantasy(font, script)) m_settings->notifyGenericFontFamilyChange(); } void WebSettingsImpl::setPictographFontFamily(const WebString& font, UScriptCode script) { if (m_settings->genericFontFamilySettings().updatePictograph(font, script)) m_settings->notifyGenericFontFamilyChange(); } void WebSettingsImpl::setDefaultFontSize(int size) { m_settings->setDefaultFontSize(size); } void WebSettingsImpl::setDefaultFixedFontSize(int size) { m_settings->setDefaultFixedFontSize(size); } void WebSettingsImpl::setDefaultVideoPosterURL(const WebString& url) { m_settings->setDefaultVideoPosterURL(url); } void WebSettingsImpl::setMinimumFontSize(int size) { m_settings->setMinimumFontSize(size); } void WebSettingsImpl::setMinimumLogicalFontSize(int size) { m_settings->setMinimumLogicalFontSize(size); } void WebSettingsImpl::setDeviceSupportsTouch(bool deviceSupportsTouch) { m_settings->setDeviceSupportsTouch(deviceSupportsTouch); } void WebSettingsImpl::setDeviceSupportsMouse(bool deviceSupportsMouse) { m_settings->setDeviceSupportsMouse(deviceSupportsMouse); } void WebSettingsImpl::setAutoZoomFocusedNodeToLegibleScale( bool autoZoomFocusedNodeToLegibleScale) { m_autoZoomFocusedNodeToLegibleScale = autoZoomFocusedNodeToLegibleScale; } void WebSettingsImpl::setBrowserSideNavigationEnabled(bool enabled) { m_settings->setBrowserSideNavigationEnabled(enabled); } void WebSettingsImpl::setTextAutosizingEnabled(bool enabled) { m_devToolsEmulator->setTextAutosizingEnabled(enabled); } void WebSettingsImpl::setAccessibilityFontScaleFactor(float fontScaleFactor) { m_settings->setAccessibilityFontScaleFactor(fontScaleFactor); } void WebSettingsImpl::setAccessibilityEnabled(bool enabled) { m_settings->setAccessibilityEnabled(enabled); } void WebSettingsImpl::setAccessibilityPasswordValuesEnabled(bool enabled) { m_settings->setAccessibilityPasswordValuesEnabled(enabled); } void WebSettingsImpl::setInlineTextBoxAccessibilityEnabled(bool enabled) { m_settings->setInlineTextBoxAccessibilityEnabled(enabled); } void WebSettingsImpl::setInertVisualViewport(bool enabled) { m_settings->setInertVisualViewport(enabled); } void WebSettingsImpl::setDeviceScaleAdjustment(float deviceScaleAdjustment) { m_devToolsEmulator->setDeviceScaleAdjustment(deviceScaleAdjustment); } void WebSettingsImpl::setDefaultTextEncodingName(const WebString& encoding) { m_settings->setDefaultTextEncodingName((String)encoding); } void WebSettingsImpl::setJavaScriptEnabled(bool enabled) { m_devToolsEmulator->setScriptEnabled(enabled); } void WebSettingsImpl::setWebSecurityEnabled(bool enabled) { m_settings->setWebSecurityEnabled(enabled); } void WebSettingsImpl::setJavaScriptCanOpenWindowsAutomatically( bool canOpenWindows) { m_settings->setJavaScriptCanOpenWindowsAutomatically(canOpenWindows); } void WebSettingsImpl::setSupportDeprecatedTargetDensityDPI( bool supportDeprecatedTargetDensityDPI) { m_supportDeprecatedTargetDensityDPI = supportDeprecatedTargetDensityDPI; } void WebSettingsImpl::setViewportMetaLayoutSizeQuirk( bool viewportMetaLayoutSizeQuirk) { m_viewportMetaLayoutSizeQuirk = viewportMetaLayoutSizeQuirk; } void WebSettingsImpl::setViewportMetaMergeContentQuirk( bool viewportMetaMergeContentQuirk) { m_settings->setViewportMetaMergeContentQuirk(viewportMetaMergeContentQuirk); } void WebSettingsImpl::setViewportMetaNonUserScalableQuirk( bool viewportMetaNonUserScalableQuirk) { m_viewportMetaNonUserScalableQuirk = viewportMetaNonUserScalableQuirk; } void WebSettingsImpl::setViewportMetaZeroValuesQuirk( bool viewportMetaZeroValuesQuirk) { m_settings->setViewportMetaZeroValuesQuirk(viewportMetaZeroValuesQuirk); } void WebSettingsImpl::setIgnoreMainFrameOverflowHiddenQuirk( bool ignoreMainFrameOverflowHiddenQuirk) { m_settings->setIgnoreMainFrameOverflowHiddenQuirk( ignoreMainFrameOverflowHiddenQuirk); } void WebSettingsImpl::setReportScreenSizeInPhysicalPixelsQuirk( bool reportScreenSizeInPhysicalPixelsQuirk) { m_settings->setReportScreenSizeInPhysicalPixelsQuirk( reportScreenSizeInPhysicalPixelsQuirk); } void WebSettingsImpl::setRubberBandingOnCompositorThread( bool rubberBandingOnCompositorThread) {} void WebSettingsImpl::setClobberUserAgentInitialScaleQuirk( bool clobberUserAgentInitialScaleQuirk) { m_clobberUserAgentInitialScaleQuirk = clobberUserAgentInitialScaleQuirk; } void WebSettingsImpl::setSupportsMultipleWindows(bool supportsMultipleWindows) { m_settings->setSupportsMultipleWindows(supportsMultipleWindows); } void WebSettingsImpl::setLoadsImagesAutomatically( bool loadsImagesAutomatically) { m_settings->setLoadsImagesAutomatically(loadsImagesAutomatically); } void WebSettingsImpl::setImageAnimationPolicy(ImageAnimationPolicy policy) { m_settings->setImageAnimationPolicy( static_cast<blink::ImageAnimationPolicy>(policy)); } void WebSettingsImpl::setImagesEnabled(bool enabled) { m_settings->setImagesEnabled(enabled); } void WebSettingsImpl::setNightModeEnabled(bool enabled) { m_settings->setNightModeEnabled(enabled); } void WebSettingsImpl::setPowersaveModeEnabled(bool enabled) { m_settings->setPowersaveModeEnabled(enabled); } void WebSettingsImpl::setLoadWithOverviewMode(bool enabled) { m_settings->setLoadWithOverviewMode(enabled); } void WebSettingsImpl::setShouldReuseGlobalForUnownedMainFrame(bool enabled) { m_settings->setShouldReuseGlobalForUnownedMainFrame(enabled); } void WebSettingsImpl::setProgressBarCompletion( ProgressBarCompletion progressBarCompletion) { m_settings->setProgressBarCompletion( static_cast<blink::ProgressBarCompletion>(progressBarCompletion)); } void WebSettingsImpl::setPluginsEnabled(bool enabled) { m_devToolsEmulator->setPluginsEnabled(enabled); } void WebSettingsImpl::setAvailablePointerTypes(int pointers) { m_devToolsEmulator->setAvailablePointerTypes(pointers); } void WebSettingsImpl::setPrimaryPointerType(PointerType pointer) { m_devToolsEmulator->setPrimaryPointerType( static_cast<blink::PointerType>(pointer)); } void WebSettingsImpl::setAvailableHoverTypes(int types) { m_devToolsEmulator->setAvailableHoverTypes(types); } void WebSettingsImpl::setPrimaryHoverType(HoverType type) { m_devToolsEmulator->setPrimaryHoverType(static_cast<blink::HoverType>(type)); } void WebSettingsImpl::setPreferHiddenVolumeControls(bool enabled) { m_settings->setPreferHiddenVolumeControls(enabled); } void WebSettingsImpl::setDOMPasteAllowed(bool enabled) { m_settings->setDOMPasteAllowed(enabled); } void WebSettingsImpl::setShrinksViewportContentToFit( bool shrinkViewportContent) { m_shrinksViewportContentToFit = shrinkViewportContent; } void WebSettingsImpl::setSpatialNavigationEnabled(bool enabled) { m_settings->setSpatialNavigationEnabled(enabled); } void WebSettingsImpl::setSpellCheckEnabledByDefault(bool enabled) { m_settings->setSpellCheckEnabledByDefault(enabled); } void WebSettingsImpl::setTextAreasAreResizable(bool areResizable) { m_settings->setTextAreasAreResizable(areResizable); } void WebSettingsImpl::setAllowScriptsToCloseWindows(bool allow) { m_settings->setAllowScriptsToCloseWindows(allow); } void WebSettingsImpl::setUseLegacyBackgroundSizeShorthandBehavior( bool useLegacyBackgroundSizeShorthandBehavior) { m_settings->setUseLegacyBackgroundSizeShorthandBehavior( useLegacyBackgroundSizeShorthandBehavior); } void WebSettingsImpl::setWideViewportQuirkEnabled( bool wideViewportQuirkEnabled) { m_settings->setWideViewportQuirkEnabled(wideViewportQuirkEnabled); } void WebSettingsImpl::setUseWideViewport(bool useWideViewport) { m_settings->setUseWideViewport(useWideViewport); } void WebSettingsImpl::setDoubleTapToZoomEnabled(bool doubleTapToZoomEnabled) { m_devToolsEmulator->setDoubleTapToZoomEnabled(doubleTapToZoomEnabled); } void WebSettingsImpl::setDownloadableBinaryFontsEnabled(bool enabled) { m_settings->setDownloadableBinaryFontsEnabled(enabled); } void WebSettingsImpl::setJavaScriptCanAccessClipboard(bool enabled) { m_settings->setJavaScriptCanAccessClipboard(enabled); } void WebSettingsImpl::setXSSAuditorEnabled(bool enabled) { m_settings->setXSSAuditorEnabled(enabled); } void WebSettingsImpl::setTextTrackKindUserPreference( TextTrackKindUserPreference preference) { m_settings->setTextTrackKindUserPreference( static_cast<blink::TextTrackKindUserPreference>(preference)); } void WebSettingsImpl::setTextTrackBackgroundColor(const WebString& color) { m_settings->setTextTrackBackgroundColor(color); } void WebSettingsImpl::setTextTrackFontFamily(const WebString& fontFamily) { m_settings->setTextTrackFontFamily(fontFamily); } void WebSettingsImpl::setTextTrackFontStyle(const WebString& fontStyle) { m_settings->setTextTrackFontStyle(fontStyle); } void WebSettingsImpl::setTextTrackFontVariant(const WebString& fontVariant) { m_settings->setTextTrackFontVariant(fontVariant); } void WebSettingsImpl::setTextTrackMarginPercentage(float percentage) { m_settings->setTextTrackMarginPercentage(percentage); } void WebSettingsImpl::setTextTrackTextColor(const WebString& color) { m_settings->setTextTrackTextColor(color); } void WebSettingsImpl::setTextTrackTextShadow(const WebString& shadow) { m_settings->setTextTrackTextShadow(shadow); } void WebSettingsImpl::setTextTrackTextSize(const WebString& size) { m_settings->setTextTrackTextSize(size); } void WebSettingsImpl::setDNSPrefetchingEnabled(bool enabled) { m_settings->setDNSPrefetchingEnabled(enabled); } void WebSettingsImpl::setDataSaverEnabled(bool enabled) { m_settings->setDataSaverEnabled(enabled); } void WebSettingsImpl::setLocalStorageEnabled(bool enabled) { m_settings->setLocalStorageEnabled(enabled); } void WebSettingsImpl::setMainFrameClipsContent(bool enabled) { m_settings->setMainFrameClipsContent(enabled); } void WebSettingsImpl::setMaxTouchPoints(int maxTouchPoints) { m_settings->setMaxTouchPoints(maxTouchPoints); } void WebSettingsImpl::setAllowUniversalAccessFromFileURLs(bool allow) { m_settings->setAllowUniversalAccessFromFileURLs(allow); } void WebSettingsImpl::setAllowFileAccessFromFileURLs(bool allow) { m_settings->setAllowFileAccessFromFileURLs(allow); } void WebSettingsImpl::setAllowGeolocationOnInsecureOrigins(bool allow) { m_settings->setAllowGeolocationOnInsecureOrigins(allow); } void WebSettingsImpl::setThreadedScrollingEnabled(bool enabled) { m_settings->setThreadedScrollingEnabled(enabled); } void WebSettingsImpl::setTouchDragDropEnabled(bool enabled) { m_settings->setTouchDragDropEnabled(enabled); } void WebSettingsImpl::setOfflineWebApplicationCacheEnabled(bool enabled) { m_settings->setOfflineWebApplicationCacheEnabled(enabled); } void WebSettingsImpl::setExperimentalWebGLEnabled(bool enabled) { m_settings->setWebGLEnabled(enabled); } void WebSettingsImpl::setRenderVSyncNotificationEnabled(bool enabled) { m_renderVSyncNotificationEnabled = enabled; } void WebSettingsImpl::setWebGLErrorsToConsoleEnabled(bool enabled) { m_settings->setWebGLErrorsToConsoleEnabled(enabled); } void WebSettingsImpl::setAlwaysShowContextMenuOnTouch(bool enabled) { m_settings->setAlwaysShowContextMenuOnTouch(enabled); } void WebSettingsImpl::setShowContextMenuOnMouseUp(bool enabled) { m_settings->setShowContextMenuOnMouseUp(enabled); } void WebSettingsImpl::setShowFPSCounter(bool show) { m_showFPSCounter = show; } void WebSettingsImpl::setShowPaintRects(bool show) { m_showPaintRects = show; } void WebSettingsImpl::setEditingBehavior(EditingBehavior behavior) { m_settings->setEditingBehaviorType( static_cast<EditingBehaviorType>(behavior)); } void WebSettingsImpl::setAcceleratedCompositingEnabled(bool enabled) { m_settings->setAcceleratedCompositingEnabled(enabled); } void WebSettingsImpl::setMockScrollbarsEnabled(bool enabled) { m_settings->setMockScrollbarsEnabled(enabled); } void WebSettingsImpl::setHideScrollbars(bool enabled) { m_settings->setHideScrollbars(enabled); } void WebSettingsImpl::setMockGestureTapHighlightsEnabled(bool enabled) { m_settings->setMockGestureTapHighlightsEnabled(enabled); } void WebSettingsImpl::setAccelerated2dCanvasMSAASampleCount(int count) { m_settings->setAccelerated2dCanvasMSAASampleCount(count); } void WebSettingsImpl::setAntialiased2dCanvasEnabled(bool enabled) { m_settings->setAntialiased2dCanvasEnabled(enabled); } void WebSettingsImpl::setAntialiasedClips2dCanvasEnabled(bool enabled) { m_settings->setAntialiasedClips2dCanvasEnabled(enabled); } void WebSettingsImpl::setPreferCompositingToLCDTextEnabled(bool enabled) { m_devToolsEmulator->setPreferCompositingToLCDTextEnabled(enabled); } void WebSettingsImpl::setMinimumAccelerated2dCanvasSize(int numPixels) { m_settings->setMinimumAccelerated2dCanvasSize(numPixels); } void WebSettingsImpl::setHideDownloadUI(bool hide) { m_settings->setHideDownloadUI(hide); } void WebSettingsImpl::setHistoryEntryRequiresUserGesture(bool enabled) { m_settings->setHistoryEntryRequiresUserGesture(enabled); } void WebSettingsImpl::setHyperlinkAuditingEnabled(bool enabled) { m_settings->setHyperlinkAuditingEnabled(enabled); } void WebSettingsImpl::setAutoplayExperimentMode(const WebString& mode) { m_settings->setAutoplayExperimentMode(mode); } void WebSettingsImpl::setValidationMessageTimerMagnification(int newValue) { m_settings->setValidationMessageTimerMagnification(newValue); } void WebSettingsImpl::setAllowRunningOfInsecureContent(bool enabled) { m_settings->setAllowRunningOfInsecureContent(enabled); } void WebSettingsImpl::setDisableReadingFromCanvas(bool enabled) { m_settings->setDisableReadingFromCanvas(enabled); } void WebSettingsImpl::setStrictMixedContentChecking(bool enabled) { m_settings->setStrictMixedContentChecking(enabled); } void WebSettingsImpl::setStrictMixedContentCheckingForPlugin(bool enabled) { m_settings->setStrictMixedContentCheckingForPlugin(enabled); } void WebSettingsImpl::setStrictPowerfulFeatureRestrictions(bool enabled) { m_settings->setStrictPowerfulFeatureRestrictions(enabled); } void WebSettingsImpl::setStrictlyBlockBlockableMixedContent(bool enabled) { m_settings->setStrictlyBlockBlockableMixedContent(enabled); } void WebSettingsImpl::setPassiveEventListenerDefault( PassiveEventListenerDefault defaultValue) { m_settings->setPassiveListenerDefault( static_cast<PassiveListenerDefault>(defaultValue)); } void WebSettingsImpl::setPasswordEchoEnabled(bool flag) { m_settings->setPasswordEchoEnabled(flag); } void WebSettingsImpl::setPasswordEchoDurationInSeconds( double durationInSeconds) { m_settings->setPasswordEchoDurationInSeconds(durationInSeconds); } void WebSettingsImpl::setPerTilePaintingEnabled(bool enabled) { m_perTilePaintingEnabled = enabled; } void WebSettingsImpl::setShouldPrintBackgrounds(bool enabled) { m_settings->setShouldPrintBackgrounds(enabled); } void WebSettingsImpl::setShouldClearDocumentBackground(bool enabled) { m_settings->setShouldClearDocumentBackground(enabled); } void WebSettingsImpl::setEnableScrollAnimator(bool enabled) { m_settings->setScrollAnimatorEnabled(enabled); } void WebSettingsImpl::setEnableTouchAdjustment(bool enabled) { m_settings->setTouchAdjustmentEnabled(enabled); } bool WebSettingsImpl::multiTargetTapNotificationEnabled() { return m_settings->multiTargetTapNotificationEnabled(); } void WebSettingsImpl::setMultiTargetTapNotificationEnabled(bool enabled) { m_settings->setMultiTargetTapNotificationEnabled(enabled); } bool WebSettingsImpl::viewportEnabled() const { return m_settings->viewportEnabled(); } bool WebSettingsImpl::viewportMetaEnabled() const { return m_settings->viewportMetaEnabled(); } bool WebSettingsImpl::doubleTapToZoomEnabled() const { return m_devToolsEmulator->doubleTapToZoomEnabled(); } bool WebSettingsImpl::mockGestureTapHighlightsEnabled() const { return m_settings->mockGestureTapHighlightsEnabled(); } bool WebSettingsImpl::shrinksViewportContentToFit() const { return m_shrinksViewportContentToFit; } void WebSettingsImpl::setShouldRespectImageOrientation(bool enabled) { m_settings->setShouldRespectImageOrientation(enabled); } void WebSettingsImpl::setMediaControlsOverlayPlayButtonEnabled(bool enabled) { m_settings->setMediaControlsOverlayPlayButtonEnabled(enabled); } void WebSettingsImpl::setMediaPlaybackRequiresUserGesture(bool required) { m_settings->setMediaPlaybackRequiresUserGesture(required); } void WebSettingsImpl::setPresentationRequiresUserGesture(bool required) { m_settings->setPresentationRequiresUserGesture(required); } void WebSettingsImpl::setViewportEnabled(bool enabled) { m_settings->setViewportEnabled(enabled); } void WebSettingsImpl::setViewportMetaEnabled(bool enabled) { m_settings->setViewportMetaEnabled(enabled); } void WebSettingsImpl::setSyncXHRInDocumentsEnabled(bool enabled) { m_settings->setSyncXHRInDocumentsEnabled(enabled); } void WebSettingsImpl::setCookieEnabled(bool enabled) { m_settings->setCookieEnabled(enabled); } void WebSettingsImpl::setNavigateOnDragDrop(bool enabled) { m_settings->setNavigateOnDragDrop(enabled); } void WebSettingsImpl::setAllowCustomScrollbarInMainFrame(bool enabled) { m_settings->setAllowCustomScrollbarInMainFrame(enabled); } void WebSettingsImpl::setSelectTrailingWhitespaceEnabled(bool enabled) { m_settings->setSelectTrailingWhitespaceEnabled(enabled); } void WebSettingsImpl::setSelectionIncludesAltImageText(bool enabled) { m_settings->setSelectionIncludesAltImageText(enabled); } void WebSettingsImpl::setSelectionStrategy(SelectionStrategyType strategy) { m_settings->setSelectionStrategy(static_cast<SelectionStrategy>(strategy)); } void WebSettingsImpl::setSmartInsertDeleteEnabled(bool enabled) { m_settings->setSmartInsertDeleteEnabled(enabled); } void WebSettingsImpl::setUseSolidColorScrollbars(bool enabled) { m_settings->setUseSolidColorScrollbars(enabled); } void WebSettingsImpl::setMainFrameResizesAreOrientationChanges(bool enabled) { m_devToolsEmulator->setMainFrameResizesAreOrientationChanges(enabled); } void WebSettingsImpl::setV8CacheOptions(V8CacheOptions options) { m_settings->setV8CacheOptions(static_cast<blink::V8CacheOptions>(options)); } void WebSettingsImpl::setV8CacheStrategiesForCacheStorage( V8CacheStrategiesForCacheStorage strategies) { m_settings->setV8CacheStrategiesForCacheStorage( static_cast<blink::V8CacheStrategiesForCacheStorage>(strategies)); } void WebSettingsImpl::setViewportStyle(WebViewportStyle style) { m_devToolsEmulator->setViewportStyle(style); } void WebSettingsImpl::setExpensiveBackgroundThrottlingCPUBudget( float cpuBudget) { m_expensiveBackgroundThrottlingCPUBudget = cpuBudget; } void WebSettingsImpl::setExpensiveBackgroundThrottlingInitialBudget( float initialBudget) { m_expensiveBackgroundThrottlingInitialBudget = initialBudget; } void WebSettingsImpl::setExpensiveBackgroundThrottlingMaxBudget( float maxBudget) { m_expensiveBackgroundThrottlingMaxBudget = maxBudget; } void WebSettingsImpl::setExpensiveBackgroundThrottlingMaxDelay(float maxDelay) { m_expensiveBackgroundThrottlingMaxDelay = maxDelay; } } // namespace blink
552215813f79a4748a59f74c2dfffb9e66de3d01
f35d380e37e54a73eccd3725e15f4d4ced11c70a
/Point.cpp
24dcbef5e72085478ad99aa226112aadbecc1dee
[]
no_license
AkashAli506/Asteroids
188e155f9849eb1f6e3206d6784ff5d82f77836c
d8b505b5388e4084b952226aab6dd067c107014c
refs/heads/master
2021-09-08T18:14:28.006901
2021-09-02T04:59:41
2021-09-02T04:59:41
159,933,006
0
0
null
null
null
null
UTF-8
C++
false
false
1,016
cpp
/* * Point.cpp * * Created on: Apr 28, 2018 * Author: akash */ #include "Point.h" Point::Point() { x=0; y=0; } Point::Point (double x1,double y1) { x=x1; y=y1; } Point::Point(Point &a) { x=a.getX(); y=a.getY(); } void Point::assign(double x1,double y1) { x=x1; y=y1; } Point::~Point() { //cout<<"Destructor Called"<<endl;; } void Point::operator=(const Point &obj) { x=obj.x; y=obj.y; } void Point::operator+=(const Point &obj) { x+=obj.x; y+=obj.y; } void Point::operator-=(const Point &obj) { x-=obj.x; y-=obj.y; } Point Point::operator+(const Point &obj) { Point temp; temp.setX(obj.getX()+this->getX()); temp.setY(obj.getY()+this->getY()); return temp; } Point Point::operator-(const Point &obj) { Point temp; temp.setX(obj.getX()-this->getX()); temp.setY(obj.getY()-this->getY()); return temp; } double Point::getX() const { return x; } void Point::setX(double x) { this->x = x; } double Point::getY() const { return y; } void Point::setY(double y) { this->y = y; }
7b9b9c0c5f563cbecdf0b8834c39f8fc0b7cdd03
df3e12ef111c9663d318634468e70a7f7ad322e7
/src/engine/core/test/util/Util.hh
f87dc0694e5a54d8f61230bc28b3795bdee4526b
[ "MIT" ]
permissive
aburgm/freeisle
6fc51933d2c4bbc50fcdd34cb5228293dacedda1
5175897b31e471b4cf9bc2a9be7a88f8b4201d2a
refs/heads/master
2023-08-31T23:29:11.059159
2021-10-21T20:34:02
2021-10-21T20:34:02
367,865,333
1
0
MIT
2021-10-20T21:20:56
2021-05-16T11:49:08
C++
UTF-8
C++
false
false
1,404
hh
#pragma once // TODO(armin): this is available in gtest post 1.10: #define ASSERT_THROW_KEEP_AS_E(statement, expected_exception) \ std::exception_ptr _exceptionPtr; \ try { \ (statement); \ FAIL() << "Expected: " #statement \ " throws an exception of type " #expected_exception \ ".\n Actual: it throws nothing."; \ } catch (expected_exception const &) { \ _exceptionPtr = std::current_exception(); \ } catch (...) { \ FAIL() << "Expected: " #statement \ " throws an exception of type " #expected_exception \ ".\n Actual: it throws a different type."; \ } \ try { \ std::rethrow_exception(_exceptionPtr); \ } catch (expected_exception const &e)
057f9cc1711fa5a2edab4b3c710d4370411ad304
53304e9a309facace5c90d17110abf6265bf9f13
/String Algorithms/Distinct Substrings.cpp
8bfbd37c6b90f027c712a7097bce928bafd4fbdc
[]
no_license
shankar9834/CSES-Solutions
88d78a5d14e09da69422c6912c09f7bad9652977
d2ea7dda34c3e68cea9e33fee4c547a625dcb493
refs/heads/main
2023-08-02T16:10:27.800444
2021-09-21T07:35:46
2021-09-21T07:35:46
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,408
cpp
#include <bits/stdc++.h> using namespace std; typedef long long ll; const int maxN = 1e5+5; struct Node { ll dp; int len, link; map<char,int> nxt; } node[2*maxN]; char S[maxN]; int N, sz, last; void init(){ node[0].len = 0; node[0].link = -1; sz = 1; last = 0; } void extend(char c){ int cur = sz++; node[cur].len = node[last].len + 1; int p = last; while(p != -1 && !node[p].nxt.count(c)){ node[p].nxt[c] = cur; p = node[p].link; } if(p == -1){ node[cur].link = 0; } else { int q = node[p].nxt[c]; if(node[p].len + 1 == node[q].len){ node[cur].link = q; } else { int clone = sz++; node[clone].len = node[p].len + 1; node[clone].nxt = node[q].nxt; node[clone].link = node[q].link; while(p != -1 && node[p].nxt[c] == q){ node[p].nxt[c] = clone; p = node[p].link; } node[q].link = node[cur].link = clone; } } last = cur; } void calc(int u = 0){ node[u].dp = 1; for(const auto& [c, v] : node[u].nxt){ if(!node[v].dp) calc(v); node[u].dp += node[v].dp; } } int main(){ scanf(" %s", S); N = strlen(S); init(); for(int i = 0; i < N; i++) extend(S[i]); calc(); printf("%lld\n", node[0].dp-1); }
11269c087f53aa5572fab9394a3c22cd36ebe592
1ec151d941d66910777ac6671599a9bb08d4c4eb
/inc/geometries/simple_orthogonal.h
9d0d512cc33b570c649e23764534ebe3de2c2ee6
[ "MIT", "LicenseRef-scancode-other-permissive", "Apache-2.0" ]
permissive
albertbsc/feltor
55f294d1fb9d4e01a3e37c9cf8b20479557c0c78
6df8646741f95b0f5d2bcd02085f163bf5c5f19d
refs/heads/develop
2021-01-20T02:54:58.256203
2017-04-26T10:19:33
2017-04-26T10:19:33
89,467,307
1
0
null
2017-04-26T10:12:26
2017-04-26T10:12:26
null
UTF-8
C++
false
false
15,907
h
#pragma once #include "dg/backend/grid.h" #include "dg/backend/functions.h" #include "dg/backend/interpolation.cuh" #include "dg/backend/operator.h" #include "dg/backend/derivatives.h" #include "dg/functors.h" #include "dg/runge_kutta.h" #include "dg/nullstelle.h" #include "dg/geometry.h" #include "utilities.h" namespace dg { namespace geo { ///@cond namespace orthogonal { namespace detail { //This leightweights struct and its methods finds the initial R and Z values and the coresponding f(\psi) as //good as it can, i.e. until machine precision is reached template< class Psi, class PsiX, class PsiY> struct Fpsi { //firstline = 0 -> conformal, firstline = 1 -> equalarc Fpsi( Psi psi, PsiX psiX, PsiY psiY, double x0, double y0, int firstline): psip_(psi), fieldRZYTconf_(psiX, psiY, x0, y0),fieldRZYTequl_(psiX, psiY, x0, y0), fieldRZtau_(psiX, psiY) { X_init = x0, Y_init = y0; while( fabs( psiX(X_init, Y_init)) <= 1e-10 && fabs( psiY( X_init, Y_init)) <= 1e-10) X_init += 1.; firstline_ = firstline; } //finds the starting points for the integration in y direction void find_initial( double psi, double& R_0, double& Z_0) { unsigned N = 50; thrust::host_vector<double> begin2d( 2, 0), end2d( begin2d), end2d_old(begin2d); begin2d[0] = end2d[0] = end2d_old[0] = X_init; begin2d[1] = end2d[1] = end2d_old[1] = Y_init; double eps = 1e10, eps_old = 2e10; while( (eps < eps_old || eps > 1e-7) && eps > 1e-14) { eps_old = eps; end2d_old = end2d; N*=2; dg::stepperRK17( fieldRZtau_, begin2d, end2d, psip_(X_init, Y_init), psi, N); eps = sqrt( (end2d[0]-end2d_old[0])*(end2d[0]-end2d_old[0]) + (end2d[1]-end2d_old[1])*(end2d[1]-end2d_old[1])); } X_init = R_0 = end2d_old[0], Y_init = Z_0 = end2d_old[1]; //std::cout << "In init function error: psi(R,Z)-psi0: "<<psip_(X_init, Y_init)-psi<<"\n"; } //compute f for a given psi between psi0 and psi1 double construct_f( double psi, double& R_0, double& Z_0) { find_initial( psi, R_0, Z_0); thrust::host_vector<double> begin( 3, 0), end(begin), end_old(begin); begin[0] = R_0, begin[1] = Z_0; double eps = 1e10, eps_old = 2e10; unsigned N = 50; while( (eps < eps_old || eps > 1e-7)&& eps > 1e-14) { eps_old = eps, end_old = end; N*=2; if( firstline_ == 0) dg::stepperRK17( fieldRZYTconf_, begin, end, 0., 2*M_PI, N); if( firstline_ == 1) dg::stepperRK17( fieldRZYTequl_, begin, end, 0., 2*M_PI, N); eps = sqrt( (end[0]-begin[0])*(end[0]-begin[0]) + (end[1]-begin[1])*(end[1]-begin[1])); } //std::cout << "\t error "<<eps<<" with "<<N<<" steps\t"; //std::cout <<end_old[2] << " "<<end[2] << "error in y is "<<y_eps<<"\n"; double f_psi = 2.*M_PI/end_old[2]; return f_psi; } double operator()( double psi) { double R_0, Z_0; return construct_f( psi, R_0, Z_0); } private: int firstline_; double X_init, Y_init; Psi psip_; dg::geo::ribeiro::FieldRZYT<PsiX, PsiY> fieldRZYTconf_; dg::geo::equalarc::FieldRZYT<PsiX, PsiY> fieldRZYTequl_; dg::geo::FieldRZtau<PsiX, PsiY> fieldRZtau_; }; //compute the vector of r and z - values that form one psi surface //assumes y_0 = 0 template <class PsiX, class PsiY> void compute_rzy( PsiX psiX, PsiY psiY, const thrust::host_vector<double>& y_vec, thrust::host_vector<double>& r, thrust::host_vector<double>& z, double R_0, double Z_0, double f_psi, int mode ) { thrust::host_vector<double> r_old(y_vec.size(), 0), r_diff( r_old); thrust::host_vector<double> z_old(y_vec.size(), 0), z_diff( z_old); r.resize( y_vec.size()), z.resize(y_vec.size()); thrust::host_vector<double> begin( 2, 0), end(begin), temp(begin); begin[0] = R_0, begin[1] = Z_0; //std::cout <<f_psi<<" "<<" "<< begin[0] << " "<<begin[1]<<"\t"; dg::geo::ribeiro::FieldRZY<PsiX, PsiY> fieldRZYconf(psiX, psiY); dg::geo::equalarc::FieldRZY<PsiX, PsiY> fieldRZYequi(psiX, psiY); fieldRZYconf.set_f(f_psi); fieldRZYequi.set_f(f_psi); unsigned steps = 1; double eps = 1e10, eps_old=2e10; while( (eps < eps_old||eps > 1e-7) && eps > 1e-14) { //begin is left const eps_old = eps, r_old = r, z_old = z; if(mode==0)dg::stepperRK17( fieldRZYconf, begin, end, 0, y_vec[0], steps); if(mode==1)dg::stepperRK17( fieldRZYequi, begin, end, 0, y_vec[0], steps); r[0] = end[0], z[0] = end[1]; for( unsigned i=1; i<y_vec.size(); i++) { temp = end; if(mode==0)dg::stepperRK17( fieldRZYconf, temp, end, y_vec[i-1], y_vec[i], steps); if(mode==1)dg::stepperRK17( fieldRZYequi, temp, end, y_vec[i-1], y_vec[i], steps); r[i] = end[0], z[i] = end[1]; } //compute error in R,Z only dg::blas1::axpby( 1., r, -1., r_old, r_diff); dg::blas1::axpby( 1., z, -1., z_old, z_diff); double er = dg::blas1::dot( r_diff, r_diff); double ez = dg::blas1::dot( z_diff, z_diff); double ar = dg::blas1::dot( r, r); double az = dg::blas1::dot( z, z); eps = sqrt( er + ez)/sqrt(ar+az); //std::cout << "rel. error is "<<eps<<" with "<<steps<<" steps\n"; //temp = end; //if(mode==0)dg::stepperRK17( fieldRZYconf, temp, end, y_vec[y_vec.size()-1], 2.*M_PI, steps); //if(mode==1)dg::stepperRK17( fieldRZYequi, temp, end, y_vec[y_vec.size()-1], 2.*M_PI, steps); //std::cout << "abs. error is "<<sqrt( (end[0]-begin[0])*(end[0]-begin[0]) + (end[1]-begin[1])*(end[1]-begin[1]))<<"\n"; steps*=2; } r = r_old, z = z_old; } //This struct computes -2pi/f with a fixed number of steps for all psi //and provides the Nemov algorithm for orthogonal grid //template< class PsiX, class PsiY, class PsiXX, class PsiXY, class PsiYY, class LaplacePsiX, class LaplacePsiY> template< class PsiX, class PsiY, class LaplacePsi> struct Nemov { Nemov( PsiX psiX, PsiY psiY, LaplacePsi laplacePsi, double f0, int mode): f0_(f0), mode_(mode), psipR_(psiX), psipZ_(psiY), laplacePsip_( laplacePsi) { } void initialize( const thrust::host_vector<double>& r_init, //1d intial values const thrust::host_vector<double>& z_init, //1d intial values thrust::host_vector<double>& h_init) //, // thrust::host_vector<double>& hr_init, // thrust::host_vector<double>& hz_init) { unsigned size = r_init.size(); h_init.resize( size);//, hr_init.resize( size), hz_init.resize( size); for( unsigned i=0; i<size; i++) { if(mode_ == 0) h_init[i] = f0_; if(mode_ == 1) { double psipR = psipR_(r_init[i], z_init[i]), psipZ = psipZ_(r_init[i], z_init[i]); double psip2 = (psipR*psipR+psipZ*psipZ); h_init[i] = f0_/sqrt(psip2); //equalarc } //double laplace = psipRR_(r_init[i], z_init[i]) + //psipZZ_(r_init[i], z_init[i]); //hr_init[i] = -f0_*laplace/psip2*psipR; //hz_init[i] = -f0_*laplace/psip2*psipZ; } } void operator()(const std::vector<thrust::host_vector<double> >& y, std::vector<thrust::host_vector<double> >& yp) { //y[0] = R, y[1] = Z, y[2] = h, y[3] = hr, y[4] = hz unsigned size = y[0].size(); double psipR, psipZ, psip2; for( unsigned i=0; i<size; i++) { psipR = psipR_(y[0][i], y[1][i]), psipZ = psipZ_(y[0][i], y[1][i]); //psipRR = psipRR_(y[0][i], y[1][i]), psipRZ = psipRZ_(y[0][i], y[1][i]), psipZZ = psipZZ_(y[0][i], y[1][i]); psip2 = f0_*(psipR*psipR+psipZ*psipZ); yp[0][i] = psipR/psip2; yp[1][i] = psipZ/psip2; yp[2][i] = y[2][i]*( -laplacePsip_(y[0][i], y[1][i]) )/psip2; //yp[3][i] = ( -(2.*psipRR+psipZZ)*y[3][i] - psipRZ*y[4][i] - laplacePsipR_(y[0][i], y[1][i])*y[2][i])/psip2; //yp[4][i] = ( -psipRZ*y[3][i] - (2.*psipZZ+psipRR)*y[4][i] - laplacePsipZ_(y[0][i], y[1][i])*y[2][i])/psip2; } } private: double f0_; int mode_; PsiX psipR_; PsiY psipZ_; LaplacePsi laplacePsip_; }; template<class Nemov> void construct_rz( Nemov nemov, double x_0, //the x value that corresponds to the first psi surface const thrust::host_vector<double>& x_vec, //1d x values const thrust::host_vector<double>& r_init, //1d intial values of the first psi surface const thrust::host_vector<double>& z_init, //1d intial values of the first psi surface thrust::host_vector<double>& r, thrust::host_vector<double>& z, thrust::host_vector<double>& h//, //thrust::host_vector<double>& hr, //thrust::host_vector<double>& hz ) { unsigned N = 1; double eps = 1e10, eps_old=2e10; std::vector<thrust::host_vector<double> > begin(3); //begin(5); thrust::host_vector<double> h_init( r_init.size(), 0.); //thrust::host_vector<double> h_init, hr_init, hz_init; nemov.initialize( r_init, z_init, h_init);//, hr_init, hz_init); begin[0] = r_init, begin[1] = z_init, begin[2] = h_init; //begin[3] = hr_init, begin[4] = hz_init; //now we have the starting values std::vector<thrust::host_vector<double> > end(begin), temp(begin); unsigned sizeX = x_vec.size(), sizeY = r_init.size(); unsigned size2d = x_vec.size()*r_init.size(); r.resize(size2d), z.resize(size2d), h.resize(size2d); //hr.resize(size2d), hz.resize(size2d); double x0=x_0, x1 = x_vec[0]; thrust::host_vector<double> r_old(r), r_diff( r), z_old(z), z_diff(z); while( (eps < eps_old || eps > 1e-6) && eps > 1e-13) { r_old = r, z_old = z; eps_old = eps; temp = begin; ////////////////////////////////////////////////// for( unsigned i=0; i<sizeX; i++) { x0 = i==0?x_0:x_vec[i-1], x1 = x_vec[i]; ////////////////////////////////////////////////// dg::stepperRK17( nemov, temp, end, x0, x1, N); for( unsigned j=0; j<sizeY; j++) { unsigned idx = j*sizeX+i; r[idx] = end[0][j], z[idx] = end[1][j]; //hr[idx] = end[3][j], hz[idx] = end[4][j]; h[idx] = end[2][j]; } ////////////////////////////////////////////////// temp = end; } dg::blas1::axpby( 1., r, -1., r_old, r_diff); dg::blas1::axpby( 1., z, -1., z_old, z_diff); dg::blas1::pointwiseDot( r_diff, r_diff, r_diff); dg::blas1::pointwiseDot( 1., z_diff, z_diff, 1., r_diff); eps = sqrt( dg::blas1::dot( r_diff, r_diff)/sizeX/sizeY); //should be relative to the interpoint distances //std::cout << "Effective Absolute diff error is "<<eps<<" with "<<N<<" steps\n"; N*=2; } } } //namespace detail }//namespace orthogonal ///@endcond /** * @brief Generate a simple orthogonal grid * * Psi is the radial coordinate and you can choose various discretizations of the first line * @ingroup generators * @tparam Psi All the template parameters must model a Binary-operator i.e. the bracket operator() must be callable with two arguments and return a double. */ template< class Psi, class PsiX, class PsiY, class LaplacePsi> struct SimpleOrthogonal { /** * @brief Construct a simple orthogonal grid * * @param psi \f$\psi(x,y)\f$ is the flux function in Cartesian coordinates (x,y) * @param psiX \f$ \psi_x\f$ is its derivative in x * @param psiY \f$ \psi_y\f$ ... * @param laplacePsi \f$ \Delta\psi\f$ * @param psi_0 first boundary * @param psi_1 second boundary * @param x0 a point in the inside of the ring bounded by psi0 (shouldn't be the O-point) * @param y0 a point in the inside of the ring bounded by psi0 (shouldn't be the O-point) * @param firstline This parameter indicates the adaption type used to create the orthogonal grid: 0 is no adaption, 1 is an equalarc adaption */ SimpleOrthogonal( Psi psi, PsiX psiX, PsiY psiY, LaplacePsi laplacePsi, double psi_0, double psi_1, double x0, double y0, int firstline =0): psiX_(psiX), psiY_(psiY), laplacePsi_(laplacePsi) { assert( psi_1 != psi_0); firstline_ = firstline; orthogonal::detail::Fpsi<Psi, PsiX, PsiY> fpsi(psi, psiX, psiY, x0, y0, firstline); f0_ = fabs( fpsi.construct_f( psi_0, R0_, Z0_)); if( psi_1 < psi_0) f0_*=-1; lz_ = f0_*(psi_1-psi_0); } /** * @brief The grid constant * * @return f_0 is the grid constant s.a. width() ) */ double f0() const{return f0_;} /** * @brief The length of the zeta-domain * * Call before discretizing the zeta domain * @return length of zeta-domain (f0*(psi_1-psi_0)) * @note the length is always positive */ double width() const{return lz_;} /** * @brief 2pi (length of the eta domain) * * Always returns 2pi * @return 2pi */ double height() const{return 2.*M_PI;} /** * @brief Indicate orthogonality * * @return true */ bool isOrthogonal() const{return true;} /** * @brief Indicate conformity * * @return false */ bool isConformal() const{return false;} /** * @brief Generate the points and the elements of the Jacobian * * Call the width() and height() function before calling this function! * @param zeta1d one-dimensional list of points inside the zeta-domain (0<zeta<width()) * @param eta1d one-dimensional list of points inside the eta-domain (0<eta<height()) * @param x \f$= x(\zeta,\eta)\f$ * @param y \f$= y(\zeta,\eta)\f$ * @param zetaX \f$= \zeta_x(\zeta,\eta)\f$ * @param zetaY \f$= \zeta_y(\zeta,\eta)\f$ * @param etaX \f$= \eta_x(\zeta,\eta)\f$ * @param etaY \f$= \eta_y(\zeta,\eta)\f$ * @note All the resulting vectors are write-only and get properly resized * @note The \f$ \zeta\f$ direction is continuous in memory */ void operator()( const thrust::host_vector<double>& zeta1d, const thrust::host_vector<double>& eta1d, thrust::host_vector<double>& x, thrust::host_vector<double>& y, thrust::host_vector<double>& zetaX, thrust::host_vector<double>& zetaY, thrust::host_vector<double>& etaX, thrust::host_vector<double>& etaY) { thrust::host_vector<double> r_init, z_init; orthogonal::detail::compute_rzy( psiX_, psiY_, eta1d, r_init, z_init, R0_, Z0_, f0_, firstline_); orthogonal::detail::Nemov<PsiX, PsiY, LaplacePsi> nemov(psiX_, psiY_, laplacePsi_, f0_, firstline_); thrust::host_vector<double> h; orthogonal::detail::construct_rz(nemov, 0., zeta1d, r_init, z_init, x, y, h); unsigned size = x.size(); zetaX.resize(size), zetaY.resize(size), etaX.resize(size), etaY.resize(size); for( unsigned idx=0; idx<size; idx++) { double psipR = psiX_(x[idx], y[idx]); double psipZ = psiY_(x[idx], y[idx]); zetaX[idx] = f0_*psipR; zetaY[idx] = f0_*psipZ; etaX[idx] = -h[idx]*psipZ; etaY[idx] = +h[idx]*psipR; } } private: PsiX psiX_; PsiY psiY_; LaplacePsi laplacePsi_; double f0_, lz_, R0_, Z0_; int firstline_; }; }//namespace geo }//namespace dg
445a73b25d6248be6ab9b7d7294d12cf85dfc62a
f53c4616616c2b6b7a3dce94174c477255c600d1
/TowerAttack/Projectile.h
53812fa87e16fb0042f9c5ba78404f017619880c
[]
no_license
stompuri/TowerAttack
c1c4b6e26832dd61da78c6b6162e55edac25e77b
77e7e6e226bacc33caeff043fc6f16290f08173f
refs/heads/master
2020-12-24T16:06:38.996528
2016-03-10T12:43:16
2016-03-10T12:43:16
20,258,703
1
0
null
null
null
null
UTF-8
C++
false
false
893
h
#pragma once #include "GameObject.h" // Parent class #include <memory> #define _USE_MATH_DEFINES #include <math.h> namespace TA { class Projectile : public GameObject { public: Projectile(); // Constructor for empty object Projectile(sf::Vector2f _position, float _rotation, unsigned int _parentId); // Constructor which takes in different information for the object ~Projectile(); // For writing/reading to/from binary file Projectile(std::istream & is); // Constructor for loading data from binary file void serialise(std::ostream & os ); // Method to save object into binary file void Update(float elapsedTime); // Update method for the object, which is called once in every game loop iteration std::string GetType(); // Return the type of the game object (Character, Tower, Projectile,...) private: unsigned int parentId; // objectId of the parent (tower) }; }
3e7c2e5f75d050a88c8ee77e46a55841181d6505
56f58b40a3c5cf8d2c3237452a824e136f9e7721
/backend/controllers/PlaceOrderController.cpp
13a3e8092fecff7d664a8133393dd83d2bcb8a21
[]
no_license
NVKShop/nvk-client
a980bf14bf6c32a3cccba72414e980d320ca551b
968a9fddebee9cb4d3bf7d5a52d5656ba6ee9981
refs/heads/master
2020-02-26T16:02:27.227207
2016-12-20T10:42:28
2016-12-20T10:42:28
71,004,379
0
0
null
null
null
null
UTF-8
C++
false
false
2,639
cpp
#include "PlaceOrderController.h" #include <QMessageBox> #include <QTableWidget> #include <QSpinBox> #include <QDebug> #include <QJsonDocument> #include <QJsonObject> PlaceOrderController::PlaceOrderController(QObject *parent) : QObject(parent), m_placeOrderWindow(new PlaceOrderWindow), m_placeOrderHandler(new HttpHandler) { connect(m_placeOrderWindow, &PlaceOrderWindow::resetCart, this, &PlaceOrderController::resetCart); connect(m_placeOrderWindow, &PlaceOrderWindow::placeOrderButtonClicked, this, &PlaceOrderController::placeOrder); connect(m_placeOrderWindow, &PlaceOrderWindow::cartCellChanged, this, &PlaceOrderController::cartCellChanged); connect(m_placeOrderHandler, &HttpHandler::finished, this, &PlaceOrderController::resetCart); connect(m_placeOrderHandler, &HttpHandler::finished, view(), &PlaceOrderWindow::accept); connect(m_placeOrderHandler, &HttpHandler::replyErrors, this, &PlaceOrderController::orderPlacementFailed); } PlaceOrderWindow* PlaceOrderController::view() const { return m_placeOrderWindow; } void PlaceOrderController::setOrder(Order *order) { m_placeOrderWindow->setOrder(order); } PlaceOrderController::~PlaceOrderController() { delete m_placeOrderWindow; } void PlaceOrderController::placeOrder() { if (view()->order()->user()->cart()->products().size() == 0 ) { QMessageBox::warning(0, "Error placing order", "Can't place an empty order!"); } else { QUrl placeOrderUrl(HttpHandler::ORDER_PLACEMENT_URL_STRING); m_placeOrderHandler->setUrl(placeOrderUrl); m_placeOrderHandler->request()->setRawHeader("Content-Type", "application/json"); m_placeOrderHandler->setUser(view()->order()->user()->properties().name()); m_placeOrderHandler->setPassword(view()->order()->user()->properties().password()); QByteArray orderstr = m_placeOrderWindow->order()->asJson().toJson(QJsonDocument::Compact); m_placeOrderHandler->sendRequest(orderstr); } } void PlaceOrderController::resetCart() { m_placeOrderWindow->order()->user()->cart()->resetCart(); setOrder(m_placeOrderWindow->order()); emit setQuantityText(0); } void PlaceOrderController::cartCellChanged(int row, int val) { m_placeOrderWindow->order()->user()->cart()->products()[row]->setQuantity(val); setOrder(m_placeOrderWindow->order()); emit setQuantityText(m_placeOrderWindow->order()->productsCount()); } void PlaceOrderController::orderPlacementFailed(const int &code) { QMessageBox::warning(0, "Error placing order", m_placeOrderHandler->reply()->errorString()); Q_UNUSED(code) }
b9e7417278ef3252a278a574c27b9a3888d054d5
dd949f215d968f2ee69bf85571fd63e4f085a869
/schools/css-2010/team-violet/subarchitectures/spatial.sa/src/c++/LocalMapManager.cpp
a5decabc7863e9f7de3b1f9e210e97161611f300
[]
no_license
marc-hanheide/cogx
a3fd395805f1b0ad7d713a05b9256312757b37a9
cb9a9c9cdfeba02afac6a83d03b7c6bb778edb95
refs/heads/master
2022-03-16T23:36:21.951317
2013-12-10T23:49:07
2013-12-10T23:49:07
219,460,352
1
2
null
null
null
null
UTF-8
C++
false
false
19,592
cpp
// // = FILENAME // LocalMapManager.cpp // // = FUNCTION // // = AUTHOR(S) // Kristoffer Sjöö // // = COPYRIGHT // Copyright (c) 2009 Kristoffer Sjöö // /*----------------------------------------------------------------------*/ #include "LocalMapManager.hpp" #include <CureHWUtils.hpp> #include <cast/architecture/ChangeFilterFactory.hpp> #include <AddressBank/ConfigFileReader.hh> #include <RobotbaseClientUtils.hpp> #include <float.h> #include <NavX/XDisplayLocalGridMap.hh> using namespace cast; using namespace std; using namespace boost; using namespace spatial; /** * The function called to create a new instance of our component. * * Taken from zwork */ extern "C" { cast::interfaces::CASTComponentPtr newComponent() { return new LocalMapManager(); } } LocalMapManager::LocalMapManager() { m_RobotServerHost = "localhost"; } LocalMapManager::~LocalMapManager() { delete m_Displaylgm1; delete m_Displaylgm2; delete m_Glrt1; delete m_Glrt2; for (map<int, Cure::LocalGridMap<unsigned char> *>::iterator it = m_nodeGridMaps.begin(); it != m_nodeGridMaps.end(); it++) { delete it->second; } delete m_lgm2; if (m_isUsingSeparateGridMaps) { delete m_Glrt1_alt; delete m_Glrt2_alt; for (map<int, Cure::LocalGridMap<unsigned char> *>::iterator it = m_nodeGridMapsAlt.begin(); it != m_nodeGridMapsAlt.end(); it++) { delete it->second; } delete m_lgm2_alt; } } void LocalMapManager::configure(const map<string,string>& _config) { map<string,string>::const_iterator it = _config.find("-c"); if (it== _config.end()) { println("configure(...) Need config file (use -c option)\n"); std::abort(); } std::string configfile = it->second; Cure::ConfigFileReader cfg; if (cfg.init(configfile)) { println("configure(...) Failed to open with \"%s\"\n", configfile.c_str()); std::abort(); } if (cfg.getSensorPose(1, m_LaserPoseR)) { println("configure(...) Failed to get sensor pose"); std::abort(); } m_MaxLaserRangeForPlaceholders = 5.0; m_MaxLaserRangeForCombinedMaps = 5.0; it = _config.find("--laser-range"); if (it != _config.end()) { m_MaxLaserRangeForPlaceholders = (atof(it->second.c_str())); m_MaxLaserRangeForCombinedMaps = m_MaxLaserRangeForPlaceholders; } else { it = _config.find("--laser-range-for-placeholders"); if (it != _config.end()) { m_MaxLaserRangeForPlaceholders = (atof(it->second.c_str())); } it = _config.find("--laser-range-for-combined-maps"); if (it != _config.end()) { m_MaxLaserRangeForCombinedMaps = (atof(it->second.c_str())); } } m_isUsingSeparateGridMaps = m_MaxLaserRangeForPlaceholders != m_MaxLaserRangeForCombinedMaps; it = _config.find("--robot-server-host"); if (it != _config.end()) { std::istringstream str(it->second); str >> m_RobotServerHost; } m_lgm1 = new Cure::LocalGridMap<unsigned char>(70, 0.1, '2', Cure::LocalGridMap<unsigned char>::MAP1); m_nodeGridMaps[0] = m_lgm1; m_Glrt1 = new Cure::GridLineRayTracer<unsigned char>(*m_lgm1); m_lgm2 = new Cure::LocalGridMap<unsigned char>(70, 0.1, '2', Cure::LocalGridMap<unsigned char>::MAP1); m_Glrt2 = new Cure::GridLineRayTracer<unsigned char>(*m_lgm2); if (_config.find("--no-tentative-window") == _config.end()) { m_Displaylgm2 = new Cure::XDisplayLocalGridMap<unsigned char>(*m_lgm2); println("Will use X window to show the tentative local map"); } else { m_Displaylgm2 = 0; println("Will NOT use X window to show the tentative local map"); } if (_config.find("--no-local-map-window") == _config.end()) { m_Displaylgm1 = new Cure::XDisplayLocalGridMap<unsigned char>(*m_lgm1); println("Will use X window to show the current local map"); } else { m_Displaylgm1 = 0; println("Will NOT use X window to show the current local map"); } if (m_isUsingSeparateGridMaps) { m_lgm1_alt = new Cure::LocalGridMap<unsigned char>(70, 0.1, '2', Cure::LocalGridMap<unsigned char>::MAP1); m_nodeGridMapsAlt[0] = m_lgm1_alt; m_Glrt1_alt = new Cure::GridLineRayTracer<unsigned char>(*m_lgm1_alt); m_lgm2_alt = new Cure::LocalGridMap<unsigned char>(70, 0.1, '2', Cure::LocalGridMap<unsigned char>::MAP1); m_Glrt2_alt = new Cure::GridLineRayTracer<unsigned char>(*m_lgm2_alt); } m_RobotServer = RobotbaseClientUtils::getServerPrx(*this, m_RobotServerHost); FrontierInterface::HypothesisEvaluatorPtr servant = new EvaluationServer(this); registerIceServer<FrontierInterface::HypothesisEvaluator, FrontierInterface::HypothesisEvaluator>(servant); FrontierInterface::LocalMapInterfacePtr mapservant = new LocalMapServer(this); registerIceServer<FrontierInterface::LocalMapInterface, FrontierInterface::LocalMapInterface>(mapservant); } void LocalMapManager::start() { addChangeFilter(createLocalTypeFilter<NavData::RobotPose2d>(cdl::ADD), new MemberFunctionChangeReceiver<LocalMapManager>(this, &LocalMapManager::newRobotPose)); addChangeFilter(createLocalTypeFilter<NavData::RobotPose2d>(cdl::OVERWRITE), new MemberFunctionChangeReceiver<LocalMapManager>(this, &LocalMapManager::newRobotPose)); m_placeInterface = getIceServer<FrontierInterface::PlaceInterface>("place.manager"); log("LocalMapManager started"); } void LocalMapManager::runComponent() { setupPushScan2d(*this, 0.1); setupPushOdometry(*this); log("I am running!"); NavData::FNodePtr curNode = getCurrentNavNode(); int prevNode = -1; while(isRunning()){ debug("lock in isRunning"); lockComponent(); //Don't allow any interface calls while processing a callback curNode = getCurrentNavNode(); if (curNode != 0) { if (curNode->nodeId != prevNode) { m_Mutex.lock(); // Node has changed! See if the node already has a lgm associated // with it; if so, swap the current for it. Otherwise, // assign the temporary to it. if (m_nodeGridMaps.find(curNode->nodeId) == m_nodeGridMaps.end()) { // There's no grid map for the current Node. Assign the // temporary lgm to it. m_nodeGridMaps[curNode->nodeId] = m_lgm2; log("Movin'"); m_lgm2->moveCenterTo(curNode->x, curNode->y); m_lgm1 = m_lgm2; log("Allocatin'"); m_lgm2 = new Cure::LocalGridMap<unsigned char>(70, 0.1, '2', Cure::LocalGridMap<unsigned char>::MAP1, curNode->x, curNode->y); if (m_isUsingSeparateGridMaps) { m_nodeGridMapsAlt[curNode->nodeId] = m_lgm2_alt; m_lgm2_alt->moveCenterTo(curNode->x, curNode->y); m_lgm1_alt = m_lgm2_alt; m_lgm2_alt = new Cure::LocalGridMap<unsigned char>(70, 0.1, '2', Cure::LocalGridMap<unsigned char>::MAP1, curNode->x, curNode->y); } } else { // Clear the temporary lgm m_lgm1 = m_nodeGridMaps[curNode->nodeId]; log("Clearin'"); m_lgm2->clearMap(); log("Movin' 2"); m_lgm2->moveCenterTo(curNode->x, curNode->y, false); if (m_isUsingSeparateGridMaps){ m_lgm1_alt = m_nodeGridMapsAlt[curNode->nodeId]; m_lgm2_alt->clearMap(); m_lgm2_alt->moveCenterTo(curNode->x, curNode->y, false); } } delete m_Glrt1; delete m_Glrt2; m_Glrt1 = new Cure::GridLineRayTracer<unsigned char>(*m_lgm1); m_Glrt2 = new Cure::GridLineRayTracer<unsigned char>(*m_lgm2); if (m_isUsingSeparateGridMaps) { delete m_Glrt1_alt; delete m_Glrt2_alt; m_Glrt1_alt = new Cure::GridLineRayTracer<unsigned char>(*m_lgm1_alt); m_Glrt2_alt = new Cure::GridLineRayTracer<unsigned char>(*m_lgm2_alt); } if (m_Displaylgm1) { //m_Displaylgm1 = new Cure::XDisplayLocalGridMap<unsigned char>(*m_lgm1); m_Displaylgm1->setMap(m_lgm1); } if (m_Displaylgm2) { m_Displaylgm2->setMap(m_lgm2); } //log("Maps set"); m_Mutex.unlock(); } prevNode = curNode->nodeId; //log("Updatin'"); if (m_Displaylgm1) { Cure::Pose3D currentPose = m_TOPP.getPose(); m_Displaylgm1->updateDisplay(&currentPose); } if (m_Displaylgm2) { Cure::Pose3D currentPose = m_TOPP.getPose(); m_Displaylgm2->updateDisplay(&currentPose); } //log("Updated"); } unlockComponent(); debug("unlock in isRunning"); usleep(250000); } } void LocalMapManager::newRobotPose(const cdl::WorkingMemoryChange &objID) { shared_ptr<CASTData<NavData::RobotPose2d> > oobj = getWorkingMemoryEntry<NavData::RobotPose2d>(objID.address); //FIXME // m_SlamRobotPose.setTime(Cure::Timestamp(oobj->getData()->time.s, // oobj->getData()->time.us)); m_SlamRobotPose.setX(oobj->getData()->x); m_SlamRobotPose.setY(oobj->getData()->y); m_SlamRobotPose.setTheta(oobj->getData()->theta); Cure::Pose3D cp = m_SlamRobotPose; m_TOPP.defineTransform(cp); } void LocalMapManager::receiveOdometry(const Robotbase::Odometry &castOdom) { lockComponent(); //Don't allow any interface calls while processing a callback Cure::Pose3D cureOdom; CureHWUtils::convOdomToCure(castOdom, cureOdom); debug("Got odometry x=%.2f y=%.2f a=%.4f t=%.6f", cureOdom.getX(), cureOdom.getY(), cureOdom.getTheta(), cureOdom.getTime().getDouble()); m_TOPP.addOdometry(cureOdom); m_CurrPose = m_TOPP.getPose(); unlockComponent(); } void LocalMapManager::receiveScan2d(const Laser::Scan2d &castScan) { lockComponent(); //Don't allow any interface calls while processing a callback debug("Got scan with n=%d and t=%ld.%06ld", castScan.ranges.size(), (long)castScan.time.s, (long)castScan.time.us); Cure::LaserScan2d cureScan; CureHWUtils::convScan2dToCure(castScan, cureScan); if (m_TOPP.isTransformDefined()) { Cure::Pose3D scanPose; if (m_TOPP.getPoseAtTime(cureScan.getTime(), scanPose) == 0) { Cure::Pose3D lpW; lpW.add(scanPose, m_LaserPoseR); m_Mutex.lock(); m_Glrt1->addScan(cureScan, lpW, m_MaxLaserRangeForCombinedMaps); m_Glrt2->addScan(cureScan, lpW, m_MaxLaserRangeForCombinedMaps); if (m_isUsingSeparateGridMaps) { m_Glrt1_alt->addScan(cureScan, lpW, m_MaxLaserRangeForPlaceholders); m_Glrt2_alt->addScan(cureScan, lpW, m_MaxLaserRangeForPlaceholders); } m_firstScanReceived = true; m_Mutex.unlock(); } } unlockComponent(); } NavData::FNodePtr LocalMapManager::getCurrentNavNode() { vector<NavData::FNodePtr> nodes; getMemoryEntries<NavData::FNode>(nodes, 0); vector<NavData::RobotPose2dPtr> robotPoses; getMemoryEntries<NavData::RobotPose2d>(robotPoses, 0); if (robotPoses.size() == 0) { log("Could not find RobotPose!"); return 0; } //Find the node closest to the robotPose double robotX = robotPoses[0]->x; double robotY = robotPoses[0]->y; double minDistance = FLT_MAX; NavData::FNodePtr ret = 0; for (vector<NavData::FNodePtr>::iterator it = nodes.begin(); it != nodes.end(); it++) { double x = (*it)->x; double y = (*it)->y; double distance = (x - robotX)*(x-robotX) + (y-robotY)*(y-robotY); if (distance < minDistance) { ret = *it; minDistance = distance; } } return ret; } FrontierInterface::HypothesisEvaluation LocalMapManager::getHypothesisEvaluation(int hypID) { // Find all hypotheses that have curPlaceID as source place // For each cell free, find which hypothesis or source node is closest // If the requested hypothesis is the one, also check if there are any extant // nodes closer than a threshold. If not, increment the free space value. // If the cell is also on the boundary to unexplored space, increment // the border value. // Then check if the hypothesis is situated in what looks like door-like // environs. while (!m_firstScanReceived) { log("Sleeping, waiting for initial scan"); unlockComponent(); usleep(500000); lockComponent(); } FrontierInterface::HypothesisEvaluation ret; ret.freeSpaceValue = 0; ret.unexploredBorderValue = 0; ret.gatewayValue = 0; vector<FrontierInterface::NodeHypothesisPtr> hyps; getMemoryEntries<FrontierInterface::NodeHypothesis>(hyps); int originPlaceID = -1; double relevantX; double relevantY; for (vector<FrontierInterface::NodeHypothesisPtr>::iterator it = hyps.begin(); it != hyps.end(); it++) { try { if ((*it)->hypID == hypID) { originPlaceID = (*it)-> originPlaceID; relevantX = (*it)->x; relevantY = (*it)->y; break; } } catch (IceUtil::NullHandleException) { log("Hypothesis unexpectedly missing from WM!"); } } vector<FrontierInterface::NodeHypothesisPtr> relevantHypotheses; if (originPlaceID != -1) { for (vector<FrontierInterface::NodeHypothesisPtr>::iterator it = hyps.begin(); it != hyps.end(); it++) { try { if ((*it)->originPlaceID == originPlaceID) { relevantHypotheses.push_back(*it); } } catch (IceUtil::NullHandleException) { log("Hypothesis unexpectedly missing from WM!"); } } log("Relevant hypotheses: %i", relevantHypotheses.size()); vector<NavData::FNodePtr> nodes; getMemoryEntries<NavData::FNode>(nodes); int totalFreeCells = 0; int totalProcessed = 0; //Loop over local grid map double x; double y; m_Mutex.lock(); log("Checkin'"); Cure::LocalGridMap<unsigned char> *propertyLGM = m_isUsingSeparateGridMaps ? m_lgm1_alt : m_lgm1; for (int yi = -propertyLGM->getSize(); yi < propertyLGM->getSize()+1; yi++) { y = propertyLGM->getCentYW() + yi * propertyLGM->getCellSize(); for (int xi = -propertyLGM->getSize(); xi < propertyLGM->getSize()+1; xi++) { x = propertyLGM->getCentXW() + xi * propertyLGM->getCellSize(); if ((*propertyLGM)(xi,yi) == '0') { totalFreeCells++; //Cell is free double relevantDistSq = (x - relevantX)*(x - relevantX) + (y - relevantY)*(y - relevantY); // Check if some other hypothesis from this Place is closer to this // grid cell bool process = true; for(vector<FrontierInterface::NodeHypothesisPtr>::iterator it = relevantHypotheses.begin(); process && it != relevantHypotheses.end(); it++) { if ((*it)->hypID != hypID) { double distSq = (x - (*it)->x)*(x - (*it)->x) + (y - (*it)->y)*(y - (*it)->y); if (distSq < relevantDistSq) process = false; } } if (process) { totalProcessed++; // Check if this cell is within the node creation radius of some // other node for (vector<NavData::FNodePtr>::iterator it2 = nodes.begin(); it2 != nodes.end(); it2++) { try { double distSq = (x - (*it2)->x)*(x - (*it2)->x) + (y - (*it2)->y)*(y - (*it2)->y); if (distSq < 2.0*2.0) process = false; } catch (IceUtil::NullHandleException e) { log("Error! FNode unexpectedly disappeared!"); } } if (process) { //This cell is known to be free, closest to the hypothesis //in question, and not too close to another node. Potential //new node material. ret.freeSpaceValue += 1.0; //Check if it borders on unknown space for (int yi2 = yi - 1; yi2 <= yi + 1; yi2++) { for (int xi2 = xi - 1; xi2 <= xi + 1; xi2++) { if ((*propertyLGM)(xi2, yi2) == '2') { ret.unexploredBorderValue += 1.0; yi2 = yi + 2; xi2 = xi + 2; } } } } } } } } log("Total free cells: %i; total processed %i", totalFreeCells, totalProcessed); m_Mutex.unlock(); } return ret; } FrontierInterface::HypothesisEvaluation LocalMapManager::EvaluationServer::getHypothesisEvaluation(int hypID, const Ice::Current &_context) { m_pOwner->lockComponent(); FrontierInterface::HypothesisEvaluation ret = m_pOwner->getHypothesisEvaluation(hypID); m_pOwner->unlockComponent(); return ret; } FrontierInterface::LocalGridMap LocalMapManager::LocalMapServer::getCombinedGridMap(const SpatialData::PlaceIDSeq &places, const Ice::Current &_context) { m_pOwner->lockComponent(); FrontierInterface::LocalGridMap ret; m_pOwner->log("3"); m_pOwner->getCombinedGridMap(ret, places); m_pOwner->log("4"); m_pOwner->unlockComponent(); return ret; } void LocalMapManager::getCombinedGridMap(FrontierInterface::LocalGridMap &map, const SpatialData::PlaceIDSeq &places) { vector<const Cure::LocalGridMap<unsigned char> *>maps; for (SpatialData::PlaceIDSeq::const_iterator it = places.begin(); it != places.end(); it++) { NavData::FNodePtr node = m_placeInterface->getNodeFromPlaceID(*it); if (node != 0) { if (m_nodeGridMaps.find(node->nodeId) != m_nodeGridMaps.end()) { maps.push_back(m_nodeGridMaps[node->nodeId]); } else { log("Couldn't find grid map for node %d", node->nodeId); } } else { log ("No grid map for Place %d; not a node!", *it); } } if (maps.empty()) { map.size = 0; map.data.clear(); return; } double minx = FLT_MAX; double maxx = -FLT_MAX; double miny = FLT_MAX; double maxy = -FLT_MAX; //Find bounds of the merged grid map for (vector<const Cure::LocalGridMap<unsigned char> *>::iterator it = maps.begin(); it != maps.end(); it++) { double mapminx = (*it)->getCentXW() - (*it)->getSize() * (*it)->getCellSize(); double mapmaxx = (*it)->getCentXW() + (*it)->getSize() * (*it)->getCellSize(); double mapminy = (*it)->getCentYW() - (*it)->getSize() * (*it)->getCellSize(); double mapmaxy = (*it)->getCentYW() + (*it)->getSize() * (*it)->getCellSize(); minx = minx < mapminx ? minx : mapminx; maxx = maxx > mapmaxx ? maxx : mapmaxx; miny = miny < mapminy ? miny : mapminy; maxy = maxy > mapmaxy ? maxy : mapmaxy; } double dsize = maxx-minx; double cellSize = maps[0]->getCellSize(); double cx = (minx+maxx)/2; double cy = (miny+maxy)/2; if (maxy-miny > dsize) dsize = maxy-miny; int newSize = (int)((dsize/2 + cellSize/2) / cellSize); Cure::LocalGridMap<unsigned char> newMap(newSize, cellSize, '2', Cure::LocalGridMap<unsigned char>::MAP1, cx, cy); map.xCenter = cx; map.yCenter = cy; map.cellSize = cellSize; map.size = newSize; map.data.clear(); map.data.reserve(4*newSize*newSize + 4*newSize + 1); //Sample each of the maps into the new map log("Sample each of the maps into the new map"); for (vector<const Cure::LocalGridMap<unsigned char> *>::iterator it = maps.begin(); it != maps.end(); it++) { log("looping over map"); for (int y = -(*it)->getSize(); y <= (*it)->getSize(); y++) { for (int x = -(*it)->getSize(); x <= (*it)->getSize(); x++) { char val = (**it)(x,y); if (val != '2') { double dx, dy; (*it)->index2WorldCoords(x, y, dx, dy); int nx, ny; if (newMap.worldCoords2Index(dx, dy, nx, ny)) { log("Error! bounds incorrect in getCombinedGridMaps!"); } else { if (newMap(nx, ny) == '2' || newMap(nx, ny) == '0') { newMap(nx, ny) = val; } } } } } } for (int x = -newSize ; x <= newSize; x++){ for (int y = -newSize ; y <= newSize; y++){ map.data.push_back(newMap(x,y)); } } Cure::LocalGridMap<unsigned char> newMap2(newSize, cellSize, '2', Cure::LocalGridMap<unsigned char>::MAP1, cx, cy); int lp = 0; for(int x = -map.size ; x <= map.size; x++){ for(int y = -map.size ; y <= map.size; y++){ (newMap2)(x,y) = map.data[lp]; lp++; } } Cure::XDisplayLocalGridMap<unsigned char>* m_Displaykrsjlgm; m_Displaykrsjlgm = new Cure::XDisplayLocalGridMap<unsigned char>(newMap2); m_Displaykrsjlgm->updateDisplay(); }
44b66c77717cdf2b847184f8ed6f07b697faf901
0e8df1125b13efb53aa66be64bdb43e7f7a0ad67
/src/performance.cpp
166d5cb03f4ab782ddae59e7cdad62b5bf1099e2
[]
no_license
erikpeter/fbroc
1be48bbfcbc1b29a5df79ba33b5dab974fdeff0e
14dbfa1750ab4093b64228316c002d357656786e
refs/heads/master
2021-01-17T07:45:52.550764
2019-03-24T16:13:23
2019-03-24T16:13:23
34,873,518
7
0
null
null
null
null
UTF-8
C++
false
false
3,517
cpp
#include <Rcpp.h> using namespace Rcpp; #include "performance.h" #include <algorithm> double get_perf_auc(NumericVector &tpr, NumericVector &fpr, NumericVector &param) { int n_thres = tpr.size(); double auc = 0.; // Numerical integration of step functions is easy for (int j = 1; j < n_thres; j++) { auc += (tpr[j - 1] - tpr[j]) * (2 - fpr[j - 1] - fpr[j]); } auc = 0.5 * auc; return auc; } double pauc_fpr_area(double fpr, NumericVector &param) { if (fpr > param[1]) return 0; if (fpr < param[0]) return (param[1] - param[0]); return (param[1] - fpr); } double pauc_tpr_area(NumericVector &tpr, NumericVector &fpr, NumericVector &param, int index) { if (tpr(index - 1) == tpr[index]) return 0; // necessary check to avoid division by zero later if (tpr[index - 1] < param[0]) return 0; if (tpr[index] > param[1]) return 0; double left = std::max(tpr[index], param[0]); double right = std::min(tpr[index - 1], param[1]); double base_val = 1 - fpr[index]; double slope = (fpr[index] - fpr[index - 1]) / (tpr[index - 1] - tpr[index]); double value_left = base_val + (left - tpr[index]) * slope; double value_right = base_val + (right - tpr[index]) * slope; return (right - left) * (value_left + value_right); } double get_perf_pauc_over_fpr(NumericVector &tpr, NumericVector &fpr, NumericVector &param) { int n_thres = tpr.size(); double p_auc = 0.; // Numerical integration of step functions is easy for (int j = 1; j < n_thres; j++) { p_auc += (tpr[j - 1] - tpr[j]) * (pauc_fpr_area(fpr[j - 1], param) + pauc_fpr_area(fpr[j], param)); } p_auc = 0.5 * p_auc; return p_auc; } double get_perf_pauc_over_tpr(NumericVector &tpr, NumericVector &fpr, NumericVector &param) { int n_thres = tpr.size(); double p_auc = 0.; // Numerical integration of step functions is easy for (int j = 1; j < n_thres; j++) { p_auc += pauc_tpr_area(tpr, fpr, param, j); } p_auc = 0.5 * p_auc; return p_auc; } // double get_perf_pauc_over_fpr(NumericVector &tpr, NumericVector &fpr, NumericVector &param) { // // int i = 0; // double p_auc = 0; // // NOTE: first fpr is 1 and param[1] <= 1 // while (fpr[i] >= param[1]) i++; // fpr starts at 1 and decreases with i // // i will be at least 1 // // // // check for case that fpr interval considered is very small // // if (fpr[i] <= param[0]) { // p_auc = (tpr[i - 1] - tpr[i]) * (2 - param[1] - param[0]); // } // else { // // // insert right partial area here // p_auc = (tpr[i - 1] - tpr[i]) * (2 - param[1] - fpr[i]); // // while (fpr[i] > param[0]) { // last fpr will be zero and param[0] >= 0 so not out of bounds // p_auc += (tpr[i - 1] - tpr[i]) * (2 - fpr[i - 1] - fpr[i]); // i++; // } // // p_auc += (tpr[i - 1] - tpr[i]) * (2 - fpr[i - 1] - param[0]); // } // // p_auc = 0.5 * p_auc; // // return p_auc; // } double get_tpr_at_fixed_fpr(NumericVector &tpr, NumericVector &fpr, NumericVector &param) { double at = param[0]; //double out = 0; if (at == 1) return param[0]; int i = 0; while (fpr[i++] > at); //if (fpr[i] == at) out = tpr[i]; //else double out = tpr[i-1]; return out; } double get_fpr_at_fixed_tpr(NumericVector &tpr, NumericVector &fpr, NumericVector &param) { double at = param[0]; if (at == 0) return param[0]; int i = tpr.size() - 1; while (tpr[i--] < at); double out = fpr[i+1]; return out; }
805893c700d5c771cb0f3bcd8607b8c22e0b8143
a90b23d93d65174248fb5b53356543e646e901c8
/plugins/login_plugin/include/bcio/login_plugin/login_plugin.hpp
fb9f918a0b6cc9db4ae63918bbbed5fa0b699063
[ "BSD-3-Clause", "MIT", "Apache-2.0" ]
permissive
bcchain2020/BCChain
eb6a91af670e766912a403c49a2573f791d5544a
6947212d12571c536225d3440e4985f5b2093cbc
refs/heads/master
2022-07-23T06:11:59.503406
2020-05-18T07:25:17
2020-05-18T07:25:17
264,853,028
0
0
null
null
null
null
UTF-8
C++
false
false
3,251
hpp
/** * @file * @copyright defined in bc/LICENSE.txt */ #pragma once #include <bcio/chain_plugin/chain_plugin.hpp> #include <bcio/http_plugin/http_plugin.hpp> #include <appbase/application.hpp> #include <bcio/chain/controller.hpp> namespace bcio { class login_plugin : public plugin<login_plugin> { public: APPBASE_PLUGIN_REQUIRES((chain_plugin)(http_plugin)) login_plugin(); virtual ~login_plugin(); virtual void set_program_options(options_description&, options_description&) override; void plugin_initialize(const variables_map&); void plugin_startup(); void plugin_shutdown(); struct start_login_request_params { chain::time_point_sec expiration_time; }; struct start_login_request_results { chain::public_key_type server_ephemeral_pub_key; }; struct finalize_login_request_params { chain::public_key_type server_ephemeral_pub_key; chain::public_key_type client_ephemeral_pub_key; chain::permission_level permission; std::string data; std::vector<chain::signature_type> signatures; }; struct finalize_login_request_results { chain::sha256 digest{}; flat_set<chain::public_key_type> recovered_keys{}; bool permission_satisfied = false; std::string error{}; }; struct do_not_use_gen_r1_key_params {}; struct do_not_use_gen_r1_key_results { chain::public_key_type pub_key; chain::private_key_type priv_key; }; struct do_not_use_sign_params { chain::private_key_type priv_key; chain::bytes data; }; struct do_not_use_sign_results { chain::signature_type sig; }; struct do_not_use_get_secret_params { chain::public_key_type pub_key; chain::private_key_type priv_key; }; struct do_not_use_get_secret_results { chain::sha512 secret; }; start_login_request_results start_login_request(const start_login_request_params&); finalize_login_request_results finalize_login_request(const finalize_login_request_params&); do_not_use_gen_r1_key_results do_not_use_gen_r1_key(const do_not_use_gen_r1_key_params&); do_not_use_sign_results do_not_use_sign(const do_not_use_sign_params&); do_not_use_get_secret_results do_not_use_get_secret(const do_not_use_get_secret_params&); private: unique_ptr<class login_plugin_impl> my; }; } // namespace bcio FC_REFLECT(bcio::login_plugin::start_login_request_params, (expiration_time)) FC_REFLECT(bcio::login_plugin::start_login_request_results, (server_ephemeral_pub_key)) FC_REFLECT(bcio::login_plugin::finalize_login_request_params, (server_ephemeral_pub_key)(client_ephemeral_pub_key)(permission)(data)(signatures)) FC_REFLECT(bcio::login_plugin::finalize_login_request_results, (digest)(recovered_keys)(permission_satisfied)(error)) FC_REFLECT_EMPTY(bcio::login_plugin::do_not_use_gen_r1_key_params) FC_REFLECT(bcio::login_plugin::do_not_use_gen_r1_key_results, (pub_key)(priv_key)) FC_REFLECT(bcio::login_plugin::do_not_use_sign_params, (priv_key)(data)) FC_REFLECT(bcio::login_plugin::do_not_use_sign_results, (sig)) FC_REFLECT(bcio::login_plugin::do_not_use_get_secret_params, (pub_key)(priv_key)) FC_REFLECT(bcio::login_plugin::do_not_use_get_secret_results, (secret))
8a1657bc8642522fd64e3d71f8a63fdd361b555a
ab63e7a0f992b3626c51b3e883d5bec30532661f
/disco/a2016.cc
e4b822d64972d7781851a8e8f46b425fbd0963a2
[]
no_license
algorithmu-mu/yamamu
86a9cc365678eb94b90b6022099dbdef2a79e38f
d0ff9de8a6a8944a2caa4fe39dc6a5d0ec0150af
refs/heads/master
2020-02-26T14:14:04.143300
2016-11-24T05:00:45
2016-11-24T05:00:45
61,190,348
0
0
null
null
null
null
UTF-8
C++
false
false
413
cc
#include <iostream> #include <vector> #include <queue> #include <string> #include <algorithm> #define MAX_N 1000001 #define ll long long template<typename A, size_t N, typename T> void Fill(A (&array)[N], const T &val){ std::fill( (T*)array, (T*)(array+N), val ); } using namespace std; int main(){ double a, b, c; cin >> a >> b >> c; printf("%.7f\n", c * b / a ); // // cout << c * b / a << endl; }
d50a7440929ed4b689d9f555736e3c732a603ecb
64f611e64804cfb842b73a3e828b26bf55ad0398
/src/puremethod.cpp
11e8bc297257d185522ed7c7522bf75a8a56b8f4
[ "MIT" ]
permissive
jroivas/nolang
1eb5a70ce82823866db15da899b8d9cb5cb458f0
761655bf851a978fb8426cc8f465e53cc86dec28
refs/heads/master
2021-01-21T08:05:21.940409
2017-07-29T13:17:57
2017-07-29T13:18:14
91,619,112
2
0
null
null
null
null
UTF-8
C++
false
false
177
cpp
#include "puremethod.hh" #include "tools.hh" using namespace nolang; void PureMethod::setParameters(std::vector<TypeIdent*> p) { applyToVector<TypeIdent*>(m_params, p); }
e6551e8ed3b27028368dd3ad22088134f65efa6c
c1e761b79f84d3f7da23d21a99b34d9063da7782
/CavemanNinja/ThrowerRunAIBehaviour.cpp
13d38b4de4ca7147d2e34594713141117925167c
[]
no_license
IgnacioAstorga/Caveman-Ninja
9040ab183d318cc5851b82a6dfbb4a120fb46f86
b55d4c659442feacb4f52c9ab1cfe32ec1b17e40
refs/heads/master
2020-12-25T20:08:47.011355
2016-01-14T16:41:01
2016-01-14T16:41:01
47,366,125
0
0
null
null
null
null
ISO-8859-3
C++
false
false
1,044
cpp
#include "ThrowerRunAIBehaviour.h" #include "ThrowerAIManager.h" #include "Entity.h" #include "Transform.h" #include "Application.h" #include "ModuleAudio.h" #include "EntityLifetimeComponent.h" #include "ColliderComponent.h" #define RUN_SPEED 300.0f ThrowerRunAIBehaviour::ThrowerRunAIBehaviour() : AIBehaviour(RUN) {} ThrowerRunAIBehaviour::~ThrowerRunAIBehaviour() { // No hace nada } void ThrowerRunAIBehaviour::OnEnter() { ThrowerAIManager* throwerManager = (ThrowerAIManager*)manager; // Huye en dirección opuesta throwerManager->orientation = -1 * throwerManager->orientation; entity->transform->speed.x = throwerManager->orientation * RUN_SPEED; // Desactiva la hitbox del personaje throwerManager->hitboxComponent->Disable(); // Activa el componente de desaparición del personaje throwerManager->lifetimeComponent->Enable(); // Reproduce el sonido App->audio->PlayFx(throwerManager->runSound); } void ThrowerRunAIBehaviour::OnTick() { // No hace nada } void ThrowerRunAIBehaviour::OnExit() { // No hace nada }
c4986dc5d901a055b68f88a1a266be2a3081f047
dcc8aaadc3a0a9dc62c4d2b87f34b64fab9cb313
/codeExecute.h
e9889460fca8540f60eb3de0e51797a192751dd2
[]
no_license
Crinnion0/PrisonerDilemma
510d470d1e2a6cb51b8bd6482eec98f18efe9fd3
57deef95cd6dde12a63550673259cd2bbb5ccba3
refs/heads/master
2020-03-10T01:49:08.552066
2018-04-11T16:08:27
2018-04-11T16:08:27
129,120,235
0
0
null
null
null
null
UTF-8
C++
false
false
1,204
h
#pragma once #include "strategy.h" #include "codeIterator.h" #include <fstream> class codeExecute { public: codeExecute(strategy &a, strategy &b); codeExecute(vector<strategy>&a , vector<strategy>&b); ~codeExecute(); bool keywordOperation(strategy a, strategy b); bool calcExpression(strategy a, strategy b, vector<string> expressionLeft, vector<string> expressionRight, string expressionOperator); string getWord(strategy a); void setHasGotoNotCalled(bool a) { hasGotoNotCalled = a; } void incrementVariables(strategy &a, strategy &b); void incrementGangVariables(vector<strategy> &purple, vector<strategy> &magentam, int purpleTotalBetray, int magentaTotalBetray); void writeResults(strategy &a, strategy &b); map<string, double> returnAllResults() { return allResults; } protected: set<string> ifOperands{ ">", "<", "=", }; int executeIterations = 0; bool betrayW; bool betrayX; bool betrayY; bool betrayZ; bool hasGotoNotCalled; bool betrayLastRoundA; bool betrayLastRoundB; map<string, double> allResults; vector<string> stringExpression; vector<string> expressionLeft; vector<string> expressionRight; string expressionOperator; int gotoLineNo; };
36dbdd84920554e84f3bb5195d17125d231b9cfd
15da3fc8bda6517c7a655741b396fdc80918e45e
/P40479.cc
b32b682dbd2b1be9071868a0d5ddda18e0626e38
[]
no_license
ShimaSama/FIB-EDA
3085af61636ff05d0fa1ee5735dbb9fbf49a2feb
91150d5f6c4ce57e81aa777e1adff0548279e4b4
refs/heads/master
2020-07-23T08:14:29.600454
2019-12-10T08:41:46
2019-12-10T08:41:46
207,496,428
0
0
null
null
null
null
UTF-8
C++
false
false
923
cc
#include <iostream> #include <vector> using namespace std; typedef vector<vector<char > > Matrix; void DFS(Matrix& g, int i, int j,char c){ if(g[i][j]=='.' ){ g[i][j]=c; DFS(g,i+1,j,c); DFS(g,i,j+1,c); DFS(g,i-1,j,c); DFS(g,i,j-1,c); } } int main(){ int n,m; while (cin >> n >> m){ Matrix g (n,vector<char>(m)); for(int i=0; i<n; i++){ for(int j=0; j<m; j++){ cin >> g[i][j]; } } for(int i=0; i<n; i++){ for(int j=0; j<m; j++){ if(g[i][j]!='#' and g[i][j]!='.') { char c=g[i][j]; DFS(g,i+1,j,c); DFS(g,i,j+1,c); DFS(g,i-1,j,c); DFS(g,i,j-1,c); } } } for(int i=0; i<n; i++){ for(int j=0; j<m; j++){ cout << g[i][j]; } cout << endl; } cout << endl; } }
bfd392938b05ec69bcbc6ca2c11c4f3e6817f3a5
94e8f9fdbe473df89c5923ac196406bc6ab37df9
/src/lib/boost/asio/ssl/context_service.hpp
50b7b57695185dbf7795dcdf31fd2e9a135d2ff2
[ "BSL-1.0" ]
permissive
willdsl/ofxBoost
5a14ce089a69dc993bacd40c73d2a19983bc2c22
1624a8247f0ede71ab46948fe02a55c260ffc0dd
refs/heads/master
2020-12-03T09:11:59.153780
2019-11-25T02:21:47
2019-11-25T02:21:47
29,944,517
0
1
BSL-1.0
2019-11-25T02:21:48
2015-01-28T01:32:03
C++
UTF-8
C++
false
false
5,297
hpp
// // ssl/context_service.hpp // ~~~~~~~~~~~~~~~~~~~~~~~ // // Copyright (c) 2005 Voipster / Indrek dot Juhani at voipster dot com // Copyright (c) 2005-2011 Christopher M. Kohlhoff (chris at kohlhoff dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #ifndef BOOST_ASIO_SSL_CONTEXT_SERVICE_HPP #define BOOST_ASIO_SSL_CONTEXT_SERVICE_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include <boost/asio/detail/config.hpp> #include <string> #include <boost/noncopyable.hpp> #include <boost/asio/error.hpp> #include <boost/asio/io_service.hpp> #include <boost/asio/ssl/context_base.hpp> #include <boost/asio/ssl/detail/openssl_context_service.hpp> #include <boost/asio/detail/push_options.hpp> namespace boost { namespace asio { namespace ssl { /// Default service implementation for a context. class context_service #if defined(GENERATING_DOCUMENTATION) : public boost::asio::io_service::service #else : public boost::asio::detail::service_base<context_service> #endif { private: // The type of the platform-specific implementation. typedef detail::openssl_context_service service_impl_type; public: #if defined(GENERATING_DOCUMENTATION) /// The unique service identifier. static boost::asio::io_service::id id; #endif /// The type of the context. #if defined(GENERATING_DOCUMENTATION) typedef implementation_defined impl_type; #else typedef service_impl_type::impl_type impl_type; #endif /// Constructor. explicit context_service(boost::asio::io_service& io_service) : boost::asio::detail::service_base<context_service>(io_service), service_impl_(boost::asio::use_service<service_impl_type>(io_service)) { } /// Destroy all user-defined handler objects owned by the service. void shutdown_service() { } /// Return a null context implementation. impl_type null() const { return service_impl_.null(); } /// Create a new context implementation. void create(impl_type& impl, context_base::method m) { service_impl_.create(impl, m); } /// Destroy a context implementation. void destroy(impl_type& impl) { service_impl_.destroy(impl); } /// Set options on the context. boost::system::error_code set_options(impl_type& impl, context_base::options o, boost::system::error_code& ec) { return service_impl_.set_options(impl, o, ec); } /// Set peer verification mode. boost::system::error_code set_verify_mode(impl_type& impl, context_base::verify_mode v, boost::system::error_code& ec) { return service_impl_.set_verify_mode(impl, v, ec); } /// Load a certification authority file for performing verification. boost::system::error_code load_verify_file(impl_type& impl, const std::string& filename, boost::system::error_code& ec) { return service_impl_.load_verify_file(impl, filename, ec); } /// Add a directory containing certification authority files to be used for /// performing verification. boost::system::error_code add_verify_path(impl_type& impl, const std::string& path, boost::system::error_code& ec) { return service_impl_.add_verify_path(impl, path, ec); } /// Use a certificate from a file. boost::system::error_code use_certificate_file(impl_type& impl, const std::string& filename, context_base::file_format format, boost::system::error_code& ec) { return service_impl_.use_certificate_file(impl, filename, format, ec); } /// Use a certificate chain from a file. boost::system::error_code use_certificate_chain_file(impl_type& impl, const std::string& filename, boost::system::error_code& ec) { return service_impl_.use_certificate_chain_file(impl, filename, ec); } /// Use a private key from a file. boost::system::error_code use_private_key_file(impl_type& impl, const std::string& filename, context_base::file_format format, boost::system::error_code& ec) { return service_impl_.use_private_key_file(impl, filename, format, ec); } /// Use an RSA private key from a file. boost::system::error_code use_rsa_private_key_file(impl_type& impl, const std::string& filename, context_base::file_format format, boost::system::error_code& ec) { return service_impl_.use_rsa_private_key_file(impl, filename, format, ec); } /// Use the specified file to obtain the temporary Diffie-Hellman parameters. boost::system::error_code use_tmp_dh_file(impl_type& impl, const std::string& filename, boost::system::error_code& ec) { return service_impl_.use_tmp_dh_file(impl, filename, ec); } /// Set the password callback. template <typename PasswordCallback> boost::system::error_code set_password_callback(impl_type& impl, PasswordCallback callback, boost::system::error_code& ec) { return service_impl_.set_password_callback(impl, callback, ec); } private: // The service that provides the platform-specific implementation. service_impl_type& service_impl_; }; } // namespace ssl } // namespace asio } // namespace boost #include <boost/asio/detail/pop_options.hpp> #endif // BOOST_ASIO_SSL_CONTEXT_SERVICE_HPP
5a1a1cc862442d388d65d93ac7c9b70658b95aef
44a5efc70bc374376217cf0274b007c581ea058a
/Perlin.hpp
4aa618ff4f92281672881107131bdaa42aa97604
[]
no_license
fqhd/PerlinNoise
2ae3d1fd295b7362031d23c9df9f87a7b8ebe4e7
00d6b776d96a61997f223a96a89260fd4bac2a8c
refs/heads/master
2023-02-23T19:58:19.476761
2021-01-31T09:06:35
2021-01-31T09:06:35
324,580,369
0
0
null
null
null
null
UTF-8
C++
false
false
454
hpp
#ifndef PERLIN_H #define PERLIN_H class Perlin { public: void init(unsigned int width, unsigned int octaves, float bias); float noise2D(unsigned int x, unsigned int y); void destroy(); private: void createRandomNoise(float* randomNoiseArray, unsigned int size); void createPerlinNoise(int width, int octaves, float bias, float* seed, float *output); float* m_noise = nullptr; unsigend int m_width = 0; }; #endif
b01675382a52af5d6600b4ccf0027f61574c8e36
e9b7c1893e51ceece24be7ac211aa1ff108b87b1
/main.cpp
3974d8cab98f6f420878bb62edd38fb2b43b3a6e
[]
no_license
Ozatooo/ZadanieLogowanieC-
1ea9137aeb8fe792c77a7664b5e42eb4b1ea7617
721ae0e89ddfe46e1c21f4cb89d20008d4e78c7f
refs/heads/master
2022-05-28T10:42:17.032162
2020-05-05T06:27:33
2020-05-05T06:27:33
261,378,268
0
0
null
null
null
null
UTF-8
C++
false
false
803
cpp
#include <iostream> using namespace std; int main(int argc, char** argv) { string haslo, odpowiedz; int wiek; cout << "Podaj swoj wiek: "; cin >> wiek; if(wiek < 18) { cout <<endl<< "Jestes niepelnoletni"; } else { cout << "Podaj haslo: "; cin >> haslo; if(haslo == "szarlotka") { cout <<endl<< "Logowanie udane"; } else { cout <<endl<< "Logowanie nieudane"; } } if(wiek >=35) { cout << "\n\nANKIETA\n"; cout << "Bedziesz glosowal na prezydenta?"<<endl<<"1.Tak"<<endl<<"2.Nie\n\n"; cin >> odpowiedz; cout << "\nDziekuje za wziecie udzialu w ankiecie!\n"; } return 0; }
1d435c48223f75df679ea84b425310c417cba342
a754da405bc3d2d2d1d8940d7d277c63bf2b7768
/android/jni/com/mapswithme/platform/HttpThread.cpp
ef454224343c4c5e82b5a1b2913d6581cd23a763
[ "Apache-2.0" ]
permissive
icyleaf/omim
3a5a4f07890e6ad0155447ed39563a710178ec35
a1a299eb341603337bf4a22b92518d9575498c97
refs/heads/master
2020-12-28T22:53:52.624975
2015-10-09T16:30:46
2015-10-09T16:30:46
43,995,093
0
0
Apache-2.0
2019-12-12T03:19:59
2015-10-10T05:08:38
C++
UTF-8
C++
false
false
3,915
cpp
#include "platform/http_thread_callback.hpp" #include "../core/jni_helper.hpp" #include "Platform.hpp" class HttpThread { private: jobject m_self; public: HttpThread(string const & url, downloader::IHttpThreadCallback & cb, int64_t beg, int64_t end, int64_t expectedFileSize, string const & pb) { /// should create java object here. JNIEnv * env = jni::GetEnv(); ASSERT ( env, () ); jclass klass = env->FindClass("com/mapswithme/maps/downloader/DownloadChunkTask"); ASSERT ( klass, () ); static jmethodID initMethodId = env->GetMethodID(klass, "<init>", "(JLjava/lang/String;JJJ[BLjava/lang/String;)V"); ASSERT ( initMethodId, () ); // User id is always the same, so do not waste time on every chunk call static string uniqueUserId = GetPlatform().UniqueClientId(); jbyteArray postBody = 0; size_t const postBodySize = pb.size(); if (postBodySize) { postBody = env->NewByteArray(postBodySize); env->SetByteArrayRegion(postBody, 0, postBodySize, reinterpret_cast<jbyte const *>(pb.c_str())); } jstring jUrl = env->NewStringUTF(url.c_str()); jstring jUserId = env->NewStringUTF(uniqueUserId.c_str()); jobject const localSelf = env->NewObject(klass, initMethodId, reinterpret_cast<jlong>(&cb), jUrl, static_cast<jlong>(beg), static_cast<jlong>(end), static_cast<jlong>(expectedFileSize), postBody, jUserId); m_self = env->NewGlobalRef(localSelf); ASSERT ( m_self, () ); env->DeleteLocalRef(localSelf); env->DeleteLocalRef(postBody); env->DeleteLocalRef(jUrl); env->DeleteLocalRef(jUserId); static jmethodID startMethodId = env->GetMethodID(klass, "start", "()V"); ASSERT ( startMethodId, () ); env->DeleteLocalRef(klass); env->CallVoidMethod(m_self, startMethodId); } ~HttpThread() { JNIEnv * env = jni::GetEnv(); ASSERT ( env, () ); jmethodID methodId = jni::GetJavaMethodID(env, m_self, "cancel", "(Z)Z"); ASSERT ( methodId, () ); env->CallBooleanMethod(m_self, methodId, false); env->DeleteGlobalRef(m_self); } }; namespace downloader { HttpThread * CreateNativeHttpThread(string const & url, downloader::IHttpThreadCallback & cb, int64_t beg, int64_t end, int64_t size, string const & pb) { return new HttpThread(url, cb, beg, end, size, pb); } void DeleteNativeHttpThread(HttpThread * request) { delete request; } } // namespace downloader extern "C" { JNIEXPORT jboolean JNICALL Java_com_mapswithme_maps_downloader_DownloadChunkTask_onWrite(JNIEnv * env, jobject thiz, jlong httpCallbackID, jlong beg, jbyteArray data, jlong size) { downloader::IHttpThreadCallback * cb = reinterpret_cast<downloader::IHttpThreadCallback*>(httpCallbackID); jbyte * buf = env->GetByteArrayElements(data, 0); ASSERT ( buf, () ); bool const ret = cb->OnWrite(beg, buf, size); env->ReleaseByteArrayElements(data, buf, 0); return ret; } JNIEXPORT void JNICALL Java_com_mapswithme_maps_downloader_DownloadChunkTask_onFinish(JNIEnv * env, jobject thiz, jlong httpCallbackID, jlong httpCode, jlong beg, jlong end) { downloader::IHttpThreadCallback * cb = reinterpret_cast<downloader::IHttpThreadCallback*>(httpCallbackID); cb->OnFinish(httpCode, beg, end); } }
f2272393321a93c2246ad3263397cafe7e9363ef
2af943fbfff74744b29e4a899a6e62e19dc63256
/BRPTools/IGTLPerformanceTest/igtlLoopController.h
aaf6028691ee696da9c1d6da9713653c5322214b
[]
no_license
lheckemann/namic-sandbox
c308ec3ebb80021020f98cf06ee4c3e62f125ad9
0c7307061f58c9d915ae678b7a453876466d8bf8
refs/heads/master
2021-08-24T12:40:01.331229
2014-02-07T21:59:29
2014-02-07T21:59:29
113,701,721
2
1
null
null
null
null
UTF-8
C++
false
false
3,028
h
/*========================================================================= Program: Open IGT Link -- Example for Tracker Client Program Module: $RCSfile: $ Language: C++ Date: $Date: $ Version: $Revision: $ Copyright (c) Insight Software Consortium. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #ifndef __igtlLoopController_h #define __igtlLoopController_h #include "igtlObject.h" #include "igtlObjectFactory.h" #include "igtlMacro.h" #include "igtlTimeStamp.h" namespace igtl { class LoopController : public Object { public: typedef struct { int type; double time; } TimeTableElement; typedef std::vector<TimeTableElement> TimeTableType; public: /** Standard class typedefs. */ typedef LoopController Self; typedef Object Superclass; typedef SmartPointer<Self> Pointer; typedef SmartPointer<const Self> ConstPointer; igtlNewMacro(Self); igtlTypeMacro(LoopController,Object); // InitLoop() initialize the member variables and // set the interval (second) and number of loops. // if n is set at 0, the loop becomes eternal loop. void InitLoop(double interval_s, int n=0); void InitLoop(TimeTableType& timeTable); // StartLoop() and function is palced at the begining // of the loop section. The function sleeps to adjust // the loop interval. StartLoop() returns 0, when the program // calls StopLoop() before calling StartLoop(). Otherwise // it returns 1. The function can be used with for(;;) loop as: // // for (loop->InitLoop(0.01); loop->StartLoop();) // { // ... // } // int StartLoop(); // StopLoop() function activate the flag to stop the loop. // After the function is called, StartLoop() returns NULL. int StopLoop(); // GetTimerDelay() returns the delay of StartLoop() function. // It is used to check the accuracy of sleeping duration in the // StartLoop() function. double GetTimerDelay(); // GetEllapsedTime() returns time since the program finishes // calling the StartLoop() function. double GetEllapsedTime(); // GetScheduledTime() returns time written on the time table. double GetScheduledTime(); // Check if the scheduled time is same as the previous loop. int IsSimultaneous() { return this->m_SimultaneousFlag; }; int GetCount() { return this->m_Count-1; }; protected: LoopController(); ~LoopController(); private: igtl::TimeStamp::Pointer m_TimeStamp; int m_StopFlag; double m_Interval; double m_Delay; double m_StartTime; double m_OriginTime; double m_PrevStartTime; int m_SimultaneousFlag; int m_MaxCount; int m_Count; TimeTableType m_TimeTable; }; } #endif //__LoopController_h
[ "tokuda@5e132c66-7cf4-0310-b4ca-cd4a7079c2d8" ]
tokuda@5e132c66-7cf4-0310-b4ca-cd4a7079c2d8
46b8a0c9749b30480dfe7667c1f5e117064df022
949749d564f421baff991dbb559fce17df36dde3
/smsListener/android/build/generated/jni/com.oodles.smslistener.SmsListenerModule.cpp
1763bd3c42d30ae6ffd8f186a904764c2c51d23a
[]
no_license
mohitvirmani/Sapna-Oodles
60eeda2a1808c01483e5c6c5866758a67e6c7d62
732e473db4993c23fa71ecfa09ffff085eb31a76
refs/heads/master
2020-06-15T15:31:03.846142
2016-12-01T13:15:55
2016-12-01T13:15:55
75,283,234
0
0
null
2016-12-01T10:48:11
2016-12-01T10:48:11
null
UTF-8
C++
false
false
8,868
cpp
/** * Appcelerator Titanium Mobile * Copyright (c) 2011-2013 by Appcelerator, Inc. All Rights Reserved. * Licensed under the terms of the Apache Public License * Please see the LICENSE included with this distribution for details. */ /** This code is generated, do not edit by hand. **/ #include "com.oodles.smslistener.SmsListenerModule.h" #include "AndroidUtil.h" #include "EventEmitter.h" #include "JNIUtil.h" #include "JSException.h" #include "Proxy.h" #include "ProxyFactory.h" #include "TypeConverter.h" #include "V8Util.h" #include "com.oodles.smslistener.ExampleProxy.h" #include "org.appcelerator.kroll.KrollModule.h" #define TAG "SmsListenerModule" using namespace v8; namespace com { namespace oodles { namespace smslistener { Persistent<FunctionTemplate> SmsListenerModule::proxyTemplate = Persistent<FunctionTemplate>(); jclass SmsListenerModule::javaClass = NULL; SmsListenerModule::SmsListenerModule(jobject javaObject) : titanium::Proxy(javaObject) { } void SmsListenerModule::bindProxy(Handle<Object> exports) { if (proxyTemplate.IsEmpty()) { getProxyTemplate(); } // use symbol over string for efficiency Handle<String> nameSymbol = String::NewSymbol("SmsListener"); Local<Function> proxyConstructor = proxyTemplate->GetFunction(); Local<Object> moduleInstance = proxyConstructor->NewInstance(); exports->Set(nameSymbol, moduleInstance); } void SmsListenerModule::dispose() { LOGD(TAG, "dispose()"); if (!proxyTemplate.IsEmpty()) { proxyTemplate.Dispose(); proxyTemplate = Persistent<FunctionTemplate>(); } titanium::KrollModule::dispose(); } Handle<FunctionTemplate> SmsListenerModule::getProxyTemplate() { if (!proxyTemplate.IsEmpty()) { return proxyTemplate; } LOGD(TAG, "GetProxyTemplate"); javaClass = titanium::JNIUtil::findClass("com/oodles/smslistener/SmsListenerModule"); HandleScope scope; // use symbol over string for efficiency Handle<String> nameSymbol = String::NewSymbol("SmsListener"); Handle<FunctionTemplate> t = titanium::Proxy::inheritProxyTemplate( titanium::KrollModule::getProxyTemplate() , javaClass, nameSymbol); proxyTemplate = Persistent<FunctionTemplate>::New(t); proxyTemplate->Set(titanium::Proxy::inheritSymbol, FunctionTemplate::New(titanium::Proxy::inherit<SmsListenerModule>)->GetFunction()); titanium::ProxyFactory::registerProxyPair(javaClass, *proxyTemplate); // Method bindings -------------------------------------------------------- DEFINE_PROTOTYPE_METHOD(proxyTemplate, "hasSMSReceivePermission", SmsListenerModule::hasSMSReceivePermission); DEFINE_PROTOTYPE_METHOD(proxyTemplate, "example", SmsListenerModule::example); Local<ObjectTemplate> prototypeTemplate = proxyTemplate->PrototypeTemplate(); Local<ObjectTemplate> instanceTemplate = proxyTemplate->InstanceTemplate(); // Delegate indexed property get and set to the Java proxy. instanceTemplate->SetIndexedPropertyHandler(titanium::Proxy::getIndexedProperty, titanium::Proxy::setIndexedProperty); // Constants -------------------------------------------------------------- JNIEnv *env = titanium::JNIScope::getEnv(); if (!env) { LOGE(TAG, "Failed to get environment in SmsListenerModule"); //return; } DEFINE_INT_CONSTANT(prototypeTemplate, "FAILED", -2); DEFINE_INT_CONSTANT(prototypeTemplate, "RECEIVED", 0); // Dynamic properties ----------------------------------------------------- instanceTemplate->SetAccessor(String::NewSymbol("exampleProp"), SmsListenerModule::getter_exampleProp , SmsListenerModule::setter_exampleProp , Handle<Value>(), DEFAULT); // Accessors -------------------------------------------------------------- return proxyTemplate; } // Methods -------------------------------------------------------------------- Handle<Value> SmsListenerModule::hasSMSReceivePermission(const Arguments& args) { LOGD(TAG, "hasSMSReceivePermission()"); HandleScope scope; JNIEnv *env = titanium::JNIScope::getEnv(); if (!env) { return titanium::JSException::GetJNIEnvironmentError(); } static jmethodID methodID = NULL; if (!methodID) { methodID = env->GetMethodID(SmsListenerModule::javaClass, "hasSMSReceivePermission", "()Z"); if (!methodID) { const char *error = "Couldn't find proxy method 'hasSMSReceivePermission' with signature '()Z'"; LOGE(TAG, error); return titanium::JSException::Error(error); } } titanium::Proxy* proxy = titanium::Proxy::unwrap(args.Holder()); jvalue* jArguments = 0; jobject javaProxy = proxy->getJavaObject(); jboolean jResult = (jboolean)env->CallBooleanMethodA(javaProxy, methodID, jArguments); if (!JavaObject::useGlobalRefs) { env->DeleteLocalRef(javaProxy); } if (env->ExceptionCheck()) { Handle<Value> jsException = titanium::JSException::fromJavaException(); env->ExceptionClear(); return jsException; } Handle<Boolean> v8Result = titanium::TypeConverter::javaBooleanToJsBoolean(env, jResult); return v8Result; } Handle<Value> SmsListenerModule::example(const Arguments& args) { LOGD(TAG, "example()"); HandleScope scope; JNIEnv *env = titanium::JNIScope::getEnv(); if (!env) { return titanium::JSException::GetJNIEnvironmentError(); } static jmethodID methodID = NULL; if (!methodID) { methodID = env->GetMethodID(SmsListenerModule::javaClass, "example", "()Ljava/lang/String;"); if (!methodID) { const char *error = "Couldn't find proxy method 'example' with signature '()Ljava/lang/String;'"; LOGE(TAG, error); return titanium::JSException::Error(error); } } titanium::Proxy* proxy = titanium::Proxy::unwrap(args.Holder()); jvalue* jArguments = 0; jobject javaProxy = proxy->getJavaObject(); jstring jResult = (jstring)env->CallObjectMethodA(javaProxy, methodID, jArguments); if (!JavaObject::useGlobalRefs) { env->DeleteLocalRef(javaProxy); } if (env->ExceptionCheck()) { Handle<Value> jsException = titanium::JSException::fromJavaException(); env->ExceptionClear(); return jsException; } if (jResult == NULL) { return Null(); } Handle<Value> v8Result = titanium::TypeConverter::javaStringToJsString(env, jResult); env->DeleteLocalRef(jResult); return v8Result; } // Dynamic property accessors ------------------------------------------------- Handle<Value> SmsListenerModule::getter_exampleProp(Local<String> property, const AccessorInfo& info) { LOGD(TAG, "get exampleProp"); HandleScope scope; JNIEnv *env = titanium::JNIScope::getEnv(); if (!env) { return titanium::JSException::GetJNIEnvironmentError(); } static jmethodID methodID = NULL; if (!methodID) { methodID = env->GetMethodID(SmsListenerModule::javaClass, "getExampleProp", "()Ljava/lang/String;"); if (!methodID) { const char *error = "Couldn't find proxy method 'getExampleProp' with signature '()Ljava/lang/String;'"; LOGE(TAG, error); return titanium::JSException::Error(error); } } titanium::Proxy* proxy = titanium::Proxy::unwrap(info.Holder()); if (!proxy) { return Undefined(); } jvalue* jArguments = 0; jobject javaProxy = proxy->getJavaObject(); jstring jResult = (jstring)env->CallObjectMethodA(javaProxy, methodID, jArguments); if (!JavaObject::useGlobalRefs) { env->DeleteLocalRef(javaProxy); } if (env->ExceptionCheck()) { Handle<Value> jsException = titanium::JSException::fromJavaException(); env->ExceptionClear(); return jsException; } if (jResult == NULL) { return Null(); } Handle<Value> v8Result = titanium::TypeConverter::javaStringToJsString(env, jResult); env->DeleteLocalRef(jResult); return v8Result; } void SmsListenerModule::setter_exampleProp(Local<String> property, Local<Value> value, const AccessorInfo& info) { LOGD(TAG, "set exampleProp"); HandleScope scope; JNIEnv *env = titanium::JNIScope::getEnv(); if (!env) { LOGE(TAG, "Failed to get environment, exampleProp wasn't set"); return; } static jmethodID methodID = NULL; if (!methodID) { methodID = env->GetMethodID(SmsListenerModule::javaClass, "setExampleProp", "(Ljava/lang/String;)V"); if (!methodID) { const char *error = "Couldn't find proxy method 'setExampleProp' with signature '(Ljava/lang/String;)V'"; LOGE(TAG, error); } } titanium::Proxy* proxy = titanium::Proxy::unwrap(info.Holder()); if (!proxy) { return; } jvalue jArguments[1]; if (!value->IsNull()) { Local<Value> arg_0 = value; jArguments[0].l = titanium::TypeConverter::jsValueToJavaString(env, arg_0); } else { jArguments[0].l = NULL; } jobject javaProxy = proxy->getJavaObject(); env->CallVoidMethodA(javaProxy, methodID, jArguments); if (!JavaObject::useGlobalRefs) { env->DeleteLocalRef(javaProxy); } env->DeleteLocalRef(jArguments[0].l); if (env->ExceptionCheck()) { titanium::JSException::fromJavaException(); env->ExceptionClear(); } } } // smslistener } // oodles } // com
0a20d012ea3367820507efe2b42943cbc45b439e
4c23be1a0ca76f68e7146f7d098e26c2bbfb2650
/h2/0.4/uniform/time
f9d41f851a60dbb4085eafb06ad569aa22e06bfa
[]
no_license
labsandy/OpenFOAM_workspace
a74b473903ddbd34b31dc93917e3719bc051e379
6e0193ad9dabd613acf40d6b3ec4c0536c90aed4
refs/heads/master
2022-02-25T02:36:04.164324
2019-08-23T02:27:16
2019-08-23T02:27:16
null
0
0
null
null
null
null
UTF-8
C++
false
false
819
/*--------------------------------*- C++ -*----------------------------------*\ ========= | \\ / F ield | OpenFOAM: The Open Source CFD Toolbox \\ / O peration | Website: https://openfoam.org \\ / A nd | Version: 6 \\/ M anipulation | \*---------------------------------------------------------------------------*/ FoamFile { version 2.0; format ascii; class dictionary; location "0.4/uniform"; object time; } // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // value 0.400000000000000022; name "0.4"; index 30; deltaT 0.1; deltaT0 0.1; // ************************************************************************* //
b9c0db2a5f93f78d1c4daf28681101cbe561b57c
ae056ba0777876ca7d7ff02fd688e5c2455bc449
/source/common/tracing/null_span_impl.h
13770006323493ecf4ad0e55e6c02488950496f1
[ "LicenseRef-scancode-unknown-license-reference", "Apache-2.0" ]
permissive
Nextdoor/envoy
860f5b47ea0afec23b22e82baf396681eb50de45
b9eada56a2ce8203c47796f80b64a7822616fa09
refs/heads/main
2023-08-05T02:16:58.838815
2021-08-23T14:11:37
2021-08-23T14:11:37
215,616,004
3
2
Apache-2.0
2023-08-16T04:55:17
2019-10-16T18:22:44
C++
UTF-8
C++
false
false
1,027
h
#pragma once #include "envoy/tracing/trace_driver.h" #include "source/common/common/empty_string.h" namespace Envoy { namespace Tracing { /** * Null implementation of Span. */ class NullSpan : public Span { public: static NullSpan& instance() { static NullSpan* instance = new NullSpan(); return *instance; } // Tracing::Span void setOperation(absl::string_view) override {} void setTag(absl::string_view, absl::string_view) override {} void log(SystemTime, const std::string&) override {} void finishSpan() override {} void injectContext(Tracing::TraceContext&) override {} void setBaggage(absl::string_view, absl::string_view) override {} std::string getBaggage(absl::string_view) override { return EMPTY_STRING; } std::string getTraceIdAsHex() const override { return EMPTY_STRING; } SpanPtr spawnChild(const Config&, const std::string&, SystemTime) override { return SpanPtr{new NullSpan()}; } void setSampled(bool) override {} }; } // namespace Tracing } // namespace Envoy
2d6a31658a9a8bf31fc6f55a8d2e03bf6389421c
1c024dfbca35f4c829d4b47bdfe900d1b1a2303b
/shell/browser/ui/webui/accessibility_ui.cc
6b64fa1fbcaeeabcbe8897c4df80be4ac13bb480
[ "MIT" ]
permissive
electron/electron
1ba6e31cf40f876044bff644ec49f8ec4923ca6a
0b0707145b157343c42266d2586ed9413a1d54f5
refs/heads/main
2023-09-01T04:28:11.016383
2023-08-31T14:36:43
2023-08-31T14:36:43
9,384,267
99,768
18,388
MIT
2023-09-14T19:50:49
2013-04-12T01:47:36
C++
UTF-8
C++
false
false
16,202
cc
// Copyright (c) 2020 Microsoft, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "shell/browser/ui/webui/accessibility_ui.h" #include <memory> #include <string> #include <utility> #include <vector> #include "base/command_line.h" #include "base/functional/bind.h" #include "base/functional/callback_helpers.h" #include "base/json/json_writer.h" #include "base/strings/escape.h" #include "base/strings/pattern.h" #include "base/strings/string_number_conversions.h" #include "base/strings/utf_string_conversions.h" #include "base/values.h" #include "build/build_config.h" #include "chrome/common/chrome_features.h" #include "chrome/common/pref_names.h" #include "chrome/common/webui_url_constants.h" #include "chrome/grit/accessibility_resources.h" // nogncheck #include "chrome/grit/accessibility_resources_map.h" // nogncheck #include "components/pref_registry/pref_registry_syncable.h" #include "components/prefs/pref_service.h" #include "content/public/browser/ax_event_notification_details.h" #include "content/public/browser/ax_inspect_factory.h" #include "content/public/browser/browser_accessibility_state.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/favicon_status.h" #include "content/public/browser/navigation_entry.h" #include "content/public/browser/render_process_host.h" #include "content/public/browser/render_view_host.h" #include "content/public/browser/render_widget_host.h" #include "content/public/browser/render_widget_host_iterator.h" #include "content/public/browser/web_contents.h" #include "content/public/browser/web_contents_delegate.h" #include "content/public/browser/web_ui_data_source.h" #include "shell/browser/native_window.h" #include "shell/browser/window_list.h" #include "third_party/abseil-cpp/absl/types/optional.h" #include "ui/accessibility/platform/ax_platform_node.h" #include "ui/accessibility/platform/ax_platform_node_delegate.h" #include "ui/base/webui/web_ui_util.h" namespace { static const char kTargetsDataFile[] = "targets-data.json"; static const char kAccessibilityModeField[] = "a11yMode"; static const char kBrowsersField[] = "browsers"; static const char kErrorField[] = "error"; static const char kFaviconUrlField[] = "faviconUrl"; static const char kNameField[] = "name"; static const char kPagesField[] = "pages"; static const char kPidField[] = "pid"; static const char kSessionIdField[] = "sessionId"; static const char kProcessIdField[] = "processId"; static const char kRequestTypeField[] = "requestType"; static const char kRoutingIdField[] = "routingId"; static const char kTypeField[] = "type"; static const char kUrlField[] = "url"; static const char kTreeField[] = "tree"; // Global flags static const char kBrowser[] = "browser"; static const char kCopyTree[] = "copyTree"; static const char kHTML[] = "html"; static const char kInternal[] = "internal"; static const char kLabelImages[] = "labelImages"; static const char kNative[] = "native"; static const char kPage[] = "page"; static const char kPDF[] = "pdf"; static const char kScreenReader[] = "screenreader"; static const char kShowOrRefreshTree[] = "showOrRefreshTree"; static const char kText[] = "text"; static const char kWeb[] = "web"; // Possible global flag values static const char kDisabled[] = "disabled"; static const char kOff[] = "off"; static const char kOn[] = "on"; base::Value::Dict BuildTargetDescriptor( const GURL& url, const std::string& name, const GURL& favicon_url, int process_id, int routing_id, ui::AXMode accessibility_mode, base::ProcessHandle handle = base::kNullProcessHandle) { base::Value::Dict target_data; target_data.Set(kProcessIdField, process_id); target_data.Set(kRoutingIdField, routing_id); target_data.Set(kUrlField, url.spec()); target_data.Set(kNameField, base::EscapeForHTML(name)); target_data.Set(kPidField, static_cast<int>(base::GetProcId(handle))); target_data.Set(kFaviconUrlField, favicon_url.spec()); target_data.Set(kAccessibilityModeField, static_cast<int>(accessibility_mode.flags())); target_data.Set(kTypeField, kPage); return target_data; } base::Value::Dict BuildTargetDescriptor(content::RenderViewHost* rvh) { content::WebContents* web_contents = content::WebContents::FromRenderViewHost(rvh); ui::AXMode accessibility_mode; std::string title; GURL url; GURL favicon_url; if (web_contents) { url = web_contents->GetURL(); title = base::UTF16ToUTF8(web_contents->GetTitle()); content::NavigationController& controller = web_contents->GetController(); content::NavigationEntry* entry = controller.GetVisibleEntry(); if (entry != nullptr && entry->GetURL().is_valid()) { gfx::Image favicon_image = entry->GetFavicon().image; if (!favicon_image.IsEmpty()) { const SkBitmap* favicon_bitmap = favicon_image.ToSkBitmap(); favicon_url = GURL(webui::GetBitmapDataUrl(*favicon_bitmap)); } } accessibility_mode = web_contents->GetAccessibilityMode(); } return BuildTargetDescriptor(url, title, favicon_url, rvh->GetProcess()->GetID(), rvh->GetRoutingID(), accessibility_mode); } base::Value::Dict BuildTargetDescriptor(electron::NativeWindow* window) { base::Value::Dict target_data; target_data.Set(kSessionIdField, window->window_id()); target_data.Set(kNameField, window->GetTitle()); target_data.Set(kTypeField, kBrowser); return target_data; } bool ShouldHandleAccessibilityRequestCallback(const std::string& path) { return path == kTargetsDataFile; } // Add property filters to the property_filters vector for the given property // filter type. The attributes are passed in as a string with each attribute // separated by a space. void AddPropertyFilters(std::vector<ui::AXPropertyFilter>* property_filters, const std::string& attributes, ui::AXPropertyFilter::Type type) { for (const std::string& attribute : base::SplitString( attributes, " ", base::KEEP_WHITESPACE, base::SPLIT_WANT_NONEMPTY)) { property_filters->emplace_back(attribute, type); } } bool MatchesPropertyFilters( const std::vector<ui::AXPropertyFilter>& property_filters, const std::string& text) { bool allow = false; for (const auto& filter : property_filters) { if (base::MatchPattern(text, filter.match_str)) { switch (filter.type) { case ui::AXPropertyFilter::ALLOW_EMPTY: case ui::AXPropertyFilter::SCRIPT: allow = true; break; case ui::AXPropertyFilter::ALLOW: allow = (!base::MatchPattern(text, "*=''")); break; case ui::AXPropertyFilter::DENY: allow = false; break; } } } return allow; } std::string RecursiveDumpAXPlatformNodeAsString( const ui::AXPlatformNode* node, int indent, const std::vector<ui::AXPropertyFilter>& property_filters) { if (!node) return ""; std::string str(2 * indent, '+'); const std::string line = node->GetDelegate()->GetData().ToString(); const std::vector<std::string> attributes = base::SplitString( line, " ", base::KEEP_WHITESPACE, base::SPLIT_WANT_NONEMPTY); for (const std::string& attribute : attributes) { if (MatchesPropertyFilters(property_filters, attribute)) { str += attribute + " "; } } str += "\n"; for (size_t i = 0; i < node->GetDelegate()->GetChildCount(); i++) { gfx::NativeViewAccessible child = node->GetDelegate()->ChildAtIndex(i); const ui::AXPlatformNode* child_node = ui::AXPlatformNode::FromNativeViewAccessible(child); str += RecursiveDumpAXPlatformNodeAsString(child_node, indent + 1, property_filters); } return str; } bool IsValidJSValue(const std::string* str) { return str && str->length() < 5000U; } void HandleAccessibilityRequestCallback( content::BrowserContext* current_context, const std::string& path, content::WebUIDataSource::GotDataCallback callback) { DCHECK(ShouldHandleAccessibilityRequestCallback(path)); base::Value::Dict data; ui::AXMode mode = content::BrowserAccessibilityState::GetInstance()->GetAccessibilityMode(); bool is_native_enabled = content::BrowserAccessibilityState::GetInstance() ->IsRendererAccessibilityEnabled(); bool native = mode.has_mode(ui::AXMode::kNativeAPIs); bool web = mode.has_mode(ui::AXMode::kWebContents); bool text = mode.has_mode(ui::AXMode::kInlineTextBoxes); bool screenreader = mode.has_mode(ui::AXMode::kScreenReader); bool html = mode.has_mode(ui::AXMode::kHTML); bool pdf = mode.has_mode(ui::AXMode::kPDF); // The "native" and "web" flags are disabled if // --disable-renderer-accessibility is set. data.Set(kNative, is_native_enabled ? (native ? kOn : kOff) : kDisabled); data.Set(kWeb, is_native_enabled ? (web ? kOn : kOff) : kDisabled); // The "text", "screenreader" and "html" flags are only // meaningful if "web" is enabled. bool is_web_enabled = is_native_enabled && web; data.Set(kText, is_web_enabled ? (text ? kOn : kOff) : kDisabled); data.Set(kScreenReader, is_web_enabled ? (screenreader ? kOn : kOff) : kDisabled); data.Set(kHTML, is_web_enabled ? (html ? kOn : kOff) : kDisabled); // TODO(codebytere): enable use of this flag. // // The "labelImages" flag works only if "web" is enabled, the current profile // has the kAccessibilityImageLabelsEnabled preference set and the appropriate // command line switch has been used. Since this is so closely tied into user // prefs and causes bugs, we're disabling it for now. bool are_accessibility_image_labels_enabled = is_web_enabled; data.Set(kLabelImages, kDisabled); // The "pdf" flag is independent of the others. data.Set(kPDF, pdf ? kOn : kOff); // Always dump the Accessibility tree. data.Set(kInternal, kOn); base::Value::List rvh_list; std::unique_ptr<content::RenderWidgetHostIterator> widgets( content::RenderWidgetHost::GetRenderWidgetHosts()); while (content::RenderWidgetHost* widget = widgets->GetNextHost()) { // Ignore processes that don't have a connection, such as crashed tabs. if (!widget->GetProcess()->IsInitializedAndNotDead()) continue; content::RenderViewHost* rvh = content::RenderViewHost::From(widget); if (!rvh) continue; content::WebContents* web_contents = content::WebContents::FromRenderViewHost(rvh); content::WebContentsDelegate* delegate = web_contents->GetDelegate(); if (!delegate) continue; // Ignore views that are never user-visible, like background pages. if (delegate->IsNeverComposited(web_contents)) continue; content::BrowserContext* context = rvh->GetProcess()->GetBrowserContext(); if (context != current_context) continue; base::Value::Dict descriptor = BuildTargetDescriptor(rvh); descriptor.Set(kNative, is_native_enabled); descriptor.Set(kWeb, is_web_enabled); descriptor.Set(kLabelImages, are_accessibility_image_labels_enabled); rvh_list.Append(std::move(descriptor)); } data.Set(kPagesField, std::move(rvh_list)); base::Value::List window_list; for (auto* window : electron::WindowList::GetWindows()) { window_list.Append(BuildTargetDescriptor(window)); } data.Set(kBrowsersField, std::move(window_list)); std::string json_string; base::JSONWriter::Write(data, &json_string); std::move(callback).Run( base::MakeRefCounted<base::RefCountedString>(std::move(json_string))); } } // namespace ElectronAccessibilityUI::ElectronAccessibilityUI(content::WebUI* web_ui) : content::WebUIController(web_ui) { // Set up the chrome://accessibility source. content::WebUIDataSource* html_source = content::WebUIDataSource::CreateAndAdd( web_ui->GetWebContents()->GetBrowserContext(), chrome::kChromeUIAccessibilityHost); // Add required resources. html_source->UseStringsJs(); html_source->AddResourcePaths( base::make_span(kAccessibilityResources, kAccessibilityResourcesSize)); html_source->SetDefaultResource(IDR_ACCESSIBILITY_ACCESSIBILITY_HTML); html_source->SetRequestFilter( base::BindRepeating(&ShouldHandleAccessibilityRequestCallback), base::BindRepeating(&HandleAccessibilityRequestCallback, web_ui->GetWebContents()->GetBrowserContext())); html_source->OverrideContentSecurityPolicy( network::mojom::CSPDirectiveName::TrustedTypes, "trusted-types parse-html-subset sanitize-inner-html;"); web_ui->AddMessageHandler( std::make_unique<ElectronAccessibilityUIMessageHandler>()); } ElectronAccessibilityUI::~ElectronAccessibilityUI() = default; ElectronAccessibilityUIMessageHandler::ElectronAccessibilityUIMessageHandler() = default; void ElectronAccessibilityUIMessageHandler::RequestNativeUITree( const base::Value::List& args) { const base::Value::Dict& data = args.front().GetDict(); const int window_id = *data.FindInt(kSessionIdField); const std::string* const request_type_p = data.FindString(kRequestTypeField); CHECK(IsValidJSValue(request_type_p)); std::string request_type = *request_type_p; CHECK(request_type == kShowOrRefreshTree || request_type == kCopyTree); request_type = "accessibility." + request_type; const std::string* const allow_p = data.FindStringByDottedPath("filters.allow"); CHECK(IsValidJSValue(allow_p)); const std::string* const allow_empty_p = data.FindStringByDottedPath("filters.allowEmpty"); CHECK(IsValidJSValue(allow_empty_p)); const std::string* const deny_p = data.FindStringByDottedPath("filters.deny"); CHECK(IsValidJSValue(deny_p)); AllowJavascript(); std::vector<ui::AXPropertyFilter> property_filters; AddPropertyFilters(&property_filters, *allow_p, ui::AXPropertyFilter::ALLOW); AddPropertyFilters(&property_filters, *allow_empty_p, ui::AXPropertyFilter::ALLOW_EMPTY); AddPropertyFilters(&property_filters, *deny_p, ui::AXPropertyFilter::DENY); for (auto* window : electron::WindowList::GetWindows()) { if (window->window_id() == window_id) { base::Value::Dict result = BuildTargetDescriptor(window); gfx::NativeWindow native_window = window->GetNativeWindow(); ui::AXPlatformNode* node = ui::AXPlatformNode::FromNativeWindow(native_window); result.Set(kTreeField, base::Value(RecursiveDumpAXPlatformNodeAsString( node, 0, property_filters))); CallJavascriptFunction(request_type, base::Value(std::move(result))); return; } } // No browser with the specified |id| was found. base::Value::Dict result; result.Set(kSessionIdField, window_id); result.Set(kTypeField, kBrowser); result.Set(kErrorField, "Window no longer exists."); CallJavascriptFunction(request_type, base::Value(std::move(result))); } void ElectronAccessibilityUIMessageHandler::RegisterMessages() { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); web_ui()->RegisterMessageCallback( "toggleAccessibility", base::BindRepeating(&AccessibilityUIMessageHandler::ToggleAccessibility, base::Unretained(this))); web_ui()->RegisterMessageCallback( "setGlobalFlag", base::BindRepeating(&AccessibilityUIMessageHandler::SetGlobalFlag, base::Unretained(this))); web_ui()->RegisterMessageCallback( "requestWebContentsTree", base::BindRepeating( &AccessibilityUIMessageHandler::RequestWebContentsTree, base::Unretained(this))); web_ui()->RegisterMessageCallback( "requestNativeUITree", base::BindRepeating( &ElectronAccessibilityUIMessageHandler::RequestNativeUITree, base::Unretained(this))); web_ui()->RegisterMessageCallback( "requestAccessibilityEvents", base::BindRepeating( &AccessibilityUIMessageHandler::RequestAccessibilityEvents, base::Unretained(this))); }
7b4c996664d6d46e20e507f378fad934a6fdd936
c766bece263e5149d0dbab04ea20308bf1191ab8
/AdobeInDesignCCProductsSDK.2020/source/public/interfaces/graphics/IOffscreenPortData.h
a5b294db1b97428221b6134d175c60484a3de6b8
[]
no_license
stevenstong/adobe-tools
37a36868619db90984d5303187305c9da1e024f7
c74d61d882363a91da4938fd525b97f83084cb2e
refs/heads/master
2022-04-08T17:31:35.516938
2020-03-18T20:57:40
2020-03-18T20:57:40
248,061,036
0
0
null
null
null
null
UTF-8
C++
false
false
4,617
h
//======================================================================================== // // $File: //depot/devtech/15.0/plugin/source/public/interfaces/graphics/IOffscreenPortData.h $ // // Owner: Jack Kirstein // // $Author: pmbuilder $ // // $DateTime: 2019/10/11 10:48:01 $ // // $Revision: #2 $ // // $Change: 1061132 $ // // Copyright 1997-2010 Adobe Systems Incorporated. All rights reserved. // // NOTICE: Adobe permits you to use, modify, and distribute this file in accordance // with the terms of the Adobe license agreement accompanying it. If you have received // this file from a source other than Adobe, then your use, modification, or // distribution of it requires the prior written permission of Adobe. // // // Purpose of interface: // This is the OffscreenPort specific interface attached to offscreen view ports. // It is a shell over the AGM API for setting up offscreen ports. // In order to use an offscreen port, you have to create an IPlatformBitmap and // then load that into the port via SetTargetBitmap. This is analogous to setting // the targetwindow on a window view port. // //======================================================================================== #pragma once #ifndef __IOffscreenPortData__ #define __IOffscreenPortData__ #include "IPMUnknown.h" #include "GraphicsID.h" #include "HelperInterface.h" #include "IDVOffscreenPortData.h" class PMMatrix; class IPlatformOffscreen; /** IOffscreenPortData is an interface for creating and updating platform offscreens. InDesign uses platform offscreen for two reasons: 1) to reduce screen flicker; 2) as a cache to avoid having to instantiate an item on a page in order to ask it to draw. On Mac OS X, the screen flicker case is handled by the OS so we don't need platform offscreens for that case. However, the optimizations that reason 2 provides forces us to continue using offscreens. This interface has methods to maintain 1 or more offscreens as used by the IOffscreenViewPortCache. The IOffscreenViewPortCache maintains two IOffscreenPortData ptrs: 1 for the background and 1 for the foreground. In the case of the layout window, the background offscreen is the contents of the window/document in an unselected state. The foreground is used as a composite. That is, if an update event occurs, we do the following: 1. Make sure the background offscreen is up to date. If nobody has called ILayoutController->InvalidateContent(), then there is nothing to do in this step. Typically, InvalidateContent() gets called by a document observer after a command has been processed which changes a page item or the layout in some way. 2. Copy the area to update from the background to the foreground. 3. Draw the selection into the foreground. 4. Draw the foreground to the window. With the introduction of Mac OS X, the foreground buffer is not needed. Rather, the OS provided back buffer can serve the purpose of the foreground/composite buffer. Hence, we need two different update methods in the IOffscreenPortData interface. One (the original UpdateTargetBitmap()) which allocates a new platform offscreen if the bounds are larger than the current one, and another, UpdateTargetBitmapIfDiffSize(), which allocates a new platform offscreen if the bounds are different. History: Prior to InDesign 3.0, there was 1 background and 1 foreground offscreen shared among all layout windows. As a result, if you had multiple documents open, switching between documents/windows caused a performance hit as we updated the contents of the bitmap. In addition, the size of the offscreen was the size of the largest window. Also, the IOffscreenViewPortCache interface lived on the Session boss since it was not associated with any window. For InDesign 3.0, I wanted to provide an offscreen per layout window. Hence, I added the IOffscreenViewPortCache to kLayoutWidgetBoss. As a result, we no longer need to have the background offscreen be the size of the largest window. However, since the foreground offscreen is simply a compositing buffer, I did not want to add a foreground offscreen per window. Therefore, the IOffscreenViewPortCache::QueryForegroundViewPort() implementation on the layout boss will simply query for the foreground viewport on the session boss. And, when it is time to update it due to a window resize, then the original UpdateTargetBitmap() function will be called. @see IOffscreenViewPortCache (now IDVOffscreenViewPortCache) */ typedef IDVOffscreenPortData IOffscreenPortData; #endif
bbd8a6fc85ced748779fba796e13ae057b03722d
d94436dbb76c4dd13d3e27dd254c70a5f5db1935
/src/layers/math/cereal_registration/sign.cpp
7cc76d06704cf381c01c59d7b3bb341e85dd03e3
[ "Apache-2.0" ]
permissive
gutseb/lbann
298a96ac4f406a20cd8e10b10dce688d2ac6ee52
0433bb81133f54d9555849e710e445b37383d2b8
refs/heads/master
2023-09-01T10:25:50.318390
2021-05-28T00:08:01
2021-05-28T00:08:01
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,742
cpp
//////////////////////////////////////////////////////////////////////////////// // Copyright (c) 2014-2019, Lawrence Livermore National Security, LLC. // Produced at the Lawrence Livermore National Laboratory. // Written by the LBANN Research Team (B. Van Essen, et al.) listed in // the CONTRIBUTORS file. <[email protected]> // // LLNL-CODE-697807. // All rights reserved. // // This file is part of LBANN: Livermore Big Artificial Neural Network // Toolkit. For details, see http://software.llnl.gov/LBANN or // https://github.com/LLNL/LBANN. // // Licensed under the Apache License, Version 2.0 (the "Licensee"); you // may not use this file except in compliance with the License. You may // obtain a copy of the License at: // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or // implied. See the License for the specific language governing // permissions and limitations under the license. //////////////////////////////////////////////////////////////////////////////// #include "lbann/utils/serialize.hpp" #include <lbann/layers/math/unary.hpp> namespace lbann { template <typename TensorDataType, data_layout Layout, El::Device Device> template <typename ArchiveT> void sign_layer<TensorDataType,Layout,Device> ::serialize(ArchiveT& ar) { using DataTypeLayer = data_type_layer<TensorDataType>; ar(::cereal::make_nvp("DataTypeLayer", ::cereal::base_class<DataTypeLayer>(this))); } } // namespace lbann #define LBANN_LAYER_NAME sign_layer #include <lbann/macros/register_layer_with_cereal.hpp>
6e5b0a402f6a613874b32e8caf3aacccffe0c754
af0ecafb5428bd556d49575da2a72f6f80d3d14b
/CodeJamCrawler/dataset/13_19946_80.cpp
ed21e28f3a0a320a81c84b526399186a38e496d0
[]
no_license
gbrlas/AVSP
0a2a08be5661c1b4a2238e875b6cdc88b4ee0997
e259090bf282694676b2568023745f9ffb6d73fd
refs/heads/master
2021-06-16T22:25:41.585830
2017-06-09T06:32:01
2017-06-09T06:32:01
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,702
cpp
#include <algorithm> #include <cassert> #include <cmath> #include <cstring> #include <cctype> #include <fstream> #include <functional> #include <iostream> #include <map> #include <queue> #include <set> #include <sstream> #include <stack> #include <string> #include <vector> using namespace std; #define VAR(a,b) __typeof(b) a=(b) #define REP(i,n) for(int _n=n, i=0;i<_n;++i) #define FOR(i,a,b) for(int i=(a),_b=(b);i<=_b;++i) #define FORD(i,a,b) for(int i=(a),_b=(b);i>=_b;--i) #define FOREACH(it,c) for(VAR(it,(c).begin());it!=(c).end();++it) #define ALL(c) (c).begin(),(c).end() #define TRACE(x) cerr << "TRACE(" #x ")" << endl; #define DEBUG(x) cerr << #x << " = " << x << endl; #define eprintf(...) fprintf(stderr, __VA_ARGS__) typedef long long ll; typedef long double ld; typedef unsigned long ulong; typedef unsigned long long ull; typedef vector<int> VI; typedef vector<vector<int> > VVI; typedef vector<char> VC; int a[200][200]; bool check(int N, int M) { REP(i,N) { REP(j,M) { bool nok = true; REP(k,N) if (a[k][j] > a[i][j]) nok = false; bool mok = true; REP(k,M) if (a[i][k] > a[i][j]) mok = false; if (nok || mok) ; else return false; } } return true; } int main() { //freopen("input", "r", stdin); //freopen("output", "w", stdout); int TN; scanf("%d", &TN); FOR(TI,1,TN) { int N, M; scanf("%d%d", &N, &M); REP(i,N) { REP(j,M) scanf("%d", &a[i][j]); } bool ok = check(N, M); printf("Case #%d: %s\n", TI, ((ok)? "YES" : "NO")); } return 0; }
580bc90e40428e7b7e5309f4fe29f9a21b7f197f
785f4629363e9426ad99763918ea7bd96bce2b21
/Engine/include/Engine/Manager/ColliderManager.h
f3baf3f156e19fd161426e325f24a7d48d42ba94
[]
no_license
NeoDahos/Robot-Survival
f5124b6bd03b1f7d236157bb421d5875d256ff88
5e5dcbaed200966262c88867185e3cea64e8e70c
refs/heads/master
2020-12-24T21:55:33.938832
2016-05-05T07:40:09
2016-05-05T07:40:09
57,878,928
0
0
null
null
null
null
UTF-8
C++
false
false
499
h
#ifndef COLLIDER_MANAGER_H #define COLLIDER_MANAGER_H #include <Engine\Export.h> #include <SFML\System\NonCopyable.hpp> #include <list> namespace engine { class Collider; class ENGINE_API ColliderManager : public sf::NonCopyable { public: ColliderManager(); ~ColliderManager(); void AddCollider(Collider* const _collider); void EraseCollider(Collider* const _collider); void ComputeCollisions(); protected: std::list<Collider*> m_colliders; }; } #endif // COLLIDER_MANAGER_H
93f1486bead20e1ad41423cd758008134fe59ae8
fee42f7dd84c0799a2dea25d08e52f99b2b88b22
/ContestUri2018/poesia.cc
a8212fe1210194705491efaa0414d44d19fbed83
[]
no_license
eassisv/online-judge
0d997bb592f2af772454fe1d2125518cc841bfa2
33c5bcf818e3635e71c7fafafb82753bff34601b
refs/heads/master
2020-03-27T03:12:22.721276
2018-11-29T01:22:15
2018-11-29T01:22:15
145,845,940
0
0
null
null
null
null
UTF-8
C++
false
false
815
cc
#include<bits/stdc++.h> using namespace std; #define pb push_back const int MAX = 2e3+1; vector<int> divs, ns, rs(MAX); int main(void) { int N, ans; cin >> N; for(int i = 2, j = N, d = 0; j > 1;){ if(j % i) { d = 0; ++i; continue; } if(!d) { d = 1; divs.pb(i); } else { int x = i * divs.back(); divs.pb(x); } j /= i; } sort(divs.begin(), divs.end()); for(int i = 0; i < N; i++) { int x; scanf("%d", &x); ns.pb(x); } ans = -1; for(auto i : divs) { int x = N / i; for(auto j : ns){ rs[j % i] += 1; } ans = i; for(int j = 0; j < i; j++) { if(rs[j] != x) ans = -1; rs[j] = 0; } if(ans != -1) break; } cout << ans << '\n'; }
118c0ed9d54842ff8f8213d557903c8a0a33854c
9ad40d7fff54f5e4f36ae974e33712a9beb7378e
/codeforces/2.cpp
9631d9797331d284c1a3fd5a2c852d013531bc13
[]
no_license
vikram-shaw/cpp
7fcac406b003dd717abe43fc5f15ea253b486b1d
8d4367dedef4e48aed649c8174cee74d38be09ea
refs/heads/master
2023-01-31T19:13:04.363704
2020-12-20T05:50:24
2020-12-20T05:50:24
null
0
0
null
null
null
null
UTF-8
C++
false
false
885
cpp
#include<bits/stdc++.h> using namespace std; bool com(pair<int,int>& p1, pair<int,int>& p2) { if(p1.first >= p2.first && p1.second >=p2.second) return true; return false; } int main() { int t; cin>>t; while(t--) { int n; cin>>n; vector<pair<int,int>> path(n); for(int i=0;i<n;i++) cin>>path[i].first>>path[i].second; sort(path.begin(),path.end()); pair<int,int> s{0,0}; bool f = false; int i; for(i=1;i<n;i++) { if(path[i].first < path[i-1].first || path[i].second < path[i-1].second) break; } if(i==n) { cout<<"YES\n"; for(int i=0;i<n;i++) { while(s.first < path[i].first || s.second < path[i].second) { if(s.first < path[i].first){ s.first++; cout<<"R"; } else if(s.second < path[i].second){ s.second++; cout<<"U"; } } } cout<<"\n"; } else cout<<"NO\n"; } }
bc004e81e77b175cd99b65b990c74d81ae0f1eba
ceec4b43ae576fc911000aaff4d045fcd50c1864
/prog/makeR.cpp
17fe482b89c2736c6a302996e2ecc3bc329228b5
[]
no_license
MasanoriYamada/analistic_functions
33a6ad29359892354b9ebb43ce323f70b8da7598
5a25771a4b97799eba1820058c0aad00c062bced
refs/heads/master
2016-09-09T19:55:28.512439
2013-11-26T07:14:28
2013-11-26T07:14:28
31,621,249
0
0
null
null
null
null
UTF-8
C++
false
false
8,580
cpp
/*2点相関関数(confを抜いたやつ)とBS波動関数(confを抜いたやつ)を読み込んでR相関関数を作る*/ #include<complex> #include <iostream> #include <iomanip> #include <fstream> #include "../include/analys.h" using namespace std; typedef std::complex<double> COMPLEX; #define I std::complex<double>(0.0,1.0) static const int datasize=XYZnodeSites; int call_data(int,int,COMPLEX[],COMPLEX[]); int call_prop(char[],COMPLEX[]); int call_omegaprop(char[],COMPLEX[]); void make_R(COMPLEX[],COMPLEX[],COMPLEX[]); void out_data(int,int,COMPLEX[]); int out_R(char[],COMPLEX[]); main(int argc, char* argv[]){ dir_path=argv[1]; cout <<"Directory path ::"<<dir_path<<endl; in_dir_path = dir_path; out_dir_path = dir_path; root_mkdir(out_dir_path.c_str()); out_dir_path = out_dir_path + "/Rcor"; root_mkdir(out_dir_path.c_str()); out_dir_path = out_dir_path + "/binR"; root_mkdir(out_dir_path.c_str()); out_dir_path = out_dir_path + "/xyz"; root_mkdir(out_dir_path.c_str()); for ( int j=0; j<binnumber; j++) { cout <<"conf"<<j<<"を計算中・・・"<<endl; for (int it=T_in; it<T_fi+1; it++) { COMPLEX* omega_sub_prop = new COMPLEX[1]; COMPLEX* ave_sub_sub = new COMPLEX[datasize]; call_data(it,j,&(ave_sub_sub[0]),&(omega_sub_prop[0])); COMPLEX* R_sub=new COMPLEX[datasize]; make_R(&(ave_sub_sub[0]),&(omega_sub_prop[0]),&(R_sub[0])); out_data(it,j,&(R_sub[0])); delete []ave_sub_sub; delete []omega_sub_prop; delete []R_sub; }} cout << "finished"<<endl; return 0; } //メインの計算の所、時間と空間をいれてomegaの相関関数を計算する /************************************************************************************************************************************************/ //call_q_propを使いquarkプロパゲータを呼び出す。call_dataでcall_q_propの適用先をconf i番目にする no (fanameをいじると読み込むファイル,データを入れる配列[Maxsize]) // /************************************************************************************************************************************************/ int call_data(int it,int b,COMPLEX local[datasize],COMPLEX local1[1]){ char fnameBS[200]={0}; char fname2point[200]={0}; sprintf(fnameBS,"%s/Projwave/binProjwave/xyz/binBS.%s.%06d-%06d.it%03d",in_dir_path.c_str(),base,binnumber,b,it); sprintf(fname2point,"%s/tcor2pt/bintcor2pt/%02d/tcor2pt.%s.%06d-%06d.it%02d",in_dir_path.c_str(),it,base,binnumber,b,it); call_prop(&(fnameBS[0]),&(local[0])); call_omegaprop(&(fname2point[0]),&(local1[0])); return 0; } /******************************************************************************/ //ファイルからぬいた4点データを呼び出す no (読み込むファイルパス,読みだしたout用の配列(double) // /******************************************************************************/ int call_prop(char fname[200],COMPLEX data[datasize]){ int switch1=0; if (switch1==0) { fstream infile; infile.open(fname,ios::in|ios::binary); if (!infile.is_open()) { cout << "ERROR file can't open (no exist) ::"<<fname<<endl; exit(1); return EXIT_FAILURE; } if (infile.fail()){ cout << "ERROR file size is 0 (can open) ::"<<fname<<endl; exit(1); return EXIT_FAILURE; } int id=0; while(!infile.eof()){ infile.read( ( char * ) &data[id], sizeof( COMPLEX ) ); id=id+1; //cout << id<<endl; } static int tmp=0; if (tmp==0) { cout <<"reading data size is ;;"<<id<<endl; tmp=tmp+1; } //endian_convert((double*)data,datasize*2); for (int point=0; point<id; point++) { //cout << data[point]<<endl; }} if (switch1==1) { std::ifstream ifs( fname , ios::in ); /* テキストモードで */ if(! ifs ) { cout << fname<<"ファイルが開きません"<<endl; return 1; } // getline( ifs,ss ); int tmpx[datasize]; int tmpy[datasize]; int tmpz[datasize]; for(int id=0; id<datasize; ++id) { ifs>>std::setw(3)>>tmpx[id]>>std::setw(3)>>tmpy[id]>>std::setw(3)>>tmpz[id]>>setprecision(15)>> data[id].real()>>setprecision(15)>>data[id].imag(); //cout<<std::setw(3)<<tmpx[id]<<std::setw(3)<<tmpy[id]<<std::setw(3)<<tmpz[id]<<setprecision(15)<< local[id].real()<<setprecision(15)<<local[id].imag()<<endl; } } return 0; } /******************************************************************************/ //ファイルから抜いた2点データを呼び出す no (読み込むファイルパス,読みだしたout用の配列(double) // /******************************************************************************/ int call_omegaprop(char fname[200],COMPLEX data[1]){ int switch1=0; if (switch1==0) { fstream infile; infile.open(fname,ios::in|ios::binary); if (!infile.is_open()) { cout << "ERROR file can't open (no exist) ::"<<fname<<endl; return EXIT_FAILURE; } int id=0; while(!infile.eof()){ infile.read( ( char * ) &data[id], sizeof( COMPLEX ) ); id=id+1; //cout << id<<endl; } static int tmp=0; if (tmp==0) { cout <<"reading data size is ;;"<<id<<endl; tmp=tmp+1; } //endian_convert((double*)data,datasize*2); for (int point=0; point<id; point++) { //cout << data[point]<<endl; } infile.close(); } if (switch1==1) { std::ifstream ifs( fname , ios::in ); /* テキストモードで */ if(! ifs ) { cout << fname<<"ファイルが開きません"<<endl; return 1; } // getline( ifs,ss ); int tmpx[1]; int tmpy[1]; int tmpz[1]; for(int id=0; id<1; ++id) { ifs>>std::setw(15)>> data[id].real()>>std::setw(15)>> data[id].imag(); //cout << std::setw(15)<<local[id].real()<<std::setw(15)<<local[id].img()<<endl; //ifs>>std::setw(3)>>tmpx[id]>>std::setw(3)>>tmpy[id]>>std::setw(3)>>tmpz[id]>>setprecision(15)>> local[id].real()>>setprecision(15)>>local[id].imag(); //cout<<std::setw(3)<<tmpx[id]<<std::setw(3)<<tmpy[id]<<std::setw(3)<<tmpz[id]<<setprecision(15)<< local[id].real()<<setprecision(15)<<local[id].imag()<<endl; }} return 0; } /************************************************************************************************************************************************/ //out_BSwaveを使いBS波動関数を書き出す。out_dataでout_BSwaveの適用先をconf j番目にする no (fanameをいじると出力ファイル,入力データの配列[Maxsize]) // /************************************************************************************************************************************************/ void out_data(int it,int j,COMPLEX local[datasize]){ char fname[300]={0}; sprintf(fname,"%s/binRwave.%s.%06d-%06d.it%03d",out_dir_path.c_str(),base,binnumber,j,it); out_R(&(fname[0]),&(local[0])); } /**************************************************************************/ //結果を書き出す no (書きだすファイルパス,BS波動関数) // /**************************************************************************/ int out_R(char fname[300],COMPLEX R_sub[datasize]){ ofstream ofs(fname,ios::binary|ios::trunc); if (!ofs.is_open()) { cout << "ERROR output file can't open (can't create)"<<endl; return EXIT_FAILURE; } for (int z=0; z<ZnodeSites; z++) { for (int y=0; y<YnodeSites; y++) { for (int x=0; x<XnodeSites; x++) { ofs.write((const char*) &(R_sub[(x) +XnodeSites*((y) + YnodeSites*((z)))]),sizeof( COMPLEX )); //cout << x<<" "<<y<<" "<<z<<" "<<R_sub[(x) +XnodeSites*((y) + YnodeSites*((z)))]<<endl; } } } ofs.close(); /* std::ofstream ofs( &(fname[0])); for (int z=0; z<ZnodeSites; z++) { for (int y=0; y<YnodeSites; y++) { for (int x=0; x<XnodeSites; x++) { ofs<<std::setw(3)<<x<<std::setw(3)<<y<<std::setw(3)<<z<<setprecision(15)<< R_sub[(x) +XnodeSites*((y) + YnodeSites*((z)))].real()<<setprecision(15)<< R_sub[(x) +XnodeSites*((y) + YnodeSites*((z)))].imag()<<endl; }}}*/ return 0; } /******************************************************************************/ //R_correlatorを作る。 BS/(2point*2point) // /******************************************************************************/ void make_R(COMPLEX jack_ave_sub_sub[datasize],COMPLEX omega_sub_prop[1],COMPLEX R_sub[datasize]){ for (int id=0; id<datasize; id++) { R_sub[id]=jack_ave_sub_sub[id]/((omega_sub_prop[0])*(omega_sub_prop[0])); //cout << "jack_ave"<<jack_ave_sub_sub[id]<<endl; //cout << "omegaprop"<<omega_sub_prop[0]<<endl; //cout << "R_sub"<<R_sub[id]<<endl; } }
09dfc8eff23ce47bf507215f1537179e074e6110
40efd1998af596082f5a006f0e2c5bc12d8e7ebc
/CppSQLite3U.cpp
2e9a0595c05677fa3105c6fb7013be9b36e7d9e2
[ "MIT" ]
permissive
cmf41013/CppSQLite3U
968a4386081b2c58cbac422ec80cc88d20444338
18d86b8c5619dcb71eb8dcebf62273a65547a2db
refs/heads/master
2021-05-28T05:30:05.364827
2014-11-20T09:45:43
2014-11-20T09:45:43
null
0
0
null
null
null
null
UTF-8
C++
false
false
20,099
cpp
//////////////////////////////////////////////////////////////////////////////// // CppSQLite3U is a C++ unicode wrapper around the SQLite3 embedded database library. // // Copyright (c) 2006 Tyushkov Nikolay. All Rights Reserved. http://softvoile.com // // // Based on beautiful wrapper written by Rob Groves // (https://secure.codeproject.com/database/CppSQLite.asp). // Very good wrapper, but without unicode support unfortunately. // So, I have reconstructed it for unicode. // // CppSQLite3 wrapper: // Copyright (c) 2004 Rob Groves. All Rights Reserved. [email protected] // // Permission to use, copy, modify, and distribute this software and its // documentation for any purpose, without fee, and without a written // agreement, is hereby granted, provided that the above copyright notice, // this paragraph and the following two paragraphs appear in all copies, // modifications, and distributions. // // IN NO EVENT SHALL THE AUTHOR BE LIABLE TO ANY PARTY FOR DIRECT, // INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING LOST // PROFITS, ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, // EVEN IF THE AUTHOR HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // THE AUTHOR SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A // PARTICULAR PURPOSE. THE SOFTWARE AND ACCOMPANYING DOCUMENTATION, IF // ANY, PROVIDED HEREUNDER IS PROVIDED "AS IS". THE AUTHOR HAS NO OBLIGATION // TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS. // // If you want to get some documentation look at // https://secure.codeproject.com/database/CppSQLite.asp // Note, not all features from CppSQLite3 were implemented in CppSQLite3U // // V1.0 11/06/2006 - Initial Public Version // // Noteses : // I have tested this wrapper only in unicode version, so I have no idea // about its work in ANSI configuration, I think it doesn't work without modification;) // // Home page : http://softvoile.com/development/CppSQLite3U/ // Please send all bug report and comment to [email protected] // // //////////////////////////////////////////////////////////////////////////////// #include "stdafx.h" #include "CppSQLite3U.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif ///////////////////////////////////////////////////////////////////////////// // CppSQLite3Exception CppSQLite3Exception::CppSQLite3Exception(const int nErrCode, LPTSTR szErrMess, bool bDeleteMsg/*=true*/) : mnErrCode(nErrCode) { int bufSize = szErrMess ? _tcslen(szErrMess) + 50 : 50; mpszErrMess = new TCHAR[ bufSize ]; _stprintf_s(mpszErrMess, bufSize, _T("%s[%d]: %s"), errorCodeAsString(nErrCode), nErrCode, szErrMess ? szErrMess : _T("")); // _stprintf(mpszErrMess, _T("%s[%d]: %s"), // errorCodeAsString(nErrCode), // nErrCode, // szErrMess ? szErrMess : _T("")); if (bDeleteMsg && szErrMess) { _sqlite3_free((char*)szErrMess); } } CppSQLite3Exception::CppSQLite3Exception(const CppSQLite3Exception& e) : mnErrCode(e.mnErrCode) { mpszErrMess = 0; if (e.mpszErrMess) { int bufSize = _tcslen(e.mpszErrMess) + 10; mpszErrMess = new TCHAR[bufSize]; _stprintf_s(mpszErrMess, bufSize, _T("%s"), e.mpszErrMess); // _stprintf(mpszErrMess, _T("%s"), e.mpszErrMess); } } LPCTSTR CppSQLite3Exception::errorCodeAsString(int nErrCode) { switch (nErrCode) { case SQLITE_OK: return _T("SQLITE_OK"); case SQLITE_ERROR: return _T("SQLITE_ERROR"); case SQLITE_INTERNAL: return _T("SQLITE_INTERNAL"); case SQLITE_PERM: return _T("SQLITE_PERM"); case SQLITE_ABORT: return _T("SQLITE_ABORT"); case SQLITE_BUSY: return _T("SQLITE_BUSY"); case SQLITE_LOCKED: return _T("SQLITE_LOCKED"); case SQLITE_NOMEM: return _T("SQLITE_NOMEM"); case SQLITE_READONLY: return _T("SQLITE_READONLY"); case SQLITE_INTERRUPT: return _T("SQLITE_INTERRUPT"); case SQLITE_IOERR: return _T("SQLITE_IOERR"); case SQLITE_CORRUPT: return _T("SQLITE_CORRUPT"); case SQLITE_NOTFOUND: return _T("SQLITE_NOTFOUND"); case SQLITE_FULL: return _T("SQLITE_FULL"); case SQLITE_CANTOPEN: return _T("SQLITE_CANTOPEN"); case SQLITE_PROTOCOL: return _T("SQLITE_PROTOCOL"); case SQLITE_EMPTY: return _T("SQLITE_EMPTY"); case SQLITE_SCHEMA: return _T("SQLITE_SCHEMA"); case SQLITE_TOOBIG: return _T("SQLITE_TOOBIG"); case SQLITE_CONSTRAINT: return _T("SQLITE_CONSTRAINT"); case SQLITE_MISMATCH: return _T("SQLITE_MISMATCH"); case SQLITE_MISUSE: return _T("SQLITE_MISUSE"); case SQLITE_NOLFS: return _T("SQLITE_NOLFS"); case SQLITE_AUTH: return _T("SQLITE_AUTH"); case SQLITE_FORMAT: return _T("SQLITE_FORMAT"); case SQLITE_RANGE: return _T("SQLITE_RANGE"); case SQLITE_ROW: return _T("SQLITE_ROW"); case SQLITE_DONE: return _T("SQLITE_DONE"); case CPPSQLITE_ERROR: return _T("CPPSQLITE_ERROR"); default: return _T("UNKNOWN_ERROR"); } } CppSQLite3Exception::~CppSQLite3Exception() { if (mpszErrMess) { delete [] mpszErrMess; mpszErrMess = 0; } } ///////////////////////////////////////////////////////////////////////////// // CppSQLite3DB CppSQLite3DB::CppSQLite3DB() { mpDB = 0; mnBusyTimeoutMs = 60000; // 60 seconds } CppSQLite3DB::CppSQLite3DB(const CppSQLite3DB& db) { mpDB = db.mpDB; mnBusyTimeoutMs = 60000; // 60 seconds } CppSQLite3DB::~CppSQLite3DB() { close(); } //////////////////////////////////////////////////////////////////////////////// CppSQLite3DB& CppSQLite3DB::operator=(const CppSQLite3DB& db) { mpDB = db.mpDB; mnBusyTimeoutMs = 60000; // 60 seconds return *this; } void CppSQLite3DB::open(LPCTSTR szFile) { int nRet; #if defined(_UNICODE) || defined(UNICODE) nRet = sqlite3_open16(szFile, &mpDB); // not tested under window 98 #else // For Ansi Version //*************- Added by Begemot szFile must be in unicode- 23/03/06 11:04 - **** OSVERSIONINFOEX osvi; ZeroMemory(&osvi, sizeof(OSVERSIONINFOEX)); osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEX); GetVersionEx ((OSVERSIONINFO *) &osvi); if ( osvi.dwMajorVersion == 5) { WCHAR pMultiByteStr[MAX_PATH+1]; MultiByteToWideChar( CP_ACP, 0, szFile, _tcslen(szFile)+1, pMultiByteStr, sizeof(pMultiByteStr)/sizeof(pMultiByteStr[0]) ); nRet = sqlite3_open16(pMultiByteStr, &mpDB); } else nRet = sqlite3_open(szFile,&mpDB); #endif //************************* if (nRet != SQLITE_OK) { LPCTSTR szError = (LPCTSTR) _sqlite3_errmsg(mpDB); throw CppSQLite3Exception(nRet, (LPTSTR)szError, DONT_DELETE_MSG); } setBusyTimeout(mnBusyTimeoutMs); } void CppSQLite3DB::close() { if (mpDB) { int nRet = _sqlite3_close(mpDB); if (nRet != SQLITE_OK) { LPCTSTR szError = (LPCTSTR)_sqlite3_errmsg(mpDB); throw CppSQLite3Exception(nRet, (LPTSTR)szError, DONT_DELETE_MSG); } mpDB = 0; } } CppSQLite3Statement CppSQLite3DB::compileStatement(LPCTSTR szSQL) { checkDB(); sqlite3_stmt* pVM = compile(szSQL); return CppSQLite3Statement(mpDB, pVM); } bool CppSQLite3DB::tableExists(LPCTSTR szTable) { TCHAR szSQL[128]; _stprintf_s(szSQL, 127, _T("select count(*) from sqlite_master where type='table' and name='%s'"), szTable); int nRet = execScalar(szSQL); return (nRet > 0); } int CppSQLite3DB::execDML(LPCTSTR szSQL) { int nRet; sqlite3_stmt* pVM; checkDB(); do { pVM = compile(szSQL); nRet = _sqlite3_step(pVM); if (nRet == SQLITE_ERROR) { LPCTSTR szError = (LPCTSTR) _sqlite3_errmsg(mpDB); throw CppSQLite3Exception(nRet, (LPTSTR)szError, DONT_DELETE_MSG); } nRet = _sqlite3_finalize(pVM); } while (nRet == SQLITE_SCHEMA); } CppSQLite3Query CppSQLite3DB::execQuery(LPCTSTR szSQL) { checkDB(); int nRet; sqlite3_stmt* pVM; do { pVM = compile(szSQL); nRet = _sqlite3_step(pVM); if (nRet == SQLITE_DONE) { // no rows return CppSQLite3Query(mpDB, pVM, true/*eof*/); } else if (nRet == SQLITE_ROW) { // at least 1 row return CppSQLite3Query(mpDB, pVM, false/*eof*/); } nRet = _sqlite3_finalize(pVM); } while (nRet == SQLITE_SCHEMA); // Edit By Begemot 08/16/06 12:44:35 - read SQLite FAQ LPCTSTR szError = (LPCTSTR) _sqlite3_errmsg(mpDB); throw CppSQLite3Exception(nRet, (LPTSTR)szError, DONT_DELETE_MSG); } int CppSQLite3DB::execScalar(LPCTSTR szSQL) { CppSQLite3Query q = execQuery(szSQL); if (q.eof() || q.numFields() < 1 || q.fieldValue(0) == NULL) throw CppSQLite3Exception(CPPSQLITE_ERROR, _T("Invalid scalar query"), DONT_DELETE_MSG); return _tstoi(q.fieldValue(0)); } // Added By Begemot, exact as execScalar but return CString 08/06/06 16:30:37 CString CppSQLite3DB::execScalarStr(LPCTSTR szSQL) { CppSQLite3Query q = execQuery(szSQL); if (q.eof() || q.numFields() < 1) throw CppSQLite3Exception(CPPSQLITE_ERROR, _T("Invalid scalar query"), DONT_DELETE_MSG); return (CString)q.getStringField(0); } sqlite_int64 CppSQLite3DB::lastRowId() { return sqlite3_last_insert_rowid(mpDB); } void CppSQLite3DB::setBusyTimeout(int nMillisecs) { mnBusyTimeoutMs = nMillisecs; sqlite3_busy_timeout(mpDB, mnBusyTimeoutMs); } void CppSQLite3DB::checkDB() { if (!mpDB) throw CppSQLite3Exception(CPPSQLITE_ERROR,_T("Database not open"), DONT_DELETE_MSG); } sqlite3_stmt* CppSQLite3DB::compile(LPCTSTR szSQL) { checkDB(); sqlite3_stmt* pVM; int nRet = _sqlite3_prepare(mpDB, szSQL, -1, &pVM, NULL); if (nRet != SQLITE_OK) { pVM = NULL; LPCTSTR szError = (LPCTSTR) _sqlite3_errmsg(mpDB); throw CppSQLite3Exception(nRet, (LPTSTR)szError, DONT_DELETE_MSG); } return pVM; } //////////////////////// CppSQLite3Statement /////////////////////////////////////////// CppSQLite3Statement::CppSQLite3Statement() { mpDB = 0; mpVM = 0; } CppSQLite3Statement::CppSQLite3Statement(const CppSQLite3Statement& rStatement) { mpDB = rStatement.mpDB; mpVM = rStatement.mpVM; // Only one object can own VM const_cast<CppSQLite3Statement&>(rStatement).mpVM = 0; } CppSQLite3Statement::CppSQLite3Statement(sqlite3* pDB, sqlite3_stmt* pVM) { mpDB = pDB; mpVM = pVM; } CppSQLite3Statement::~CppSQLite3Statement() { try { finalize(); } catch (...) {} } CppSQLite3Statement& CppSQLite3Statement::operator=(const CppSQLite3Statement& rStatement) { mpDB = rStatement.mpDB; mpVM = rStatement.mpVM; // Only one object can own VM const_cast<CppSQLite3Statement&>(rStatement).mpVM = 0; return *this; } int CppSQLite3Statement::execDML() { checkDB(); checkVM(); int nRet = sqlite3_step(mpVM); if (nRet == SQLITE_DONE) { int nRowsChanged = sqlite3_changes(mpDB); nRet = sqlite3_reset(mpVM); if (nRet != SQLITE_OK) { LPCTSTR szError = (LPCTSTR) _sqlite3_errmsg(mpDB); throw CppSQLite3Exception(nRet, (LPTSTR)szError, DONT_DELETE_MSG); } return nRowsChanged; } else { nRet = sqlite3_reset(mpVM); LPCTSTR szError = (LPCTSTR) _sqlite3_errmsg(mpDB); throw CppSQLite3Exception(nRet, (LPTSTR)szError, DONT_DELETE_MSG); } } void CppSQLite3Statement::bind(int nParam, LPCTSTR szValue) { checkVM(); int nRes = _sqlite3_bind_text(mpVM, nParam, szValue, -1, SQLITE_TRANSIENT); if (nRes != SQLITE_OK) throw CppSQLite3Exception(nRes,_T("Error binding string param"), DONT_DELETE_MSG); } void CppSQLite3Statement::bind(int nParam, const int nValue) { checkVM(); int nRes = sqlite3_bind_int(mpVM, nParam, nValue); if (nRes != SQLITE_OK) throw CppSQLite3Exception(nRes,_T("Error binding int param"), DONT_DELETE_MSG); } void CppSQLite3Statement::bind(int nParam, const double dValue) { checkVM(); int nRes = sqlite3_bind_double(mpVM, nParam, dValue); if (nRes != SQLITE_OK) throw CppSQLite3Exception(nRes, _T("Error binding double param"), DONT_DELETE_MSG); } void CppSQLite3Statement::bind(int nParam, const unsigned char* blobValue, int nLen) { checkVM(); int nRes = sqlite3_bind_blob(mpVM, nParam, (const void*)blobValue, nLen, SQLITE_TRANSIENT); if (nRes != SQLITE_OK) throw CppSQLite3Exception(nRes,_T("Error binding blob param"), DONT_DELETE_MSG); } void CppSQLite3Statement::bindNull(int nParam) { checkVM(); int nRes = sqlite3_bind_null(mpVM, nParam); if (nRes != SQLITE_OK) throw CppSQLite3Exception(nRes,_T("Error binding NULL param"), DONT_DELETE_MSG); } int CppSQLite3Statement::bindParameterIndex(LPCTSTR szParam) { checkVM(); CStringA s(szParam); int nParam = _sqlite3_bind_parameter_index(mpVM, s); int nn = sqlite3_bind_parameter_count(mpVM); const char* sz1 = sqlite3_bind_parameter_name(mpVM, 1); const char* sz2 = sqlite3_bind_parameter_name(mpVM, 2); if (!nParam) { TCHAR buf[128]; _stprintf_s(buf, 128, _T("Parameter '%s' is not valid for this statement"), szParam); throw CppSQLite3Exception(CPPSQLITE_ERROR, buf, DONT_DELETE_MSG); } return nParam; } void CppSQLite3Statement::bind(LPCTSTR szParam, LPCTSTR szValue) { int nParam = bindParameterIndex(szParam); bind(nParam, szValue); } void CppSQLite3Statement::bind(LPCTSTR szParam, int const nValue) { int nParam = bindParameterIndex(szParam); bind(nParam, nValue); } void CppSQLite3Statement::bind(LPCTSTR szParam, double const dwValue) { int nParam = bindParameterIndex(szParam); bind(nParam, dwValue); } void CppSQLite3Statement::bind(LPCTSTR szParam, unsigned char const* blobValue, int nLen) { int nParam = bindParameterIndex(szParam); bind(nParam, blobValue, nLen); } void CppSQLite3Statement::bindNull(LPCTSTR szParam) { int nParam = bindParameterIndex(szParam); bindNull(nParam); } void CppSQLite3Statement::reset() { if (mpVM) { int nRet = sqlite3_reset(mpVM); if (nRet != SQLITE_OK) { LPCTSTR szError = (LPCTSTR) _sqlite3_errmsg(mpDB); throw CppSQLite3Exception(nRet, (LPTSTR)szError, DONT_DELETE_MSG); } } } void CppSQLite3Statement::finalize() { if (mpVM) { int nRet = sqlite3_finalize(mpVM); mpVM = 0; if (nRet != SQLITE_OK) { LPCTSTR szError = (LPCTSTR) _sqlite3_errmsg(mpDB); throw CppSQLite3Exception(nRet, (LPTSTR)szError, DONT_DELETE_MSG); } } } void CppSQLite3Statement::checkDB() { if (mpDB == 0) throw CppSQLite3Exception(CPPSQLITE_ERROR,_T("Database not open"), DONT_DELETE_MSG); } void CppSQLite3Statement::checkVM() { if (mpVM == 0) throw CppSQLite3Exception(CPPSQLITE_ERROR,_T("Null Virtual Machine pointer"), DONT_DELETE_MSG); } ///////////////////// CppSQLite3Query ////////////////////////////////////////////////// CppSQLite3Query::CppSQLite3Query() { mpVM = 0; mbEof = true; mnCols = 0; mbOwnVM = false; } CppSQLite3Query::CppSQLite3Query(const CppSQLite3Query& rQuery) { mpVM = rQuery.mpVM; // Only one object can own the VM const_cast<CppSQLite3Query&>(rQuery).mpVM = 0; mbEof = rQuery.mbEof; mnCols = rQuery.mnCols; mbOwnVM = rQuery.mbOwnVM; } CppSQLite3Query::CppSQLite3Query(sqlite3* pDB, sqlite3_stmt* pVM, bool bEof, bool bOwnVM/*=true*/) { mpDB = pDB; mpVM = pVM; mbEof = bEof; mnCols = _sqlite3_column_count(mpVM); mbOwnVM = bOwnVM; } CppSQLite3Query::~CppSQLite3Query() { try { finalize(); } catch (...) {} } CppSQLite3Query& CppSQLite3Query::operator=(const CppSQLite3Query& rQuery) { try { finalize(); } catch (...) {} mpVM = rQuery.mpVM; // Only one object can own the VM const_cast<CppSQLite3Query&>(rQuery).mpVM = 0; mbEof = rQuery.mbEof; mnCols = rQuery.mnCols; mbOwnVM = rQuery.mbOwnVM; return *this; } int CppSQLite3Query::numFields() { checkVM(); return mnCols; } LPCTSTR CppSQLite3Query::fieldValue(int nField) { checkVM(); if (nField < 0 || nField > mnCols - 1) throw CppSQLite3Exception(CPPSQLITE_ERROR,_T("Invalid field index requested"), DONT_DELETE_MSG); return (LPCTSTR)_sqlite3_column_text(mpVM, nField); } LPCTSTR CppSQLite3Query::fieldValue(LPCTSTR szField) { int nField = fieldIndex(szField); return (LPCTSTR)_sqlite3_column_text(mpVM, nField); } int CppSQLite3Query::getIntField(int nField, int nNullValue/*=0*/) { if (fieldDataType(nField) == SQLITE_NULL) { return nNullValue; } else { return _sqlite3_column_int(mpVM, nField); } } int CppSQLite3Query::getIntField(LPCTSTR szField, int nNullValue/*=0*/) { int nField = fieldIndex(szField); return getIntField(nField, nNullValue); } double CppSQLite3Query::getFloatField(int nField, double fNullValue/*=0.0*/) { if (fieldDataType(nField) == SQLITE_NULL) { return fNullValue; } else { return _sqlite3_column_double(mpVM, nField); } } double CppSQLite3Query::getFloatField(LPCTSTR szField, double fNullValue/*=0.0*/) { int nField = fieldIndex(szField); return getFloatField(nField, fNullValue); } LPCTSTR CppSQLite3Query::getStringField(int nField, LPCTSTR szNullValue/*=""*/) { if (fieldDataType(nField) == SQLITE_NULL) { return szNullValue; } else { return (LPCTSTR)_sqlite3_column_text(mpVM, nField); } } LPCTSTR CppSQLite3Query::getStringField(LPCTSTR szField, LPCTSTR szNullValue/*=""*/) { int nField = fieldIndex(szField); return getStringField(nField, szNullValue); } const unsigned char* CppSQLite3Query::getBlobField(int nField, int& nLen) { checkVM(); if (nField < 0 || nField > mnCols - 1) throw CppSQLite3Exception(CPPSQLITE_ERROR,_T("Invalid field index requested"), DONT_DELETE_MSG); nLen = _sqlite3_column_bytes(mpVM, nField); return (const unsigned char*)sqlite3_column_blob(mpVM, nField); } const unsigned char* CppSQLite3Query::getBlobField(LPCTSTR szField, int& nLen) { int nField = fieldIndex(szField); return getBlobField(nField, nLen); } bool CppSQLite3Query::fieldIsNull(int nField) { return (fieldDataType(nField) == SQLITE_NULL); } bool CppSQLite3Query::fieldIsNull(LPCTSTR szField) { int nField = fieldIndex(szField); return (fieldDataType(nField) == SQLITE_NULL); } int CppSQLite3Query::fieldIndex(LPCTSTR szField) { checkVM(); if (szField) { for (int nField = 0; nField < mnCols; nField++) { LPCTSTR szTemp = (LPCTSTR)_sqlite3_column_name(mpVM, nField); if (_tcscmp(szField, szTemp) == 0) { return nField; } } } throw CppSQLite3Exception(CPPSQLITE_ERROR,_T("Invalid field name requested"), DONT_DELETE_MSG); } LPCTSTR CppSQLite3Query::fieldName(int nCol) { checkVM(); if (nCol < 0 || nCol > mnCols - 1) { throw CppSQLite3Exception(CPPSQLITE_ERROR,_T("Invalid field index requested"), DONT_DELETE_MSG); } return (LPCTSTR)_sqlite3_column_name(mpVM, nCol); } LPCTSTR CppSQLite3Query::fieldDeclType(int nCol) { checkVM(); if (nCol < 0 || nCol > mnCols - 1) { throw CppSQLite3Exception(CPPSQLITE_ERROR,_T("Invalid field index requested"), DONT_DELETE_MSG); } return (LPCTSTR)_sqlite3_column_decltype(mpVM, nCol); } int CppSQLite3Query::fieldDataType(int nCol) { checkVM(); if (nCol < 0 || nCol > mnCols - 1) { throw CppSQLite3Exception(CPPSQLITE_ERROR,_T("Invalid field index requested"), DONT_DELETE_MSG); } return _sqlite3_column_type(mpVM, nCol); } bool CppSQLite3Query::eof() { checkVM(); return mbEof; } void CppSQLite3Query::nextRow() { checkVM(); int nRet = _sqlite3_step(mpVM); if (nRet == SQLITE_DONE) { // no rows mbEof = true; } else if (nRet == SQLITE_ROW) { // more rows, nothing to do } else { nRet = _sqlite3_finalize(mpVM); mpVM = 0; LPCTSTR szError = (LPCTSTR)_sqlite3_errmsg(mpDB); throw CppSQLite3Exception(nRet, (LPTSTR)szError, DONT_DELETE_MSG); } } void CppSQLite3Query::finalize() { if (mpVM && mbOwnVM) { int nRet = _sqlite3_finalize(mpVM); mpVM = 0; if (nRet != SQLITE_OK) { LPCTSTR szError = (LPCTSTR)_sqlite3_errmsg(mpDB); throw CppSQLite3Exception(nRet, (LPTSTR)szError, DONT_DELETE_MSG); } } } void CppSQLite3Query::checkVM() { if (mpVM == 0) { throw CppSQLite3Exception(CPPSQLITE_ERROR,_T("Null Virtual Machine pointer"), DONT_DELETE_MSG); } } //////////////////////////////////////////////////////////////////////////////// //************************** //*************- Added By Begemot - 28/02/06 20:25 - **** CString DoubleQuotes(CString in) { in.Replace(_T("\'"),_T("\'\'")); return in; }
cedcab71b8ce5c3d55aab4d52b2669074d5a8760
f92f86ae5595fa82f46eddaf005fd4e12150237a
/TICPP-2nd-ed-Vol-two/code/C05/ToLower2.cpp
73b7c81d13df1ea716ae5dba57572228c32cfada
[]
no_license
charles-pku-2013/CodeRes_Cpp
0b3d84412303c42a64fd943e8d0259dacd17954f
a2486495062743c1ec752b26989391f7e580d724
refs/heads/master
2023-08-31T19:44:34.784744
2023-08-30T06:28:21
2023-08-30T06:28:21
44,118,898
3
6
null
null
null
null
UTF-8
C++
false
false
631
cpp
//: C05:ToLower2.cpp {-mwcc} // From "Thinking in C++, Volume 2", by Bruce Eckel & Chuck Allison. // (c) 1995-2004 MindView, Inc. All Rights Reserved. // See source code use permissions stated in the file 'License.txt', // distributed with the code package available at www.MindView.net. #include <algorithm> #include <cctype> #include <iostream> #include <string> using namespace std; template<class charT> charT strTolower(charT c) { return tolower(c); // One-arg version called } int main() { string s("LOWER"); transform(s.begin(),s.end(),s.begin(),&strTolower<char>); cout << s << endl; } ///:~
1668062d6f35ef93535d12b81c7d09dce335a2ce
80bee850d1197772d61e05d8febc014e9980d7c0
/Addons/ExileReborn-Reborn_Zombies/@ExileServer/addons/Enigma_Exile_Custom/config.cpp
b599d7884fd7f9af5d528ef2cf49ffaf7d43298c
[ "MIT" ]
permissive
x-cessive/Exile
0443bb201bda31201fadc9c0ac80823fb2d7a25d
c5d1f679879a183549e1c87d078d462cbba32c25
refs/heads/master
2021-11-29T08:40:00.286597
2021-11-14T17:36:51
2021-11-14T17:36:51
82,304,207
10
8
null
2017-04-11T14:44:21
2017-02-17T14:20:22
SQF
UTF-8
C++
false
false
359
cpp
class CfgPatches { class Enigma_Exile_Custom { units[] = {}; weapons[] = {}; requiredVersion = 0.1; author[]= {"Happydayz_EngimaTeam"}; }; }; class CfgFunctions { class EnigmaTeam { class main { file = "\Enigma_Exile_Custom\init"; class init { preInit = 1; }; class postinit { postInit = 1; }; }; }; };
3d990c1341cce745c8cd816c66e6e52a1a6126af
e9ed8f198134984a9342e50d96a454a0ed1e094a
/AR-VR/tanya007_Tanya_2024ec1197_2/gettingStarted/primesinrange.cpp
5973ff067ac49bf3d32c2080e55fb573c937d87b
[]
no_license
divyaagarwal24/coderspree
20978b6dabefd84cac1343fffa79741bd6372046
7aafdab534bbab8dd1073007d83517470aae3492
refs/heads/main
2023-08-26T12:15:52.236087
2021-11-10T11:48:55
2021-11-10T11:48:55
412,049,822
0
1
null
2021-09-30T12:09:47
2021-09-30T12:09:47
null
UTF-8
C++
false
false
313
cpp
#include<iostream> using namespace std; int main(){ int a,b; cin>>a>>b; for(int num=a;num<=b;num++){ int i; for(i=2;i<num;i++){ if(num%i==0){ break; } } if(i==num){ cout<<num<<endl; } } return 0; }
b0efac308b2c16a35a0a38bab7c8398313f37cad
97195724f8a99189c9afbcb371eb0816da5f2ec7
/imu/Teensy/src/imu_device.cpp
9a8da954c4acfbaaf2f461e105f3079490da0b94
[ "MIT" ]
permissive
mylightyeah/Yukari
a8bc1e98156212df323dc53db2ec9ce16c6103aa
da3e599477302c241b438ca44d6711fdd68b6ef8
refs/heads/master
2021-05-22T16:11:23.320608
2017-06-16T13:43:00
2017-06-16T13:43:00
null
0
0
null
null
null
null
UTF-8
C++
false
false
13,437
cpp
#include "imu_device.h" #include <I2Cdev.h> #include <BMP085.h> #include <MPU9150_9Axis_MotionApps41.h> #include <TinyGPS++.h> #include <helper_3dmath.h> #include <MSP.h> #include <Scheduler.h> Scheduler g_scheduler; MSP g_msp(MSP_SERIAL); TinyGPSPlus g_gps; BMP085 g_barometer; float g_temperature; float g_pressure; float g_altitude; int32_t g_baroLastMicros = 0; MPU9150 g_imu; uint16_t g_dmpFIFOPacketSize; uint16_t g_dmpFIFOBufferSize; uint8_t g_dmpFIFOBuffer[64]; volatile bool g_mpuInterrupt = false; // DMP packets use 1g = 4096 (AFS_SEL=2) const float ACCEL_COEFF = 9.81f / 4096.0f; Quaternion g_quat; VectorFloat g_gravity; VectorInt16 g_accelCalib; VectorInt16 g_accel; VectorInt16 g_realAccel; VectorInt16 g_worldAccel; VectorFloat g_worldAccelMS2; uint8_t g_worldAccelMS2Zero[3]; uint8_t g_accelSamples = 0; VectorFloat g_worldAccelMS2LPFAccum; VectorFloat g_worldAccelMS2LPF; uint32_t g_lastIntegrationTimestep = 0; VectorFloat g_velocity; VectorFloat g_displacement; void dmpDataReady() { g_mpuInterrupt = true; } void taskBlink() { static bool blinkState = false; blinkState = !blinkState; digitalWrite(LED_PIN, blinkState); } #ifdef SERIALPLOT /* * Prints debug data as CSV for serialplot. * * 1) Acceleration - x * 2) Acceleration - y * 3) Acceleration - z * 4) Linear acceleration - x * 5) Linear acceleration - y * 6) Linear acceleration - z * 7) World acceleration - x * 8) World acceleration - y * 9) World acceleration - z * 10) Velocity - x * 11) Velocity - y * 12) Velocity - z * 13) Displacement - x * 14) Displacement - y * 15) Displacement - z */ void taskDebugPrintCSV() { DEBUG_SERIAL.printf("%d,%d,%d,%d,%d,%d,", g_accel.x, g_accel.y, g_accel.z, g_realAccel.x, g_realAccel.y, g_realAccel.z); DEBUG_SERIAL.print(g_worldAccelMS2.x); DEBUG_SERIAL.print(","); DEBUG_SERIAL.print(g_worldAccelMS2.y); DEBUG_SERIAL.print(","); DEBUG_SERIAL.print(g_worldAccelMS2.z); DEBUG_SERIAL.print(","); DEBUG_SERIAL.print(g_velocity.x); DEBUG_SERIAL.print(","); DEBUG_SERIAL.print(g_velocity.y); DEBUG_SERIAL.print(","); DEBUG_SERIAL.print(g_velocity.z); DEBUG_SERIAL.print(","); DEBUG_SERIAL.print(g_displacement.x); DEBUG_SERIAL.print(","); DEBUG_SERIAL.print(g_displacement.y); DEBUG_SERIAL.print(","); DEBUG_SERIAL.print(g_displacement.z); DEBUG_SERIAL.println(); } #endif /* SERIALPLOT */ void taskDMP() { if (!g_mpuInterrupt && g_dmpFIFOBufferSize < g_dmpFIFOPacketSize) return; // reset interrupt flag and get INT_STATUS byte g_mpuInterrupt = false; uint8_t mpuIntStatus = g_imu.getIntStatus(); // get current FIFO count g_dmpFIFOBufferSize = g_imu.getFIFOCount(); // check for overflow (this should never happen unless our code is too inefficient) if ((mpuIntStatus & 0x10) || g_dmpFIFOBufferSize == 1024) { // reset so we can continue cleanly g_imu.resetFIFO(); #ifdef DEBUG DEBUG_SERIAL.printf("FIFO overflow!\n"); #endif } // otherwise, check for DMP data ready interrupt (this should happen frequently) else if (mpuIntStatus & 0x02) { // wait for correct available data length, should be a VERY short wait while (g_dmpFIFOBufferSize < g_dmpFIFOPacketSize) g_dmpFIFOBufferSize = g_imu.getFIFOCount(); // read a packet from FIFO g_imu.getFIFOBytes(g_dmpFIFOBuffer, g_dmpFIFOPacketSize); // track FIFO count here in case there is > 1 packet available // (this lets us immediately read more without waiting for an interrupt) g_dmpFIFOBufferSize -= g_dmpFIFOPacketSize; g_imu.dmpGetQuaternion(&g_quat, g_dmpFIFOBuffer); g_imu.dmpGetAccel(&g_accel, g_dmpFIFOBuffer); g_accel.x -= g_accelCalib.x; g_accel.y -= g_accelCalib.y; g_accel.z -= g_accelCalib.z; g_imu.dmpGetGravity(&g_gravity, &g_quat); g_imu.dmpGetLinearAccel(&g_realAccel, &g_accel, &g_gravity); g_imu.dmpGetLinearAccelInWorld(&g_worldAccel, &g_realAccel, &g_quat); g_worldAccelMS2 = VectorFloat(g_worldAccel.x, g_worldAccel.y, g_worldAccel.z - 5150) * ACCEL_COEFF; for (uint8_t i = 0; i < 3; i++) { if (abs(g_worldAccelMS2[i]) < 0.2f) g_worldAccelMS2Zero[i]++; else g_worldAccelMS2Zero[i] = 0; if (g_worldAccelMS2Zero[i] >= 10) g_worldAccelMS2[i] = 0.0f; } g_worldAccelMS2LPFAccum += g_worldAccelMS2 / 8.0f; g_accelSamples++; // Calculate velocity and displacement uint32_t now = micros(); if (g_lastIntegrationTimestep != 0 && g_accelSamples == 8) { g_worldAccelMS2LPF = g_worldAccelMS2LPFAccum; g_worldAccelMS2LPFAccum.toZero(); g_accelSamples = 0; float deltaTime = (float)(now - g_lastIntegrationTimestep) * 1e-6; g_velocity += g_worldAccelMS2LPF * deltaTime; g_displacement += g_velocity * deltaTime; } taskDebugPrintCSV(); g_lastIntegrationTimestep = now; } } void taskResetIMUIntegration() { if (digitalRead(10) == LOW) { g_velocity.toZero(); g_displacement.toZero(); #ifdef DEBUG DEBUG_SERIAL.printf("IMU integration reset\n"); #endif } } void taskBarometer() { g_baroLastMicros = micros(); g_barometer.setControl(BMP085_MODE_TEMPERATURE); while (micros() - g_baroLastMicros < g_barometer.getMeasureDelayMicroseconds()) ; g_temperature = g_barometer.getTemperatureC(); g_barometer.setControl(BMP085_MODE_PRESSURE_3); while (micros() - g_baroLastMicros < g_barometer.getMeasureDelayMicroseconds()) ; g_pressure = g_barometer.getPressure(); g_altitude = g_barometer.getAltitude(g_pressure); } #ifdef DEBUG void taskPrintData() { // Device orientation as quaternion DEBUG_SERIAL.printf("quat\t"); DEBUG_SERIAL.print(g_quat.w); DEBUG_SERIAL.print("\t"); DEBUG_SERIAL.print(g_quat.x); DEBUG_SERIAL.print("\t"); DEBUG_SERIAL.print(g_quat.y); DEBUG_SERIAL.print("\t"); DEBUG_SERIAL.println(g_quat.z); // Linear acceleration DEBUG_SERIAL.printf("a\t%d\t%d\t%d\n", g_accel.x, g_accel.y, g_accel.z); // Linear acceleration without gravity DEBUG_SERIAL.printf("aReal\t%d\t%d\t%d\n", g_realAccel.x, g_realAccel.y, g_realAccel.z); // Linear acceleration without gravity and corrected for orientation DEBUG_SERIAL.printf("aWorld\t%d\t%d\t%d\n", g_worldAccel.x, g_worldAccel.y, g_worldAccel.z); // Linear acceleration without gravity and corrected for orientation in ms-2 DEBUG_SERIAL.print("aWorld (ms-2)\t"); DEBUG_SERIAL.print(g_worldAccelMS2.x); DEBUG_SERIAL.print("\t"); DEBUG_SERIAL.print(g_worldAccelMS2.y); DEBUG_SERIAL.print("\t"); DEBUG_SERIAL.println(g_worldAccelMS2.z); // Linear acceleration without gravity and corrected for orientation in ms-2 with low pass filter DEBUG_SERIAL.print("aWorld LPF (ms-2)\t"); DEBUG_SERIAL.print(g_worldAccelMS2LPF.x); DEBUG_SERIAL.print("\t"); DEBUG_SERIAL.print(g_worldAccelMS2LPF.y); DEBUG_SERIAL.print("\t"); DEBUG_SERIAL.println(g_worldAccelMS2LPF.z); // Velocity DEBUG_SERIAL.printf("velocity (ms-1)\t"); DEBUG_SERIAL.print(g_velocity.x); DEBUG_SERIAL.print("\t"); DEBUG_SERIAL.print(g_velocity.y); DEBUG_SERIAL.print("\t"); DEBUG_SERIAL.println(g_velocity.z); // Displacement DEBUG_SERIAL.printf("displacement (m)\t"); DEBUG_SERIAL.print(g_displacement.x); DEBUG_SERIAL.print("\t"); DEBUG_SERIAL.print(g_displacement.y); DEBUG_SERIAL.print("\t"); DEBUG_SERIAL.println(g_displacement.z); // BMP180 data DEBUG_SERIAL.printf("T/P/Alt\t"); DEBUG_SERIAL.print(g_temperature); DEBUG_SERIAL.print("\t"); DEBUG_SERIAL.print(g_pressure); DEBUG_SERIAL.print("\t"); DEBUG_SERIAL.println(g_altitude); } #endif /* DEBUG */ void taskFeedGPS() { if (GPS_SERIAL.available()) g_gps.encode(GPS_SERIAL.read()); } #if defined(DEBUG) void taskDebugPrintGPS() { DEBUG_SERIAL.printf("GPS stats\n"); if (g_gps.satellites.isUpdated()) DEBUG_SERIAL.printf("Sats: %ld\n", g_gps.satellites.value()); if (g_gps.location.isUpdated()) { DEBUG_SERIAL.printf("Lat: %c%d.%ld\n", g_gps.location.rawLat().negative ? '-' : '+', g_gps.location.rawLat().deg, g_gps.location.rawLat().billionths); DEBUG_SERIAL.printf("Lng: %c%d.%ld\n", g_gps.location.rawLng().negative ? '-' : '+', g_gps.location.rawLng().deg, g_gps.location.rawLng().billionths); DEBUG_SERIAL.printf("Age: %ld\n", g_gps.location.age()); } if (g_gps.altitude.isUpdated()) DEBUG_SERIAL.printf("Alt: %ldcm\n", g_gps.altitude.value()); if (g_gps.course.isUpdated()) DEBUG_SERIAL.printf("Course: %ld(deg/100)\n", g_gps.course.value()); if (g_gps.speed.isUpdated()) DEBUG_SERIAL.printf("Speed: %ld(knot/100)\n", g_gps.speed.value()); } #endif /* DEBUG */ void taskMSP() { g_msp.loop(); } void imu_device_init() { pinMode(LED_PIN, OUTPUT); digitalWrite(LED_PIN, HIGH); #if defined(DEBUG) || defined(SERIALPLOT) /* Init debug serial */ DEBUG_SERIAL.begin(DEBUG_BAUD); while (!DEBUG_SERIAL) delay(5); DEBUG_SERIAL.printf("Serial up\n"); #endif /* DEBUG || SERIALPLOT */ /* Init MSP */ MSP_SERIAL.begin(MSP_BAUD); g_msp.setOnMessage([](MSP::Direction dir, MSP::Command cmd, uint8_t *buff, uint8_t len) { #ifdef DEBUG DEBUG_SERIAL.printf("dir="); DEBUG_SERIAL.println((uint8_t)dir, HEX); DEBUG_SERIAL.printf("cmd="); DEBUG_SERIAL.println((uint8_t)cmd, HEX); DEBUG_SERIAL.printf("len=%d\n", len); for (uint8_t i = 0; i < len; i++) { DEBUG_SERIAL.print(buff[i], HEX); DEBUG_SERIAL.print(' '); } DEBUG_SERIAL.printf("\n"); #endif switch (cmd) { case MSP::Command::Y_ORIENTATION: { uint8_t pkt[8]; pkt[0] = g_dmpFIFOBuffer[0]; pkt[1] = g_dmpFIFOBuffer[1]; pkt[2] = g_dmpFIFOBuffer[4]; pkt[3] = g_dmpFIFOBuffer[5]; pkt[4] = g_dmpFIFOBuffer[8]; pkt[5] = g_dmpFIFOBuffer[9]; pkt[6] = g_dmpFIFOBuffer[12]; pkt[7] = g_dmpFIFOBuffer[13]; g_msp.sendPacket(MSP::Command::Y_RAW_IMU, pkt, 8); break; } case MSP::Command::Y_DISPLACEMENT: { /* TODO */ break; } case MSP::Command::Y_RESET_DISPLACEMENT: { /* TODO */ break; } default: break; } }); #ifdef DEBUG DEBUG_SERIAL.printf("MSP init\n"); #endif /* DEBUG */ #if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE /* Init i2c bus (Arduino) */ Wire.begin(); Wire.setClock(400000); // 400kHz I2C clock #elif I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_FASTWIRE /* Init i2c bus (Fast Wire) */ Fastwire::setup(400, true); #endif /* I2CDEV_IMPLEMENTATION */ #ifdef DEBUG DEBUG_SERIAL.printf("Wire init\n"); #endif /* DEBUG */ #ifndef DISABLE_GPS GPS_SERIAL.begin(GPS_BAUD); #endif /* GPS_SERIAL */ #ifdef DEBUG DEBUG_SERIAL.printf("GPS init\n"); DEBUG_SERIAL.printf("TinyGPS++ version: %s\n", TinyGPSPlus::libraryVersion()); #endif /* DEBUG */ #ifndef DISABLE_IMU /* Init IMU */ g_imu.initialize(); #ifdef DEBU2 DEBUG_SERIAL.printf("IMU init: %d\n", g_imu.testConnection()); #endif /* DEBUG */ for (uint8_t i = 0; i < 3; i++) g_worldAccelMS2Zero[i] = 0; pinMode(MPU_INTERRUPT_PIN, INPUT); /* Init DMP */ uint8_t dmpStatus = g_imu.dmpInitialize(); if (dmpStatus == 0) { g_imu.setDMPEnabled(true); attachInterrupt(digitalPinToInterrupt(MPU_INTERRUPT_PIN), dmpDataReady, RISING); dmpStatus = g_imu.getIntStatus(); g_dmpFIFOPacketSize = g_imu.dmpGetFIFOPacketSize(); } /* Calibration sample */ int64_t axa = 0; int64_t aya = 0; int64_t aza = 0; const uint16_t numSamples = 5000; int16_t dummy, ax, ay, az; #ifdef DEBUG DEBUG_SERIAL.printf("Accel. calibration start\n"); #endif /* DEBUG */ for (uint16_t i = 0; i < numSamples; i++) { g_imu.getMotion6(&ax, &ay, &az, &dummy, &dummy, &dummy); axa += ax; aya += ay; aza += az; delay(1); } g_accelCalib.x = axa / numSamples; g_accelCalib.y = aya / numSamples; g_accelCalib.z = aza / numSamples; #ifdef DEBUG DEBUG_SERIAL.printf("Accel. calibration done: %d, %d, %d\n", g_accelCalib.x, g_accelCalib.y, g_accelCalib.z); #endif /* DEBUG */ #endif /* DISABLE_IMU */ #ifndef DISABLE_BARO /* Init barometer */ g_barometer.initialize(); #ifdef DEBUG DEBUG_SERIAL.printf("Barometer init: %d\n", g_barometer.testConnection()); #endif /* DEBUG */ #endif /* DISABLE_BARO */ /* Init scheduler */ g_scheduler.addTask(&taskBlink, Scheduler::HzToUsInterval(5.0f)); g_scheduler.addTask(&taskMSP, 0); g_scheduler.addTask(&taskResetIMUIntegration, Scheduler::HzToUsInterval(10.0f)); #ifdef SERIALPLOT /* g_scheduler.addTask(&taskDebugPrintCSV, Scheduler::HzToUsInterval(10.0f)); */ #endif /* SERIALPLOT */ #ifndef DISABLE_GPS g_scheduler.addTask(&taskFeedGPS, 0); #endif /* DISABLE_GPS */ #ifndef DISABLE_IMU if (dmpStatus == 0) g_scheduler.addTask(&taskDMP, 0); #endif /* DISABLE_IMU */ #ifndef DISABLE_BARO g_scheduler.addTask(&taskBarometer, Scheduler::HzToUsInterval(10.0f)); #endif /* DISABLE_BARO */ #ifdef DEBUG g_scheduler.addTask(&taskPrintData, Scheduler::HzToUsInterval(10.0f)); #ifndef DISABLE_GPS g_scheduler.addTask(&taskDebugPrintGPS, Scheduler::HzToUsInterval(1.0f)); #endif /* DISABLE_GPS */ g_scheduler.print(DEBUG_SERIAL); #endif /* DEBUG */ digitalWrite(LED_PIN, LOW); #ifdef DEBUG DEBUG_SERIAL.printf("Ready\n"); #endif /* DEBUG */ } void imu_device_loop() { g_scheduler.loop(); }
88a2761c16aa3a2578fe59343015078e6cb66dda
24169ed433d6fb46ee6c00d49a31ee834f517dce
/GFlowSim/src/dataobjects/graphobjects/kineticenergydata.cpp
ddd79fb3082496106556e8f29df5c5d8299fec32
[]
no_license
nrupprecht/GFlow
0ae566e33305c31c1fead7834a0b89f611abb715
445bf3cbdbcdc68aa51b5737f60d96634009a731
refs/heads/master
2021-11-22T22:07:31.721612
2020-04-22T18:51:21
2020-04-22T18:51:21
60,136,842
2
2
null
2020-02-10T23:10:33
2016-06-01T01:49:26
C++
UTF-8
C++
false
false
1,508
cpp
#include "kineticenergydata.hpp" namespace GFlowSimulation { // Constructor KineticEnergyData::KineticEnergyData(GFlow *gflow, bool ave) : GraphObject(gflow, "KE", "time", "kinetic energy"), useAve(ave) {}; void KineticEnergyData::post_step() { // Only record if enough time has gone by if (!DataObject::_check()) return; // Get data. RealType ke = calculate_kinetic(simData, false); // Store data. These functions work correctly with multiprocessor runs. if (useAve) gatherAverageData(gflow->getElapsedTime(), ke, simData->size_owned()); else gatherData(gflow->getElapsedTime(), ke); } RealType KineticEnergyData::calculate_kinetic(shared_ptr<SimData> simData, bool average) { RealType ke = 0; auto v = simData->V(); auto im = simData->Im(); int sim_dimensions = simData->getSimDimensions(); int count = 0; for (int n=0; n<simData->size_owned(); ++n) { RealType vsqr = sqr(v(n), sim_dimensions); if (im[n]>0 && !isnan(vsqr)) { RealType m = 1./im(n); ke += m*vsqr; ++count; } } ke *= 0.5; // Return the total kinetic energy return average ? ke/static_cast<RealType>(count) : ke; } RealType KineticEnergyData::calculate_temperature(shared_ptr<SimData> simData) { // Get the kinetic energy. RealType ke = KineticEnergyData::calculate_kinetic(simData, true); // Calculate temperature. return 2./simData->getSimDimensions() * ke / simData->getGFlow()->getKB(); } }
aa686bb8bc1b77a1d341f72ab1b544dd58b0547c
60798997f9ff3a60b8787386dbed1ad06c1c9ccc
/DesignPatterns/Structural/Composite/floppydisk.cpp
192d2092f00675c638331e84d52d77c7be50f25d
[]
no_license
e5MaxSpace/DesignPatterns
be7e478c0fca1626c764287af17fd4457c99a975
c44a2b6781a571937f85634b57f6feb60a744f89
refs/heads/master
2016-09-06T18:08:11.377009
2013-09-16T12:16:41
2013-09-16T12:16:41
null
0
0
null
null
null
null
UTF-8
C++
false
false
320
cpp
#include "floppydisk.h" FloppyDisk::FloppyDisk(const std::string &name) : Equipment(name) { } FloppyDisk::~FloppyDisk() { } int FloppyDisk::Power() const { return 180; } Currency FloppyDisk::NetPrice() const { return 500.0; } Currency FloppyDisk::DiscountPrice() const { return NetPrice() * 0.85; }
0d449d2d6cb108c915ae5de4f0411cf0a9e2d826
b22522fe8fc3777b51dba385f0cdb7a7d2911e96
/project/faceTrack/faceTrack/train_patch_model.cpp
a7ddb7679cd4e5ffdcf28fd1fa21664769387074
[]
no_license
txaxx/opencv
5320cbe28b04dc9b6b4b0ed17daf2464ae46816d
23e2394ab204f7439c62cffbae1f997cca50bf3e
refs/heads/master
2020-05-16T01:54:16.331452
2019-05-09T02:36:42
2019-05-09T02:36:42
182,612,736
0
0
null
null
null
null
UTF-8
C++
false
false
2,306
cpp
/***************************************************************************** * Non-Rigid Face Tracking ****************************************************************************** * by Jason Saragih, 5th Dec 2012 * http://jsaragih.org/ ****************************************************************************** * Ch6 of the book "Mastering OpenCV with Practical Computer Vision Projects" * Copyright Packt Publishing 2012. * http://www.packtpub.com/cool-projects-with-opencv/book *****************************************************************************/ /* train_patch_model: learn a patch_model object from training data Jason Saragih (2012) */ #include "ft.hpp" #include <opencv2/highgui/highgui.hpp> #include <iostream> #define fl at<float> //============================================================================== float //scaling factor calc_scale(const Mat &X, //scaling basis vector const float width) //width of desired shape { int n = X.rows/2; float xmin = X.at<float>(0),xmax = X.at<float>(0); for(int i = 0; i < n; i++){ xmin = min(xmin,X.at<float>(2*i)); xmax = max(xmax,X.at<float>(2*i)); }return width/(xmax-xmin); } //============================================================================== int main() { int width = 100; int psize = 11; int ssize = 11; bool mirror = false; Size wsize(psize+ssize,psize+ssize); //load data ft_data data = load_ft<ft_data>("E:\\C++\\opencv\\project\\muct-landmarks\\annotations.yaml"); data.rm_incomplete_samples(); if(data.imnames.size() == 0){ cerr << "Data file does not contain any annotations."<< endl; return 0; } //load shape model shape_model smodel = load_ft<shape_model>("E:\\C++\\opencv\\project\\muct-landmarks\\shape.yaml"); //generate reference shape smodel.p = Scalar::all(0.0); smodel.p.fl(0) = calc_scale(smodel.V.col(0),width); vector<Point2f> r = smodel.calc_shape(); //train patch models patch_models pmodel; pmodel.train(data,r,Size(psize,psize),Size(ssize,ssize),mirror); save_ft<patch_models>("E:\\C++\\opencv\\project\\muct-landmarks\\patch.yaml",pmodel); return 0; } //==============================================================================
6fe60d39bf4547f42863d16dfbf7ca7049749d7b
ea2ef79d13c8c8c70f96ba6683bf0f321e9942c1
/include/graphics/Scene.h
c81617ee928d3fac81fbae6a558df2d9eb7d98d1
[ "MIT" ]
permissive
stnma7e/scim
32145a3d51aadb2013f2ab452fb1c83af563ca13
a82f0e97018a4a2abf0a225f75ebc7e8ef6f1e0d
refs/heads/master
2021-01-10T20:17:34.222501
2014-02-01T19:08:54
2014-02-01T19:08:54
7,210,907
1
2
null
null
null
null
UTF-8
C++
false
false
954
h
#ifndef SCENE_H_ #define SCENE_H_ #include "IMesh.h" #include <glm/glm.hpp> #include <vector> #include <stdio.h> #include <iostream> namespace scim { struct SceneNode { U32 index; glm::mat4* wmat; glm::mat4* lmat; U32 parentNode; IMesh* mesh; }; class Scene { std::vector<glm::mat4> m_wmat; // world transform matrix list std::vector<glm::mat4> m_lmat; // local transform matrix list std::vector<const IMesh*> m_meshes; std::vector<U32> m_parents; public: enum SceneConstant { ROOT_NODE = 0 }; static void PrintMatrix(const glm::mat4& matToPrint) { for (int j = 0; j < 4; ++j) { printf("row %d: ", j); for (int k = 0; k < 4; ++k) { std::cout << matToPrint[k][j] << ", "; // row major order } printf("\n"); } printf("\n"); } Scene(); void UpdateNodes(); void RenderNodes(); SceneNode CreateNode(U32 parentNode, IMesh* mesh); const SceneNode GetNode(U32 nodeIndex); }; } #endif
ecedf5a152a68f5ec4f7cabfe1fa482708e8bcb4
60276f056f1fc509593d4e05c383ba59148ad5e3
/DemoProj/Huffman/stdafx.cpp
96e356bbac808cb9db13c6d419381e0de5d5b75e
[]
no_license
feiilin/DemoCodes
8b63b6afb3c0afe001be00848fd9409b3510aa51
d1b142da92318a66a7aab1f7cebdf54b1fe24b67
refs/heads/master
2022-11-30T17:08:40.234741
2020-08-18T07:05:22
2020-08-18T07:05:22
286,668,819
1
0
null
null
null
null
GB18030
C++
false
false
260
cpp
// stdafx.cpp : 只包括标准包含文件的源文件 // Huffman.pch 将作为预编译头 // stdafx.obj 将包含预编译类型信息 #include "stdafx.h" // TODO: 在 STDAFX.H 中 // 引用任何所需的附加头文件,而不是在此文件中引用
ab6cf205c80f1278abb9878f5413de2cb172a5a2
a35b30a7c345a988e15d376a4ff5c389a6e8b23a
/boost/mpl/transform.hpp
d1f94e6638ff71a7c071a7fdff5b74d040c2cd41
[]
no_license
huahang/thirdparty
55d4cc1c8a34eff1805ba90fcbe6b99eb59a7f0b
07a5d64111a55dda631b7e8d34878ca5e5de05ab
refs/heads/master
2021-01-15T14:29:26.968553
2014-02-06T07:35:22
2014-02-06T07:35:22
null
0
0
null
null
null
null
UTF-8
C++
false
false
59
hpp
#include "thirdparty/boost_1_55_0/boost/mpl/transform.hpp"
95d8241b798c687382be3f0c81556fcd4f16eb99
cb6a6b91b6f260e233663985a6e24bdd21559c91
/chapter16/c16e5.cc
7b20dea79c6a70359d25577c3e689641f8b536f2
[]
no_license
drcxd/CppPrimerExercise
bf2ef28cfe9b1f5722116d550e7456fb395369c0
1b5b85d573144fc1019632c1e95cdcac01979d77
refs/heads/master
2021-01-23T09:10:06.782754
2018-02-09T02:01:19
2018-02-09T02:01:19
102,560,940
0
0
null
null
null
null
UTF-8
C++
false
false
590
cc
#include <iostream> #include <array> // built-in array version // template <unsigned N, typename T> // void print(const T (&arr)[N]) { // for (auto &it : arr) { // std::cout << it << std::endl; // } // } // stl array version template <unsigned long N, typename T> void print(const std::array<T, N> &arr) { for (auto &it : arr) { std::cout << it << std::endl; } } int main() { // std::string arr[5] = {"one", "two", "three", "four", "five"}; std::array<std::string, 5> arr = {"one", "two", "three", "four", "five"}; print(arr); return 0; }
756dfeb3fab0239288a99914424c3d4bbe3ffa62
cd484c21d9d412d81ee3039072365fbb32947fce
/WBoard/Source/tools/WBGraphicsCache.h
c267da4ccda46f5f770a130514051547cb0f5d34
[]
no_license
drivestudy/WBoard
8c97fc4f01f58540718cd2c082562f9eab5761de
18959203a234944fb402b444462db76c6dd5b3c6
refs/heads/main
2023-08-01T01:41:04.303780
2021-09-09T04:56:46
2021-09-09T04:56:46
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,474
h
#ifndef WBGRAPHICSCACHE_H #define WBGRAPHICSCACHE_H #include <QColor> #include <QGraphicsSceneMouseEvent> #include "domain/WBItem.h" #include "core/WB.h" typedef enum { eMaskShape_Circle, eMaskShap_Rectangle }eMaskShape; class WBGraphicsCache : public QGraphicsRectItem, public WBItem { public: static WBGraphicsCache* instance(WBGraphicsScene *scene); ~WBGraphicsCache(); enum { Type = WBGraphicsItemType::cacheItemType }; virtual int type() const{ return Type;} virtual WBItem* deepCopy() const; virtual void copyItemParameters(WBItem *copy) const; QColor maskColor(); void setMaskColor(QColor color); eMaskShape maskshape(); void setMaskShape(eMaskShape shape); int shapeWidth(); void setShapeWidth(int width); protected: void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget); void mouseMoveEvent(QGraphicsSceneMouseEvent *event); void mousePressEvent(QGraphicsSceneMouseEvent *event); void mouseReleaseEvent(QGraphicsSceneMouseEvent *event); private: static QMap<WBGraphicsScene*, WBGraphicsCache*> sInstances; QColor mMaskColor; eMaskShape mMaskShape; int mShapeWidth; bool mDrawMask; QPointF mShapePos; int mOldShapeWidth; QPointF mOldShapePos; WBGraphicsScene* mScene; WBGraphicsCache(WBGraphicsScene *scene); void init(); QRectF updateRect(QPointF currentPoint); }; #endif // WBGRAPHICSCACHE_H
d9383c6124ba75f5460fb2432f541924204971c7
8774e1860d88aeadcd1709e543f262b9f7983f31
/src/qt/test/uritests.h
6943eeb2c400be9216b1820af02d060a08439468
[ "MIT" ]
permissive
npq7721/raven-dark
cb1d0f5da007ff5a46f6b1d8410101ce827a7f5f
abc2c956f5eb5b01eb4703918f50ba325b676661
refs/heads/master
2020-08-04T17:04:11.847541
2019-07-19T19:32:55
2019-07-19T19:32:55
212,213,490
0
0
MIT
2019-10-01T22:47:40
2019-10-01T22:47:40
null
UTF-8
C++
false
false
436
h
// Copyright (c) 2009-2015 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef RAVENDARK_QT_TEST_URITESTS_H #define RAVENDARK_QT_TEST_URITESTS_H #include <QObject> #include <QTest> class URITests : public QObject { Q_OBJECT private Q_SLOTS: void uriTests(); }; #endif // RAVENDARK_QT_TEST_URITESTS_H
cf2a06f81eb7045b31dd1a84c6a824280a9ec8aa
ea72aac3344f9474a0ba52c90ed35e24321b025d
/PathFinding/PathFinding/PathFinding.cpp
ee86e175b6437840cdb4904cdd62c789f72b837e
[]
no_license
nlelouche/ia-2009
3bd7f1e42280001024eaf7433462b2949858b1c2
44c07567c3b74044e59313532b5829f3a3466a32
refs/heads/master
2020-05-17T02:21:02.137224
2009-03-31T01:12:44
2009-03-31T01:12:44
32,657,337
0
0
null
null
null
null
UTF-8
C++
false
false
2,208
cpp
#include "PathFinding.h" //-------------------------------------------------------------- PathFind::PathFind(int * _map[],int _rows,int _cols) : m_pkPath(NULL), m_pkClosedNodes(NULL), m_pkOpenNodes(NULL), m_CurrentNode(NULL), m_pkiPathIT(0), m_pkOpenNodesIT(0), m_pkClosedNodesIT(0) { // Copiamos el mapa pasado a un mapa fijo. for (int i = 0; i > LARGO_MAPA; i++){ m_Map[i] = (int)_map[i]; } /***/ } //-------------------------------------------------------------- PathFind::~PathFind(){ /***/ } //-------------------------------------------------------------- void PathFind::OpenNodes(Node * _node){ // m_pkOpenNodes.insert(_node); // Insertar nodo en la lista /***/ } //-------------------------------------------------------------- void PathFind::CloseNode(Node * _node){ /***/ } //-------------------------------------------------------------- bool PathFind::ExistOpenNodes(){ /***/ return false; } //-------------------------------------------------------------- bool PathFind::IsExitNode(Node *_node){ /***/ return false; } //-------------------------------------------------------------- Node * PathFind::LessValueNode(){ /***/ return m_CurrentNode; } //-------------------------------------------------------------- list<Node*> PathFind::GenerarCamino(){ /***/ return m_pkPath; } //-------------------------------------------------------------- bool PathFind::IsEndingNode(Node * _node){ return false; } //-------------------------------------------------------------- void PathFind::CalculateMap(Node * _initialNode, Node * _endingNode){ // Copiamos Posicion X,Y de nodos inicial y destino. //m_InitialPosition.Initial_X = _initial.Initial_X; //m_InitialPosition.Initial_Y = _initial.Initial_Y; //m_EndingPosition.Ending_X = _ending.Ending_X; //m_EndingPosition.Ending_Y = _ending.Ending_Y; OpenNodes(_initialNode); while (ExistOpenNodes()){ m_CurrentNode = LessValueNode(); if (IsEndingNode(m_CurrentNode)){ //GenerarCamino(); } else { CloseNode(m_CurrentNode); OpenNodes(m_CurrentNode); } } } //--------------------------------------------------------------
[ "calaverax@bb2752b8-1d7e-11de-9d52-39b120432c5d" ]
calaverax@bb2752b8-1d7e-11de-9d52-39b120432c5d
2182894dc402d1ceaeb4508f476495cd88830f87
d4c720f93631097ee048940d669e0859e85eabcf
/third_party/webrtc_overrides/p2p/base/ice_connection.h
9082894cdcb42672cdeb2877b36f56a634df64bb
[ "Apache-2.0", "LGPL-2.0-or-later", "MIT", "GPL-1.0-or-later", "BSD-3-Clause" ]
permissive
otcshare/chromium-src
26a7372773b53b236784c51677c566dc0ad839e4
3b920d87437d9293f654de1f22d3ea341e7a8b55
refs/heads/webnn
2023-03-21T03:20:15.377034
2023-01-25T21:19:44
2023-01-25T21:19:44
209,262,645
18
21
BSD-3-Clause
2023-03-23T06:20:07
2019-09-18T08:52:07
null
UTF-8
C++
false
false
3,138
h
// Copyright 2022 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef THIRD_PARTY_WEBRTC_OVERRIDES_P2P_BASE_ICE_CONNECTION_H_ #define THIRD_PARTY_WEBRTC_OVERRIDES_P2P_BASE_ICE_CONNECTION_H_ #include <string> #include <vector> #include "third_party/webrtc/api/array_view.h" #include "third_party/webrtc/api/candidate.h" #include "third_party/webrtc/p2p/base/connection.h" #include "third_party/webrtc/rtc_base/system/rtc_export.h" namespace blink { // Represents an ICE connection comprising of a local candidate, a remote // candidate, and some state information about the connection. class RTC_EXPORT IceConnection { public: struct RttSample { int64_t timestamp; int value; }; enum class WriteState { STATE_WRITABLE = 0, // we have received ping responses recently STATE_WRITE_UNRELIABLE = 1, // we have had a few ping failures STATE_WRITE_INIT = 2, // we have yet to receive a ping response STATE_WRITE_TIMEOUT = 3, // we have had a large number of ping failures }; explicit IceConnection(const cricket::Connection* connection); IceConnection(const IceConnection&) = default; ~IceConnection() = default; // The connection ID. uint32_t id() const { return id_; } // The local candidate for this connection. const cricket::Candidate& local_candidate() const { return local_candidate_; } // The remote candidate for this connection. const cricket::Candidate& remote_candidate() const { return remote_candidate_; } // Whether the connection is in a connected state. bool connected() const { return connected_; } // Whether the connection is currently active for the transport. bool selected() const { return selected_; } // Write state of the connection. WriteState write_state() const { return write_state_; } // Last time we sent a ping to the other side. int64_t last_ping_sent() const { return last_ping_sent_; } // Last time we received a ping from the other side. int64_t last_ping_received() const { return last_ping_received_; } // Last time we received date from the other side. int64_t last_data_received() const { return last_data_received_; } // Last time we received a response to a ping from the other side. int64_t last_ping_response_received() const { return last_ping_response_received_; } // The number of pings sent. int num_pings_sent() const { return num_pings_sent_; } // Samples of round trip times. const rtc::ArrayView<const RttSample> rtt_samples() const { return rtt_samples_; } private: uint32_t id_; cricket::Candidate local_candidate_; cricket::Candidate remote_candidate_; // Connection state information. bool connected_; bool selected_; WriteState write_state_; int64_t last_ping_sent_; int64_t last_ping_received_; int64_t last_data_received_; int64_t last_ping_response_received_; int num_pings_sent_; std::vector<RttSample> rtt_samples_; }; } // namespace blink #endif // THIRD_PARTY_WEBRTC_OVERRIDES_P2P_BASE_ICE_CONNECTION_H_
4da7e1f0758c1104525dc6ac848d7aa50586f3df
bfc0a74a378d3692d5b033c21c29cf223d2668da
/unittests/libtests/faults/TestFaultCohesiveKinSrcsCases.hh
2d50d2c0cf9ca9b8b598e087bf3d83de1c9de730
[ "MIT" ]
permissive
rishabhdutta/pylith
b2ed9cd8039de33e337c5bc989e6d76d85fd4df1
cb07c51b1942f7c6d60ceca595193c59a0faf3a5
refs/heads/master
2020-12-29T01:53:49.828328
2016-07-15T20:34:58
2016-07-15T20:34:58
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,478
hh
// -*- C++ -*- // // ---------------------------------------------------------------------- // // Brad T. Aagaard, U.S. Geological Survey // Charles A. Williams, GNS Science // Matthew G. Knepley, University of Chicago // // This code was developed as part of the Computational Infrastructure // for Geodynamics (http://geodynamics.org). // // Copyright (c) 2010-2016 University of California, Davis // // See COPYING for license information. // // ---------------------------------------------------------------------- // /** * @file unittests/libtests/faults/TestFaultCohesiveKinSrcsCases.hh * * @brief C++ unit testing for FaultCohesiveKin with multiple earthquake ruptures. */ #if !defined(pylith_faults_testfaultcohesivekinsrcscases_hh) #define pylith_faults_testfaultcohesivekinsrcscases_hh #include "TestFaultCohesiveKinSrcs.hh" // ISA TestFaultCohesiveKinSrcs /// Namespace for pylith package namespace pylith { namespace faults { class TestFaultCohesiveKinSrcsTri3; class TestFaultCohesiveKinSrcsQuad4; class TestFaultCohesiveKinSrcsTet4; class TestFaultCohesiveKinSrcsHex8; } // bc } // pylith // ---------------------------------------------------------------------- /// C++ unit testing for FaultCohesiveKinSrcs for mesh with 2-D triangular cells. class pylith::faults::TestFaultCohesiveKinSrcsTri3 : public TestFaultCohesiveKinSrcs { // class TestFaultCohesiveKinSrcsTri3 // CPPUNIT TEST SUITE ///////////////////////////////////////////////// CPPUNIT_TEST_SUITE( TestFaultCohesiveKinSrcsTri3 ); CPPUNIT_TEST( testInitialize ); CPPUNIT_TEST( testIntegrateResidual ); CPPUNIT_TEST( testIntegrateJacobian ); CPPUNIT_TEST( testIntegrateJacobianLumped ); CPPUNIT_TEST( testCalcTractionsChange ); CPPUNIT_TEST_SUITE_END(); // PUBLIC METHODS ///////////////////////////////////////////////////// public : /// Setup testing data. void setUp(void); }; // class TestFaultCohesiveKinSrcsTri3 // ---------------------------------------------------------------------- /// C++ unit testing for FaultCohesiveKin for mesh with 2-D quadrilateral cells. class pylith::faults::TestFaultCohesiveKinSrcsQuad4 : public TestFaultCohesiveKinSrcs { // class TestFaultCohesiveKinSrcsQuad4 // CPPUNIT TEST SUITE ///////////////////////////////////////////////// CPPUNIT_TEST_SUITE( TestFaultCohesiveKinSrcsQuad4 ); CPPUNIT_TEST( testInitialize ); CPPUNIT_TEST( testIntegrateResidual ); CPPUNIT_TEST( testIntegrateJacobian ); CPPUNIT_TEST( testIntegrateJacobianLumped ); CPPUNIT_TEST( testCalcTractionsChange ); CPPUNIT_TEST_SUITE_END(); // PUBLIC METHODS ///////////////////////////////////////////////////// public : /// Setup testing data. void setUp(void); }; // class TestFaultCohesiveKinSrcsQuad4 // ---------------------------------------------------------------------- /// C++ unit testing for FaultCohesiveKin for mesh with 3-D tetrahedral cells. class pylith::faults::TestFaultCohesiveKinSrcsTet4 : public TestFaultCohesiveKinSrcs { // class TestFaultCohesiveKinSrcsTet4 // CPPUNIT TEST SUITE ///////////////////////////////////////////////// CPPUNIT_TEST_SUITE( TestFaultCohesiveKinSrcsTet4 ); CPPUNIT_TEST( testInitialize ); CPPUNIT_TEST( testIntegrateResidual ); CPPUNIT_TEST( testIntegrateJacobian ); CPPUNIT_TEST( testIntegrateJacobianLumped ); CPPUNIT_TEST( testCalcTractionsChange ); CPPUNIT_TEST_SUITE_END(); // PUBLIC METHODS ///////////////////////////////////////////////////// public : /// Setup testing data. void setUp(void); }; // class TestFaultCohesiveKinSrcsTet4 // ---------------------------------------------------------------------- /// C++ unit testing for FaultCohesiveKin for mesh with 3-D hex cells. class pylith::faults::TestFaultCohesiveKinSrcsHex8 : public TestFaultCohesiveKinSrcs { // class TestFaultCohesiveKinSrcsHex8 // CPPUNIT TEST SUITE ///////////////////////////////////////////////// CPPUNIT_TEST_SUITE( TestFaultCohesiveKinSrcsHex8 ); CPPUNIT_TEST( testInitialize ); CPPUNIT_TEST( testIntegrateResidual ); CPPUNIT_TEST( testIntegrateJacobian ); CPPUNIT_TEST( testIntegrateJacobianLumped ); CPPUNIT_TEST( testCalcTractionsChange ); CPPUNIT_TEST_SUITE_END(); // PUBLIC METHODS ///////////////////////////////////////////////////// public : /// Setup testing data. void setUp(void); }; // class TestFaultCohesiveKinSrcsHex8 #endif // pylith_faults_testfaultcohesivesrcscases_hh // End of file
defe98cf16efd53719fd8430f90528824ef85856
fafce52a38479e8391173f58d76896afcba07847
/uppdev/YPuzzle/TinyXML/tinyxml.h
0024ae903bccd754478dc1cd8ced715361f6f7ed
[]
no_license
Sly14/upp-mirror
253acac2ec86ad3a3f825679a871391810631e61
ed9bc6028a6eed422b7daa21139a5e7cbb5f1fb7
refs/heads/master
2020-05-17T08:25:56.142366
2015-08-24T18:08:09
2015-08-24T18:08:09
41,750,819
2
1
null
null
null
null
UTF-8
C++
false
false
51,669
h
/* www.sourceforge.net/projects/tinyxml Original code (2.0 and earlier )copyright (c) 2000-2002 Lee Thomason (www.grinninglizard.com) This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #ifndef TINYXML_INCLUDED #define TINYXML_INCLUDED #ifdef _MSC_VER #pragma warning( disable : 4530 ) #pragma warning( disable : 4786 ) #endif #include <ctype.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <assert.h> // Help out windows: #if defined( _DEBUG ) && !defined( DEBUG ) #define DEBUG #endif #if defined( DEBUG ) && defined( _MSC_VER ) #include <windows.h> #define TIXML_LOG OutputDebugString #else #define TIXML_LOG printf #endif #ifdef TIXML_USE_STL #include <string> #include <iostream> #define TIXML_STRING std::string #define TIXML_ISTREAM std::istream #define TIXML_OSTREAM std::ostream #else #include "tinystr.h" #define TIXML_STRING TiXmlString #define TIXML_OSTREAM TiXmlOutStream #endif class TiXmlDocument; class TiXmlElement; class TiXmlComment; class TiXmlUnknown; class TiXmlAttribute; class TiXmlText; class TiXmlDeclaration; class TiXmlParsingData; const int TIXML_MAJOR_VERSION = 2; const int TIXML_MINOR_VERSION = 3; const int TIXML_PATCH_VERSION = 4; /* Internal structure for tracking location of items in the XML file. */ struct TiXmlCursor { TiXmlCursor() { Clear(); } void Clear() { row = col = -1; } int row; // 0 based. int col; // 0 based. }; // Only used by Attribute::Query functions enum { TIXML_SUCCESS, TIXML_NO_ATTRIBUTE, TIXML_WRONG_TYPE }; // Used by the parsing routines. enum TiXmlEncoding { TIXML_ENCODING_UNKNOWN, TIXML_ENCODING_UTF8, TIXML_ENCODING_LEGACY }; const TiXmlEncoding TIXML_DEFAULT_ENCODING = TIXML_ENCODING_UNKNOWN; /** TiXmlBase is a base class for every class in TinyXml. It does little except to establish that TinyXml classes can be printed and provide some utility functions. In XML, the document and elements can contain other elements and other types of nodes. @verbatim A Document can contain: Element (container or leaf) Comment (leaf) Unknown (leaf) Declaration( leaf ) An Element can contain: Element (container or leaf) Text (leaf) Attributes (not on tree) Comment (leaf) Unknown (leaf) A Decleration contains: Attributes (not on tree) @endverbatim */ class TiXmlBase { friend class TiXmlNode; friend class TiXmlElement; friend class TiXmlDocument; public: TiXmlBase() : userData(0) {} virtual ~TiXmlBase() {} /** All TinyXml classes can print themselves to a filestream. This is a formatted print, and will insert tabs and newlines. (For an unformatted stream, use the << operator.) */ virtual void Print( FILE* cfile, int depth ) const = 0; /** The world does not agree on whether white space should be kept or not. In order to make everyone happy, these global, static functions are provided to set whether or not TinyXml will condense all white space into a single space or not. The default is to condense. Note changing this values is not thread safe. */ static void SetCondenseWhiteSpace( bool condense ) { condenseWhiteSpace = condense; } /// Return the current white space setting. static bool IsWhiteSpaceCondensed() { return condenseWhiteSpace; } /** Return the position, in the original source file, of this node or attribute. The row and column are 1-based. (That is the first row and first column is 1,1). If the returns values are 0 or less, then the parser does not have a row and column value. Generally, the row and column value will be set when the TiXmlDocument::Load(), TiXmlDocument::LoadFile(), or any TiXmlNode::Parse() is called. It will NOT be set when the DOM was created from operator>>. The values reflect the initial load. Once the DOM is modified programmatically (by adding or changing nodes and attributes) the new values will NOT update to reflect changes in the document. There is a minor performance cost to computing the row and column. Computation can be disabled if TiXmlDocument::SetTabSize() is called with 0 as the value. @sa TiXmlDocument::SetTabSize() */ int Row() const { return location.row + 1; } int Column() const { return location.col + 1; } ///< See Row() void SetUserData( void* user ) { userData = user; } void* GetUserData() { return userData; } // Table that returs, for a given lead byte, the total number of bytes // in the UTF-8 sequence. static const int utf8ByteTable[256]; virtual const char* Parse( const char* p, TiXmlParsingData* data, TiXmlEncoding encoding /*= TIXML_ENCODING_UNKNOWN */ ) = 0; enum { TIXML_NO_ERROR = 0, TIXML_ERROR, TIXML_ERROR_OPENING_FILE, TIXML_ERROR_OUT_OF_MEMORY, TIXML_ERROR_PARSING_ELEMENT, TIXML_ERROR_FAILED_TO_READ_ELEMENT_NAME, TIXML_ERROR_READING_ELEMENT_VALUE, TIXML_ERROR_READING_ATTRIBUTES, TIXML_ERROR_PARSING_EMPTY, TIXML_ERROR_READING_END_TAG, TIXML_ERROR_PARSING_UNKNOWN, TIXML_ERROR_PARSING_COMMENT, TIXML_ERROR_PARSING_DECLARATION, TIXML_ERROR_DOCUMENT_EMPTY, TIXML_ERROR_EMBEDDED_NULL, TIXML_ERROR_STRING_COUNT }; protected: // See STL_STRING_BUG // Utility class to overcome a bug. class StringToBuffer { public: StringToBuffer( const TIXML_STRING& str ); ~StringToBuffer(); char* buffer; }; static const char* SkipWhiteSpace( const char*, TiXmlEncoding encoding ); inline static bool IsWhiteSpace( char c ) { return ( isspace( (unsigned char) c ) || c == '\n' || c == '\r' ); } virtual void StreamOut (TIXML_OSTREAM *) const = 0; #ifdef TIXML_USE_STL static bool StreamWhiteSpace( TIXML_ISTREAM * in, TIXML_STRING * tag ); static bool StreamTo( TIXML_ISTREAM * in, int character, TIXML_STRING * tag ); #endif /* Reads an XML name into the string provided. Returns a pointer just past the last character of the name, or 0 if the function has an error. */ static const char* ReadName( const char* p, TIXML_STRING* name, TiXmlEncoding encoding ); /* Reads text. Returns a pointer past the given end tag. Wickedly complex options, but it keeps the (sensitive) code in one place. */ static const char* ReadText( const char* in, // where to start TIXML_STRING* text, // the string read bool ignoreWhiteSpace, // whether to keep the white space const char* endTag, // what ends this text bool ignoreCase, // whether to ignore case in the end tag TiXmlEncoding encoding ); // the current encoding // If an entity has been found, transform it into a character. static const char* GetEntity( const char* in, char* value, int* length, TiXmlEncoding encoding ); // Get a character, while interpreting entities. // The length can be from 0 to 4 bytes. inline static const char* GetChar( const char* p, char* _value, int* length, TiXmlEncoding encoding ) { assert( p ); if ( encoding == TIXML_ENCODING_UTF8 ) { *length = utf8ByteTable[ *((unsigned char*)p) ]; assert( *length >= 0 && *length < 5 ); } else { *length = 1; } if ( *length == 1 ) { if ( *p == '&' ) return GetEntity( p, _value, length, encoding ); *_value = *p; return p+1; } else if ( *length ) { strncpy( _value, p, *length ); return p + (*length); } else { // Not valid text. return 0; } } // Puts a string to a stream, expanding entities as it goes. // Note this should not contian the '<', '>', etc, or they will be transformed into entities! static void PutString( const TIXML_STRING& str, TIXML_OSTREAM* out ); static void PutString( const TIXML_STRING& str, TIXML_STRING* out ); // Return true if the next characters in the stream are any of the endTag sequences. // Ignore case only works for english, and should only be relied on when comparing // to Engilish words: StringEqual( p, "version", true ) is fine. static bool StringEqual( const char* p, const char* endTag, bool ignoreCase, TiXmlEncoding encoding ); static const char* errorString[ TIXML_ERROR_STRING_COUNT ]; TiXmlCursor location; /// Field containing a generic user pointer void* userData; // None of these methods are reliable for any language except English. // Good for approximation, not great for accuracy. static int IsAlpha( unsigned char anyByte, TiXmlEncoding encoding ); static int IsAlphaNum( unsigned char anyByte, TiXmlEncoding encoding ); inline static int ToLower( int v, TiXmlEncoding encoding ) { if ( encoding == TIXML_ENCODING_UTF8 ) { if ( v < 128 ) return tolower( v ); return v; } else { return tolower( v ); } } static void ConvertUTF32ToUTF8( unsigned long input, char* output, int* length ); private: TiXmlBase( const TiXmlBase& ); // not implemented. void operator=( const TiXmlBase& base ); // not allowed. struct Entity { const char* str; unsigned int strLength; char chr; }; enum { NUM_ENTITY = 5, MAX_ENTITY_LENGTH = 6 }; static Entity entity[ NUM_ENTITY ]; static bool condenseWhiteSpace; }; /** The parent class for everything in the Document Object Model. (Except for attributes). Nodes have siblings, a parent, and children. A node can be in a document, or stand on its own. The type of a TiXmlNode can be queried, and it can be cast to its more defined type. */ class TiXmlNode : public TiXmlBase { friend class TiXmlDocument; friend class TiXmlElement; public: #ifdef TIXML_USE_STL /** An input stream operator, for every class. Tolerant of newlines and formatting, but doesn't expect them. */ friend std::istream& operator >> (std::istream& in, TiXmlNode& base); /** An output stream operator, for every class. Note that this outputs without any newlines or formatting, as opposed to Print(), which includes tabs and new lines. The operator<< and operator>> are not completely symmetric. Writing a node to a stream is very well defined. You'll get a nice stream of output, without any extra whitespace or newlines. But reading is not as well defined. (As it always is.) If you create a TiXmlElement (for example) and read that from an input stream, the text needs to define an element or junk will result. This is true of all input streams, but it's worth keeping in mind. A TiXmlDocument will read nodes until it reads a root element, and all the children of that root element. */ friend std::ostream& operator<< (std::ostream& out, const TiXmlNode& base); /// Appends the XML node or attribute to a std::string. friend std::string& operator<< (std::string& out, const TiXmlNode& base ); #else // Used internally, not part of the public API. friend TIXML_OSTREAM& operator<< (TIXML_OSTREAM& out, const TiXmlNode& base); #endif /** The types of XML nodes supported by TinyXml. (All the unsupported types are picked up by UNKNOWN.) */ enum NodeType { DOCUMENT, ELEMENT, COMMENT, UNKNOWN, TEXT, DECLARATION, TYPECOUNT }; virtual ~TiXmlNode(); /** The meaning of 'value' changes for the specific type of TiXmlNode. @verbatim Document: filename of the xml file Element: name of the element Comment: the comment text Unknown: the tag contents Text: the text string @endverbatim The subclasses will wrap this function. */ const char * Value() const { return value.c_str (); } /** Changes the value of the node. Defined as: @verbatim Document: filename of the xml file Element: name of the element Comment: the comment text Unknown: the tag contents Text: the text string @endverbatim */ void SetValue(const char * _value) { value = _value;} #ifdef TIXML_USE_STL /// STL std::string form. void SetValue( const std::string& _value ) { StringToBuffer buf( _value ); SetValue( buf.buffer ? buf.buffer : "" ); } #endif /// Delete all the children of this node. Does not affect 'this'. void Clear(); /// One step up the DOM. TiXmlNode* Parent() { return parent; } const TiXmlNode* Parent() const { return parent; } const TiXmlNode* FirstChild() const { return firstChild; } ///< The first child of this node. Will be null if there are no children. TiXmlNode* FirstChild() { return firstChild; } const TiXmlNode* FirstChild( const char * value ) const; ///< The first child of this node with the matching 'value'. Will be null if none found. TiXmlNode* FirstChild( const char * value ); ///< The first child of this node with the matching 'value'. Will be null if none found. ///Arlen Albert Keshabian addons: gets the element a path points to virtual TiXmlNode *NodeFromPath(const char *sPath, char chSeparator = '.') const; virtual TiXmlElement *ElementFromPath(const char *sPath, char chSeparator = '.') const { TiXmlNode *l_pNode = NodeFromPath(sPath, chSeparator); return (l_pNode) ? l_pNode->ToElement() : NULL; } #ifdef TIXML_USE_STL virtual TiXmlNode *NodeFromPath( const std::string& sPath, char chSeparator = '.') const {return NodeFromPath(sPath.c_str(), chSeparator);} virtual TiXmlElement *ElementFromPath( const std::string& sPath, char chSeparator = '.') const {return ElementFromPath(sPath.c_str(), chSeparator);} #endif ////////////////////////////////////////////////////////////////////////// const TiXmlNode* LastChild() const { return lastChild; } /// The last child of this node. Will be null if there are no children. TiXmlNode* LastChild() { return lastChild; } const TiXmlNode* LastChild( const char * value ) const; /// The last child of this node matching 'value'. Will be null if there are no children. TiXmlNode* LastChild( const char * value ); #ifdef TIXML_USE_STL const TiXmlNode* FirstChild( const std::string& _value ) const { return FirstChild (_value.c_str ()); } ///< STL std::string form. TiXmlNode* FirstChild( const std::string& _value ) { return FirstChild (_value.c_str ()); } ///< STL std::string form. const TiXmlNode* LastChild( const std::string& _value ) const { return LastChild (_value.c_str ()); } ///< STL std::string form. TiXmlNode* LastChild( const std::string& _value ) { return LastChild (_value.c_str ()); } ///< STL std::string form. #endif /** An alternate way to walk the children of a node. One way to iterate over nodes is: @verbatim for( child = parent->FirstChild(); child; child = child->NextSibling() ) @endverbatim IterateChildren does the same thing with the syntax: @verbatim child = 0; while( child = parent->IterateChildren( child ) ) @endverbatim IterateChildren takes the previous child as input and finds the next one. If the previous child is null, it returns the first. IterateChildren will return null when done. */ const TiXmlNode* IterateChildren( const TiXmlNode* previous ) const; TiXmlNode* IterateChildren( TiXmlNode* previous ); /// This flavor of IterateChildren searches for children with a particular 'value' const TiXmlNode* IterateChildren( const char * value, const TiXmlNode* previous ) const; TiXmlNode* IterateChildren( const char * value, TiXmlNode* previous ); #ifdef TIXML_USE_STL const TiXmlNode* IterateChildren( const std::string& _value, const TiXmlNode* previous ) const { return IterateChildren (_value.c_str (), previous); } ///< STL std::string form. TiXmlNode* IterateChildren( const std::string& _value, TiXmlNode* previous ) { return IterateChildren (_value.c_str (), previous); } ///< STL std::string form. #endif /** Add a new node related to this. Adds a child past the LastChild. Returns a pointer to the new object or NULL if an error occured. */ TiXmlNode* InsertEndChild( const TiXmlNode& addThis ); /** Add a new node related to this. Adds a child past the LastChild. NOTE: the node to be added is passed by pointer, and will be henceforth owned (and deleted) by tinyXml. This method is efficient and avoids an extra copy, but should be used with care as it uses a different memory model than the other insert functions. @sa InsertEndChild */ TiXmlNode* LinkEndChild( TiXmlNode* addThis ); /** Add a new node related to this. Adds a child before the specified child. Returns a pointer to the new object or NULL if an error occured. */ TiXmlNode* InsertBeforeChild( TiXmlNode* beforeThis, const TiXmlNode& addThis ); /** Add a new node related to this. Adds a child after the specified child. Returns a pointer to the new object or NULL if an error occured. */ TiXmlNode* InsertAfterChild( TiXmlNode* afterThis, const TiXmlNode& addThis ); /** Replace a child of this node. Returns a pointer to the new object or NULL if an error occured. */ TiXmlNode* ReplaceChild( TiXmlNode* replaceThis, const TiXmlNode& withThis ); /// Delete a child of this node. bool RemoveChild( TiXmlNode* removeThis ); /// Navigate to a sibling node. const TiXmlNode* PreviousSibling() const { return prev; } TiXmlNode* PreviousSibling() { return prev; } /// Navigate to a sibling node. const TiXmlNode* PreviousSibling( const char * ) const; TiXmlNode* PreviousSibling( const char * ); #ifdef TIXML_USE_STL const TiXmlNode* PreviousSibling( const std::string& _value ) const { return PreviousSibling (_value.c_str ()); } ///< STL std::string form. TiXmlNode* PreviousSibling( const std::string& _value ) { return PreviousSibling (_value.c_str ()); } ///< STL std::string form. const TiXmlNode* NextSibling( const std::string& _value) const { return NextSibling (_value.c_str ()); } ///< STL std::string form. TiXmlNode* NextSibling( const std::string& _value) { return NextSibling (_value.c_str ()); } ///< STL std::string form. #endif /// Navigate to a sibling node. const TiXmlNode* NextSibling() const { return next; } TiXmlNode* NextSibling() { return next; } /// Navigate to a sibling node with the given 'value'. const TiXmlNode* NextSibling( const char * ) const; TiXmlNode* NextSibling( const char * ); /** Convenience function to get through elements. Calls NextSibling and ToElement. Will skip all non-Element nodes. Returns 0 if there is not another element. */ const TiXmlElement* NextSiblingElement() const; TiXmlElement* NextSiblingElement(); /** Convenience function to get through elements. Calls NextSibling and ToElement. Will skip all non-Element nodes. Returns 0 if there is not another element. */ const TiXmlElement* NextSiblingElement( const char * ) const; TiXmlElement* NextSiblingElement( const char * ); #ifdef TIXML_USE_STL const TiXmlElement* NextSiblingElement( const std::string& _value) const { return NextSiblingElement (_value.c_str ()); } ///< STL std::string form. TiXmlElement* NextSiblingElement( const std::string& _value) { return NextSiblingElement (_value.c_str ()); } ///< STL std::string form. #endif /// Convenience function to get through elements. const TiXmlElement* FirstChildElement() const; TiXmlElement* FirstChildElement(); /// Convenience function to get through elements. const TiXmlElement* FirstChildElement( const char * value ) const; TiXmlElement* FirstChildElement( const char * value ); #ifdef TIXML_USE_STL const TiXmlElement* FirstChildElement( const std::string& _value ) const { return FirstChildElement (_value.c_str ()); } ///< STL std::string form. TiXmlElement* FirstChildElement( const std::string& _value ) { return FirstChildElement (_value.c_str ()); } ///< STL std::string form. #endif /** Query the type (as an enumerated value, above) of this node. The possible types are: DOCUMENT, ELEMENT, COMMENT, UNKNOWN, TEXT, and DECLARATION. */ virtual int Type() const { return type; } /** Return a pointer to the Document this node lives in. Returns null if not in a document. */ const TiXmlDocument* GetDocument() const; TiXmlDocument* GetDocument(); /// Returns true if this node has no children. bool NoChildren() const { return !firstChild; } const TiXmlDocument* ToDocument() const { return ( this && type == DOCUMENT ) ? (const TiXmlDocument*) this : 0; } ///< Cast to a more defined type. Will return null not of the requested type. const TiXmlElement* ToElement() const { return ( this && type == ELEMENT ) ? (const TiXmlElement*) this : 0; } ///< Cast to a more defined type. Will return null not of the requested type. const TiXmlComment* ToComment() const { return ( this && type == COMMENT ) ? (const TiXmlComment*) this : 0; } ///< Cast to a more defined type. Will return null not of the requested type. const TiXmlUnknown* ToUnknown() const { return ( this && type == UNKNOWN ) ? (const TiXmlUnknown*) this : 0; } ///< Cast to a more defined type. Will return null not of the requested type. const TiXmlText* ToText() const { return ( this && type == TEXT ) ? (const TiXmlText*) this : 0; } ///< Cast to a more defined type. Will return null not of the requested type. const TiXmlDeclaration* ToDeclaration() const { return ( this && type == DECLARATION ) ? (const TiXmlDeclaration*) this : 0; } ///< Cast to a more defined type. Will return null not of the requested type. TiXmlDocument* ToDocument() { return ( this && type == DOCUMENT ) ? (TiXmlDocument*) this : 0; } ///< Cast to a more defined type. Will return null not of the requested type. TiXmlElement* ToElement() { return ( this && type == ELEMENT ) ? (TiXmlElement*) this : 0; } ///< Cast to a more defined type. Will return null not of the requested type. TiXmlComment* ToComment() { return ( this && type == COMMENT ) ? (TiXmlComment*) this : 0; } ///< Cast to a more defined type. Will return null not of the requested type. TiXmlUnknown* ToUnknown() { return ( this && type == UNKNOWN ) ? (TiXmlUnknown*) this : 0; } ///< Cast to a more defined type. Will return null not of the requested type. TiXmlText* ToText() { return ( this && type == TEXT ) ? (TiXmlText*) this : 0; } ///< Cast to a more defined type. Will return null not of the requested type. TiXmlDeclaration* ToDeclaration() { return ( this && type == DECLARATION ) ? (TiXmlDeclaration*) this : 0; } ///< Cast to a more defined type. Will return null not of the requested type. /** Create an exact duplicate of this node and return it. The memory must be deleted by the caller. */ virtual TiXmlNode* Clone() const = 0; protected: TiXmlNode( NodeType _type ); // Copy to the allocated object. Shared functionality between Clone, Copy constructor, // and the assignment operator. void CopyTo( TiXmlNode* target ) const; #ifdef TIXML_USE_STL // The real work of the input operator. virtual void StreamIn( TIXML_ISTREAM* in, TIXML_STRING* tag ) = 0; #endif // Figure out what is at *p, and parse it. Returns null if it is not an xml node. TiXmlNode* Identify( const char* start, TiXmlEncoding encoding ); // Internal Value function returning a TIXML_STRING const TIXML_STRING& SValue() const { return value ; } TiXmlNode* parent; NodeType type; TiXmlNode* firstChild; TiXmlNode* lastChild; TIXML_STRING value; TiXmlNode* prev; TiXmlNode* next; private: TiXmlNode( const TiXmlNode& ); // not implemented. void operator=( const TiXmlNode& base ); // not allowed. }; /** An attribute is a name-value pair. Elements have an arbitrary number of attributes, each with a unique name. @note The attributes are not TiXmlNodes, since they are not part of the tinyXML document object model. There are other suggested ways to look at this problem. */ class TiXmlAttribute : public TiXmlBase { friend class TiXmlAttributeSet; public: /// Construct an empty attribute. TiXmlAttribute() : TiXmlBase() { document = 0; prev = next = 0; } #ifdef TIXML_USE_STL /// std::string constructor. TiXmlAttribute( const std::string& _name, const std::string& _value ) { name = _name; value = _value; document = 0; prev = next = 0; } #endif /// Construct an attribute with a name and value. TiXmlAttribute( const char * _name, const char * _value ) { name = _name; value = _value; document = 0; prev = next = 0; } const char* Name() const { return name.c_str (); } ///< Return the name of this attribute. const char* Value() const { return value.c_str (); } ///< Return the value of this attribute. const int IntValue() const; ///< Return the value of this attribute, converted to an integer. const double DoubleValue() const; ///< Return the value of this attribute, converted to a double. /** QueryIntValue examines the value string. It is an alternative to the IntValue() method with richer error checking. If the value is an integer, it is stored in 'value' and the call returns TIXML_SUCCESS. If it is not an integer, it returns TIXML_WRONG_TYPE. A specialized but useful call. Note that for success it returns 0, which is the opposite of almost all other TinyXml calls. */ int QueryIntValue( int* value ) const; /// QueryDoubleValue examines the value string. See QueryIntValue(). int QueryDoubleValue( double* value ) const; void SetName( const char* _name ) { name = _name; } ///< Set the name of this attribute. void SetValue( const char* _value ) { value = _value; } ///< Set the value. void SetIntValue( int value ); ///< Set the value from an integer. void SetDoubleValue( double value ); ///< Set the value from a double. #ifdef TIXML_USE_STL /// STL std::string form. void SetName( const std::string& _name ) { StringToBuffer buf( _name ); SetName ( buf.buffer ? buf.buffer : "error" ); } /// STL std::string form. void SetValue( const std::string& _value ) { StringToBuffer buf( _value ); SetValue( buf.buffer ? buf.buffer : "error" ); } #endif /// Get the next sibling attribute in the DOM. Returns null at end. const TiXmlAttribute* Next() const; TiXmlAttribute* Next(); /// Get the previous sibling attribute in the DOM. Returns null at beginning. const TiXmlAttribute* Previous() const; TiXmlAttribute* Previous(); bool operator==( const TiXmlAttribute& rhs ) const { return rhs.name == name; } bool operator<( const TiXmlAttribute& rhs ) const { return name < rhs.name; } bool operator>( const TiXmlAttribute& rhs ) const { return name > rhs.name; } /* Attribute parsing starts: first letter of the name returns: the next char after the value end quote */ virtual const char* Parse( const char* p, TiXmlParsingData* data, TiXmlEncoding encoding ); // Prints this Attribute to a FILE stream. virtual void Print( FILE* cfile, int depth ) const; virtual void StreamOut( TIXML_OSTREAM * out ) const; // [internal use] // Set the document pointer so the attribute can report errors. void SetDocument( TiXmlDocument* doc ) { document = doc; } private: TiXmlAttribute( const TiXmlAttribute& ); // not implemented. void operator=( const TiXmlAttribute& base ); // not allowed. TiXmlDocument* document; // A pointer back to a document, for error reporting. TIXML_STRING name; TIXML_STRING value; TiXmlAttribute* prev; TiXmlAttribute* next; }; /* A class used to manage a group of attributes. It is only used internally, both by the ELEMENT and the DECLARATION. The set can be changed transparent to the Element and Declaration classes that use it, but NOT transparent to the Attribute which has to implement a next() and previous() method. Which makes it a bit problematic and prevents the use of STL. This version is implemented with circular lists because: - I like circular lists - it demonstrates some independence from the (typical) doubly linked list. */ class TiXmlAttributeSet { public: TiXmlAttributeSet(); ~TiXmlAttributeSet(); void Add( TiXmlAttribute* attribute ); void Remove( TiXmlAttribute* attribute ); const TiXmlAttribute* First() const { return ( sentinel.next == &sentinel ) ? 0 : sentinel.next; } TiXmlAttribute* First() { return ( sentinel.next == &sentinel ) ? 0 : sentinel.next; } const TiXmlAttribute* Last() const { return ( sentinel.prev == &sentinel ) ? 0 : sentinel.prev; } TiXmlAttribute* Last() { return ( sentinel.prev == &sentinel ) ? 0 : sentinel.prev; } const TiXmlAttribute* Find( const char * name ) const; TiXmlAttribute* Find( const char * name ); private: //*ME: Because of hidden/disabled copy-construktor in TiXmlAttribute (sentinel-element), //*ME: this class must be also use a hidden/disabled copy-constructor !!! TiXmlAttributeSet( const TiXmlAttributeSet& ); // not allowed void operator=( const TiXmlAttributeSet& ); // not allowed (as TiXmlAttribute) TiXmlAttribute sentinel; }; /** The element is a container class. It has a value, the element name, and can contain other elements, text, comments, and unknowns. Elements also contain an arbitrary number of attributes. */ class TiXmlElement : public TiXmlNode { public: /// Construct an element. TiXmlElement (const char * in_value); #ifdef TIXML_USE_STL /// std::string constructor. TiXmlElement( const std::string& _value ); #endif TiXmlElement( const TiXmlElement& ); void operator=( const TiXmlElement& base ); virtual ~TiXmlElement(); /** Given an attribute name, Attribute() returns the value for the attribute of that name, or null if none exists. */ const char* Attribute( const char* name ) const; /** Given an attribute name, Attribute() returns the value for the attribute of that name, or null if none exists. If the attribute exists and can be converted to an integer, the integer value will be put in the return 'i', if 'i' is non-null. */ const char* Attribute( const char* name, int* i ) const; /** Given an attribute name, Attribute() returns the value for the attribute of that name, or null if none exists. If the attribute exists and can be converted to an double, the double value will be put in the return 'd', if 'd' is non-null. */ const char* Attribute( const char* name, double* d ) const; /** QueryIntAttribute examines the attribute - it is an alternative to the Attribute() method with richer error checking. If the attribute is an integer, it is stored in 'value' and the call returns TIXML_SUCCESS. If it is not an integer, it returns TIXML_WRONG_TYPE. If the attribute does not exist, then TIXML_NO_ATTRIBUTE is returned. */ int QueryIntAttribute( const char* name, int* value ) const; /// QueryDoubleAttribute examines the attribute - see QueryIntAttribute(). int QueryDoubleAttribute( const char* name, double* value ) const; /// QueryFloatAttribute examines the attribute - see QueryIntAttribute(). int QueryDoubleAttribute( const char* name, float* value ) const { double d; int result = QueryDoubleAttribute( name, &d ); *value = (float)d; return result; } /** Sets an attribute of name to a given value. The attribute will be created if it does not exist, or changed if it does. */ void SetAttribute( const char* name, const char * value ); #ifdef TIXML_USE_STL const char* Attribute( const std::string& name ) const { return Attribute( name.c_str() ); } const char* Attribute( const std::string& name, int* i ) const { return Attribute( name.c_str(), i ); } const char* Attribute( const std::string& name, double* d ) const { return Attribute( name.c_str(), d ); } int QueryIntAttribute( const std::string& name, int* value ) const { return QueryIntAttribute( name.c_str(), value ); } int QueryDoubleAttribute( const std::string& name, double* value ) const { return QueryDoubleAttribute( name.c_str(), value ); } /// STL std::string form. void SetAttribute( const std::string& name, const std::string& _value ) { StringToBuffer n( name ); StringToBuffer v( _value ); if ( n.buffer && v.buffer ) SetAttribute (n.buffer, v.buffer ); } ///< STL std::string form. void SetAttribute( const std::string& name, int _value ) { StringToBuffer n( name ); if ( n.buffer ) SetAttribute (n.buffer, _value); } #endif /** Sets an attribute of name to a given value. The attribute will be created if it does not exist, or changed if it does. */ void SetAttribute( const char * name, int value ); /** Sets an attribute of name to a given value. The attribute will be created if it does not exist, or changed if it does. */ void SetDoubleAttribute( const char * name, double value ); /** Deletes an attribute with the given name. */ void RemoveAttribute( const char * name ); #ifdef TIXML_USE_STL void RemoveAttribute( const std::string& name ) { RemoveAttribute (name.c_str ()); } ///< STL std::string form. #endif const TiXmlAttribute* FirstAttribute() const { return attributeSet.First(); } ///< Access the first attribute in this element. TiXmlAttribute* FirstAttribute() { return attributeSet.First(); } const TiXmlAttribute* LastAttribute() const { return attributeSet.Last(); } ///< Access the last attribute in this element. TiXmlAttribute* LastAttribute() { return attributeSet.Last(); } /// Creates a new Element and returns it - the returned element is a copy. virtual TiXmlNode* Clone() const; // Print the Element to a FILE stream. virtual void Print( FILE* cfile, int depth ) const; /* Attribtue parsing starts: next char past '<' returns: next char past '>' */ virtual const char* Parse( const char* p, TiXmlParsingData* data, TiXmlEncoding encoding ); protected: void CopyTo( TiXmlElement* target ) const; void ClearThis(); // like clear, but initializes 'this' object as well // Used to be public [internal use] #ifdef TIXML_USE_STL virtual void StreamIn( TIXML_ISTREAM * in, TIXML_STRING * tag ); #endif virtual void StreamOut( TIXML_OSTREAM * out ) const; /* [internal use] Reads the "value" of the element -- another element, or text. This should terminate with the current end tag. */ const char* ReadValue( const char* in, TiXmlParsingData* prevData, TiXmlEncoding encoding ); private: TiXmlAttributeSet attributeSet; }; /** An XML comment. */ class TiXmlComment : public TiXmlNode { public: /// Constructs an empty comment. TiXmlComment() : TiXmlNode( TiXmlNode::COMMENT ) {} TiXmlComment( const TiXmlComment& ); void operator=( const TiXmlComment& base ); virtual ~TiXmlComment() {} /// Returns a copy of this Comment. virtual TiXmlNode* Clone() const; /// Write this Comment to a FILE stream. virtual void Print( FILE* cfile, int depth ) const; /* Attribtue parsing starts: at the ! of the !-- returns: next char past '>' */ virtual const char* Parse( const char* p, TiXmlParsingData* data, TiXmlEncoding encoding ); protected: void CopyTo( TiXmlComment* target ) const; // used to be public #ifdef TIXML_USE_STL virtual void StreamIn( TIXML_ISTREAM * in, TIXML_STRING * tag ); #endif virtual void StreamOut( TIXML_OSTREAM * out ) const; private: }; /** XML text. Contained in an element. */ class TiXmlText : public TiXmlNode { friend class TiXmlElement; public: /// Constructor. TiXmlText (const char * initValue) : TiXmlNode (TiXmlNode::TEXT) { SetValue( initValue ); } virtual ~TiXmlText() {} #ifdef TIXML_USE_STL /// Constructor. TiXmlText( const std::string& initValue ) : TiXmlNode (TiXmlNode::TEXT) { SetValue( initValue ); } #endif TiXmlText( const TiXmlText& copy ) : TiXmlNode( TiXmlNode::TEXT ) { copy.CopyTo( this ); } void operator=( const TiXmlText& base ) { base.CopyTo( this ); } /// Write this text object to a FILE stream. virtual void Print( FILE* cfile, int depth ) const; virtual const char* Parse( const char* p, TiXmlParsingData* data, TiXmlEncoding encoding ); protected : /// [internal use] Creates a new Element and returns it. virtual TiXmlNode* Clone() const; void CopyTo( TiXmlText* target ) const; virtual void StreamOut ( TIXML_OSTREAM * out ) const; bool Blank() const; // returns true if all white space and new lines // [internal use] #ifdef TIXML_USE_STL virtual void StreamIn( TIXML_ISTREAM * in, TIXML_STRING * tag ); #endif private: }; /** In correct XML the declaration is the first entry in the file. @verbatim <?xml version="1.0" standalone="yes"?> @endverbatim TinyXml will happily read or write files without a declaration, however. There are 3 possible attributes to the declaration: version, encoding, and standalone. Note: In this version of the code, the attributes are handled as special cases, not generic attributes, simply because there can only be at most 3 and they are always the same. */ class TiXmlDeclaration : public TiXmlNode { public: /// Construct an empty declaration. TiXmlDeclaration() : TiXmlNode( TiXmlNode::DECLARATION ) {} #ifdef TIXML_USE_STL /// Constructor. TiXmlDeclaration( const std::string& _version, const std::string& _encoding, const std::string& _standalone ); #endif /// Construct. TiXmlDeclaration( const char* _version, const char* _encoding, const char* _standalone ); TiXmlDeclaration( const TiXmlDeclaration& copy ); void operator=( const TiXmlDeclaration& copy ); virtual ~TiXmlDeclaration() {} /// Version. Will return an empty string if none was found. const char *Version() const { return version.c_str (); } /// Encoding. Will return an empty string if none was found. const char *Encoding() const { return encoding.c_str (); } /// Is this a standalone document? const char *Standalone() const { return standalone.c_str (); } /// Creates a copy of this Declaration and returns it. virtual TiXmlNode* Clone() const; /// Print this declaration to a FILE stream. virtual void Print( FILE* cfile, int depth ) const; virtual const char* Parse( const char* p, TiXmlParsingData* data, TiXmlEncoding encoding ); protected: void CopyTo( TiXmlDeclaration* target ) const; // used to be public #ifdef TIXML_USE_STL virtual void StreamIn( TIXML_ISTREAM * in, TIXML_STRING * tag ); #endif virtual void StreamOut ( TIXML_OSTREAM * out) const; private: TIXML_STRING version; TIXML_STRING encoding; TIXML_STRING standalone; }; /** Any tag that tinyXml doesn't recognize is saved as an unknown. It is a tag of text, but should not be modified. It will be written back to the XML, unchanged, when the file is saved. DTD tags get thrown into TiXmlUnknowns. */ class TiXmlUnknown : public TiXmlNode { public: TiXmlUnknown() : TiXmlNode( TiXmlNode::UNKNOWN ) {} virtual ~TiXmlUnknown() {} TiXmlUnknown( const TiXmlUnknown& copy ) : TiXmlNode( TiXmlNode::UNKNOWN ) { copy.CopyTo( this ); } void operator=( const TiXmlUnknown& copy ) { copy.CopyTo( this ); } /// Creates a copy of this Unknown and returns it. virtual TiXmlNode* Clone() const; /// Print this Unknown to a FILE stream. virtual void Print( FILE* cfile, int depth ) const; virtual const char* Parse( const char* p, TiXmlParsingData* data, TiXmlEncoding encoding ); protected: void CopyTo( TiXmlUnknown* target ) const; #ifdef TIXML_USE_STL virtual void StreamIn( TIXML_ISTREAM * in, TIXML_STRING * tag ); #endif virtual void StreamOut ( TIXML_OSTREAM * out ) const; private: }; /** Always the top level node. A document binds together all the XML pieces. It can be saved, loaded, and printed to the screen. The 'value' of a document node is the xml file name. */ class TiXmlDocument : public TiXmlNode { public: /// Create an empty document, that has no name. TiXmlDocument(); /// Create a document with a name. The name of the document is also the filename of the xml. TiXmlDocument( const char * documentName ); #ifdef TIXML_USE_STL /// Constructor. TiXmlDocument( const std::string& documentName ); #endif TiXmlDocument( const TiXmlDocument& copy ); void operator=( const TiXmlDocument& copy ); virtual ~TiXmlDocument() {} /** Load a file using the current document value. Returns true if successful. Will delete any existing document data before loading. */ bool LoadFile( TiXmlEncoding encoding = TIXML_DEFAULT_ENCODING ); /// Save a file using the current document value. Returns true if successful. bool SaveFile() const; /// Load a file using the given filename. Returns true if successful. bool LoadFile( const char * filename, TiXmlEncoding encoding = TIXML_DEFAULT_ENCODING ); /// Save a file using the given filename. Returns true if successful. bool SaveFile( const char * filename ) const; #ifdef TIXML_USE_STL bool LoadFile( const std::string& filename, TiXmlEncoding encoding = TIXML_DEFAULT_ENCODING ) ///< STL std::string version. { StringToBuffer f( filename ); return ( f.buffer && LoadFile( f.buffer, encoding )); } bool SaveFile( const std::string& filename ) const ///< STL std::string version. { StringToBuffer f( filename ); return ( f.buffer && SaveFile( f.buffer )); } #endif /** Parse the given null terminated block of xml data. Passing in an encoding to this method (either TIXML_ENCODING_LEGACY or TIXML_ENCODING_UTF8 will force TinyXml to use that encoding, regardless of what TinyXml might otherwise try to detect. */ virtual const char* Parse( const char* p, TiXmlParsingData* data = 0, TiXmlEncoding encoding = TIXML_DEFAULT_ENCODING ); /** Get the root element -- the only top level element -- of the document. In well formed XML, there should only be one. TinyXml is tolerant of multiple elements at the document level. */ const TiXmlElement* RootElement() const { return FirstChildElement(); } TiXmlElement* RootElement() { return FirstChildElement(); } /** If an error occurs, Error will be set to true. Also, - The ErrorId() will contain the integer identifier of the error (not generally useful) - The ErrorDesc() method will return the name of the error. (very useful) - The ErrorRow() and ErrorCol() will return the location of the error (if known) */ bool Error() const { return error; } /// Contains a textual (english) description of the error if one occurs. const char * ErrorDesc() const { return errorDesc.c_str (); } /** Generally, you probably want the error string ( ErrorDesc() ). But if you prefer the ErrorId, this function will fetch it. */ const int ErrorId() const { return errorId; } /** Returns the location (if known) of the error. The first column is column 1, and the first row is row 1. A value of 0 means the row and column wasn't applicable (memory errors, for example, have no row/column) or the parser lost the error. (An error in the error reporting, in that case.) @sa SetTabSize, Row, Column */ int ErrorRow() { return errorLocation.row+1; } int ErrorCol() { return errorLocation.col+1; } ///< The column where the error occured. See ErrorRow() /** By calling this method, with a tab size greater than 0, the row and column of each node and attribute is stored when the file is loaded. Very useful for tracking the DOM back in to the source file. The tab size is required for calculating the location of nodes. If not set, the default of 4 is used. The tabsize is set per document. Setting the tabsize to 0 disables row/column tracking. Note that row and column tracking is not supported when using operator>>. The tab size needs to be enabled before the parse or load. Correct usage: @verbatim TiXmlDocument doc; doc.SetTabSize( 8 ); doc.Load( "myfile.xml" ); @endverbatim @sa Row, Column */ void SetTabSize( int _tabsize ) { tabsize = _tabsize; } int TabSize() const { return tabsize; } /** If you have handled the error, it can be reset with this call. The error state is automatically cleared if you Parse a new XML block. */ void ClearError() { error = false; errorId = 0; errorDesc = ""; errorLocation.row = errorLocation.col = 0; //errorLocation.last = 0; } /** Dump the document to standard out. */ void Print() const { Print( stdout, 0 ); } /// Print this Document to a FILE stream. virtual void Print( FILE* cfile, int depth = 0 ) const; // [internal use] void SetError( int err, const char* errorLocation, TiXmlParsingData* prevData, TiXmlEncoding encoding ); protected : virtual void StreamOut ( TIXML_OSTREAM * out) const; // [internal use] virtual TiXmlNode* Clone() const; #ifdef TIXML_USE_STL virtual void StreamIn( TIXML_ISTREAM * in, TIXML_STRING * tag ); #endif private: void CopyTo( TiXmlDocument* target ) const; bool error; int errorId; TIXML_STRING errorDesc; int tabsize; TiXmlCursor errorLocation; }; /** A TiXmlHandle is a class that wraps a node pointer with null checks; this is an incredibly useful thing. Note that TiXmlHandle is not part of the TinyXml DOM structure. It is a separate utility class. Take an example: @verbatim <Document> <Element attributeA = "valueA"> <Child attributeB = "value1" /> <Child attributeB = "value2" /> </Element> <Document> @endverbatim Assuming you want the value of "attributeB" in the 2nd "Child" element, it's very easy to write a *lot* of code that looks like: @verbatim TiXmlElement* root = document.FirstChildElement( "Document" ); if ( root ) { TiXmlElement* element = root->FirstChildElement( "Element" ); if ( element ) { TiXmlElement* child = element->FirstChildElement( "Child" ); if ( child ) { TiXmlElement* child2 = child->NextSiblingElement( "Child" ); if ( child2 ) { // Finally do something useful. @endverbatim And that doesn't even cover "else" cases. TiXmlHandle addresses the verbosity of such code. A TiXmlHandle checks for null pointers so it is perfectly safe and correct to use: @verbatim TiXmlHandle docHandle( &document ); TiXmlElement* child2 = docHandle.FirstChild( "Document" ).FirstChild( "Element" ).Child( "Child", 1 ).Element(); if ( child2 ) { // do something useful @endverbatim Which is MUCH more concise and useful. It is also safe to copy handles - internally they are nothing more than node pointers. @verbatim TiXmlHandle handleCopy = handle; @endverbatim What they should not be used for is iteration: @verbatim int i=0; while ( true ) { TiXmlElement* child = docHandle.FirstChild( "Document" ).FirstChild( "Element" ).Child( "Child", i ).Element(); if ( !child ) break; // do something ++i; } @endverbatim It seems reasonable, but it is in fact two embedded while loops. The Child method is a linear walk to find the element, so this code would iterate much more than it needs to. Instead, prefer: @verbatim TiXmlElement* child = docHandle.FirstChild( "Document" ).FirstChild( "Element" ).FirstChild( "Child" ).Element(); for( child; child; child=child->NextSiblingElement() ) { // do something } @endverbatim */ class TiXmlHandle { public: /// Create a handle from any node (at any depth of the tree.) This can be a null pointer. TiXmlHandle( TiXmlNode* node ) { this->node = node; } /// Copy constructor TiXmlHandle( const TiXmlHandle& ref ) { this->node = ref.node; } TiXmlHandle operator=( const TiXmlHandle& ref ) { this->node = ref.node; return *this; } /// Return a handle to the first child node. TiXmlHandle FirstChild() const; /// Return a handle to the first child node with the given name. TiXmlHandle FirstChild( const char * value ) const; /// Return a handle to the first child element. TiXmlHandle FirstChildElement() const; /// Return a handle to the first child element with the given name. TiXmlHandle FirstChildElement( const char * value ) const; /** Return a handle to the "index" child with the given name. The first child is 0, the second 1, etc. */ TiXmlHandle Child( const char* value, int index ) const; /** Return a handle to the "index" child. The first child is 0, the second 1, etc. */ TiXmlHandle Child( int index ) const; /** Return a handle to the "index" child element with the given name. The first child element is 0, the second 1, etc. Note that only TiXmlElements are indexed: other types are not counted. */ TiXmlHandle ChildElement( const char* value, int index ) const; /** Return a handle to the "index" child element. The first child element is 0, the second 1, etc. Note that only TiXmlElements are indexed: other types are not counted. */ TiXmlHandle ChildElement( int index ) const; #ifdef TIXML_USE_STL TiXmlHandle FirstChild( const std::string& _value ) const { return FirstChild( _value.c_str() ); } TiXmlHandle FirstChildElement( const std::string& _value ) const { return FirstChildElement( _value.c_str() ); } TiXmlHandle Child( const std::string& _value, int index ) const { return Child( _value.c_str(), index ); } TiXmlHandle ChildElement( const std::string& _value, int index ) const { return ChildElement( _value.c_str(), index ); } #endif /// Return the handle as a TiXmlNode. This may return null. TiXmlNode* Node() const { return node; } /// Return the handle as a TiXmlElement. This may return null. TiXmlElement* Element() const { return ( ( node && node->ToElement() ) ? node->ToElement() : 0 ); } /// Return the handle as a TiXmlText. This may return null. TiXmlText* Text() const { return ( ( node && node->ToText() ) ? node->ToText() : 0 ); } /// Return the handle as a TiXmlUnknown. This may return null; TiXmlUnknown* Unknown() const { return ( ( node && node->ToUnknown() ) ? node->ToUnknown() : 0 ); } private: TiXmlNode* node; }; #ifdef _MSC_VER #pragma warning( default : 4530 ) #pragma warning( default : 4786 ) #endif #endif
c94356bef61c119527a1d10644cfa7cfa23881c5
d52d5fdbcd848334c6b7799cad7b3dfd2f1f33e4
/third_party/folly/folly/test/ChronoTest.cpp
0e7ac92ee49b7aee8b4642b76964d27f578cdc02
[ "Apache-2.0" ]
permissive
zhiliaoniu/toolhub
4109c2a488b3679e291ae83cdac92b52c72bc592
39a3810ac67604e8fa621c69f7ca6df1b35576de
refs/heads/master
2022-12-10T23:17:26.541731
2020-07-18T03:33:48
2020-07-18T03:33:48
125,298,974
1
0
null
null
null
null
UTF-8
C++
false
false
3,146
cpp
/* * Copyright 2017-present Facebook, 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. */ #include <folly/Chrono.h> #include <folly/portability/GTest.h> using namespace std::chrono; using namespace folly::chrono; namespace { class ChronoTest : public testing::Test {}; } // namespace TEST_F(ChronoTest, ceil_duration) { EXPECT_EQ(seconds(7), ceil<seconds>(seconds(7))); EXPECT_EQ(seconds(7), ceil<seconds>(milliseconds(7000))); EXPECT_EQ(seconds(7), ceil<seconds>(milliseconds(6200))); } TEST_F(ChronoTest, ceil_time_point) { auto const point = steady_clock::time_point{}; EXPECT_EQ(point + seconds(7), ceil<seconds>(point + seconds(7))); EXPECT_EQ(point + seconds(7), ceil<seconds>(point + milliseconds(7000))); EXPECT_EQ(point + seconds(7), ceil<seconds>(point + milliseconds(6200))); } TEST_F(ChronoTest, floor_duration) { EXPECT_EQ(seconds(7), floor<seconds>(seconds(7))); EXPECT_EQ(seconds(7), floor<seconds>(milliseconds(7000))); EXPECT_EQ(seconds(7), floor<seconds>(milliseconds(7800))); } TEST_F(ChronoTest, floor_time_point) { auto const point = steady_clock::time_point{}; EXPECT_EQ(point + seconds(7), floor<seconds>(point + seconds(7))); EXPECT_EQ(point + seconds(7), floor<seconds>(point + milliseconds(7000))); EXPECT_EQ(point + seconds(7), floor<seconds>(point + milliseconds(7800))); } TEST_F(ChronoTest, round_duration) { EXPECT_EQ(seconds(7), round<seconds>(seconds(7))); EXPECT_EQ(seconds(6), round<seconds>(milliseconds(6200))); EXPECT_EQ(seconds(6), round<seconds>(milliseconds(6500))); EXPECT_EQ(seconds(7), round<seconds>(milliseconds(6800))); EXPECT_EQ(seconds(7), round<seconds>(milliseconds(7000))); EXPECT_EQ(seconds(7), round<seconds>(milliseconds(7200))); EXPECT_EQ(seconds(8), round<seconds>(milliseconds(7500))); EXPECT_EQ(seconds(8), round<seconds>(milliseconds(7800))); } TEST_F(ChronoTest, round_time_point) { auto const point = steady_clock::time_point{}; EXPECT_EQ(point + seconds(7), round<seconds>(point + seconds(7))); EXPECT_EQ(point + seconds(6), round<seconds>(point + milliseconds(6200))); EXPECT_EQ(point + seconds(6), round<seconds>(point + milliseconds(6500))); EXPECT_EQ(point + seconds(7), round<seconds>(point + milliseconds(6800))); EXPECT_EQ(point + seconds(7), round<seconds>(point + milliseconds(7000))); EXPECT_EQ(point + seconds(7), round<seconds>(point + milliseconds(7200))); EXPECT_EQ(point + seconds(8), round<seconds>(point + milliseconds(7500))); EXPECT_EQ(point + seconds(8), round<seconds>(point + milliseconds(7800))); }
35eaf2cfd43f19409e8bbd5e0df9d689e9f85a2a
b59daf97e55cb798de6daeb31a6872d7586bd500
/src/nstd/execution/let_value.cpp
215b4e97edff38333a7762215723498ecf23ee65
[]
no_license
kirkshoop/kuhllib
29a7348cd92ec67564a01bf5a4ebd3ce262a206d
8ac4f14d37db3d93e09dd2756a36bf7937c2faa2
refs/heads/main
2023-08-10T22:40:50.933000
2021-10-02T16:09:55
2021-10-02T16:09:55
412,868,756
2
0
null
2021-10-02T17:39:59
2021-10-02T17:39:58
null
UTF-8
C++
false
false
1,939
cpp
// nstd/execution/let_value.cpp -*-C++-*- // ---------------------------------------------------------------------------- // Copyright (C) 2021 Dietmar Kuehl http://www.dietmar-kuehl.de // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without restriction, // including without limitation the rights to use, copy, modify, // merge, publish, distribute, sublicense, and/or sell copies of // the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. // ---------------------------------------------------------------------------- #include "nstd/execution/let_value.hpp" // ---------------------------------------------------------------------------- namespace nstd::execution { int let_value_dummy = 0; }
6cab9ee2dad26a02dae02de57035067263fd4566
41279e0ed19e26cc0fcaafa229604d1094aed6a8
/include/networking/ServerStartException.hpp
f772241d67296e4ca574cea40b6c1e9c1c1c293f
[]
no_license
ChuxiongMa/TextAdventure
20a180747414ede1a8b0e85869809f955b067b11
4f217106de6908909f17408c16df822ed9543284
refs/heads/master
2016-08-13T02:01:58.490646
2016-02-21T23:26:48
2016-02-21T23:26:48
52,233,748
0
0
null
null
null
null
UTF-8
C++
false
false
395
hpp
#ifndef SERVER_START_EXCEPTION_H #define SERVER_START_EXCEPTION_H #include <exception> #include <string> using exception = std::exception; using string = std::string; namespace networking { class ServerStartException : public exception { string reason; public: ServerStartException(); ServerStartException(string); virtual const char* what() const throw(); }; } #endif
bd9d1112e540706e20bb52c10417811b68da86fb
1d450ef7469a01208e67b0820f0e91bd3630630a
/third-party/jni.hpp-4.0.0/include/jni/native_method.hpp
978b733d24f7c236099446afe4c899ac251ec9d3
[ "BSD-3-Clause", "Apache-2.0", "ISC" ]
permissive
folkene/pyjadx
db3ff1e9f4625add618388f28441ebd7dd894692
d16ece0df2cb9b0500d00cac49df84578a81fc56
refs/heads/master
2020-08-04T14:59:14.259823
2019-10-08T14:24:40
2019-10-08T14:24:40
212,176,491
1
0
Apache-2.0
2019-10-01T18:59:38
2019-10-01T18:59:38
null
UTF-8
C++
false
false
13,769
hpp
#pragma once #include <jni/types.hpp> #include <jni/errors.hpp> #include <jni/functions.hpp> #include <jni/tagging.hpp> #include <jni/class.hpp> #include <jni/object.hpp> #include <exception> #include <type_traits> #include <iostream> namespace jni { template < class M, class Enable = void > struct NativeMethodTraits; template < class R, class... Args > struct NativeMethodTraits< R (Args...) > { using Type = R (Args...); using ResultType = R; }; template < class R, class... Args > struct NativeMethodTraits< R (*)(Args...) > : NativeMethodTraits< R (Args...) > {}; template < class T, class R, class... Args > struct NativeMethodTraits< R (T::*)(Args...) const > : NativeMethodTraits< R (Args...) > {}; template < class T, class R, class... Args > struct NativeMethodTraits< R (T::*)(Args...) > : NativeMethodTraits< R (Args...) > {}; template < class M > struct NativeMethodTraits< M, std::enable_if_t< std::is_class<M>::value > > : NativeMethodTraits< decltype(&M::operator()) > {}; /// Low-level, lambda template < class M > auto MakeNativeMethod(const char* name, const char* sig, const M& m, std::enable_if_t< std::is_class<M>::value >* = nullptr) { using FunctionType = typename NativeMethodTraits<M>::Type; using ResultType = typename NativeMethodTraits<M>::ResultType; static FunctionType* method = m; auto wrapper = [] (JNIEnv* env, auto... args) { try { return method(env, args...); } catch (...) { ThrowJavaError(*env, std::current_exception()); return ResultType(); } }; return JNINativeMethod< FunctionType > { name, sig, wrapper }; } /// Low-level, function pointer template < class M, M method > auto MakeNativeMethod(const char* name, const char* sig) { using FunctionType = typename NativeMethodTraits<M>::Type; using ResultType = typename NativeMethodTraits<M>::ResultType; auto wrapper = [] (JNIEnv* env, auto... args) { try { return method(env, args...); } catch (...) { ThrowJavaError(*env, std::current_exception()); return ResultType(); } }; return JNINativeMethod< FunctionType > { name, sig, wrapper }; } /// High-level, lambda template < class T, T*... > struct NativeMethodMaker; template < class T, class R, class Subject, class... Args > struct NativeMethodMaker< R (T::*)(JNIEnv&, Subject, Args...) const > { template < class M > auto operator()(const char* name, const M& m) { static M method(m); auto wrapper = [] (JNIEnv* env, UntaggedType<Subject> subject, UntaggedType<Args>... args) { return ReleaseUnique(method(*env, AsLvalue(Tag<std::decay_t<Subject>>(*env, *subject)), AsLvalue(Tag<std::decay_t<Args>>(*env, args))...)); }; return MakeNativeMethod(name, TypeSignature<RemoveUniqueType<R> (std::decay_t<Args>...)>()(), wrapper); } }; template < class T, class Subject, class... Args > struct NativeMethodMaker< void (T::*)(JNIEnv&, Subject, Args...) const > { template < class M > auto operator()(const char* name, const M& m) { static M method(m); auto wrapper = [] (JNIEnv* env, UntaggedType<Subject> subject, UntaggedType<Args>... args) { method(*env, AsLvalue(Tag<std::decay_t<Subject>>(*env, *subject)), AsLvalue(Tag<std::decay_t<Args>>(*env, args))...); }; return MakeNativeMethod(name, TypeSignature<void (std::decay_t<Args>...)>()(), wrapper); } }; template < class M > auto MakeNativeMethod(const char* name, const M& m) { return NativeMethodMaker<decltype(&M::operator())>()(name, m); } /// High-level, function pointer template < class R, class Subject, class... Args, R (*method)(JNIEnv&, Subject, Args...) > struct NativeMethodMaker< R (JNIEnv&, Subject, Args...), method > { auto operator()(const char* name) { auto wrapper = [] (JNIEnv* env, UntaggedType<Subject> subject, UntaggedType<Args>... args) { return ReleaseUnique(method(*env, AsLvalue(Tag<std::decay_t<Subject>>(*env, *subject)), AsLvalue(Tag<std::decay_t<Args>>(*env, args))...)); }; return MakeNativeMethod(name, TypeSignature<RemoveUniqueType<R> (std::decay_t<Args>...)>()(), wrapper); } }; template < class Subject, class... Args, void (*method)(JNIEnv&, Subject, Args...) > struct NativeMethodMaker< void (JNIEnv&, Subject, Args...), method > { auto operator()(const char* name) { auto wrapper = [] (JNIEnv* env, UntaggedType<Subject> subject, UntaggedType<Args>... args) { method(*env, AsLvalue(Tag<std::decay_t<Subject>>(*env, *subject)), AsLvalue(Tag<std::decay_t<Args>>(*env, args))...); }; return MakeNativeMethod(name, TypeSignature<void (std::decay_t<Args>...)>()(), wrapper); } }; template < class M, M method > auto MakeNativeMethod(const char* name) { using FunctionType = typename NativeMethodTraits<M>::Type; return NativeMethodMaker<FunctionType, method>()(name); } /// High-level peer, lambda template < class L, class > class NativePeerLambdaMethod; template < class L, class R, class P, class... Args > class NativePeerLambdaMethod< L, R (L::*)(JNIEnv&, P&, Args...) const > { private: const char* name; L lambda; public: NativePeerLambdaMethod(const char* n, const L& l) : name(n), lambda(l) {} template < class Peer, class TagType, class = std::enable_if_t< std::is_same<P, Peer>::value > > auto operator()(const Field<TagType, jlong>& field) { auto wrapper = [field, lambda = lambda] (JNIEnv& env, Object<TagType>& obj, Args... args) { return lambda(env, *reinterpret_cast<P*>(obj.Get(env, field)), args...); }; return MakeNativeMethod(name, wrapper); } }; template < class L > auto MakeNativePeerMethod(const char* name, const L& lambda, std::enable_if_t< std::is_class<L>::value >* = nullptr) { return NativePeerLambdaMethod<L, decltype(&L::operator())>(name, lambda); } /// High-level peer, function pointer template < class M, M* > class NativePeerFunctionPointerMethod; template < class R, class P, class... Args, R (*method)(JNIEnv&, P&, Args...) > class NativePeerFunctionPointerMethod< R (JNIEnv&, P&, Args...), method > { private: const char* name; public: NativePeerFunctionPointerMethod(const char* n) : name(n) {} template < class Peer, class TagType, class = std::enable_if_t< std::is_same<P, Peer>::value > > auto operator()(const Field<TagType, jlong>& field) { auto wrapper = [field] (JNIEnv& env, Object<TagType>& obj, Args... args) { return method(env, *reinterpret_cast<P*>(obj.Get(env, field)), args...); }; return MakeNativeMethod(name, wrapper); } }; template < class M, M method > auto MakeNativePeerMethod(const char* name, std::enable_if_t< !std::is_member_function_pointer<M>::value >* = nullptr) { using FunctionType = typename NativeMethodTraits<M>::Type; return NativePeerFunctionPointerMethod<FunctionType, method>(name); } /// High-level peer, member function pointer template < class M, M > class NativePeerMemberFunctionMethod; template < class R, class P, class... Args, R (P::*method)(JNIEnv&, Args...) > class NativePeerMemberFunctionMethod< R (P::*)(JNIEnv&, Args...), method > { private: const char* name; public: NativePeerMemberFunctionMethod(const char* n) : name(n) {} template < class Peer, class TagType, class = std::enable_if_t< std::is_same<P, Peer>::value > > auto operator()(const Field<TagType, jlong>& field) { auto wrapper = [field] (JNIEnv& env, Object<TagType>& obj, Args... args) { return (reinterpret_cast<P*>(obj.Get(env, field))->*method)(env, args...); }; return MakeNativeMethod(name, wrapper); } }; template < class M, M method > auto MakeNativePeerMethod(const char* name, std::enable_if_t< std::is_member_function_pointer<M>::value >* = nullptr) { return NativePeerMemberFunctionMethod<M, method>(name); } /** * A registration function for native methods on a "native peer": a long-lived native * object corresponding to a Java object, usually created when the Java object is created * and destroyed when the Java object's finalizer runs. * * It assumes that the Java object has a field, named by `fieldName`, of Java type `long`, * which is used to hold a pointer to the native peer. * * `Methods` must be a sequence of `NativePeerMethod` instances, instantiated with pointer * to member functions of the native peer class. For each method in `methods`, a native * method is bound with a signature corresponding to that of the member function. The * wrapper for that native method obtains the native peer instance from the Java field and * calls the native peer method on it, passing along any arguments. * * An overload is provided that accepts a Callable object with a unique_ptr result type and * the names for native creation and finalization methods, allowing creation and disposal of * the native peer from Java. * * For an example of all of the above, see the `examples` directory. */ template < class Peer, class TagType, class... Methods > void RegisterNativePeer(JNIEnv& env, const Class<TagType>& clazz, const char* fieldName, Methods&&... methods) { static Field<TagType, jni::jlong> field { env, clazz, fieldName }; RegisterNatives(env, *clazz, methods.template operator()<Peer>(field)...); } template < class Peer, class TagType, class > struct NativePeerHelper; template < class Peer, class TagType, class... Args > struct NativePeerHelper< Peer, TagType, std::unique_ptr<Peer> (JNIEnv&, Args...) > { using UniquePeer = std::unique_ptr<Peer>; using Initializer = UniquePeer (JNIEnv&, Args...); auto MakeInitializer(const Field<TagType, jlong>& field, const char* name, Initializer* initializer) const { auto wrapper = [field, initializer] (JNIEnv& e, Object<TagType>& obj, std::decay_t<Args>&... args) { UniquePeer previous(reinterpret_cast<Peer*>(obj.Get(e, field))); UniquePeer instance(initializer(e, args...)); obj.Set(e, field, reinterpret_cast<jlong>(instance.get())); instance.release(); }; return MakeNativeMethod(name, wrapper); } auto MakeFinalizer(const Field<TagType, jlong>& field, const char* name) const { auto wrapper = [field] (JNIEnv& e, Object<TagType>& obj) { UniquePeer instance(reinterpret_cast<Peer*>(obj.Get(e, field))); if (instance) obj.Set(e, field, jlong(0)); instance.reset(); }; return MakeNativeMethod(name, wrapper); } }; template < class Peer, class TagType, class Initializer, class... Methods > void RegisterNativePeer(JNIEnv& env, const Class<TagType>& clazz, const char* fieldName, Initializer initialize, const char* initializeMethodName, const char* finalizeMethodName, Methods&&... methods) { static Field<TagType, jlong> field { env, clazz, fieldName }; using InitializerMethodType = typename NativeMethodTraits<Initializer>::Type; NativePeerHelper<Peer, TagType, InitializerMethodType> helper; RegisterNatives(env, *clazz, helper.MakeInitializer(field, initializeMethodName, initialize), helper.MakeFinalizer(field, finalizeMethodName), methods.template operator()<Peer>(field)...); } // Like std::make_unique, but with non-universal reference arguments, so it can be // explicitly specialized (jni::MakePeer<Peer, jni::jboolean, ...>). template < class Peer, class... Args > std::unique_ptr<Peer> MakePeer(jni::JNIEnv& env, Args... args) { return std::make_unique<Peer>(env, args...); } }
55995aeb48ad970642db50003a20a0b3b4918d5b
c45ed46065d8b78dac0dd7df1c95b944f34d1033
/TC-SRM-567-div1-1000/oysq.cpp
9ce257fe231a6a09783dc6cbca5f2e0060064870
[]
no_license
yzq986/cntt2016-hw1
ed65a6b7ad3dfe86a4ff01df05b8fc4b7329685e
12e799467888a0b3c99ae117cce84e8842d92337
refs/heads/master
2021-01-17T11:27:32.270012
2017-01-26T03:23:22
2017-01-26T03:23:22
84,036,200
0
0
null
2017-03-06T06:04:12
2017-03-06T06:04:12
null
UTF-8
C++
false
false
1,806
cpp
// BEGIN CUT HERE // END CUT HERE #line 5 "Mountains.cpp" #include <bits/stdc++.h> using namespace std; #define SZ(x) (int)(x).size() #define pb push_back #define mp make_pair #define fi first #define se second typedef vector<int> VI; typedef vector<string> VS; typedef vector<double> VD; typedef long long ll; typedef pair<int,int> pii; template<class T>inline void chkmax(T &x, const T &y) {if(x < y) x = y;} template<class T>inline void chkmin(T &x, const T &y) {if(x > y) x = y;} const int N = 10; const int W = 50; const int MOD = 1000000009; int n, w; bool vis[N + 9][W + 9];// vis[i][j] = true 表示第i座山在第j列可以看到 std::vector<int> h;// 每个山顶的高度 std::map<std::vector<int>, int> f[N + 9];// f[i][v] 表示倒着放到第i座山时状态为v的方案数 int dp(int x, const std::vector<int> &a) {// x表示当前处理第i座山,a表示每列的高度 if(x == -1) return 1; if(f[x].count(a)) return f[x][a];// 记忆化搜索 int &ret = f[x][a]; std::vector<int> na; for(int i = 0; i < w; ++i) {// 枚举山顶的列坐标 bool flag = true; for(int j = 0; j < w; ++j) if((h[x] - abs(j - i) <= a[j]) == vis[x][j]) {// 判断是否满足题意 flag = false; break; } if(flag) { na = a; for(int j = 0; j < w; ++j) chkmax(na[j], h[x] - abs(j - i)); (ret += dp(x - 1, na)) %= MOD; } } return ret; } struct Mountains { int countPlacements(vector <int> _h, vector <string> v) { h = _h, n = SZ(h), w = SZ(v[0]); for(int i = 0; i < n; ++i) f[i].clear(); for(int i = 0; i < n; ++i) for(int j = 0; j < w; ++j) if(v[i][j] == 'X') vis[i][j] = true; else vis[i][j] = false; std::vector<int> t; for(int i = 0; i < w; ++i) t.pb(0);// 初始每列的高度为0 return dp(n - 1, t); } };
0f9f0ead55a6b801d35b58d56eb57f2de6bcb09a
4c1d515719425db127ba5285b5be4f03af10d5a1
/URI-Judge/URI_1111.cpp
feb270b9bb96d652571c2d090fdfed91da0c8e01
[]
no_license
matheusmtta/Competitive-Programming
26e51741332aed223b9231da33749940f5a1b977
e254b80090cc75bc213aad0a7957875842e90f1a
refs/heads/master
2023-04-28T18:08:51.417470
2023-04-24T21:09:00
2023-04-24T21:09:00
223,605,672
7
0
null
null
null
null
UTF-8
C++
false
false
1,974
cpp
#include <bits/stdc++.h> using namespace std; #define MOD 1000000007 #define INF (int)0x3f3f3f3f #define MP make_pair #define PB push_back typedef long int int32; typedef unsigned long int uint32; typedef long long int int64; typedef unsigned long long int uint64; const int MAX = 15; int n; map <pair<int, int>, vector<int>> mtx; map <pair<int, int>, int> dist; map <pair<int, int>, int> visited; //NORTH: ( 1, 0) //SOUTH: (-1, 0) //WEST: ( 0,-1) //EAST: ( 0, 1) map <int, pair <int, int>> mov; int BFS(pair<int, int> source, int x1, int y1){ queue <pair<int,int>> walk; dist[source] = 0; visited[source] = 1; walk.push(source); while (!walk.empty()){ pair <int, int> v = walk.front(); walk.pop(); if (v.first == x1 && v.second == y1) return dist[v]; for (int i = 0; i < 4; i++){ pair <int, int> tmp; tmp.first = v.first + mov[i].first; tmp.second = v.second + mov[i].second; if (mtx[v][i] == 1 && visited[tmp] == 0){ visited[tmp] = 1; dist[tmp] = dist[v] + 1; walk.push(tmp); } } } return -1; } int main(){ ios_base::sync_with_stdio(false); cin.tie(NULL); mov[0] = MP(0, 1); mov[1] = MP(0, -1); mov[2] = MP(-1, 0); mov[3] = MP( 1, 0); while (true){ cin >> n; if (n == 0) return 0; for (int y = n-1; y >= 0; y--){ for (int x = 0; x < n; x++){ //cout << "(" << x << " " << y << "): "; for (int k = 0; k < 4; k++){ int z; cin >> z; //cout << z << " "; mtx[MP(x, y)].push_back(z); visited[MP(x, y)] = 0; dist[MP(x, y)] = -1; } //cout << endl; } } int q; cin >> q; while (q--){ int x0, y0, x1, y1; cin >> x0 >> y0 >> x1 >> y1; int ans = BFS(MP(x0, y0), x1, y1); if(ans == -1) cout << "Impossible" << endl; else cout << ans << endl; for (int y = n-1; y >= 0; y--){ for (int x = 0; x < n; x++){ visited[MP(x, y)] = 0; dist[MP(x, y)] = -1; } } } cout << endl; mtx.clear(); } return 0; }
ad656658ad1414291b8accf70d9023af491026c8
4258a21020932d0849a95c182aa8086a0467e641
/sdk/verify/mi_demo/alderaan/vpe/st_main_vpe.cpp
65bd8dc4eb7499503c3429ff7b88012308da7223
[]
no_license
sengeiou/Democode-TAKOYAKI-BETA001-0312
a04647412764b57532a1b8ca02a1b4966a5a5395
0c3261e5c067314d2ac4f858399fff8cc2793f01
refs/heads/master
2022-05-24T09:48:13.816615
2020-04-13T10:47:24
2020-04-13T10:47:24
null
0
0
null
null
null
null
UTF-8
C++
false
false
107,538
cpp
/* Copyright (c) 2018-2019 Sigmastar Technology Corp. All rights reserved. Unless otherwise stipulated in writing, any and all information contained herein regardless in any format shall remain the sole proprietary of Sigmastar Technology Corp. and be kept in strict confidence (��Sigmastar Confidential Information��) by the recipient. Any unauthorized act including without limitation unauthorized disclosure, copying, use, reproduction, sale, distribution, modification, disassembling, reverse engineering and compiling of the contents of Sigmastar Confidential Information is unlawful and strictly prohibited. Sigmastar hereby reserves the rights to any and all damages, losses, costs and expenses resulting therefrom. */ #include <stdio.h> #include <stdlib.h> #include <signal.h> #include <time.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <pthread.h> #include <sys/syscall.h> #include "st_common.h" #include "st_vif.h" #include "st_vpe.h" #include "st_venc.h" #include "BasicUsageEnvironment.hh" #include "liveMedia.hh" #include "Live555RTSPServer.hh" //#include "mi_rgn.h" #include "mi_sensor.h" #include "mi_sensor_datatype.h" #include "mi_isp.h" #include "mi_iqserver.h" #include "mi_eptz.h" #include "mi_ldc.h" #include "mi_eptz.h" #define RTSP_LISTEN_PORT 554 static Live555RTSPServer *g_pRTSPServer = NULL; #define PATH_PREFIX "/mnt" int s32LoadIQBin = 1; #define NONHDR_PATH "/customer/nohdr.bin" #define HDR_PATH "/customer/hdr.bin" #define ST_MAX_PORT_NUM (5) #define ST_MAX_SCL_NUM (3) #define ST_MAX_SENSOR_NUM (3) #define ST_MAX_STREAM_NUM (ST_MAX_PORT_NUM * ST_MAX_SENSOR_NUM) #define ST_LDC_MAX_VIEWNUM (4) #define ASCII_COLOR_GREEN "\033[1;32m" #define ASCII_COLOR_END "\033[0m" #define ASCII_COLOR_RED "\033[1;31m" #define DBG_INFO(fmt, args...) printf(ASCII_COLOR_GREEN"%s[%d]: " fmt ASCII_COLOR_END, __FUNCTION__,__LINE__, ##args); #define DBG_ERR(fmt, args...) printf(ASCII_COLOR_RED"%s[%d]: " fmt ASCII_COLOR_END, __FUNCTION__,__LINE__, ##args); typedef struct ST_Sensor_Attr_s { MI_U32 u32BindVifDev; MI_BOOL bUsed; }ST_Sensor_Attr_t; typedef struct ST_Vif_Attr_s { MI_U32 u32BindVpeChan; MI_SYS_BindType_e eBindType; MI_VIF_WorkMode_e eWorkMode; }ST_Vif_Attr_t; typedef struct ST_VpePortAttr_s { MI_BOOL bUsed; MI_U32 u32BindVencChan; MI_BOOL bMirror; MI_BOOL bFlip; MI_SYS_PixelFormat_e ePixelFormat; MI_SYS_WindowRect_t stPortCrop; MI_SYS_WindowSize_t stPortSize; MI_SYS_WindowSize_t stOrigPortSize; MI_SYS_WindowRect_t stOrigPortCrop; MI_S32 s32DumpBuffNum; char FilePath[256]; pthread_mutex_t Portmutex; pthread_t pGetDatathread; }ST_VpePortAttr_t; typedef struct ST_VpeChannelAttr_s { ST_VpePortAttr_t stVpePortAttr[ST_MAX_PORT_NUM]; MI_VPE_HDRType_e eHdrType; MI_VPE_3DNR_Level_e e3DNRLevel; MI_SYS_Rotate_e eVpeRotate; MI_BOOL bChnMirror; MI_BOOL bChnFlip; MI_SYS_WindowRect_t stVpeChnCrop; MI_SYS_WindowRect_t stOrgVpeChnCrop; MI_BOOL bEnLdc; MI_U32 u32ChnPortMode; MI_VPE_RunningMode_e eRunningMode; char LdcCfgbin_Path[128]; mi_eptz_config_param tconfig_para; MI_U32 u32ViewNum; LDC_BIN_HANDLE ldcBinBuffer[ST_LDC_MAX_VIEWNUM]; MI_U32 u32LdcBinSize[ST_LDC_MAX_VIEWNUM]; MI_S32 s32Rot[ST_LDC_MAX_VIEWNUM]; }ST_VpeChannelAttr_t; typedef struct ST_VencAttr_s { MI_U32 u32BindVpeChn; MI_U32 u32BindVpePort; MI_SYS_BindType_e eBindType; MI_U32 u32BindParam; MI_VENC_CHN vencChn; MI_VENC_ModType_e eType; MI_U32 u32Width; MI_U32 u32Height; char szStreamName[128]; MI_BOOL bUsed; MI_BOOL bStart; }ST_VencAttr_t; static MI_S32 gbPreviewByVenc = FALSE; static ST_Sensor_Attr_t gstSensorAttr[ST_MAX_SENSOR_NUM]; static ST_Vif_Attr_t gstVifAttr[ST_MAX_SENSOR_NUM]; static ST_VpeChannelAttr_t gstVpeChnattr[ST_MAX_SENSOR_NUM]; static ST_VencAttr_t gstVencattr[ST_MAX_STREAM_NUM]; static MI_BOOL bExit = FALSE; void ST_Flush(void) { char c; while((c = getchar()) != '\n' && c != EOF); } void *ST_OpenStream(char const *szStreamName, void *arg) { MI_U32 i = 0; MI_S32 s32Ret = MI_SUCCESS; for(i = 0; i < ST_MAX_STREAM_NUM; i ++) { if(!strncmp(szStreamName, gstVencattr[i].szStreamName, strlen(szStreamName))) { break; } } if(i >= ST_MAX_STREAM_NUM) { ST_ERR("not found this stream, \"%s\"", szStreamName); return NULL; } ST_VencAttr_t *pstVencAttr = &gstVencattr[i]; s32Ret = MI_VENC_RequestIdr(pstVencAttr->vencChn, TRUE); ST_DBG("open stream \"%s\" success, chn:%d\n", szStreamName, pstVencAttr->vencChn); if(MI_SUCCESS != s32Ret) { ST_WARN("request IDR fail, error:%x\n", s32Ret); } return pstVencAttr; } MI_U32 u32GetCnt=0, u32ReleaseCnt=0; int ST_VideoReadStream(void *handle, unsigned char *ucpBuf, int BufLen, struct timeval *p_Timestamp, void *arg) { MI_SYS_BufInfo_t stBufInfo; MI_S32 s32Ret = MI_SUCCESS; MI_S32 len = 0; MI_U32 u32DevId = 0; MI_VENC_Stream_t stStream; MI_VENC_Pack_t stPack; MI_VENC_ChnStat_t stStat; MI_VENC_CHN vencChn ; if(handle == NULL) { return -1; } ST_VencAttr_t *pstStreamInfo = (ST_VencAttr_t *)handle; vencChn = pstStreamInfo->vencChn; if(pstStreamInfo->bStart == FALSE) return 0; s32Ret = MI_VENC_GetChnDevid(vencChn, &u32DevId); if(MI_SUCCESS != s32Ret) { ST_INFO("MI_VENC_GetChnDevid %d error, %X\n", vencChn, s32Ret); } memset(&stBufInfo, 0x0, sizeof(MI_SYS_BufInfo_t)); memset(&stStream, 0, sizeof(stStream)); memset(&stPack, 0, sizeof(stPack)); stStream.pstPack = &stPack; stStream.u32PackCount = 1; s32Ret = MI_VENC_Query(vencChn, &stStat); if(s32Ret != MI_SUCCESS || stStat.u32CurPacks == 0) { return 0; } s32Ret = MI_VENC_GetStream(vencChn, &stStream, 40); if(MI_SUCCESS == s32Ret) { u32GetCnt++; len = stStream.pstPack[0].u32Len; memcpy(ucpBuf, stStream.pstPack[0].pu8Addr, MIN(len, BufLen)); s32Ret = MI_VENC_ReleaseStream(vencChn, &stStream); if(s32Ret != MI_SUCCESS) { ST_WARN("RELEASE venc buffer fail\n"); } u32ReleaseCnt ++; return len; } return 0; } int ST_CloseStream(void *handle, void *arg) { if(handle == NULL) { return -1; } ST_VencAttr_t *pstStreamInfo = (ST_VencAttr_t *)handle; ST_DBG("close \"%s\" success\n", pstStreamInfo->szStreamName); return 0; } MI_S32 ST_RtspServerStart(void) { unsigned int rtspServerPortNum = RTSP_LISTEN_PORT; int iRet = 0; char *urlPrefix = NULL; int arraySize = ARRAY_SIZE(gstVencattr); ST_VencAttr_t *pstStreamAttr = gstVencattr; int i = 0; ServerMediaSession *mediaSession = NULL; ServerMediaSubsession *subSession = NULL; Live555RTSPServer *pRTSPServer = NULL; pRTSPServer = new Live555RTSPServer(); if(pRTSPServer == NULL) { ST_ERR("malloc error\n"); return -1; } iRet = pRTSPServer->SetRTSPServerPort(rtspServerPortNum); while(iRet < 0) { rtspServerPortNum++; if(rtspServerPortNum > 65535) { ST_INFO("Failed to create RTSP server: %s\n", pRTSPServer->getResultMsg()); delete pRTSPServer; pRTSPServer = NULL; return -2; } iRet = pRTSPServer->SetRTSPServerPort(rtspServerPortNum); } urlPrefix = pRTSPServer->rtspURLPrefix(); for(i = 0; i < arraySize; i ++) { if(pstStreamAttr[i].bUsed != TRUE) continue; printf("=================URL===================\n"); printf("%s%s\n", urlPrefix, pstStreamAttr[i].szStreamName); printf("=================URL===================\n"); pRTSPServer->createServerMediaSession(mediaSession, pstStreamAttr[i].szStreamName, NULL, NULL); if(pstStreamAttr[i].eType == E_MI_VENC_MODTYPE_H264E) { subSession = WW_H264VideoFileServerMediaSubsession::createNew( *(pRTSPServer->GetUsageEnvironmentObj()), pstStreamAttr[i].szStreamName, ST_OpenStream, ST_VideoReadStream, ST_CloseStream, 30); } else if(pstStreamAttr[i].eType == E_MI_VENC_MODTYPE_H265E) { subSession = WW_H265VideoFileServerMediaSubsession::createNew( *(pRTSPServer->GetUsageEnvironmentObj()), pstStreamAttr[i].szStreamName, ST_OpenStream, ST_VideoReadStream, ST_CloseStream, 30); } else if(pstStreamAttr[i].eType == E_MI_VENC_MODTYPE_JPEGE) { subSession = WW_JPEGVideoFileServerMediaSubsession::createNew( *(pRTSPServer->GetUsageEnvironmentObj()), pstStreamAttr[i].szStreamName, ST_OpenStream, ST_VideoReadStream, ST_CloseStream, 30); } pRTSPServer->addSubsession(mediaSession, subSession); pRTSPServer->addServerMediaSession(mediaSession); } pRTSPServer->Start(); g_pRTSPServer = pRTSPServer; return 0; } MI_S32 ST_RtspServerStop(void) { if(g_pRTSPServer) { g_pRTSPServer->Join(); delete g_pRTSPServer; g_pRTSPServer = NULL; } return 0; } MI_S32 ST_WriteOneFrame(FILE *fp, int offset, char *pDataFrame, int line_offset, int line_size, int lineNumber) { int size = 0; int i = 0; char *pData = NULL; int yuvSize = line_size; MI_S32 s32Ret = -1; for(i = 0; i < lineNumber; i++) { pData = pDataFrame + line_offset * i; yuvSize = line_size; do { if(yuvSize < 256) { size = yuvSize; } else { size = 256; } size = fwrite(pData, 1, size, fp); if(size == 0) { break; } else if(size < 0) { break; } pData += size; yuvSize -= size; } while(yuvSize > 0); s32Ret = MI_SUCCESS; } return s32Ret; } MI_S32 ST_GetVpeOutputData(MI_U32 u32SensorNum) { MI_S32 s32Portid = 0; MI_S32 s32Channelid = 0; MI_S32 s32DumpBuffNum =0; char sFilePath[128]; time_t stTime = 0; ST_VpePortAttr_t *pstVpePortAttr = NULL; MI_VPE_PortMode_t stVpePortMode; memset(&stVpePortMode, 0x0, sizeof(MI_VPE_PortMode_t)); memset(&stTime, 0, sizeof(stTime)); if(u32SensorNum > 1) { printf("select channel id:"); scanf("%d", &s32Channelid); ST_Flush(); if(s32Channelid >= ST_MAX_SENSOR_NUM) { printf("chnid %d > max %d \n", s32Channelid, ST_MAX_SENSOR_NUM); return 0; } } else { s32Channelid = 0; } printf("select port id:"); scanf("%d", &s32Portid); ST_Flush(); printf("Dump Buffer Num:"); scanf("%d", &s32DumpBuffNum); ST_Flush(); printf("write file path:\n"); scanf("%s", sFilePath); ST_Flush(); if(s32Portid >= ST_MAX_PORT_NUM) { printf("port %d, not valid 0~3 \n", s32Portid); return 0; } pstVpePortAttr = &gstVpeChnattr[s32Channelid].stVpePortAttr[s32Portid]; if(pstVpePortAttr->bUsed != TRUE) { printf("port %d, not valid \n", s32Portid); return 0; } pthread_mutex_lock(&pstVpePortAttr->Portmutex); MI_VPE_GetPortMode(0, s32Portid, &stVpePortMode); sprintf(pstVpePortAttr->FilePath, "%s/vpeport%d_%dx%d_pixel%d_%ld.raw", sFilePath, s32Portid, stVpePortMode.u16Width, stVpePortMode.u16Height, stVpePortMode.ePixelFormat, time(&stTime)); pstVpePortAttr->s32DumpBuffNum = s32DumpBuffNum; pthread_mutex_unlock(&pstVpePortAttr->Portmutex); return 0; } MI_S32 ST_VpeDisablePort(MI_U32 u32SensorNum) { MI_S32 s32Portid = 0; ST_VpePortAttr_t *pstVpePortAttr = NULL; MI_S32 s32Channelid = 0; if(u32SensorNum > 1) { printf("select channel id:"); scanf("%d", &s32Channelid); ST_Flush(); if(s32Channelid >= ST_MAX_SENSOR_NUM) { printf("chnid %d > max %d \n", s32Channelid, ST_MAX_SENSOR_NUM); return 0; } } else { s32Channelid = 0; } printf("select port id:"); scanf("%d", &s32Portid); ST_Flush(); if(s32Portid >= ST_MAX_PORT_NUM) { printf("port %d, not valid 0~3 \n", s32Portid); return 0; } pstVpePortAttr = &gstVpeChnattr[s32Channelid].stVpePortAttr[s32Portid]; pstVpePortAttr->bUsed = FALSE; MI_VPE_DisablePort(s32Channelid, s32Portid); return 0; } MI_S32 ST_GetVencOut() { MI_S32 s32Ret = MI_SUCCESS; MI_VENC_Stream_t stStream; MI_VENC_Pack_t stPack; MI_U32 u32BypassCnt = 0; MI_S32 s32DumpBuffNum = 0; MI_S32 VencChn = 0; MI_VENC_Pack_t *pstPack = NULL; MI_U32 i=0; FILE *fp = NULL; char FilePath[256]; char sFilePath[128]; time_t stTime = 0; MI_VENC_ChnStat_t stStat; MI_VENC_ChnAttr_t stVencAttr; memset(&stVencAttr, 0x0, sizeof(MI_VENC_ChnAttr_t)); memset(&stStat, 0x0, sizeof(MI_VENC_ChnStat_t)); memset(&stStream, 0, sizeof(MI_VENC_Stream_t)); memset(&stPack, 0, sizeof(MI_VENC_Pack_t)); stStream.pstPack = &stPack; stStream.u32PackCount = 1; printf("select venc chn id:"); scanf("%d", &VencChn); ST_Flush(); printf("Dump Buffer Num:"); scanf("%d", &s32DumpBuffNum); ST_Flush(); printf("write file path:\n"); scanf("%s", sFilePath); ST_Flush(); s32Ret = MI_VENC_GetChnAttr(VencChn, &stVencAttr); if(s32Ret != MI_SUCCESS) { printf("channel %d, not valid \n", VencChn); return 0; } if(stVencAttr.stVeAttr.eType == E_MI_VENC_MODTYPE_JPEGE) sprintf(FilePath, "%s/venc_%ld.jpg", sFilePath, time(&stTime)); else sprintf(FilePath, "%s/venc_%ld.es", sFilePath, time(&stTime)); fp = fopen(FilePath,"wb"); if(fp == NULL) { printf("open file %s fail \n",FilePath); return 0; } while(s32DumpBuffNum > 0) { s32Ret = MI_VENC_Query(VencChn, &stStat); if(s32Ret != MI_SUCCESS || stStat.u32CurPacks == 0) { usleep(1 * 1000); continue; } s32Ret = MI_VENC_GetStream(VencChn, &stStream, 100); if(MI_SUCCESS == s32Ret) { if (0 == u32BypassCnt) { printf("##########Start to write file %s, id %d !!!#####################\n",FilePath, s32DumpBuffNum); for(i = 0; i < stStream.u32PackCount; i ++) { pstPack = &stStream.pstPack[i]; fwrite(pstPack->pu8Addr + pstPack->u32Offset, pstPack->u32Len - pstPack->u32Offset, 1, fp); } printf("##########End to write file id %d !!!#####################\n", s32DumpBuffNum); s32DumpBuffNum --; } else { u32BypassCnt--; printf("Bypasss frame %d !\n", u32BypassCnt); } s32Ret = MI_VENC_ReleaseStream(VencChn, &stStream); if(MI_SUCCESS != s32Ret) { ST_DBG("MI_VENC_ReleaseStream fail, ret:0x%x\n", s32Ret); } } usleep(200 * 1000); } fclose(fp); return 0; } MI_S32 ST_ReadLdcTableBin(const char *pConfigPath, LDC_BIN_HANDLE *tldc_bin, MI_U32 *pu32BinSize) { struct stat statbuff; MI_U8 *pBufData = NULL; MI_S32 s32Fd = 0; MI_U32 u32Size = 0; if (pConfigPath == NULL) { ST_ERR("File path null!\n"); return MI_ERR_LDC_ILLEGAL_PARAM; } printf("Read file %s\n", pConfigPath); memset(&statbuff, 0, sizeof(struct stat)); if(stat(pConfigPath, &statbuff) < 0) { ST_ERR("Bb table file not exit!\n"); return MI_ERR_LDC_ILLEGAL_PARAM; } else { if (statbuff.st_size == 0) { ST_ERR("File size is zero!\n"); return MI_ERR_LDC_ILLEGAL_PARAM; } u32Size = statbuff.st_size; } s32Fd = open(pConfigPath, O_RDONLY); if (s32Fd < 0) { ST_ERR("Open file[%d] error!\n", s32Fd); return MI_ERR_LDC_ILLEGAL_PARAM; } pBufData = (MI_U8 *)malloc(u32Size); if (!pBufData) { ST_ERR("Malloc error!\n"); close(s32Fd); return MI_ERR_LDC_ILLEGAL_PARAM; } memset(pBufData, 0, u32Size); read(s32Fd, pBufData, u32Size); close(s32Fd); *tldc_bin = pBufData; *pu32BinSize = u32Size; printf("%d: read buffer %p \n",__LINE__, pBufData); printf("%d: &bin address %p, *binbuffer %p \n",__LINE__, tldc_bin, *tldc_bin); //free(pBufData); return MI_SUCCESS; } MI_S32 ST_GetLdcCfgViewNum(mi_LDC_MODE eLdcMode) { MI_U32 u32ViewNum = 0; switch(eLdcMode) { case LDC_MODE_1R: case LDC_MODE_1P_CM: case LDC_MODE_1P_WM: case LDC_MODE_1O: case LDC_MODE_1R_WM: u32ViewNum = 1; break; case LDC_MODE_2P_CM: case LDC_MODE_2P_DM: u32ViewNum = 2; break; case LDC_MODE_4R_CM: case LDC_MODE_4R_WM: u32ViewNum = 4; break; default: printf("########### ldc mode %d err \n", eLdcMode); break; } printf("view num %d \n", u32ViewNum); return u32ViewNum; } MI_S32 ST_Parse_LibarayCfgFilePath(char *pLdcLibCfgPath, mi_eptz_config_param *ptconfig_para) { mi_eptz_err err_state = MI_EPTZ_ERR_NONE; printf("cfg file path %s\n", pLdcLibCfgPath); //check cfg file, in out path with bin position err_state = mi_eptz_config_parse(pLdcLibCfgPath, ptconfig_para); if (err_state != MI_EPTZ_ERR_NONE) { printf("confile file read error: %d\n", err_state); return err_state; } printf("ldc mode %d \n", ptconfig_para->ldc_mode); return 0; } MI_S32 ST_Libaray_CreatBin(MI_S32 s32ViewId, mi_eptz_config_param *ptconfig_para, LDC_BIN_HANDLE *ptldc_bin, MI_U32 *pu32LdcBinSize, MI_S32 s32Rot) { unsigned char* pWorkingBuffer; int working_buf_len = 0; mi_eptz_err err_state = MI_EPTZ_ERR_NONE; EPTZ_DEV_HANDLE eptz_handle = NULL; mi_eptz_para teptz_para; memset(&teptz_para, 0x0, sizeof(mi_eptz_para)); printf("view %d rot %d\n", s32ViewId, s32Rot); working_buf_len = mi_eptz_get_buffer_info(ptconfig_para); pWorkingBuffer = (unsigned char*)malloc(working_buf_len); if (pWorkingBuffer == NULL) { printf("buffer allocate error\n"); return MI_EPTZ_ERR_MEM_ALLOCATE_FAIL; } // printf("%s:%d working_buf_len %d \n", __FUNCTION__, __LINE__, working_buf_len); //EPTZ init teptz_para.ptconfig_para = ptconfig_para; //ldc configure // printf("%s:%d ptconfig_para %p, pWorkingBuffer %p, working_buf_len %d\n", __FUNCTION__, __LINE__, teptz_para.ptconfig_para, // pWorkingBuffer, working_buf_len); eptz_handle = mi_eptz_runtime_init(pWorkingBuffer, working_buf_len, &teptz_para); if (eptz_handle == NULL) { printf("EPTZ init error\n"); return MI_EPTZ_ERR_NOT_INIT; } teptz_para.pan = 0; teptz_para.tilt = -60; if(ptconfig_para->ldc_mode == 1) teptz_para.tilt = 60; teptz_para.rotate = s32Rot; teptz_para.zoom = 150.00; teptz_para.out_rot = 0; teptz_para.view_index = s32ViewId; //Gen bin files from 0 to 360 degree switch (ptconfig_para->ldc_mode) { case LDC_MODE_4R_CM: //LDC_MODE_4R_CM/Desk, if in desk mount mode, tilt is nagetive. teptz_para.view_index = s32ViewId; teptz_para.pan = 0; teptz_para.tilt = -50; //In CM mode, tilt is positive, but in desk mode, tilt is negative. teptz_para.rotate = s32Rot; teptz_para.zoom = 150; teptz_para.out_rot = 0; err_state = (mi_eptz_err)mi_eptz_runtime_map_gen(eptz_handle,(mi_eptz_para*)&teptz_para, ptldc_bin, (int *)pu32LdcBinSize); if (err_state != MI_EPTZ_ERR_NONE) { printf("[EPTZ ERR] = %d !! \n", err_state); } break; case LDC_MODE_4R_WM: //LDC_MODE_4R_WM teptz_para.view_index = s32ViewId; teptz_para.pan = 0; teptz_para.tilt = 50; //In CM mode, tilt is positive, but in desk mode, tilt is negative. teptz_para.rotate = s32Rot; teptz_para.zoom = 150; teptz_para.out_rot = 0; err_state = (mi_eptz_err)mi_eptz_runtime_map_gen(eptz_handle,(mi_eptz_para*)&teptz_para, ptldc_bin, (int *)pu32LdcBinSize); if (err_state != MI_EPTZ_ERR_NONE) { printf("[EPTZ ERR] = %d !! \n", err_state); } break; case LDC_MODE_1R: //LDC_MODE_1R CM/Desk, if in desk mount mode, tilt is negative. teptz_para.view_index = s32ViewId; teptz_para.pan = 0; teptz_para.tilt = 0; //In CM mode, tilt is positive, but in desk mode, tilt is negative. teptz_para.rotate = s32Rot; teptz_para.zoom = 150; teptz_para.out_rot = 0; err_state = (mi_eptz_err)mi_eptz_runtime_map_gen(eptz_handle,(mi_eptz_para*)&teptz_para, ptldc_bin, (int *)pu32LdcBinSize); if (err_state != MI_EPTZ_ERR_NONE) { printf("[EPTZ ERR] = %d !! \n", err_state); } break; case LDC_MODE_1R_WM: //LDC_MODE_1R WM teptz_para.view_index = s32ViewId; teptz_para.pan = 0; teptz_para.tilt = 50; //In CM mode, tilt is positive, but in desk mode, tilt is negative. teptz_para.rotate = s32Rot; teptz_para.zoom = 150; teptz_para.out_rot = 0; err_state = (mi_eptz_err)mi_eptz_runtime_map_gen(eptz_handle,(mi_eptz_para*)&teptz_para, ptldc_bin, (int *)pu32LdcBinSize); if (err_state != MI_EPTZ_ERR_NONE) { printf("[EPTZ ERR] = %d !! \n", err_state); } break; case LDC_MODE_2P_CM: //LDC_MODE_2P_CM case LDC_MODE_2P_DM: //LDC_MODE_2P_DM case LDC_MODE_1P_CM: //LDC_MODE_1P_CM //Set the input parameters for donut mode if(s32Rot > 180) { //Degree 180 ~ 360 teptz_para.view_index = s32ViewId; teptz_para.r_inside = 550; teptz_para.r_outside = 10; teptz_para.theta_start = s32Rot; teptz_para.theta_end = s32Rot+360; } else { //Degree 180 ~ 0 teptz_para.view_index = s32ViewId; teptz_para.r_inside = 10; teptz_para.r_outside = 550; teptz_para.theta_start = s32Rot; teptz_para.theta_end = s32Rot+360; } err_state = (mi_eptz_err)mi_donut_runtime_map_gen(eptz_handle, (mi_eptz_para*)&teptz_para, ptldc_bin, (int *)pu32LdcBinSize); if (err_state != MI_EPTZ_ERR_NONE) { printf("[EPTZ ERR] = %d !! \n", err_state); } break; case LDC_MODE_1P_WM: //LDC_MODE_1P wall mount. teptz_para.view_index = s32ViewId; teptz_para.pan = 0; teptz_para.tilt = 0; teptz_para.zoom_h = 100; teptz_para.zoom_v = 100; err_state = (mi_eptz_err)mi_erp_runtime_map_gen(eptz_handle,(mi_eptz_para*)&teptz_para, ptldc_bin, (int *)pu32LdcBinSize); if (err_state != MI_EPTZ_ERR_NONE) { printf("[EPTZ ERR] = %d !! \n", err_state); } break; case LDC_MODE_1O: //bypass mode teptz_para.view_index = 0; //view index printf("begin mi_bypass_runtime_map_gen \n"); err_state = (mi_eptz_err)mi_bypass_runtime_map_gen(eptz_handle, (mi_eptz_para*)&teptz_para, ptldc_bin, (int *)pu32LdcBinSize); if (err_state != MI_EPTZ_ERR_NONE) { printf("[MODE %d ERR] = %d !! \n", LDC_MODE_1O, err_state); return err_state; } printf("end mi_bypass_runtime_map_gen\n"); break; default : printf("********************err ldc mode %d \n", ptconfig_para->ldc_mode); return 0; } #if 0 FILE *fp = NULL; fp = fopen("/mnt/ldc.bin","wb"); fwrite(ptldc_bin, *pu32LdcBinSize, 1, fp); fclose(fp); #endif //Free bin buffer /* err_state = mi_eptz_buffer_free((LDC_BIN_HANDLE)tldc_bin); if (err_state != MI_EPTZ_ERR_NONE) { printf("[MI EPTZ ERR] = %d !! \n", err_state); }*/ //release working buffer free(pWorkingBuffer); return 0; } MI_S32 ST_GetLdcBinBuffer(MI_S32 s32Cfg_Param, char *pCfgFilePath, mi_eptz_config_param *ptconfig_para, MI_U32 *pu32ViewNum, LDC_BIN_HANDLE *ptldc_bin, MI_U32 *pu32LdcBinSize, MI_S32 *ps32Rot) { MI_U8 i =0; MI_U32 u32ViewNum = 0; if(s32Cfg_Param == 0) { ST_Parse_LibarayCfgFilePath(pCfgFilePath, ptconfig_para); u32ViewNum = ST_GetLdcCfgViewNum(ptconfig_para->ldc_mode); for(i=0; i<u32ViewNum; i++) { ST_Libaray_CreatBin(i, ptconfig_para, &ptldc_bin[i], &pu32LdcBinSize[i], ps32Rot[i]); } *pu32ViewNum = u32ViewNum; } else { ST_ReadLdcTableBin(pCfgFilePath, ptldc_bin, pu32LdcBinSize); *pu32ViewNum = 1; } return 0; } MI_S32 ST_SetLdcOnOff(MI_U32 u32SensorNum) { MI_S32 s32LdcOnoff = 0; MI_VPE_ChannelPara_t stVpeChnParam; memset(&stVpeChnParam, 0x0, sizeof(MI_VPE_ChannelPara_t)); MI_S32 s32Channelid = 0; if(u32SensorNum > 1) { printf("select channel id:"); scanf("%d", &s32Channelid); ST_Flush(); if(s32Channelid >= ST_MAX_SENSOR_NUM) { printf("chnid %d > max %d \n", s32Channelid, ST_MAX_SENSOR_NUM); return 0; } } else { s32Channelid = 0; } ST_VpeChannelAttr_t *pstVpeChnattr = &gstVpeChnattr[s32Channelid]; printf("Set Ldc ON(1), OFF(0): \n"); scanf("%d", &s32LdcOnoff); ST_Flush(); if(s32LdcOnoff == TRUE && pstVpeChnattr->bEnLdc == FALSE) { printf("ldc onoff %d, before enldc %d need set bin path \n", s32LdcOnoff, pstVpeChnattr->bEnLdc); printf("set Ldc libaray cfg path: "); scanf("%s", pstVpeChnattr->LdcCfgbin_Path); ST_Flush(); ST_ReadLdcTableBin(pstVpeChnattr->LdcCfgbin_Path, &pstVpeChnattr->ldcBinBuffer[0], &pstVpeChnattr->u32LdcBinSize[0]); } MI_VPE_StopChannel(s32Channelid); MI_VPE_GetChannelParam(s32Channelid, &stVpeChnParam); printf("get channel param benldc %d, bmirror %d, bflip %d, e3dnrlevel %d, hdrtype %d \n", stVpeChnParam.bEnLdc, stVpeChnParam.bMirror,stVpeChnParam.bFlip,stVpeChnParam.e3DNRLevel,stVpeChnParam.eHDRType); stVpeChnParam.bEnLdc = s32LdcOnoff; MI_VPE_SetChannelParam(s32Channelid, &stVpeChnParam); if(s32LdcOnoff == TRUE && pstVpeChnattr->bEnLdc == FALSE) { MI_VPE_LDCBegViewConfig(s32Channelid); MI_VPE_LDCSetViewConfig(s32Channelid, pstVpeChnattr->ldcBinBuffer[0], pstVpeChnattr->u32LdcBinSize[0]); MI_VPE_LDCEndViewConfig(s32Channelid); //free(pstVpeChnattr->ldcBinBuffer); if(mi_eptz_buffer_free(pstVpeChnattr->ldcBinBuffer[0]) != MI_EPTZ_ERR_NONE) { printf("[MI EPTZ ERR] %d !! \n", __LINE__); } pstVpeChnattr->bEnLdc = TRUE; } MI_VPE_StartChannel(s32Channelid); return 0; } void * ST_GetVpeOutputDataThread(void * args) { MI_SYS_BufInfo_t stBufInfo; MI_SYS_BUF_HANDLE hHandle; MI_U8 u8Params = *((MI_U8 *)(args)); MI_U8 u8Chnid = u8Params / ST_MAX_PORT_NUM; MI_U8 u8Portid = u8Params % ST_MAX_PORT_NUM; FILE *fp = NULL; ST_VpePortAttr_t *pstVpePortAttr = &gstVpeChnattr[u8Chnid].stVpePortAttr[u8Portid]; MI_BOOL bFileOpen = FALSE; MI_SYS_ChnPort_t stChnPort; memset(&stChnPort, 0x0, sizeof(MI_SYS_ChnPort_t)); stChnPort.eModId = E_MI_MODULE_ID_VPE; stChnPort.u32DevId = 0; stChnPort.u32ChnId = u8Chnid; stChnPort.u32PortId = u8Portid; if(pstVpePortAttr->bUsed == TRUE) { MI_SYS_SetChnOutputPortDepth(&stChnPort, 1, 4); } while (!bExit) { pthread_mutex_lock(&pstVpePortAttr->Portmutex); if(pstVpePortAttr->s32DumpBuffNum > 0 && bFileOpen == FALSE) { fp = fopen(pstVpePortAttr->FilePath ,"wb"); if(fp == NULL) { printf("file %s open fail\n", pstVpePortAttr->FilePath); pstVpePortAttr->s32DumpBuffNum = 0;\ pthread_mutex_unlock(&pstVpePortAttr->Portmutex); continue; } else { bFileOpen = TRUE; } } if(pstVpePortAttr->bUsed == TRUE) { if (MI_SUCCESS == MI_SYS_ChnOutputPortGetBuf(&stChnPort, &stBufInfo, &hHandle)) { //printf("get out success \n"); if(pstVpePortAttr->s32DumpBuffNum > 0) { pstVpePortAttr->s32DumpBuffNum--; printf( "=======begin writ port %d file id %d, file path %s, bufsize %d, stride %d, height %d\n", u8Portid, pstVpePortAttr->s32DumpBuffNum, pstVpePortAttr->FilePath, stBufInfo.stFrameData.u32BufSize,stBufInfo.stFrameData.u32Stride[0], stBufInfo.stFrameData.u16Height); fwrite(stBufInfo.stFrameData.pVirAddr[0], stBufInfo.stFrameData.u32BufSize, 1, fp); printf( "=======end writ port %d file id %d, file path %s \n", u8Portid, pstVpePortAttr->s32DumpBuffNum, pstVpePortAttr->FilePath); } //printf("begin release out \n"); MI_SYS_ChnOutputPortPutBuf(hHandle); //printf("end release out \n"); } } if(bFileOpen == TRUE && pstVpePortAttr->s32DumpBuffNum == 0) { fclose(fp); bFileOpen = FALSE; } pthread_mutex_unlock(&pstVpePortAttr->Portmutex); usleep(10*1000); } return NULL; } void *ST_IQthread(void * args) { MI_VIF_ChnPortAttr_t stVifAttr; MI_VPE_ChannelPara_t stVpeParam; MI_VPE_HDRType_e eLastHdrType = E_MI_VPE_HDR_TYPE_MAX; MI_ISP_IQ_PARAM_INIT_INFO_TYPE_t status; MI_U8 u8ispreadycnt = 0; memset(&stVifAttr, 0x0, sizeof(MI_VIF_ChnPortAttr_t)); memset(&stVpeParam, 0x0, sizeof(MI_VPE_ChannelPara_t)); MI_IQSERVER_Open(1920, 1080, 0); while(1) { if(u8ispreadycnt > 100) { printf("%s:%d, isp ready time out \n", __FUNCTION__, __LINE__); u8ispreadycnt = 0; } MI_ISP_IQ_GetParaInitStatus(0, &status); if(status.stParaAPI.bFlag != 1) { usleep(10*1000); u8ispreadycnt++; continue; } u8ispreadycnt = 0; MI_VPE_GetChannelParam(0, &stVpeParam); if(eLastHdrType != stVpeParam.eHDRType) { printf("hdr type change before %d, current %d, load api bin\n", eLastHdrType, stVpeParam.eHDRType); MI_ISP_API_CmdLoadBinFile(0, (char *)((stVpeParam.eHDRType>0) ? HDR_PATH : NONHDR_PATH), 1234); } eLastHdrType = stVpeParam.eHDRType; usleep(10*1000); } return NULL; } void *ST_SendVpeBufthread(void * args) { MI_SYS_ChnPort_t stVpeChnInput; MI_SYS_BUF_HANDLE hHandle = 0; MI_SYS_BufConf_t stBufConf; MI_SYS_BufInfo_t stBufInfo; struct timeval stTv; MI_U16 u16Width = 1920, u16Height = 1080; FILE *fp = NULL; memset(&stVpeChnInput, 0x0, sizeof(MI_SYS_ChnPort_t)); memset(&stBufConf, 0x0, sizeof(MI_SYS_BufConf_t)); memset(&stBufInfo, 0x0, sizeof(MI_SYS_BufInfo_t)); stVpeChnInput.eModId = E_MI_MODULE_ID_VPE; stVpeChnInput.u32DevId = 0; stVpeChnInput.u32ChnId = 0; stVpeChnInput.u32PortId = 0; fp = fopen("/mnt/vpeport0_1920x1080_pixel0_737.raw","rb"); if(fp == NULL) { printf("file %s open fail\n", "/mnt/vpeport0_1920x1080_pixel0_737.raw"); return 0; } while(1) { stBufConf.eBufType = E_MI_SYS_BUFDATA_FRAME; gettimeofday(&stTv, NULL); stBufConf.u64TargetPts = stTv.tv_sec*1000000 + stTv.tv_usec; stBufConf.stFrameCfg.eFormat = E_MI_SYS_PIXEL_FRAME_YUV422_YUYV; stBufConf.stFrameCfg.eFrameScanMode = E_MI_SYS_FRAME_SCAN_MODE_PROGRESSIVE; stBufConf.stFrameCfg.u16Width = u16Width; stBufConf.stFrameCfg.u16Height = u16Height; if(MI_SUCCESS == MI_SYS_ChnInputPortGetBuf(&stVpeChnInput,&stBufConf,&stBufInfo,&hHandle,0)) { if(fread(stBufInfo.stFrameData.pVirAddr[0], u16Width*u16Height*2, 1, fp) <= 0) { fseek(fp, 0, SEEK_SET); } MI_SYS_ChnInputPortPutBuf(hHandle,&stBufInfo, FALSE); } } } MI_S32 ST_BaseModuleInit(MI_SNR_PAD_ID_e eSnrPad) { MI_U32 u32CapWidth = 0, u32CapHeight = 0; MI_VIF_FrameRate_e eFrameRate = E_MI_VIF_FRAMERATE_FULL; MI_SYS_PixelFormat_e ePixFormat; MI_SNR_PADInfo_t stPad0Info; MI_SNR_PlaneInfo_t stSnrPlane0Info; MI_SNR_PAD_ID_e eSnrPadId = eSnrPad; MI_VIF_DEV vifDev = gstSensorAttr[eSnrPad].u32BindVifDev; MI_VIF_CHN vifChn = vifDev*4; MI_VPE_CHANNEL vpechn = gstVifAttr[vifDev].u32BindVpeChan; ST_VpeChannelAttr_t *pstVpeChnattr = &gstVpeChnattr[vpechn]; ST_Vif_Attr_t *pstVifDevAttr = &gstVifAttr[vifDev]; MI_U8 i=0; memset(&stPad0Info, 0x0, sizeof(MI_SNR_PADInfo_t)); if(E_MI_VPE_HDR_TYPE_OFF== pstVpeChnattr->eHdrType || E_MI_VPE_HDR_TYPE_EMBEDDED == pstVpeChnattr->eHdrType || E_MI_VPE_HDR_TYPE_LI== pstVpeChnattr->eHdrType) { MI_SNR_SetPlaneMode(eSnrPad, FALSE); } else { MI_SNR_SetPlaneMode(eSnrPad, TRUE); } MI_U32 u32ResCount =0; MI_U8 u8ResIndex =0; MI_SNR_Res_t stRes; MI_U8 u8ChocieRes =0; MI_S32 s32Input =0; memset(&stRes, 0x0, sizeof(MI_SNR_Res_t)); MI_SNR_QueryResCount(eSnrPadId, &u32ResCount); for(u8ResIndex=0; u8ResIndex < u32ResCount; u8ResIndex++) { MI_SNR_GetRes(eSnrPadId, u8ResIndex, &stRes); printf("index %d, Crop(%d,%d,%d,%d), outputsize(%d,%d), maxfps %d, minfps %d, ResDesc %s\n", u8ResIndex, stRes.stCropRect.u16X, stRes.stCropRect.u16Y, stRes.stCropRect.u16Width,stRes.stCropRect.u16Height, stRes.stOutputSize.u16Width, stRes.stOutputSize.u16Height, stRes.u32MaxFps,stRes.u32MinFps, stRes.strResDesc); } printf("choice which resolution use, cnt %d\n", u32ResCount); do { scanf("%d", &s32Input); u8ChocieRes = (MI_U8)s32Input; ST_Flush(); MI_SNR_QueryResCount(eSnrPadId, &u32ResCount); if(u8ChocieRes >= u32ResCount) { printf("choice err res %d > =cnt %d\n", u8ChocieRes, u32ResCount); } }while(u8ChocieRes >= u32ResCount); printf("You select %d res\n", u8ChocieRes); MI_SNR_SetRes(eSnrPadId,u8ChocieRes); MI_SNR_Enable(eSnrPadId); MI_SNR_GetPadInfo(eSnrPadId, &stPad0Info); MI_SNR_GetPlaneInfo(eSnrPadId, 0, &stSnrPlane0Info); u32CapWidth = stSnrPlane0Info.stCapRect.u16Width; u32CapHeight = stSnrPlane0Info.stCapRect.u16Height; eFrameRate = E_MI_VIF_FRAMERATE_FULL; ePixFormat = (MI_SYS_PixelFormat_e)RGB_BAYER_PIXEL(stSnrPlane0Info.ePixPrecision, stSnrPlane0Info.eBayerId);; /************************************************ Step1: init SYS *************************************************/ STCHECKRESULT(ST_Sys_Init()); /* stSnrPlane0Info.stCapRect.u16X = 0; stSnrPlane0Info.stCapRect.u16Y = 0; stSnrPlane0Info.stCapRect.u16Width = 1920; stSnrPlane0Info.stCapRect.u16Height = 1080; ePixFormat = E_MI_SYS_PIXEL_FRAME_YUV422_YUYV; pstVifDevAttr->eWorkMode = E_MI_VIF_WORK_MODE_RGB_FRAMEMODE; pstVpeChnattr->eRunningMode = E_MI_VPE_RUN_DVR_MODE; */ /************************************************ Step2: init VIF(for IPC, only one dev) *************************************************/ MI_VIF_DevAttr_t stDevAttr; memset(&stDevAttr, 0x0, sizeof(MI_VIF_DevAttr_t)); stDevAttr.eIntfMode = stPad0Info.eIntfMode; stDevAttr.eWorkMode = pstVifDevAttr->eWorkMode; stDevAttr.eHDRType = (MI_VIF_HDRType_e)pstVpeChnattr->eHdrType; if(stDevAttr.eIntfMode == E_MI_VIF_MODE_BT656) stDevAttr.eClkEdge = stPad0Info.unIntfAttr.stBt656Attr.eClkEdge; else stDevAttr.eClkEdge = E_MI_VIF_CLK_EDGE_DOUBLE; if(stDevAttr.eIntfMode == E_MI_VIF_MODE_MIPI) stDevAttr.eDataSeq =stPad0Info.unIntfAttr.stMipiAttr.eDataYUVOrder; else stDevAttr.eDataSeq = E_MI_VIF_INPUT_DATA_YUYV; if(stDevAttr.eIntfMode == E_MI_VIF_MODE_BT656) memcpy(&stDevAttr.stSyncAttr, &stPad0Info.unIntfAttr.stBt656Attr.stSyncAttr, sizeof(MI_VIF_SyncAttr_t)); stDevAttr.eBitOrder = E_MI_VIF_BITORDER_NORMAL; ExecFunc(MI_VIF_SetDevAttr(vifDev, &stDevAttr), MI_SUCCESS); ExecFunc(MI_VIF_EnableDev(vifDev), MI_SUCCESS); ST_VIF_PortInfo_T stVifPortInfoInfo; memset(&stVifPortInfoInfo, 0, sizeof(ST_VIF_PortInfo_T)); stVifPortInfoInfo.u32RectX = stSnrPlane0Info.stCapRect.u16X; stVifPortInfoInfo.u32RectY = stSnrPlane0Info.stCapRect.u16Y; stVifPortInfoInfo.u32RectWidth = u32CapWidth; stVifPortInfoInfo.u32RectHeight = u32CapHeight; stVifPortInfoInfo.u32DestWidth = u32CapWidth; stVifPortInfoInfo.u32DestHeight = u32CapHeight; stVifPortInfoInfo.eFrameRate = eFrameRate; stVifPortInfoInfo.ePixFormat = ePixFormat; STCHECKRESULT(ST_Vif_CreatePort(vifChn, 0, &stVifPortInfoInfo)); STCHECKRESULT(ST_Vif_StartPort(0, vifChn, 0)); /************************************************ Step3: init VPE (create one VPE) *************************************************/ MI_VPE_ChannelAttr_t stChannelVpeAttr; MI_VPE_ChannelPara_t stChannelVpeParam; memset(&stChannelVpeAttr, 0, sizeof(MI_VPE_ChannelAttr_t)); memset(&stChannelVpeParam, 0x00, sizeof(MI_VPE_ChannelPara_t)); stChannelVpeParam.eHDRType = pstVpeChnattr->eHdrType; stChannelVpeParam.e3DNRLevel = pstVpeChnattr->e3DNRLevel; stChannelVpeParam.bMirror = pstVpeChnattr->bChnMirror; stChannelVpeParam.bFlip = pstVpeChnattr->bChnFlip; MI_VPE_SetChannelParam(vpechn, &stChannelVpeParam); stChannelVpeAttr.u16MaxW = u32CapWidth; stChannelVpeAttr.u16MaxH = u32CapHeight; stChannelVpeAttr.ePixFmt = ePixFormat; stChannelVpeAttr.eRunningMode = pstVpeChnattr->eRunningMode; stChannelVpeAttr.eSensorBindId = (MI_VPE_SensorChannel_e)(eSnrPadId+1); stChannelVpeAttr.bEnLdc = pstVpeChnattr->bEnLdc; stChannelVpeAttr.u32ChnPortMode = pstVpeChnattr->u32ChnPortMode; stChannelVpeAttr.eHDRType = pstVpeChnattr->eHdrType; ExecFunc(MI_VPE_CreateChannel(vpechn, &stChannelVpeAttr), MI_VPE_OK); if(pstVpeChnattr->bEnLdc == TRUE && pstVpeChnattr->ldcBinBuffer[0] != NULL) { MI_VPE_LDCBegViewConfig(vpechn); for(i=0; i<pstVpeChnattr->u32ViewNum; i++) { MI_VPE_LDCSetViewConfig(vpechn, pstVpeChnattr->ldcBinBuffer[i], pstVpeChnattr->u32LdcBinSize[i]); //free(pstVpeChnattr->ldcBinBuffer); if(mi_eptz_buffer_free(pstVpeChnattr->ldcBinBuffer[i]) != MI_EPTZ_ERR_NONE) { printf("[MI EPTZ ERR] %d !! \n", __LINE__); } } MI_VPE_LDCEndViewConfig(vpechn); } else printf("##############benldc %d, ldc bin buffer %p \n",pstVpeChnattr->bEnLdc, pstVpeChnattr->ldcBinBuffer); STCHECKRESULT(MI_VPE_SetChannelRotation(vpechn, pstVpeChnattr->eVpeRotate)); STCHECKRESULT(MI_VPE_SetChannelCrop(vpechn, &pstVpeChnattr->stVpeChnCrop)); STCHECKRESULT(ST_Vpe_StartChannel(vpechn)); for(i=0; i<ST_MAX_PORT_NUM; i++) { MI_VPE_PortMode_t stVpeMode; memset(&stVpeMode, 0, sizeof(stVpeMode)); if(pstVpeChnattr->stVpePortAttr[i].bUsed == TRUE) { MI_VPE_SetPortCrop(vpechn, i, &pstVpeChnattr->stVpePortAttr[i].stPortCrop); stVpeMode.u16Width = pstVpeChnattr->stVpePortAttr[i].stPortSize.u16Width; stVpeMode.u16Height = pstVpeChnattr->stVpePortAttr[i].stPortSize.u16Height; stVpeMode.ePixelFormat = pstVpeChnattr->stVpePortAttr[i].ePixelFormat; stVpeMode.eCompressMode = E_MI_SYS_COMPRESS_MODE_NONE; stVpeMode.bMirror =pstVpeChnattr->stVpePortAttr[i].bMirror; stVpeMode.bFlip = pstVpeChnattr->stVpePortAttr[i].bFlip; ExecFunc(MI_VPE_SetPortMode(vpechn, i, &stVpeMode), MI_VPE_OK); ExecFunc(MI_VPE_EnablePort(vpechn, i), MI_VPE_OK); } } /************************************************ Step1: bind VIF->VPE *************************************************/ ST_Sys_BindInfo_T stBindInfo; memset(&stBindInfo, 0x0, sizeof(ST_Sys_BindInfo_T)); stBindInfo.stSrcChnPort.eModId = E_MI_MODULE_ID_VIF; stBindInfo.stSrcChnPort.u32DevId = vifDev; stBindInfo.stSrcChnPort.u32ChnId = vifChn; stBindInfo.stSrcChnPort.u32PortId = 0; stBindInfo.stDstChnPort.eModId = E_MI_MODULE_ID_VPE; stBindInfo.stDstChnPort.u32DevId = 0; stBindInfo.stDstChnPort.u32ChnId = vpechn; stBindInfo.stDstChnPort.u32PortId = 0; stBindInfo.u32SrcFrmrate = 30; stBindInfo.u32DstFrmrate = 30; stBindInfo.eBindType = pstVifDevAttr->eBindType; STCHECKRESULT(ST_Sys_Bind(&stBindInfo)); return MI_SUCCESS; } MI_S32 ST_BaseModuleUnInit(MI_SNR_PAD_ID_e eSnrPad) { MI_VIF_DEV vifDev = gstSensorAttr[eSnrPad].u32BindVifDev; MI_VIF_CHN vifChn = vifDev*4; MI_VPE_CHANNEL vpechn = gstVifAttr[vifDev].u32BindVpeChan; ST_VpeChannelAttr_t *pstVpeChnattr = &gstVpeChnattr[vpechn]; MI_U32 i = 0; ST_Sys_BindInfo_T stBindInfo; memset(&stBindInfo, 0x0, sizeof(ST_Sys_BindInfo_T)); stBindInfo.stSrcChnPort.eModId = E_MI_MODULE_ID_VIF; stBindInfo.stSrcChnPort.u32DevId = vifDev; stBindInfo.stSrcChnPort.u32ChnId = vifChn; stBindInfo.stSrcChnPort.u32PortId = 0; stBindInfo.stDstChnPort.eModId = E_MI_MODULE_ID_VPE; stBindInfo.stDstChnPort.u32DevId = 0; stBindInfo.stDstChnPort.u32ChnId = vpechn; stBindInfo.stDstChnPort.u32PortId = 0; stBindInfo.u32SrcFrmrate = 30; stBindInfo.u32DstFrmrate = 30; STCHECKRESULT(ST_Sys_UnBind(&stBindInfo)); for(i = 0; i < ST_MAX_PORT_NUM; i ++) { if(pstVpeChnattr->stVpePortAttr[i].bUsed == TRUE) { STCHECKRESULT(ST_Vpe_StopPort(vpechn, i)); } } /************************************************ Step2: destory VPE *************************************************/ STCHECKRESULT(ST_Vpe_StopChannel(vpechn)); STCHECKRESULT(ST_Vpe_DestroyChannel(vpechn)); /************************************************ Step3: destory VIF *************************************************/ STCHECKRESULT(ST_Vif_StopPort(vifChn, 0)); STCHECKRESULT(ST_Vif_DisableDev(vifDev)); MI_SNR_Disable(eSnrPad); /************************************************ Step4: destory SYS *************************************************/ STCHECKRESULT(ST_Sys_Exit()); return MI_SUCCESS; } MI_S32 ST_VencStart(MI_U32 u32MaxVencWidth, MI_U32 u32MaxVencHeight, MI_U32 u32VpeChn) { MI_U32 u32VenBitRate = 0; MI_U32 i = 0; ST_Sys_BindInfo_T stBindInfo; MI_U32 u32DevId = -1; MI_VENC_ChnAttr_t stChnAttr; for(i = 0; i < ST_MAX_PORT_NUM; i ++) { MI_U32 u32VencChn = gstVpeChnattr[u32VpeChn].stVpePortAttr[i].u32BindVencChan; ST_VencAttr_t *pstStreamAttr = &gstVencattr[u32VencChn]; memset(&stChnAttr, 0, sizeof(MI_VENC_ChnAttr_t)); if(pstStreamAttr->bUsed != TRUE) continue; u32VenBitRate = ((pstStreamAttr->u32Width * pstStreamAttr->u32Height + 500000)/1000000)*1024*1024; DBG_INFO("chn %d, pichwidth %d, height %d, MaxWidth %d, MaxHeight %d \n", u32VencChn, pstStreamAttr->u32Width, pstStreamAttr->u32Height, u32MaxVencWidth, u32MaxVencHeight); if(pstStreamAttr->eType == E_MI_VENC_MODTYPE_H264E) { stChnAttr.stVeAttr.stAttrH264e.u32PicWidth = pstStreamAttr->u32Width; stChnAttr.stVeAttr.stAttrH264e.u32PicHeight = pstStreamAttr->u32Height; stChnAttr.stVeAttr.stAttrH264e.u32MaxPicWidth = u32MaxVencWidth; stChnAttr.stVeAttr.stAttrH264e.u32BFrameNum = 2; stChnAttr.stVeAttr.stAttrH264e.bByFrame = TRUE; stChnAttr.stVeAttr.stAttrH264e.u32MaxPicHeight = u32MaxVencHeight; stChnAttr.stRcAttr.eRcMode = E_MI_VENC_RC_MODE_H264CBR; stChnAttr.stRcAttr.stAttrH264Cbr.u32BitRate = u32VenBitRate; stChnAttr.stRcAttr.stAttrH264Cbr.u32FluctuateLevel = 0; stChnAttr.stRcAttr.stAttrH264Cbr.u32Gop = 30; stChnAttr.stRcAttr.stAttrH264Cbr.u32SrcFrmRateNum = 30; stChnAttr.stRcAttr.stAttrH264Cbr.u32SrcFrmRateDen = 1; stChnAttr.stRcAttr.stAttrH264Cbr.u32StatTime = 0; } else if(pstStreamAttr->eType == E_MI_VENC_MODTYPE_H265E) { stChnAttr.stVeAttr.stAttrH265e.u32PicWidth = pstStreamAttr->u32Width; stChnAttr.stVeAttr.stAttrH265e.u32PicHeight = pstStreamAttr->u32Height; stChnAttr.stVeAttr.stAttrH265e.u32MaxPicWidth = u32MaxVencWidth; stChnAttr.stVeAttr.stAttrH265e.u32MaxPicHeight = u32MaxVencHeight; stChnAttr.stVeAttr.stAttrH265e.bByFrame = TRUE; stChnAttr.stRcAttr.eRcMode = E_MI_VENC_RC_MODE_H265CBR; stChnAttr.stRcAttr.stAttrH265Cbr.u32BitRate = u32VenBitRate; stChnAttr.stRcAttr.stAttrH265Cbr.u32SrcFrmRateNum = 30; stChnAttr.stRcAttr.stAttrH265Cbr.u32SrcFrmRateDen = 1; stChnAttr.stRcAttr.stAttrH265Cbr.u32Gop = 30; stChnAttr.stRcAttr.stAttrH265Cbr.u32FluctuateLevel = 0; stChnAttr.stRcAttr.stAttrH265Cbr.u32StatTime = 0; } else if(pstStreamAttr->eType == E_MI_VENC_MODTYPE_JPEGE) { stChnAttr.stVeAttr.eType = E_MI_VENC_MODTYPE_JPEGE; stChnAttr.stRcAttr.eRcMode = E_MI_VENC_RC_MODE_MJPEGFIXQP; stChnAttr.stVeAttr.stAttrJpeg.u32PicWidth = pstStreamAttr->u32Width; stChnAttr.stVeAttr.stAttrJpeg.u32PicHeight = pstStreamAttr->u32Height; stChnAttr.stVeAttr.stAttrJpeg.u32MaxPicWidth = u32MaxVencWidth; stChnAttr.stVeAttr.stAttrJpeg.u32MaxPicHeight = u32MaxVencHeight; } stChnAttr.stVeAttr.eType = pstStreamAttr->eType; u32VencChn = pstStreamAttr->vencChn; STCHECKRESULT(ST_Venc_CreateChannel(u32VencChn, &stChnAttr)); ExecFunc(MI_VENC_GetChnDevid(u32VencChn, &u32DevId), MI_SUCCESS); memset(&stBindInfo, 0x0, sizeof(ST_Sys_BindInfo_T)); stBindInfo.stSrcChnPort.eModId = E_MI_MODULE_ID_VPE; stBindInfo.stSrcChnPort.u32DevId = 0; stBindInfo.stSrcChnPort.u32ChnId = pstStreamAttr->u32BindVpeChn; stBindInfo.stSrcChnPort.u32PortId = pstStreamAttr->u32BindVpePort; stBindInfo.stDstChnPort.eModId = E_MI_MODULE_ID_VENC; stBindInfo.stDstChnPort.u32DevId = u32DevId; stBindInfo.stDstChnPort.u32ChnId = u32VencChn; stBindInfo.stDstChnPort.u32PortId = 0; stBindInfo.u32SrcFrmrate = 30; stBindInfo.u32DstFrmrate = 30; stBindInfo.eBindType = pstStreamAttr->eBindType; stBindInfo.u32BindParam = pstStreamAttr->u32BindParam; STCHECKRESULT(ST_Sys_Bind(&stBindInfo)); STCHECKRESULT(ST_Venc_StartChannel(u32VencChn)); pstStreamAttr->bStart = TRUE; } return MI_SUCCESS; } MI_S32 ST_VencStop(MI_U32 u32VpeChn) { MI_U32 i = 0; ST_Sys_BindInfo_T stBindInfo; MI_VENC_CHN VencChn = 0; MI_U32 u32DevId = -1; for(i = 0; i < ST_MAX_PORT_NUM; i ++) { MI_U32 u32VencChn = gstVpeChnattr[u32VpeChn].stVpePortAttr[i].u32BindVencChan; ST_VencAttr_t *pstStreamAttr = &gstVencattr[u32VencChn]; if(pstStreamAttr->bUsed != TRUE) continue; VencChn = pstStreamAttr->vencChn; ExecFunc(MI_VENC_GetChnDevid(VencChn, &u32DevId), MI_SUCCESS); memset(&stBindInfo, 0x0, sizeof(ST_Sys_BindInfo_T)); stBindInfo.stSrcChnPort.eModId = E_MI_MODULE_ID_VPE; stBindInfo.stSrcChnPort.u32DevId = 0; stBindInfo.stSrcChnPort.u32ChnId = pstStreamAttr->u32BindVpeChn; stBindInfo.stSrcChnPort.u32PortId = pstStreamAttr->u32BindVpePort; stBindInfo.stDstChnPort.eModId = E_MI_MODULE_ID_VENC; stBindInfo.stDstChnPort.u32DevId = u32DevId; stBindInfo.stDstChnPort.u32ChnId = VencChn; stBindInfo.stDstChnPort.u32PortId = 0; stBindInfo.u32SrcFrmrate = 30; stBindInfo.u32DstFrmrate = 30; STCHECKRESULT(ST_Sys_UnBind(&stBindInfo)); STCHECKRESULT(ST_Venc_StopChannel(VencChn)); STCHECKRESULT(ST_Venc_DestoryChannel(VencChn)); pstStreamAttr->bStart = FALSE; } return MI_SUCCESS; } void ST_SetArgs(MI_U32 u32SensorId) { MI_S32 s32HDRtype = 0; MI_S32 s323DNRLevel = 0; MI_S32 s32Rotation = 0; MI_S32 s32ChannelCropX =0, s32ChannelCropY=0,s32ChannelCropW=0,s32ChannelCropH =0; MI_S32 s32bEnLdc =0; MI_S32 s32ChnPortMode = 0, s32PortSelect =0; MI_U8 i=0; MI_U32 u32VifDev = gstSensorAttr[u32SensorId].u32BindVifDev; MI_U32 u32VpeChn = gstVifAttr[u32VifDev].u32BindVpeChan; DBG_INFO("set vpe channelid %d \n", u32VpeChn); ST_VpeChannelAttr_t *pstVpeChnattr = &gstVpeChnattr[u32VpeChn]; printf("preview by venc ?(0: write file, 1:preview use rtsp)\n"); scanf("%d", &gbPreviewByVenc); ST_Flush(); printf("Use HDR ?\n 0 not use, 1 use VC, 2 use DOL, 3 use EMBEDDED, 4 use LI\n"); printf("sony sensor(ex imx307) use DOL, sc sensor(ex sc4238) use VC\n"); scanf("%d", &s32HDRtype); ST_Flush(); printf("3dnr level(0~2):"); scanf("%d", &s323DNRLevel); ST_Flush(); printf("rotation(0:0, 1:90, 2:180, 3:270, 4:mirror, 5:flip):"); scanf("%d", &s32Rotation); ST_Flush(); printf("Channel Crop x:"); scanf("%d", &s32ChannelCropX); ST_Flush(); printf("Channel Crop y:"); scanf("%d", &s32ChannelCropY); ST_Flush(); printf("Channel Crop width:"); scanf("%d", &s32ChannelCropW); ST_Flush(); printf("Channel Crop height:"); scanf("%d", &s32ChannelCropH); ST_Flush(); printf("bEnLdc:"); scanf("%d", &s32bEnLdc); ST_Flush(); if(s32bEnLdc == TRUE) { printf("set Ldc libaray cfg path: "); scanf("%s", pstVpeChnattr->LdcCfgbin_Path); ST_Flush(); } pstVpeChnattr->e3DNRLevel = (MI_VPE_3DNR_Level_e)s323DNRLevel; pstVpeChnattr->eHdrType = (MI_VPE_HDRType_e)s32HDRtype; if(s32Rotation < 4) pstVpeChnattr->eVpeRotate = (MI_SYS_Rotate_e)s32Rotation; else if(s32Rotation == 4) { pstVpeChnattr->bChnMirror = TRUE; pstVpeChnattr->bChnFlip = FALSE; } else if(s32Rotation == 5) { pstVpeChnattr->bChnMirror = FALSE; pstVpeChnattr->bChnFlip = TRUE; } pstVpeChnattr->stOrgVpeChnCrop.u16X = s32ChannelCropX; pstVpeChnattr->stOrgVpeChnCrop.u16Y = s32ChannelCropY; pstVpeChnattr->stOrgVpeChnCrop.u16Width = s32ChannelCropW; pstVpeChnattr->stOrgVpeChnCrop.u16Height = s32ChannelCropH; pstVpeChnattr->bEnLdc = s32bEnLdc; if(pstVpeChnattr->eVpeRotate == E_MI_SYS_ROTATE_90 || pstVpeChnattr->eVpeRotate == E_MI_SYS_ROTATE_270) { pstVpeChnattr->stVpeChnCrop.u16X = pstVpeChnattr->stOrgVpeChnCrop.u16Y; pstVpeChnattr->stVpeChnCrop.u16Y = pstVpeChnattr->stOrgVpeChnCrop.u16X; pstVpeChnattr->stVpeChnCrop.u16Width = pstVpeChnattr->stOrgVpeChnCrop.u16Height; pstVpeChnattr->stVpeChnCrop.u16Height = pstVpeChnattr->stOrgVpeChnCrop.u16Width; } else { pstVpeChnattr->stVpeChnCrop.u16X = pstVpeChnattr->stOrgVpeChnCrop.u16X; pstVpeChnattr->stVpeChnCrop.u16Y = pstVpeChnattr->stOrgVpeChnCrop.u16Y; pstVpeChnattr->stVpeChnCrop.u16Width = pstVpeChnattr->stOrgVpeChnCrop.u16Width; pstVpeChnattr->stVpeChnCrop.u16Height = pstVpeChnattr->stOrgVpeChnCrop.u16Height; } for(i=0; i<ST_MAX_SCL_NUM; i++) { printf("port %d 0:real, 1:frame:", i); scanf("%d", &s32PortSelect); ST_Flush(); if(s32PortSelect == 1) { switch(i) { case 0: s32ChnPortMode |= E_MI_VPE_ZOOM_LDC_PORT0; break; case 1: s32ChnPortMode |= E_MI_VPE_ZOOM_LDC_PORT1; break; case 2: s32ChnPortMode |= E_MI_VPE_ZOOM_LDC_PORT2; break; case 3: s32ChnPortMode = s32ChnPortMode; break; default: s32ChnPortMode = 0; break; } } } for(i=0; i<ST_MAX_PORT_NUM; i++) { MI_S32 s32BusePort = 0; MI_S32 s32PortCropX =0, s32PortCropY=0,s32PortCropW=0,s32PortCropH =0; MI_S32 s32PortPixelFormat =0; MI_S32 s32PortMirror=0, s32PortFlip=0; MI_S32 s32PortW=0, s32PortH=0; printf("use port%d ?(0,not use, 1 use):", i); scanf("%d", &s32BusePort); ST_Flush(); if(s32BusePort > 0) { ST_VpePortAttr_t *pstVpePortAttr = &pstVpeChnattr->stVpePortAttr[i]; if(i < ST_MAX_SCL_NUM) { printf("port %d port crop x:", i); scanf("%d", &s32PortCropX); ST_Flush(); printf("port %d port crop y:", i); scanf("%d", &s32PortCropY); ST_Flush(); printf("port %d port crop width:", i); scanf("%d", &s32PortCropW); ST_Flush(); printf("port %d port crop height:", i); scanf("%d", &s32PortCropH); ST_Flush(); printf("port %d bmirror:", i); scanf("%d", &s32PortMirror); ST_Flush(); printf("port %d bflip:", i); scanf("%d", &s32PortFlip); ST_Flush(); printf("port %d port width:", i); scanf("%d", &s32PortW); ST_Flush(); printf("port %d port height:", i); scanf("%d", &s32PortH); ST_Flush(); } else { MI_SNR_PlaneInfo_t stPlaneInfo; memset(&stPlaneInfo, 0x0, sizeof(MI_SNR_PlaneInfo_t)); MI_SNR_GetPlaneInfo((MI_SNR_PAD_ID_e)u32SensorId, 0, &stPlaneInfo); if(i==3) { s32PortW = stPlaneInfo.stCapRect.u16Width; s32PortH = stPlaneInfo.stCapRect.u16Height; } else if(i==4) { s32PortW = stPlaneInfo.stCapRect.u16Width/2; s32PortH = stPlaneInfo.stCapRect.u16Height/2; } } if(gbPreviewByVenc > 0) { MI_S32 s32BindType =0; MI_S32 eType = 0; MI_U32 u32VencChnid = pstVpePortAttr->u32BindVencChan; ST_VencAttr_t *pstVencAttr = &gstVencattr[u32VencChnid]; printf("vpe port bindtype venc ?\n0 frame mode, 1 ring mode, 2 imi mode, 3 ring mode(half)\n"); scanf("%d", &s32BindType); ST_Flush(); if(s32BindType == 0) { pstVencAttr->eBindType = E_MI_SYS_BIND_TYPE_FRAME_BASE; pstVencAttr->u32BindParam = 0; } else if(s32BindType == 1) { pstVencAttr->eBindType = E_MI_SYS_BIND_TYPE_HW_RING; pstVencAttr->u32BindParam = s32PortH; } else if(s32BindType == 2) { pstVencAttr->eBindType = E_MI_SYS_BIND_TYPE_REALTIME; pstVencAttr->u32BindParam = 0; } else if(s32BindType == 3) { pstVencAttr->eBindType = E_MI_SYS_BIND_TYPE_HW_RING; pstVencAttr->u32BindParam = s32PortH/2; } printf("venc encode type ?\n 2 h264, 3 h265, 4 JPEG\n"); scanf("%d", &eType); ST_Flush(); if(eType == 4) { pstVencAttr->eType = E_MI_VENC_MODTYPE_JPEGE; if(pstVencAttr->eBindType == E_MI_SYS_BIND_TYPE_REALTIME) s32PortPixelFormat = E_MI_SYS_PIXEL_FRAME_YUV422_YUYV; else s32PortPixelFormat = E_MI_SYS_PIXEL_FRAME_YUV_SEMIPLANAR_420; } else { pstVencAttr->eType = (MI_VENC_ModType_e)eType; s32PortPixelFormat = E_MI_SYS_PIXEL_FRAME_YUV_SEMIPLANAR_420; } pstVencAttr->vencChn = u32VencChnid; pstVencAttr->bUsed = TRUE; sprintf(pstVencAttr->szStreamName, "video%d", u32VencChnid); if(pstVpeChnattr->eVpeRotate == E_MI_SYS_ROTATE_90 || pstVpeChnattr->eVpeRotate == E_MI_SYS_ROTATE_270) { pstVencAttr->u32Width = s32PortH; pstVencAttr->u32Height = s32PortW; } else { pstVencAttr->u32Width = s32PortW; pstVencAttr->u32Height = s32PortH; } pstVencAttr->u32BindVpeChn = u32VpeChn; pstVencAttr->u32BindVpePort = i; } else { printf("port %d port pixel:", i); printf("yuv422:0, argb8888:1, abgr8888:2, bgra8888:3, yuv420:11\n"); scanf("%d", &s32PortPixelFormat); ST_Flush(); } pstVpePortAttr->bMirror = s32PortMirror; pstVpePortAttr->bFlip = s32PortFlip; pstVpePortAttr->stOrigPortCrop.u16X = s32PortCropX; pstVpePortAttr->stOrigPortCrop.u16Y = s32PortCropY; pstVpePortAttr->stOrigPortCrop.u16Width = s32PortCropW; pstVpePortAttr->stOrigPortCrop.u16Height = s32PortCropH; pstVpePortAttr->stOrigPortSize.u16Width = s32PortW; pstVpePortAttr->stOrigPortSize.u16Height = s32PortH; if(pstVpeChnattr->eVpeRotate == E_MI_SYS_ROTATE_90 || pstVpeChnattr->eVpeRotate == E_MI_SYS_ROTATE_270) { pstVpePortAttr->stPortSize.u16Width = pstVpePortAttr->stOrigPortSize.u16Height; pstVpePortAttr->stPortSize.u16Height = pstVpePortAttr->stOrigPortSize.u16Width; pstVpePortAttr->stPortCrop.u16X = pstVpePortAttr->stOrigPortCrop.u16Y; pstVpePortAttr->stPortCrop.u16Y = pstVpePortAttr->stOrigPortCrop.u16X; pstVpePortAttr->stPortCrop.u16Width = pstVpePortAttr->stOrigPortCrop.u16Height; pstVpePortAttr->stPortCrop.u16Height = pstVpePortAttr->stOrigPortCrop.u16Width; } else { pstVpePortAttr->stPortSize.u16Width = pstVpePortAttr->stOrigPortSize.u16Width; pstVpePortAttr->stPortSize.u16Height = pstVpePortAttr->stOrigPortSize.u16Height; pstVpePortAttr->stPortCrop.u16X = pstVpePortAttr->stOrigPortCrop.u16X; pstVpePortAttr->stPortCrop.u16Y = pstVpePortAttr->stOrigPortCrop.u16Y; pstVpePortAttr->stPortCrop.u16Width = pstVpePortAttr->stOrigPortCrop.u16Width; pstVpePortAttr->stPortCrop.u16Height = pstVpePortAttr->stOrigPortCrop.u16Height; } pstVpePortAttr->ePixelFormat = (MI_SYS_PixelFormat_e)s32PortPixelFormat; pstVpePortAttr->bUsed = TRUE; } } if((s32ChnPortMode & E_MI_VPE_ZOOM_LDC_PORT1) || (s32ChnPortMode & E_MI_VPE_ZOOM_LDC_PORT2)) { s32ChnPortMode |= E_MI_VPE_ZOOM_LDC_PORT1 | E_MI_VPE_ZOOM_LDC_PORT2; } pstVpeChnattr->u32ChnPortMode = s32ChnPortMode; printf("chnport mode %d \n", pstVpeChnattr->u32ChnPortMode); if(pstVpeChnattr->bEnLdc == TRUE) { MI_U32 u32Cfg_Param = 0; pstVpeChnattr->s32Rot[0] = 0; pstVpeChnattr->s32Rot[1] = 90; pstVpeChnattr->s32Rot[2] = 180; pstVpeChnattr->s32Rot[3] = 270; ST_GetLdcBinBuffer(u32Cfg_Param, pstVpeChnattr->LdcCfgbin_Path, &pstVpeChnattr->tconfig_para, &pstVpeChnattr->u32ViewNum, pstVpeChnattr->ldcBinBuffer, pstVpeChnattr->u32LdcBinSize, pstVpeChnattr->s32Rot); } } MI_BOOL ST_DoGetVifRawData(MI_S32 HDRtype) { MI_SNR_PADInfo_t stPad0Info; MI_SNR_PlaneInfo_t stSnrPlane0Info; MI_U32 u32CapWidth = 0, u32CapHeight = 0; MI_VIF_FrameRate_e eFrameRate = E_MI_VIF_FRAMERATE_FULL; MI_SYS_PixelFormat_e ePixFormat; MI_VIF_DEV vifDev = 1; MI_VIF_CHN vifChn = 4; MI_SNR_GetPadInfo(E_MI_SNR_PAD_ID_0, &stPad0Info); MI_SNR_GetPlaneInfo(E_MI_SNR_PAD_ID_0, 0, &stSnrPlane0Info); u32CapWidth = stSnrPlane0Info.stCapRect.u16Width; u32CapHeight = stSnrPlane0Info.stCapRect.u16Height; eFrameRate = E_MI_VIF_FRAMERATE_FULL; ePixFormat = (MI_SYS_PixelFormat_e)RGB_BAYER_PIXEL(stSnrPlane0Info.ePixPrecision, stSnrPlane0Info.eBayerId); /************************************************ Step2: init VIF(for IPC, only one dev) *************************************************/ MI_VIF_Dev2SnrPadMuxCfg_t stVifDevMap[4]; memset(stVifDevMap, 0xff, sizeof(MI_VIF_Dev2SnrPadMuxCfg_t)*4); if(HDRtype > 0) { /* stVifDevMap[0].eSensorPadID = E_MI_VIF_SNRPAD_ID_0; stVifDevMap[0].u32PlaneID = 1; stVifDevMap[1].eSensorPadID = E_MI_VIF_SNRPAD_ID_0; stVifDevMap[1].u32PlaneID = 0; stVifDevMap[2].eSensorPadID = E_MI_VIF_SNRPAD_ID_0; stVifDevMap[2].u32PlaneID = 1;*/ printf("HDR ON not support"); return 0; } else { stVifDevMap[0].eSensorPadID = E_MI_VIF_SNRPAD_ID_0; stVifDevMap[0].u32PlaneID = 0XFF; stVifDevMap[1].eSensorPadID = E_MI_VIF_SNRPAD_ID_0; stVifDevMap[1].u32PlaneID = 0XFF; } printf("devmap %p\n", stVifDevMap); MI_VIF_SetDev2SnrPadMux(stVifDevMap, 4); MI_VIF_DevAttr_t stDevAttr; memset(&stDevAttr, 0x0, sizeof(MI_VIF_DevAttr_t)); stDevAttr.eIntfMode = stPad0Info.eIntfMode; stDevAttr.eWorkMode = E_MI_VIF_WORK_MODE_RGB_FRAMEMODE; stDevAttr.eHDRType = E_MI_VIF_HDR_TYPE_OFF; if(stDevAttr.eIntfMode == E_MI_VIF_MODE_BT656) stDevAttr.eClkEdge = stPad0Info.unIntfAttr.stBt656Attr.eClkEdge; else stDevAttr.eClkEdge = E_MI_VIF_CLK_EDGE_DOUBLE; if(stDevAttr.eIntfMode == E_MI_VIF_MODE_MIPI) stDevAttr.eDataSeq =stPad0Info.unIntfAttr.stMipiAttr.eDataYUVOrder; else stDevAttr.eDataSeq = E_MI_VIF_INPUT_DATA_YUYV; if(stDevAttr.eIntfMode == E_MI_VIF_MODE_BT656) memcpy(&stDevAttr.stSyncAttr, &stPad0Info.unIntfAttr.stBt656Attr.stSyncAttr, sizeof(MI_VIF_SyncAttr_t)); stDevAttr.eBitOrder = E_MI_VIF_BITORDER_NORMAL; ExecFunc(MI_VIF_SetDevAttr(vifDev, &stDevAttr), MI_SUCCESS); ExecFunc(MI_VIF_EnableDev(vifDev), MI_SUCCESS); ST_VIF_PortInfo_T stVifPortInfoInfo; memset(&stVifPortInfoInfo, 0, sizeof(ST_VIF_PortInfo_T)); stVifPortInfoInfo.u32RectX = 0; stVifPortInfoInfo.u32RectY = 0; stVifPortInfoInfo.u32RectWidth = u32CapWidth; stVifPortInfoInfo.u32RectHeight = u32CapHeight; stVifPortInfoInfo.u32DestWidth = u32CapWidth; stVifPortInfoInfo.u32DestHeight = u32CapHeight; stVifPortInfoInfo.eFrameRate = eFrameRate; stVifPortInfoInfo.ePixFormat = ePixFormat;//E_MI_SYS_PIXEL_FRAME_RGB_BAYER_12BPP_GR; STCHECKRESULT(ST_Vif_CreatePort(vifChn, 0, &stVifPortInfoInfo)); STCHECKRESULT(ST_Vif_StartPort(0, vifChn, 0)); { MI_SYS_ChnPort_t stChnPort; MI_SYS_BufInfo_t stBufInfo; MI_SYS_BUF_HANDLE hHandle; MI_S32 s32WriteCnt = 0; FILE *fp = NULL; char aName[128]; struct timeval CurTime; MI_U64 u64Time = 0; memset(&stChnPort, 0x0, sizeof(MI_SYS_ChnPort_t)); stChnPort.eModId = E_MI_MODULE_ID_VIF; stChnPort.u32DevId = 0; stChnPort.u32ChnId = vifChn; stChnPort.u32PortId = 0; gettimeofday(&CurTime,NULL); u64Time = CurTime.tv_sec*1000; sprintf(aName, "/mnt/dump_vif4_port0_%dx%d_pts%llu.yuv",u32CapWidth,u32CapHeight, u64Time); fp = fopen(aName,"wb"); if(fp == NULL) printf("file open fail\n"); while (s32WriteCnt < 10) { if (MI_SUCCESS == MI_SYS_ChnOutputPortGetBuf(&stChnPort, &stBufInfo, &hHandle)) { int size = stBufInfo.stFrameData.u32BufSize; fwrite(stBufInfo.stFrameData.pVirAddr[0], size, 1, fp); s32WriteCnt++; printf("\t vif(%d) size(%d) get buf cnt (%d)...w(%d)...h(%d)..\n", vifChn, size, s32WriteCnt, stBufInfo.stFrameData.u16Width, stBufInfo.stFrameData.u16Height); MI_SYS_ChnOutputPortPutBuf(hHandle); } usleep(10*1000); } fclose(fp); } STCHECKRESULT(ST_Vif_StopPort(vifChn, 0)); STCHECKRESULT(ST_Vif_DisableDev(vifDev)); return MI_SUCCESS; } MI_BOOL ST_DoChangeRes(MI_U32 u32SensorNum) { char select = 0xFF; MI_U8 u8ResIdx =0; MI_SNR_Res_t stRes; ST_Sys_BindInfo_T stBindInfo; MI_SNR_PADInfo_t stPad0Info; MI_SNR_PlaneInfo_t stSnrPlane0Info; MI_U32 u32CapWidth = 0, u32CapHeight = 0; MI_VIF_FrameRate_e eFrameRate = E_MI_VIF_FRAMERATE_FULL; MI_SYS_PixelFormat_e ePixFormat; MI_U32 u32ResCount =0; MI_U8 u8ResIndex =0; MI_S32 s32SnrPad =0; memset(&stRes, 0x0, sizeof(MI_SNR_Res_t)); if(u32SensorNum > 1) { printf("select SensorPad id:"); scanf("%d", &s32SnrPad); ST_Flush(); if(s32SnrPad >= ST_MAX_SENSOR_NUM) { printf("s32SnrPad %d > max %d \n", s32SnrPad, ST_MAX_SENSOR_NUM); return 0; } } else { s32SnrPad = 0; } MI_SNR_PAD_ID_e eSnrPad = (MI_SNR_PAD_ID_e)s32SnrPad; MI_VIF_DEV vifDev = gstSensorAttr[eSnrPad].u32BindVifDev; MI_VIF_CHN vifChn = vifDev*4; MI_U8 u8VpeChn = gstVifAttr[vifDev].u32BindVpeChan; ST_VpeChannelAttr_t *pstVpeChnattr = &gstVpeChnattr[u8VpeChn]; ST_Vif_Attr_t *pstVifAttr = &gstVifAttr[vifDev]; MI_SNR_QueryResCount(eSnrPad, &u32ResCount); for(u8ResIndex=0; u8ResIndex < u32ResCount; u8ResIndex++) { MI_SNR_GetRes(eSnrPad, u8ResIndex, &stRes); printf("index %d, Crop(%d,%d,%d,%d), outputsize(%d,%d), maxfps %d, minfps %d, ResDesc %s\n", u8ResIndex, stRes.stCropRect.u16X, stRes.stCropRect.u16Y, stRes.stCropRect.u16Width,stRes.stCropRect.u16Height, stRes.stOutputSize.u16Width, stRes.stOutputSize.u16Height, stRes.u32MaxFps,stRes.u32MinFps, stRes.strResDesc); } printf("select res\n"); scanf("%c", &select); ST_Flush(); if(select == 'q') { return 1; } u8ResIdx = atoi(&select); if(u8ResIdx >= u32ResCount) return 0; memset(&stBindInfo, 0x0, sizeof(ST_Sys_BindInfo_T)); stBindInfo.stSrcChnPort.eModId = E_MI_MODULE_ID_VIF; stBindInfo.stSrcChnPort.u32DevId = vifDev; stBindInfo.stSrcChnPort.u32ChnId = vifChn; stBindInfo.stSrcChnPort.u32PortId = 0; stBindInfo.stDstChnPort.eModId = E_MI_MODULE_ID_VPE; stBindInfo.stDstChnPort.u32DevId = 0; stBindInfo.stDstChnPort.u32ChnId = u8VpeChn; stBindInfo.stDstChnPort.u32PortId = 0; STCHECKRESULT(ST_Sys_UnBind(&stBindInfo)); STCHECKRESULT(ST_Vpe_StopChannel(u8VpeChn)); /************************************************ Step3: destory VIF *************************************************/ STCHECKRESULT(ST_Vif_StopPort(vifChn, 0)); STCHECKRESULT(ST_Vif_DisableDev(vifDev)); MI_SNR_Disable(eSnrPad); if(pstVpeChnattr->eHdrType > 0) { MI_SNR_SetPlaneMode(eSnrPad, TRUE); } else { MI_SNR_SetPlaneMode(eSnrPad, FALSE); } MI_SNR_SetRes(eSnrPad,u8ResIdx); MI_SNR_Enable(eSnrPad); MI_SNR_GetPadInfo(eSnrPad, &stPad0Info); MI_SNR_GetPlaneInfo(eSnrPad, 0, &stSnrPlane0Info); u32CapWidth = stSnrPlane0Info.stCapRect.u16Width; u32CapHeight = stSnrPlane0Info.stCapRect.u16Height; eFrameRate = E_MI_VIF_FRAMERATE_FULL; ePixFormat = (MI_SYS_PixelFormat_e)RGB_BAYER_PIXEL(stSnrPlane0Info.ePixPrecision, stSnrPlane0Info.eBayerId); /************************************************ Step2: init VIF(for IPC, only one dev) *************************************************/ MI_VIF_DevAttr_t stDevAttr; memset(&stDevAttr, 0x0, sizeof(MI_VIF_DevAttr_t)); stDevAttr.eIntfMode = stPad0Info.eIntfMode; stDevAttr.eWorkMode = pstVifAttr->eWorkMode; stDevAttr.eHDRType = (MI_VIF_HDRType_e)pstVpeChnattr->eHdrType; if(stDevAttr.eIntfMode == E_MI_VIF_MODE_BT656) stDevAttr.eClkEdge = stPad0Info.unIntfAttr.stBt656Attr.eClkEdge; else stDevAttr.eClkEdge = E_MI_VIF_CLK_EDGE_DOUBLE; if(stDevAttr.eIntfMode == E_MI_VIF_MODE_MIPI) stDevAttr.eDataSeq =stPad0Info.unIntfAttr.stMipiAttr.eDataYUVOrder; else stDevAttr.eDataSeq = E_MI_VIF_INPUT_DATA_YUYV; if(stDevAttr.eIntfMode == E_MI_VIF_MODE_BT656) memcpy(&stDevAttr.stSyncAttr, &stPad0Info.unIntfAttr.stBt656Attr.stSyncAttr, sizeof(MI_VIF_SyncAttr_t)); stDevAttr.eBitOrder = E_MI_VIF_BITORDER_NORMAL; ExecFunc(MI_VIF_SetDevAttr(vifDev, &stDevAttr), MI_SUCCESS); ExecFunc(MI_VIF_EnableDev(vifDev), MI_SUCCESS); ST_VIF_PortInfo_T stVifPortInfoInfo; memset(&stVifPortInfoInfo, 0, sizeof(ST_VIF_PortInfo_T)); stVifPortInfoInfo.u32RectX = stSnrPlane0Info.stCapRect.u16X; stVifPortInfoInfo.u32RectY = stSnrPlane0Info.stCapRect.u16Y; stVifPortInfoInfo.u32RectWidth = u32CapWidth; stVifPortInfoInfo.u32RectHeight = u32CapHeight; stVifPortInfoInfo.u32DestWidth = u32CapWidth; stVifPortInfoInfo.u32DestHeight = u32CapHeight; stVifPortInfoInfo.eFrameRate = eFrameRate; stVifPortInfoInfo.ePixFormat = ePixFormat;//E_MI_SYS_PIXEL_FRAME_RGB_BAYER_12BPP_GR; STCHECKRESULT(ST_Vif_CreatePort(vifChn, 0, &stVifPortInfoInfo)); STCHECKRESULT(ST_Vif_StartPort(vifDev, vifChn, 0)); STCHECKRESULT(ST_Vpe_StartChannel(u8VpeChn)); /************************************************ Step1: bind VIF->VPE *************************************************/ memset(&stBindInfo, 0x0, sizeof(ST_Sys_BindInfo_T)); stBindInfo.stSrcChnPort.eModId = E_MI_MODULE_ID_VIF; stBindInfo.stSrcChnPort.u32DevId = vifDev; stBindInfo.stSrcChnPort.u32ChnId = vifChn; stBindInfo.stSrcChnPort.u32PortId = 0; stBindInfo.stDstChnPort.eModId = E_MI_MODULE_ID_VPE; stBindInfo.stDstChnPort.u32DevId = 0; stBindInfo.stDstChnPort.u32ChnId = u8VpeChn; stBindInfo.stDstChnPort.u32PortId = 0; stBindInfo.u32SrcFrmrate = 30; stBindInfo.u32DstFrmrate = 30; stBindInfo.eBindType = pstVifAttr->eBindType; STCHECKRESULT(ST_Sys_Bind(&stBindInfo)); return 0; } MI_BOOL ST_DoChangeHDRtype() { MI_S32 select = 0; MI_U8 u8ResIdx =0; MI_SNR_Res_t stRes; MI_SNR_PAD_ID_e eSnrPad = E_MI_SNR_PAD_ID_0; ST_Sys_BindInfo_T stBindInfo; MI_SNR_PADInfo_t stPad0Info; MI_SNR_PlaneInfo_t stSnrPlane0Info; MI_U32 u32CapWidth = 0, u32CapHeight = 0; MI_VIF_FrameRate_e eFrameRate = E_MI_VIF_FRAMERATE_FULL; MI_SYS_PixelFormat_e ePixFormat; MI_VIF_HDRType_e eVifHdrType = E_MI_VIF_HDR_TYPE_OFF; MI_VPE_HDRType_e eVpeHdrType = E_MI_VPE_HDR_TYPE_OFF; MI_VIF_DEV vifDev = 0; MI_VIF_CHN vifChn = 0; MI_U32 u32VpeChn = 0; MI_VPE_ChannelPara_t stVpeChParam; ST_VpeChannelAttr_t *pstVpeChnattr = &gstVpeChnattr[u32VpeChn]; memset(&stVpeChParam, 0x0, sizeof(MI_VPE_ChannelPara_t)); memset(&stRes, 0x0, sizeof(MI_SNR_Res_t)); printf("Use HDR ?\n 0 not use, 1 use VC, 2 use DOL, 3 use EMBEDDED, 4 use LI\n"); printf("sony sensor(ex imx307) use DOL, sc sensor(ex sc4238) use VC\n"); scanf("%d", &select); ST_Flush(); printf("You select %d HDR\n", select); if(select == 0) { eVifHdrType = E_MI_VIF_HDR_TYPE_OFF; eVpeHdrType = E_MI_VPE_HDR_TYPE_OFF; } else if(select == 1) { eVifHdrType = E_MI_VIF_HDR_TYPE_VC; eVpeHdrType = E_MI_VPE_HDR_TYPE_VC; } else if(select == 2) { eVifHdrType = E_MI_VIF_HDR_TYPE_DOL; eVpeHdrType = E_MI_VPE_HDR_TYPE_DOL; } else if(select == 3) { eVifHdrType = E_MI_VIF_HDR_TYPE_EMBEDDED; eVpeHdrType = E_MI_VPE_HDR_TYPE_EMBEDDED; } else if(select == 4) { eVifHdrType = E_MI_VIF_HDR_TYPE_LI; eVpeHdrType = E_MI_VPE_HDR_TYPE_LI; } else { printf("select hdrtype %d not support \n", select); return 0; } pstVpeChnattr->eHdrType = eVpeHdrType; /************************************************ Step1: unbind VIF->VPE *************************************************/ memset(&stBindInfo, 0x0, sizeof(ST_Sys_BindInfo_T)); stBindInfo.stSrcChnPort.eModId = E_MI_MODULE_ID_VIF; stBindInfo.stSrcChnPort.u32DevId = vifDev; stBindInfo.stSrcChnPort.u32ChnId = vifChn; stBindInfo.stSrcChnPort.u32PortId = 0; stBindInfo.stDstChnPort.eModId = E_MI_MODULE_ID_VPE; stBindInfo.stDstChnPort.u32DevId = 0; stBindInfo.stDstChnPort.u32ChnId = u32VpeChn; stBindInfo.stDstChnPort.u32PortId = 0; STCHECKRESULT(ST_Sys_UnBind(&stBindInfo)); STCHECKRESULT(ST_Vpe_StopChannel(u32VpeChn)); /************************************************ Step3: destory VIF *************************************************/ STCHECKRESULT(ST_Vif_StopPort(vifChn, 0)); STCHECKRESULT(ST_Vif_DisableDev(vifDev)); MI_SNR_Disable(eSnrPad); if(E_MI_VIF_HDR_TYPE_OFF==eVifHdrType || E_MI_VIF_HDR_TYPE_EMBEDDED==eVifHdrType || E_MI_VIF_HDR_TYPE_LI==eVifHdrType) { MI_SNR_SetPlaneMode(eSnrPad, FALSE); } else { MI_SNR_SetPlaneMode(eSnrPad, TRUE); } MI_SNR_SetRes(eSnrPad,u8ResIdx); MI_SNR_Enable(eSnrPad); MI_SNR_GetPadInfo(eSnrPad, &stPad0Info); MI_SNR_GetPlaneInfo(eSnrPad, 0, &stSnrPlane0Info); u32CapWidth = stSnrPlane0Info.stCapRect.u16Width; u32CapHeight = stSnrPlane0Info.stCapRect.u16Height; eFrameRate = E_MI_VIF_FRAMERATE_FULL; ePixFormat = (MI_SYS_PixelFormat_e)RGB_BAYER_PIXEL(stSnrPlane0Info.ePixPrecision, stSnrPlane0Info.eBayerId); /************************************************ Step2: init VIF(for IPC, only one dev) *************************************************/ MI_VIF_DevAttr_t stDevAttr; memset(&stDevAttr, 0x0, sizeof(MI_VIF_DevAttr_t)); stDevAttr.eIntfMode = stPad0Info.eIntfMode; stDevAttr.eWorkMode = gstVifAttr[vifDev].eWorkMode; stDevAttr.eHDRType = eVifHdrType; if(stDevAttr.eIntfMode == E_MI_VIF_MODE_BT656) stDevAttr.eClkEdge = stPad0Info.unIntfAttr.stBt656Attr.eClkEdge; else stDevAttr.eClkEdge = E_MI_VIF_CLK_EDGE_DOUBLE; if(stDevAttr.eIntfMode == E_MI_VIF_MODE_MIPI) stDevAttr.eDataSeq =stPad0Info.unIntfAttr.stMipiAttr.eDataYUVOrder; else stDevAttr.eDataSeq = E_MI_VIF_INPUT_DATA_YUYV; if(stDevAttr.eIntfMode == E_MI_VIF_MODE_BT656) memcpy(&stDevAttr.stSyncAttr, &stPad0Info.unIntfAttr.stBt656Attr.stSyncAttr, sizeof(MI_VIF_SyncAttr_t)); stDevAttr.eBitOrder = E_MI_VIF_BITORDER_NORMAL; ExecFunc(MI_VIF_SetDevAttr(vifDev, &stDevAttr), MI_SUCCESS); ExecFunc(MI_VIF_EnableDev(vifDev), MI_SUCCESS); ST_VIF_PortInfo_T stVifPortInfoInfo; memset(&stVifPortInfoInfo, 0, sizeof(ST_VIF_PortInfo_T)); stVifPortInfoInfo.u32RectX = stSnrPlane0Info.stCapRect.u16X; stVifPortInfoInfo.u32RectY = stSnrPlane0Info.stCapRect.u16Y; stVifPortInfoInfo.u32RectWidth = u32CapWidth; stVifPortInfoInfo.u32RectHeight = u32CapHeight; stVifPortInfoInfo.u32DestWidth = u32CapWidth; stVifPortInfoInfo.u32DestHeight = u32CapHeight; stVifPortInfoInfo.eFrameRate = eFrameRate; stVifPortInfoInfo.ePixFormat = ePixFormat; STCHECKRESULT(ST_Vif_CreatePort(vifChn, 0, &stVifPortInfoInfo)); STCHECKRESULT(ST_Vif_StartPort(vifDev, vifChn, 0)); /************************************************ Step3: init VPE (create one VPE) *************************************************/ MI_VPE_GetChannelParam(u32VpeChn, &stVpeChParam); stVpeChParam.eHDRType = eVpeHdrType; MI_VPE_SetChannelParam(u32VpeChn, &stVpeChParam); STCHECKRESULT(ST_Vpe_StartChannel(0)); /************************************************ Step1: bind VIF->VPE *************************************************/ memset(&stBindInfo, 0x0, sizeof(ST_Sys_BindInfo_T)); stBindInfo.stSrcChnPort.eModId = E_MI_MODULE_ID_VIF; stBindInfo.stSrcChnPort.u32DevId = vifDev; stBindInfo.stSrcChnPort.u32ChnId = vifChn; stBindInfo.stSrcChnPort.u32PortId = 0; stBindInfo.stDstChnPort.eModId = E_MI_MODULE_ID_VPE; stBindInfo.stDstChnPort.u32DevId = 0; stBindInfo.stDstChnPort.u32ChnId = u32VpeChn; stBindInfo.stDstChnPort.u32PortId = 0; stBindInfo.u32SrcFrmrate = 30; stBindInfo.u32DstFrmrate = 30; stBindInfo.eBindType = gstVifAttr[vifDev].eBindType; STCHECKRESULT(ST_Sys_Bind(&stBindInfo)); return 0; } MI_BOOL ST_DoChangeRotate(MI_U32 u32SensorNum) { ST_Sys_BindInfo_T stBindInfo; MI_S32 s32Rotation = 0; MI_S32 s32Mirror = 0; MI_S32 s32Flip = 0; ST_VencAttr_t *pstVencattr = gstVencattr; MI_U8 i=0; MI_U32 u32VifDev=0, vifChn=0; MI_S32 VpeChn = 0; MI_U32 u32MaxVencWidth =0, u32MaxVencHeight =0; if(u32SensorNum > 1) { printf("select channel id:"); scanf("%d", &VpeChn); ST_Flush(); if(VpeChn >= ST_MAX_SENSOR_NUM) { printf("VpeChn %d > max %d \n", VpeChn, ST_MAX_SENSOR_NUM); return 0; } } else { VpeChn = 0; } u32VifDev = VpeChn; vifChn = u32VifDev*4; ST_VpeChannelAttr_t *pstVpeChnattr = &gstVpeChnattr[VpeChn]; printf("rotation(0:0, 1:90, 2:180, 3:270):"); scanf("%d", &s32Rotation); ST_Flush(); printf("bmirror 0: FALSE, 1:TRUE :"); scanf("%d", &s32Mirror); ST_Flush(); printf("bFlip 0: FALSE, 1:TRUE :"); scanf("%d", &s32Flip); ST_Flush(); pstVpeChnattr->eVpeRotate = (MI_SYS_Rotate_e)s32Rotation; pstVpeChnattr->bChnFlip = s32Flip; pstVpeChnattr->bChnMirror = s32Mirror; /************************************************ Step1: unbind VIF->VPE *************************************************/ memset(&stBindInfo, 0x0, sizeof(ST_Sys_BindInfo_T)); stBindInfo.stSrcChnPort.eModId = E_MI_MODULE_ID_VIF; stBindInfo.stSrcChnPort.u32DevId = u32VifDev; stBindInfo.stSrcChnPort.u32ChnId = vifChn; stBindInfo.stSrcChnPort.u32PortId = 0; stBindInfo.stDstChnPort.eModId = E_MI_MODULE_ID_VPE; stBindInfo.stDstChnPort.u32DevId = 0; stBindInfo.stDstChnPort.u32ChnId = VpeChn; stBindInfo.stDstChnPort.u32PortId = 0; STCHECKRESULT(ST_Sys_UnBind(&stBindInfo)); if(gbPreviewByVenc == TRUE) { ST_VencStop(VpeChn); } STCHECKRESULT(ST_Vpe_StopChannel(VpeChn)); if(pstVpeChnattr->eRunningMode == E_MI_VPE_RUN_REALTIME_MODE) STCHECKRESULT(ST_Vif_StopPort(vifChn, 0)); /************************************************ Step3: init VPE (create one VPE) *************************************************/ MI_VPE_SetChannelRotation(VpeChn, pstVpeChnattr->eVpeRotate); MI_VPE_ChannelPara_t stChnParam; memset(&stChnParam, 0x0, sizeof(MI_VPE_ChannelPara_t)); MI_VPE_GetChannelParam(VpeChn, &stChnParam); stChnParam.bMirror = pstVpeChnattr->bChnMirror; stChnParam.bFlip = pstVpeChnattr->bChnFlip; MI_VPE_SetChannelParam(VpeChn, &stChnParam); for(i=0; i<ST_MAX_PORT_NUM; i++) { MI_SYS_WindowRect_t stOutCropInfo; MI_VPE_PortMode_t stVpeMode; MI_U32 u32VencChn = pstVpeChnattr->stVpePortAttr[i].u32BindVencChan; memset(&stOutCropInfo, 0x0, sizeof(MI_SYS_WindowRect_t)); memset(&stVpeMode, 0x0, sizeof(MI_VPE_PortMode_t)); if(pstVpeChnattr->stVpePortAttr[i].bUsed == TRUE) { MI_VPE_GetPortCrop(VpeChn, i, &stOutCropInfo); MI_VPE_GetPortMode(VpeChn , i, &stVpeMode); if(pstVpeChnattr->eVpeRotate == E_MI_SYS_ROTATE_90 || pstVpeChnattr->eVpeRotate == E_MI_SYS_ROTATE_270) { stOutCropInfo.u16X = pstVpeChnattr->stVpePortAttr[i].stOrigPortCrop.u16Y; stOutCropInfo.u16Y = pstVpeChnattr->stVpePortAttr[i].stOrigPortCrop.u16X; stOutCropInfo.u16Width = pstVpeChnattr->stVpePortAttr[i].stOrigPortCrop.u16Height; stOutCropInfo.u16Height = pstVpeChnattr->stVpePortAttr[i].stOrigPortCrop.u16Width; stVpeMode.u16Width = pstVpeChnattr->stVpePortAttr[i].stOrigPortSize.u16Height; stVpeMode.u16Height = pstVpeChnattr->stVpePortAttr[i].stOrigPortSize.u16Width; u32MaxVencWidth = 2160; u32MaxVencHeight = 3840; } else { stOutCropInfo.u16X = pstVpeChnattr->stVpePortAttr[i].stOrigPortCrop.u16X; stOutCropInfo.u16Y = pstVpeChnattr->stVpePortAttr[i].stOrigPortCrop.u16Y; stOutCropInfo.u16Width = pstVpeChnattr->stVpePortAttr[i].stOrigPortCrop.u16Width; stOutCropInfo.u16Height = pstVpeChnattr->stVpePortAttr[i].stOrigPortCrop.u16Height; stVpeMode.u16Width = pstVpeChnattr->stVpePortAttr[i].stOrigPortSize.u16Width; stVpeMode.u16Height = pstVpeChnattr->stVpePortAttr[i].stOrigPortSize.u16Height; u32MaxVencWidth = 3840; u32MaxVencHeight = 2160; } MI_VPE_SetPortCrop(VpeChn, i, &stOutCropInfo); MI_VPE_SetPortMode(VpeChn , i, &stVpeMode); pstVencattr[u32VencChn].u32Width = stVpeMode.u16Width; pstVencattr[u32VencChn].u32Height = stVpeMode.u16Height; } } if(gbPreviewByVenc == TRUE) { ST_VencStart(u32MaxVencWidth, u32MaxVencHeight, VpeChn); //ExecFunc(MI_VENC_StartRecvPic(pstVencattr[u32VencChn].vencChn), MI_SUCCESS); } if(pstVpeChnattr->eRunningMode == E_MI_VPE_RUN_REALTIME_MODE) STCHECKRESULT(ST_Vif_StartPort(u32VifDev, vifChn, 0)); STCHECKRESULT(ST_Vpe_StartChannel(VpeChn)); /************************************************ Step1: bind VIF->VPE *************************************************/ memset(&stBindInfo, 0x0, sizeof(ST_Sys_BindInfo_T)); stBindInfo.stSrcChnPort.eModId = E_MI_MODULE_ID_VIF; stBindInfo.stSrcChnPort.u32DevId = u32VifDev; stBindInfo.stSrcChnPort.u32ChnId = vifChn; stBindInfo.stSrcChnPort.u32PortId = 0; stBindInfo.stDstChnPort.eModId = E_MI_MODULE_ID_VPE; stBindInfo.stDstChnPort.u32DevId = 0; stBindInfo.stDstChnPort.u32ChnId = VpeChn; stBindInfo.stDstChnPort.u32PortId = 0; stBindInfo.u32SrcFrmrate = 30; stBindInfo.u32DstFrmrate = 30; stBindInfo.eBindType = gstVifAttr[u32VifDev].eBindType; STCHECKRESULT(ST_Sys_Bind(&stBindInfo)); return 0; } MI_BOOL ST_ResetPortMode(MI_U32 u32SensorNum) { MI_S32 s32Portid = 0; MI_S32 s32PortPixelFormat =0; MI_S32 s32PortMirror=0, s32PortFlip=0; MI_S32 s32PortW=0, s32PortH=0; MI_VPE_PortMode_t stVpePortMode; ST_Sys_BindInfo_T stBindInfo; MI_U32 u32DevId = 0; memset(&stVpePortMode, 0x0, sizeof(MI_VPE_PortMode_t)); memset(&stBindInfo, 0x0, sizeof(ST_Sys_BindInfo_T)); MI_U32 VpeChn =0; if(u32SensorNum > 1) { printf("select channel id:"); scanf("%d", &VpeChn); ST_Flush(); if(VpeChn >= ST_MAX_SENSOR_NUM) { printf("VpeChn %d > max %d \n", VpeChn, ST_MAX_SENSOR_NUM); return 0; } } else { VpeChn = 0; } printf("select port id:"); scanf("%d", &s32Portid); ST_Flush(); if(s32Portid >= ST_MAX_PORT_NUM) { printf("port %d, not valid \n", s32Portid); return 0; } printf("port %d bmirror:", s32Portid); scanf("%d", &s32PortMirror); ST_Flush(); printf("port %d bflip:", s32Portid); scanf("%d", &s32PortFlip); ST_Flush(); printf("port %d port width:", s32Portid); scanf("%d", &s32PortW); ST_Flush(); printf("port %d port height:", s32Portid); scanf("%d", &s32PortH); ST_Flush(); ST_VpeChannelAttr_t *pstVpeChnattr = &gstVpeChnattr[VpeChn]; ST_VpePortAttr_t *pstVpePortAttr = &pstVpeChnattr->stVpePortAttr[s32Portid]; MI_U32 U32VencChn = pstVpePortAttr->u32BindVencChan; ST_VencAttr_t *pstVencattr = &gstVencattr[U32VencChn]; MI_VPE_GetPortMode(VpeChn, s32Portid, &stVpePortMode); if(gbPreviewByVenc == FALSE) { printf("port %d port pixel:", s32Portid); printf("yuv422:0, argb8888:1, abgr8888:2, bgra8888:3, yuv420:11\n"); scanf("%d", &s32PortPixelFormat); ST_Flush(); } else s32PortPixelFormat = stVpePortMode.ePixelFormat; if(gbPreviewByVenc == TRUE) { ExecFunc(MI_VENC_GetChnDevid(pstVencattr->vencChn, &u32DevId), MI_SUCCESS); stBindInfo.stSrcChnPort.eModId = E_MI_MODULE_ID_VPE; stBindInfo.stSrcChnPort.u32DevId = 0; stBindInfo.stSrcChnPort.u32ChnId = VpeChn; stBindInfo.stSrcChnPort.u32PortId = s32Portid; stBindInfo.stDstChnPort.eModId = E_MI_MODULE_ID_VENC; stBindInfo.stDstChnPort.u32DevId = u32DevId; stBindInfo.stDstChnPort.u32ChnId = pstVencattr->vencChn; stBindInfo.stDstChnPort.u32PortId = 0; STCHECKRESULT(ST_Sys_UnBind(&stBindInfo)); if(pstVencattr->bUsed == TRUE) ExecFunc(MI_VENC_StopRecvPic(pstVencattr->vencChn), MI_SUCCESS); } MI_VPE_DisablePort(VpeChn, s32Portid); pstVpePortAttr->bMirror = s32PortMirror; pstVpePortAttr->bFlip = s32PortFlip; pstVpePortAttr->stOrigPortSize.u16Width = s32PortW; pstVpePortAttr->stOrigPortSize.u16Height = s32PortH; pstVpePortAttr->ePixelFormat = (MI_SYS_PixelFormat_e)s32PortPixelFormat; pstVpePortAttr->bUsed = TRUE; stVpePortMode.bMirror = pstVpePortAttr->bMirror; stVpePortMode.bFlip = pstVpePortAttr->bFlip; stVpePortMode.ePixelFormat = pstVpePortAttr->ePixelFormat; if(pstVpeChnattr->eVpeRotate == E_MI_SYS_ROTATE_90 || pstVpeChnattr->eVpeRotate == E_MI_SYS_ROTATE_270) { stVpePortMode.u16Width = pstVpePortAttr->stOrigPortSize.u16Height; stVpePortMode.u16Height = pstVpePortAttr->stOrigPortSize.u16Width; } else { stVpePortMode.u16Width = pstVpePortAttr->stOrigPortSize.u16Width; stVpePortMode.u16Height = pstVpePortAttr->stOrigPortSize.u16Height; } MI_VPE_SetPortMode(VpeChn, s32Portid, &stVpePortMode); if(gbPreviewByVenc == TRUE) { MI_VENC_ChnAttr_t stChnAttr; memset(&stChnAttr, 0x0, sizeof(MI_VENC_ChnAttr_t)); if(pstVencattr->bUsed == TRUE) { ExecFunc(MI_VENC_GetChnAttr(pstVencattr->vencChn, &stChnAttr), MI_SUCCESS); if(pstVencattr->eType == E_MI_VENC_MODTYPE_H264E) { stChnAttr.stVeAttr.stAttrH264e.u32PicWidth = stVpePortMode.u16Width; stChnAttr.stVeAttr.stAttrH264e.u32PicHeight = stVpePortMode.u16Height; } else if(pstVencattr->eType == E_MI_VENC_MODTYPE_H264E) { stChnAttr.stVeAttr.stAttrH265e.u32PicWidth = stVpePortMode.u16Width; stChnAttr.stVeAttr.stAttrH265e.u32PicHeight = stVpePortMode.u16Height; } else if(pstVencattr->eType == E_MI_VENC_MODTYPE_H264E) { stChnAttr.stVeAttr.stAttrJpeg.u32PicWidth = stVpePortMode.u16Width; stChnAttr.stVeAttr.stAttrJpeg.u32PicHeight = stVpePortMode.u16Height; } ExecFunc(MI_VENC_SetChnAttr(pstVencattr->vencChn, &stChnAttr), MI_SUCCESS); } else printf("port %d, venc buse %d \n", s32Portid, pstVencattr->bUsed); } MI_VPE_EnablePort(VpeChn, s32Portid); MI_SYS_ChnPort_t stChnPort; memset(&stChnPort, 0x0, sizeof(MI_SYS_ChnPort_t)); stChnPort.eModId = E_MI_MODULE_ID_VPE; stChnPort.u32DevId = 0; stChnPort.u32ChnId = VpeChn; stChnPort.u32PortId = s32Portid; MI_SYS_SetChnOutputPortDepth(&stChnPort, 1, 4); if(gbPreviewByVenc == TRUE) { if(pstVencattr->bUsed == TRUE) ExecFunc(MI_VENC_StartRecvPic(pstVencattr->vencChn), MI_SUCCESS); ExecFunc(MI_VENC_GetChnDevid(pstVencattr->vencChn, &u32DevId), MI_SUCCESS); stBindInfo.stSrcChnPort.eModId = E_MI_MODULE_ID_VPE; stBindInfo.stSrcChnPort.u32DevId = 0; stBindInfo.stSrcChnPort.u32ChnId = VpeChn; stBindInfo.stSrcChnPort.u32PortId = s32Portid; stBindInfo.stDstChnPort.eModId = E_MI_MODULE_ID_VENC; stBindInfo.stDstChnPort.u32DevId = u32DevId; stBindInfo.stDstChnPort.u32ChnId = pstVencattr->vencChn; stBindInfo.stDstChnPort.u32PortId = 0; stBindInfo.u32SrcFrmrate = 30; stBindInfo.u32DstFrmrate = 30; stBindInfo.eBindType = pstVencattr->eBindType; stBindInfo.u32BindParam = pstVencattr->u32BindParam; STCHECKRESULT(ST_Sys_Bind(&stBindInfo)); } return 0; } MI_BOOL ST_DoSetChnCrop(MI_U32 u32SensorNum) { MI_S32 s32ChannelCropX =0, s32ChannelCropY=0,s32ChannelCropW=0,s32ChannelCropH =0; MI_SYS_WindowRect_t stVpeChnCrop; memset(&stVpeChnCrop, 0x0, sizeof(MI_SYS_WindowRect_t)); MI_U32 VpeChn =0; if(u32SensorNum > 1) { printf("select channel id:"); scanf("%d", &VpeChn); ST_Flush(); if(VpeChn >= ST_MAX_SENSOR_NUM) { printf("VpeChn %d > max %d \n", VpeChn, ST_MAX_SENSOR_NUM); return 0; } } else { VpeChn = 0; } ST_VpeChannelAttr_t *pstVpeChnattr = &gstVpeChnattr[VpeChn]; printf("Channel Crop x:"); scanf("%d", &s32ChannelCropX); ST_Flush(); printf("Channel Crop y:"); scanf("%d", &s32ChannelCropY); ST_Flush(); printf("Channel Crop width:"); scanf("%d", &s32ChannelCropW); ST_Flush(); printf("Channel Crop height:"); scanf("%d", &s32ChannelCropH); ST_Flush(); pstVpeChnattr->stOrgVpeChnCrop.u16X = s32ChannelCropX; pstVpeChnattr->stOrgVpeChnCrop.u16Y = s32ChannelCropY; pstVpeChnattr->stOrgVpeChnCrop.u16Width = s32ChannelCropW; pstVpeChnattr->stOrgVpeChnCrop.u16Height = s32ChannelCropH; if(pstVpeChnattr->eVpeRotate == E_MI_SYS_ROTATE_90 || pstVpeChnattr->eVpeRotate == E_MI_SYS_ROTATE_270) { stVpeChnCrop.u16X = pstVpeChnattr->stOrgVpeChnCrop.u16Y; stVpeChnCrop.u16Y = pstVpeChnattr->stOrgVpeChnCrop.u16X; stVpeChnCrop.u16Width = pstVpeChnattr->stOrgVpeChnCrop.u16Height; stVpeChnCrop.u16Height = pstVpeChnattr->stOrgVpeChnCrop.u16Width; } else { stVpeChnCrop.u16X = pstVpeChnattr->stOrgVpeChnCrop.u16X; stVpeChnCrop.u16Y = pstVpeChnattr->stOrgVpeChnCrop.u16Y; stVpeChnCrop.u16Width = pstVpeChnattr->stOrgVpeChnCrop.u16Width; stVpeChnCrop.u16Height = pstVpeChnattr->stOrgVpeChnCrop.u16Height; } MI_VPE_SetChannelCrop(VpeChn,&stVpeChnCrop); return 0; } MI_BOOL ST_DoSetChnZoom(MI_U32 u32SensorNum) { float r = 16.0/9; MI_U16 ystep = 8; MI_U16 xstep =ALIGN_UP((MI_U16)(r*ystep), 2); int oriW = 0, oriH = 0; MI_SYS_WindowRect_t stCropInfo; MI_VIF_ChnPortAttr_t stVifPortInfo; MI_U32 u32SleepTimeUs = 0; MI_U32 u32Fps =0; MI_S32 s32ZoomPosition = 0; MI_S32 s32PortZoom = 0; MI_BOOL bZoomDone = TRUE; memset(&stVifPortInfo, 0x0, sizeof(MI_VIF_ChnPortAttr_t)); memset(&stCropInfo, 0, sizeof(MI_SYS_WindowRect_t)); MI_U32 VpeChn =0; if(u32SensorNum > 1) { printf("select channel id:"); scanf("%d", &VpeChn); ST_Flush(); if(VpeChn >= ST_MAX_SENSOR_NUM) { printf("VpeChn %d > max %d \n", VpeChn, ST_MAX_SENSOR_NUM); return 0; } } else { VpeChn = 0; } MI_U32 u32VifDev = VpeChn; MI_U32 u32VifChn = u32VifDev*4; MI_SNR_PAD_ID_e eSnrPadId = E_MI_SNR_PAD_ID_0; if(u32VifDev == 0) eSnrPadId = E_MI_SNR_PAD_ID_0; else if(u32VifDev == 2) eSnrPadId = E_MI_SNR_PAD_ID_1; else DBG_ERR("VIF DEV ERR %d \n", u32VifDev); MI_VIF_GetChnPortAttr(u32VifChn,0,&stVifPortInfo); oriW = stVifPortInfo.stCapRect.u16Width; oriH = stVifPortInfo.stCapRect.u16Height; MI_SNR_GetFps(eSnrPadId, &u32Fps); u32SleepTimeUs = 1000000/u32Fps; printf("fps %d, sleeptime %d \n", u32Fps, u32SleepTimeUs); printf("set zoom position: 1.vif, 2.vpe isp dma, 3.vpe scl pre-crop"); scanf("%d", &s32ZoomPosition); ST_Flush(); if(s32ZoomPosition == 3) { printf("select which port zoom: 0:port0, 1:port1, 2:port2, 3: all port \n"); scanf("%d", &s32PortZoom); ST_Flush(); } while(1) { if(bZoomDone == TRUE) { stCropInfo.u16X += xstep; stCropInfo.u16Y += ystep; stCropInfo.u16Width = oriW - (2 * stCropInfo.u16X); stCropInfo.u16Height = oriH -(2 * stCropInfo.u16Y); stCropInfo.u16Width = ALIGN_UP(stCropInfo.u16Width, 2); stCropInfo.u16Height = ALIGN_UP(stCropInfo.u16Height, 2); if(stCropInfo.u16Width < 660 || stCropInfo.u16Height < 360) { bZoomDone = FALSE; } } else { stCropInfo.u16X -= xstep; stCropInfo.u16Y -= ystep; stCropInfo.u16Width = oriW - (2 * stCropInfo.u16X); stCropInfo.u16Height = oriH -(2 * stCropInfo.u16Y); stCropInfo.u16Width = ALIGN_UP(stCropInfo.u16Width, 2); stCropInfo.u16Height = ALIGN_UP(stCropInfo.u16Height, 2); if(stCropInfo.u16Width > oriW || stCropInfo.u16Height > oriH) { break; } } if(s32ZoomPosition == 1) { MI_VIF_ChnPortAttr_t stChnPortAttr; ExecFunc(MI_VIF_GetChnPortAttr(u32VifChn, 0, &stChnPortAttr), MI_SUCCESS); memcpy(&stChnPortAttr.stCapRect, &stCropInfo, sizeof(MI_SYS_WindowRect_t)); stChnPortAttr.stDestSize.u16Width = stCropInfo.u16Width; stChnPortAttr.stDestSize.u16Height = stCropInfo.u16Height; ExecFunc(MI_VIF_SetChnPortAttr(u32VifChn, 0, &stChnPortAttr), MI_SUCCESS); } else if(s32ZoomPosition == 2) { STCHECKRESULT(MI_VPE_SetChannelCrop(VpeChn, &stCropInfo)); STCHECKRESULT(MI_VPE_GetChannelCrop(VpeChn, &stCropInfo)); } else if(s32ZoomPosition == 3) { if(s32PortZoom == 3) { MI_VPE_SetPortCrop(VpeChn, 0, &stCropInfo); MI_VPE_SetPortCrop(VpeChn, 1, &stCropInfo); MI_VPE_SetPortCrop(VpeChn, 2, &stCropInfo); } else MI_VPE_SetPortCrop(VpeChn, s32PortZoom, &stCropInfo); } printf("after crop down x:%d y:%d w:%d h:%d\n", stCropInfo.u16X, stCropInfo.u16Y, stCropInfo.u16Width, stCropInfo.u16Height); //ST_Flush(); usleep(u32SleepTimeUs); } return 0; } MI_BOOL ST_DoSetPortCrop(MI_U32 u32SensorNum) { MI_S32 s32Portid = 0; MI_S32 s32PortCropX =0, s32PortCropY=0,s32PortCropW=0,s32PortCropH =0; MI_SYS_WindowRect_t stPortCropSize; memset(&stPortCropSize, 0x0, sizeof(MI_SYS_WindowRect_t)); MI_U32 VpeChn =0; if(u32SensorNum > 1) { printf("select channel id:"); scanf("%d", &VpeChn); ST_Flush(); if(VpeChn >= ST_MAX_SENSOR_NUM) { printf("VpeChn %d > max %d \n", VpeChn, ST_MAX_SENSOR_NUM); return 0; } } else { VpeChn = 0; } ST_VpeChannelAttr_t *pstVpeChnattr = &gstVpeChnattr[VpeChn]; ST_VpePortAttr_t *pstVpePortAttr = pstVpeChnattr->stVpePortAttr; printf("select port id:"); scanf("%d", &s32Portid); ST_Flush(); if(s32Portid >= ST_MAX_PORT_NUM || pstVpePortAttr[s32Portid].bUsed != TRUE) { printf("port %d, not valid \n", s32Portid); return 0; } printf("port %d port crop x:", s32Portid); scanf("%d", &s32PortCropX); ST_Flush(); printf("port %d port crop y:", s32Portid); scanf("%d", &s32PortCropY); ST_Flush(); printf("port %d port crop width:", s32Portid); scanf("%d", &s32PortCropW); ST_Flush(); printf("port %d port crop height:", s32Portid); scanf("%d", &s32PortCropH); ST_Flush(); pstVpePortAttr[s32Portid].stOrigPortCrop.u16X = s32PortCropX; pstVpePortAttr[s32Portid].stOrigPortCrop.u16Y = s32PortCropY; pstVpePortAttr[s32Portid].stOrigPortCrop.u16Width = s32PortCropW; pstVpePortAttr[s32Portid].stOrigPortCrop.u16Height = s32PortCropH; if(pstVpeChnattr->eVpeRotate == E_MI_SYS_ROTATE_90 || pstVpeChnattr->eVpeRotate == E_MI_SYS_ROTATE_270) { stPortCropSize.u16X = pstVpePortAttr[s32Portid].stOrigPortCrop.u16Y; stPortCropSize.u16Y = pstVpePortAttr[s32Portid].stOrigPortCrop.u16X; stPortCropSize.u16Width = pstVpePortAttr[s32Portid].stOrigPortCrop.u16Height; stPortCropSize.u16Height = pstVpePortAttr[s32Portid].stOrigPortCrop.u16Width; } else { stPortCropSize.u16X = pstVpePortAttr[s32Portid].stOrigPortCrop.u16X; stPortCropSize.u16Y = pstVpePortAttr[s32Portid].stOrigPortCrop.u16Y; stPortCropSize.u16Width = pstVpePortAttr[s32Portid].stOrigPortCrop.u16Width; stPortCropSize.u16Height = pstVpePortAttr[s32Portid].stOrigPortCrop.u16Height; } MI_VPE_SetPortCrop(VpeChn , s32Portid, &stPortCropSize); return 0; } int main(int argc, char **argv) { MI_U8 i = 0, j=0; MI_SNR_PAD_ID_e eSnrPad = E_MI_SNR_PAD_ID_0; MI_U32 u32SensorNum = 0; gstSensorAttr[0].u32BindVifDev = 0; gstSensorAttr[1].u32BindVifDev = 2; if(argc > 1 && argc < 5) { for(i=0; i<argc-1;i++) { gstSensorAttr[i].bUsed = (MI_BOOL)atoi(argv[i+1]); } for(i=0; i<ST_MAX_SENSOR_NUM; i++) { gstVifAttr[i].eBindType = E_MI_SYS_BIND_TYPE_FRAME_BASE; gstVifAttr[i].eWorkMode = E_MI_VIF_WORK_MODE_RGB_FRAMEMODE; gstVifAttr[i].u32BindVpeChan = i; gstVpeChnattr[i].eRunningMode = E_MI_VPE_RUN_CAM_MODE; for(j=0; j< ST_MAX_PORT_NUM; j++) { gstVpeChnattr[i].stVpePortAttr[j].u32BindVencChan = i*ST_MAX_PORT_NUM + j; } } } else if(argc == 1) { gstSensorAttr[0].bUsed = TRUE; gstVifAttr[0].eBindType = E_MI_SYS_BIND_TYPE_REALTIME; gstVifAttr[0].eWorkMode = E_MI_VIF_WORK_MODE_RGB_REALTIME; gstVifAttr[0].u32BindVpeChan = 0; gstVpeChnattr[0].eRunningMode = E_MI_VPE_RUN_REALTIME_MODE; for(j=0; j< ST_MAX_PORT_NUM; j++) { gstVpeChnattr[0].stVpePortAttr[j].u32BindVencChan = j; } } else { printf("realtime ./prog_vpe, frame mode ./prog_vpe 1 0 0, which sensor use \n"); } u32SensorNum = argc-1; for(i=0; i<ST_MAX_SENSOR_NUM; i++) { if(gstSensorAttr[i].bUsed == TRUE) ST_SetArgs(i); } for(i=0; i<ST_MAX_SENSOR_NUM; i++) { if(gstSensorAttr[i].bUsed == TRUE) { eSnrPad = (MI_SNR_PAD_ID_e)i; MI_VIF_DEV vifDev = gstSensorAttr[eSnrPad].u32BindVifDev; MI_VPE_CHANNEL vpechn = gstVifAttr[vifDev].u32BindVpeChan; STCHECKRESULT(ST_BaseModuleInit(eSnrPad)); if(gbPreviewByVenc == TRUE) { ST_VpeChannelAttr_t *pstVpeChnattr = &gstVpeChnattr[vpechn]; MI_U32 u32MaxWidth =0, u32MaxHeight =0; if(pstVpeChnattr->eVpeRotate == E_MI_SYS_ROTATE_90 || pstVpeChnattr->eVpeRotate == E_MI_SYS_ROTATE_270) { u32MaxWidth = 2160; u32MaxHeight = 3840; } else { u32MaxWidth = 3840; u32MaxHeight = 2160; } STCHECKRESULT(ST_VencStart(u32MaxWidth,u32MaxHeight, vpechn)); } } } ST_RtspServerStart(); #if 0 pthread_t pIQthread; pthread_create(&pIQthread, NULL, ST_IQthread, NULL); #endif //pthread_t pSenVpeDatathread; //pthread_create(&pSenVpeDatathread, NULL, ST_SendVpeBufthread, NULL); if(gbPreviewByVenc == FALSE) { MI_U8 u8PortId[ST_MAX_SENSOR_NUM*ST_MAX_PORT_NUM]; for(j=0; j< ST_MAX_SENSOR_NUM; j++) { for(i=0; i< ST_MAX_PORT_NUM; i++) { u8PortId[j*ST_MAX_SENSOR_NUM+i] = j*ST_MAX_SENSOR_NUM+i; pthread_mutex_init(&gstVpeChnattr[j].stVpePortAttr[i].Portmutex, NULL); pthread_create(&gstVpeChnattr[j].stVpePortAttr[i].pGetDatathread, NULL, ST_GetVpeOutputDataThread, (void *)(&u8PortId[i])); } } } for(i=0; i<ST_MAX_SENSOR_NUM; i++) { if(gstSensorAttr[i].bUsed == TRUE) { eSnrPad = (MI_SNR_PAD_ID_e)i; MI_SNR_PlaneInfo_t stSnrPlane0Info; memset(&stSnrPlane0Info, 0x0, sizeof(MI_SNR_PlaneInfo_t)); MI_SNR_GetPlaneInfo(eSnrPad, 0, &stSnrPlane0Info); MI_IQSERVER_Open(stSnrPlane0Info.stCapRect.u16Width, stSnrPlane0Info.stCapRect.u16Height, 0); } } while(!bExit) { MI_U32 u32Select = 0xff; printf("select 0: change res \n"); printf("select 1: change hdrtype\n"); printf("select 2: change rotate\n"); printf("select 3: change chancrop\n"); printf("select 4: change portMode\n"); printf("select 5: change portcrop\n"); printf("select 6: Get port buffer\n"); printf("select 7: disable port \n"); printf("select 8: get venc out \n"); printf("select 9: Ldc on/off \n"); printf("select 10: vpe chn zoom\n"); printf("select 11: exit\n"); scanf("%d", &u32Select); ST_Flush(); if(u32Select == 0) bExit = ST_DoChangeRes(u32SensorNum); else if(u32Select == 1) { bExit = ST_DoChangeHDRtype(); } else if(u32Select == 2) { bExit =ST_DoChangeRotate(u32SensorNum); } else if(u32Select == 3) { bExit =ST_DoSetChnCrop(u32SensorNum); } else if(u32Select == 4) { bExit =ST_ResetPortMode(u32SensorNum); } else if(u32Select == 5) { bExit =ST_DoSetPortCrop(u32SensorNum); } else if(u32Select == 6) { bExit =ST_GetVpeOutputData(u32SensorNum); } else if(u32Select == 7) { bExit =ST_VpeDisablePort(u32SensorNum); } else if(u32Select == 8) { bExit =ST_GetVencOut(); } else if(u32Select == 9) { bExit =ST_SetLdcOnOff(u32SensorNum); } else if(u32Select == 10) { bExit =ST_DoSetChnZoom(u32SensorNum); } else if(u32Select == 11) { bExit = TRUE; } usleep(100 * 1000); } usleep(100 * 1000); if(gbPreviewByVenc == FALSE) { for(j=0; j< ST_MAX_SENSOR_NUM; j++) { for(i=0; i< ST_MAX_PORT_NUM; i++) { void *retarg = NULL; pthread_cancel(gstVpeChnattr[j].stVpePortAttr[i].pGetDatathread); pthread_join(gstVpeChnattr[j].stVpePortAttr[i].pGetDatathread, &retarg); } for(i=0; i< ST_MAX_PORT_NUM; i++) { pthread_mutex_destroy(&gstVpeChnattr[j].stVpePortAttr[i].Portmutex); } } } ST_RtspServerStop(); for(i=0; i<ST_MAX_SENSOR_NUM; i++) { if(gstSensorAttr[i].bUsed == TRUE) { eSnrPad = (MI_SNR_PAD_ID_e)i; MI_VIF_DEV vifDev = gstSensorAttr[eSnrPad].u32BindVifDev; MI_VPE_CHANNEL vpechn = gstVifAttr[vifDev].u32BindVpeChan; if(gbPreviewByVenc == TRUE) { STCHECKRESULT(ST_VencStop(vpechn)); } STCHECKRESULT(ST_BaseModuleUnInit(eSnrPad)); } } memset(&gstSensorAttr, 0x0, sizeof(gstSensorAttr)); memset(&gstVifAttr, 0x0, sizeof(gstVifAttr)); memset(&gstVpeChnattr, 0x0, sizeof(gstVpeChnattr)); memset(&gstVencattr, 0x0, sizeof(gstVencattr)); return 0; }
6292c448cb2d02c252c06d1c449d9574ed567697
81041c13fcb8d0d9cbd46b018d72c77dd0400429
/exception/cFileExce.h
10ea0614817ac583ca52e5e6cfdddcc7da511358
[]
no_license
degawang/degawong
0c49feb10941ed915fa6cfe3677b85d3baf8fb36
64e20912fc3e8c4dae58a14b097cc8ec1b052365
refs/heads/master
2021-09-17T19:32:48.017411
2018-07-04T14:33:05
2018-07-04T14:33:05
null
0
0
null
null
null
null
UTF-8
C++
false
false
575
h
#pragma once #include "cDegaException.h" namespace degawong { class cFileExce : public cDegaException { public: cFileExce(); cFileExce(std::string _fileReason) : exceReason(_fileReason) {}; ~cFileExce(); public: friend std::istream& operator >> (std::istream& is, cFileExce &exce) { is >> exce.exceReason; return is; }; friend std::ostream& operator << (std::ostream& os, const cFileExce &exce) { os << exce.what() << std::endl; return os; }; public: inline std::string what() const { return exceReason; } private: std::string exceReason; }; }
0a0893e0d653780a1c0a7ac24d780cd30093a535
f37a800cd831b948949ecc054c5be2aac87b4331
/lab6-sound/tinyos/support/cpp/ali/ACP/main.cpp
e4df1e401597a08f4175046af2e200a9bfe01a34
[]
no_license
ChenchengLiang/Practical-Course-on-WSNs-Lab-WS16-17
e1f3018900cecaa49731163b3f3ff79a50321c5b
c7f2573ad558c514d6d6985cd78c6131e74db04d
refs/heads/master
2020-03-31T10:40:51.605436
2018-10-08T20:48:24
2018-10-08T20:48:24
null
0
0
null
null
null
null
UTF-8
C++
false
false
8,571
cpp
/** Copyright (c) 2010, University of Szeged * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * - Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * - Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * - Neither the name of University of Szeged nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. * * Author: Ali Baharev */ #include <fstream> #include <iostream> #include <iomanip> #include <cstdlib> #include <cstdio> #include <string> #include <sstream> #include <list> #include <vector> #include <cassert> using namespace std; namespace { const int N_FIELDS = 10; typedef unsigned short uint16; typedef unsigned int uint32; const uint32 TICKS_PER_SEC = 32768; const uint32 SAMPLING_RATE = 160; const uint32 TOLERANCE = 4; struct dat { uint32 time; uint16 counter; uint16 ax; uint16 ay; uint16 az; uint16 wx; uint16 wy; uint16 wz; uint16 volt; uint16 temp; }; const char header[] = "Time,sequence_number,Accel_X,Accel_Y,Accel_Z,Gyro_X,Gyro_Y,Gyro_Z,Volt,Temp"; vector<list<dat>*> data; typedef list<dat>::const_iterator cli; typedef list<dat>::reverse_iterator rli; } void exit(const string& msg) { cout << "Error: " << msg << "!" << endl; exit(1); } const string int2string(const int i) { ostringstream os; os << i << flush; return os.str(); } const string time2str(uint32 t) { ostringstream os; uint32 hour, min, sec, milli; hour = t/(3600*TICKS_PER_SEC); t = t%(3600*TICKS_PER_SEC); min = t/(60*TICKS_PER_SEC); t = t%(60*TICKS_PER_SEC); sec = t/TICKS_PER_SEC; t = t%TICKS_PER_SEC; milli = t/(TICKS_PER_SEC/1000.0); os << setfill('0') << setw(2) << hour << ":"; os << setfill('0') << setw(2) << min << ":"; os << setfill('0') << setw(2) << sec << "."; os << setfill('0') << setw(3) << milli<< flush; return os.str(); } bool str2ticks(uint32& ticks, const uint32 max) { uint32 hour, min, sec; string sh; string sm; string ss; getline(cin, sh, ':'); getline(cin, sm, ':'); getline(cin, ss); hour = atoi(sh.c_str()); min = atoi(sm.c_str()); sec = atoi(ss.c_str()); if ((hour<0 || hour>99) || (min<0 || min>59) || (sec<0 || sec>59)) { cout << "Error: incorrect format for time string" << endl; ticks = 0; return true; } ticks = (3600*TICKS_PER_SEC)*hour + (60*TICKS_PER_SEC)*min + TICKS_PER_SEC*sec; if (ticks > max) { cout << "Error: the entered time is greater that the length!" << endl; return true; } return false; } void check_data_consistency(const dat& b, uint32 lines, uint32 prevTime, uint16 prevCnt) { uint16 cnt = b.counter; if (!((cnt-prevCnt == 1) || (cnt==0 && prevCnt==0xFFFF))) { cout << "Warning: line " << lines << flush; cout << ", missing " << (cnt-prevCnt-1) << " samples" << endl; } uint32 expected = prevTime + SAMPLING_RATE; int dt = b.time - expected; if (abs(dt) > TOLERANCE) { cout << "Warning: line " << lines << flush; cout << ", " << dt << " ticks error" << endl; } } void allocate_container(list<dat>*& samples, const dat& b, uint32& t0, uint32 lines) { cout << "Found a re-boot on line " << lines << endl; samples = new list<dat>(); data.push_back(samples); t0 = b.time; } void print_info() { const int n = static_cast<int> (data.size()); cout << n << " measurements" << endl; for (int i=0; i<n; ++i) { list<dat>* samples = data.at(i); rli rbeg(samples->rbegin()); cout << "Length of #" << (i+1) << " is "<< time2str(rbeg->time) << endl; } } void grab_content(const char* filename) { FILE* in = fopen(filename, "r"); if (!in) { exit("failed to open input file"); } cout << "Reading file " << filename << endl; //========================================================================== char first_line[sizeof(header)]; fgets(first_line, sizeof(first_line), in); if (string(header)!=first_line) { exit("wrong file format"); } //========================================================================== const int m = static_cast<int> (data.size()); for (int i=0; i<m; ++i) { delete data.at(i); } data.clear(); //========================================================================== const char* fmt = "%u,%hu,%hu,%hu,%hu,%hu,%hu,%hu,%hu,%hu"; uint32 lines = 1; dat b; int n; uint16 prevCnt = 1; uint32 prevTime = 0; list<dat>* samples = 0; uint32 t0 = 0; //========================================================================== while ( (!ferror(in)) && (!feof(in)) ) { n = fscanf(in,fmt,&b.time,&b.counter,&b.ax,&b.ay,&b.az,&b.wx, &b.wy, &b.wz, &b.volt,&b.temp); ++lines; if (n!= N_FIELDS) { cout << "Conversion failed on line " << lines << endl; break; } if (b.time==0 && b.counter==0) { cout << "Warning: found a line with zeros, at " << lines; cout << ", reading stopped!" << endl; break; } if (b.counter == 1 && prevCnt != 0) { allocate_container(samples, b, t0, lines); } else { check_data_consistency(b, lines, prevTime, prevCnt); } prevTime = b.time; prevCnt = b.counter; b.time -= t0; samples->push_back(b); } cout << "Read " << lines << endl; fclose(in); in = 0; } void dump_data(const char* filename, int index, uint32 start, uint32 end) { const list<dat>* const samples = data.at(index-1); cli i(samples->begin()); while (i!=samples->end() && i->time < start) { ++i; } ostringstream os; os << filename << '_' << index << '_' << start << '_' << end << flush; ofstream out(os.str().c_str()); if (!out) { exit("failed to create output file"); } out << "#" << header << ",RotMat[9]" << endl; uint32 lines = 0; while (i!=samples->end() && i->time <= end) { dat b = *i; // b.counter removed, currently not supported in TestShimmer out << b.time << ',' << b.ax << ',' << b.ay << ',' << b.az; out << ',' << b.wx << ',' << b.wy << ',' << b.wz << ',' << b.volt << ',' << b.temp ; out << ',' << 1 << ',' << 0 << ',' << 0; out << ',' << 0 << ',' << 1 << ',' << 0; out << ',' << 0 << ',' << 0 << ',' << 1; out << endl; ++i; ++lines; } out.close(); cout << lines << " lines written" << endl; } int main(int argc, char* argv[]) { if (argc!=2) { exit("specify input file"); } const char* filename = argv[1]; grab_content(filename); print_info(); while (true) { print_info(); cout << "Select measurement (or -1 to quit): " << flush; int n = 0; cin >> n; if (n==-1) { break; } else if (n < 1 || n > static_cast<int> (data.size())) { cout << "Error: " << n << " is out of range (" << flush; cout << 1 << ", " << data.size() << ")" << endl; continue; } const uint32 ticks = data.at(n-1)->rbegin()->time; cout << "Length of #" << n << " is "<< flush; cout << time2str(ticks) << endl; cout << "Enter start in hh:mm:ss format" << endl; uint32 start; if (str2ticks(start, ticks)) continue; cout << "Enter end in hh:mm:ss format" << endl; uint32 end; if (str2ticks(end, ticks)) continue; if (start >= end) { cout << "Error: start must be before end!" << endl; continue; } cout << "Cropping from " << time2str(start) << " to " << time2str(end) << endl; cout << "Check the time strings, are they OK? [y,n]" << endl; char c = cin.get(); if (c!='y') continue; cout << "Writing cropped file" << endl; dump_data(filename, n, start, end); } cout << "Terminated ..." << endl; return 0; }
e4a9c8ca91f878dc313aee2aad48a546408124a7
e926db4dab0237aaae30a539b5f69ad37b195091
/scale_puzzle/src/scale_puzzle/scale_puzzle.ino
5c0c60e108742a4fd7256aae18f04fe23cae34eb
[]
no_license
ubilab-escape/prototype
6b4fca4f3d1820278a3d7847f3ef2daed9c7af0f
a673625ef53867bb029d6ddc2312c830b2f05bfa
refs/heads/master
2020-08-26T20:52:12.852255
2020-02-29T21:34:13
2020-02-29T21:34:13
217,144,860
0
0
null
null
null
null
UTF-8
C++
false
false
18,400
ino
#include <Arduino.h> #include <ESP8266WiFi.h> /* define keepalive settings before PubSubClient.h */ #define MQTT_KEEPALIVE 10 #include <PubSubClient.h> #include <ArduinoJson.h> #include "HX711.h" #include "scale_puzzle.h" #include "wifi_pw.h" /* uncomment to activate debug mode */ //#define DEBUG /* State machine variables */ ScalePuzzle_HandlerType ScaleStruct; /* Scale variables */ HX711 scale; const long scale_divider = 7000; const int LOADCELL_DOUT_PIN = 13; const int LOADCELL_SCK_PIN = 12; const int LED_GREEN = 0; const int LED_RED = 5; /* WiFi, Mqtt variables */ WiFiClient espClient; PubSubClient client(espClient); StaticJsonDocument<300> rxdoc; /* MQTT Topics */ const char* Safe_activate_topic = "5/safe/control"; const char* Mqtt_topic = "6/puzzle/scale"; const char* Mqtt_terminal = "6/puzzle/terminal"; /* MQTT Messages */ const char* Msg_inactive = "{\"method\": \"status\", \"state\": \"inactive\"}"; const char* Msg_active = "{\"method\": \"status\", \"state\": \"active\"}"; const char* Msg_solved = "{\"method\":\"status\",\"state\":\"solved\"}"; const char* Msg_green = "{\"method\":\"trigger\",\"state\":\"on\",\"data\":\"2:0\"}"; // Constant green const char* Msg_red = "{\"method\":\"trigger\",\"state\":\"on\",\"data\":\"1:3\"}"; // Blinking red const char* Msg_orange = "{\"method\":\"trigger\",\"state\":\"on\",\"data\":\"4:3\"}"; // Blinking orange /* Arduino main functions */ void setup() { #ifdef DEBUG Serial.begin(115200); delay(3000); Serial.println(); #endif scale.begin(LOADCELL_DOUT_PIN, LOADCELL_SCK_PIN); scale.set_scale(scale_divider); } void loop() { /* scale puzzle state machine */ switch (ScaleStruct.state) { case INIT: InitScalePuzzleStructure(); debug_print(String(ScaleStruct.state)); ScaleStruct.state = WIFI_SETUP; wifi_set_sleep_type(NONE_SLEEP_T); break; case WIFI_SETUP: if (wifi_setup() != false) { delay(500); ScaleStruct.connection_check_counter = 0; debug_print(String(ScaleStruct.state)); ScaleStruct.state = MQTT_SETUP; } break; case MQTT_SETUP: if (mqtt_setup() != false) { delay(500); debug_print(String(ScaleStruct.state)); ScaleStruct.state = MQTT_CONNECT; } break; case MQTT_CONNECT: if (mqtt_connect() != false) { delay(500); ScaleStruct.mqtt_connected = true; debug_print(String(ScaleStruct.state)); ScaleStruct.state = PUZZLE_START; } break; case PUZZLE_START: ReInitScalePuzzleStructure(); debug_print(String(ScaleStruct.state)); ScaleStruct.state = SCALE_CALIBRATION; break; case SCALE_CALIBRATION: if (calibration_setup() != false) { debug_print(String(ScaleStruct.state)); if (client.publish(Mqtt_topic, Msg_inactive, true) != false) { ScaleStruct.state = WAIT_FOR_BEGIN; } } break; case WAIT_FOR_BEGIN: if (ScaleStruct.puzzle_start != false) { debug_print(String(ScaleStruct.state)); ScaleStruct.state = SCALE_GREEN; } break; case SCALE_GREEN: if (is_scale_unbalanced() != false) { debug_print(String(ScaleStruct.state)); if (client.publish(Mqtt_topic, Msg_active, true) != false) { ScaleStruct.state = SCALE_RED; } } break; case SCALE_RED: if (is_scale_balanced() != false) { debug_print(String(ScaleStruct.state)); if (client.publish(Mqtt_topic, Msg_inactive, true) != false) { ScaleStruct.state = SCALE_GREEN; } } break; case PUZZLE_SOLVED: if (client.publish(Mqtt_topic, Msg_solved, true) != false) { set_safe_color(LED_STATE_GREEN); ScaleStruct.puzzle_solved = false; debug_print(String(ScaleStruct.state)); ScaleStruct.state = WAIT_FOR_RESTART; } break; case WAIT_FOR_RESTART: if (ScaleStruct.puzzle_restart != false) { debug_print(String(ScaleStruct.state)); ScaleStruct.state = RESTART; } break; case MQTT_LOST: if (mqtt_connect() != false) { debug_print(String(ScaleStruct.state)); ScaleStruct.state = ScaleStruct.reconnect_state; } else { ScaleStruct.mqtt_connected = false; } break; case WIFI_LOST: WiFi.disconnect(); debug_print(String(ScaleStruct.state)); ScaleStruct.state = INIT; break; case ERROR_STATE: WiFi.disconnect(); debug_print(String(ScaleStruct.state)); ScaleStruct.state = INIT; break; case RESTART: debug_print(String(ScaleStruct.state)); ScaleStruct.state = PUZZLE_START; break; default: break; } /* puzzle solved trigger or skip puzzle trigger arrived */ if ((ScaleStruct.puzzle_solved != false) && (ScaleStruct.puzzle_restart == false)) { ScaleStruct.state = PUZZLE_SOLVED; } /* restart trigger arrived */ if ((ScaleStruct.puzzle_solved == false) && (ScaleStruct.puzzle_restart != false)) { ScaleStruct.puzzle_restart = false; ScaleStruct.state = RESTART; } /* restart if both triggers are sent */ if ((ScaleStruct.puzzle_solved != false) && (ScaleStruct.puzzle_restart != false)) { ScaleStruct.state = RESTART; ScaleStruct.puzzle_solved = false; ScaleStruct.puzzle_restart = false; } /* run mqtt handling */ if (ScaleStruct.mqtt_connected != false) { client.loop(); } delay(100); /* run wifi and mqtt checks approx. every 5s */ if (ScaleStruct.connection_check_counter > 49) { if ((ScaleStruct.state > WIFI_SETUP) && (ScaleStruct.state < WIFI_LOST) && (WiFi.status() != WL_CONNECTED)) { ScaleStruct.state = WIFI_LOST; debug_print("WIFI LOST"); } if ((ScaleStruct.state > MQTT_CONNECT) && (ScaleStruct.state < MQTT_LOST) && (client.state() != 0)){ ScaleStruct.reconnect_state = ScaleStruct.state; ScaleStruct.state = MQTT_LOST; } ScaleStruct.connection_check_counter = 0; } ScaleStruct.connection_check_counter += 1; } /* State Machine functions */ /***************************************************************************************** FUNCTION INFO NAME: InitScalePuzzleStructure DESCRIPTION: Initialization function to initialize the Scale Puzzle Structure. To call at every startup of the device. *****************************************************************************************/ void InitScalePuzzleStructure(void) { ScaleStruct.state = INIT; ScaleStruct.mqtt_connected = false; ScaleStruct.connection_check_counter = 0; ScaleStruct.scale_failure = 0; ReInitScalePuzzleStructure(); } /***************************************************************************************** FUNCTION INFO NAME: ReInitScalePuzzleStructure DESCRIPTION: Initialization function to reinitialize the Scale Puzzle Structure. To call at every restart of the puzzle. *****************************************************************************************/ void ReInitScalePuzzleStructure(void) { ScaleStruct.reconnect_state = ERROR_STATE; ScaleStruct.led_state = LED_STATE_GREEN; ScaleStruct.puzzle_start = false; ScaleStruct.led_control = false; ScaleStruct.puzzle_solved = false; ScaleStruct.puzzle_restart = false; } /***************************************************************************************** FUNCTION INFO NAME: wifi_setup DESCRIPTION: Connect to the given WiFi. For the password create a file named wifi_pw.h and define a variable "const char* PASSWORD" containing the password. *****************************************************************************************/ bool wifi_setup(void) { bool wifi_finished = false; const char* ssid = "ubilab_wifi"; const char* pw = PASSWORD; WiFi.begin(ssid, pw); while (WiFi.status() != WL_CONNECTED) { delay(500); #ifdef DEBUG Serial.print("."); #endif if (WiFi.status() == WL_CONNECTED) { wifi_finished = true; delay(500); debug_print(String("Connection status: " + String(WiFi.status()))); delay(500); debug_print("Connected, IP address: "); debug_print(WiFi.localIP().toString()); } else { delay(500); } } return wifi_finished; } /***************************************************************************************** FUNCTION INFO NAME: mqtt_setup DESCRIPTION: Submits the MQTT connection with the specified IP address and MQTT server port to the MQTT client. Submits the callback function with a given set of messages to the MQTT client. *****************************************************************************************/ bool mqtt_setup(void) { bool mqtt_setup_finished = false; const IPAddress mqttServerIP(10,0,0,2); uint16_t mqtt_server_port = 1883; client.setServer(mqttServerIP, mqtt_server_port); client.setCallback(mqtt_callback); delay(100); debug_print("Keepalive setting:"); debug_print(String(MQTT_KEEPALIVE)); mqtt_setup_finished = true; return mqtt_setup_finished; } /***************************************************************************************** FUNCTION INFO NAME: mqtt_connect DESCRIPTION: Creates a new client ID and connects to the MQTT server. Creates subscriptions to the specified MQTT topics. If no connection is possible, wait 2 seconds before the next try. *****************************************************************************************/ bool mqtt_connect(void) { bool reconnect_finished = false; debug_print("Attempting MQTT connection..."); /* Create a random client ID */ String clientId = "ESP8266Scale-"; clientId += String(random(0xffff), HEX); /* Attempt to connect */ if (client.connect(clientId.c_str())) { debug_print("connected"); /* Subscribe */ client.subscribe(Mqtt_topic); client.subscribe(Mqtt_terminal); reconnect_finished = true; } else { debug_print("failed, rc="); debug_print(String(client.state())); debug_print("try again in 5 seconds"); /* Wait 2 seconds before retrying */ delay(2000); } return reconnect_finished; } /***************************************************************************************** FUNCTION INFO NAME: calibration_setup DESCRIPTION: Tare the scale to the current weight and wait until the scale is ready. *****************************************************************************************/ bool calibration_setup(void) { bool calibration_finished = false; scale.tare(); debug_print("Beginning:"); #ifdef DEBUG pinMode(LED_RED, OUTPUT); pinMode(LED_GREEN, OUTPUT); #endif while (!scale.is_ready()) { Serial.println("Scale is not ready"); delay(100); } calibration_finished = true; return calibration_finished; } /***************************************************************************************** FUNCTION INFO NAME: is_scale_unbalanced DESCRIPTION: Measure the weight on the scale and if a wrong weight is measured, change the color of the safe to red. The measuring process is debounced. *****************************************************************************************/ bool is_scale_unbalanced(void) { bool unbalanced = false; static int red_count = 0; if (scale_measure_floppy_disks() == 0) { red_count = 0; } else { red_count++; if (red_count == RED_DELAY) { debug_led(LED_RED); set_safe_color(LED_STATE_RED); red_count = 0; unbalanced = true; } } return unbalanced; } /***************************************************************************************** FUNCTION INFO NAME: is_scale_balanced DESCRIPTION: Measure the weight on the scale and if the initially tared weight is measured, change the color of the safe to green. The measuring process is debounced. *****************************************************************************************/ bool is_scale_balanced(void) { bool balanced = false; static int old_reading = 4; static int new_reading = 4; static int green_count = 0; /* measure the current weight */ int reading = scale_measure_floppy_disks(); /* compare the last measured value with the current value */ old_reading = new_reading; new_reading = reading; if (old_reading == new_reading) { if (new_reading == 0) { green_count++; if (green_count == GREEN_DELAY) { debug_led(LED_GREEN); set_safe_color(LED_STATE_GREEN); green_count = 0; balanced = true; } } else { green_count = 0; } } else { green_count = 0; } return balanced; } /* Utility Functions */ /***************************************************************************************** FUNCTION INFO NAME: mqtt_callback DESCRIPTION: Evaluates the received MQTT messages. The following messages are processed: Topic: 6/puzzle/scale Messages: trigger on || starts the puzzle trigger off || restarts the puzzle trigger off skipped || skips the puzzle and starts puzzle solved handling Topic: 6/puzzle/terminal Message: status active || sets the puzzle to solved *****************************************************************************************/ void mqtt_callback(char* topic, byte* message, unsigned int length) { debug_print("Message arrived on topic: "); debug_print(topic); debug_print(". Message: "); String messageTemp; for (unsigned int i = 0; i < length; i++) { messageTemp += (char)message[i]; } debug_print(messageTemp); deserializeJson(rxdoc, message); const char* method1 = rxdoc["method"]; const char* state1 = rxdoc["state"]; const char* data1 = rxdoc["data"]; /* If a message is received on the topic 6/puzzle/scale, check the message. */ if (String(topic).equals(Mqtt_topic) != false) { if (String(method1).equals("trigger") != false) { if (String(state1).equals("on") != false) { debug_print("Start Puzzle"); ScaleStruct.puzzle_start = true; ScaleStruct.led_control = true; } else if (String(state1).equals("off") != false){ if (String(data1).equals("skipped") != false) { debug_print("Puzzle Skipped"); ScaleStruct.puzzle_solved = true; } else { debug_print("Restart Puzzle"); ScaleStruct.puzzle_restart = true; } } } } /* If a message is received on the topic 6/puzzle/terminal, check the message. */ if (String(topic).equals(Mqtt_terminal) != false) { if (String(method1).equals("status") != false) { if (String(state1).equals("active") != false) { debug_print("Puzzle Solved"); ScaleStruct.puzzle_solved = true; } } } } /***************************************************************************************** FUNCTION INFO NAME: scale_measure_floppy_disks DESCRIPTION: Measures the weight on the scale. The scale is tared to a certain amount of floppy disks. The amount of floppy disks is returned. If the scale is not reacting for a specific time go to the error state. *****************************************************************************************/ int scale_measure_floppy_disks() { int measure = 0; if (scale.is_ready()) { measure = round(scale.get_units(10)); ScaleStruct.scale_failure = 0; debug_print("Value for known weight is: "); debug_print(String(measure)); } else { debug_print("HX711 not found."); ScaleStruct.scale_failure = ScaleStruct.scale_failure + 1; if (ScaleStruct.scale_failure > 20) { ScaleStruct.state = ERROR_STATE; } delay(500); } return measure; } /***************************************************************************************** FUNCTION INFO NAME: set_safe_color DESCRIPTION: Sends a MQTT message to the safe with a specific color. The colors green, red and orange are possible. *****************************************************************************************/ void set_safe_color(led_state_t color_state){ const char* color_message; if (ScaleStruct.led_control != false) { if ((ScaleStruct.led_state != color_state)) { switch (color_state) { case LED_STATE_GREEN: color_message = Msg_green; break; case LED_STATE_ORANGE: color_message = Msg_orange; break; case LED_STATE_RED: color_message = Msg_red; break; default: color_message = Msg_green; break; } if (client.publish(Safe_activate_topic, color_message, false) != false) { ScaleStruct.led_state = color_state; } } } } /***************************************************************************************** FUNCTION INFO NAME: debug_print DESCRIPTION: Debug function to print messages via serial connection. *****************************************************************************************/ void debug_print(String print_string) { #ifdef DEBUG Serial.println(print_string); #endif } /***************************************************************************************** FUNCTION INFO NAME: debug_led DESCRIPTION: Debug function to connect LEDs to show the current scale status. *****************************************************************************************/ void debug_led(int led_color) { #ifdef DEBUG if (led_color == LED_RED) { digitalWrite(LED_RED, HIGH); digitalWrite(LED_GREEN, LOW); } if (led_color == LED_GREEN) { digitalWrite(LED_RED, LOW); digitalWrite(LED_GREEN, HIGH); } #endif }
b4bacf770bbde397468dac64964b28fbbf6a94f4
b8499de1a793500b47f36e85828f997e3954e570
/v2_3/build/Android/Preview/app/src/main/include/Fuse.NodeGroupBase.h
eb078dfd79ac290e0c6d5d63a1ea4472d3bb8d97
[]
no_license
shrivaibhav/boysinbits
37ccb707340a14f31bd57ea92b7b7ddc4859e989
04bb707691587b253abaac064317715adb9a9fe5
refs/heads/master
2020-03-24T05:22:21.998732
2018-07-26T20:06:00
2018-07-26T20:06:00
142,485,250
0
0
null
2018-07-26T20:03:22
2018-07-26T19:30:12
C++
UTF-8
C++
false
false
3,019
h
// This file was generated based on 'C:/Users/hp laptop/AppData/Local/Fusetools/Packages/Fuse.Nodes/1.9.0/NodeGroup.uno'. // WARNING: Changes might be lost if you edit this file directly. #pragma once #include <Fuse.Behavior.h> #include <Fuse.Binding.h> #include <Fuse.INotifyUnrooted.h> #include <Fuse.IProperties.h> #include <Fuse.ISourceLocation.h> #include <Fuse.Scripting.IScriptObject.h> #include <Fuse.TemplateSourceImpl.h> #include <Uno.Collections.ICollection-1.h> #include <Uno.Collections.IEnumerable-1.h> #include <Uno.Collections.IList-1.h> namespace g{namespace Fuse{struct Node;}} namespace g{namespace Fuse{struct NodeGroupBase;}} namespace g{namespace Uno{namespace Collections{struct RootableList;}}} namespace g{namespace Uno{namespace UX{struct Resource;}}} namespace g{namespace Uno{namespace UX{struct Template;}}} namespace g{ namespace Fuse{ // public abstract class NodeGroupBase :16 // { ::g::Fuse::Node_type* NodeGroupBase_typeof(); void NodeGroupBase__ctor_3_fn(NodeGroupBase* __this, int32_t* flags); void NodeGroupBase__AddContent_fn(NodeGroupBase* __this); void NodeGroupBase__FindTemplate_fn(NodeGroupBase* __this, uString* key, ::g::Uno::UX::Template** __retval); void NodeGroupBase__get_NodeCount_fn(NodeGroupBase* __this, int32_t* __retval); void NodeGroupBase__get_Nodes_fn(NodeGroupBase* __this, uObject** __retval); void NodeGroupBase__OnNodeAdded_fn(NodeGroupBase* __this, ::g::Fuse::Node* n); void NodeGroupBase__OnNodeRemoved_fn(NodeGroupBase* __this, ::g::Fuse::Node* n); void NodeGroupBase__OnResourceAdded_fn(NodeGroupBase* __this, ::g::Uno::UX::Resource* r); void NodeGroupBase__OnResourceRemoved_fn(NodeGroupBase* __this, ::g::Uno::UX::Resource* r); void NodeGroupBase__OnRooted_fn(NodeGroupBase* __this); void NodeGroupBase__OnUnrooted_fn(NodeGroupBase* __this); void NodeGroupBase__RemoveContent_fn(NodeGroupBase* __this); void NodeGroupBase__get_Resources_fn(NodeGroupBase* __this, uObject** __retval); void NodeGroupBase__get_Templates_fn(NodeGroupBase* __this, uObject** __retval); void NodeGroupBase__get_UseContent_fn(NodeGroupBase* __this, bool* __retval); void NodeGroupBase__set_UseContent_fn(NodeGroupBase* __this, bool* value); struct NodeGroupBase : ::g::Fuse::Behavior { uStrong< ::g::Uno::Collections::RootableList*> _nodes; ::g::Fuse::TemplateSourceImpl _templates; bool _useTemplates; bool _useContent; uStrong< ::g::Uno::Collections::RootableList*> _resources; bool _contentAdded; uStrong<uArray*> _addedNodes; void ctor_3(int32_t flags); void AddContent(); ::g::Uno::UX::Template* FindTemplate(uString* key); int32_t NodeCount(); uObject* Nodes(); void OnNodeAdded(::g::Fuse::Node* n); void OnNodeRemoved(::g::Fuse::Node* n); void OnResourceAdded(::g::Uno::UX::Resource* r); void OnResourceRemoved(::g::Uno::UX::Resource* r); void RemoveContent(); uObject* Resources(); uObject* Templates(); bool UseContent(); void UseContent(bool value); }; // } }} // ::g::Fuse
c515a27617525d746053e17e71df5d783b320aab
0eff74b05b60098333ad66cf801bdd93becc9ea4
/second/download/httpd/gumtree/httpd_repos_function_689_httpd-2.2.14.cpp
059621ec5096a4c8c5911be99ef7fb26a21a0b32
[]
no_license
niuxu18/logTracker-old
97543445ea7e414ed40bdc681239365d33418975
f2b060f13a0295387fe02187543db124916eb446
refs/heads/master
2021-09-13T21:39:37.686481
2017-12-11T03:36:34
2017-12-11T03:36:34
null
0
0
null
null
null
null
UTF-8
C++
false
false
111
cpp
static int bio_filter_out_gets(BIO *bio, char *buf, int size) { /* this is never called */ return -1; }
96dce74cc57071dcc14ad9eeb385db0bea59a9d9
8e514382d5844d0208ebba778eab28b0f76a89cd
/src/interface/execution_context.hpp
8c3d60916b4d3bbf3deaf42dcc1cfc7470a6bb0f
[ "MIT" ]
permissive
KhalilBellakrid/ledger-test-library
580255d517f1ab7d4733614339e419b6d081b236
250c9fc992f498360f6396d4ed3ea1bb7637d863
refs/heads/master
2021-05-02T12:58:22.810296
2018-02-16T17:43:14
2018-02-16T17:43:14
120,751,274
0
3
null
2018-02-16T10:29:43
2018-02-08T11:12:46
C++
UTF-8
C++
false
false
453
hpp
// AUTOGENERATED FILE - DO NOT MODIFY! // This file generated by Djinni from async.djinni #pragma once #include <cstdint> #include <memory> namespace ledgerapp_gen { class Runnable; class ExecutionContext { public: virtual ~ExecutionContext() {} virtual void execute(const std::shared_ptr<Runnable> & runnable) = 0; virtual void delay(const std::shared_ptr<Runnable> & runnable, int64_t millis) = 0; }; } // namespace ledgerapp_gen
bc4a731ca349b014dc306381f35e48f211c6a2fa
af0ecafb5428bd556d49575da2a72f6f80d3d14b
/CodeJamCrawler/dataset/11_1078_45.cpp
020ee7d9a02bb81a8af136f96009f5cbecb77ce6
[]
no_license
gbrlas/AVSP
0a2a08be5661c1b4a2238e875b6cdc88b4ee0997
e259090bf282694676b2568023745f9ffb6d73fd
refs/heads/master
2021-06-16T22:25:41.585830
2017-06-09T06:32:01
2017-06-09T06:32:01
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,416
cpp
// // package main import ( "io/ioutil" "strconv" "strings" "fmt" "bufio" "os" "sort" ) var out = "Case #%d: [%s]\n" type comb []string func (me *comb) combine(s1, s2 string) string { tmp := []string{s1, s2} tm := make([]string, 2) sort.SortStrings(tmp) for _, v := range *me { tm = strings.Split(v, "", -1)[0:2] sort.SortStrings(tm) if strings.Join(tmp, "") == strings.Join(tm, "") { //fmt.Println(tm, tmp) return strings.Split(v, "", -1)[2] } } return "" } func perm(str string) []string { n := 0 for i := len(str) - 1; i > 0; i-- { n += i } p := make([]string, n) for i, k := 0, 0; k < n && i < len(str)-1; i++ { for j := i + 1; j < len(str); j++ { p[k] = str[i:i+1] + str[j:j+1] k++ } } return p } type opp []string func (me *opp) opposed(str string) bool { tmp := strings.Split(str, "", -1) tm := make([]string, 2) sort.SortStrings(tmp) for _, v := range *me { tm = strings.Split(v, "", -1) sort.SortStrings(tm) if strings.Join(tmp, "") == strings.Join(tm, "") { return true } } return false } var opposed = &opp{} var combinatns = &comb{} func main() { file, _ := os.Open("input.in") input := bufio.NewReader(file) str, _, _ := input.ReadLine() cases, _ := strconv.Atoi(string(str)) ans := make([]string, cases) i := 0 for str, _, err := input.ReadLine(); err == nil; { line := strings.Fields(string(str)) c, _ := strconv.Atoi(line[0]) *combinatns = line[1 : c+1] d, _ := strconv.Atoi(line[c+1]) *opposed = line[c+2 : c+2+d] //n := line[c+2+d] base := line[c+3+d] ans[i] = process(base) i++ str, _, err = input.ReadLine() } output(ans) } func process(base string) string { set := "" add := func(s string) { set += s } clear := func() { set = "" } combine := func() bool { s1 := set[len(set)-2 : len(set)-1] s2 := set[len(set)-1 : len(set)] c := combinatns.combine(s1, s2) if c != "" { set = set[:len(set)-2] add(c) return true } return false } for i := 0; i < len(base); i++ { add(base[i : i+1]) if len(set) < 2 { continue } if combine() { continue } for _, v := range perm(set) { if opposed.opposed(v) { clear() break } } } return strings.Join(strings.Split(set, "", -1), ", ") } func output(ans []string) { str := "" for i, v := range ans { str += fmt.Sprintf(out, i+1, v) } ioutil.WriteFile("output.out", []byte(str), 0666) }
310606d17fd13b0c2265e676adf73bbef6453ada
9bd74727033ae641c2d6c0f57fe1576fa7b05b37
/micrisoft/sharememory/Writer.cpp
e57c593eb5dda6385171cf4e5719b2105bc49b61
[]
no_license
kamleshiitbhu/practice
eeff2ce478bfe176f4063f26dae020f6de9e5ab0
ec5c38d5e1f447811e578d619432f289266f61a3
refs/heads/master
2022-05-30T21:22:00.194423
2022-05-19T10:58:29
2022-05-19T10:58:29
124,258,203
1
0
null
null
null
null
UTF-8
C++
false
false
529
cpp
#include <iostream> #include <sys/ipc.h> #include <sys/shm.h> #include <stdio.h> using namespace std; int main() { // ftok to generate unique key key_t key = ftok("shmfile",65); // shmget returns an identifier in shmid int shmid = shmget(key,1024,0666|IPC_CREAT); // shmat to attach to shared memory char *str = (char*) shmat(shmid,(void*)0,0); cout<<"Write Data : "; cin>>str; printf("Data written in memory: %s\n",str); //detach from shared memory shmdt(str); return 0; }
f92333ed3b78cf40f333055a2bf75f75e6267738
36183993b144b873d4d53e7b0f0dfebedcb77730
/GameDevelopment/AI Game Programming Wisdom/SourceCode/02 Useful Techniques/07 Vykruta/ChildView.h
50ca275123e31322ffae7e7e2b7831e59de9a421
[]
no_license
alecnunn/bookresources
b95bf62dda3eb9b0ba0fb4e56025c5c7b6d605c0
4562f6430af5afffde790c42d0f3a33176d8003b
refs/heads/master
2020-04-12T22:28:54.275703
2018-12-22T09:00:31
2018-12-22T09:00:31
162,790,540
20
14
null
null
null
null
UTF-8
C++
false
false
1,533
h
// ChildView.h : interface of the CChildView class // ///////////////////////////////////////////////////////////////////////////// #if !defined(AFX_CHILDVIEW_H__6F71D25A_D83E_11D5_BA44_000102368FA3__INCLUDED_) #define AFX_CHILDVIEW_H__6F71D25A_D83E_11D5_BA44_000102368FA3__INCLUDED_ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 #include <math.h> class VECTOR2D; void DrawLine(VECTOR2D vOrig, VECTOR2D vLine, int iColorType = 0); void DrawLine2(VECTOR2D vOrig, VECTOR2D vLine, int iColorType = 0); ///////////////////////////////////////////////////////////////////////////// // CChildView window class CChildView : public CWnd { // Construction public: CChildView(); // Attributes public: // Operations public: // Overrides // ClassWizard generated virtual function overrides //{{AFX_VIRTUAL(CChildView) protected: virtual BOOL PreCreateWindow(CREATESTRUCT& cs); //}}AFX_VIRTUAL // Implementation public: virtual ~CChildView(); // Generated message map functions protected: //{{AFX_MSG(CChildView) afx_msg void OnPaint(); afx_msg void OnLButtonDown( UINT, CPoint ); afx_msg void OnRButtonDown( UINT, CPoint ); afx_msg void OnMouseMove( UINT nFlags, CPoint point ); //}}AFX_MSG DECLARE_MESSAGE_MAP() }; ///////////////////////////////////////////////////////////////////////////// //{{AFX_INSERT_LOCATION}} // Microsoft Visual C++ will insert additional declarations immediately before the previous line. #endif // !defined(AFX_CHILDVIEW_H__6F71D25A_D83E_11D5_BA44_000102368FA3__INCLUDED_)
a303607dc917160905dfc1459e96cb85883d4d76
4485b30d3188a4aed2d2d5dfb246e048c0505da1
/Solution/Solution/src/Engine/Engine.h
cde557a7a49fdfc61db7ee940e107427d3165038
[]
no_license
BooLeet/PhasePortrait
3a2b214ece1f805cbee3842a4a4d5561fb56ce9e
5ea0fd2636617b20b2e1c37d6d7b4f5ab2f92081
refs/heads/main
2023-08-22T01:34:45.540012
2021-10-13T17:11:14
2021-10-13T17:11:14
327,359,563
7
0
null
null
null
null
UTF-8
C++
false
false
1,742
h
#pragma once #include <vector> #include "OpenGLComponents.h" #include <string> class Scene; class CameraBehaviour; class RendererBehaviour; class Input; class Shader; class Engine { private: GLFWwindow* window; Scene* scene; double unscaledDeltaTime; size_t windowWidth, windowHeight; bool fullScreen; Input* input; Shader* defaultShader; bool quitFlag = false; bool CloseWindow(); public: vec3 clearColor = vec3(0, 0, 0); double timeScale; // Has references for all the renderers on the scene class RendererRegistry { private: std::vector< RendererBehaviour*> renderers; public: // Adds a renderer void RegisterRenderer(RendererBehaviour* renderer); // Removes a renderer void UnregisterRenderer(RendererBehaviour* renderer); // Renders all objects void RenderAll(CameraBehaviour* camera) const; RendererBehaviour* operator[](size_t index) const; size_t Size() const; }; // Has references for all the cameras on the scene class CameraRegistry { private: std::vector<CameraBehaviour*> cameras; public: // Adds a camera void RegisterCamera(CameraBehaviour* cam); // Finds and removes a camera void UnregisterCamera(CameraBehaviour* cam); void RenderCameras(const RendererRegistry& rendererRegistry) const; }; CameraRegistry cameraRegistry; RendererRegistry rendererRegistry; Engine(size_t windowWidth, size_t windowHeight,bool fullscreen); ~Engine(); // Main engine loop int MainLoop(); Scene* GetScene(); size_t GetWindowWidth() const; size_t GetWindowHeight() const; double GetDeltaTime() const; double GetUnscaledDeltaTime() const; Input* GetInput() const; void ConsoleLog(std::string str) const; const Shader& GetDefaultShader() const; void Quit(); };
aa7bcc521ec4e31416d884ccb82f1c5e1c0fb804
5d68b88653b6e495439d99194964fc4bf6c25aff
/lib/RcppParallel/include/tbb/flow_graph_opencl_node.h
89f4da7b167b1711b519b2b8ab0678bb85c738bc
[]
no_license
BRICOMATA9/TRDFMLQEO
8b3b0690547ad5b40cebb45bf996dee9ee7dbc40
dadaff4a3aa290809336a784357b13787bd78046
refs/heads/master
2020-05-16T00:31:36.108773
2019-04-21T20:30:53
2019-04-21T20:30:53
182,571,145
0
1
null
null
null
null
UTF-8
C++
false
false
60,073
h
/* Copyright (c) 2005-2017 Intel Corporation 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. */ #ifndef __TBB_flow_graph_opencl_node_H #define __TBB_flow_graph_opencl_node_H #include "tbb/tbb_config.h" #if __TBB_PREVIEW_OPENCL_NODE #include "flow_graph.h" #include <vector> #include <string> #include <algorithm> #include <iostream> #include <fstream> #include <map> #include <mutex> #ifdef __APPLE__ #include <OpenCL/opencl.h> #else #include <CL/cl.h> #endif namespace tbb { namespace flow { namespace interface9 { class opencl_foundation; class opencl_device_list; template <typename Factory> class opencl_buffer_impl; template <typename Factory> class opencl_program; class default_opencl_factory; class opencl_graph : public graph { public: //! Constructs a graph with isolated task_group_context opencl_graph() : my_opencl_foundation( NULL ) {} //! Constructs a graph with an user context explicit opencl_graph( task_group_context& context ) : graph( context ), my_opencl_foundation( NULL ) {} //! Destroys a graph ~opencl_graph(); //! Available devices const opencl_device_list& available_devices(); default_opencl_factory& opencl_factory(); protected: opencl_foundation *my_opencl_foundation; opencl_foundation &get_opencl_foundation(); template <typename T, typename Factory> friend class opencl_buffer; template <cl_channel_order channel_order, cl_channel_type channel_type, typename Factory> friend class opencl_image2d; template<typename... Args> friend class opencl_node; template <typename DeviceFilter> friend class opencl_factory; }; template <typename DeviceFilter> class opencl_factory; template <typename T, typename Factory> class dependency_msg; inline void enforce_cl_retcode( cl_int err, std::string msg ) { if ( err != CL_SUCCESS ) { std::cerr << msg << "; error code: " << err << std::endl; throw msg; } } template <typename T> T event_info( cl_event e, cl_event_info i ) { T res; enforce_cl_retcode( clGetEventInfo( e, i, sizeof( res ), &res, NULL ), "Failed to get OpenCL event information" ); return res; } template <typename T> T device_info( cl_device_id d, cl_device_info i ) { T res; enforce_cl_retcode( clGetDeviceInfo( d, i, sizeof( res ), &res, NULL ), "Failed to get OpenCL device information" ); return res; } template <> std::string device_info<std::string>( cl_device_id d, cl_device_info i ) { size_t required; enforce_cl_retcode( clGetDeviceInfo( d, i, 0, NULL, &required ), "Failed to get OpenCL device information" ); char *buff = (char*)alloca( required ); enforce_cl_retcode( clGetDeviceInfo( d, i, required, buff, NULL ), "Failed to get OpenCL device information" ); return buff; } template <typename T> T platform_info( cl_platform_id p, cl_platform_info i ) { T res; enforce_cl_retcode( clGetPlatformInfo( p, i, sizeof( res ), &res, NULL ), "Failed to get OpenCL platform information" ); return res; } template <> std::string platform_info<std::string>( cl_platform_id p, cl_platform_info i ) { size_t required; enforce_cl_retcode( clGetPlatformInfo( p, i, 0, NULL, &required ), "Failed to get OpenCL platform information" ); char *buff = (char*)alloca( required ); enforce_cl_retcode( clGetPlatformInfo( p, i, required, buff, NULL ), "Failed to get OpenCL platform information" ); return buff; } class opencl_device { public: typedef size_t device_id_type; enum : device_id_type { unknown = device_id_type( -2 ), host = device_id_type( -1 ) }; opencl_device() : my_device_id( unknown ) {} opencl_device( cl_device_id cl_d_id, device_id_type device_id ) : my_device_id( device_id ), my_cl_device_id( cl_d_id ) {} std::string platform_profile() const { return platform_info<std::string>( platform(), CL_PLATFORM_PROFILE ); } std::string platform_version() const { return platform_info<std::string>( platform(), CL_PLATFORM_VERSION ); } std::string platform_name() const { return platform_info<std::string>( platform(), CL_PLATFORM_NAME ); } std::string platform_vendor() const { return platform_info<std::string>( platform(), CL_PLATFORM_VENDOR ); } std::string platform_extensions() const { return platform_info<std::string>( platform(), CL_PLATFORM_EXTENSIONS ); } template <typename T> void info( cl_device_info i, T &t ) const { t = device_info<T>( my_cl_device_id, i ); } std::string version() const { // The version string format: OpenCL<space><major_version.minor_version><space><vendor-specific information> return device_info<std::string>( my_cl_device_id, CL_DEVICE_VERSION ); } int major_version() const { int major; std::sscanf( version().c_str(), "OpenCL %d", &major ); return major; } int minor_version() const { int major, minor; std::sscanf( version().c_str(), "OpenCL %d.%d", &major, &minor ); return minor; } bool out_of_order_exec_mode_on_host_present() const { #if CL_VERSION_2_0 if ( major_version() >= 2 ) return (device_info<cl_command_queue_properties>( my_cl_device_id, CL_DEVICE_QUEUE_ON_HOST_PROPERTIES ) & CL_QUEUE_OUT_OF_ORDER_EXEC_MODE_ENABLE) != 0; else #endif /* CL_VERSION_2_0 */ return (device_info<cl_command_queue_properties>( my_cl_device_id, CL_DEVICE_QUEUE_PROPERTIES ) & CL_QUEUE_OUT_OF_ORDER_EXEC_MODE_ENABLE) != 0; } bool out_of_order_exec_mode_on_device_present() const { #if CL_VERSION_2_0 if ( major_version() >= 2 ) return (device_info<cl_command_queue_properties>( my_cl_device_id, CL_DEVICE_QUEUE_ON_DEVICE_PROPERTIES ) & CL_QUEUE_OUT_OF_ORDER_EXEC_MODE_ENABLE) != 0; else #endif /* CL_VERSION_2_0 */ return false; } std::array<size_t, 3> max_work_item_sizes() const { return device_info<std::array<size_t, 3>>( my_cl_device_id, CL_DEVICE_MAX_WORK_ITEM_SIZES ); } size_t max_work_group_size() const { return device_info<size_t>( my_cl_device_id, CL_DEVICE_MAX_WORK_GROUP_SIZE ); } bool built_in_kernel_available( const std::string& k ) const { const std::string semi = ";"; // Added semicolumns to force an exact match (to avoid a partial match, e.g. "add" is partly matched with "madd"). return (semi + built_in_kernels() + semi).find( semi + k + semi ) != std::string::npos; } std::string built_in_kernels() const { return device_info<std::string>( my_cl_device_id, CL_DEVICE_BUILT_IN_KERNELS ); } std::string name() const { return device_info<std::string>( my_cl_device_id, CL_DEVICE_NAME ); } cl_bool available() const { return device_info<cl_bool>( my_cl_device_id, CL_DEVICE_AVAILABLE ); } cl_bool compiler_available() const { return device_info<cl_bool>( my_cl_device_id, CL_DEVICE_COMPILER_AVAILABLE ); } cl_bool linker_available() const { return device_info<cl_bool>( my_cl_device_id, CL_DEVICE_LINKER_AVAILABLE ); } bool extension_available( const std::string &ext ) const { const std::string space = " "; // Added space to force an exact match (to avoid a partial match, e.g. "ext" is partly matched with "ext2"). return (space + extensions() + space).find( space + ext + space ) != std::string::npos; } std::string extensions() const { return device_info<std::string>( my_cl_device_id, CL_DEVICE_EXTENSIONS ); } cl_device_type type() const { return device_info<cl_device_type>( my_cl_device_id, CL_DEVICE_TYPE ); } std::string vendor() const { return device_info<std::string>( my_cl_device_id, CL_DEVICE_VENDOR ); } cl_uint address_bits() const { return device_info<cl_uint>( my_cl_device_id, CL_DEVICE_ADDRESS_BITS ); } cl_device_id device_id() const { return my_cl_device_id; } cl_command_queue command_queue() const { return my_cl_command_queue; } void set_command_queue( cl_command_queue cmd_queue ) { my_cl_command_queue = cmd_queue; } private: opencl_device( cl_device_id d_id ) : my_device_id( unknown ), my_cl_device_id( d_id ) {} cl_platform_id platform() const { return device_info<cl_platform_id>( my_cl_device_id, CL_DEVICE_PLATFORM ); } device_id_type my_device_id; cl_device_id my_cl_device_id; cl_command_queue my_cl_command_queue; friend bool operator==(opencl_device d1, opencl_device d2) { return d1.my_cl_device_id == d2.my_cl_device_id; } template <typename DeviceFilter> friend class opencl_factory; template <typename Factory> friend class opencl_memory; template <typename Factory> friend class opencl_program; friend class opencl_foundation; #if TBB_USE_ASSERT template <typename T, typename Factory> friend class opencl_buffer; #endif }; class opencl_device_list { typedef std::vector<opencl_device> container_type; public: typedef container_type::iterator iterator; typedef container_type::const_iterator const_iterator; typedef container_type::size_type size_type; opencl_device_list() {} opencl_device_list( std::initializer_list<opencl_device> il ) : my_container( il ) {} void add( opencl_device d ) { my_container.push_back( d ); } size_type size() const { return my_container.size(); } bool empty() const { return my_container.empty(); } iterator begin() { return my_container.begin(); } iterator end() { return my_container.end(); } const_iterator begin() const { return my_container.begin(); } const_iterator end() const { return my_container.end(); } const_iterator cbegin() const { return my_container.cbegin(); } const_iterator cend() const { return my_container.cend(); } private: container_type my_container; }; class callback_base : tbb::internal::no_copy { public: virtual void call() = 0; virtual ~callback_base() {} }; template <typename Callback, typename T> class callback : public callback_base { graph &my_graph; Callback my_callback; T my_data; public: callback( graph &g, Callback c, const T& t ) : my_graph( g ), my_callback( c ), my_data( t ) { // Extend the graph lifetime until the callback completion. my_graph.increment_wait_count(); } ~callback() { // Release the reference to the graph. my_graph.decrement_wait_count(); } void call() __TBB_override { my_callback( my_data ); } }; template <typename T, typename Factory = default_opencl_factory> class dependency_msg : public async_msg<T> { public: typedef T value_type; dependency_msg() : my_callback_flag_ptr( std::make_shared< tbb::atomic<bool>>() ) { my_callback_flag_ptr->store<tbb::relaxed>(false); } explicit dependency_msg( const T& data ) : my_data(data), my_callback_flag_ptr( std::make_shared<tbb::atomic<bool>>() ) { my_callback_flag_ptr->store<tbb::relaxed>(false); } dependency_msg( opencl_graph &g, const T& data ) : my_data(data), my_graph(&g), my_callback_flag_ptr( std::make_shared<tbb::atomic<bool>>() ) { my_callback_flag_ptr->store<tbb::relaxed>(false); } dependency_msg( const T& data, cl_event event ) : my_data(data), my_event(event), my_is_event(true), my_callback_flag_ptr( std::make_shared<tbb::atomic<bool>>() ) { my_callback_flag_ptr->store<tbb::relaxed>(false); enforce_cl_retcode( clRetainEvent( my_event ), "Failed to retain an event" ); } T& data( bool wait = true ) { if ( my_is_event && wait ) { enforce_cl_retcode( clWaitForEvents( 1, &my_event ), "Failed to wait for an event" ); enforce_cl_retcode( clReleaseEvent( my_event ), "Failed to release an event" ); my_is_event = false; } return my_data; } const T& data( bool wait = true ) const { if ( my_is_event && wait ) { enforce_cl_retcode( clWaitForEvents( 1, &my_event ), "Failed to wait for an event" ); enforce_cl_retcode( clReleaseEvent( my_event ), "Failed to release an event" ); my_is_event = false; } return my_data; } dependency_msg( const dependency_msg &dmsg ) : async_msg<T>(dmsg), my_data(dmsg.my_data), my_event(dmsg.my_event), my_is_event( dmsg.my_is_event ), my_graph( dmsg.my_graph ), my_callback_flag_ptr(dmsg.my_callback_flag_ptr) { if ( my_is_event ) enforce_cl_retcode( clRetainEvent( my_event ), "Failed to retain an event" ); } dependency_msg( dependency_msg &&dmsg ) : async_msg<T>(std::move(dmsg)), my_data(std::move(dmsg.my_data)), my_event(dmsg.my_event), my_is_event(dmsg.my_is_event), my_graph(dmsg.my_graph), my_callback_flag_ptr( std::move(dmsg.my_callback_flag_ptr) ) { dmsg.my_is_event = false; } dependency_msg& operator=(const dependency_msg &dmsg) { async_msg<T>::operator =(dmsg); // Release original event if ( my_is_event ) enforce_cl_retcode( clReleaseEvent( my_event ), "Failed to retain an event" ); my_data = dmsg.my_data; my_event = dmsg.my_event; my_is_event = dmsg.my_is_event; my_graph = dmsg.my_graph; // Retain copied event if ( my_is_event ) enforce_cl_retcode( clRetainEvent( my_event ), "Failed to retain an event" ); my_callback_flag_ptr = dmsg.my_callback_flag_ptr; return *this; } ~dependency_msg() { if ( my_is_event ) enforce_cl_retcode( clReleaseEvent( my_event ), "Failed to release an event" ); } cl_event const * get_event() const { return my_is_event ? &my_event : NULL; } void set_event( cl_event e ) const { if ( my_is_event ) { cl_command_queue cq = event_info<cl_command_queue>( my_event, CL_EVENT_COMMAND_QUEUE ); if ( cq != event_info<cl_command_queue>( e, CL_EVENT_COMMAND_QUEUE ) ) enforce_cl_retcode( clFlush( cq ), "Failed to flush an OpenCL command queue" ); enforce_cl_retcode( clReleaseEvent( my_event ), "Failed to release an event" ); } my_is_event = true; my_event = e; clRetainEvent( my_event ); } void set_graph( graph &g ) { my_graph = &g; } void clear_event() const { if ( my_is_event ) { enforce_cl_retcode( clFlush( event_info<cl_command_queue>( my_event, CL_EVENT_COMMAND_QUEUE ) ), "Failed to flush an OpenCL command queue" ); enforce_cl_retcode( clReleaseEvent( my_event ), "Failed to release an event" ); } my_is_event = false; } template <typename Callback> void register_callback( Callback c ) const { __TBB_ASSERT( my_is_event, "The OpenCL event is not set" ); __TBB_ASSERT( my_graph, "The graph is not set" ); enforce_cl_retcode( clSetEventCallback( my_event, CL_COMPLETE, register_callback_func, new callback<Callback, T>( *my_graph, c, my_data ) ), "Failed to set an OpenCL callback" ); } operator T&() { return data(); } operator const T&() const { return data(); } protected: // Overridden in this derived class to inform that // async calculation chain is over void finalize() const __TBB_override { receive_if_memory_object(*this); if (! my_callback_flag_ptr->fetch_and_store(true)) { dependency_msg a(*this); if (my_is_event) { register_callback([a](const T& t) mutable { a.set(t); }); } else { a.set(my_data); } } clear_event(); } private: static void CL_CALLBACK register_callback_func( cl_event, cl_int event_command_exec_status, void *data ) { tbb::internal::suppress_unused_warning( event_command_exec_status ); __TBB_ASSERT( event_command_exec_status == CL_COMPLETE, NULL ); __TBB_ASSERT( data, NULL ); callback_base *c = static_cast<callback_base*>(data); c->call(); delete c; } T my_data; mutable cl_event my_event; mutable bool my_is_event = false; graph *my_graph = NULL; std::shared_ptr< tbb::atomic<bool> > my_callback_flag_ptr; }; template <typename K, typename T, typename Factory> K key_from_message( const dependency_msg<T, Factory> &dmsg ) { using tbb::flow::key_from_message; const T &t = dmsg.data( false ); __TBB_STATIC_ASSERT( true, "" ); return key_from_message<K, T>( t ); } template <typename Factory> class opencl_memory { public: opencl_memory() {} opencl_memory( Factory &f ) : my_host_ptr( NULL ), my_factory( &f ), my_sending_event_present( false ) { my_curr_device_id = my_factory->devices().begin()->my_device_id; } ~opencl_memory() { if ( my_sending_event_present ) enforce_cl_retcode( clReleaseEvent( my_sending_event ), "Failed to release an event for the OpenCL buffer" ); enforce_cl_retcode( clReleaseMemObject( my_cl_mem ), "Failed to release an memory object" ); } cl_mem get_cl_mem() const { return my_cl_mem; } void* get_host_ptr() { if ( !my_host_ptr ) { dependency_msg<void*, Factory> d = receive( NULL ); d.data(); __TBB_ASSERT( d.data() == my_host_ptr, NULL ); } return my_host_ptr; } Factory *factory() const { return my_factory; } dependency_msg<void*, Factory> send( opencl_device d, const cl_event *e ); dependency_msg<void*, Factory> receive( const cl_event *e ); virtual void map_memory( opencl_device, dependency_msg<void*, Factory> & ) = 0; protected: cl_mem my_cl_mem; tbb::atomic<opencl_device::device_id_type> my_curr_device_id; void* my_host_ptr; Factory *my_factory; tbb::spin_mutex my_sending_lock; bool my_sending_event_present; cl_event my_sending_event; }; template <typename Factory> class opencl_buffer_impl : public opencl_memory<Factory> { size_t my_size; public: opencl_buffer_impl( size_t size, Factory& f ) : opencl_memory<Factory>( f ), my_size( size ) { cl_int err; this->my_cl_mem = clCreateBuffer( this->my_factory->context(), CL_MEM_ALLOC_HOST_PTR, size, NULL, &err ); enforce_cl_retcode( err, "Failed to create an OpenCL buffer" ); } // The constructor for subbuffers. opencl_buffer_impl( cl_mem m, size_t index, size_t size, Factory& f ) : opencl_memory<Factory>( f ), my_size( size ) { cl_int err; cl_buffer_region region = { index, size }; this->my_cl_mem = clCreateSubBuffer( m, 0, CL_BUFFER_CREATE_TYPE_REGION, &region, &err ); enforce_cl_retcode( err, "Failed to create an OpenCL subbuffer" ); } size_t size() const { return my_size; } void map_memory( opencl_device device, dependency_msg<void*, Factory> &dmsg ) __TBB_override { this->my_factory->enque_map_buffer( device, *this, dmsg ); } #if TBB_USE_ASSERT template <typename, typename> friend class opencl_buffer; #endif }; enum access_type { read_write, write_only, read_only }; template <typename T, typename Factory = default_opencl_factory> class opencl_subbuffer; template <typename T, typename Factory = default_opencl_factory> class opencl_buffer { public: typedef cl_mem native_object_type; typedef opencl_buffer memory_object_type; typedef Factory opencl_factory_type; template<access_type a> using iterator = T*; template <access_type a> iterator<a> access() const { T* ptr = (T*)my_impl->get_host_ptr(); __TBB_ASSERT( ptr, NULL ); return iterator<a>( ptr ); } T* data() const { return &access<read_write>()[0]; } template <access_type a = read_write> iterator<a> begin() const { return access<a>(); } template <access_type a = read_write> iterator<a> end() const { return access<a>()+my_impl->size()/sizeof(T); } size_t size() const { return my_impl->size()/sizeof(T); } T& operator[] ( ptrdiff_t k ) { return begin()[k]; } opencl_buffer() {} opencl_buffer( opencl_graph &g, size_t size ); opencl_buffer( Factory &f, size_t size ) : my_impl( std::make_shared<impl_type>( size*sizeof(T), f ) ) {} cl_mem native_object() const { return my_impl->get_cl_mem(); } const opencl_buffer& memory_object() const { return *this; } void send( opencl_device device, dependency_msg<opencl_buffer, Factory> &dependency ) const { __TBB_ASSERT( dependency.data( /*wait = */false ) == *this, NULL ); dependency_msg<void*, Factory> d = my_impl->send( device, dependency.get_event() ); const cl_event *e = d.get_event(); if ( e ) dependency.set_event( *e ); else dependency.clear_event(); } void receive( const dependency_msg<opencl_buffer, Factory> &dependency ) const { __TBB_ASSERT( dependency.data( /*wait = */false ) == *this, NULL ); dependency_msg<void*, Factory> d = my_impl->receive( dependency.get_event() ); const cl_event *e = d.get_event(); if ( e ) dependency.set_event( *e ); else dependency.clear_event(); } opencl_subbuffer<T, Factory> subbuffer( size_t index, size_t size ) const; private: // The constructor for subbuffers. opencl_buffer( Factory &f, cl_mem m, size_t index, size_t size ) : my_impl( std::make_shared<impl_type>( m, index*sizeof(T), size*sizeof(T), f ) ) {} typedef opencl_buffer_impl<Factory> impl_type; std::shared_ptr<impl_type> my_impl; friend bool operator==(const opencl_buffer<T, Factory> &lhs, const opencl_buffer<T, Factory> &rhs) { return lhs.my_impl == rhs.my_impl; } template <typename> friend class opencl_factory; template <typename, typename> friend class opencl_subbuffer; }; template <typename T, typename Factory> class opencl_subbuffer : public opencl_buffer<T, Factory> { opencl_buffer<T, Factory> my_owner; public: opencl_subbuffer() {} opencl_subbuffer( const opencl_buffer<T, Factory> &owner, size_t index, size_t size ) : opencl_buffer<T, Factory>( *owner.my_impl->factory(), owner.native_object(), index, size ), my_owner( owner ) {} }; template <typename T, typename Factory> opencl_subbuffer<T, Factory> opencl_buffer<T, Factory>::subbuffer( size_t index, size_t size ) const { return opencl_subbuffer<T, Factory>( *this, index, size ); } #define is_typedef(type) \ template <typename T> \ struct is_##type { \ template <typename C> \ static std::true_type check( typename C::type* ); \ template <typename C> \ static std::false_type check( ... ); \ \ static const bool value = decltype(check<T>(0))::value; \ } is_typedef( native_object_type ); is_typedef( memory_object_type ); template <typename T> typename std::enable_if<is_native_object_type<T>::value, typename T::native_object_type>::type get_native_object( const T &t ) { return t.native_object(); } template <typename T> typename std::enable_if<!is_native_object_type<T>::value, T>::type get_native_object( T t ) { return t; } // send_if_memory_object checks if the T type has memory_object_type and call the send method for the object. template <typename T, typename Factory> typename std::enable_if<is_memory_object_type<T>::value>::type send_if_memory_object( opencl_device device, dependency_msg<T, Factory> &dmsg ) { const T &t = dmsg.data( false ); typedef typename T::memory_object_type mem_obj_t; mem_obj_t mem_obj = t.memory_object(); dependency_msg<mem_obj_t, Factory> d( mem_obj ); if ( dmsg.get_event() ) d.set_event( *dmsg.get_event() ); mem_obj.send( device, d ); if ( d.get_event() ) dmsg.set_event( *d.get_event() ); } template <typename T> typename std::enable_if<is_memory_object_type<T>::value>::type send_if_memory_object( opencl_device device, T &t ) { typedef typename T::memory_object_type mem_obj_t; mem_obj_t mem_obj = t.memory_object(); dependency_msg<mem_obj_t, typename mem_obj_t::opencl_factory_type> dmsg( mem_obj ); mem_obj.send( device, dmsg ); } template <typename T> typename std::enable_if<!is_memory_object_type<T>::value>::type send_if_memory_object( opencl_device, T& ) {}; // receive_if_memory_object checks if the T type has memory_object_type and call the receive method for the object. template <typename T, typename Factory> typename std::enable_if<is_memory_object_type<T>::value>::type receive_if_memory_object( const dependency_msg<T, Factory> &dmsg ) { const T &t = dmsg.data( false ); typedef typename T::memory_object_type mem_obj_t; mem_obj_t mem_obj = t.memory_object(); dependency_msg<mem_obj_t, Factory> d( mem_obj ); if ( dmsg.get_event() ) d.set_event( *dmsg.get_event() ); mem_obj.receive( d ); if ( d.get_event() ) dmsg.set_event( *d.get_event() ); } template <typename T> typename std::enable_if<!is_memory_object_type<T>::value>::type receive_if_memory_object( const T& ) {} class opencl_range { public: typedef size_t range_index_type; typedef std::array<range_index_type, 3> nd_range_type; template <typename G = std::initializer_list<int>, typename L = std::initializer_list<int>, typename = typename std::enable_if<!std::is_same<typename std::decay<G>::type, opencl_range>::value>::type> opencl_range(G&& global_work = std::initializer_list<int>({ 0 }), L&& local_work = std::initializer_list<int>({ 0, 0, 0 })) { auto g_it = global_work.begin(); auto l_it = local_work.begin(); my_global_work_size = { size_t(-1), size_t(-1), size_t(-1) }; // my_local_work_size is still uninitialized for (int s = 0; s < 3 && g_it != global_work.end(); ++g_it, ++l_it, ++s) { __TBB_ASSERT(l_it != local_work.end(), "global_work & local_work must have same size"); my_global_work_size[s] = *g_it; my_local_work_size[s] = *l_it; } } const nd_range_type& global_range() const { return my_global_work_size; } const nd_range_type& local_range() const { return my_local_work_size; } private: nd_range_type my_global_work_size; nd_range_type my_local_work_size; }; template <typename DeviceFilter> class opencl_factory { public: template<typename T> using async_msg_type = dependency_msg<T, opencl_factory<DeviceFilter>>; typedef opencl_device device_type; class kernel : tbb::internal::no_assign { public: kernel( const kernel& k ) : my_factory( k.my_factory ) { // Clone my_cl_kernel via opencl_program size_t ret_size = 0; std::vector<char> kernel_name; for ( size_t curr_size = 32;; curr_size <<= 1 ) { kernel_name.resize( curr_size <<= 1 ); enforce_cl_retcode( clGetKernelInfo( k.my_cl_kernel, CL_KERNEL_FUNCTION_NAME, curr_size, kernel_name.data(), &ret_size ), "Failed to get kernel info" ); if ( ret_size < curr_size ) break; } cl_program program; enforce_cl_retcode( clGetKernelInfo( k.my_cl_kernel, CL_KERNEL_PROGRAM, sizeof(program), &program, &ret_size ), "Failed to get kernel info" ); __TBB_ASSERT( ret_size == sizeof(program), NULL ); my_cl_kernel = opencl_program< factory_type >( my_factory, program ).get_cl_kernel( kernel_name.data() ); } ~kernel() { enforce_cl_retcode( clReleaseKernel( my_cl_kernel ), "Failed to release a kernel" ); } private: typedef opencl_factory<DeviceFilter> factory_type; kernel( const cl_kernel& k, factory_type& f ) : my_cl_kernel( k ), my_factory( f ) {} // Data cl_kernel my_cl_kernel; factory_type& my_factory; template <typename DeviceFilter_> friend class opencl_factory; template <typename Factory> friend class opencl_program; }; typedef kernel kernel_type; // 'range_type' enables kernel_executor with range support // it affects expectations for enqueue_kernel(.....) interface method typedef opencl_range range_type; opencl_factory( opencl_graph &g ) : my_graph( g ) {} ~opencl_factory() { if ( my_devices.size() ) { for ( auto d = my_devices.begin(); d != my_devices.end(); ++d ) { enforce_cl_retcode( clReleaseCommandQueue( (*d).my_cl_command_queue ), "Failed to release a command queue" ); } enforce_cl_retcode( clReleaseContext( my_cl_context ), "Failed to release a context" ); } } bool init( const opencl_device_list &device_list ) { tbb::spin_mutex::scoped_lock lock( my_devices_mutex ); if ( !my_devices.size() ) { my_devices = device_list; return true; } return false; } private: template <typename Factory> void enque_map_buffer( opencl_device device, opencl_buffer_impl<Factory> &buffer, dependency_msg<void*, Factory>& dmsg ) { cl_event const* e1 = dmsg.get_event(); cl_event e2; cl_int err; void *ptr = clEnqueueMapBuffer( device.my_cl_command_queue, buffer.get_cl_mem(), false, CL_MAP_READ | CL_MAP_WRITE, 0, buffer.size(), e1 == NULL ? 0 : 1, e1, &e2, &err ); enforce_cl_retcode( err, "Failed to map a buffer" ); dmsg.data( false ) = ptr; dmsg.set_event( e2 ); enforce_cl_retcode( clReleaseEvent( e2 ), "Failed to release an event" ); } template <typename Factory> void enque_unmap_buffer( opencl_device device, opencl_memory<Factory> &memory, dependency_msg<void*, Factory>& dmsg ) { cl_event const* e1 = dmsg.get_event(); cl_event e2; enforce_cl_retcode( clEnqueueUnmapMemObject( device.my_cl_command_queue, memory.get_cl_mem(), memory.get_host_ptr(), e1 == NULL ? 0 : 1, e1, &e2 ), "Failed to unmap a buffer" ); dmsg.set_event( e2 ); enforce_cl_retcode( clReleaseEvent( e2 ), "Failed to release an event" ); } // --------- Kernel argument & event list helpers --------- // template <size_t NUM_ARGS, typename T> void process_one_arg( const kernel_type& kernel, std::array<cl_event, NUM_ARGS>&, int&, int& place, const T& t ) { auto p = get_native_object(t); enforce_cl_retcode( clSetKernelArg(kernel.my_cl_kernel, place++, sizeof(p), &p), "Failed to set a kernel argument" ); } template <size_t NUM_ARGS, typename T, typename F> void process_one_arg( const kernel_type& kernel, std::array<cl_event, NUM_ARGS>& events, int& num_events, int& place, const dependency_msg<T, F>& msg ) { __TBB_ASSERT((static_cast<typename std::array<cl_event, NUM_ARGS>::size_type>(num_events) < events.size()), NULL); const cl_event * const e = msg.get_event(); if (e != NULL) { events[num_events++] = *e; } process_one_arg( kernel, events, num_events, place, msg.data(false) ); } template <size_t NUM_ARGS, typename T, typename ...Rest> void process_arg_list( const kernel_type& kernel, std::array<cl_event, NUM_ARGS>& events, int& num_events, int& place, const T& t, const Rest&... args ) { process_one_arg( kernel, events, num_events, place, t ); process_arg_list( kernel, events, num_events, place, args... ); } template <size_t NUM_ARGS> void process_arg_list( const kernel_type&, std::array<cl_event, NUM_ARGS>&, int&, int& ) {} // ------------------------------------------- // template <typename T> void update_one_arg( cl_event, T& ) {} template <typename T, typename F> void update_one_arg( cl_event e, dependency_msg<T, F>& msg ) { msg.set_event( e ); msg.set_graph( my_graph ); } template <typename T, typename ...Rest> void update_arg_list( cl_event e, T& t, Rest&... args ) { update_one_arg( e, t ); update_arg_list( e, args... ); } void update_arg_list( cl_event ) {} // ------------------------------------------- // public: template <typename ...Args> void send_kernel( opencl_device device, const kernel_type& kernel, const range_type& work_size, Args&... args ) { std::array<cl_event, sizeof...(Args)> events; int num_events = 0; int place = 0; process_arg_list( kernel, events, num_events, place, args... ); const cl_event e = send_kernel_impl( device, kernel.my_cl_kernel, work_size, num_events, events.data() ); update_arg_list(e, args...); // Release our own reference to cl_event enforce_cl_retcode( clReleaseEvent(e), "Failed to release an event" ); } // ------------------------------------------- // template <typename T, typename ...Rest> void send_data(opencl_device device, T& t, Rest&... args) { send_if_memory_object( device, t ); send_data( device, args... ); } void send_data(opencl_device) {} // ------------------------------------------- // private: cl_event send_kernel_impl( opencl_device device, const cl_kernel& kernel, const range_type& work_size, cl_uint num_events, cl_event* event_list ) { const typename range_type::nd_range_type g_offset = { { 0, 0, 0 } }; const typename range_type::nd_range_type& g_size = work_size.global_range(); const typename range_type::nd_range_type& l_size = work_size.local_range(); cl_uint s; for ( s = 1; s < 3 && g_size[s] != size_t(-1); ++s) {} cl_event event; enforce_cl_retcode( clEnqueueNDRangeKernel( device.my_cl_command_queue, kernel, s, g_offset.data(), g_size.data(), l_size[0] ? l_size.data() : NULL, num_events, num_events ? event_list : NULL, &event ), "Failed to enqueue a kernel" ); return event; } // ------------------------------------------- // template <typename T> bool get_event_from_one_arg( cl_event&, const T& ) { return false; } template <typename T, typename F> bool get_event_from_one_arg( cl_event& e, const dependency_msg<T, F>& msg) { cl_event const *e_ptr = msg.get_event(); if ( e_ptr != NULL ) { e = *e_ptr; return true; } return false; } template <typename T, typename ...Rest> bool get_event_from_args( cl_event& e, const T& t, const Rest&... args ) { if ( get_event_from_one_arg( e, t ) ) { return true; } return get_event_from_args( e, args... ); } bool get_event_from_args( cl_event& ) { return false; } // ------------------------------------------- // struct finalize_fn : tbb::internal::no_assign { virtual ~finalize_fn() {} virtual void operator() () {} }; template<typename Fn> struct finalize_fn_leaf : public finalize_fn { Fn my_fn; finalize_fn_leaf(Fn fn) : my_fn(fn) {} void operator() () __TBB_override { my_fn(); } }; static void CL_CALLBACK finalize_callback(cl_event, cl_int event_command_exec_status, void *data) { tbb::internal::suppress_unused_warning(event_command_exec_status); __TBB_ASSERT(event_command_exec_status == CL_COMPLETE, NULL); finalize_fn * const fn_ptr = static_cast<finalize_fn*>(data); __TBB_ASSERT(fn_ptr != NULL, "Invalid finalize function pointer"); (*fn_ptr)(); // Function pointer was created by 'new' & this callback must be called once only delete fn_ptr; } public: template <typename FinalizeFn, typename ...Args> void finalize( opencl_device device, FinalizeFn fn, Args&... args ) { cl_event e; if ( get_event_from_args( e, args... ) ) { enforce_cl_retcode( clSetEventCallback( e, CL_COMPLETE, finalize_callback, new finalize_fn_leaf<FinalizeFn>(fn) ), "Failed to set a callback" ); } enforce_cl_retcode( clFlush( device.my_cl_command_queue ), "Failed to flush an OpenCL command queue" ); } const opencl_device_list& devices() { std::call_once( my_once_flag, &opencl_factory::init_once, this ); return my_devices; } private: bool is_same_context( opencl_device::device_id_type d1, opencl_device::device_id_type d2 ) { __TBB_ASSERT( d1 != opencl_device::unknown && d2 != opencl_device::unknown, NULL ); // Currently, factory supports only one context so if the both devices are not host it means the are in the same context. if ( d1 != opencl_device::host && d2 != opencl_device::host ) return true; return d1 == d2; } private: opencl_factory( const opencl_factory& ); opencl_factory& operator=(const opencl_factory&); cl_context context() { std::call_once( my_once_flag, &opencl_factory::init_once, this ); return my_cl_context; } void init_once(); std::once_flag my_once_flag; opencl_device_list my_devices; cl_context my_cl_context; opencl_graph &my_graph; tbb::spin_mutex my_devices_mutex; template <typename Factory> friend class opencl_program; template <typename Factory> friend class opencl_buffer_impl; template <typename Factory> friend class opencl_memory; }; template <typename Factory> dependency_msg<void*, Factory> opencl_memory<Factory>::receive( const cl_event *e ) { dependency_msg<void*, Factory> d = e ? dependency_msg<void*, Factory>( my_host_ptr, *e ) : dependency_msg<void*, Factory>( my_host_ptr ); // Concurrent receives are prohibited so we do not worry about synchronization. if ( my_curr_device_id.load<tbb::relaxed>() != opencl_device::host ) { map_memory( *my_factory->devices().begin(), d ); my_curr_device_id.store<tbb::relaxed>( opencl_device::host ); my_host_ptr = d.data( false ); } // Release the sending event if ( my_sending_event_present ) { enforce_cl_retcode( clReleaseEvent( my_sending_event ), "Failed to release an event" ); my_sending_event_present = false; } return d; } template <typename Factory> dependency_msg<void*, Factory> opencl_memory<Factory>::send( opencl_device device, const cl_event *e ) { opencl_device::device_id_type device_id = device.my_device_id; if ( !my_factory->is_same_context( my_curr_device_id.load<tbb::acquire>(), device_id ) ) { { tbb::spin_mutex::scoped_lock lock( my_sending_lock ); if ( !my_factory->is_same_context( my_curr_device_id.load<tbb::relaxed>(), device_id ) ) { __TBB_ASSERT( my_host_ptr, "The buffer has not been mapped" ); dependency_msg<void*, Factory> d( my_host_ptr ); my_factory->enque_unmap_buffer( device, *this, d ); my_sending_event = *d.get_event(); my_sending_event_present = true; enforce_cl_retcode( clRetainEvent( my_sending_event ), "Failed to retain an event" ); my_host_ptr = NULL; my_curr_device_id.store<tbb::release>(device_id); } } __TBB_ASSERT( my_sending_event_present, NULL ); } // !e means that buffer has come from the host if ( !e && my_sending_event_present ) e = &my_sending_event; __TBB_ASSERT( !my_host_ptr, "The buffer has not been unmapped" ); return e ? dependency_msg<void*, Factory>( NULL, *e ) : dependency_msg<void*, Factory>( NULL ); } struct default_opencl_factory_device_filter { opencl_device_list operator()( const opencl_device_list &devices ) { opencl_device_list dl; dl.add( *devices.begin() ); return dl; } }; class default_opencl_factory : public opencl_factory < default_opencl_factory_device_filter > { public: template<typename T> using async_msg_type = dependency_msg<T, default_opencl_factory>; default_opencl_factory( opencl_graph &g ) : opencl_factory( g ) {} private: default_opencl_factory( const default_opencl_factory& ); default_opencl_factory& operator=(const default_opencl_factory&); }; class opencl_foundation : tbb::internal::no_assign { struct default_device_selector_type { opencl_device operator()( default_opencl_factory& f ) { __TBB_ASSERT( ! f.devices().empty(), "No available devices" ); return *( f.devices().begin() ); } }; public: opencl_foundation(opencl_graph &g) : my_default_opencl_factory(g), my_default_device_selector() { cl_uint num_platforms; enforce_cl_retcode(clGetPlatformIDs(0, NULL, &num_platforms), "clGetPlatformIDs failed"); std::vector<cl_platform_id> platforms(num_platforms); enforce_cl_retcode(clGetPlatformIDs(num_platforms, platforms.data(), NULL), "clGetPlatformIDs failed"); cl_uint num_devices; std::vector<cl_platform_id>::iterator platforms_it = platforms.begin(); cl_uint num_all_devices = 0; while (platforms_it != platforms.end()) { cl_int err = clGetDeviceIDs(*platforms_it, CL_DEVICE_TYPE_ALL, 0, NULL, &num_devices); if (err == CL_DEVICE_NOT_FOUND) { platforms_it = platforms.erase(platforms_it); } else { enforce_cl_retcode(err, "clGetDeviceIDs failed"); num_all_devices += num_devices; ++platforms_it; } } std::vector<cl_device_id> devices(num_all_devices); std::vector<cl_device_id>::iterator devices_it = devices.begin(); for (auto p = platforms.begin(); p != platforms.end(); ++p) { enforce_cl_retcode(clGetDeviceIDs((*p), CL_DEVICE_TYPE_ALL, (cl_uint)std::distance(devices_it, devices.end()), &*devices_it, &num_devices), "clGetDeviceIDs failed"); devices_it += num_devices; } for (auto d = devices.begin(); d != devices.end(); ++d) { my_devices.add(opencl_device((*d))); } } default_opencl_factory &get_default_opencl_factory() { return my_default_opencl_factory; } const opencl_device_list &get_all_devices() { return my_devices; } default_device_selector_type get_default_device_selector() { return my_default_device_selector; } private: default_opencl_factory my_default_opencl_factory; opencl_device_list my_devices; const default_device_selector_type my_default_device_selector; }; opencl_foundation &opencl_graph::get_opencl_foundation() { opencl_foundation* INITIALIZATION = (opencl_foundation*)1; if ( my_opencl_foundation <= INITIALIZATION ) { if ( tbb::internal::as_atomic( my_opencl_foundation ).compare_and_swap( INITIALIZATION, NULL ) == 0 ) { my_opencl_foundation = new opencl_foundation( *this ); } else { tbb::internal::spin_wait_while_eq( my_opencl_foundation, INITIALIZATION ); } } __TBB_ASSERT( my_opencl_foundation > INITIALIZATION, "opencl_foundation is not initialized"); return *my_opencl_foundation; } opencl_graph::~opencl_graph() { if ( my_opencl_foundation ) delete my_opencl_foundation; } template <typename DeviceFilter> void opencl_factory<DeviceFilter>::init_once() { { tbb::spin_mutex::scoped_lock lock( my_devices_mutex ); if ( !my_devices.size() ) my_devices = DeviceFilter()(my_graph.get_opencl_foundation().get_all_devices()); } enforce_cl_retcode( my_devices.size() ? CL_SUCCESS : CL_INVALID_DEVICE, "No devices in the device list" ); cl_platform_id platform_id = my_devices.begin()->platform(); for ( opencl_device_list::iterator it = ++my_devices.begin(); it != my_devices.end(); ++it ) enforce_cl_retcode( it->platform() == platform_id ? CL_SUCCESS : CL_INVALID_PLATFORM, "All devices should be in the same platform" ); std::vector<cl_device_id> cl_device_ids; for (auto d = my_devices.begin(); d != my_devices.end(); ++d) { cl_device_ids.push_back((*d).my_cl_device_id); } cl_context_properties context_properties[3] = { CL_CONTEXT_PLATFORM, (cl_context_properties)platform_id, (cl_context_properties)NULL }; cl_int err; cl_context ctx = clCreateContext( context_properties, (cl_uint)cl_device_ids.size(), cl_device_ids.data(), NULL, NULL, &err ); enforce_cl_retcode( err, "Failed to create context" ); my_cl_context = ctx; size_t device_counter = 0; for ( auto d = my_devices.begin(); d != my_devices.end(); d++ ) { (*d).my_device_id = device_counter++; cl_int err2; cl_command_queue cq; #if CL_VERSION_2_0 if ( (*d).major_version() >= 2 ) { if ( (*d).out_of_order_exec_mode_on_host_present() ) { cl_queue_properties props[] = { CL_QUEUE_PROPERTIES, CL_QUEUE_OUT_OF_ORDER_EXEC_MODE_ENABLE, 0 }; cq = clCreateCommandQueueWithProperties( ctx, (*d).my_cl_device_id, props, &err2 ); } else { cl_queue_properties props[] = { 0 }; cq = clCreateCommandQueueWithProperties( ctx, (*d).my_cl_device_id, props, &err2 ); } } else #endif { cl_command_queue_properties props = (*d).out_of_order_exec_mode_on_host_present() ? CL_QUEUE_OUT_OF_ORDER_EXEC_MODE_ENABLE : 0; // Suppress "declared deprecated" warning for the next line. #if __TBB_GCC_WARNING_SUPPRESSION_PRESENT #pragma GCC diagnostic push // #pragma GCC diagnostic ignored "-Wdeprecated-declarations" #endif #if _MSC_VER || __INTEL_COMPILER #pragma warning( push ) #if __INTEL_COMPILER #pragma warning (disable: 1478) #else #pragma warning (disable: 4996) #endif #endif cq = clCreateCommandQueue( ctx, (*d).my_cl_device_id, props, &err2 ); #if _MSC_VER || __INTEL_COMPILER #pragma warning( pop ) #endif #if __TBB_GCC_WARNING_SUPPRESSION_PRESENT #pragma GCC diagnostic pop #endif } enforce_cl_retcode( err2, "Failed to create command queue" ); (*d).my_cl_command_queue = cq; } } const opencl_device_list &opencl_graph::available_devices() { return get_opencl_foundation().get_all_devices(); } default_opencl_factory &opencl_graph::opencl_factory() { return get_opencl_foundation().get_default_opencl_factory(); } template <typename T, typename Factory> opencl_buffer<T, Factory>::opencl_buffer( opencl_graph &g, size_t size ) : my_impl( std::make_shared<impl_type>( size*sizeof(T), g.get_opencl_foundation().get_default_opencl_factory() ) ) {} enum class opencl_program_type { SOURCE, PRECOMPILED, SPIR }; template <typename Factory = default_opencl_factory> class opencl_program : tbb::internal::no_assign { public: typedef typename Factory::kernel_type kernel_type; opencl_program( Factory& factory, opencl_program_type type, const std::string& program_name ) : my_factory( factory ), my_type(type) , my_arg_str( program_name) {} opencl_program( Factory& factory, const char* program_name ) : opencl_program( factory, std::string( program_name ) ) {} opencl_program( Factory& factory, const std::string& program_name ) : opencl_program( factory, opencl_program_type::SOURCE, program_name ) {} opencl_program( opencl_graph& graph, opencl_program_type type, const std::string& program_name ) : opencl_program( graph.opencl_factory(), type, program_name ) {} opencl_program( opencl_graph& graph, const char* program_name ) : opencl_program( graph.opencl_factory(), program_name ) {} opencl_program( opencl_graph& graph, const std::string& program_name ) : opencl_program( graph.opencl_factory(), program_name ) {} opencl_program( opencl_graph& graph, opencl_program_type type ) : opencl_program( graph.opencl_factory(), type ) {} opencl_program( const opencl_program &src ) : my_factory( src.my_factory ), my_type( src.type ), my_arg_str( src.my_arg_str ), my_cl_program( src.my_cl_program ) { // Set my_do_once_flag to the called state. std::call_once( my_do_once_flag, [](){} ); } kernel_type get_kernel( const std::string& k ) const { return kernel_type( get_cl_kernel(k), my_factory ); } private: opencl_program( Factory& factory, cl_program program ) : my_factory( factory ), my_cl_program( program ) { // Set my_do_once_flag to the called state. std::call_once( my_do_once_flag, [](){} ); } cl_kernel get_cl_kernel( const std::string& k ) const { std::call_once( my_do_once_flag, [this, &k](){ this->init( k ); } ); cl_int err; cl_kernel kernel = clCreateKernel( my_cl_program, k.c_str(), &err ); enforce_cl_retcode( err, std::string( "Failed to create kernel: " ) + k ); return kernel; } class file_reader { public: file_reader( const std::string& filepath ) { std::ifstream file_descriptor( filepath, std::ifstream::binary ); if ( !file_descriptor.is_open() ) { std::string str = std::string( "Could not open file: " ) + filepath; std::cerr << str << std::endl; throw str; } file_descriptor.seekg( 0, file_descriptor.end ); size_t length = size_t( file_descriptor.tellg() ); file_descriptor.seekg( 0, file_descriptor.beg ); my_content.resize( length ); char* begin = &*my_content.begin(); file_descriptor.read( begin, length ); file_descriptor.close(); } const char* content() { return &*my_content.cbegin(); } size_t length() { return my_content.length(); } private: std::string my_content; }; class opencl_program_builder { public: typedef void (CL_CALLBACK *cl_callback_type)(cl_program, void*); opencl_program_builder( Factory& f, const std::string& name, cl_program program, cl_uint num_devices, cl_device_id* device_list, const char* options, cl_callback_type callback, void* user_data ) { cl_int err = clBuildProgram( program, num_devices, device_list, options, callback, user_data ); if( err == CL_SUCCESS ) return; std::string str = std::string( "Failed to build program: " ) + name; if ( err == CL_BUILD_PROGRAM_FAILURE ) { const opencl_device_list &devices = f.devices(); for ( auto d = devices.begin(); d != devices.end(); ++d ) { std::cerr << "Build log for device: " << (*d).name() << std::endl; size_t log_size; cl_int query_err = clGetProgramBuildInfo( program, (*d).my_cl_device_id, CL_PROGRAM_BUILD_LOG, 0, NULL, &log_size ); enforce_cl_retcode( query_err, "Failed to get build log size" ); if( log_size ) { std::vector<char> output; output.resize( log_size ); query_err = clGetProgramBuildInfo( program, (*d).my_cl_device_id, CL_PROGRAM_BUILD_LOG, output.size(), output.data(), NULL ); enforce_cl_retcode( query_err, "Failed to get build output" ); std::cerr << output.data() << std::endl; } else { std::cerr << "No build log available" << std::endl; } } } enforce_cl_retcode( err, str ); } }; class opencl_device_filter { public: template<typename Filter> opencl_device_filter( cl_uint& num_devices, cl_device_id* device_list, Filter filter, const char* message ) { for ( cl_uint i = 0; i < num_devices; ++i ) if ( filter(device_list[i]) ) { device_list[i--] = device_list[--num_devices]; } if ( !num_devices ) enforce_cl_retcode( CL_DEVICE_NOT_AVAILABLE, message ); } }; void init( const std::string& ) const { cl_uint num_devices; enforce_cl_retcode( clGetContextInfo( my_factory.context(), CL_CONTEXT_NUM_DEVICES, sizeof( num_devices ), &num_devices, NULL ), "Failed to get OpenCL context info" ); if ( !num_devices ) enforce_cl_retcode( CL_DEVICE_NOT_FOUND, "No supported devices found" ); cl_device_id *device_list = (cl_device_id *)alloca( num_devices*sizeof( cl_device_id ) ); enforce_cl_retcode( clGetContextInfo( my_factory.context(), CL_CONTEXT_DEVICES, num_devices*sizeof( cl_device_id ), device_list, NULL ), "Failed to get OpenCL context info" ); const char *options = NULL; switch ( my_type ) { case opencl_program_type::SOURCE: { file_reader fr( my_arg_str ); const char *s[] = { fr.content() }; const size_t l[] = { fr.length() }; cl_int err; my_cl_program = clCreateProgramWithSource( my_factory.context(), 1, s, l, &err ); enforce_cl_retcode( err, std::string( "Failed to create program: " ) + my_arg_str ); opencl_device_filter( num_devices, device_list, []( const opencl_device& d ) -> bool { return !d.compiler_available() || !d.linker_available(); }, "No one device supports building program from sources" ); opencl_program_builder( my_factory, my_arg_str, my_cl_program, num_devices, device_list, options, /*callback*/ NULL, /*user data*/NULL ); break; } case opencl_program_type::SPIR: options = "-x spir"; case opencl_program_type::PRECOMPILED: { file_reader fr( my_arg_str ); std::vector<const unsigned char*> s( num_devices, reinterpret_cast<const unsigned char*>(fr.content()) ); std::vector<size_t> l( num_devices, fr.length() ); std::vector<cl_int> bin_statuses( num_devices, -1 ); cl_int err; my_cl_program = clCreateProgramWithBinary( my_factory.context(), num_devices, device_list, l.data(), s.data(), bin_statuses.data(), &err ); if( err != CL_SUCCESS ) { std::string statuses_str; for (auto st = bin_statuses.begin(); st != bin_statuses.end(); ++st) { statuses_str += std::to_string((*st)); } enforce_cl_retcode( err, std::string( "Failed to create program, error " + std::to_string( err ) + " : " ) + my_arg_str + std::string( ", binary_statuses = " ) + statuses_str ); } opencl_program_builder( my_factory, my_arg_str, my_cl_program, num_devices, device_list, options, /*callback*/ NULL, /*user data*/NULL ); break; } default: __TBB_ASSERT( false, "Unsupported program type" ); } } Factory& my_factory; opencl_program_type my_type; std::string my_arg_str; mutable cl_program my_cl_program; mutable std::once_flag my_do_once_flag; template <typename DeviceFilter> friend class opencl_factory; template <typename DeviceFilter> friend class opencl_factory<DeviceFilter>::kernel; }; template<typename... Args> class opencl_node; template<typename JP, typename Factory, typename... Ports> class opencl_node< tuple<Ports...>, JP, Factory > : public streaming_node< tuple<Ports...>, JP, Factory > { typedef streaming_node < tuple<Ports...>, JP, Factory > base_type; public: typedef typename base_type::kernel_type kernel_type; opencl_node( opencl_graph &g, const kernel_type& kernel ) : base_type( g, kernel, g.get_opencl_foundation().get_default_device_selector(), g.get_opencl_foundation().get_default_opencl_factory() ) {} opencl_node( opencl_graph &g, const kernel_type& kernel, Factory &f ) : base_type( g, kernel, g.get_opencl_foundation().get_default_device_selector(), f ) {} template <typename DeviceSelector> opencl_node( opencl_graph &g, const kernel_type& kernel, DeviceSelector d, Factory &f) : base_type( g, kernel, d, f) {} }; template<typename JP, typename... Ports> class opencl_node< tuple<Ports...>, JP > : public opencl_node < tuple<Ports...>, JP, default_opencl_factory > { typedef opencl_node < tuple<Ports...>, JP, default_opencl_factory > base_type; public: typedef typename base_type::kernel_type kernel_type; opencl_node( opencl_graph &g, const kernel_type& kernel ) : base_type( g, kernel, g.get_opencl_foundation().get_default_device_selector(), g.get_opencl_foundation().get_default_opencl_factory() ) {} template <typename DeviceSelector> opencl_node( opencl_graph &g, const kernel_type& kernel, DeviceSelector d ) : base_type( g, kernel, d, g.get_opencl_foundation().get_default_opencl_factory() ) {} }; template<typename... Ports> class opencl_node< tuple<Ports...> > : public opencl_node < tuple<Ports...>, queueing, default_opencl_factory > { typedef opencl_node < tuple<Ports...>, queueing, default_opencl_factory > base_type; public: typedef typename base_type::kernel_type kernel_type; opencl_node( opencl_graph &g, const kernel_type& kernel ) : base_type( g, kernel, g.get_opencl_foundation().get_default_device_selector(), g.get_opencl_foundation().get_default_opencl_factory() ) {} template <typename DeviceSelector> opencl_node( opencl_graph &g, const kernel_type& kernel, DeviceSelector d ) : base_type( g, kernel, d, g.get_opencl_foundation().get_default_opencl_factory() ) {} }; } // namespace interface9 using interface9::opencl_graph; using interface9::opencl_node; using interface9::read_only; using interface9::read_write; using interface9::write_only; using interface9::opencl_buffer; using interface9::opencl_subbuffer; using interface9::opencl_device; using interface9::opencl_device_list; using interface9::opencl_program; using interface9::opencl_program_type; using interface9::dependency_msg; using interface9::opencl_factory; using interface9::opencl_range; } // namespace flow } // namespace tbb #endif /* __TBB_PREVIEW_OPENCL_NODE */ #endif // __TBB_flow_graph_opencl_node_H
d3a500690115a80dd9f2aa4bdeace366641c3426
1f48a24e68d346164bd654b4c11adcc1770fbcf2
/kocsi_pd.ino
94f2e613079fede2ddeaf8adbd0437def4a346ba
[ "MIT" ]
permissive
erwzqsdsdsf/TDK
018f04e9f3bfacf1ae3ca7d4ff062072ae6a9bd7
c62c4ffac17caeed9d09f63f1ee068a19f85b679
refs/heads/master
2022-04-09T18:56:38.396222
2020-02-28T09:20:16
2020-02-28T09:20:16
null
0
0
null
null
null
null
UTF-8
C++
false
false
6,529
ino
#include <Arduino.h> #include <Wire.h> #include <avr/wdt.h> #include "PinChangeInt.h" //interrupt kezeléshez //lábkiosztás definiálása #define enc_pend1 4 //szögelfordulás mérése #define enc_pend2 5 #define enc_cart1 2 //kocsi elmozdulásmérése #define enc_cart2 3 #define rotR 12 //motor forgásiránya #define rotL 13 #define pwm 10 //PWM jel #define integral_null 8 //integrátor tag nullázása #define poti 5 //poti #define MAXPWM 230 //maximális kiadható PWM #define calibn 7 //szögelfordulás nullpontjának #define calibp 11 //kalibrálása #define xnull 9 volatile int lastEncoded_pend = 0; volatile int lastEncoded_cart = 0; volatile long sum_pend = -1200; //nullpont beállítása alsó long last_sum_pend = 0; //egyensúlyi helyzetben volatile long sum_cart = 0; //kalibrálás a kocsi szélső, //nullpont a középső helyzetében double last_sum_cart = 0; double xIntegral = 0; long lastencoderValue_pend = 0; long lastencoderValue_cart = 0; int currPos = 0; int lastPos = 0; unsigned long currTime = 0; unsigned long currTimeM = 0; unsigned long lastTime = 0; double sampleTime = 5; //mintavételezési idő double velocity = 0; double angVelocity = 0; //szabalyozo parameterei double p_fi = 90; double d_fi = 4.7 / (sampleTime); double p_x = 0.005; double d_x = 0.08 / (sampleTime); //pwm int pwmValue; //haladási irányu bool R = 0; int potiVal = 0; //mozgoatlag const int M = 1; double readings[M]; int readIndex = 0; double total = 0; double average = 0; void setup() { Serial.begin (9600); pinMode(enc_pend1, INPUT_PULLUP); pinMode(enc_pend2, INPUT_PULLUP); pinMode(enc_cart1,INPUT); pinMode(enc_cart2, INPUT); pinMode(integral_null, INPUT); pinMode(poti,INPUT); pinMode(calibp,INPUT); pinMode(calibn,INPUT); pinMode(xnull, INPUT_PULLUP); //felhúzó ellenállások aktiválása digitalWrite(enc_pend1, HIGH); digitalWrite(enc_pend2, HIGH); digitalWrite(enc_cart1, HIGH); digitalWrite(enc_cart2, HIGH); digitalWrite(xnull, HIGH); //updateEncoder() függvény meghívása a fototranzisztor jelszintjének //változásakor attachPinChangeInterrupt(enc_pend1, updateEncoderPend, CHANGE); attachPinChangeInterrupt(enc_pend2, updateEncoderPend, CHANGE); attachPinChangeInterrupt(xnull, xNull, RISING); attachInterrupt(0, updateEncoderCart, CHANGE); attachInterrupt(1, updateEncoderCart, CHANGE); //motorvezérlőhöz tartozó pinek kalibrálása pinMode(pwm,OUTPUT); pinMode(rotR,OUTPUT); pinMode(rotL,OUTPUT); pwmValue = 0; Left(); analogWrite(pwm,pwmValue); // light = analogRead(LIGHT); // last_light = light; } void loop(){ currTime = micros(); //beavatkozó feszültség számítása: if(currTime - lastTime >= sampleTime * 1000){ // currTimeM = micros(); // movingAverage(sum_cart); // if(p_x * average < -5) average = -5 / p_x; // if(p_x * average > 5) average = 5 / p_x; pwmValue = p_fi * (double(sum_pend) + p_x * double(sum_cart) + d_x * double(sum_cart - last_sum_cart)) + d_fi * (double(sum_pend - last_sum_pend) + p_x * double(sum_cart) + d_x * double(sum_cart - last_sum_cart)); last_sum_pend = sum_pend; last_sum_cart = sum_cart; lastTime = currTime; if(pwmValue >= 0) Right(); else Left(); pwmValue = abs(pwmValue); //ha túl közel vagyunk a szerkezet széléhez: if(abs(sum_cart) >= 3200) pwmValue = 0; //telítődés esetére: if(pwmValue > MAXPWM) pwmValue = MAXPWM; analogWrite(pwm,pwmValue); // if(++i > 50){ // Serial.println(pwmValue); // i=0; // } // i = micros(); // Serial.println(i-currTimeM); // Serial.print('\t'); // if(abs(analogRead(LIGHT)-light) > 150) // { // enabledata = !enabledata; // light = analogRead(LIGHT); // } // enabledata = (abs(analogRead(LIGHT)-light) > 150); // if(enabledata && (i < arraysize)){ // cartarray[i] = sum_cart; // pendarray[i] = sum_pend; // i++; // } // if(!enabledata && i>200){ // analogWrite(pwm,0); // for(int j = 0; j <= i; j++){ // Serial.print(cartarray[j]); // Serial.print('\t'); // Serial.println(pendarray[j]); // } // i = 0; // } } // // //szögelfordulás nullpontjának menet közbeni kalibrálására if(digitalRead(calibp)){ sum_pend = sum_pend + 1; delay(300); } if(digitalRead(calibn)){ sum_pend = sum_pend - 1; delay(300); } //integrátor menet közbeni nullázására if(digitalRead(integral_null)){ xIntegral = 0; sum_cart = 0; } // //Serial.print(sum_pend); // //Serial.print('\t'); // //Serial.println(digitalRead(calibn)); } void updateEncoderPend(){ int MSB = digitalRead(enc_pend1); //MSB = most significant bit int LSB = digitalRead(enc_pend2); //LSB = least significant bit //a pinek értékének konvertálása egész számmá: int encoded = (MSB << 1) |LSB; //az előző értékhez való hozzáadás int sum = (lastEncoded_pend << 2) | encoded; //menetirány megállapítása, ez alapján az elfordulásérték frissítése if(sum == 0b1101 || sum == 0b0100 || sum == 0b0010 || sum == 0b1011) sum_pend ++; if(sum == 0b1110 || sum == 0b0111 || sum == 0b0001 || sum == 0b1000) sum_pend --; lastEncoded_pend = encoded; } void updateEncoderCart(){ int MSB = digitalRead(enc_cart1); int LSB = digitalRead(enc_cart2); int encoded = (MSB << 1) |LSB; int sum = (lastEncoded_cart << 2) | encoded; if(sum == 0b1101 || sum == 0b0100 || sum == 0b0010 || sum == 0b1011) sum_cart --; if(sum == 0b1110 || sum == 0b0111 || sum == 0b0001 || sum == 0b1000) sum_cart ++; lastEncoded_cart = encoded; } //ha negatív x irányba kell a kocsit vezérelni void Left() { digitalWrite(rotR,LOW); digitalWrite(rotL,HIGH); R = 0; } //ha pozitív x irányba kell a kocsit vezérelni void Right(){ digitalWrite(rotL,LOW); digitalWrite(rotR,HIGH); R = 1; } void movingAverage(double unit){ total -= readings[readIndex]; readings[readIndex] = unit; total += readings[readIndex]; readIndex++; if(readIndex >= M) readIndex = 0; average = total / M; } void xNull(){ sum_cart = 0; }
a4c62877e6c1d20e71dc914be8a9177173f8443f
736c9e4877ccdecd96d233d67d4e395e5f735919
/pcc-gradient/sender/app/incast_client.cpp
5a2d09a50a20adc972a85dd2791ceb88b8fd155b
[ "GPL-3.0-only" ]
permissive
5G-Measurement/PCC-Uspace
a35601692360290596fd9940ca11973c7ea0c23d
f89a3de579344585e38c926262bdb05964dd08b8
refs/heads/master
2023-01-24T00:18:35.610111
2020-11-22T03:53:43
2020-11-22T03:53:43
313,701,713
0
0
BSD-3-Clause
2020-11-17T18:51:29
2020-11-17T18:02:30
null
UTF-8
C++
false
false
5,192
cpp
#ifndef WIN32 #include <unistd.h> #include <cstdlib> #include <cstring> #include <netdb.h> #include <time.h> #include <math.h> #else #include <winsock2.h> #include <ws2tcpip.h> #include <wspiapi.h> #endif #include <iostream> #include <udt.h> #include "cc_incast.h" #include <sys/time.h> using namespace std; int windowsize; char argv1[50],argv2[50]; int Interval_avg; int tt; int trap; int safe; #ifndef WIN32 void* monitor(void*); void* worker(void*); #else DWORD WINAPI monitor(LPVOID); #endif int count=0; double avg_fluc; struct timeval current; int start_s, start_us; int data_length; int main(int argc, char* argv[]) { //sendinginterval=0; start_s = atoi(argv[4]); start_us = atoi(argv[5]); pthread_t t; tt=0; Interval_avg=50; avg_fluc=0.25; strcpy(argv1,argv[1]); strcpy(argv2,argv[2]); data_length = atoi(argv[3]); // use this function to initialize the UDT library int i=0; while(i<1){ i++; pthread_create(&t, NULL, worker, NULL); pthread_join(t,NULL); } return 1; } void * worker(void * s) { cout<<endl; srand((unsigned)time(NULL)); windowsize=data_length;//rand()%900+100; UDT::startup(); struct addrinfo hints, *local, *peer; memset(&hints, 0, sizeof(struct addrinfo)); hints.ai_flags = AI_PASSIVE; hints.ai_family = AF_INET; hints.ai_socktype = SOCK_STREAM; //hints.ai_socktype = SOCK_DGRAM; if (0 != getaddrinfo(NULL, "9000", &hints, &local)) { cout << "incorrect network address.\n" << endl; return 0; } UDTSOCKET client = UDT::socket(local->ai_family, local->ai_socktype, local->ai_protocol); // UDT Options UDT::setsockopt(client, 0, UDT_CC, new CCCFactory<BBCC>, sizeof(CCCFactory<BBCC>)); //UDT::setsockopt(client, 0, UDT_MSS, new int(9000), sizeof(int)); //UDT::setsockopt(client, 0, UDT_SNDBUF, new int(10000000), sizeof(int)); //UDT::setsockopt(client, 0, UDP_SNDBUF, new int(10000000), sizeof(int)); // Windows UDP issue // For better performance, modify HKLM\System\CurrentControlSet\Services\Afd\Parameters\FastSendDatagramThreshold #ifdef WIN32 UDT::setsockopt(client, 0, UDT_MSS, new int(1052), sizeof(int)); #endif // for rendezvous connection, enable the code below /* UDT::setsockopt(client, 0, UDT_RENDEZVOUS, new bool(true), sizeof(bool)); if (UDT::ERROR == UDT::bind(client, local->ai_addr, local->ai_addrlen)) { cout << "bind: " << UDT::getlasterror().getErrorMessage() << endl; return 0; } */ freeaddrinfo(local); if (0 != getaddrinfo(argv1, argv2, &hints, &peer)) { cout << "incorrect server/peer address. " << argv1 << ":" << argv2 << endl; return 0; } // connect to the server, implict bind if (UDT::ERROR == UDT::connect(client, peer->ai_addr, peer->ai_addrlen)) { cout << "connect: " << UDT::getlasterror().getErrorMessage() << endl; return 0; } ; freeaddrinfo(peer); // using CC method BBCC* cchandle = NULL; int temp; UDT::getsockopt(client, 0, UDT_CC, &cchandle, &temp); // if (NULL != cchandle) // cout<<"notNULL!"<<endl; // cchandle->setRate(5); //cchandle->m_dCWndSize=windowsize+100; //cout<<cchandle->m_dCWndSize<<endl; //cout<<"k"<<cchandle->m_dCWndSize<<endl; int usize = 1456; int size=0; size=usize*windowsize; //cout<<"size"<<size<<endl; char* data = new char[size]; #ifndef WIN32 // count++; //cout<<count<<endl; #else CreateThread(NULL, 0, monitor, &client, 0, NULL); #endif int ssize = 0; int ss=0; do { gettimeofday(&current, NULL); if (current.tv_sec>=start_s+2 && current.tv_usec>=start_us) break; } while(1); // cout<<start.tv_sec<<"."<<start.tv_usec<<endl; cout<<"Start time "<<current.tv_sec<<"."<<current.tv_usec<<endl; if (UDT::ERROR == (ss = UDT::send(client, data + ssize, size - ssize, 0))) { cout << "send:" << UDT::getlasterror().getErrorMessage() << endl; //break; } //cout<<ss<<endl; sleep(5); //cout<<cchandle->count2<<endl; //cout<<cchandle->m_dCWndSize<<endl; //cout<<"YES!!"<<cchandle->haslost<<endl; /*if(cchandle->haslost) {cchandle->haslost=0; windowsize-=4;} if(cchandle->hasloss) {cchandle->hasloss=0; windowsize-=7; } windowsize+=2; if(ss==size) // cout<<"FINISH!"<<endl; */ //cout<<windowsize<<endl; //sleep(5); delete [] data; UDT::close(client); // use this function to release the UDT library UDT::cleanup(); //cout<<"TIME,"<<time<<endl; sleep(3); return NULL; } #ifndef WIN32 void* monitor(void* s) #else DWORD WINAPI monitor(LPVOID s) #endif { UDTSOCKET u = *(UDTSOCKET*)s; UDT::TRACEINFO perf; cout << "SendRate(Mb/s)\tRTT(ms)\tCWnd\tPktSndPeriod(us)\tRecvACK\tLoss" << endl; while (true) { #ifndef WIN32 sleep(100); #else Sleep(100); #endif if (UDT::ERROR == UDT::perfmon(u, &perf)) { cout << "perfmon: " << UDT::getlasterror().getErrorMessage() << endl; break; } cout << perf.pktCongestionWindow << endl; } #ifndef WIN32 return NULL; #else return 0; #endif }
02792efc58567c93adaa1f8f828d230c4152afb2
c5efae416d17809142a24bf6536eb3d48c75843e
/pywin32-217/com/win32com/src/PythonCOM.cpp
18b4d8d9afbe3a7d7523f6faaf5940bc20906367
[]
no_license
ctismer/Python-2.7.5-VS2010
846a804cee8fa7143d6fdcd3b4e9b60c24c1428f
63476264a452d856ae197f46070f96fd8f4a066d
refs/heads/master
2020-12-14T02:11:04.334418
2013-08-09T20:45:04
2013-08-09T20:45:04
null
0
0
null
null
null
null
WINDOWS-1250
C++
false
false
98,519
cpp
// pythoncom.cpp : /*** Note that this source file contains embedded documentation. This documentation consists of marked up text inside the C comments, and is prefixed with an '@' symbol. The source files are processed by a tool called "autoduck" which generates Windows .hlp files. @doc ***/ #include "stdafx.h" #include <objbase.h> #include "PythonCOM.h" #include "PythonCOMServer.h" #include "PyFactory.h" #include "PyRecord.h" #include "PyComTypeObjects.h" #include "OleAcc.h" // for ObjectFromLresult proto... #include "pyerrors.h" // for PyErr_Warn in 2.5 and earlier... extern int PyCom_RegisterCoreIIDs(PyObject *dict); extern int PyCom_RegisterCoreSupport(void); extern PyObject *pythoncom_IsGatewayRegistered(PyObject *self, PyObject *args); extern PyObject *g_obPyCom_MapIIDToType; extern PyObject *g_obPyCom_MapGatewayIIDToName; extern PyObject *g_obPyCom_MapInterfaceNameToIID; PyObject *g_obEmpty = NULL; PyObject *g_obMissing = NULL; PyObject *g_obArgNotFound = NULL; PyObject *PyCom_InternalError = NULL; // Storage related functions. extern PyObject *pythoncom_StgOpenStorage(PyObject *self, PyObject *args); extern PyObject *pythoncom_StgOpenStorageEx(PyObject *self, PyObject *args); extern PyObject *pythoncom_FmtIdToPropStgName(PyObject *self, PyObject *args); extern PyObject *pythoncom_PropStgNameToFmtId(PyObject *self, PyObject *args); #ifndef MS_WINCE extern PyObject *pythoncom_StgIsStorageFile(PyObject *self, PyObject *args); #endif // MS_WINCE extern PyObject *pythoncom_StgCreateDocfile(PyObject *self, PyObject *args); extern PyObject *pythoncom_StgCreateDocfileOnILockBytes(PyObject *self, PyObject *args); extern PyObject *pythoncom_WriteClassStg(PyObject *self, PyObject *args); extern PyObject *pythoncom_ReadClassStg(PyObject *self, PyObject *args); extern PyObject *pythoncom_WriteClassStm(PyObject *self, PyObject *args); extern PyObject *pythoncom_ReadClassStm(PyObject *self, PyObject *args); extern PyObject *pythoncom_CreateStreamOnHGlobal(PyObject *self, PyObject *args); extern PyObject *pythoncom_CreateILockBytesOnHGlobal(PyObject *self, PyObject *args); extern PyObject *pythoncom_GetRecordFromGuids(PyObject *self, PyObject *args); extern PyObject *pythoncom_GetRecordFromTypeInfo(PyObject *self, PyObject *args); extern PyObject *Py_NewSTGMEDIUM(PyObject *self, PyObject *args); // Typelib related functions extern PyObject *pythoncom_loadtypelib(PyObject *self, PyObject *args); extern PyObject *pythoncom_loadregtypelib(PyObject *self, PyObject *args); extern PyObject *pythoncom_registertypelib(PyObject *self, PyObject *args); extern PyObject *pythoncom_unregistertypelib(PyObject *self, PyObject *args); #ifndef MS_WINCE extern PyObject *pythoncom_querypathofregtypelib(PyObject *self, PyObject *args); #endif // MS_WINCE // Type object helpers PyObject *Py_NewFUNCDESC(PyObject *self, PyObject *args); PyObject *Py_NewTYPEATTR(PyObject *self, PyObject *args); PyObject *Py_NewVARDESC(PyObject *self, PyObject *args); // Error related functions void GetScodeString(SCODE sc, TCHAR *buf, int bufSize); LPCTSTR GetScodeRangeString(SCODE sc); LPCTSTR GetSeverityString(SCODE sc); LPCTSTR GetFacilityString(SCODE sc); /* Debug/Test helpers */ extern LONG _PyCom_GetInterfaceCount(void); extern LONG _PyCom_GetGatewayCount(void); // Function pointers we load at runtime. #define CHECK_PFN(fname) if (pfn##fname==NULL) return PyCom_BuildPyException(E_NOTIMPL); typedef HRESULT (STDAPICALLTYPE *CoWaitForMultipleHandlesfunc)(DWORD dwFlags, DWORD dwTimeout, ULONG cHandles, LPHANDLE pHandles, LPDWORD lpdwindex ); static CoWaitForMultipleHandlesfunc pfnCoWaitForMultipleHandles = NULL; typedef HRESULT (STDAPICALLTYPE *CreateURLMonikerExfunc)(LPMONIKER,LPCWSTR,LPMONIKER *,DWORD); static CreateURLMonikerExfunc pfnCreateURLMonikerEx = NULL; // typedefs for the function pointers are in OleAcc.h LPFNOBJECTFROMLRESULT pfnObjectFromLresult = NULL; BOOL PyCom_HasDCom() { #ifndef MS_WINCE static BOOL bHaveDCOM = -1; if (bHaveDCOM==-1) { HMODULE hMod = GetModuleHandle(_T("ole32.dll")); if (hMod) { FARPROC fp = GetProcAddress(hMod, "CoInitializeEx"); bHaveDCOM = (fp!=NULL); } else bHaveDCOM = FALSE; // not much we can do! } return bHaveDCOM; #else // no DCOM on WinCE. return FALSE; #endif } #ifdef _MSC_VER #pragma optimize ("y", off) #endif // _MSC_VER // This optimisation seems to screw things in release builds... /* MODULE FUNCTIONS: pythoncom */ // @pymethod <o PyIUnknown>|pythoncom|CoCreateInstance|Create a new instance of an OLE automation server. static PyObject *pythoncom_CoCreateInstance(PyObject *self, PyObject *args) { PyObject *obCLSID; PyObject *obUnk; DWORD dwClsContext; PyObject *obiid; CLSID clsid; IUnknown *punk; CLSID iid; if (!PyArg_ParseTuple(args, "OOiO:CoCreateInstance", &obCLSID, // @pyparm <o PyIID>|clsid||Class identifier (CLSID) of the object &obUnk, // @pyparm <o PyIUnknown>|unkOuter||The outer unknown, or None &dwClsContext,// @pyparm int|context||The create context for the object &obiid)) // @pyparm <o PyIID>|iid||The IID required from the object return NULL; if (!PyWinObject_AsIID(obCLSID, &clsid)) return NULL; if (!PyWinObject_AsIID(obiid, &iid)) return NULL; if (!PyCom_InterfaceFromPyInstanceOrObject(obUnk, IID_IUnknown, (void **)&punk, TRUE)) return NULL; // Make the call. IUnknown *result = NULL; PY_INTERFACE_PRECALL; SCODE sc = CoCreateInstance(clsid, punk, dwClsContext, iid, (void **)&result); if ( punk ) punk->Release(); PY_INTERFACE_POSTCALL; if (FAILED(sc)) return PyCom_BuildPyException(sc); return PyCom_PyObjectFromIUnknown(result, iid); } #ifdef _MSC_VER #pragma optimize ("", on) #endif // _MSC_VER #ifndef MS_WINCE #ifdef _MSC_VER #pragma optimize ("", off) #endif // _MSC_VER // @pymethod <o PyIUnknown>|pythoncom|CoCreateInstanceEx|Create a new instance of an OLE automation server possibly on a remote machine. static PyObject *pythoncom_CoCreateInstanceEx(PyObject *self, PyObject *args) { PyObject *obCLSID; PyObject *obUnk; PyObject *obCoServer; DWORD dwClsContext; PyObject *obrgiids; CLSID clsid; COSERVERINFO serverInfo = {0, NULL, NULL, 0}; COSERVERINFO *pServerInfo = NULL; IID *iids = NULL; MULTI_QI *mqi = NULL; IUnknown *punk = NULL; PyObject *result = NULL; ULONG numIIDs = 0; ULONG i; Py_ssize_t py_numIIDs; if (!PyArg_ParseTuple(args, "OOiOO:CoCreateInstanceEx", &obCLSID, // @pyparm <o PyIID>|clsid||Class identifier (CLSID) of the object &obUnk, // @pyparm <o PyIUnknown>|unkOuter||The outer unknown, or None &dwClsContext, // @pyparm int|context||The create context for the object &obCoServer, // @pyparm (server, authino=None, reserved1=0,reserved2=0)|serverInfo||May be None, or describes the remote server to execute on. &obrgiids)) // @pyparm [<o PyIID>, ...]|iids||A list of IIDs required from the object return NULL; if (!PyWinObject_AsIID(obCLSID, &clsid)) goto done; if (obCoServer==Py_None) pServerInfo = NULL; else { pServerInfo = &serverInfo; PyObject *obName, *obAuth = Py_None; if (!PyArg_ParseTuple(obCoServer, "O|Oii", &obName, &obAuth, &serverInfo.dwReserved1, &serverInfo.dwReserved2)) { PyErr_Clear(); PyErr_SetString(PyExc_TypeError, "The SERVERINFO is not in the correct format"); goto done; } if (obAuth!=Py_None) { PyErr_SetString(PyExc_TypeError, "authinfo in the SERVERINFO must be None"); goto done; } if (!PyWinObject_AsWCHAR(obName, &serverInfo.pwszName, FALSE)) goto done; } if (!PyCom_InterfaceFromPyInstanceOrObject(obUnk, IID_IUnknown, (void **)&punk, TRUE)) goto done; if (!PySequence_Check(obrgiids)) { PyErr_SetString(PyExc_TypeError, "IID's must be sequence of IID objects"); goto done; } py_numIIDs = PySequence_Length(obrgiids); if (py_numIIDs > ULONG_MAX){ PyErr_Format(PyExc_ValueError, "%u is maximum number of IIDs", ULONG_MAX); goto done; } numIIDs=(ULONG)py_numIIDs; iids = new IID[numIIDs]; mqi = new MULTI_QI[numIIDs]; if (iids==NULL || mqi==NULL) { PyErr_SetString(PyExc_MemoryError, "Allocating MULTIQI array"); goto done; } for (i=0;i<numIIDs;i++) { PyObject *me = PySequence_GetItem(obrgiids, i); if (me==NULL) goto done; BOOL ok = PyWinObject_AsIID(me, iids+i); Py_DECREF(me); if (!ok) goto done; mqi[i].pIID = iids+i; mqi[i].pItf = NULL; mqi[i].hr = 0; } // Jump hoops in case the platform doesnt have it. { // scoping HRESULT (STDAPICALLTYPE *mypfn)(REFCLSID, IUnknown *, DWORD, COSERVERINFO *, ULONG, MULTI_QI *); HMODULE hMod = GetModuleHandle(_T("ole32.dll")); if (hMod==0) { PyCom_BuildInternalPyException("Can not load ole32.dll"); goto done; } FARPROC fp = GetProcAddress(hMod, "CoCreateInstanceEx"); if (fp==NULL) { PyCom_BuildPyException(E_NOTIMPL); goto done; } mypfn = (HRESULT (STDAPICALLTYPE *)(REFCLSID, IUnknown *, DWORD, COSERVERINFO *, ULONG, MULTI_QI *))fp; PY_INTERFACE_PRECALL; HRESULT hr = (*mypfn)(clsid, punk, dwClsContext, pServerInfo, numIIDs, mqi); PY_INTERFACE_POSTCALL; if (FAILED(hr)) { PyCom_BuildPyException(hr); goto done; } } // end scoping. result = PyTuple_New(numIIDs); if (result==NULL) goto done; for (i=0;i<numIIDs;i++) { PyObject *obNew; if (mqi[i].hr==0) obNew = PyCom_PyObjectFromIUnknown(mqi[i].pItf, *mqi[i].pIID, FALSE); else { obNew = Py_None; Py_INCREF(Py_None); } PyTuple_SET_ITEM(result, i, obNew); } done: if (punk) { PY_INTERFACE_PRECALL; punk->Release(); PY_INTERFACE_POSTCALL; } if (serverInfo.pwszName) PyWinObject_FreeWCHAR(serverInfo.pwszName); delete [] iids; delete [] mqi; return result; } #ifdef _MSC_VER #pragma optimize ("", on) #endif // _MSC_VER // @pymethod |pythoncom|CoInitializeSecurity|Registers security and sets the default security values. static PyObject *pythoncom_CoInitializeSecurity(PyObject *self, PyObject *args) { DWORD cAuthSvc; SOLE_AUTHENTICATION_SERVICE *pAS = NULL; DWORD dwAuthnLevel; DWORD dwImpLevel; DWORD dwCapabilities; PSECURITY_DESCRIPTOR pSD, pSD_absolute=NULL; PyObject *obSD, *obAuthSvc, *obReserved1, *obReserved2, *obAuthInfo; if (!PyArg_ParseTuple(args, "OOOiiOiO:CoInitializeSecurity", &obSD, // @pyparm <o PySECURITY_DESCRIPTOR>|sd||Security descriptor containing access permissions for process' objects, can be None &obAuthSvc, // @pyparm object|authInfo||A value of None tells COM to choose which authentication services to use. An empty list means use no services. &obReserved1,// @pyparm object|reserved1||Must be None &dwAuthnLevel, // @pyparm int|authnLevel||One of pythoncom.RPC_C_AUTHN_LEVEL_* values. The default authentication level for proxies. On the server side, COM will fail calls that arrive at a lower level. All calls to AddRef and Release are made at this level. &dwImpLevel, // @pyparm int|impLevel||One of pythoncom.RPC_C_IMP_LEVEL_* values. The default impersonation level for proxies. This value is not checked on the server side. AddRef and Release calls are made with this impersonation level so even security aware apps should set this carefully. Setting IUnknown security only affects calls to QueryInterface, not AddRef or Release. &obAuthInfo, // @pyparm object|authInfo||Must be None &dwCapabilities, // @pyparm int|capabilities||Additional client and/or server-side capabilities. Any set of pythoncom.EOAC_* flags may be passed. Currently only EOAC_MUTUAL_AUTH, EOAC_SECURE_REFS, and EOAC_NONE are defined &obReserved2)) // @pyparm object|reserved2||Must be None return NULL; if (obReserved1 != Py_None || obReserved2 != Py_None || obAuthInfo != Py_None) { PyErr_SetString(PyExc_TypeError, "Not all of the 'None' arguments are None!"); return NULL; } if (!PyWinObject_AsSECURITY_DESCRIPTOR(obSD, &pSD, /*BOOL bNoneOK = */TRUE)) return NULL; if (obAuthSvc==Py_None) cAuthSvc = (DWORD)-1; else if (PySequence_Check(obAuthSvc)) { cAuthSvc = 0; } else { PyErr_SetString(PyExc_TypeError, "obAuthSvc must be None or an empty sequence."); return NULL; } HMODULE hMod = GetModuleHandle(_T("ole32.dll")); if (hMod==0) return PyCom_BuildInternalPyException("Can not load ole32.dll"); FARPROC fp = GetProcAddress(hMod, "CoInitializeSecurity"); if (fp==NULL) return PyCom_BuildPyException(E_NOTIMPL); typedef HRESULT (STDAPICALLTYPE *CoInitializeSecurityfunc) (PSECURITY_DESCRIPTOR, LONG, SOLE_AUTHENTICATION_SERVICE*, void *, DWORD, DWORD, void *, DWORD, void *); CoInitializeSecurityfunc mypfn=(CoInitializeSecurityfunc)fp; // Security descriptor must be in absolute form if (pSD!=NULL) if (!_MakeAbsoluteSD(pSD, &pSD_absolute)) return NULL; PY_INTERFACE_PRECALL; HRESULT hr = (*mypfn)(pSD_absolute, cAuthSvc, pAS, NULL, dwAuthnLevel, dwImpLevel, NULL, dwCapabilities, NULL); // HRESULT hr = CoInitializeSecurity(pSD, cAuthSvc, pAS, NULL, dwAuthnLevel, dwImpLevel, NULL, dwCapabilities, NULL); PY_INTERFACE_POSTCALL; if (pSD_absolute!=NULL) FreeAbsoluteSD(pSD_absolute); if (FAILED(hr)) return PyCom_BuildPyException(hr); Py_INCREF(Py_None); return Py_None; } #ifdef _MSC_VER #pragma optimize ("y", off) #endif // _MSC_VER // @pymethod int|pythoncom|CoRegisterClassObject|Registers an EXE class object with OLE so other applications can connect to it. static PyObject *pythoncom_CoRegisterClassObject(PyObject *self, PyObject *args) { DWORD reg; DWORD context; DWORD flags; PyObject *obIID, *obFactory; IID iid; if (!PyArg_ParseTuple(args, "OOii:CoRegisterClassObject", &obIID, // @pyparm <o PyIID>|iid||The IID of the object to register &obFactory, // @pyparm <o PyIUnknown>|factory||The class factory object. It is the Python programmers responsibility to ensure this object remains alive until the class is unregistered. &context, // @pyparm int|context||The create context for the server. Must be a combination of the CLSCTX_* flags. &flags)) // @pyparm int|flags||Create flags. return NULL; // @comm The class factory object should be <o PyIClassFactory> object, but as per the COM documentation, only <o PyIUnknown> is checked. if (!PyWinObject_AsIID(obIID, &iid)) return NULL; IUnknown *pFactory; if (!PyCom_InterfaceFromPyObject(obFactory, IID_IUnknown, (void **)&pFactory, /*BOOL bNoneOK=*/FALSE)) return NULL; PY_INTERFACE_PRECALL; HRESULT hr = CoRegisterClassObject(iid, pFactory, context, flags, &reg); pFactory->Release(); PY_INTERFACE_POSTCALL; if (FAILED(hr)) return PyCom_BuildPyException(hr); // @rdesc The result is a handle which should be revoked using <om pythoncom.CoRevokeClassObject> return PyInt_FromLong(reg); } // @pymethod |pythoncom|CoRevokeClassObject|Informs OLE that a class object, previously registered with the <om pythoncom.CoRegisterClassObject> method, is no longer available for use. static PyObject *pythoncom_CoRevokeClassObject(PyObject *self, PyObject *args) { DWORD reg; if (!PyArg_ParseTuple(args, "i:CoRevokeClassObject", &reg)) // @pyparm int|reg||The value returned from <om pythoncom.CoRegisterClassObject> return NULL; PY_INTERFACE_PRECALL; HRESULT hr = CoRevokeClassObject(reg); PY_INTERFACE_POSTCALL; if (FAILED(hr)) { return PyCom_BuildPyException(hr); } Py_INCREF(Py_None); return Py_None; } // @pymethod |pythoncom|CoResumeClassObjects|Called by a server that can register multiple class objects to inform the OLE SCM about all registered classes, and permits activation requests for those class objects. static PyObject *pythoncom_CoResumeClassObjects(PyObject *self, PyObject *args) { if (!PyArg_ParseTuple(args, ":CoResumeClassObjects")) return NULL; PY_INTERFACE_PRECALL; HRESULT hr = CoResumeClassObjects(); PY_INTERFACE_POSTCALL; if (FAILED(hr)) return PyCom_BuildPyException(hr); Py_INCREF(Py_None); return Py_None; } // @pymethod |pythoncom|CoTreatAsClass|Establishes or removes an emulation, in which objects of one class are treated as objects of a different class. static PyObject *pythoncom_CoTreatAsClass(PyObject *self, PyObject *args) { PyObject *obguid1, *obguid2 = NULL; if (!PyArg_ParseTuple(args, "O|O", &obguid1, &obguid2)) return NULL; CLSID clsid1, clsid2 = GUID_NULL; // @pyparm <o PyIID>|clsidold||CLSID of the object to be emulated. // @pyparm <o PyIID>|clsidnew|CLSID_NULL|CLSID of the object that should emulate the original object. This replaces any existing emulation for clsidOld. Can be ommitted or CLSID_NULL, in which case any existing emulation for clsidOld is removed. if (!PyWinObject_AsIID(obguid1, &clsid1)) return NULL; if (obguid2!=NULL && !PyWinObject_AsIID(obguid2, &clsid2)) return NULL; PY_INTERFACE_PRECALL; HRESULT hr = CoTreatAsClass(clsid1, clsid2); PY_INTERFACE_POSTCALL; if (FAILED(hr)) return PyCom_BuildPyException(hr); Py_INCREF(Py_None); return Py_None; } #endif // MS_WINCE // @pymethod <o PyIClassFactory>|pythoncom|MakePyFactory|Creates a new <o PyIClassFactory> object wrapping a PythonCOM Class Factory object. static PyObject *pythoncom_MakePyFactory(PyObject *self, PyObject *args) { PyObject *obIID; if (!PyArg_ParseTuple(args, "O:MakePyFactory", &obIID)) // @pyparm <o PyIID>|iid||The IID of the object the class factory provides. return NULL; IID iid; if (!PyWinObject_AsIID(obIID, &iid)) return NULL; PY_INTERFACE_PRECALL; CPyFactory *pFact = new CPyFactory(iid); PY_INTERFACE_POSTCALL; if (pFact==NULL) return PyCom_BuildPyException(E_OUTOFMEMORY); return PyCom_PyObjectFromIUnknown(pFact, IID_IClassFactory, /*bAddRef =*/FALSE); } // @pymethod int|pythoncom|_GetInterfaceCount|Retrieves the number of interface objects currently in existance static PyObject *pythoncom_GetInterfaceCount(PyObject *self, PyObject *args) { if (!PyArg_ParseTuple(args, ":_GetInterfaceCount")) return NULL; return PyInt_FromLong(_PyCom_GetInterfaceCount()); // @comm If is occasionally a good idea to call this function before your Python program // terminates. If this function returns non-zero, then you still have PythonCOM objects // alive in your program (possibly in global variables). } // @pymethod int|pythoncom|_GetGatewayCount|Retrieves the number of gateway objects currently in existance static PyObject *pythoncom_GetGatewayCount(PyObject *self, PyObject *args) { // @comm This is the number of Python object that implement COM servers which // are still alive (ie, serving a client). The only way to reduce this count // is to have the process which uses these PythonCOM servers release its references. if (!PyArg_ParseTuple(args, ":_GetGatewayCount")) return NULL; return PyInt_FromLong(_PyCom_GetGatewayCount()); } #ifndef MS_WINCE // @pymethod <o PyIUnknown>|pythoncom|GetActiveObject|Retrieves an object representing a running object registered with OLE static PyObject *pythoncom_GetActiveObject(PyObject *self, PyObject *args) { PyObject *obCLSID; // @pyparm CLSID|cls||The IID for the program. As for all CLSID's in Python, a "program.name" or IID format string may be used, or a real <o PyIID> object. if (!PyArg_ParseTuple(args, "O:GetActiveObject", &obCLSID)) return NULL; CLSID clsid; if (!PyWinObject_AsIID(obCLSID, &clsid)) return NULL; // Make the call. IUnknown *result = NULL; PY_INTERFACE_PRECALL; SCODE sc = GetActiveObject(clsid, NULL, &result); PY_INTERFACE_POSTCALL; if (FAILED(sc)) return PyCom_BuildPyException(sc); return PyCom_PyObjectFromIUnknown(result, IID_IUnknown); } // @pymethod <o PyIDispatch>|pythoncom|Connect|Connect to an already running OLE automation server. static PyObject *pythoncom_connect(PyObject *self, PyObject *args) { PyObject *obCLSID; // @pyparm CLSID|cls||An identifier for the program. Usually "program.item" if (!PyArg_ParseTuple(args, "O:Connect", &obCLSID)) return NULL; CLSID clsid; if (!PyWinObject_AsIID(obCLSID, &clsid)) return NULL; IUnknown *unk = NULL; PY_INTERFACE_PRECALL; HRESULT hr = GetActiveObject(clsid, NULL, &unk); PY_INTERFACE_POSTCALL; if (FAILED(hr) || unk == NULL) return PyCom_BuildPyException(hr); IDispatch *disp = NULL; SCODE sc; // local scope for macro PY_INTERFACE_PRECALL local variables { PY_INTERFACE_PRECALL; sc = unk->QueryInterface(IID_IDispatch, (void**)&disp); unk->Release(); PY_INTERFACE_POSTCALL; } if (FAILED(sc) || disp == NULL) return PyCom_BuildPyException(sc); return PyCom_PyObjectFromIUnknown(disp, IID_IDispatch); // @comm This function is equivalent to <om pythoncom.GetActiveObject>(clsid).<om pythoncom.QueryInterace>(pythoncom.IID_IDispatch) } #endif // MS_WINCE // @pymethod <o PyIDispatch>|pythoncom|new|Create a new instance of an OLE automation server. static PyObject *pythoncom_new(PyObject *self, PyObject *args) { PyErr_Clear(); PyObject *progid; // @pyparm CLSID|cls||An identifier for the program. Usually "program.item" if (!PyArg_ParseTuple(args, "O", &progid)) return NULL; // @comm This is just a wrapper for the CoCreateInstance method. // Specifically, this call is identical to: // <nl>pythoncom.CoCreateInstance(cls, None, pythoncom.CLSCTX_SERVER, pythoncom.IID_IDispatch) int clsctx = PyCom_HasDCom() ? CLSCTX_SERVER : CLSCTX_INPROC_SERVER| CLSCTX_LOCAL_SERVER; PyObject *obIID = PyWinObject_FromIID(IID_IDispatch); PyObject *newArgs = Py_BuildValue("OOiO", progid, Py_None, clsctx, obIID); Py_DECREF(obIID); PyObject *rc = pythoncom_CoCreateInstance(self, newArgs); Py_DECREF(newArgs); return rc; } #ifndef MS_WINCE // @pymethod <o PyIID>|pythoncom|CreateGuid|Creates a new, unique GUIID. static PyObject *pythoncom_createguid(PyObject *self, PyObject *args) { PyErr_Clear(); if (PyTuple_Size(args) != 0) { PyErr_SetString(PyExc_TypeError, "function requires no arguments"); return NULL; } GUID guid; PY_INTERFACE_PRECALL; CoCreateGuid(&guid); PY_INTERFACE_POSTCALL; // @comm Use the CreateGuid function when you need an absolutely unique number that you will use as a persistent identifier in a distributed environment.To a very high degree of certainty, this function returns a unique value – no other invocation, on the same or any other system (networked or not), should return the same value. return PyWinObject_FromIID(guid); } // @pymethod string|pythoncom|ProgIDFromCLSID|Converts a CLSID to a progID. static PyObject *pythoncom_progidfromclsid(PyObject *self, PyObject *args) { PyObject *obCLSID; // @pyparm IID|clsid||A CLSID (either in a string, or in an <o PyIID> object) if (!PyArg_ParseTuple(args, "O", &obCLSID)) return NULL; CLSID clsid; if (!PyWinObject_AsIID(obCLSID, &clsid)) return NULL; LPOLESTR progid = NULL; PY_INTERFACE_PRECALL; HRESULT sc = ProgIDFromCLSID(clsid, &progid); PY_INTERFACE_POSTCALL; if (FAILED(sc)) return PyCom_BuildPyException(sc); PyObject *ob = MakeOLECHARToObj(progid); CoTaskMemFree(progid); return ob; } #endif // MS_WINCE // @pymethod string|pythoncom|GetScodeString|Returns the string for an OLE scode (HRESULT) static PyObject *pythoncom_GetScodeString(PyObject *self, PyObject *args) { SCODE scode; TCHAR buf[512]; // @pyparm int|scode||The OLE error code for the scode string requested. if (!PyArg_ParseTuple(args, "k", &scode)) return NULL; GetScodeString(scode, buf, sizeof(buf)/sizeof(buf[0])); return PyWinObject_FromTCHAR(buf); // @comm This will obtain the COM Error message for a given HRESULT. // Internally, PythonCOM uses this function to obtain the description // when a <o com_error> COM Exception is raised. } // @pymethod string|pythoncom|GetScodeRangeString|Returns the scode range string, given an OLE scode. static PyObject *pythoncom_GetScodeRangeString(PyObject *self, PyObject *args) { SCODE scode; // @pyparm int|scode||An OLE error code to return the scode range string for. if (!PyArg_ParseTuple(args, "k", &scode)) return NULL; return PyWinObject_FromTCHAR(GetScodeRangeString(scode)); } // @pymethod string|pythoncom|GetSeverityString|Returns the severity string, given an OLE scode. static PyObject *pythoncom_GetSeverityString(PyObject *self, PyObject *args) { SCODE scode; // @pyparm int|scode||The OLE error code for the severity string requested. if (!PyArg_ParseTuple(args, "k", &scode)) return NULL; return PyWinObject_FromTCHAR(GetSeverityString(scode)); } // @pymethod string|pythoncom|GetFacilityString|Returns the facility string, given an OLE scode. static PyObject *pythoncom_GetFacilityString(PyObject *self, PyObject *args) { SCODE scode; // @pyparm int|scode||The OLE error code for the facility string requested. if (!PyArg_ParseTuple(args, "k", &scode)) return NULL; return PyWinObject_FromTCHAR(GetFacilityString(scode)); } // @pymethod <o PyIDispatch>|pythoncom|UnwrapObject|Unwraps a Python instance in a gateway object. static PyObject *pythoncom_UnwrapObject(PyObject *self, PyObject *args) { PyObject *ob; // @pyparm <o PyIUnknown>|ob||The object to unwrap. if ( !PyArg_ParseTuple(args, "O", &ob ) ) return NULL; // @comm If the object is not a PythonCOM object, then ValueError is raised. if ( !PyIBase::is_object(ob, &PyIUnknown::type) ) { PyErr_SetString(PyExc_ValueError, "argument is not a COM object"); return NULL; } // Unwrapper does not need thread state management // Ie PY_INTERFACE_PRE/POSTCALL; HRESULT hr; IInternalUnwrapPythonObject *pUnwrapper; if (S_OK!=(hr=((PyIUnknown *)ob)->m_obj->QueryInterface(IID_IInternalUnwrapPythonObject, (void **)&pUnwrapper))) { PyErr_Format(PyExc_ValueError, "argument is not a Python gateway (0x%x)", hr); return NULL; } PyObject *retval; pUnwrapper->Unwrap(&retval); pUnwrapper->Release(); if (S_OK!=hr) return PyCom_BuildPyException(hr); return retval; // Use this function to obtain the inverse of the <om WrapObject> method. // Eg, if you pass to this function the value you received from <om WrapObject>, it // will return the object you originally passed as the parameter to <om WrapObject> } // @pymethod <o PyIUnknown>|pythoncom|WrapObject|Wraps a Python instance in a gateway object. static PyObject *pythoncom_WrapObject(PyObject *self, PyObject *args) { PyObject *ob; PyObject *obIID = NULL; IID iid = IID_IDispatch; PyObject *obIIDInterface = NULL; IID iidInterface = IID_IDispatch; // @pyparm object|ob||The object to wrap. // @pyparm <o PyIID>|gatewayIID|IID_IDispatch|The IID of the gateway object to create (ie, the interface of the server object wrapped by the return value) // @pyparm <o PyIID>|interfaceIID|IID_IDispatch|The IID of the interface object to create (ie, the interface of the returned object) if ( !PyArg_ParseTuple(args, "O|OO", &ob, &obIID, &obIIDInterface) ) return NULL; // @rdesc Note that there are 2 objects created by this call - a gateway (server) object, suitable for // use by other external COM clients/hosts, as well as the returned Python interface (client) object, which // maps to the new gateway. // <nl>There are some unusual cases where the 2 IID parameters will not be identical. // If you need to do this, you should know exactly what you are doing, and why! if (obIID && obIID != Py_None) { if (!PyWinObject_AsIID(obIID, &iid)) return NULL; } if (obIIDInterface && obIIDInterface != Py_None) { if (!PyWinObject_AsIID(obIIDInterface, &iidInterface)) return NULL; } // Make a gateway of the specific IID we ask for. // The gateway must exist (ie, we _must_ support PyGIXXX // XXX - do we need an optional arg for "base object"? // XXX - If we did, we would unwrap it like thus: /**** IUnknown *pLook = (IUnknown *)(*ppv); IInternalUnwrapPythonObject *pTemp; if (pLook->QueryInterface(IID_IInternalUnwrapPythonObject, (void **)&pTemp)==S_OK) { // One of our objects, so set the base object if it doesnt already have one PyGatewayBase *pG = (PyGatewayBase *)pTemp; // Eeek - just these few next lines need to be thread-safe :-( PyWin_AcquireGlobalLock(); if (pG->m_pBaseObject==NULL && pG != (PyGatewayBase *)this) { pG->m_pBaseObject = this; pG->m_pBaseObject->AddRef(); } PyWin_ReleaseGlobalLock(); pTemp->Release(); } ******/ IUnknown *pDispatch; PY_INTERFACE_PRECALL; HRESULT hr = PyCom_MakeRegisteredGatewayObject(iid, ob, NULL, (void **)&pDispatch); PY_INTERFACE_POSTCALL; if ( FAILED(hr) ) return PyCom_BuildPyException(hr); /* pass the pDispatch reference into this thing */ /* ### this guy should always AddRef() ... */ PyObject *result = PyCom_PyObjectFromIUnknown(pDispatch, iidInterface, FALSE); if ( !result ) { PY_INTERFACE_PRECALL; pDispatch->Release(); PY_INTERFACE_POSTCALL; return NULL; } return result; } static PyObject *pythoncom_MakeIID(PyObject *self, PyObject *args) { PyErr_Warn(PyExc_PendingDeprecationWarning, "MakeIID is deprecated - please use pywintypes.IID() instead."); return PyWinMethod_NewIID(self, args); } // no autoduck - this is deprecated. static PyObject *pythoncom_MakeTime(PyObject *self, PyObject *args) { PyErr_Warn(PyExc_PendingDeprecationWarning, "MakeTime is deprecated - please use pywintypes.Time() instead."); return PyWinMethod_NewTime(self, args); } #ifndef MS_WINCE // @pymethod <o PyIMoniker>,int,<o PyIBindCtx>|pythoncom|MkParseDisplayName|Parses a moniker display name into a moniker object. The inverse of <om PyIMoniker.GetDisplayName> static PyObject *pythoncom_MkParseDisplayName(PyObject *self, PyObject *args) { WCHAR *displayName = NULL; PyObject *obDisplayName; PyObject *obBindCtx = NULL; // @pyparm string|displayName||The display name to parse // @pyparm <o PyIBindCtx>|bindCtx|None|The bind context object to use. // @comm If a binding context is not provided, then one will be created. // Any binding context created or passed in will be returned to the // caller. if ( !PyArg_ParseTuple(args, "O|O:MkParseDisplayName", &obDisplayName, &obBindCtx) ) return NULL; if (!PyWinObject_AsWCHAR(obDisplayName, &displayName, FALSE)) return NULL; HRESULT hr; IBindCtx *pBC; if ( obBindCtx == NULL || obBindCtx==Py_None) { hr = CreateBindCtx(0, &pBC); if ( FAILED(hr) ) { PyWinObject_FreeWCHAR(displayName); return PyCom_BuildPyException(hr); } /* pass the pBC ref into obBindCtx */ obBindCtx = PyCom_PyObjectFromIUnknown(pBC, IID_IBindCtx, FALSE); } else { if ( !PyCom_InterfaceFromPyObject(obBindCtx, IID_IBindCtx, (LPVOID*)&pBC, FALSE) ) { PyWinObject_FreeWCHAR(displayName); return NULL; } /* we want our own ref to obBindCtx, but not pBC */ Py_INCREF(obBindCtx); pBC->Release(); } /* at this point: we own a ref to obBindCtx, but not pBC */ ULONG chEaten; IMoniker *pmk; PY_INTERFACE_PRECALL; hr = MkParseDisplayName(pBC, displayName, &chEaten, &pmk); PY_INTERFACE_POSTCALL; PyWinObject_FreeWCHAR(displayName); if ( FAILED(hr) ) { Py_DECREF(obBindCtx); return PyCom_BuildPyException(hr); } /* pass ownership of the moniker into the result */ PyObject *obMoniker = PyCom_PyObjectFromIUnknown(pmk, IID_IMoniker, FALSE); /* build the result */ PyObject *result = Py_BuildValue("OiO", obMoniker, chEaten, obBindCtx); /* done with these obs */ Py_XDECREF(obMoniker); Py_DECREF(obBindCtx); return result; } // @pymethod <o PyIMoniker>|pythoncom|CreatePointerMoniker|Creates a new <o PyIMoniker> object. static PyObject *pythoncom_CreatePointerMoniker(PyObject *self, PyObject *args) { PyObject *obUnk; // @pyparm <o PyIUnknown>|IUnknown||The interface for the moniker. if ( !PyArg_ParseTuple(args, "O:CreatePointerMoniker", &obUnk) ) return NULL; IUnknown *punk; if ( !PyCom_InterfaceFromPyObject(obUnk, IID_IUnknown, (LPVOID*)&punk, FALSE) ) return NULL; IMoniker *pmk; PY_INTERFACE_PRECALL; HRESULT hr = CreatePointerMoniker(punk, &pmk); punk->Release(); PY_INTERFACE_POSTCALL; if ( FAILED(hr) ) return PyCom_BuildPyException(hr); return PyCom_PyObjectFromIUnknown(pmk, IID_IMoniker, FALSE); } // @pymethod <o PyIMoniker>|pythoncom|CreateFileMoniker|Creates a new <o PyIMoniker> object. static PyObject *pythoncom_CreateFileMoniker(PyObject *self, PyObject *args) { PyObject *obName; // @pyparm string|filename||The name of the file. if ( !PyArg_ParseTuple(args, "O:CreateFileMoniker", &obName) ) return NULL; BSTR bstrName; if (!PyWinObject_AsBstr(obName, &bstrName)) return NULL; IMoniker *pmk; PY_INTERFACE_PRECALL; HRESULT hr = CreateFileMoniker(bstrName, &pmk); PY_INTERFACE_POSTCALL; PyWinObject_FreeBstr(bstrName); if ( FAILED(hr) ) return PyCom_BuildPyException(hr); return PyCom_PyObjectFromIUnknown(pmk, IID_IMoniker, FALSE); } // @pymethod <o PyIMoniker>|pythoncom|CreateItemMoniker|Creates an item moniker // that identifies an object within a containing object (typically a compound document). static PyObject *pythoncom_CreateItemMoniker(PyObject *self, PyObject *args) { PyObject *obDelim, *obItem; // @pyparm string|delim||String containing the delimiter (typically "!") used to separate this item's display name from the display name of its containing object. // @pyparm string|item||String indicating the containing object's name for the object being identified. if ( !PyArg_ParseTuple(args, "OO:CreateItemMoniker", &obDelim, &obItem) ) return NULL; BSTR bstrDelim, bstrItem; if (!PyWinObject_AsBstr(obDelim, &bstrDelim, TRUE)) return NULL; if (!PyWinObject_AsBstr(obItem, &bstrItem, FALSE)) { PyWinObject_FreeBstr(bstrDelim); return NULL; } IMoniker *pmk; PY_INTERFACE_PRECALL; HRESULT hr = CreateItemMoniker(bstrDelim, bstrItem, &pmk); PY_INTERFACE_POSTCALL; PyWinObject_FreeBstr(bstrDelim); PyWinObject_FreeBstr(bstrItem); if ( FAILED(hr) ) return PyCom_BuildPyException(hr); return PyCom_PyObjectFromIUnknown(pmk, IID_IMoniker, FALSE); } // @pymethod <o PyIMoniker>|pythoncom|CreateURLMonikerEx|Create a URL moniker from a full url or partial url and base moniker // @pyseeapi CreateURLMonikerEx static PyObject *pythoncom_CreateURLMonikerEx(PyObject *self, PyObject *args) { WCHAR *url = NULL; PyObject *obbase, *oburl, *ret = NULL; IMoniker *base_moniker = NULL, *output_moniker = NULL; HRESULT hr; DWORD flags = URL_MK_UNIFORM; CHECK_PFN(CreateURLMonikerEx); if (!PyArg_ParseTuple(args, "OO|k:CreateURLMonikerEx", &obbase, // @pyparm <o PyIMoniker>|Context||An IMoniker interface to be used as a base with a partial URL, can be None &oburl, // @pyparm <o PyUNICODE>|URL||Full or partial url for which to create a moniker &flags)) // @pyparm int|Flags|URL_MK_UNIFORM|URL_MK_UNIFORM or URL_MK_LEGACY return NULL; if (!PyWinObject_AsWCHAR(oburl, &url, FALSE)) return NULL; if (PyCom_InterfaceFromPyObject(obbase, IID_IMoniker, (LPVOID*)&base_moniker, TRUE)){ PY_INTERFACE_PRECALL; hr = (*pfnCreateURLMonikerEx)(base_moniker, url, &output_moniker, flags); if (base_moniker) base_moniker->Release(); PY_INTERFACE_POSTCALL; if (FAILED(hr)) PyCom_BuildPyException(hr); else ret=PyCom_PyObjectFromIUnknown(output_moniker, IID_IMoniker, FALSE); } PyWinObject_FreeWCHAR(url); return ret; } // @pymethod <o PyIID>|pythoncom|GetClassFile|Supplies the CLSID associated with the given filename. static PyObject *pythoncom_GetClassFile(PyObject *self, PyObject *args) { CLSID clsid; PyObject *obFileName; BSTR fname; // @pyparm string|fileName||The filename for which you are requesting the associated CLSID. if (!PyArg_ParseTuple(args, "O", &obFileName)) return NULL; if (!PyCom_BstrFromPyObject(obFileName, &fname, FALSE)) return NULL; PY_INTERFACE_PRECALL; HRESULT hr = GetClassFile(fname, &clsid); PY_INTERFACE_POSTCALL; SysFreeString(fname); if (FAILED(hr)) return PyCom_BuildPyException(hr); return PyWinObject_FromIID(clsid); } #endif // MS_WINCE // @pymethod |pythoncom|CoInitialize|Initialize the COM libraries for the calling thread. static PyObject *pythoncom_CoInitialize(PyObject *self, PyObject *args) { if (!PyArg_ParseTuple(args, ":CoInitialize")) return NULL; PY_INTERFACE_PRECALL; HRESULT hr = PyCom_CoInitialize(NULL); PY_INTERFACE_POSTCALL; // @rdesc This function will ignore the RPC_E_CHANGED_MODE error, as // that error indicates someone else beat you to the initialization, and // did so with a different threading model. This error is ignored as it // still means COM is ready for use on this thread, and as this function // does not explicitly specify a threading model the caller probably // doesn't care what model it is. // <nl>All other COM errors will raise pythoncom.error as usual. Use // <om pythoncom.CoInitializeEx> if you also want to handle the RPC_E_CHANGED_MODE // error. if (FAILED(hr) && hr != RPC_E_CHANGED_MODE) return PyCom_BuildPyException(hr); Py_INCREF(Py_None); return Py_None; // @comm Apart from the error handling semantics, this is equivalent // to <om pythoncom.CoInitializeEx>(pythoncom.COINIT_APARTMENTTHREADED). // See <om pythoncom.CoInitializeEx> for a description. } // @pymethod |pythoncom|CoInitializeEx|Initialize the COM libraries for the calling thread. static PyObject *pythoncom_CoInitializeEx(PyObject *self, PyObject *args) { // @rdesc This function will raise pythoncom.error for all error // return values, including RPC_E_CHANGED_MODE error. This is // in contrast to <om pythoncom.CoInitialize> which will hide that // specific error. If your code is happy to work in a threading model // other than the one you specified, you must explicitly handle // (and presumably ignore) this exception. DWORD val; if (!PyArg_ParseTuple(args, "l:CoInitializeEx", &val)) // @pyparm int|flags||Flags for the initialization. return NULL; PY_INTERFACE_PRECALL; HRESULT hr = PyCom_CoInitializeEx(NULL, val); PY_INTERFACE_POSTCALL; if (FAILED(hr)) return PyCom_BuildPyException(hr); Py_INCREF(Py_None); return Py_None; // @comm There is no need to call this for the main Python thread, as it is called // automatically by pythoncom (using sys.coinit_flags as the param, or COINIT_APARTMENTTHREADED // if sys.coinit_flags does not exist). // <nl>You must call this manually if you create a thread which wishes to use COM. } // @pymethod |pythoncom|CoUninitialize|Uninitialize the COM libraries for the calling thread. static PyObject *pythoncom_CoUninitialize(PyObject *self, PyObject *args) { // comm This function is never called automatically by COM (as this seems the better of // 2 evils if COM objects are still alive). If your Python program hangs on termination, // add a call to this function before terminating. PY_INTERFACE_PRECALL; PyCom_CoUninitialize(); PY_INTERFACE_POSTCALL; Py_INCREF(Py_None); return Py_None; } // @pymethod |pythoncom|CoFreeUnusedLibraries|Unloads any DLLs that are no longer in use and that, when loaded, were specified to be freed automatically. static PyObject *pythoncom_CoFreeUnusedLibraries(PyObject *self, PyObject *args) { if (!PyArg_ParseTuple(args, ":CoFreeUnusedLibraries")) return NULL; PY_INTERFACE_PRECALL; CoFreeUnusedLibraries(); PY_INTERFACE_POSTCALL; Py_INCREF(Py_None); return Py_None; } #ifndef MS_WINCE // @pymethod <o PyIRunningObjectTable>|pythoncom|GetRunningObjectTable|Creates a new <o PyIRunningObjectTable> object. static PyObject *pythoncom_GetRunningObjectTable(PyObject *self, PyObject *args) { DWORD reserved = 0; // @pyparm int|reserved|0|A reserved parameter. Should be zero unless you have inside information that I don't! if ( !PyArg_ParseTuple(args, "|l:GetRunningObjectTable", &reserved) ) return NULL; IRunningObjectTable *pROT = NULL; PY_INTERFACE_PRECALL; HRESULT hr = GetRunningObjectTable(reserved,&pROT); PY_INTERFACE_POSTCALL; if (S_OK!=hr) return PyCom_BuildPyException(hr); return PyCom_PyObjectFromIUnknown(pROT, IID_IRunningObjectTable, FALSE); } // @pymethod <o PyIBindCtx>|pythoncom|CreateBindCtx|Creates a new <o PyIBindCtx> object. static PyObject *pythoncom_CreateBindCtx(PyObject *self, PyObject *args) { DWORD reserved = 0; if ( !PyArg_ParseTuple(args, "|l:CreateBindCtx", &reserved) ) return NULL; IBindCtx *pBC = NULL; PY_INTERFACE_PRECALL; HRESULT hr = CreateBindCtx(reserved,&pBC); PY_INTERFACE_POSTCALL; if (S_OK!=hr) return PyCom_BuildPyException(hr); return PyCom_PyObjectFromIUnknown(pBC, IID_IBindCtx, FALSE); } // @pymethod int|pythoncom|RegisterActiveObject|Register an object as the active object for its class static PyObject *pythoncom_RegisterActiveObject(PyObject *self, PyObject *args) { DWORD dwflags=0, dwkey=0; HRESULT hr; CLSID clsid; PyObject *obclsid; PyObject *obunk; IUnknown *punk; // @pyparm <o PyIUnknown>|obUnknown||The object to register. // @pyparm <o PyIID>|clsid||The CLSID for the object // @pyparm int|flags||Flags to use. if (!PyArg_ParseTuple(args, "OOi:RegisterActiveObject", &obunk, &obclsid, &dwflags)) return NULL; if (!PyWinObject_AsIID(obclsid, &clsid)) return NULL; if (!PyCom_InterfaceFromPyInstanceOrObject(obunk, IID_IUnknown, (void **)&punk), FALSE) return NULL; PY_INTERFACE_PRECALL; hr = RegisterActiveObject(punk, clsid, dwflags, &dwkey); punk->Release(); PY_INTERFACE_POSTCALL; if (S_OK!=hr) return PyCom_BuildPyException(hr); return PyInt_FromLong(dwkey); // @rdesc The result is a handle which should be pass to <om pythoncom.RevokeActiveObject> } // @pymethod |pythoncom|RevokeActiveObject|Ends an object’s status as active. static PyObject *pythoncom_RevokeActiveObject(PyObject *self, PyObject *args) { DWORD dw_x=0; HRESULT hr; // @pyparm int|handle||A handle obtained from <om pythoncom.RegisterActiveObject> if(!PyArg_ParseTuple(args,"l:RevokeActiveObject", &dw_x)) return NULL; PY_INTERFACE_PRECALL; hr = RevokeActiveObject(dw_x, NULL); PY_INTERFACE_POSTCALL; if (S_OK!=hr) return PyCom_BuildPyException(hr); Py_INCREF(Py_None); return Py_None; } // Some basic marshalling support // @pymethod <o PyIStream>|pythoncom|CoMarshalInterThreadInterfaceInStream|Marshals an interface pointer from one thread to another thread in the same process. static PyObject *pythoncom_CoMarshalInterThreadInterfaceInStream(PyObject *self, PyObject*args) { PyObject *obIID, *obUnk; IID iid; if ( !PyArg_ParseTuple(args, "OO:CoMarshalInterThreadInterfaceInStream", &obIID, // @pyparm <o PyIID>|iid||The IID of the interface to marshal. &obUnk)) // @pyparm <o PyIUnknown>|unk||The interface to marshal. return NULL; if (!PyWinObject_AsIID(obIID, &iid)) return NULL; IUnknown *pUnk; if (!PyCom_InterfaceFromPyInstanceOrObject(obUnk, IID_IUnknown, (void **)&pUnk, FALSE)) return NULL; IStream *pStream = NULL; PY_INTERFACE_PRECALL; HRESULT hr = CoMarshalInterThreadInterfaceInStream(iid, pUnk, &pStream); pUnk->Release(); PY_INTERFACE_POSTCALL; if (FAILED(hr)) return PyCom_BuildPyException(hr); return PyCom_PyObjectFromIUnknown(pStream, IID_IStream, /*BOOL bAddRef*/ FALSE); } // @pymethod <o PyIUnknown>|pythoncom|CoGetInterfaceAndReleaseStream|Unmarshals a buffer containing an interface pointer and releases the stream when an interface pointer has been marshaled from another thread to the calling thread. static PyObject *pythoncom_CoGetInterfaceAndReleaseStream(PyObject *self, PyObject*args) { PyObject *obStream, *obIID; if ( !PyArg_ParseTuple(args, "OO:CoGetInterfaceAndReleaseStream", &obStream, // @pyparm <o PyIStream>|stream||The stream to unmarshal the object from. &obIID )) // @pyparm <o PyIID>|iid||The IID if the interface to unmarshal. return NULL; IID iid; if (!PyWinObject_AsIID(obIID, &iid)) return NULL; IStream *pStream; if (!PyCom_InterfaceFromPyObject(obStream, IID_IStream, (void **)&pStream, FALSE)) return NULL; IUnknown *pUnk; PY_INTERFACE_PRECALL; HRESULT hr = CoGetInterfaceAndReleaseStream(pStream, iid, (void **)&pUnk); // pStream is released by this call - no need for me to do it! PY_INTERFACE_POSTCALL; if (FAILED(hr)) return PyCom_BuildPyException(hr); return PyCom_PyObjectFromIUnknown(pUnk, iid, /*BOOL bAddRef*/ FALSE); } // @pymethod <o PyIUnknown>|pythoncom|CoCreateFreeThreadedMarshaler|Creates an aggregatable object capable of context-dependent marshaling. static PyObject *pythoncom_CoCreateFreeThreadedMarshaler(PyObject *self, PyObject*args) { PyObject *obUnk; if ( !PyArg_ParseTuple(args, "O:CoCreateFreeThreadedMarshaler", &obUnk )) // @pyparm <o PyIUnknown>|unk||The unknown object to marshal. return NULL; IUnknown *pUnk; if (!PyCom_InterfaceFromPyObject(obUnk, IID_IUnknown, (void **)&pUnk, FALSE)) return NULL; IUnknown *pUnkRet; PY_INTERFACE_PRECALL; HRESULT hr = CoCreateFreeThreadedMarshaler(pUnk, &pUnkRet); pUnk->Release(); PY_INTERFACE_POSTCALL; if (FAILED(hr)) return PyCom_BuildPyException(hr); return PyCom_PyObjectFromIUnknown(pUnkRet, IID_IUnknown, FALSE); } // @pymethod |pythoncom|CoMarshalInterface|Marshals an interface into a stream static PyObject *pythoncom_CoMarshalInterface(PyObject *self, PyObject*args) { PyObject *obriid, *obIStream, *obUnk, *ret=NULL; IID riid; IStream *pIStream=NULL; IUnknown *pIUnknown=NULL; void *pvdestctxt=NULL; // reserved DWORD destctxt, flags=MSHLFLAGS_NORMAL; if ( !PyArg_ParseTuple(args, "OOOk|k:CoMarshalInterface", &obIStream, // @pyparm <o PyIStream>|Stm||An IStream interface into which marshalled interface will be written &obriid, // @pyparm <o PyIID>|riid||IID of interface to be marshalled &obUnk, // @pyparm <o PyIUnknown>|Unk||Base IUnknown of the object to be marshalled &destctxt, // @pyparm int|DestContext||MSHCTX_* flag indicating where object will be unmarshalled &flags)) // @pyparm int|flags|MSHLFLAGS_NORMAL|MSHLFLAGS_* flag indicating marshalling options return NULL; if (PyWinObject_AsIID(obriid, &riid) &&PyCom_InterfaceFromPyObject(obIStream, IID_IStream, (void **)&pIStream, FALSE) &&PyCom_InterfaceFromPyObject(obUnk, IID_IUnknown, (void **)&pIUnknown, FALSE)){ PY_INTERFACE_PRECALL; HRESULT hr = CoMarshalInterface(pIStream, riid, pIUnknown, destctxt, pvdestctxt, flags); PY_INTERFACE_POSTCALL; if (FAILED(hr)) PyCom_BuildPyException(hr); else{ Py_INCREF(Py_None); ret=Py_None; } } PY_INTERFACE_PRECALL; if (pIUnknown) pIUnknown->Release(); if (pIStream) pIStream->Release(); PY_INTERFACE_POSTCALL; return ret; } // @pymethod interface|pythoncom|CoUnmarshalInterface|Unmarshals an interface static PyObject *pythoncom_CoUnmarshalInterface(PyObject *self, PyObject*args) { PyObject *obriid, *obIStream, *ret=NULL; IID riid; IStream *pIStream=NULL; IUnknown *pIUnknown=NULL; if (!PyArg_ParseTuple(args, "OO:CoUnmarshalInterface", &obIStream, // @pyparm <o PyIStream>|Stm||Stream containing marshalled interface &obriid)) // @pyparm <o PyIID>|riid||IID of interface to be unmarshalled return NULL; if (PyWinObject_AsIID(obriid, &riid) &&PyCom_InterfaceFromPyObject(obIStream, IID_IStream, (void **)&pIStream, FALSE)){ PY_INTERFACE_PRECALL; HRESULT hr = CoUnmarshalInterface(pIStream, riid, (void **)&pIUnknown); pIStream->Release(); PY_INTERFACE_POSTCALL; if (FAILED(hr)) PyCom_BuildPyException(hr); else ret=PyCom_PyObjectFromIUnknown(pIUnknown, riid, FALSE); } return ret; } // @pymethod |pythoncom|CoReleaseMarshalData|Frees resources used by a marshalled interface // @comm This is usually only needed when the interface could not be successfully unmarshalled static PyObject *pythoncom_CoReleaseMarshalData(PyObject *self, PyObject*args) { PyObject *obIStream, *ret=NULL; IStream *pIStream=NULL; if (!PyArg_ParseTuple(args, "O:CoReleaseMarshalData", &obIStream)) // @pyparm <o PyIStream>|Stm||Stream containing marshalled interface return NULL; if (!PyCom_InterfaceFromPyObject(obIStream, IID_IStream, (void **)&pIStream, FALSE)) return NULL; PY_INTERFACE_PRECALL; HRESULT hr = CoReleaseMarshalData(pIStream); pIStream->Release(); PY_INTERFACE_POSTCALL; if (FAILED(hr)) return PyCom_BuildPyException(hr); Py_INCREF(Py_None); return Py_None; } #endif // MS_WINCE // @pymethod <o PyIUnknown>|pythoncom|CoGetObject|Converts a display name into a moniker that identifies the object named, and then binds to the object identified by the moniker. static PyObject *pythoncom_CoGetObject(PyObject *self, PyObject*args) { PyObject *obName; PyObject *obBindOpts = Py_None; PyObject *obIID = Py_None; if (!PyArg_ParseTuple(args, "O|OO:CoGetObject", &obName, // @pyparm string|name|| &obBindOpts, // @pyparm None|bindOpts||Must be None &obIID )) // @pyparm <o PyIID>|iid||The IID if the interface to unmarshal. return NULL; if (obBindOpts != Py_None) return PyErr_Format(PyExc_ValueError, "BindOptions must be None"); IID iid; if (obIID == Py_None) iid = IID_IUnknown; else { if (!PyWinObject_AsIID(obIID, &iid)) return NULL; } PyWin_AutoFreeBstr name; if (!PyWinObject_AsAutoFreeBstr(obName, &name)) return NULL; IUnknown *pUnk; PY_INTERFACE_PRECALL; HRESULT hr = CoGetObject(name, NULL, iid, (void **)&pUnk); PY_INTERFACE_POSTCALL; if (FAILED(hr)) return PyCom_BuildPyException(hr); return PyCom_PyObjectFromIUnknown(pUnk, iid, /*BOOL bAddRef*/ FALSE); } // @pymethod |pythoncom|OleLoad|Loads into memory an object nested within a specified storage object. static PyObject *pythoncom_OleLoad(PyObject *self, PyObject* args) { PyObject *obStorage, *obIID, *obSite; if ( !PyArg_ParseTuple(args, "OOO:OleLoad", &obStorage, // @pyparm <o PyIStorage>|storage||The storage object from which to load &obIID, // @pyparm <o PyIID>|iid||The IID if the interface to load. &obSite)) // @pyparm <o PyIOleClientSite>|site||The client site for the object. return NULL; IID iid; if (!PyWinObject_AsIID(obIID, &iid)) return NULL; IStorage *pStorage; if (!PyCom_InterfaceFromPyObject(obStorage, IID_IStorage, (void **)&pStorage, FALSE)) return NULL; IOleClientSite *pSite; if (!PyCom_InterfaceFromPyObject(obSite, IID_IOleClientSite, (void **)&pSite, TRUE)) { pStorage->Release(); return NULL; } IUnknown *pUnk; PY_INTERFACE_PRECALL; HRESULT hr = OleLoad(pStorage, iid, pSite, (void **)&pUnk); pStorage->Release(); pSite->Release(); PY_INTERFACE_POSTCALL; if (FAILED(hr)) return PyCom_BuildPyException(hr); return PyCom_PyObjectFromIUnknown(pUnk, iid, /*BOOL bAddRef*/ FALSE); } // @pymethod |pythoncom|OleLoadFromStream|Load an object from an IStream. static PyObject *pythoncom_OleLoadFromStream(PyObject *self, PyObject* args) { PyObject *obStream, *obIID; if ( !PyArg_ParseTuple(args, "OO:OleLoadFromStream", &obStream, // @pyparm <o PyIStream>|stream||The stream to load the object from. &obIID )) // @pyparm <o PyIID>|iid||The IID if the interface to load. return NULL; IID iid; if (!PyWinObject_AsIID(obIID, &iid)) return NULL; IStream *pStream; if (!PyCom_InterfaceFromPyObject(obStream, IID_IStream, (void **)&pStream, FALSE)) return NULL; IUnknown *pUnk; PY_INTERFACE_PRECALL; HRESULT hr = OleLoadFromStream(pStream, iid, (void **)&pUnk); pStream->Release(); PY_INTERFACE_POSTCALL; if (FAILED(hr)) return PyCom_BuildPyException(hr); return PyCom_PyObjectFromIUnknown(pUnk, iid, /*BOOL bAddRef*/ FALSE); } // @pymethod |pythoncom|OleSaveToStream|Save an object to an IStream. static PyObject *pythoncom_OleSaveToStream(PyObject *self, PyObject*args) { PyObject *obPersist,*obStream; if ( !PyArg_ParseTuple(args, "OO:OleSaveToStream", &obPersist, // @pyparm <o PyIPersistStream>|persist||The object to save &obStream )) // @pyparm <o PyIStream>|stream||The stream to save the object to. return NULL; // This parameter is allowed to be None. This follows the COM documentation rather // than the COM implementation, which is likely to return an error if you do pass // it a NULL IPersistStream IPersistStream *pPersist; if (!PyCom_InterfaceFromPyObject(obPersist, IID_IPersistStream, (void**)&pPersist, FALSE)) return NULL; IStream *pStream; if (!PyCom_InterfaceFromPyObject(obStream, IID_IStream, (void **)&pStream, FALSE)) { PY_INTERFACE_PRECALL; if(pPersist) pPersist->Release(); PY_INTERFACE_POSTCALL; return NULL; } PY_INTERFACE_PRECALL; HRESULT hr = OleSaveToStream(pPersist, pStream); pStream->Release(); if(pPersist) pPersist->Release(); PY_INTERFACE_POSTCALL; if (FAILED(hr)) return PyCom_BuildPyException(hr); Py_INCREF(Py_None); return Py_None; } // @pymethod <o ICreateTypeLib>|pythoncom|CreateTypeLib|Provides access to a new object instance that supports the ICreateTypeLib interface. static PyObject *pythoncom_CreateTypeLib(PyObject *self, PyObject *args) { long syskind; PyObject *obfname; if (!PyArg_ParseTuple(args, "lO", &syskind, &obfname)) return NULL; BSTR fname; if (!PyWinObject_AsBstr(obfname, &fname)) return NULL; ICreateTypeLib *pcti = NULL; PY_INTERFACE_PRECALL; HRESULT hr = CreateTypeLib((SYSKIND)syskind, fname, &pcti); PY_INTERFACE_POSTCALL; PyWinObject_FreeBstr(fname); if (FAILED(hr)) return PyCom_BuildPyException(hr); return PyCom_PyObjectFromIUnknown(pcti, IID_ICreateTypeLib, FALSE); } // @pymethod <o ICreateTypeLib2>|pythoncom|CreateTypeLib2|Provides access to a new object instance that supports the ICreateTypeLib2 interface. static PyObject *pythoncom_CreateTypeLib2(PyObject *self, PyObject *args) { long syskind; PyObject *obfname; if (!PyArg_ParseTuple(args, "lO", &syskind, &obfname)) return NULL; BSTR fname; if (!PyWinObject_AsBstr(obfname, &fname)) return NULL; ICreateTypeLib2 *pcti = NULL; PY_INTERFACE_PRECALL; HRESULT hr = CreateTypeLib2((SYSKIND)syskind, fname, &pcti); PY_INTERFACE_POSTCALL; PyWinObject_FreeBstr(fname); if (FAILED(hr)) return PyCom_BuildPyException(hr); return PyCom_PyObjectFromIUnknown(pcti, IID_ICreateTypeLib2, FALSE); } // @pymethod int|pythoncom|PumpWaitingMessages|Pumps all waiting messages for the current thread. // @comm It is sometimes necessary for a COM thread to have a message loop. This function // can be used with <om win32event.MsgWaitForMultipleObjects> to pump all messages // when necessary. Please see the COM documentation for more details. // @rdesc Returns 1 if a WM_QUIT message was received, else 0 static PyObject *pythoncom_PumpWaitingMessages(PyObject *self, PyObject *args) { UINT firstMsg = 0, lastMsg = 0; if (!PyArg_ParseTuple (args, "|ii:PumpWaitingMessages", &firstMsg, &lastMsg)) return NULL; // @pyseeapi PeekMessage and DispatchMessage MSG msg; long result = 0; // Read all of the messages in this next loop, // removing each message as we read it. Py_BEGIN_ALLOW_THREADS while (PeekMessage(&msg, NULL, firstMsg, lastMsg, PM_REMOVE)) { // If it's a quit message, we're out of here. if (msg.message == WM_QUIT) { result = 1; break; } // Otherwise, dispatch the message. DispatchMessage(&msg); } // End of PeekMessage while loop Py_END_ALLOW_THREADS return PyInt_FromLong(result); } // @pymethod |pythoncom|PumpMessages|Pumps all messages for the current thread until a WM_QUIT message. static PyObject *pythoncom_PumpMessages(PyObject *self, PyObject *args) { MSG msg; int rc; Py_BEGIN_ALLOW_THREADS while ((rc=GetMessage(&msg, 0, 0, 0))==1) { TranslateMessage(&msg); // needed? DispatchMessage(&msg); } Py_END_ALLOW_THREADS if (rc==-1) return PyWin_SetAPIError("GetMessage"); Py_INCREF(Py_None); return Py_None; } // @pymethod |pythoncom|EnableQuitMessage|Indicates the thread PythonCOM should post a WM_QUIT message to. static PyObject *pythoncom_EnableQuitMessage(PyObject *self, PyObject *args) { extern void PyCom_EnableQuitMessage( DWORD dwThreadId ); DWORD id; // @pyparm int|threadId||The thread ID. if (!PyArg_ParseTuple (args, "l:EnableQuitMessage", &id)) return NULL; PyCom_EnableQuitMessage(id); Py_INCREF(Py_None); return Py_None; } static BOOL MakeHandleList(PyObject *handleList, HANDLE **ppBuf, DWORD *pNumEntries) { if (!PySequence_Check(handleList)) { PyErr_SetString(PyExc_TypeError, "Handles must be a list of integers"); return FALSE; } DWORD numItems = (DWORD)PySequence_Length(handleList); HANDLE *pItems = (HANDLE *)malloc(sizeof(HANDLE) * numItems); if (pItems==NULL) { PyErr_SetString(PyExc_MemoryError,"Allocating array of handles"); return FALSE; } for (DWORD i=0;i<numItems;i++) { PyObject *obItem = PySequence_GetItem(handleList, i); if (obItem==NULL) { free(pItems); return FALSE; } if (!PyWinObject_AsHANDLE(obItem,pItems+i)) { Py_DECREF(obItem); free(pItems); PyErr_SetString(PyExc_TypeError, "Handles must be a list of integers"); return FALSE; } Py_DECREF(obItem); } *ppBuf = pItems; *pNumEntries = numItems; return TRUE; } // @pymethod int|pythoncom|CoWaitForMultipleHandles|Waits for specified handles to be signaled or for a specified timeout period to elapse. static PyObject *pythoncom_CoWaitForMultipleHandles(PyObject *self, PyObject *args) { DWORD flags, timeout; PyObject *obHandles; DWORD numItems; HANDLE *pItems = NULL; CHECK_PFN(CoWaitForMultipleHandles); if (!PyArg_ParseTuple(args, "iiO:CoWaitForMultipleHandles", &flags, // @pyparm int|Flags||Combination of pythoncom.COWAIT_* values &timeout, // @pyparm int|Timeout||Timeout in milliseconds &obHandles)) // @pyparm [<o PyHANDLE>, ...]|Handles||Sequence of handles return NULL; if (!MakeHandleList(obHandles, &pItems, &numItems)) return NULL; DWORD index; PyObject *rc = NULL; HRESULT hr; Py_BEGIN_ALLOW_THREADS hr = (*pfnCoWaitForMultipleHandles)(flags, timeout, numItems, pItems, &index); Py_END_ALLOW_THREADS if (FAILED(hr)) { PyCom_BuildPyException(hr); } else rc = PyInt_FromLong(index); free(pItems); return rc; } // @pymethod <o PyIDataObject>|pythoncom|OleGetClipboard|Retrieves a data object that you can use to access the contents of the clipboard. static PyObject *pythoncom_OleGetClipboard(PyObject *, PyObject *args) { if (!PyArg_ParseTuple(args, ":OleGetClipboard")) return NULL; IDataObject *pd = NULL; HRESULT hr; Py_BEGIN_ALLOW_THREADS hr = ::OleGetClipboard(&pd); Py_END_ALLOW_THREADS if (FAILED(hr)) { PyCom_BuildPyException(hr); return NULL; } return PyCom_PyObjectFromIUnknown(pd, IID_IDataObject, FALSE); } // @pymethod |pythoncom|OleSetClipboard|Places a pointer to a specific data object onto the clipboard. This makes the data object accessible to the OleGetClipboard function. static PyObject *pythoncom_OleSetClipboard(PyObject *, PyObject *args) { PyObject *obd; // @pyparm <o PyIDataObject>|dataObj||The data object to place on the clipboard. // This parameter can be None in which case the clipboard is emptied. if (!PyArg_ParseTuple(args, "O:OleSetClipboard", &obd)) return NULL; IDataObject *pd; if (!PyCom_InterfaceFromPyObject(obd, IID_IDataObject, (void**)&pd, TRUE)) return NULL; HRESULT hr; Py_BEGIN_ALLOW_THREADS hr = ::OleSetClipboard(pd); Py_END_ALLOW_THREADS if (pd) pd->Release(); if (FAILED(hr)) { PyCom_BuildPyException(hr); return NULL; } Py_INCREF(Py_None); return Py_None; } // @pymethod true/false|pythoncom|OleIsCurrentClipboard|Determines whether the data object pointer previously placed on the clipboard by the OleSetClipboard function is still on the clipboard. static PyObject *pythoncom_OleIsCurrentClipboard(PyObject *, PyObject *args) { PyObject *obd; if (!PyArg_ParseTuple(args, "O:OleIsCurrentClipboard", &obd)) return NULL; // @pyparm <o PyIDataObject>|dataObj||The data object to check IDataObject *pd; if (!PyCom_InterfaceFromPyObject(obd, IID_IDataObject, (void**)&pd, FALSE)) return NULL; HRESULT hr; Py_BEGIN_ALLOW_THREADS hr = ::OleIsCurrentClipboard(pd); Py_END_ALLOW_THREADS pd->Release(); if (FAILED(hr)) { PyCom_BuildPyException(hr); return NULL; } PyObject *ret = hr==S_OK ? Py_True: Py_False; Py_INCREF(ret); return ret; } // @pymethod |pythoncom|OleFlushClipboard|Carries out the clipboard shutdown sequence. It also releases the IDataObject pointer that was placed on the clipboard by the <om pythoncom.OleSetClipboard> function. static PyObject *pythoncom_OleFlushClipboard(PyObject *, PyObject *args) { if (!PyArg_ParseTuple(args, ":OleFlushClipboard")) return NULL; HRESULT hr; Py_BEGIN_ALLOW_THREADS hr = ::OleFlushClipboard(); Py_END_ALLOW_THREADS if (FAILED(hr)) { PyCom_BuildPyException(hr); return NULL; } Py_INCREF(Py_None); return Py_None; } // @pymethod |pythoncom|RegisterDragDrop|Registers the specified window as // one that can be the target of an OLE drag-and-drop operation and // specifies the <o PyIDropTarget> instance to use for drop operations. static PyObject *pythoncom_RegisterDragDrop(PyObject *, PyObject *args) { PyObject *obd; HWND hwnd; PyObject *obhwnd; if (!PyArg_ParseTuple(args, "OO:RegisterDragDrop", &obhwnd, &obd)) return NULL; if (!PyWinObject_AsHANDLE(obhwnd, (HANDLE *)&hwnd)) return NULL; // @pyparm <o PyHANDLE>|hwnd||Handle to a window // @pyparm <o PyIDropTarget>|dropTarget||Object that implements the IDropTarget interface IDropTarget *dt; if (!PyCom_InterfaceFromPyObject(obd, IID_IDropTarget, (void**)&dt, FALSE)) return NULL; HRESULT hr; Py_BEGIN_ALLOW_THREADS hr = ::RegisterDragDrop(hwnd, dt); Py_END_ALLOW_THREADS dt->Release(); if (FAILED(hr)) { PyCom_BuildPyException(hr); return NULL; } Py_INCREF(Py_None); return Py_None; } // @pymethod |pythoncom|RevokeDragDrop|Revokes the registration of the // specified application window as a potential target for OLE drag-and-drop // operations. static PyObject *pythoncom_RevokeDragDrop(PyObject *, PyObject *args) { HWND hwnd; PyObject *obhwnd; // @pyparm <o PyHANDLE>|hwnd||Handle to a window registered as an OLE drop target. if (!PyArg_ParseTuple(args, "O:RevokeDragDrop", &obhwnd)) return NULL; if (!PyWinObject_AsHANDLE(obhwnd, (HANDLE *)&hwnd)) return NULL; HRESULT hr; Py_BEGIN_ALLOW_THREADS hr = ::RevokeDragDrop(hwnd); Py_END_ALLOW_THREADS if (FAILED(hr)) { PyCom_BuildPyException(hr); return NULL; } Py_INCREF(Py_None); return Py_None; } // @pymethod |pythoncom|DoDragDrop|Carries out an OLE drag and drop operation. static PyObject *pythoncom_DoDragDrop(PyObject *, PyObject *args) { PyObject *obdo, *obds; DWORD effects; if (!PyArg_ParseTuple(args, "OOl:DoDragDrop", &obdo, &obds, &effects)) return NULL; IDropSource *ds; if (!PyCom_InterfaceFromPyObject(obds, IID_IDropSource, (void**)&ds, FALSE)) return NULL; IDataObject *dob; if (!PyCom_InterfaceFromPyObject(obdo, IID_IDataObject, (void**)&dob, FALSE)) { ds->Release(); return NULL; } HRESULT hr; DWORD retEffect = 0; Py_BEGIN_ALLOW_THREADS hr = ::DoDragDrop(dob, ds, effects, &retEffect); Py_END_ALLOW_THREADS ds->Release(); dob->Release(); if (FAILED(hr)) { PyCom_BuildPyException(hr); return NULL; } return PyInt_FromLong(retEffect); } // @pymethod |pythoncom|OleInitialize|Calls OleInitialized - this should rarely // be needed, although some clipboard operations insist this is called rather // than <om pythoncom.CoInitialize> static PyObject *pythoncom_OleInitialize(PyObject *, PyObject *args) { if (!PyArg_ParseTuple(args, ":OleInitialize")) return NULL; HRESULT hr; Py_BEGIN_ALLOW_THREADS hr = ::OleInitialize(NULL); Py_END_ALLOW_THREADS if (FAILED(hr)) { PyCom_BuildPyException(hr); return NULL; } Py_INCREF(Py_None); return Py_None; } // @pymethod <o PyIUnknown>|pythoncom|ObjectFromLresult|Retrieves a requested // interface pointer for an object based on a previously generated object reference. static PyObject *pythoncom_ObjectFromLresult(PyObject *self, PyObject *args) { PyObject *oblresult; PyObject *obIID = NULL; PyObject *obwparam; // @pyparm int|lresult|| // @pyparm <o PyIID>|iid||The IID to query // @pyparm int|wparm|| LRESULT lresult; WPARAM wparam; IID iid; if (!PyArg_ParseTuple(args, "OOO", &oblresult, &obIID, &obwparam)) return NULL; if (!PyWinLong_AsULONG_PTR(oblresult, (ULONG_PTR *)&lresult)) return NULL; if (!PyWinLong_AsULONG_PTR(obwparam, (ULONG_PTR *)&wparam)) return NULL; if (obIID && !PyWinObject_AsIID(obIID, &iid)) return NULL; // GIL protects us from races here. if (pfnObjectFromLresult==NULL) { HMODULE hmod = LoadLibrary(_T("oleacc.dll")); if (hmod) pfnObjectFromLresult = (LPFNOBJECTFROMLRESULT) GetProcAddress(hmod, "ObjectFromLresult"); } if (pfnObjectFromLresult==NULL) return PyErr_Format(PyExc_NotImplementedError, "Not available on this platform"); HRESULT hr; void *ret = 0; Py_BEGIN_ALLOW_THREADS hr = (*pfnObjectFromLresult)(lresult, iid, wparam, &ret); Py_END_ALLOW_THREADS if (FAILED(hr)) { PyCom_BuildPyException(hr); return NULL; } // docs for ObjectFromLresult don't mention reference counting, but // it does say that you can't call this twice on the same object, and // it has a signature that implies normal reference counting. So // we assume this call has already added a reference to the result. return PyCom_PyObjectFromIUnknown((IUnknown *)ret, iid, FALSE); } // @pymethod <o PyIUnknown>|pythoncom|ObjectFromAddress|Returns a COM object given its address in memory. // @rdesc This method is useful for applications which return objects via non-standard // mechanisms - eg, Windows Explorer allows you to send a specific message to the // explorer window and the result will be the address of an object Explorer implements. // This method allows you to recover the object from that address. static PyObject *pythoncom_ObjectFromAddress(PyObject *self, PyObject *args) { IID iid = IID_IUnknown; void *addr; PyObject *obAddr; PyObject *obIID = NULL; // @pyparm int|address||The address which holds a COM object // @pyparm <o PyIID>|iid|IUnknown|The IID to query if (!PyArg_ParseTuple(args, "O|O", &obAddr, &obIID)) return NULL; if (!PyWinLong_AsVoidPtr(obAddr, &addr)) return NULL; if (obIID && !PyWinObject_AsIID(obIID, &iid)) return NULL; HRESULT hr; IUnknown *ret = 0; PyThreadState *_save = PyEval_SaveThread(); PYWINTYPES_TRY { hr = ((IUnknown *)addr)->QueryInterface(iid, (void **)&ret); PyEval_RestoreThread(_save); } PYWINTYPES_EXCEPT { PyEval_RestoreThread(_save); return PyErr_Format(PyExc_ValueError, "Address is not a valid COM object (win32 exception attempting to retrieve it!)"); } if (FAILED(hr) || ret==0) { PyCom_BuildPyException(hr); return NULL; } // We've added a reference via the QI above. return PyCom_PyObjectFromIUnknown(ret, iid, FALSE); } /* List of module functions */ // @module pythoncom|A module, encapsulating the OLE automation API static struct PyMethodDef pythoncom_methods[]= { { "_GetInterfaceCount", pythoncom_GetInterfaceCount, 1}, // @pymeth _GetInterfaceCount|Retrieves the number of interface objects currently in existance { "_GetGatewayCount", pythoncom_GetGatewayCount, 1}, // @pymeth _GetInterfaceCount|Retrieves the number of gateway objects currently in existance #ifndef MS_WINCE { "CoCreateFreeThreadedMarshaler", pythoncom_CoCreateFreeThreadedMarshaler, 1},// @pymeth CoCreateFreeThreadedMarshaler|Creates an aggregatable object capable of context-dependent marshaling. { "CoCreateInstanceEx", pythoncom_CoCreateInstanceEx, 1 }, // @pymeth CoCreateInstanceEx|Create a new instance of an OLE automation server possibly on a remote machine. #endif // MS_WINCE { "CoCreateInstance", pythoncom_CoCreateInstance, 1 }, // @pymeth CoCreateInstance|Create a new instance of an OLE automation server. { "CoFreeUnusedLibraries", pythoncom_CoFreeUnusedLibraries, 1}, // @pymeth CoFreeUnusedLibraries|Unloads any DLLs that are no longer in use and that, when loaded, were specified to be freed automatically. { "CoInitialize", pythoncom_CoInitialize, 1 }, // @pymeth CoInitialize|Initialize the COM libraries for the calling thread. { "CoInitializeEx", pythoncom_CoInitializeEx, 1 }, // @pymeth CoInitializeEx|Initialize the COM libraries for the calling thread. #ifndef MS_WINCE { "CoInitializeSecurity",pythoncom_CoInitializeSecurity, 1}, // @pymeth CoInitializeSecurity|Registers security and sets the default security values. { "CoGetInterfaceAndReleaseStream", pythoncom_CoGetInterfaceAndReleaseStream, 1}, // @pymeth CoGetInterfaceAndReleaseStream|Unmarshals a buffer containing an interface pointer and releases the stream when an interface pointer has been marshaled from another thread to the calling thread. { "CoMarshalInterThreadInterfaceInStream", pythoncom_CoMarshalInterThreadInterfaceInStream, 1}, // @pymeth CoMarshalInterThreadInterfaceInStream|Marshals an interface pointer from one thread to another thread in the same process. { "CoMarshalInterface", pythoncom_CoMarshalInterface, 1}, // @pymeth CoMarshalInterface|Marshals an interface into a stream { "CoUnmarshalInterface", pythoncom_CoUnmarshalInterface, 1}, // @pymeth CoUnmarshalInterface|Unmarshals an interface { "CoReleaseMarshalData", pythoncom_CoReleaseMarshalData, 1}, // @pymeth CoReleaseMarshalData|Frees resources used by a marshalled interface #endif // MS_WINCE { "CoGetObject", pythoncom_CoGetObject, 1}, // @pymeth CoGetObject|Converts a display name into a moniker that identifies the object named, and then binds to the object identified by the moniker. { "CoUninitialize", pythoncom_CoUninitialize, 1 }, // @pymeth CoUninitialize|Uninitialize the COM libraries. #ifndef MS_WINCE { "CoRegisterClassObject",pythoncom_CoRegisterClassObject, 1 },// @pymeth CoRegisterClassObject|Registers an EXE class object with OLE so other applications can connect to it. { "CoResumeClassObjects", pythoncom_CoResumeClassObjects, 1}, // @pymeth CoResumeClassObjects|Called by a server that can register multiple class objects to inform the OLE SCM about all registered classes, and permits activation requests for those class objects. { "CoRevokeClassObject",pythoncom_CoRevokeClassObject, 1 },// @pymeth CoRevokeClassObject|Informs OLE that a class object, previously registered with the <om pythoncom.CoRegisterClassObject> method, is no longer available for use. { "CoTreatAsClass", pythoncom_CoTreatAsClass, 1}, // @pymeth CoTreatAsClass|Establishes or removes an emulation, in which objects of one class are treated as objects of a different class. { "CoWaitForMultipleHandles", pythoncom_CoWaitForMultipleHandles, 1}, // @pymeth CoWaitForMultipleHandles|Waits for specified handles to be signaled or for a specified timeout period to elapse. { "Connect", pythoncom_connect, 1 }, // @pymeth Connect|Connects to a running instance of an OLE automation server. { "connect", pythoncom_connect, 1 }, { "CreateGuid", pythoncom_createguid, 1 }, // @pymeth CreateGuid|Creates a new, unique GUIID. { "CreateBindCtx", pythoncom_CreateBindCtx, 1 }, // @pymeth CreateBindCtx|Obtains a <o PyIBindCtx> object. { "CreateFileMoniker", pythoncom_CreateFileMoniker, 1 }, // @pymeth CreateFileMoniker|Creates a file moniker given a file name. { "CreateItemMoniker", pythoncom_CreateItemMoniker, 1 }, // @pymeth CreateItemMoniker|Creates an item moniker that identifies an object within a containing object (typically a compound document). { "CreatePointerMoniker", pythoncom_CreatePointerMoniker, 1 }, // @pymeth CreatePointerMoniker|Creates a pointer moniker based on a pointer to an object. { "CreateURLMonikerEx", pythoncom_CreateURLMonikerEx, 1 }, // @pymeth CreateURLMoniker|Create a URL moniker from a full url or partial url and base moniker { "CreateTypeLib", pythoncom_CreateTypeLib, 1}, // @pymeth CreateTypeLib|Provides access to a new object instance that supports the ICreateTypeLib interface. { "CreateTypeLib2", pythoncom_CreateTypeLib2, 1}, // @pymeth CreateTypeLib2|Provides access to a new object instance that supports the ICreateTypeLib2 interface. #endif // MS_WINCE { "CreateStreamOnHGlobal", pythoncom_CreateStreamOnHGlobal, 1 }, // @pymeth CreateStreamOnHGlobal|Creates an in-memory stream storage object { "CreateILockBytesOnHGlobal", pythoncom_CreateILockBytesOnHGlobal, 1 }, // @pymeth CreateILockBytesOnHGlobal|Creates an ILockBytes interface based on global memory { "EnableQuitMessage", pythoncom_EnableQuitMessage, 1 }, // @pymeth EnableQuitMessage|Indicates the thread PythonCOM should post a WM_QUIT message to. { "FUNCDESC", Py_NewFUNCDESC, 1}, // @pymeth FUNCDESC|Returns a new <o FUNCDESC> object. #ifndef MS_WINCE { "GetActiveObject", pythoncom_GetActiveObject, 1 }, // @pymeth GetActiveObject|Retrieves an object representing a running object registered with OLE { "GetClassFile", pythoncom_GetClassFile, 1 }, // @pymeth GetClassFile|Supplies the CLSID associated with the given filename. #endif // MS_WINCE { "GetFacilityString", pythoncom_GetFacilityString, 1 }, // @pymeth GetFacilityString|Returns the facility string, given an OLE scode. { "GetRecordFromGuids", pythoncom_GetRecordFromGuids, 1}, // @pymeth GetRecordFromGuids|Creates a new record object from the given GUIDs { "GetRecordFromTypeInfo", pythoncom_GetRecordFromTypeInfo, 1}, // @pymeth GetRecordFromTypeInfo|Creates a <o PyRecord> object from a <o PyITypeInfo> interface #ifndef MS_WINCE { "GetRunningObjectTable", pythoncom_GetRunningObjectTable, 1 }, // @pymeth GetRunningObjectTable|Obtains a <o PyIRunningObjectTable> object. #endif // MS_WINCE { "GetScodeString", pythoncom_GetScodeString, 1 }, // @pymeth GetScodeString|Returns the string for an OLE scode. { "GetScodeRangeString", pythoncom_GetScodeRangeString, 1 }, // @pymeth GetScodeRangeString|Returns the scode range string, given an OLE scode. { "GetSeverityString", pythoncom_GetSeverityString, 1 }, // @pymeth GetSeverityString|Returns the severity string, given an OLE scode. { "IsGatewayRegistered", pythoncom_IsGatewayRegistered, 1}, // @pymeth IsGatewayRegistered|Returns 1 if the given IID has a registered gateway object. { "LoadRegTypeLib", pythoncom_loadregtypelib, 1 }, // @pymeth LoadRegTypeLib|Loads a registered type library by CLSID { "LoadTypeLib", pythoncom_loadtypelib, 1 }, // @pymeth LoadTypeLib|Loads a type library by name { "MakeIID", pythoncom_MakeIID, 1 }, { "MakeTime", pythoncom_MakeTime, 1 }, { "MakePyFactory", pythoncom_MakePyFactory, 1 }, // @pymeth MakePyFactory|Creates a new <o PyIClassFactory> object wrapping a PythonCOM Class Factory object. #ifndef MS_WINCE { "MkParseDisplayName", pythoncom_MkParseDisplayName, 1 }, // @pymeth MkParseDisplayName|Parses a moniker display name into a moniker object. The inverse of IMoniker::GetDisplayName. #endif // MS_WINCE { "new", pythoncom_new, 1 }, { "New", pythoncom_new, 1 }, // @pymeth New|Create a new instance of an OLE automation server. { "ObjectFromAddress", pythoncom_ObjectFromAddress, 1 }, // @pymeth ObjectFromAddress|Returns a COM object given its address in memory. { "ObjectFromLresult", pythoncom_ObjectFromLresult, 1 }, // @pymeth ObjectFromLresult|Retrieves a requested interface pointer for an object based on a previously generated object reference. { "OleInitialize", pythoncom_OleInitialize, 1}, // @pymeth OleInitialize| { "OleGetClipboard", pythoncom_OleGetClipboard, 1}, // @pymeth OleGetClipboard|Retrieves a data object that you can use to access the contents of the clipboard. { "OleFlushClipboard", pythoncom_OleFlushClipboard, 1}, // @pymeth OleFlushClipboard|Carries out the clipboard shutdown sequence. It also releases the IDataObject pointer that was placed on the clipboard by the <om pythoncom.OleSetClipboard> function. { "OleIsCurrentClipboard",pythoncom_OleIsCurrentClipboard, 1}, // @pymeth OleIsCurrentClipboard|Determines whether the data object pointer previously placed on the clipboard by the OleSetClipboard function is still on the clipboard. { "OleSetClipboard", pythoncom_OleSetClipboard, 1}, // @pymeth OleSetClipboard|Places a pointer to a specific data object onto the clipboard. This makes the data object accessible to the OleGetClipboard function. { "OleLoadFromStream", pythoncom_OleLoadFromStream, 1}, // @pymeth OleLoadFromStream|Load an object from an IStream. { "OleSaveToStream", pythoncom_OleSaveToStream, 1}, // @pymeth OleSaveToStream|Save an object to an IStream. { "OleLoad", pythoncom_OleLoad, 1 }, // @pymeth OleLoad|Loads into memory an object nested within a specified storage object. #ifndef MS_WINCE { "ProgIDFromCLSID", pythoncom_progidfromclsid, 1 }, // @pymeth ProgIDFromCLSID|Converts a CLSID string to a progID. #endif // MS_WINCE { "PumpWaitingMessages", pythoncom_PumpWaitingMessages, 1}, // @pymeth PumpWaitingMessages|Pumps all waiting messages for the current thread. { "PumpMessages", pythoncom_PumpMessages, 1}, // @pymeth PumpMessages|Pumps all messages for the current thread until a WM_QUIT message. #ifndef MS_WINCE { "QueryPathOfRegTypeLib",pythoncom_querypathofregtypelib, 1}, // @pymeth QueryPathOfRegTypeLib|Retrieves the path of a registered type library #endif // MS_WINCE { "ReadClassStg", pythoncom_ReadClassStg, 1}, // @pymeth ReadClassStg|Reads a CLSID from a storage object { "ReadClassStm", pythoncom_ReadClassStm, 1}, // @pymeth ReadClassStm|Reads a CLSID from a <o PyIStream> object { "RegisterTypeLib", pythoncom_registertypelib, 1}, // @pymeth RegisterTypeLib|Adds information about a type library to the system registry. { "UnRegisterTypeLib", pythoncom_unregistertypelib, 1}, // @pymeth UnRegisterTypeLib|Removes a type library from the system registry. #ifndef MS_WINCE { "RegisterActiveObject",pythoncom_RegisterActiveObject, 1 }, // @pymeth RegisterActiveObject|Register an object as the active object for its class { "RevokeActiveObject", pythoncom_RevokeActiveObject, 1 }, // @pymeth RevokeActiveObject|Ends an object’s status as active. { "RegisterDragDrop", pythoncom_RegisterDragDrop, 1}, // @pymeth RegisterDragDrop|Registers the specified window as one that can be the target of an OLE drag-and-drop operation. { "RevokeDragDrop", pythoncom_RevokeDragDrop, 1}, // @pymeth RevokeDragDrop|Revokes the specified window as the target of an OLE drag-and-drop operation. { "DoDragDrop", pythoncom_DoDragDrop, 1}, // @pymeth DoDragDrop|Carries out an OLE drag and drop operation. #endif // MS_WINCE { "StgCreateDocfile", pythoncom_StgCreateDocfile, 1 }, // @pymeth StgCreateDocfile|Creates a new compound file storage object using the OLE-provided compound file implementation for the <o PyIStorage> interface. { "StgCreateDocfileOnILockBytes", pythoncom_StgCreateDocfileOnILockBytes, 1 }, // @pymeth StgCreateDocfileOnILockBytes|Creates a new compound file storage object using the OLE-provided compound file implementation for the <o PyIStorage> interface. #ifndef MS_WINCE { "StgIsStorageFile", pythoncom_StgIsStorageFile, 1 }, // @pymeth StgIsStorageFile|Indicates whether a particular disk file contains a storage object. #endif // MS_WINCE { "STGMEDIUM", Py_NewSTGMEDIUM, 1}, // @pymeth STGMEDIUM|Creates a new <o PySTGMEDIUM> object suitable for the <o PyIDataObject> interface. { "StgOpenStorage", pythoncom_StgOpenStorage, 1 }, // @pymeth StgOpenStorage|Opens an existing root storage object in the file system. { "StgOpenStorageEx", pythoncom_StgOpenStorageEx, 1 }, // @pymeth StgOpenStorageEx|Access IStorage and IPropertySetStorage interfaces for normal files { "TYPEATTR", Py_NewTYPEATTR, 1}, // @pymeth TYPEATTR|Returns a new <o TYPEATTR> object. { "VARDESC", Py_NewVARDESC, 1}, // @pymeth VARDESC|Returns a new <o VARDESC> object. { "WrapObject", pythoncom_WrapObject, 1 }, // @pymeth WrapObject|Wraps an object in a gateway. { "WriteClassStg", pythoncom_WriteClassStg, 1}, // @pymeth WriteClassStg|Stores a CLSID from a storage object { "WriteClassStm", pythoncom_WriteClassStm, 1}, // @pymeth WriteClassStm|Sets the CLSID of a stream { "UnwrapObject", pythoncom_UnwrapObject, 1 }, // @pymeth UnwrapObject|Unwraps a Python instance in a gateway object. { "FmtIdToPropStgName", pythoncom_FmtIdToPropStgName, 1}, //@pymeth FmtIdToPropStgName|Convert a FMTID to its stream name { "PropStgNameToFmtId", pythoncom_PropStgNameToFmtId, 1}, //@pymeth PropStgNameToFmtId|Convert property set name to FMTID { NULL, NULL } }; int AddConstant(PyObject *dict, const char *key, long value) { PyObject *oval = PyInt_FromLong(value); if (!oval) { return 1; } int rc = PyDict_SetItemString(dict, (char*)key, oval); Py_DECREF(oval); return rc; } #define ADD_CONSTANT(tok) AddConstant(dict, #tok, tok) static char *modName = "pythoncom"; extern BOOL initunivgw(PyObject *parentDict); /* Module initialisation */ PYWIN_MODULE_INIT_FUNC(pythoncom) { // The DLL Load inited the module. // All we do here is init COM itself. Done here // so other clients get a chance to beat us to it! // Support a special sys.coinit_flags attribute to control us. DWORD coinit_flags = COINIT_APARTMENTTHREADED; PyObject *obFlags = PySys_GetObject("coinit_flags"); // No reference added to obFlags. if (obFlags) { if (PyInt_Check(obFlags)) coinit_flags = PyInt_AsLong(obFlags); } else PyErr_Clear(); // Error raised by no coinit_flags attribute. HRESULT hr = PyCom_CoInitializeEx(NULL, coinit_flags); if (hr==E_NOTIMPL) // Special return val from PyCom_Co.. indicates not DCOM. hr = PyCom_CoInitialize(NULL); // If HR fails, we really dont care - the import should work. User can // manually CoInit() to see! PYWIN_MODULE_INIT_PREPARE(pythoncom, pythoncom_methods, "A module, encapsulating the OLE automation API"); // ensure the framework has valid state to work with. // XXX - more error checking? PyCom_RegisterCoreSupport(); PyDict_SetItemString(dict, "TypeIIDs", g_obPyCom_MapIIDToType); PyDict_SetItemString(dict, "ServerInterfaces", g_obPyCom_MapGatewayIIDToName); PyDict_SetItemString(dict, "InterfaceNames", g_obPyCom_MapInterfaceNameToIID); if (PyType_Ready(&PyOleEmptyType) == -1 ||PyType_Ready(&PyOleMissingType) == -1 ||PyType_Ready(&PyOleArgNotFoundType) == -1) PYWIN_MODULE_INIT_RETURN_ERROR; g_obEmpty = new PyOleEmpty; PyDict_SetItemString(dict, "Empty", g_obEmpty); g_obMissing = new PyOleMissing; PyDict_SetItemString(dict, "Missing", g_obMissing); g_obArgNotFound = new PyOleArgNotFound; PyDict_SetItemString(dict, "ArgNotFound", g_obArgNotFound); // Add some symbolic constants to the module // pycom_Error = PyString_FromString("pythoncom.error"); if (PyWinExc_COMError==NULL) { // This is created by PyWin_Globals_Ensure PyErr_SetString(PyExc_MemoryError, "can't define ole_error"); PYWIN_MODULE_INIT_RETURN_ERROR; } PyObject *pycom_Error = PyWinExc_COMError; if (PyDict_SetItemString(dict, "ole_error", PyWinExc_COMError) != 0) PYWIN_MODULE_INIT_RETURN_ERROR; if (PyDict_SetItemString(dict, "error", pycom_Error) != 0) PYWIN_MODULE_INIT_RETURN_ERROR; // Add the same constant, but with a "new name" if (PyDict_SetItemString(dict, "com_error", PyWinExc_COMError) != 0) PYWIN_MODULE_INIT_RETURN_ERROR; PyCom_InternalError = PyErr_NewException("pythoncom.internal_error", NULL, NULL); if (PyDict_SetItemString(dict, "internal_error", PyCom_InternalError) != 0) PYWIN_MODULE_INIT_RETURN_ERROR; // Add the IIDs if (PyCom_RegisterCoreIIDs(dict) != 0) PYWIN_MODULE_INIT_RETURN_ERROR; // Initialize various non-interface types if (PyType_Ready(&PyFUNCDESC::Type) == -1 || PyType_Ready(&PySTGMEDIUM::Type) == -1 || PyType_Ready(&PyTYPEATTR::Type) == -1 || PyType_Ready(&PyVARDESC::Type) == -1 || PyType_Ready(&PyRecord::Type) == -1) PYWIN_MODULE_INIT_RETURN_ERROR; // Setup our sub-modules if (!initunivgw(dict)) PYWIN_MODULE_INIT_RETURN_ERROR; // Load function pointers. HMODULE hModOle32 = GetModuleHandle(_T("ole32.dll")); if (hModOle32) pfnCoWaitForMultipleHandles = (CoWaitForMultipleHandlesfunc)GetProcAddress(hModOle32, "CoWaitForMultipleHandles"); HMODULE hModurlmon = GetModuleHandle(_T("urlmon.dll")); if (hModurlmon == NULL) hModurlmon = LoadLibrary(_T("urlmon.dll")); if (hModurlmon) pfnCreateURLMonikerEx = (CreateURLMonikerExfunc)GetProcAddress(hModurlmon, "CreateURLMonikerEx"); // Symbolic constants. ADD_CONSTANT(ACTIVEOBJECT_STRONG); ADD_CONSTANT(ACTIVEOBJECT_WEAK); ADD_CONSTANT(CLSCTX_ALL); ADD_CONSTANT(CLSCTX_INPROC); ADD_CONSTANT(CLSCTX_SERVER); ADD_CONSTANT(CLSCTX_INPROC_SERVER); ADD_CONSTANT(CLSCTX_INPROC_HANDLER); ADD_CONSTANT(CLSCTX_LOCAL_SERVER); ADD_CONSTANT(CLSCTX_REMOTE_SERVER); // COINIT values ADD_CONSTANT(COINIT_APARTMENTTHREADED); #ifdef _WIN32_DCOM ADD_CONSTANT(COINIT_MULTITHREADED); ADD_CONSTANT(COINIT_DISABLE_OLE1DDE); ADD_CONSTANT(COINIT_SPEED_OVER_MEMORY); #endif // CLIPBOARD ADD_CONSTANT(DATADIR_GET); ADD_CONSTANT(DATADIR_SET); ADD_CONSTANT(TYMED_HGLOBAL); ADD_CONSTANT(TYMED_FILE); ADD_CONSTANT(TYMED_ISTREAM); ADD_CONSTANT(TYMED_ISTORAGE); ADD_CONSTANT(TYMED_GDI); ADD_CONSTANT(TYMED_MFPICT); ADD_CONSTANT(TYMED_ENHMF); ADD_CONSTANT(TYMED_NULL); ADD_CONSTANT(DVASPECT_CONTENT); ADD_CONSTANT(DVASPECT_THUMBNAIL); ADD_CONSTANT(DVASPECT_ICON); ADD_CONSTANT(DVASPECT_DOCPRINT); // DISPATCH ADD_CONSTANT(DISPATCH_PROPERTYGET); ADD_CONSTANT(DISPATCH_PROPERTYPUT); ADD_CONSTANT(DISPATCH_PROPERTYPUTREF); ADD_CONSTANT(DISPATCH_METHOD); // DISPID ADD_CONSTANT(DISPID_CONSTRUCTOR); ADD_CONSTANT(DISPID_DESTRUCTOR); ADD_CONSTANT(DISPID_COLLECT); ADD_CONSTANT(DISPID_VALUE); ADD_CONSTANT(DISPID_UNKNOWN); ADD_CONSTANT(DISPID_PROPERTYPUT); ADD_CONSTANT(DISPID_NEWENUM); ADD_CONSTANT(DISPID_EVALUATE); #ifndef NO_PYCOM_IDISPATCHEX ADD_CONSTANT(DISPID_STARTENUM); ADD_CONSTANT(DISPID_UNKNOWN); #endif #ifdef DISPID_THIS ADD_CONSTANT(DISPID_THIS); #endif // EXTCON ADD_CONSTANT(EXTCONN_STRONG); ADD_CONSTANT(EXTCONN_WEAK); ADD_CONSTANT(EXTCONN_CALLABLE); // FUNCFLAGS ADD_CONSTANT(FUNCFLAG_FRESTRICTED); ADD_CONSTANT(FUNCFLAG_FSOURCE); ADD_CONSTANT(FUNCFLAG_FBINDABLE); ADD_CONSTANT(FUNCFLAG_FREQUESTEDIT); ADD_CONSTANT(FUNCFLAG_FDISPLAYBIND); ADD_CONSTANT(FUNCFLAG_FDEFAULTBIND); ADD_CONSTANT(FUNCFLAG_FHIDDEN); ADD_CONSTANT(FUNCFLAG_FUSESGETLASTERROR); // FUNCKIND ADD_CONSTANT(FUNC_VIRTUAL); ADD_CONSTANT(FUNC_PUREVIRTUAL); ADD_CONSTANT(FUNC_NONVIRTUAL); ADD_CONSTANT(FUNC_STATIC); ADD_CONSTANT(FUNC_DISPATCH); // IMPLTYPEFLAGS ADD_CONSTANT(IMPLTYPEFLAG_FDEFAULT); ADD_CONSTANT(IMPLTYPEFLAG_FSOURCE); ADD_CONSTANT(IMPLTYPEFLAG_FRESTRICTED); // IDLFLAGS ADD_CONSTANT(IDLFLAG_NONE); ADD_CONSTANT(IDLFLAG_FIN); ADD_CONSTANT(IDLFLAG_FOUT); ADD_CONSTANT(IDLFLAG_FLCID); ADD_CONSTANT(IDLFLAG_FRETVAL); // Moniker types. ADD_CONSTANT(MKSYS_NONE); ADD_CONSTANT(MKSYS_GENERICCOMPOSITE); ADD_CONSTANT(MKSYS_FILEMONIKER); ADD_CONSTANT(MKSYS_ANTIMONIKER); ADD_CONSTANT(MKSYS_ITEMMONIKER); ADD_CONSTANT(MKSYS_POINTERMONIKER); ADD_CONSTANT(MKSYS_CLASSMONIKER); // PARAMFLAGS ADD_CONSTANT(PARAMFLAG_NONE); ADD_CONSTANT(PARAMFLAG_FIN); ADD_CONSTANT(PARAMFLAG_FOUT); ADD_CONSTANT(PARAMFLAG_FLCID); ADD_CONSTANT(PARAMFLAG_FRETVAL); ADD_CONSTANT(PARAMFLAG_FOPT); ADD_CONSTANT(PARAMFLAG_FHASDEFAULT); // STREAMSEEK ADD_CONSTANT(STREAM_SEEK_SET); ADD_CONSTANT(STREAM_SEEK_CUR); ADD_CONSTANT(STREAM_SEEK_END); // INVOKEKIND ADD_CONSTANT(INVOKE_FUNC); ADD_CONSTANT(INVOKE_PROPERTYGET); ADD_CONSTANT(INVOKE_PROPERTYPUT); ADD_CONSTANT(INVOKE_PROPERTYPUTREF); ADD_CONSTANT(REGCLS_SINGLEUSE); ADD_CONSTANT(REGCLS_MULTIPLEUSE); ADD_CONSTANT(REGCLS_MULTI_SEPARATE); ADD_CONSTANT(REGCLS_SUSPENDED); // ROT ADD_CONSTANT(ROTFLAGS_REGISTRATIONKEEPSALIVE); ADD_CONSTANT(ROTFLAGS_ALLOWANYCLIENT); // RPC // Authentication Level used with CoInitializeSecurity ADD_CONSTANT(RPC_C_AUTHN_LEVEL_DEFAULT); // RPC_C_AUTHN_LEVEL_DEFAULT|Lets DCOM negotiate the authentication level automatically. (Win2k or later) ADD_CONSTANT(RPC_C_AUTHN_LEVEL_NONE); // RPC_C_AUTHN_LEVEL_NONE|Performs no authentication. ADD_CONSTANT(RPC_C_AUTHN_LEVEL_CONNECT); // RPC_C_AUTHN_LEVEL_CONNECT|Authenticates only when the client establishes a relationship with the server. Datagram transports always use RPC_AUTHN_LEVEL_PKT instead. ADD_CONSTANT(RPC_C_AUTHN_LEVEL_CALL); // RPC_C_AUTHN_LEVEL_CALL|Authenticates only at the beginning of each remote procedure call when the server receives the request. Datagram transports use RPC_C_AUTHN_LEVEL_PKT instead. ADD_CONSTANT(RPC_C_AUTHN_LEVEL_PKT); // RPC_C_AUTHN_LEVEL_PKT|Authenticates that all data received is from the expected client. ADD_CONSTANT(RPC_C_AUTHN_LEVEL_PKT_INTEGRITY); // RPC_C_AUTHN_LEVEL_PKT_INTEGRITY|Authenticates and verifies that none of the data transferred between client and server has been modified. ADD_CONSTANT(RPC_C_AUTHN_LEVEL_PKT_PRIVACY); // RPC_C_AUTHN_LEVEL_PKT_PRIVACY|Authenticates all previous levels and encrypts the argument value of each remote procedure call. // Impersonation level used with CoInitializeSecurity ADD_CONSTANT(RPC_C_IMP_LEVEL_DEFAULT); // RPC_C_IMP_LEVEL_DEFAULT|Use default impersonation level (Win2k or later) ADD_CONSTANT(RPC_C_IMP_LEVEL_ANONYMOUS); // RPC_C_IMP_LEVEL_ANONYMOUS|(Not supported in this release.) The client is anonymous to the server. The server process cannot obtain identification information about the client and it cannot impersonate the client. ADD_CONSTANT(RPC_C_IMP_LEVEL_IDENTIFY); // RPC_C_IMP_LEVEL_IDENTIFY|The server can obtain the client’s identity. The server can impersonate the client for ACL checking, but cannot access system objects as the client. This information is obtained when the connection is established, not on every call.<nl>Note  GetUserName will fail while impersonating at identify level. The workaround is to impersonate, OpenThreadToken, revert, call GetTokenInformation, and finally, call LookupAccountSid. ADD_CONSTANT(RPC_C_IMP_LEVEL_IMPERSONATE); // RPC_C_IMP_LEVEL_IMPERSONATE|The server process can impersonate the client's security context while acting on behalf of the client. This information is obtained when the connection is established, not on every call. ADD_CONSTANT(RPC_C_IMP_LEVEL_DELEGATE); // RPC_C_IMP_LEVEL_DELEGATE|(Not supported in this release.) The server process can impersonate the client's security context while acting on behalf of the client. The server process can also make outgoing calls to other servers while acting on behalf of the client. This information is obtained when the connection is established, not on every call. // Authentication capabilities used with CoInitializeSecurity (EOLE_AUTHENTICATION_CAPABILITIES enum) ADD_CONSTANT(EOAC_NONE); ADD_CONSTANT(EOAC_MUTUAL_AUTH); ADD_CONSTANT(EOAC_SECURE_REFS); ADD_CONSTANT(EOAC_ACCESS_CONTROL); ADD_CONSTANT(EOAC_APPID); ADD_CONSTANT(EOAC_DYNAMIC); ADD_CONSTANT(EOAC_STATIC_CLOAKING); ADD_CONSTANT(EOAC_DYNAMIC_CLOAKING); ADD_CONSTANT(EOAC_ANY_AUTHORITY); ADD_CONSTANT(EOAC_MAKE_FULLSIC); ADD_CONSTANT(EOAC_REQUIRE_FULLSIC); ADD_CONSTANT(EOAC_AUTO_IMPERSONATE); ADD_CONSTANT(EOAC_DEFAULT); ADD_CONSTANT(EOAC_DISABLE_AAA); ADD_CONSTANT(EOAC_NO_CUSTOM_MARSHAL); // STDOLE ADD_CONSTANT(STDOLE_MAJORVERNUM); ADD_CONSTANT(STDOLE_MINORVERNUM); ADD_CONSTANT(STDOLE_LCID); ADD_CONSTANT(STDOLE2_MAJORVERNUM); ADD_CONSTANT(STDOLE2_MINORVERNUM); ADD_CONSTANT(STDOLE2_LCID); // SYSKIND ADD_CONSTANT(SYS_WIN16); ADD_CONSTANT(SYS_WIN32); ADD_CONSTANT(SYS_MAC); // TYPEFLAGS ADD_CONSTANT(TYPEFLAG_FAPPOBJECT); ADD_CONSTANT(TYPEFLAG_FCANCREATE); ADD_CONSTANT(TYPEFLAG_FLICENSED); ADD_CONSTANT(TYPEFLAG_FPREDECLID); ADD_CONSTANT(TYPEFLAG_FHIDDEN); ADD_CONSTANT(TYPEFLAG_FCONTROL); ADD_CONSTANT(TYPEFLAG_FDUAL); ADD_CONSTANT(TYPEFLAG_FNONEXTENSIBLE); ADD_CONSTANT(TYPEFLAG_FOLEAUTOMATION); ADD_CONSTANT(TYPEFLAG_FRESTRICTED); ADD_CONSTANT(TYPEFLAG_FAGGREGATABLE); ADD_CONSTANT(TYPEFLAG_FREPLACEABLE); ADD_CONSTANT(TYPEFLAG_FDISPATCHABLE); ADD_CONSTANT(TYPEFLAG_FREVERSEBIND); // TYPEKIND ADD_CONSTANT(TKIND_ENUM); ADD_CONSTANT(TKIND_RECORD); ADD_CONSTANT(TKIND_MODULE); ADD_CONSTANT(TKIND_INTERFACE); ADD_CONSTANT(TKIND_DISPATCH); ADD_CONSTANT(TKIND_COCLASS); ADD_CONSTANT(TKIND_ALIAS); ADD_CONSTANT(TKIND_UNION); // VARFLAGS ADD_CONSTANT(VARFLAG_FREADONLY); // VARKIND ADD_CONSTANT(VAR_PERINSTANCE); ADD_CONSTANT(VAR_STATIC); ADD_CONSTANT(VAR_CONST); ADD_CONSTANT(VAR_DISPATCH); // VARTYPE ADD_CONSTANT(VT_EMPTY); ADD_CONSTANT(VT_NULL); ADD_CONSTANT(VT_I2); ADD_CONSTANT(VT_I4); ADD_CONSTANT(VT_R4); ADD_CONSTANT(VT_R8); ADD_CONSTANT(VT_CY); ADD_CONSTANT(VT_DATE); ADD_CONSTANT(VT_BSTR); ADD_CONSTANT(VT_DISPATCH); ADD_CONSTANT(VT_ERROR); ADD_CONSTANT(VT_BOOL); ADD_CONSTANT(VT_VARIANT); ADD_CONSTANT(VT_UNKNOWN); ADD_CONSTANT(VT_DECIMAL); ADD_CONSTANT(VT_I1); ADD_CONSTANT(VT_UI1); ADD_CONSTANT(VT_UI2); ADD_CONSTANT(VT_UI4); ADD_CONSTANT(VT_I8); ADD_CONSTANT(VT_UI8); ADD_CONSTANT(VT_INT); ADD_CONSTANT(VT_UINT); ADD_CONSTANT(VT_VOID); ADD_CONSTANT(VT_HRESULT); ADD_CONSTANT(VT_PTR); ADD_CONSTANT(VT_SAFEARRAY); ADD_CONSTANT(VT_CARRAY); ADD_CONSTANT(VT_USERDEFINED); ADD_CONSTANT(VT_LPSTR); ADD_CONSTANT(VT_LPWSTR); ADD_CONSTANT(VT_RECORD); ADD_CONSTANT(VT_FILETIME); ADD_CONSTANT(VT_BLOB); ADD_CONSTANT(VT_STREAM); ADD_CONSTANT(VT_STORAGE); ADD_CONSTANT(VT_STREAMED_OBJECT); ADD_CONSTANT(VT_STORED_OBJECT); ADD_CONSTANT(VT_BLOB_OBJECT); ADD_CONSTANT(VT_CF); ADD_CONSTANT(VT_CLSID); ADD_CONSTANT(VT_BSTR_BLOB); ADD_CONSTANT(VT_VECTOR); ADD_CONSTANT(VT_ARRAY); ADD_CONSTANT(VT_BYREF); ADD_CONSTANT(VT_RESERVED); ADD_CONSTANT(VT_ILLEGAL); ADD_CONSTANT(VT_ILLEGALMASKED); ADD_CONSTANT(VT_TYPEMASK); // DestContext for CoMarshalInterface (MSHCTX enum) ADD_CONSTANT(MSHCTX_LOCAL); ADD_CONSTANT(MSHCTX_NOSHAREDMEM); ADD_CONSTANT(MSHCTX_DIFFERENTMACHINE); ADD_CONSTANT(MSHCTX_INPROC); // Marshalling flags used with CoMarshalInterface (MSHLFLAGS enum) ADD_CONSTANT(MSHLFLAGS_NORMAL); ADD_CONSTANT(MSHLFLAGS_TABLESTRONG); ADD_CONSTANT(MSHLFLAGS_TABLEWEAK); ADD_CONSTANT(MSHLFLAGS_NOPING); // Flags for CreateUrlMoniker ADD_CONSTANT(URL_MK_UNIFORM); ADD_CONSTANT(URL_MK_LEGACY); // Flags for CoWaitForMultipleHandles ADD_CONSTANT(COWAIT_WAITALL); ADD_CONSTANT(COWAIT_ALERTABLE); #ifndef NO_PYCOM_IDISPATCHEX ADD_CONSTANT(fdexNameCaseSensitive); // Request that the name lookup be done in a case-sensitive manner. May be ignored by object that does not support case-sensitive lookup. ADD_CONSTANT(fdexNameEnsure); // Request that the member be created if it does not already exist. The new member should be created with the value VT_EMPTY. ADD_CONSTANT(fdexNameImplicit); // Indicates that the caller is searching object(s) for a member of a particular name, when the base object is not explicitly specified. ADD_CONSTANT(fdexNameCaseInsensitive); // Request that the name lookup be done in a case-insensitive manner. May be ignored by object that does not support case-insensitive lookup. ADD_CONSTANT(fdexPropCanGet); // The member can be obtained using DISPATCH_PROPERTYGET. ADD_CONSTANT(fdexPropCannotGet); // The member cannot be obtained using DISPATCH_PROPERTYGET. ADD_CONSTANT(fdexPropCanPut); // The member can be set using DISPATCH_PROPERTYPUT. ADD_CONSTANT(fdexPropCannotPut); // The member cannot be set using DISPATCH_PROPERTYPUT. ADD_CONSTANT(fdexPropCanPutRef); // The member can be set using DISPATCH_PROPERTYPUTREF. ADD_CONSTANT(fdexPropCannotPutRef); // The member cannot be set using DISPATCH_PROPERTYPUTREF. ADD_CONSTANT(fdexPropNoSideEffects); // The member does not have any side effects. For example, a debugger could safely get/set/call this member without changing the state of the script being debugged. ADD_CONSTANT(fdexPropDynamicType); // The member is dynamic and can change during the lifetime of the object. ADD_CONSTANT(fdexPropCanCall); // The member can be called as a method using DISPATCH_METHOD. ADD_CONSTANT(fdexPropCannotCall); // The member cannot be called as a method using DISPATCH_METHOD. ADD_CONSTANT(fdexPropCanConstruct); // The member can be called as a constructor using DISPATCH_CONSTRUCT. ADD_CONSTANT(fdexPropCannotConstruct); // The member cannot be called as a constructor using DISPATCH_CONSTRUCT. ADD_CONSTANT(fdexPropCanSourceEvents); // The member can fire events. ADD_CONSTANT(fdexPropCannotSourceEvents); // The member cannot fire events. #endif // NO_PYCOM_IDISPATCHEX // Expose the frozen flag, as Python itself doesnt!! // @prop int|frozen|1 if the host is a frozen program, else 0 AddConstant(dict, "frozen", Py_FrozenFlag ); // And finally some gross hacks relating to DCOM // Im really not sure what a better option is! // // If these #error pragma's fire it means this needs revisiting for // an upgrade to the MSVC header files! if (PyCom_HasDCom()) { # if ((CLSCTX_ALL != (CLSCTX_INPROC_SERVER| CLSCTX_INPROC_HANDLER|CLSCTX_LOCAL_SERVER| CLSCTX_REMOTE_SERVER)) || \ (CLSCTX_SERVER != (CLSCTX_INPROC_SERVER|CLSCTX_LOCAL_SERVER|CLSCTX_REMOTE_SERVER))) # error DCOM constants are not in synch. # endif ADD_CONSTANT(CLSCTX_ALL); ADD_CONSTANT(CLSCTX_SERVER); AddConstant(dict, "dcom", 1 ); } else { AddConstant(dict, "CLSCTX_ALL", CLSCTX_INPROC_SERVER| CLSCTX_INPROC_HANDLER| CLSCTX_LOCAL_SERVER ); AddConstant(dict, "CLSCTX_SERVER", CLSCTX_INPROC_SERVER| CLSCTX_LOCAL_SERVER ); AddConstant(dict, "dcom", 0 ); } AddConstant(dict, "__future_currency__", 0); PyObject *obfmtid=NULL; obfmtid=PyWinObject_FromIID(FMTID_DocSummaryInformation); PyDict_SetItemString(dict,"FMTID_DocSummaryInformation",obfmtid); Py_DECREF(obfmtid); obfmtid=PyWinObject_FromIID(FMTID_SummaryInformation); PyDict_SetItemString(dict,"FMTID_SummaryInformation",obfmtid); Py_DECREF(obfmtid); obfmtid=PyWinObject_FromIID(FMTID_UserDefinedProperties); PyDict_SetItemString(dict,"FMTID_UserDefinedProperties",obfmtid); Py_DECREF(obfmtid); // obfmtid=PyWinObject_FromIID(FMTID_MediaFileSummaryInfo); // PyDict_SetItemString(dict,"FMTID_MediaFileSummaryInfo",obfmtid); // Py_DECREF(obfmtid); // @prop int|dcom|1 if the system is DCOM aware, else 0. Only Win95 without DCOM extensions should return 0 // ### ALL THE @PROPERTY TAGS MUST COME AFTER THE LAST @PROP TAG!! // @property int|pythoncom|frozen|1 if the host is a frozen program, else 0 // @property int|pythoncom|dcom|1 if the system is DCOM aware, else 0. Only Win95 without DCOM extensions should return 0 PYWIN_MODULE_INIT_RETURN_SUCCESS; }
72a574f6cb59aee59ab7a8a477d8c523e85cdcdf
5486c8a5695a885152a6ff0278f64bc32bbf64b9
/UVa/13025 - Back to the Past.cpp
4ee81829983032e05f8f68b61b52f740444e2571
[]
no_license
emrul-chy/Competitive-Programming
3a3c5fd8fb41320d924c309873868a6d81585bf4
b22fddadaec2c40c1ffebaf594ded94434443662
refs/heads/master
2021-01-10T23:37:36.250883
2018-01-18T16:39:09
2018-01-18T16:39:09
70,418,520
2
1
null
null
null
null
UTF-8
C++
false
false
93
cpp
#include<stdio.h> int main() { printf("May 29, 2013 Wednesday\n"); return 0; }
f5f1dd91f18f2933632b4ab953dc066b33533cc9
52e20f6ebe62bb24a0cc3c024b3ed8af0ef7bd57
/Geometry Objects/ConvexCylinder.cpp
028001981f1396ce100d1a547a3c7bc937c2d44b
[]
no_license
matthiascy/crocus
a4bcc9b5683230f97c71fc8c8232e3cfd1e3029b
d0780e36d30c43a35d5bf9adc6b99892845cf95e
refs/heads/master
2023-01-14T01:15:29.091364
2019-12-09T17:59:51
2019-12-09T17:59:51
42,220,320
3
0
null
null
null
null
UTF-8
C++
false
false
3,218
cpp
#include "ConvexCylinder.h" #include <cmath> const double ConvexCylinder::kEpsilon = 0.001; ConvexCylinder::ConvexCylinder(void) : GeometryObject(), y0(-1.0), y1(1.0), radius(1.0), inv_radius(1.0) {} ConvexCylinder::ConvexCylinder(const double bottom, const double top, const double r) : GeometryObject(), y0(bottom), y1(top), radius(r), inv_radius(1.0 / radius) {} ConvexCylinder::ConvexCylinder(const ConvexCylinder& c) : GeometryObject(c), y0(c.y0), y1(c.y1), radius(c.radius), inv_radius(c.inv_radius) {} ConvexCylinder& ConvexCylinder::operator= (const ConvexCylinder& rhs) { if (this == &rhs) return (*this); GeometryObject::operator= (rhs); y0 = rhs.y0; y1 = rhs.y1; radius = rhs.radius; inv_radius = rhs.inv_radius; return (*this) ; } ConvexCylinder::~ConvexCylinder(void) {} // The code reverses the normal when the ray hits the inside surface, allows both // sides to be shaded, but completely messes up transparency. bool ConvexCylinder::hit(const Ray& ray, double& tmin, ShadeRec& sr) const { double t; double ox = ray.o.x; double oy = ray.o.y; double oz = ray.o.z; double dx = ray.d.x; double dy = ray.d.y; double dz = ray.d.z; double a = dx * dx + dz * dz; double b = 2.0 * (ox * dx + oz * dz); double c = ox * ox + oz * oz - radius * radius; double disc = b * b - 4.0 * a * c ; if (disc < 0.0) return(false); else { double e = sqrt(disc); double denom = 2.0 * a; t = (-b - e) / denom; // smaller root if (t > kEpsilon) { double yhit = oy + t * dy; if (yhit > y0 && yhit < y1) { tmin = t; sr.normal = Normal((ox + t * dx) * inv_radius, 0.0, (oz + t * dz) * inv_radius); sr.local_hit_point = ray.o + t * ray.d; return (true); } } t = (-b + e) / denom; // larger root if (t > kEpsilon) { double yhit = oy + t * dy; if (yhit > y0 && yhit < y1) { tmin = t; sr.normal = Normal((ox + t * dx) * inv_radius, 0.0, (oz + t * dz) * inv_radius); sr.local_hit_point = ray.o + t * ray.d; return (true); } } } return (false); } bool ConvexCylinder::shadow_hit(const Ray &ray, float &tmin) const { double t; double ox = ray.o.x; double oy = ray.o.y; double oz = ray.o.z; double dx = ray.d.x; double dy = ray.d.y; double dz = ray.d.z; double a = dx * dx + dz * dz; double b = 2.0 * (ox * dx + oz * dz); double c = ox * ox + oz * oz - radius * radius; double disc = b * b - 4.0 * a * c ; if (disc < 0.0) return(false); else { double e = sqrt(disc); double denom = 2.0 * a; t = (-b - e) / denom; // smaller root if (t > kEpsilon) { double yhit = oy + t * dy; if (yhit > y0 && yhit < y1) { tmin = t; return (true); } } t = (-b + e) / denom; // larger root if (t > kEpsilon) { double yhit = oy + t * dy; if (yhit > y0 && yhit < y1) { tmin = t; return (true); } } } return (false); }
4af65f9f424670bcbb0ce716463dab0e8b7d8b3c
65439e109bcb4644341187d911fc6dcfd145ac4a
/src/Instrucao.cpp
663742f4db837fb5200285bda3223fc7598fe1e8
[]
no_license
juan-santos/apresentacaoPAA
65e1ce2e802d15cdf5be9edfeba25a509ac2e4f7
7d082e692841a8b1a2206155c7259782d4da40be
refs/heads/master
2021-08-23T10:36:53.257363
2017-12-03T15:08:58
2017-12-03T15:08:58
112,538,810
0
0
null
null
null
null
UTF-8
C++
false
false
921
cpp
#include "Instrucao.h" Instrucao::Instrucao() { } int Instrucao::Run(sf::RenderWindow &App) { sf::Event Event; sf::Texture Texture; sf::Sprite Sprite; bool Running = true; if (!Texture.loadFromFile("bin/Release/files/images/menu/instrucao.png")){ std::cerr << "Error loading menu.png" << std::endl; } Sprite.setTexture(Texture); Sprite.setColor(sf::Color(255, 255, 255, 255)); while (Running) { //Verifying events while (App.pollEvent(Event)) { // Window closed if (Event.type == sf::Event::Closed) { return SAIR; } //Key pressed if (Event.type == sf::Event::KeyPressed) { switch (Event.key.code) { case sf::Keyboard::Return: return MENU; default: break; } } } //Clearing screen App.clear(); //Drawing App.draw(Sprite); App.display(); } return SAIR; }
ae992b6a1b0f1da69bc52e67b368ab40419c78e1
66c869c7e34c1557d17ba7185549ea49f8955b64
/core/include/ample/ActionsFactory.h
a94ae78d95d9b62122cf318f9da553b627fdb224
[ "MIT" ]
permissive
blizmax/ample
f091a00b9a69cac510be12d99f6f62de6989ec65
71336c2fb69748b8c2f27a6810e7cc047cbab359
refs/heads/master
2022-09-19T14:53:02.046860
2020-05-27T14:58:45
2020-05-27T14:58:45
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,341
h
#pragma once #include "Factory.h" #include "GraphicalRotateAction.h" #include "GraphicalTranslateAction.h" #include "FollowObjectAction.h" #include "CameraTranslateAction.h" #include "PhysicalApplyForceAction.h" namespace ample::game::factory { static ample::utils::Factory<Action, const std::string &> ActionsFactory; namespace registers { static ample::utils::Factory<Action, const std::string &>::Register<ample::game::stateMachine::actions::GraphicalTranslateAction> GraphicalTranslateActionRegister("GraphicalTranslateAction"); static ample::utils::Factory<Action, const std::string &>::Register<ample::game::stateMachine::actions::GraphicalRotateAction> GraphicalRotateActionRegister("GraphicalRotateAction"); static ample::utils::Factory<Action, const std::string &>::Register<ample::game::stateMachine::actions::PhysicalApplyForceAction> PhysicalApplyForceActionRegister("PhysicalApplyForceAction"); static ample::utils::Factory<Action, const std::string &>::Register<ample::game::stateMachine::actions::FollowObjectAction> FollowObjectActionActionRegister("FollowObjectAction"); static ample::utils::Factory<Action, const std::string &>::Register<ample::game::stateMachine::actions::CameraTranslateAction> CameraTranslateActionActionRegister("CameraTranslateAction"); } // namespace registers } // namespace ample::game::factory
bee932171576f57bee93e221b6d8fc1408868561
964e0c2adfe540f6412472370b2ccc51f938e207
/3.5일차/Sprite.cpp
70fbbf76802b2914a30994b5b226bd90b3ef0cd3
[]
no_license
andy5840/sosujungong
c804ed49792f77f0755b4231c96e048d50b4d1c1
d6002d94fca70d368ad403c091ecc06d7190cf0c
refs/heads/master
2022-11-30T12:38:49.348793
2020-08-19T06:50:06
2020-08-19T06:50:06
286,414,711
0
0
null
null
null
null
UTF-8
C++
false
false
979
cpp
#include "stdafx.h" #include "Sprite.h" Sprite::Sprite(char* path) { texture = textureManager->LoadTextureFromFile(path); D3DSURFACE_DESC desc; texture->GetLevelDesc(0, &desc); width = desc.Width; height = desc.Height; visibleRect.left = 0; visibleRect.right = 0; visibleRect.top = 0; visibleRect.bottom = 0; rect = visibleRect; color = D3DCOLOR_ARGB(255, 255, 255, 255); } Sprite::~Sprite() { } void Sprite::Render() { Object::Render(); pd3dSprite->SetTransform(&mat); pd3dSprite->Draw(texture, &visibleRect, NULL, NULL, color); } int Sprite::getWidth() { return width; } int Sprite::getHeight() { return height; } D3DCOLOR Sprite::getColor() { return color; } void Sprite::setColor(D3DCOLOR color) { this->color = color; } void Sprite::setCenter(int width, int height, Sprite* sprite) { rect.left = -width / 2; rect.top = -height / 2; rect.right = width / 2; rect.bottom = height / 2; sprite->pos = D3DXVECTOR2(-width / 2, -height / 2); }
01a7b31debe429bb783cef193cf4446270cee1fd
33035c05aad9bca0b0cefd67529bdd70399a9e04
/src/boost_geometry_io_svg_write_svg_multi.hpp
3c2086a333da0ec0f33bedd43d6b2a07a06ecaf5
[ "LicenseRef-scancode-unknown-license-reference", "BSL-1.0" ]
permissive
elvisbugs/BoostForArduino
7e2427ded5fd030231918524f6a91554085a8e64
b8c912bf671868e2182aa703ed34076c59acf474
refs/heads/master
2023-03-25T13:11:58.527671
2021-03-27T02:37:29
2021-03-27T02:37:29
null
0
0
null
null
null
null
UTF-8
C++
false
false
53
hpp
#include <boost/geometry/io/svg/write_svg_multi.hpp>
d408ca50bdb42bf173e87a6a271e041646a70101
ff25608db10343d007c5b6e3cdd1bbba72b49c23
/Tanoa_Life.Tanoa/The-Programmer/GPS/menu/gps_menu_map.hpp
3d8515074ac7a19b6fd3ce27f11890d3ee68c546
[]
no_license
172644/FriendLife.Tanoa
f722b690dd35132e839d829dd3e7cfb62f8d5a12
cb1efc0ccefacd6abcb390c22813c881298091a4
refs/heads/master
2022-12-25T21:37:24.101175
2020-10-10T21:03:59
2020-10-10T21:03:59
289,088,357
0
0
null
null
null
null
UTF-8
C++
false
false
5,324
hpp
/* Author: Maxence Lyon Altis DEV: https://altisdev.com/user/maxence-lyon Teamspeak 3: ts.the-programmer.com Web site: www.the-programmer.com Steam: « Une Vache Sur CS – Maxence », please leave a message on my profile who says the exact reason before adding me. Terms of use: - This file is forbidden unless you have permission from the author. If you have this file without permission to use it please do not use it and do not share it. - If you have permission to use this file, you can use it on your server however it is strictly forbidden to share it. - Out of respect for the author please do not delete this information. License number: Server's name: Owner's name: */ class gps_menu_map { idd = 369853; name = "gps_menu_map"; class controlsBackground { class Fond : A3GPS_RscPicture { text = "\Assets\Data\The-Programmer\GPS\menu\textures\gps_map.paa"; x = 0.2975 * safezoneW + safezoneX; y = 0.155 * safezoneH + safezoneY; w = 0.4 * safezoneW; h = 0.7 * safezoneH; idc = -1; }; class map : A3GPS_RscMapControl { idc = 2201; x = 0.3457 * safezoneW + safezoneX; y = 0.342 * safezoneH + safezoneY; w = 0.305 * safezoneW; h = 0.32 * safezoneH; }; }; class controls { class RscPicture_1208 : A3GPS_RscPicture { idc = 1205; text = "\A3\ui_f\data\GUI\Rsc\RscMiniMapSmall\gps_L_ca.paa"; x = 0.689 * safezoneW + safezoneX; y = 0.338 * safezoneH + safezoneY; w = 0.0239062 * safezoneW; h = 0.33 * safezoneH; }; class RscPicture_1209 : A3GPS_RscPicture { idc = 1213; text = "\A3\ui_f\data\GUI\Rsc\RscMiniMapSmall\gps_R_ca.paa"; x = 0.8261 * safezoneW + safezoneX; y = 0.338 * safezoneH + safezoneY; w = 0.0239062 * safezoneW; h = 0.33 * safezoneH; }; class RscPicture_1210 : A3GPS_RscPicture { idc = 1201; text = "\A3\ui_f\data\GUI\Rsc\RscMiniMapSmall\gps_B_ca.paa"; x = 0.7075 * safezoneW + safezoneX; y = 0.658 * safezoneH + safezoneY; w = 0.1275 * safezoneW; h = 0.051 * safezoneH; }; class RscPicture_1211 : A3GPS_RscPicture { idc = 1208; text = "\A3\ui_f\data\GUI\Rsc\RscMiniMapSmall\gps_BL_ca.paa"; x = 0.689 * safezoneW + safezoneX; y = 0.658 * safezoneH + safezoneY; w = 0.0239034 * safezoneW; h = 0.051 * safezoneH; }; class RscPicture_1212 : A3GPS_RscPicture { idc = 1212; text = "\A3\ui_f\data\GUI\Rsc\RscMiniMapSmall\gps_BR_ca.paa"; x = 0.8261 * safezoneW + safezoneX; y = 0.658 * safezoneH + safezoneY; w = 0.0239034 * safezoneW; h = 0.051 * safezoneH; }; class RscPicture_1213 : A3GPS_RscPicture { idc = 1206; text = "\A3\ui_f\data\GUI\Rsc\RscMiniMapSmall\gps_TL_ca.paa"; x = 0.689 * safezoneW + safezoneX; y = 0.303 * safezoneH + safezoneY; w = 0.0239034 * safezoneW; h = 0.051 * safezoneH; }; class RscPicture_1214 : A3GPS_RscPicture { idc = 1214; text = "\A3\ui_f\data\GUI\Rsc\RscMiniMapSmall\gps_TR_ca.paa"; x = 0.8261 * safezoneW + safezoneX; y = 0.303 * safezoneH + safezoneY; w = 0.0239034 * safezoneW; h = 0.051 * safezoneH; }; class RscPicture_1215 : A3GPS_RscPicture { idc = 1215; text = "\A3\ui_f\data\GUI\Rsc\RscMiniMapSmall\gps_T_ca.paa"; x = 0.703 * safezoneW + safezoneX; y = 0.303 * safezoneH + safezoneY; w = 0.1275 * safezoneW; h = 0.051 * safezoneH; }; class saved_paths : A3GPS_RscListBox { idc = 1500; x = 0.7175 * safezoneW + safezoneX; y = 0.363 * safezoneH + safezoneY; w = 0.1 * safezoneW; h = 0.2 * safezoneH; }; class exec_saved : A3GPS_RscButton { idc = 1600; x = 0.7175 * safezoneW + safezoneX; y = 0.623 * safezoneH + safezoneY; w = 0.103581 * safezoneW; h = 0.035 * safezoneH; }; class delete_saved : A3GPS_RscButton { idc = 1601; x = 0.7175 * safezoneW + safezoneX; y = 0.582 * safezoneH + safezoneY; w = 0.103581 * safezoneW; h = 0.035 * safezoneH; }; class femer : A3GPS_RscbuttonMain { idc = 2403; onbuttonclick = "closeDialog 0;"; x = 0.486301833333333 * safezoneW + safezoneX; y = 0.636430678466076 * safezoneH + safezoneY; w = 0.02 * safezoneW; h = 0.02 * safezoneH; animTextureDefault = ""; animTextureNormal = ""; animTextureDisabled = ""; animTextureOver = ""; animTextureFocused = ""; animTexturePressed = ""; text = ""; }; }; };
a02d8fd4ce849595ce3f7fd9eb24b6f0fa002e6a
dba9410a15ba312c5a37502b7c040de6c525974e
/bus-stops/bus-stops.cpp
77805271b9afc43423202845be05303fa15e7971
[]
no_license
feco93/OSM-projects
587c53b061ada45035785baef2c2ae71c4e2e599
33815a894d64d56ccd1291427d288c8efcb69178
refs/heads/master
2020-04-25T14:36:03.003808
2015-04-12T08:21:35
2015-04-12T08:21:35
33,809,001
0
0
null
null
null
null
UTF-8
C++
false
false
2,896
cpp
/* * Sipos Ferenc, [email protected] * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ #include <map> #include <list> #include <string> #include <iostream> #include <cstddef> #include <osmium/io/any_input.hpp> #include <osmium/handler.hpp> #include <osmium/visitor.hpp> #include <osmium/osm/node.hpp> #include <osmium/osm/way.hpp> #include <osmium/osm/relation.hpp> #include <osmium/index/map/sparse_table.hpp> #include <osmium/index/map/vector.hpp> #include <osmium/handler/node_locations_for_ways.hpp> #include <osmium/geom/haversine.hpp> class BusHandler:public osmium::handler::Handler { public: osmium::index::map::VectorBasedSparseMap <osmium::unsigned_object_id_type,osmium::Location, std::vector > locations; void relation (osmium::Relation & rel) { const char * bus = rel.tags ()["route"]; if (bus && (!strcmp (bus, "bus") /*|| !strcmp (bus, "trolleybus") || !strcmp(bus,"tram")*/) ) { std::string bus_no; if(rel.get_value_by_key("ref")) { bus_no=rel.get_value_by_key("ref"); } else { bus_no=rel.get_value_by_key("name"); } std::cout <<bus_no <<" BUS"<<'\n'; std::vector<std::vector<osmium::Location>> asd; for(const osmium::Tag& info : rel.tags() ) { std::cout <<info.key() <<": " <<info.value() <<'\t'; } std::cout <<'\n'; int i=0; for (const osmium::RelationMember& rm: rel.members()) { if(rm.type() == osmium::item_type::node) { osmium::Location loc = locations.get(rm.positive_ref()); std::cout <<i <<"\tLon: " <<loc.lon() <<"\tLat: " <<loc.lat() <<'\n'; } ++i; } } } }; int main (int argc, char *argv[]) { if (argc == 2) { osmium::io::File infile (argv[1]); osmium::io::Reader reader (infile, osmium::osm_entity_bits::all); BusHandler bus_handler; osmium::handler::NodeLocationsForWays < osmium::index::map::VectorBasedSparseMap <osmium::unsigned_object_id_type, osmium::Location, std::vector > > node_locations (bus_handler.locations); osmium::apply (reader, node_locations, bus_handler); reader.close (); google::protobuf::ShutdownProtobufLibrary (); } else { std::cout << "Usage: " << argv[0] << "city.osm" << std::endl; std::exit (1); } }
2442c3ecbb03bbc84d0180304e82123b0a16c202
7f11317085d407d10b0e55c4b31bc81333a07eaa
/Codeforces/1191/d/d.cpp
b3602ede18875f802b723f552ca94b70a776b2d7
[]
no_license
ericbrandwein/competencias
14116a1bc76e70a55ebebdc946679cd92cb8a3db
bf22b874646586ae7de573991fa932a2fa90e2c9
refs/heads/master
2023-05-03T09:51:26.100257
2021-05-30T16:18:08
2021-05-30T16:18:08
371,562,451
0
0
null
null
null
null
UTF-8
C++
false
false
1,423
cpp
//#pragma GCC optimize("Ofast") //#pragma GCC optimize("unroll-loops,no-stack-protector") //#pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,tune=native") #include <bits/stdc++.h> #define IOS ios::sync_with_stdio(false);cin.tie(0);cout.tie(0) #define endl '\n' #define elif else if #define ll long long int #define ld long double #define vec vector #define forn(a) for(ll a=0; a<n; a++) #define fore(a, v, n) for(ll a=v; a<n; a++) #define all(x) x.begin(), x.end() #define presicion(x) cout<<fixed<<setprecision(x) #define dbg(x) cerr<<#x<<" = "<<x<<endl #define PI 3.14159265358979323 #define sen(ang) sin((ang)*PI/180) //cout<<flush; using namespace std; int main() { IOS; ll n; cin >> n; vec<ll> a(n); ll suma = 0; forn (i) { cin >> a[i]; suma += a[i]; } vec<string> jugadores = {"sjfnb", "cslnb"}; sort(all(a)); if (n >= 2 && a[0] == 0 && a[1] == 0) { cout << jugadores[1] << endl; return 0; } ll iguales = 1; ll numero_igual = a[0]; fore (i, 1, n) { if (a[i] == a[i-1]) { iguales++; numero_igual = a[i]; } } if (iguales > 2) { cout << jugadores[1] << endl; return 0; } fore (i, 0, n) { if (a[i] == numero_igual - 1) { cout << jugadores[1] << endl; return 0; } } ll escalera = (n-1) * n / 2; ll restante = suma - escalera; if (restante % 2 == 0) { cout << jugadores[1] << endl; } else { cout << jugadores[0] << endl; } return 0; }
73eeb9facbd46821aa6536f72a4ae4fa9dae3cf2
fb6331627a01ff490b474a890ff56c2310f6bc39
/ChinolChoko/kzyKT/kzyKT.cc
8390ca858fccfcc6ffbbc0e5b5ecad25cb806521
[]
no_license
satellitex/acpc2017
a065b5f66734c5bdb206ae1c9c15f79ea032db70
8f938553eaaafe56565d77da9a406f05fe2ee107
refs/heads/master
2021-01-01T15:49:01.855760
2017-09-19T00:02:31
2017-09-19T00:02:31
97,707,979
1
2
null
null
null
null
UTF-8
C++
false
false
2,220
cc
#include <bits/stdc++.h> using namespace std; #define F first #define S second #define rrep(i,n) for(int i=(int)(n)-1;i>=0;i--) #define REP(i,a,b) for(int i=(int)(a);i<(int)(b);i++) #define rep(i,n) REP(i,0,n) typedef pair<double,double> P; #define N 1001 double d[1<<15][15][15]; vector<int> G[N],rG[N],g; bool u[N]; int n,cmp[N]; void add_edge(int x,int y){G[x].push_back(y);rG[y].push_back(x);} void dfs(int x){u[x]=1;rep(i,G[x].size())if(!u[G[x][i]])dfs(G[x][i]);g.push_back(x);} void rdfs(int x,int k){u[x]=1;cmp[x]=k;rep(i,rG[x].size())if(!u[rG[x][i]])rdfs(rG[x][i],k);} int scc() { memset(u,0,sizeof(u));g.clear();rep(i,n)if(!u[i])dfs(i);memset(u,0,sizeof(u)); int k=0;rrep(i,g.size())if(!u[g[i]])rdfs(g[i],k++);return k; } void init() { rep(i,n) G[i].clear(),rG[i].clear(); g.clear(); } int rev(int x) {return (x+n/2)%n;} int two_sat(vector<P> v) { init(); rep(i,v.size()) { add_edge(v[i].F,rev(v[i].S)); add_edge(v[i].S,rev(v[i].F)); } scc(); rep(i,n/2) { if(cmp[i]==cmp[i+n/2]) return 0; } return 1; } double D(P a,P b) { return sqrt((a.F-b.F)*(a.F-b.F)+(a.S-b.S)*(a.S-b.S)); } int main() { int m; cin >> n >> m; P a[n][2],b[m]; rep(i,n)rep(j,2) cin >> a[i][j].F >> a[i][j].S; rep(i,m) cin >> b[i].F >> b[i].S; rep(t,1<<m)rep(i,m)rep(j,m) d[t][i][j]=1<<30; rep(k,m) { d[1<<k][k][k]=0; rep(t,1<<m) { rep(i,m) { if(!(t&(1<<i))) continue; rep(j,m) { if(!(t&(1<<j))) d[t|(1<<j)][k][j]=min(d[t|(1<<j)][k][j],d[t][k][i]+D(b[i],b[j])); } } } } double c[n][n][4]; n*=2; rep(i,n/2) { REP(j,i+1,n/2) { rep(k,4) c[i][j][k]=1<<30; rep(k,m)rep(l,m)rep(s,2)rep(t,2)c[i][j][s+t*2]=min(c[i][j][s+t*2],D(a[i][s],b[k])+d[(1<<m)-1][k][l]+D(b[l],a[j][t])); } } double l=0,r=10000; rep(t,50) { double mid=(l+r)/2; vector<P> v; rep(i,n/2) { REP(j,i+1,n/2) { if(c[i][j][0]>mid) v.push_back(P(i,j)); if(c[i][j][1]>mid) v.push_back(P(rev(i),j)); if(c[i][j][2]>mid) v.push_back(P(i,rev(j))); if(c[i][j][3]>mid) v.push_back(P(rev(i),rev(j))); } } if(two_sat(v)) r=mid; else l=mid; } printf("%.10f\n",l); return 0; }
a020088919fe78e4e4e195a36c06833bf39b26b5
9647fd27fed29c2614f8d406fa90f19f1b55370c
/simon-touch/voipproviderfactory.cpp
d88aae90ef30c77f894b6fefe015e0fa3cf6a927
[]
no_license
KDE/simon-tools
aa42bdd96dff99a67c0e1a93adaa89afce7f749b
ca668c91b6ac2455b8bdd47f013701eff1ea1fb9
refs/heads/master
2021-01-06T20:37:26.029880
2019-03-03T01:06:46
2019-03-03T01:06:46
42,732,489
2
0
null
null
null
null
UTF-8
C++
false
false
954
cpp
/* * Copyright (C) 2011-2012 Peter Grasch <[email protected]> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2, * or (at your option) any later version, as published by the Free * Software Foundation * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details * * You should have received a copy of the GNU General Public * License along with this program; if not, write to the * Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "voipproviderfactory.h" #include "skypevoipprovider.h" VoIPProvider* VoIPProviderFactory::getProvider() { return new SkypeVoIPProvider; }
a120c473245e832ef76ab896c1f66b26bfb39e58
26ad4cc35496d364b31396e43a863aee08ef2636
/SDK/SoT_Proposal_Merchant_Rank07_CargoRun_03_classes.hpp
002c3f2d67d747c02e3e6b1c78b449cd49bd9fa1
[]
no_license
cw100/SoT-SDK
ddb9b19ce6ae623299b2b02dee51c29581537ba1
3e6f12384c8e21ed83ef56f00030ca0506d297fb
refs/heads/master
2020-05-05T12:09:55.938323
2019-03-20T14:11:57
2019-03-20T14:11:57
null
0
0
null
null
null
null
UTF-8
C++
false
false
817
hpp
#pragma once // Sea of Thieves (1.4) SDK #ifdef _MSC_VER #pragma pack(push, 0x8) #endif #include "SoT_Proposal_Merchant_Rank07_CargoRun_03_structs.hpp" namespace SDK { //--------------------------------------------------------------------------- //Classes //--------------------------------------------------------------------------- // BlueprintGeneratedClass Proposal_Merchant_Rank07_CargoRun_03.Proposal_Merchant_Rank07_CargoRun_03_C // 0x0000 (0x0138 - 0x0138) class UProposal_Merchant_Rank07_CargoRun_03_C : public UVoyageProposalDesc { public: static UClass* StaticClass() { static auto ptr = UObject::FindObject<UClass>(_xor_("BlueprintGeneratedClass Proposal_Merchant_Rank07_CargoRun_03.Proposal_Merchant_Rank07_CargoRun_03_C")); return ptr; } }; } #ifdef _MSC_VER #pragma pack(pop) #endif
a40b78e53bcb5d16ac5dd4fc44375829d1f9c9c4
2ded02bed0db431b80e918b41c644e66478f1c0a
/array/union_sorted_array.cpp
407328c508b4b606a09655b9ebaaa41bafb39c31
[]
no_license
itsmegr/next-dsa
e73bbd373c8bfc0e93d84d2870849b764c11abdb
fa50875f3b7a77bf9bfb215c311c5d8a280c3f4e
refs/heads/master
2023-05-15T00:32:12.443113
2021-06-09T17:02:55
2021-06-09T17:02:55
325,457,327
1
0
null
null
null
null
UTF-8
C++
false
false
2,197
cpp
#include<bits/stdc++.h> using namespace std; #define fo(i,n) for(i=0;i<n;i++) #define Fo(i,k,n) for(i=k;k<n?i<n:i>n;k<n?i+=1:i-=1) #define ll long long #define ull unsigned long long #define deb(x) cout << #x << "=" << x << endl #define deb2(x, y) cout << #x << "=" << x << "," << #y << "=" << y << endl #define pb push_back #define mp make_pair typedef pair<int, int> pii; typedef pair<ll,ll> pll; typedef vector<int> vi; typedef vector<ll> vl; typedef vector<pii> vpii; typedef vector<pll> vpl; typedef vector<vi> vvi; typedef vector<vl> vvl; void solve(); void takeArrayInput(int arr[], int n){ int i; fo(i,n){ cin>>arr[i]; } } int main() { #ifndef ONLINE_JUDGE freopen("input.txt", "r", stdin); freopen("output.txt", "w", stdout); #endif ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); int t = 1; cin >> t; while(t--) { solve(); } return 0; } void solve() { int i, j, n, m; cin>>n; int* a = new int[n]; takeArrayInput(a, n); cin>>m; int* b = new int[m]; takeArrayInput(b,m); if(a[0]>b[0]){ swap(a,b); swap(m,n); } //this programme will also run for array containing duplicate elemenst int count = 1, intersec = 0; i=0;j=0; while(i<n-1&&j<m){ if(a[i]!=a[i+1]){ count++; if(b[j]>a[i]&&b[j]<a[i+1]){ count++; j++; } else if(b[j]==a[i]||b[j]==a[i+1]){ j++; if(b[j]!=b[j-1]) intersec++; } } else{ if(b[j]==a[i]){ j++; if(b[j]!=b[j-1]) intersec++; } } deb2(i,j); deb(count); deb(intersec); i++; } if(i==n-1){ while(j<m-1){ if(b[j]!=b[j+1]&&b[j]!=a[i]){ count++; } j++; } count++; } if(j==m){ i++; while(i<n-1){ if(a[i]!=a[i+1]&&a[i]!=b[m-1]){ count++; } i++; } count++; } deb(count); deb(intersec); }
b95f0a0598ccb5f1e0c5f92f6f1d99ec119ac348
77263106b3b07890763ae16c2b43b200480579ac
/ball trail/box.cpp
470f23390b23d740b584b74c62ce6ac0757ca76f
[]
no_license
vivasvan1/tempballtrail
1f608f9453a7cb4f03abb470e296682b19e2a087
bfc00c95bcbf4570675fea734ede6307740c9ad0
refs/heads/master
2021-05-15T04:14:04.008632
2018-02-12T18:31:06
2018-02-12T18:31:06
119,888,572
0
0
null
null
null
null
UTF-8
C++
false
false
345
cpp
#include "box.h" Box::Box(const float width,const float height,const float depth,const std::string& fileName) { SetDepth(depth); SetHeight(height); } Box::~Box() { //dtor } void Box::Draw(Box box) { // floor.Draw(); // ceil.Draw(); // left.Draw(); // right.Draw(); // endWall.Draw(); // frontWall.Draw(); }
d224da84e34b8ac851d28e647b9b7b550e82f4c4
d6b461bf38bdadc03b30d39b1511b7e658d4890a
/Necro/Enemy.h
96857599728903225ae922242956e5b3031f8bd0
[]
no_license
koe22kr/2Dbasis
f27d74a038f6eb5f92ae91fae88ea2dbac2bd98c
1763942042c31f520a4039deba8d9ad9ad0fbc82
refs/heads/master
2022-04-05T08:26:19.643151
2020-03-04T01:42:09
2020-03-04T01:42:09
185,978,543
0
0
null
null
null
null
UTF-8
C++
false
false
745
h
#pragma once #include "Std.h" #include "Chara.h" class Pather { public: Pather* pre_pather = nullptr; POINT pos = { 0,0 }; int Score = 0; int direction; int Getdirection(); Pather(); ~Pather(); private: }; class Enemy :public Chara { public: virtual bool Init(); bool release(); virtual void Process(); virtual void Move(); virtual bool Mining(); virtual WINT Attack(); virtual void Change_rt(int start_rt,int end_rt); POINT Astar(); vector<POINT> Direction_for_search; vector<POINT> path; set <Pather*> Openlist; set <Pather*> Closelist; Pather* find_Pather_in_openlist(set<Pather*> openlist, Pather* newpather); Enemy(); virtual ~Enemy(); };
d1f1a335cda6b2fecd64ce254996e08f8219665b
5ec06dab1409d790496ce082dacb321392b32fe9
/clients/cpp-restsdk/generated/model/ComAdobeGraniteLicenseImplLicenseCheckFilterProperties.h
b697353f2d529559a4bdfbe1cffc3fc696309055
[ "Apache-2.0" ]
permissive
shinesolutions/swagger-aem-osgi
e9d2385f44bee70e5bbdc0d577e99a9f2525266f
c2f6e076971d2592c1cbd3f70695c679e807396b
refs/heads/master
2022-10-29T13:07:40.422092
2021-04-09T07:46:03
2021-04-09T07:46:03
190,217,155
3
3
Apache-2.0
2022-10-05T03:26:20
2019-06-04T14:23:28
null
UTF-8
C++
false
false
2,890
h
/** * Adobe Experience Manager OSGI config (AEM) API * Swagger AEM OSGI is an OpenAPI specification for Adobe Experience Manager (AEM) OSGI Configurations API * * OpenAPI spec version: 1.0.0-pre.0 * Contact: [email protected] * * NOTE: This class is auto generated by OpenAPI-Generator 3.2.1-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ /* * ComAdobeGraniteLicenseImplLicenseCheckFilterProperties.h * * */ #ifndef ORG_OPENAPITOOLS_CLIENT_MODEL_ComAdobeGraniteLicenseImplLicenseCheckFilterProperties_H_ #define ORG_OPENAPITOOLS_CLIENT_MODEL_ComAdobeGraniteLicenseImplLicenseCheckFilterProperties_H_ #include "../ModelBase.h" #include "ConfigNodePropertyBoolean.h" #include "ConfigNodePropertyInteger.h" #include "ConfigNodePropertyArray.h" namespace org { namespace openapitools { namespace client { namespace model { /// <summary> /// /// </summary> class ComAdobeGraniteLicenseImplLicenseCheckFilterProperties : public ModelBase { public: ComAdobeGraniteLicenseImplLicenseCheckFilterProperties(); virtual ~ComAdobeGraniteLicenseImplLicenseCheckFilterProperties(); ///////////////////////////////////////////// /// ModelBase overrides void validate() override; web::json::value toJson() const override; void fromJson(web::json::value& json) override; void toMultipart(std::shared_ptr<MultipartFormData> multipart, const utility::string_t& namePrefix) const override; void fromMultiPart(std::shared_ptr<MultipartFormData> multipart, const utility::string_t& namePrefix) override; ///////////////////////////////////////////// /// ComAdobeGraniteLicenseImplLicenseCheckFilterProperties members /// <summary> /// /// </summary> std::shared_ptr<ConfigNodePropertyInteger> getCheckInternval() const; bool checkInternvalIsSet() const; void unsetCheckInternval(); void setCheckInternval(std::shared_ptr<ConfigNodePropertyInteger> value); /// <summary> /// /// </summary> std::shared_ptr<ConfigNodePropertyArray> getExcludeIds() const; bool excludeIdsIsSet() const; void unsetExcludeIds(); void setExcludeIds(std::shared_ptr<ConfigNodePropertyArray> value); /// <summary> /// /// </summary> std::shared_ptr<ConfigNodePropertyBoolean> getEncryptPing() const; bool encryptPingIsSet() const; void unsetEncryptPing(); void setEncryptPing(std::shared_ptr<ConfigNodePropertyBoolean> value); protected: std::shared_ptr<ConfigNodePropertyInteger> m_CheckInternval; bool m_CheckInternvalIsSet; std::shared_ptr<ConfigNodePropertyArray> m_ExcludeIds; bool m_ExcludeIdsIsSet; std::shared_ptr<ConfigNodePropertyBoolean> m_EncryptPing; bool m_EncryptPingIsSet; }; } } } } #endif /* ORG_OPENAPITOOLS_CLIENT_MODEL_ComAdobeGraniteLicenseImplLicenseCheckFilterProperties_H_ */
7fae0103d14ec73e12e2b4e94f9dcf6e30b681b4
2abc848023b0701b0a1c66b53a29938f6819a6dd
/Aula-01/Tarefa-01/Tarefa-01.ino
82d7796dd8502be46898d7f0d8634d81cafa5563
[ "MIT" ]
permissive
thiagola92/PUC-INF1805
1e2fe76994ea9fe902fa20407544c10c7d2598bb
8d5b022f97181c698fa6607b3aecb672fe95b1eb
refs/heads/master
2021-06-25T22:35:36.001266
2020-01-24T04:57:51
2020-01-24T04:57:51
124,196,700
0
0
null
null
null
null
UTF-8
C++
false
false
1,348
ino
#define LED_PIN 13 #define KEY1 A1 #define KEY2 A2 #define KEY3 A3 int state = 1; float delayTime = 1000; unsigned long old; int but1pressed; int but2pressed; int but1delay = 1000; int but2delay = 1000; unsigned long but1old; unsigned long but2old; void setup() { // put your setup code here, to run once: pinMode(LED_PIN, OUTPUT); pinMode(KEY1, INPUT_PULLUP); pinMode(KEY2, INPUT_PULLUP); pinMode(KEY3, INPUT_PULLUP); Serial.begin(9600); but1pressed = 1000 + millis(); but2pressed = millis(); } void loop() { // put your main code here, to run repeatedly: unsigned long now = millis(); int but1 = digitalRead(KEY1); int but2 = digitalRead(KEY2); int but3 = digitalRead(KEY3); if((now >= but1old + but1delay) && (but1 == 0)){ delayTime /= 2.0; but1pressed = now; Serial.print('a'); Serial.print(delayTime); Serial.print('\n'); but1old = now; } if((now >= but2old + but2delay) && (but2 == 0)){ delayTime *= 2; but2pressed = now; Serial.print('b'); Serial.print(delayTime); Serial.print('\n'); but2old = now; } if (now >= old + delayTime){ old = now; state = !state; digitalWrite(LED_PIN, state); } int interval = abs(but1pressed - but2pressed); //Serial.println(interval); if(interval <= 500){ while(1); } }
824d50a5a1a74e3339f7f3b167e15a8ee569caa2
349ca5e14381a74d7d1e0fe542a0d62c664ca2da
/c++/Study1/Study1/CTest1.h
5595412c4a53a49197552463ededff0f1846b153
[]
no_license
somnisfelix/work
a4994c3a7b6409e3e954d0ed5b473f202288caaf
57af7c092faf2d1c2cfa5e33655908ceb4346dc1
refs/heads/master
2020-07-27T10:59:05.985251
2020-01-07T01:59:39
2020-01-07T01:59:39
209,066,492
0
0
null
null
null
null
UHC
C++
false
false
782
h
#pragma once class CTest1 { public: CTest1(); virtual ~CTest1(); public: void ConstTest1(const int number) { //number = 100; // 에러 매개변수에 const가 있으므로 m_nTestNumber = 20; } void ConstTest2(int number) const { number = 100; //m_nTestNumber = 20; // 에러 함수선언 뒤에 const가 붙었으므로 //int test = ConstTest3(20); //test = 200; } const int GetNumber() { return m_nTestNumber; } public: // 순수 가상함수 상속시 구현해줘야한다. virtual void ChildTest() = 0; virtual void ChildTest2() { m_nTestNumber = 200; } protected: int m_nTestNumber; }; class CTestChild : public CTest1 { public: CTestChild(); virtual ~CTestChild(); public: virtual void ChildTest() { m_nTestNumber = 20; } };
3e22a61c4bc4645cd12aa633e270d42cc0a54cd5
6c13991a694cd4ab5320c5bf79bab0e9d392e354
/envoy/source/common/protobuf/utility.cc
f2c94278313fca82213637bd6e7b14b994780d50
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
bdecoste/upstream-envoy-openssl
4cac1ac3df194f0896bb79db2813f0c8db14e8ca
f2bd116a9dd1f7da8ba00b6d473607190fdb0b2c
refs/heads/master
2022-10-13T08:05:35.704119
2019-10-11T22:11:24
2019-10-11T22:11:24
208,906,237
0
0
Apache-2.0
2022-09-23T22:28:25
2019-09-16T22:04:09
C++
UTF-8
C++
false
false
17,618
cc
#include "common/protobuf/utility.h" #include <numeric> #include "envoy/protobuf/message_validator.h" #include "common/common/assert.h" #include "common/common/fmt.h" #include "common/json/json_loader.h" #include "common/protobuf/message_validator_impl.h" #include "common/protobuf/protobuf.h" #include "absl/strings/match.h" #include "yaml-cpp/yaml.h" namespace Envoy { namespace { absl::string_view filenameFromPath(absl::string_view full_path) { size_t index = full_path.rfind("/"); if (index == std::string::npos || index == full_path.size()) { return full_path; } return full_path.substr(index + 1, full_path.size()); } void blockFormat(YAML::Node node) { node.SetStyle(YAML::EmitterStyle::Block); if (node.Type() == YAML::NodeType::Sequence) { for (auto it : node) { blockFormat(it); } } if (node.Type() == YAML::NodeType::Map) { for (auto it : node) { blockFormat(it.second); } } } } // namespace namespace ProtobufPercentHelper { uint64_t checkAndReturnDefault(uint64_t default_value, uint64_t max_value) { ASSERT(default_value <= max_value); return default_value; } uint64_t convertPercent(double percent, uint64_t max_value) { // Checked by schema. ASSERT(percent >= 0.0 && percent <= 100.0); return max_value * (percent / 100.0); } bool evaluateFractionalPercent(envoy::type::FractionalPercent percent, uint64_t random_value) { return random_value % fractionalPercentDenominatorToInt(percent.denominator()) < percent.numerator(); } uint64_t fractionalPercentDenominatorToInt( const envoy::type::FractionalPercent::DenominatorType& denominator) { switch (denominator) { case envoy::type::FractionalPercent::HUNDRED: return 100; case envoy::type::FractionalPercent::TEN_THOUSAND: return 10000; case envoy::type::FractionalPercent::MILLION: return 1000000; default: // Checked by schema. NOT_REACHED_GCOVR_EXCL_LINE; } } } // namespace ProtobufPercentHelper MissingFieldException::MissingFieldException(const std::string& field_name, const Protobuf::Message& message) : EnvoyException( fmt::format("Field '{}' is missing in: {}", field_name, message.DebugString())) {} ProtoValidationException::ProtoValidationException(const std::string& validation_error, const Protobuf::Message& message) : EnvoyException(fmt::format("Proto constraint validation failed ({}): {}", validation_error, message.DebugString())) { ENVOY_LOG_MISC(debug, "Proto validation error; throwing {}", what()); } void MessageUtil::loadFromJson(const std::string& json, Protobuf::Message& message, ProtobufMessage::ValidationVisitor& validation_visitor) { Protobuf::util::JsonParseOptions options; options.case_insensitive_enum_parsing = true; // Let's first try and get a clean parse when checking for unknown fields; // this should be the common case. options.ignore_unknown_fields = false; const auto strict_status = Protobuf::util::JsonStringToMessage(json, &message, options); if (strict_status.ok()) { // Success, no need to do any extra work. return; } // If we fail, we see if we get a clean parse when allowing unknown fields. // This is essentially a workaround // for https://github.com/protocolbuffers/protobuf/issues/5967. // TODO(htuch): clean this up when protobuf supports JSON/YAML unknown field // detection directly. options.ignore_unknown_fields = true; const auto relaxed_status = Protobuf::util::JsonStringToMessage(json, &message, options); // If we still fail with relaxed unknown field checking, the error has nothing // to do with unknown fields. if (!relaxed_status.ok()) { throw EnvoyException("Unable to parse JSON as proto (" + relaxed_status.ToString() + "): " + json); } // We know it's an unknown field at this point. validation_visitor.onUnknownField("type " + message.GetTypeName() + " reason " + strict_status.ToString()); } void MessageUtil::loadFromJson(const std::string& json, ProtobufWkt::Struct& message) { // No need to validate if converting to a Struct, since there are no unknown // fields possible. return loadFromJson(json, message, ProtobufMessage::getNullValidationVisitor()); } void MessageUtil::loadFromYaml(const std::string& yaml, Protobuf::Message& message, ProtobufMessage::ValidationVisitor& validation_visitor) { const auto loaded_object = Json::Factory::loadFromYamlString(yaml); // Load the message if the loaded object has type Object or Array. if (loaded_object->isObject() || loaded_object->isArray()) { const std::string json = loaded_object->asJsonString(); loadFromJson(json, message, validation_visitor); return; } throw EnvoyException("Unable to convert YAML as JSON: " + yaml); } void MessageUtil::loadFromFile(const std::string& path, Protobuf::Message& message, ProtobufMessage::ValidationVisitor& validation_visitor, Api::Api& api) { const std::string contents = api.fileSystem().fileReadToEnd(path); // If the filename ends with .pb, attempt to parse it as a binary proto. if (absl::EndsWith(path, FileExtensions::get().ProtoBinary)) { // Attempt to parse the binary format. if (message.ParseFromString(contents)) { MessageUtil::checkForUnexpectedFields(message, validation_visitor); return; } throw EnvoyException("Unable to parse file \"" + path + "\" as a binary protobuf (type " + message.GetTypeName() + ")"); } // If the filename ends with .pb_text, attempt to parse it as a text proto. if (absl::EndsWith(path, FileExtensions::get().ProtoText)) { if (Protobuf::TextFormat::ParseFromString(contents, &message)) { return; } throw EnvoyException("Unable to parse file \"" + path + "\" as a text protobuf (type " + message.GetTypeName() + ")"); } if (absl::EndsWith(path, FileExtensions::get().Yaml)) { loadFromYaml(contents, message, validation_visitor); } else { loadFromJson(contents, message, validation_visitor); } } void MessageUtil::checkForUnexpectedFields(const Protobuf::Message& message, ProtobufMessage::ValidationVisitor& validation_visitor, Runtime::Loader* runtime) { // Reject unknown fields. const auto& unknown_fields = message.GetReflection()->GetUnknownFields(message); if (!unknown_fields.empty()) { std::string error_msg; for (int n = 0; n < unknown_fields.field_count(); ++n) { error_msg += absl::StrCat(n > 0 ? ", " : "", unknown_fields.field(n).number()); } // We use the validation visitor but have hard coded behavior below for deprecated fields. // TODO(htuch): Unify the deprecated and unknown visitor handling behind the validation // visitor pattern. https://github.com/envoyproxy/envoy/issues/8092. validation_visitor.onUnknownField("type " + message.GetTypeName() + " with unknown field set {" + error_msg + "}"); } const Protobuf::Descriptor* descriptor = message.GetDescriptor(); const Protobuf::Reflection* reflection = message.GetReflection(); for (int i = 0; i < descriptor->field_count(); ++i) { const auto* field = descriptor->field(i); // If this field is not in use, continue. if ((field->is_repeated() && reflection->FieldSize(message, field) == 0) || (!field->is_repeated() && !reflection->HasField(message, field))) { continue; } #ifdef ENVOY_DISABLE_DEPRECATED_FEATURES bool warn_only = false; #else bool warn_only = true; #endif absl::string_view filename = filenameFromPath(field->file()->name()); // Allow runtime to be null both to not crash if this is called before server initialization, // and so proto validation works in context where runtime singleton is not set up (e.g. // standalone config validation utilities) if (runtime && field->options().deprecated() && !runtime->snapshot().deprecatedFeatureEnabled( absl::StrCat("envoy.deprecated_features.", filename, ":", field->name()))) { warn_only = false; } // If this field is deprecated, warn or throw an error. if (field->options().deprecated()) { std::string err = fmt::format( "Using deprecated option '{}' from file {}. This configuration will be removed from " "Envoy soon. Please see https://www.envoyproxy.io/docs/envoy/latest/intro/deprecated " "for details.", field->full_name(), filename); if (warn_only) { ENVOY_LOG_MISC(warn, "{}", err); } else { const char fatal_error[] = " If continued use of this field is absolutely necessary, see " "https://www.envoyproxy.io/docs/envoy/latest/configuration/operations/runtime" "#using-runtime-overrides-for-deprecated-features for how to apply a temporary and " "highly discouraged override."; throw ProtoValidationException(err + fatal_error, message); } } // If this is a message, recurse to check for deprecated fields in the sub-message. if (field->cpp_type() == Protobuf::FieldDescriptor::CPPTYPE_MESSAGE) { if (field->is_repeated()) { const int size = reflection->FieldSize(message, field); for (int j = 0; j < size; ++j) { checkForUnexpectedFields(reflection->GetRepeatedMessage(message, field, j), validation_visitor, runtime); } } else { checkForUnexpectedFields(reflection->GetMessage(message, field), validation_visitor, runtime); } } } } std::string MessageUtil::getYamlStringFromMessage(const Protobuf::Message& message, const bool block_print, const bool always_print_primitive_fields) { std::string json = getJsonStringFromMessage(message, false, always_print_primitive_fields); auto node = YAML::Load(json); if (block_print) { blockFormat(node); } YAML::Emitter out; out << node; return out.c_str(); } std::string MessageUtil::getJsonStringFromMessage(const Protobuf::Message& message, const bool pretty_print, const bool always_print_primitive_fields) { Protobuf::util::JsonPrintOptions json_options; // By default, proto field names are converted to camelCase when the message is converted to JSON. // Setting this option makes debugging easier because it keeps field names consistent in JSON // printouts. json_options.preserve_proto_field_names = true; if (pretty_print) { json_options.add_whitespace = true; } // Primitive types such as int32s and enums will not be serialized if they have the default value. // This flag disables that behavior. if (always_print_primitive_fields) { json_options.always_print_primitive_fields = true; } std::string json; const auto status = Protobuf::util::MessageToJsonString(message, &json, json_options); // This should always succeed unless something crash-worthy such as out-of-memory. RELEASE_ASSERT(status.ok(), ""); return json; } namespace { void jsonConvertInternal(const Protobuf::Message& source, ProtobufMessage::ValidationVisitor& validation_visitor, Protobuf::Message& dest) { Protobuf::util::JsonPrintOptions json_options; json_options.preserve_proto_field_names = true; std::string json; const auto status = Protobuf::util::MessageToJsonString(source, &json, json_options); if (!status.ok()) { throw EnvoyException(fmt::format("Unable to convert protobuf message to JSON string: {} {}", status.ToString(), source.DebugString())); } MessageUtil::loadFromJson(json, dest, validation_visitor); } } // namespace void MessageUtil::jsonConvert(const Protobuf::Message& source, ProtobufWkt::Struct& dest) { // Any proto3 message can be transformed to Struct, so there is no need to check for unknown // fields. There is one catch; Duration/Timestamp etc. which have non-object canonical JSON // representations don't work. jsonConvertInternal(source, ProtobufMessage::getNullValidationVisitor(), dest); } void MessageUtil::jsonConvert(const ProtobufWkt::Struct& source, ProtobufMessage::ValidationVisitor& validation_visitor, Protobuf::Message& dest) { jsonConvertInternal(source, validation_visitor, dest); } ProtobufWkt::Struct MessageUtil::keyValueStruct(const std::string& key, const std::string& value) { ProtobufWkt::Struct struct_obj; ProtobufWkt::Value val; val.set_string_value(value); (*struct_obj.mutable_fields())[key] = val; return struct_obj; } // TODO(alyssawilk) see if we can get proto's CodeEnumToString made accessible // to avoid copying it. Otherwise change this to absl::string_view. std::string MessageUtil::CodeEnumToString(ProtobufUtil::error::Code code) { switch (code) { case ProtobufUtil::error::OK: return "OK"; case ProtobufUtil::error::CANCELLED: return "CANCELLED"; case ProtobufUtil::error::UNKNOWN: return "UNKNOWN"; case ProtobufUtil::error::INVALID_ARGUMENT: return "INVALID_ARGUMENT"; case ProtobufUtil::error::DEADLINE_EXCEEDED: return "DEADLINE_EXCEEDED"; case ProtobufUtil::error::NOT_FOUND: return "NOT_FOUND"; case ProtobufUtil::error::ALREADY_EXISTS: return "ALREADY_EXISTS"; case ProtobufUtil::error::PERMISSION_DENIED: return "PERMISSION_DENIED"; case ProtobufUtil::error::UNAUTHENTICATED: return "UNAUTHENTICATED"; case ProtobufUtil::error::RESOURCE_EXHAUSTED: return "RESOURCE_EXHAUSTED"; case ProtobufUtil::error::FAILED_PRECONDITION: return "FAILED_PRECONDITION"; case ProtobufUtil::error::ABORTED: return "ABORTED"; case ProtobufUtil::error::OUT_OF_RANGE: return "OUT_OF_RANGE"; case ProtobufUtil::error::UNIMPLEMENTED: return "UNIMPLEMENTED"; case ProtobufUtil::error::INTERNAL: return "INTERNAL"; case ProtobufUtil::error::UNAVAILABLE: return "UNAVAILABLE"; case ProtobufUtil::error::DATA_LOSS: return "DATA_LOSS"; default: return ""; } } bool ValueUtil::equal(const ProtobufWkt::Value& v1, const ProtobufWkt::Value& v2) { ProtobufWkt::Value::KindCase kind = v1.kind_case(); if (kind != v2.kind_case()) { return false; } switch (kind) { case ProtobufWkt::Value::KIND_NOT_SET: return v2.kind_case() == ProtobufWkt::Value::KIND_NOT_SET; case ProtobufWkt::Value::kNullValue: return true; case ProtobufWkt::Value::kNumberValue: return v1.number_value() == v2.number_value(); case ProtobufWkt::Value::kStringValue: return v1.string_value() == v2.string_value(); case ProtobufWkt::Value::kBoolValue: return v1.bool_value() == v2.bool_value(); case ProtobufWkt::Value::kStructValue: { const ProtobufWkt::Struct& s1 = v1.struct_value(); const ProtobufWkt::Struct& s2 = v2.struct_value(); if (s1.fields_size() != s2.fields_size()) { return false; } for (const auto& it1 : s1.fields()) { const auto& it2 = s2.fields().find(it1.first); if (it2 == s2.fields().end()) { return false; } if (!equal(it1.second, it2->second)) { return false; } } return true; } case ProtobufWkt::Value::kListValue: { const ProtobufWkt::ListValue& l1 = v1.list_value(); const ProtobufWkt::ListValue& l2 = v2.list_value(); if (l1.values_size() != l2.values_size()) { return false; } for (int i = 0; i < l1.values_size(); i++) { if (!equal(l1.values(i), l2.values(i))) { return false; } } return true; } default: NOT_REACHED_GCOVR_EXCL_LINE; } } namespace { void validateDuration(const ProtobufWkt::Duration& duration) { if (duration.seconds() < 0 || duration.nanos() < 0) { throw DurationUtil::OutOfRangeException( fmt::format("Expected positive duration: {}", duration.DebugString())); } if (duration.nanos() > 999999999 || duration.seconds() > Protobuf::util::TimeUtil::kDurationMaxSeconds) { throw DurationUtil::OutOfRangeException( fmt::format("Duration out-of-range: {}", duration.DebugString())); } } } // namespace uint64_t DurationUtil::durationToMilliseconds(const ProtobufWkt::Duration& duration) { validateDuration(duration); return Protobuf::util::TimeUtil::DurationToMilliseconds(duration); } uint64_t DurationUtil::durationToSeconds(const ProtobufWkt::Duration& duration) { validateDuration(duration); return Protobuf::util::TimeUtil::DurationToSeconds(duration); } void TimestampUtil::systemClockToTimestamp(const SystemTime system_clock_time, ProtobufWkt::Timestamp& timestamp) { // Converts to millisecond-precision Timestamp by explicitly casting to millisecond-precision // time_point. timestamp.MergeFrom(Protobuf::util::TimeUtil::MillisecondsToTimestamp( std::chrono::time_point_cast<std::chrono::milliseconds>(system_clock_time) .time_since_epoch() .count())); } } // namespace Envoy
8901c7b0a6522c3bafbf3f2c7233c4b075942a78
b7ef6ad95ba4479255abe0e995b4f3928245223b
/myEngine/eGameObject.cpp
ed3dd731ddd75c8b462e24818759d236bb46ff17
[]
no_license
jelcic/SpaceHero
2cdfd44115675a87b6cd63badeba21a9da4ecb8f
dcddedaaffd17b86c7309f1e2ce72cb56122ce45
refs/heads/master
2020-04-29T00:45:41.836522
2019-03-18T21:01:45
2019-03-18T21:01:45
175,096,326
0
0
null
null
null
null
UTF-8
C++
false
false
1,479
cpp
#include "eGameObject.h" #include "Director.h" namespace Engine { eGameObject::eGameObject(int Zorder) : zOrder(Zorder) {} eGameObject::~eGameObject() { } void eGameObject::Init() { init(); } void eGameObject::Update(float dt) { update(dt); if (collider) collider->Update(Angle); } void eGameObject::Draw() { draw(); if (collider) collider->Draw(); } void eGameObject::SetAnchorPoint(Vec2 anchorPoint) { AnchorPoint = anchorPoint; } void eGameObject::SetGameObjectScale(float scale) { this->scale = scale; } void eGameObject::SetRotationCenter(float x, float y) { rotationCenter.X = x; rotationCenter.Y = y; } void eGameObject::AddCollider(Engine::eCollider * _collider) { if (collider) delete collider; collider = _collider; collide = true; } void eGameObject::DrawCollider(bool draw) { if(collider) collider->ShowCollider(draw); } Engine::eCollider * eGameObject::GetCollider() { return collider; } Size eGameObject::GetObjectSize() { return objectSize; } Vec2& eGameObject::GetPosition() { return Position; } Vec2 eGameObject::GetRotationCenter() { return rotationCenter; } void eGameObject::_setPosition(Vec2 newPosition) { Position = newPosition; } void eGameObject::Collision(eGameObject * secondObject) { } void eGameObject::SetObjectSize(int width, int height) { objectSize.Width = width; objectSize.Height = height; } eGameObject::eGameObject() {} }
92eb27a94c553af8a00cd7466823db317e7ac020
b4b4e324cbc6159a02597aa66f52cb8e1bc43bc1
/C++ code/HDU Online Judge/4605(2).cpp
de7a0b735e3e27b9cf016ee47a97d7c63762f084
[]
no_license
fsps60312/old-C-code
5d0ffa0796dde5ab04c839e1dc786267b67de902
b4be562c873afe9eacb45ab14f61c15b7115fc07
refs/heads/master
2022-11-30T10:55:25.587197
2017-06-03T16:23:03
2017-06-03T16:23:03
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,639
cpp
#include<cstdio> #include<cassert> #include<vector> #include<set> using namespace std; const int INF=2147483647; int Rand() { static unsigned int seed=20160221; seed*=0xdefaced,seed+=115216; return (seed+=seed>>20)&0x7fffffff; } static int Node_COUNTER=0; struct Node { Node *ch[2]; const int x; int sz; int cnt7,cnt2; int tag7,tag2; int ref; Node(const int _x):ch{NULL,NULL},x(_x),sz(1),cnt7(),cnt2(),tag7(),tag2(),ref(0) { Node_COUNTER++; } Node(Node *o):ch{o->ch[0],o->ch[1]},x(o->x),sz(o->sz),cnt7(o->cnt7),cnt2(o->cnt2),tag7(o->tag7),tag2(o->tag2),ref(0) { Node_COUNTER++; for(int d=0;d<2;d++)if(ch[d])ch[d]->ref++; } ~Node(){Node_COUNTER--;} void Add(const int v7,const int v2) { if(cnt7==-1)return; cnt7+=v7,cnt2+=v2; tag7+=v7,tag2+=v2; } }; void Assign(Node* &o,Node *v) { if(v)v->ref++; if(o&&!--o->ref) { for(int d=0;d<2;d++)Assign(o->ch[d],NULL); delete o; } o=v; } void PutDown(Node *o) { assert(o); if(!o->tag7&&!o->tag2)return; for(int d=0;d<2;d++)if(o->ch[d]) { Assign(o->ch[d],new Node(o->ch[d])); o->ch[d]->Add(o->tag7,o->tag2); } o->tag7=o->tag2=0; } int Sz(Node *o){return o?o->sz:0;} void Maintain(Node *o){o->sz=Sz(o->ch[0])+1+Sz(o->ch[1]);} void Merge(Node* &o,Node *a,Node *b) { if(a)a=new Node(a),a->ref++; if(b)b=new Node(b),b->ref++; if(!a||!b)Assign(o,a?a:b); else if(Rand()%(a->sz+b->sz)<a->sz) { Assign(o,a); PutDown(o); Merge(o->ch[1],o->ch[1],b); Maintain(o); } else { Assign(o,b); PutDown(o); Merge(o->ch[0],a,o->ch[0]); Maintain(o); } Assign(a,NULL),Assign(b,NULL); } void Split(Node *o,Node* &a,Node* &b,const int x) { if(o)o=new Node(o),o->ref++; if(!o)Assign(a,NULL),Assign(b,NULL); else if((o->x)<=x) { Assign(a,o); PutDown(a); Split(a->ch[1],a->ch[1],b,x); Maintain(a); } else { Assign(b,o); PutDown(b); Split(b->ch[0],a,b->ch[0],x); Maintain(b); } Assign(o,NULL); } void Query(Node *o,const int x,int &cnt7,int &cnt2) { if(!o)return; PutDown(o); if(x<=(o->x)) { cnt7=o->cnt7,cnt2=o->cnt2; Query(o->ch[0],x,cnt7,cnt2); } else Query(o->ch[1],x,cnt7,cnt2); } Node *S[100000]; int N,W[100000]; vector<int>ET[100000]; void BuildTree(const int u) { // printf("u=%d\n",u); if(ET[u].empty())return; assert((int)ET[u].size()==2); for(int d=0;d<2;d++) { Node *a=NULL,*b=NULL,*c=NULL; Split(S[u],b,c,W[u]); Split(b,a,b,W[u]-1); assert(a&&c); a->Add(0,1),b->cnt7=-1,c->Add(d,3); Merge(b,b,c); Merge(S[ET[u][d]],a,b); Assign(a,NULL),Assign(b,NULL),Assign(c,NULL); BuildTree(ET[u][d]); } } void Merge(Node* &o,const int x) { Node *n=NULL; Assign(n,new Node(x)); Merge(o,o,n); Assign(n,NULL); } int main() { // freopen("in.txt","r",stdin); for(int i=0;i<100000;i++)S[i]=NULL; int testcount;scanf("%d",&testcount); while(testcount--) { scanf("%d",&N); for(int i=0;i<N;i++)ET[i].clear(); for(int i=0;i<N;i++)scanf("%d",&W[i]); if(true) { int m;scanf("%d",&m); for(int u,a,b;m--;) { scanf("%d%d%d",&u,&a,&b),u--,a--,b--; ET[u].push_back(a),ET[u].push_back(b); } } if(true) { set<int>tmp; for(int i=0;i<N;i++)tmp.insert(W[i]-1),tmp.insert(W[i]); Assign(S[0],NULL); for(const int v:tmp)Merge(S[0],v); Merge(S[0],INF); } BuildTree(0); int querycount;scanf("%d",&querycount); for(int v,x,cnt7,cnt2;querycount--;) { scanf("%d%d",&v,&x),v--; Query(S[v],x,cnt7,cnt2); if(cnt7==-1)puts("0"); else printf("%d %d\n",cnt7,cnt2); } } // printf("Node_COUNTER=%d\n",Node_COUNTER); // for(int i=0;i<100000;i++)Assign(S[i],NULL); // printf("Node_COUNTER=%d\n",Node_COUNTER); // assert(Node_COUNTER==0); return 0; }
6eafc91e8b8083415befe6df065c6c0926d9bac2
133d0f38b3da2c51bf52bcdfa11d62978b94d031
/testAutocad/vendor/objectArx/inc/oleaprot.h
d44996624c03dfd45289b7b09a929ba3b15baae0
[]
no_license
Aligon42/ImportIFC
850404f1e1addf848e976b0351d9e217a72f868a
594001fc0942d356eb0d0472c959195151510493
refs/heads/master
2023-08-15T08:00:14.056542
2021-07-05T13:49:28
2021-07-05T13:49:28
361,410,709
0
1
null
null
null
null
UTF-8
C++
false
false
2,772
h
////////////////////////////////////////////////////////////////////////////// // // Copyright 2020 Autodesk, Inc. All rights reserved. // // Use of this software is subject to the terms of the Autodesk license // agreement provided at the time of installation or download, or which // otherwise accompanies this software in either electronic or hard copy form. // ////////////////////////////////////////////////////////////////////////////// #ifndef OLEAUTO_H #define OLEAUTO_H #include "adesk.h" #include "acdbport.h" #ifdef _ADESK_WINDOWS_ #include "dbmain.h" #pragma pack (push, 8) // // AcAxOleLinkManager is used to maintain the link between an ARX // objects and their respective COM wrapper. // class ADESK_NO_VTABLE AcAxOleLinkManager { public: // Given a pointer to a database resident object, return // the IUnknown of the COM wrapper. NULL is returned if // no wrapper is found. virtual IUnknown* GetIUnknown(AcDbObject* pObject) = 0; // Set the link between a database resident object and a // COM wrapper. If the IUnknown is NULL, then the link is removed. virtual Adesk::Boolean SetIUnknown(AcDbObject* pObject, IUnknown* pUnknown) = 0; // Given a pointer to a database object, return // the IUnknown of the COM wrapper. NULL is returned if // no wrapper is found. virtual IUnknown* GetIUnknown(AcDbDatabase* pDatabase) = 0; // Set the link between a database object and a COM wrapper. // If the IUnknown is NULL, then the link is removed. virtual Adesk::Boolean SetIUnknown(AcDbDatabase* pDatabase, IUnknown* pUnknown) = 0; // Given a pointer to a database object, return the // IDispatch of then document object. NULL is returned if // the database does not belong to a particular document. virtual IDispatch* GetDocIDispatch(AcDbDatabase* pDatabase) = 0; // Set the link between a database object and the IDispatch // of the document it belongs to. If the IDispatch is NULL, then // the link is removed. virtual Adesk::Boolean SetDocIDispatch(AcDbDatabase* pDatabase, IDispatch* pDispatch) = 0; // Given a pointer to a database resident object and a subentID, return // the IUnknown of the COM wrapper. NULL is returned if // no wrapper is found. virtual IUnknown* GetIUnknown(AcDbObject* pObject, const AcDbSubentId &id) = 0; // Set the link between a database resident object, a subentID and a // COM wrapper. If the IUnknown is NULL, then the link is removed. virtual Adesk::Boolean SetIUnknown(AcDbObject* pObject, const AcDbSubentId &id, IUnknown* pUnknown) = 0; }; ACDB_PORT AcAxOleLinkManager* AcAxGetOleLinkManager(); #pragma pack (pop) #endif //_ADESK_WINDOWS_ #endif // OLEAUTO_H
21d815d9c686ea95921031d8fe2066005f2a5422
c583a5fd60d8497c82c2864e5dec2d1b0853f3b1
/0092-Reverse_Linked_List_II/main.cpp
c418ead103c018884aa2896c25fb9557c21b2957
[]
no_license
oliver-zeng/leetcode
401c9455c73cfe198b1d947407596aaa4d61f6fe
d98fbefb9c6fc0dc78da3cfabf7906f3fa712102
refs/heads/master
2020-12-19T19:17:45.522346
2020-06-04T12:25:03
2020-06-04T12:25:03
235,826,235
0
0
null
null
null
null
UTF-8
C++
false
false
2,022
cpp
#include<iostream> using namespace std; struct ListNode { int val; ListNode* next; ListNode(int x) : val(x), next(NULL) {} }; ListNode* createListNode(int arr[], int sz) { if (sz == 0) return NULL; ListNode* head = new ListNode(arr[0]); ListNode* cur = head; for (int i = 1; i < sz; i++) { cur->next = new ListNode(arr[i]); cur = cur->next; } return head; } void printListNode(ListNode* head) { ListNode* p = head; while(p) { cout << p->val << " -> "; p = p->next; } cout << "null" << endl; return; } class Solution { private: bool g_debug = false; public: ListNode* reverseBetween(ListNode* head, int m, int n) { // 建立哨兵节点,里面的value随意写一个,能调用构造就行 ListNode* dummyHead = new ListNode(-1); dummyHead->next = head; // 找到m-1与m节点 ListNode* mPrev = dummyHead; ListNode* mNode; for (int i = 0; i < m - 1; i++, mPrev = mPrev->next); mNode = mPrev->next; if (g_debug) cout << "mPrev " << mPrev->val << " mNode " << mNode->val << endl; // 逆转从[m, n]的节点 // 逆转完成,prev是节点n,cur是节点n+1 int times = n - m + 1; ListNode* prev = mPrev; ListNode* cur = mNode; ListNode* next; while(times--) { next = cur->next; cur->next = prev; prev = cur; cur = next; } // mPrev -> [n, m] -> n + 1 mPrev->next = prev; mNode->next = cur; // 释放哨兵节点 head = dummyHead->next; delete dummyHead; return head; } }; int main() { int m = 2, n = 4; int arr[] = { 1,2,3,4,5 }; //int m = 1, n = 1; //int arr[] = { 5 }; ListNode* p = createListNode(arr, sizeof(arr)/sizeof(int)); printListNode(p); Solution().reverseBetween(p, m, n); printListNode(p); return 0; }
65635830a16978796b85593059886db4edac8ed2
9da42e04bdaebdf0193a78749a80c4e7bf76a6cc
/third_party/gecko-15/win32/include/nsIToolkitProfile.h
c0f0f24d7cf800dfcb237e90d564988c7f726f7d
[ "Apache-2.0" ]
permissive
bwp/SeleniumWebDriver
9d49e6069881845e9c23fb5211a7e1b8959e2dcf
58221fbe59fcbbde9d9a033a95d45d576b422747
refs/heads/master
2021-01-22T21:32:50.541163
2012-11-09T16:19:48
2012-11-09T16:19:48
6,602,097
1
0
null
null
null
null
UTF-8
C++
false
false
9,430
h
/* * DO NOT EDIT. THIS FILE IS GENERATED FROM e:/builds/moz2_slave/rel-m-rel-xr-w32-bld/build/toolkit/profile/nsIToolkitProfile.idl */ #ifndef __gen_nsIToolkitProfile_h__ #define __gen_nsIToolkitProfile_h__ #ifndef __gen_nsISupports_h__ #include "nsISupports.h" #endif /* For IDL files that don't want to include root IDL files. */ #ifndef NS_NO_VTABLE #define NS_NO_VTABLE #endif class nsILocalFile; /* forward declaration */ class nsIToolkitProfile; /* forward declaration */ class nsIProfileUnlocker; /* forward declaration */ /* starting interface: nsIProfileLock */ #define NS_IPROFILELOCK_IID_STR "7c58c703-d245-4864-8d75-9648ca4a6139" #define NS_IPROFILELOCK_IID \ {0x7c58c703, 0xd245, 0x4864, \ { 0x8d, 0x75, 0x96, 0x48, 0xca, 0x4a, 0x61, 0x39 }} class NS_NO_VTABLE NS_SCRIPTABLE nsIProfileLock : public nsISupports { public: NS_DECLARE_STATIC_IID_ACCESSOR(NS_IPROFILELOCK_IID) /* readonly attribute nsILocalFile directory; */ NS_SCRIPTABLE NS_IMETHOD GetDirectory(nsILocalFile * *aDirectory) = 0; /* readonly attribute nsILocalFile localDirectory; */ NS_SCRIPTABLE NS_IMETHOD GetLocalDirectory(nsILocalFile * *aLocalDirectory) = 0; /* readonly attribute PRInt64 replacedLockTime; */ NS_SCRIPTABLE NS_IMETHOD GetReplacedLockTime(PRInt64 *aReplacedLockTime) = 0; /* void unlock (); */ NS_SCRIPTABLE NS_IMETHOD Unlock(void) = 0; }; NS_DEFINE_STATIC_IID_ACCESSOR(nsIProfileLock, NS_IPROFILELOCK_IID) /* Use this macro when declaring classes that implement this interface. */ #define NS_DECL_NSIPROFILELOCK \ NS_SCRIPTABLE NS_IMETHOD GetDirectory(nsILocalFile * *aDirectory); \ NS_SCRIPTABLE NS_IMETHOD GetLocalDirectory(nsILocalFile * *aLocalDirectory); \ NS_SCRIPTABLE NS_IMETHOD GetReplacedLockTime(PRInt64 *aReplacedLockTime); \ NS_SCRIPTABLE NS_IMETHOD Unlock(void); /* Use this macro to declare functions that forward the behavior of this interface to another object. */ #define NS_FORWARD_NSIPROFILELOCK(_to) \ NS_SCRIPTABLE NS_IMETHOD GetDirectory(nsILocalFile * *aDirectory) { return _to GetDirectory(aDirectory); } \ NS_SCRIPTABLE NS_IMETHOD GetLocalDirectory(nsILocalFile * *aLocalDirectory) { return _to GetLocalDirectory(aLocalDirectory); } \ NS_SCRIPTABLE NS_IMETHOD GetReplacedLockTime(PRInt64 *aReplacedLockTime) { return _to GetReplacedLockTime(aReplacedLockTime); } \ NS_SCRIPTABLE NS_IMETHOD Unlock(void) { return _to Unlock(); } /* Use this macro to declare functions that forward the behavior of this interface to another object in a safe way. */ #define NS_FORWARD_SAFE_NSIPROFILELOCK(_to) \ NS_SCRIPTABLE NS_IMETHOD GetDirectory(nsILocalFile * *aDirectory) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetDirectory(aDirectory); } \ NS_SCRIPTABLE NS_IMETHOD GetLocalDirectory(nsILocalFile * *aLocalDirectory) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetLocalDirectory(aLocalDirectory); } \ NS_SCRIPTABLE NS_IMETHOD GetReplacedLockTime(PRInt64 *aReplacedLockTime) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetReplacedLockTime(aReplacedLockTime); } \ NS_SCRIPTABLE NS_IMETHOD Unlock(void) { return !_to ? NS_ERROR_NULL_POINTER : _to->Unlock(); } #if 0 /* Use the code below as a template for the implementation class for this interface. */ /* Header file */ class nsProfileLock : public nsIProfileLock { public: NS_DECL_ISUPPORTS NS_DECL_NSIPROFILELOCK nsProfileLock(); private: ~nsProfileLock(); protected: /* additional members */ }; /* Implementation file */ NS_IMPL_ISUPPORTS1(nsProfileLock, nsIProfileLock) nsProfileLock::nsProfileLock() { /* member initializers and constructor code */ } nsProfileLock::~nsProfileLock() { /* destructor code */ } /* readonly attribute nsILocalFile directory; */ NS_IMETHODIMP nsProfileLock::GetDirectory(nsILocalFile * *aDirectory) { return NS_ERROR_NOT_IMPLEMENTED; } /* readonly attribute nsILocalFile localDirectory; */ NS_IMETHODIMP nsProfileLock::GetLocalDirectory(nsILocalFile * *aLocalDirectory) { return NS_ERROR_NOT_IMPLEMENTED; } /* readonly attribute PRInt64 replacedLockTime; */ NS_IMETHODIMP nsProfileLock::GetReplacedLockTime(PRInt64 *aReplacedLockTime) { return NS_ERROR_NOT_IMPLEMENTED; } /* void unlock (); */ NS_IMETHODIMP nsProfileLock::Unlock() { return NS_ERROR_NOT_IMPLEMENTED; } /* End of implementation class template. */ #endif /* starting interface: nsIToolkitProfile */ #define NS_ITOOLKITPROFILE_IID_STR "7422b090-4a86-4407-972e-75468a625388" #define NS_ITOOLKITPROFILE_IID \ {0x7422b090, 0x4a86, 0x4407, \ { 0x97, 0x2e, 0x75, 0x46, 0x8a, 0x62, 0x53, 0x88 }} class NS_NO_VTABLE NS_SCRIPTABLE nsIToolkitProfile : public nsISupports { public: NS_DECLARE_STATIC_IID_ACCESSOR(NS_ITOOLKITPROFILE_IID) /* readonly attribute nsILocalFile rootDir; */ NS_SCRIPTABLE NS_IMETHOD GetRootDir(nsILocalFile * *aRootDir) = 0; /* readonly attribute nsILocalFile localDir; */ NS_SCRIPTABLE NS_IMETHOD GetLocalDir(nsILocalFile * *aLocalDir) = 0; /* attribute AUTF8String name; */ NS_SCRIPTABLE NS_IMETHOD GetName(nsACString & aName) = 0; NS_SCRIPTABLE NS_IMETHOD SetName(const nsACString & aName) = 0; /* void remove (in boolean removeFiles); */ NS_SCRIPTABLE NS_IMETHOD Remove(bool removeFiles) = 0; /* nsIProfileLock lock (out nsIProfileUnlocker aUnlocker); */ NS_SCRIPTABLE NS_IMETHOD Lock(nsIProfileUnlocker * *aUnlocker NS_OUTPARAM, nsIProfileLock * *_retval NS_OUTPARAM) = 0; }; NS_DEFINE_STATIC_IID_ACCESSOR(nsIToolkitProfile, NS_ITOOLKITPROFILE_IID) /* Use this macro when declaring classes that implement this interface. */ #define NS_DECL_NSITOOLKITPROFILE \ NS_SCRIPTABLE NS_IMETHOD GetRootDir(nsILocalFile * *aRootDir); \ NS_SCRIPTABLE NS_IMETHOD GetLocalDir(nsILocalFile * *aLocalDir); \ NS_SCRIPTABLE NS_IMETHOD GetName(nsACString & aName); \ NS_SCRIPTABLE NS_IMETHOD SetName(const nsACString & aName); \ NS_SCRIPTABLE NS_IMETHOD Remove(bool removeFiles); \ NS_SCRIPTABLE NS_IMETHOD Lock(nsIProfileUnlocker * *aUnlocker NS_OUTPARAM, nsIProfileLock * *_retval NS_OUTPARAM); /* Use this macro to declare functions that forward the behavior of this interface to another object. */ #define NS_FORWARD_NSITOOLKITPROFILE(_to) \ NS_SCRIPTABLE NS_IMETHOD GetRootDir(nsILocalFile * *aRootDir) { return _to GetRootDir(aRootDir); } \ NS_SCRIPTABLE NS_IMETHOD GetLocalDir(nsILocalFile * *aLocalDir) { return _to GetLocalDir(aLocalDir); } \ NS_SCRIPTABLE NS_IMETHOD GetName(nsACString & aName) { return _to GetName(aName); } \ NS_SCRIPTABLE NS_IMETHOD SetName(const nsACString & aName) { return _to SetName(aName); } \ NS_SCRIPTABLE NS_IMETHOD Remove(bool removeFiles) { return _to Remove(removeFiles); } \ NS_SCRIPTABLE NS_IMETHOD Lock(nsIProfileUnlocker * *aUnlocker NS_OUTPARAM, nsIProfileLock * *_retval NS_OUTPARAM) { return _to Lock(aUnlocker, _retval); } /* Use this macro to declare functions that forward the behavior of this interface to another object in a safe way. */ #define NS_FORWARD_SAFE_NSITOOLKITPROFILE(_to) \ NS_SCRIPTABLE NS_IMETHOD GetRootDir(nsILocalFile * *aRootDir) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetRootDir(aRootDir); } \ NS_SCRIPTABLE NS_IMETHOD GetLocalDir(nsILocalFile * *aLocalDir) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetLocalDir(aLocalDir); } \ NS_SCRIPTABLE NS_IMETHOD GetName(nsACString & aName) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetName(aName); } \ NS_SCRIPTABLE NS_IMETHOD SetName(const nsACString & aName) { return !_to ? NS_ERROR_NULL_POINTER : _to->SetName(aName); } \ NS_SCRIPTABLE NS_IMETHOD Remove(bool removeFiles) { return !_to ? NS_ERROR_NULL_POINTER : _to->Remove(removeFiles); } \ NS_SCRIPTABLE NS_IMETHOD Lock(nsIProfileUnlocker * *aUnlocker NS_OUTPARAM, nsIProfileLock * *_retval NS_OUTPARAM) { return !_to ? NS_ERROR_NULL_POINTER : _to->Lock(aUnlocker, _retval); } #if 0 /* Use the code below as a template for the implementation class for this interface. */ /* Header file */ class nsToolkitProfile : public nsIToolkitProfile { public: NS_DECL_ISUPPORTS NS_DECL_NSITOOLKITPROFILE nsToolkitProfile(); private: ~nsToolkitProfile(); protected: /* additional members */ }; /* Implementation file */ NS_IMPL_ISUPPORTS1(nsToolkitProfile, nsIToolkitProfile) nsToolkitProfile::nsToolkitProfile() { /* member initializers and constructor code */ } nsToolkitProfile::~nsToolkitProfile() { /* destructor code */ } /* readonly attribute nsILocalFile rootDir; */ NS_IMETHODIMP nsToolkitProfile::GetRootDir(nsILocalFile * *aRootDir) { return NS_ERROR_NOT_IMPLEMENTED; } /* readonly attribute nsILocalFile localDir; */ NS_IMETHODIMP nsToolkitProfile::GetLocalDir(nsILocalFile * *aLocalDir) { return NS_ERROR_NOT_IMPLEMENTED; } /* attribute AUTF8String name; */ NS_IMETHODIMP nsToolkitProfile::GetName(nsACString & aName) { return NS_ERROR_NOT_IMPLEMENTED; } NS_IMETHODIMP nsToolkitProfile::SetName(const nsACString & aName) { return NS_ERROR_NOT_IMPLEMENTED; } /* void remove (in boolean removeFiles); */ NS_IMETHODIMP nsToolkitProfile::Remove(bool removeFiles) { return NS_ERROR_NOT_IMPLEMENTED; } /* nsIProfileLock lock (out nsIProfileUnlocker aUnlocker); */ NS_IMETHODIMP nsToolkitProfile::Lock(nsIProfileUnlocker * *aUnlocker NS_OUTPARAM, nsIProfileLock * *_retval NS_OUTPARAM) { return NS_ERROR_NOT_IMPLEMENTED; } /* End of implementation class template. */ #endif #endif /* __gen_nsIToolkitProfile_h__ */
844a9d6f44dc610d697bcdaf299fd020ae4fa5f5
4bcc9806152542ab43fc2cf47c499424f200896c
/tensorflow/lite/delegates/gpu/cl/kernels/space_to_depth_test.cc
17b32bcaecc7e59dca660c340a673480ac32b64d
[ "Apache-2.0", "LicenseRef-scancode-generic-cla", "BSD-2-Clause" ]
permissive
tensorflow/tensorflow
906276dbafcc70a941026aa5dc50425ef71ee282
a7f3934a67900720af3d3b15389551483bee50b8
refs/heads/master
2023-08-25T04:24:41.611870
2023-08-25T04:06:24
2023-08-25T04:14:08
45,717,250
208,740
109,943
Apache-2.0
2023-09-14T20:55:50
2015-11-07T01:19:20
C++
UTF-8
C++
false
false
1,938
cc
/* Copyright 2020 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include <gmock/gmock.h> #include <gtest/gtest.h> #include "tensorflow/lite/delegates/gpu/cl/kernels/cl_test.h" #include "tensorflow/lite/delegates/gpu/common/operations.h" #include "tensorflow/lite/delegates/gpu/common/status.h" #include "tensorflow/lite/delegates/gpu/common/tasks/space_to_depth_test_util.h" namespace tflite { namespace gpu { namespace cl { namespace { // A known Qualcomm Adreno bug makes the 1 channel test fail on some Adreno // 5xxs. TEST_F(OpenCLOperationTest, SpaceToDepthTensorShape1x2x2x1BlockSize2) { ASSERT_OK(SpaceToDepthTensorShape1x2x2x1BlockSize2Test(&exec_env_)); } TEST_F(OpenCLOperationTest, SpaceToDepthTensorShape1x2x2x2BlockSize2) { ASSERT_OK(SpaceToDepthTensorShape1x2x2x2BlockSize2Test(&exec_env_)); } TEST_F(OpenCLOperationTest, SpaceToDepthTensorShape1x2x2x3BlockSize2) { ASSERT_OK(SpaceToDepthTensorShape1x2x2x3BlockSize2Test(&exec_env_)); } TEST_F(OpenCLOperationTest, SpaceToDepthTensorShape1x4x4x1BlockSize2) { ASSERT_OK(SpaceToDepthTensorShape1x4x4x1BlockSize2Test(&exec_env_)); } TEST_F(OpenCLOperationTest, SpaceToDepthTensorShape1x6x6x1BlockSize3) { ASSERT_OK(SpaceToDepthTensorShape1x6x6x1BlockSize3Test(&exec_env_)); } } // namespace } // namespace cl } // namespace gpu } // namespace tflite
d2c6bc478596a0d4ce6d3fe51280de5181f093a3
23d71c9281cfd801a2f5599c53d475c7879ab707
/proyecto/ProyectoEstructuras/ProyectoEstructuras/Proyecto.cpp
88e0ed079de6034fd8f8781ea3939d96a185e3ea
[]
no_license
abicarvajal/ProyectoEstructuras
479dd62d44fade0b491650247911c633beb85ab6
f2c77e9d8091f2009fff82b70b5f073c1047637a
refs/heads/master
2021-08-22T03:50:01.074416
2017-11-29T06:01:18
2017-11-29T06:01:18
112,433,406
0
0
null
null
null
null
ISO-8859-1
C++
false
false
26,936
cpp
#include <iostream> #include <conio.h> #include <string> #include <locale.h> #include <stdio.h> #include <stdlib.h> #include <windows.h> #include "qrcodegen.h" #define Tam 11 #define vabTam 20 using namespace std; //DEFINICION DE ESTRUCTURAS struct Producto { //muestra produtos char nombre[20]; float precio = 0; float pUnidad = 0; int stock = 0; }; struct DatosCliente { char nombre[15]; char apellido[15]; int cedula; }; struct ListaDatosCliente { DatosCliente datosCliente; float total = 0.0f; ListaDatosCliente *ant, *sig; }; struct ListaProducto { Producto producto; ListaProducto *sig; ListaProducto *ant; }listita; struct Factura { ListaProducto compra; DatosCliente datos; float total; }; typedef ListaProducto *Lista; typedef Factura *fact; typedef ListaDatosCliente *ListaCliente; //PROTOTIPOS DE FUNCIONES int validaCedula(); void menuCompra(int opcion); void compra(Lista &, Lista &, int); void mostrarProductos(Lista); void inicializarProductos(Lista &, char *, float, int, int); int validarProducto(Lista &, char *, int); void validarPrecio(Lista &, Lista); void validarStock(Lista &); void facturar(Lista &, fact &); void ingresoDatos(fact &, Lista &); void nuevaCompra(Lista &); void gotoxy(int x, int y); void barraCarga(); void seleccionarProducto(Lista lista); int menuTeclas(Lista &); void backgroundcolor(int color); void guardar(ListaCliente &listaCliente, fact &factura, char *archivo, int contador); bool esNumerico(string); int validarIngresoNumeros(char *); char *validarCaracteres(char *); int menuDireccion(); void modificarListaCompra(Lista &, Lista &, Lista &); void inicio(); void generarQr(char *); static void generarQrBasico(char dato1[]); static void printQr(const uint8_t qrcode[]); int main() { char nombreArchivo[12] = "factura.txt"; int i = 1, j = 0, contador = 0; char opcion; char *lista[vabTam] = { "Sprite 200ml","Coca-Cola","ChocoWonka","Caramelos", "V220 bebida","Nueces 1kg","Pretzels","Chocolate", "Te Verde","Queso Fresco","Frutaris","Harina 1kg", "Helado 1L","Nescafe","Doritos","Powerade","Pilsener 1L", "Yogurt 1L","Colcafe","Atun Real"}; float precios[vabTam] = { 1.00,1.00,2.30,2.4,2.90,3.00,2.00,1.50,1.50,2.30,0.25,2.00,2.00,1.75,1.00,2.30,2.4,2.90,3.00,2.00 }; int stock[vabTam] = { 5,5,2,2,2,6,5,6,7,8,1,1,1,1,1,2,6,5,6,7 }; Lista listaCompra, lisProductos, lisAuxiliar; ListaCliente listaCliente; fact factura; factura = new (struct Factura); listaCliente = new ListaDatosCliente(); listaCompra = NULL; lisProductos = NULL; lisAuxiliar = NULL; listaCliente = NULL; //Inicializa los productos disponibles do { inicializarProductos(lisProductos, lista[j], precios[j], stock[j], j); inicializarProductos(lisAuxiliar, lista[j], precios[j], stock[j], j); j++; } while (j<vabTam); inicio(); barraCarga(); //Muestra el menu hasta que se elija "Salir". do { menuCompra(i); while ((opcion = getch()) != 13) { if (opcion == 72) { if (i == 1) { i = 6; } else { i--; } } if (opcion == 80) { if (i == 6) { i = 1; } else { i++; } } menuCompra(i); } switch (i) { case 1: if (lisProductos == NULL) { printf("No puede comprar mas productos"); i = 6; exit(1); } else { int opc; system("cls"); opc = menuTeclas(lisProductos); compra(listaCompra, lisProductos, opc); validarStock(lisProductos); } system("pause"); break; case 2: system("cls"); modificarListaCompra(listaCompra, lisProductos, lisAuxiliar); printf("\n\n"); mostrarProductos(listaCompra); system("pause"); break; case 3: system("cls"); if (listaCompra != NULL) { contador++; printf("\n\n\tFACTURACION\n\n"); ingresoDatos(factura, listaCompra); nuevaCompra(listaCompra); guardar(listaCliente, factura, nombreArchivo, contador); printf("\n\n SU COMPRA HA FINALIZADO CON EXITO\!\n\n"); system("pause"); system("cls"); barraCarga(); } else { printf("\n\n\n\t*******************************************"); printf("\n\n\t No ha seleccionado ningun producto\n"); printf("\n\n\t*******************************************\n"); Sleep(700); //system("pause"); } break; case 4: system("cls"); printf("Abriendo archivo ayuda...\n"); ShellExecute(NULL, L"open", L"C://Users/Administrador1/Desktop/proyecto/ManualdeUsuario.chm", NULL, NULL, SW_SHOWNORMAL); system("pause"); break; case 5: system("cls"); printf("SOBRE NOSOTROS\n\n"); /* char lista[300] = ""; strcpy(lista, "https://scontent.fuio7-1.fna.fbcdn.net/v/t34.0-12/24203566_2162297370462812_645498074_n.jpg?oh=5ba57cf8ae52e28be8fcec13a863d333&oe=5A213C96");*/ //generarQr(lista); system("pause"); break; case 6: system("cls"); printf("\n\n\t*******************************************\n"); printf("\t\tGracias por usar este software!\n"); printf("\n\t*******************************************\n"); system("Start C:/Users/Administrador1/Desktop/proyecto/ProyectoEstructuras/ProyectoEstructuras/PDFg.jar"); system("pause");//Sleep(2000); break; default:; } } while (i != 6); return 0; } void backgroundcolor(int color) { SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), color); } void inicio() { system("color 0A"); gotoxy(0, 0); backgroundcolor(7); while (!kbhit()) { gotoxy(20, 28); printf("||"); gotoxy(20, 29); printf("||"); gotoxy(20, 30); printf("||"); gotoxy(20, 31); printf("||"); gotoxy(20, 32); printf("||"); gotoxy(20, 33); printf("||"); gotoxy(20, 34); printf("||"); gotoxy(20, 35); printf("||"); gotoxy(20, 36); printf("||"); gotoxy(20, 37); printf("||"); gotoxy(20, 38); printf("||"); gotoxy(20, 39); printf("||"); gotoxy(78, 28); printf("||"); gotoxy(78, 29); printf("||"); gotoxy(78, 30); printf("||"); gotoxy(78, 31); printf("||"); gotoxy(78, 32); printf("||"); gotoxy(78, 33); printf("||"); gotoxy(78, 34); printf("||"); gotoxy(78, 35); printf("||"); gotoxy(78, 36); printf("||"); gotoxy(78, 37); printf("||"); gotoxy(78, 38); printf("||"); gotoxy(78, 39); printf("||"); gotoxy(22, 26); printf("********************************************************"); gotoxy(29, 28); printf("UNIVERSIDAD DE LAS FUERZAS ARMADAS ESPE"); gotoxy(38, 30); printf("ESTRUCTURA DE DATOS"); gotoxy(25, 32); printf("INTEGRANTES:"); gotoxy(38, 34); printf("Carvajal Abigail"); gotoxy(38, 35); printf("Corral Daniel"); gotoxy(40, 37); printf("TEMA PROYECTO:"); gotoxy(25, 39); printf("TIENDA VIRTUAL CON LISTAS DOBLEMENTE ENLAZADAS"); gotoxy(22, 41); printf("********************************************************"); gotoxy(25, 42); printf("\n"); gotoxy(25, 43); printf("\n"); gotoxy(25, 44); printf("\n"); gotoxy(25, 45); printf("\n"); gotoxy(25, 46); printf("\n"); gotoxy(25, 47); printf("\n"); gotoxy(25, 48); printf("\n"); gotoxy(25, 49); printf("\n"); gotoxy(25, 50); printf("\n"); gotoxy(25, 51); printf("\n"); } system("cls"); } int menuTeclas(Lista &lista) { system("color 07"); system("cls"); Lista aux, aux1; aux = lista; aux1 = lista; int cont = 0; while (aux != NULL) { cont++; aux = aux->sig; } int men[50] = {}; string menNombre[50] = {}; float precio[50] = {}; for (int i = 0; i<cont; i++) { men[i] = aux1->producto.stock; menNombre[i] = aux1->producto.nombre; precio[i] = aux1->producto.precio; aux1 = aux1->sig; } int cursor = 0; char tecla; for (;;) { system("cls"); backgroundcolor(7); printf("\n\n\t PRODUCTOS DISPONIBLES\n\n"); printf(" Producto\t\t Precio\t Stock\n"); printf("---------------------------------------------------------\n"); for (int i = 0; i < cont; i++) { if (cursor == i) { backgroundcolor(160); printf(" %s\t\t %.2f\t\t %d\n", menNombre[i].c_str(), precio[i], men[i]); backgroundcolor(7); } else { backgroundcolor(7); printf(" %s\t\t %.2f\t\t %d\n", menNombre[i].c_str(), precio[i], men[i]); } } for (;;) { tecla = _getch(); if (tecla == 80) { cursor++; if (cursor == cont) { cursor = 0; } break; } if (tecla == 72) { cursor--; if (cursor == -1) { cursor = cont; } break; } if (tecla == 13) { cursor += 1; /*Dependiendo de donde el cursor de enter entra en el switch*/ return cursor; } } }while (tecla != 13); //printf("%d",cursor); system("pause"); return cursor; } //Esta función permite realizar nuevas compras/vacia la lista de compras void nuevaCompra(Lista &lista) { if (lista != NULL) { Lista punteroAuxiliar; while (lista != NULL) { punteroAuxiliar = lista->sig; delete(lista); lista = punteroAuxiliar; } } } //Ingresa datos de Usuario... aqui se mete generacion de QR void ingresoDatos(fact &factura, Lista &lisProductos) { fact aux = new(struct Factura); char nombre[50], apellido[50]; int cedula; //Nombre strcpy(nombre, validarCaracteres("Ingrese su Nombre: ")); strcpy(aux->datos.nombre, nombre); //Apellido strcpy(apellido, validarCaracteres("Ingrese su Apellido: ")); strcpy(aux->datos.apellido, apellido); //Cedula fflush(stdin); cedula = validaCedula(); aux->datos.cedula = cedula; factura = aux; facturar(lisProductos, aux); } char *validarCaracteres(char *mensaje) { int i = 0; bool esCadena = false; char cadena[50]; do { i = 0; fflush(stdin); printf("%s", mensaje); scanf("%s", &cadena); while (cadena[i] != NULL) { if (cadena[i] > 64 && cadena[i] < 91) { esCadena = true; } if (cadena[i] > 96 && cadena[i] < 123) { esCadena = true; } i++; } if (esCadena == false) printf("Ingreso no valido.\n"); } while (esCadena == false); return cadena; } void facturar(Lista &lisProductos, fact &factura) { float total = 0; Lista aux = new(struct ListaProducto); aux = lisProductos; char espacio[2] = "\t"; char fin[30] = ""; while (aux != NULL) { aux->producto.pUnidad += aux->producto.precio;//*aux->producto.stock; total += aux->producto.precio;//*aux->producto.stock; aux = aux->sig; } factura->total = total; system("cls"); printf("\n\t|**********************************************************|"); printf("\n\t|\t\t\t FACTURA |"); printf("\n\t| Usuario: %s %s ", factura->datos.nombre, factura->datos.apellido); printf("\n\t| ID: %d ", factura->datos.cedula); printf("\n\t|--------------------------------------------------------- |\n"); printf("\n\t| Producto\t\t Precio\t Cantidad |\n"); printf("\t|--------------------------------------------------------- |\n"); mostrarProductos(lisProductos); printf("\t \t\t Total = %.2f\n", factura->total); printf("\t|--------------------------------------------------------- |\n"); strcat(fin , factura->datos.nombre); strcat(fin, espacio); strcat(fin, factura->datos.apellido); generarQr(fin); } //PARA INICIALIZAR LOS PRODUCTOS DISPONIBLES void inicializarProductos(Lista &lisProductos, char *lista, float precios, int stock, int i) { if (lisProductos == NULL) { Lista aux, aux1; aux = new (struct ListaProducto); strcpy(aux->producto.nombre, lista); aux->producto.precio = precios; aux->producto.stock = stock; aux->sig = aux->ant = NULL; lisProductos = aux; } if (lisProductos != NULL) { Lista aux, aux1; aux = new (struct ListaProducto); strcpy(aux->producto.nombre, lista); aux->producto.precio = precios; aux->producto.stock = stock; aux1 = lisProductos; aux->sig = aux1; aux->ant = aux1->ant; aux1->ant = aux; lisProductos = aux; } } void mostrarProductos(Lista lista) { if (lista == NULL) { printf("No existen elementos en la lista. \n"); } else { int i = 1; while (lista != NULL) { //SetConsoleTextAttribute ( salida, FOREGROUND_GREEN | BACKGROUND_BLUE ); printf("\t| %s\t\t %.2f\t\t %d |\n", lista->producto.nombre, lista->producto.precio, lista->producto.stock); //SetConsoleTextAttribute ( salida, coloresOriginales); printf("\t|--------------------------------------------------------- |\n"); lista = lista->sig; i++; } printf("\n"); } } //MENU CON CURSORES void menuCompra(int opcion) { HANDLE salida = GetStdHandle(STD_OUTPUT_HANDLE); WORD coloresOriginales; CONSOLE_SCREEN_BUFFER_INFO csbiInfo; GetConsoleScreenBufferInfo(salida, &csbiInfo); coloresOriginales = csbiInfo.wAttributes; switch (opcion) { case 1: system("cls"); printf("\t\t----------------------\n"); printf("\t\t CYBER-MARKET\n"); printf("\t\t----------------------\n\n"); SetConsoleTextAttribute(salida, FOREGROUND_GREEN | BACKGROUND_BLUE); printf("\t Iniciar compra \n"); SetConsoleTextAttribute(salida, coloresOriginales); printf("\t Eliminar de lista de productos \n"); printf("\t Finalizar Compra \n"); printf("\t Ayuda\n"); printf("\t Sobre Nosotros \n"); printf("\t Salir. \n\n"); break; case 2: system("cls"); printf("\t\t----------------------\n"); printf("\t\t CYBER-MARKET\n"); printf("\t\t----------------------\n\n"); printf("\t Iniciar compra. \n"); SetConsoleTextAttribute(salida, FOREGROUND_GREEN | BACKGROUND_BLUE); printf("\t Eliminar de lista de productos \n"); SetConsoleTextAttribute(salida, coloresOriginales); printf("\t Finalizar Compra \n"); printf("\t Ayuda\n"); printf("\t Sobre Nosotros \n"); printf("\t Salir. \n\n"); break; case 3: system("cls"); printf("\t\t----------------------\n"); printf("\t\t CYBER-MARKET\n"); printf("\t\t----------------------\n\n"); printf("\t Iniciar compra \n"); printf("\t Eliminar de lista de productos \n"); SetConsoleTextAttribute(salida, FOREGROUND_GREEN | BACKGROUND_BLUE); printf("\t Finalizar Compra \n"); SetConsoleTextAttribute(salida, coloresOriginales); printf("\t Ayuda\n"); printf("\t Sobre Nosotros \n"); printf("\t Salir. \n\n"); break; case 4: system("cls"); printf("\t\t----------------------\n"); printf("\t\t CYBER-MARKET\n"); printf("\t\t----------------------\n\n"); printf("\t Iniciar compra \n"); printf("\t Eliminar de lista de productos \n"); printf("\t Finalizar Compra \n"); SetConsoleTextAttribute(salida, FOREGROUND_GREEN | BACKGROUND_BLUE); printf("\t Ayuda\n"); SetConsoleTextAttribute(salida, coloresOriginales); printf("\t Sobre Nosotros \n"); printf("\t Salir. \n\n"); break; case 5: system("cls"); printf("\t\t----------------------\n"); printf("\t\t CYBER-MARKET\n"); printf("\t\t----------------------\n\n"); printf("\t Iniciar compra \n"); printf("\t Eliminar de lista de productos \n"); printf("\t Finalizar Compra \n"); printf("\t Ayuda\n"); SetConsoleTextAttribute(salida, FOREGROUND_GREEN | BACKGROUND_BLUE); printf("\t Sobre Nosotros \n"); SetConsoleTextAttribute(salida, coloresOriginales); printf("\t Salir. \n\n"); break; case 6: system("cls"); printf("\t\t----------------------\n"); printf("\t\t CYBER-MARKET\n"); printf("\t\t----------------------\n\n"); printf("\t Iniciar compra \n"); printf("\t Eliminar de lista de productos \n"); printf("\t Finalizar Compra \n"); printf("\t Ayuda\n"); printf("\t Sobre Nosotros \n"); SetConsoleTextAttribute(salida, FOREGROUND_GREEN | BACKGROUND_BLUE); printf("\t Salir. \n\n"); SetConsoleTextAttribute(salida, coloresOriginales); break; default:; } } void compra(Lista &listaCompra, Lista &lisProductos, int opc) { printf("\n\n************************ \n"); printf("\nEl producto escogido es: \n"); int i = 0, cantidad; float total = 0; Lista auxprod = new (struct ListaProducto); auxprod = lisProductos; for (i = 0; i<opc - 1; i++) { auxprod = auxprod->sig; } printf("%s \n", auxprod->producto.nombre); do { cantidad = validarIngresoNumeros("\nIngrese la cantidad del producto que desea: "); if (cantidad > auxprod->producto.stock) printf("No disponemos de esa cantidad de productos.\n"); } while (cantidad < 0 || cantidad > auxprod->producto.stock); auxprod->producto.stock = auxprod->producto.stock - cantidad; //Se añade el producto seleccionado a la lista de compras if (listaCompra != NULL) { Lista aux, aux1; aux = new (struct ListaProducto); if (validarProducto(listaCompra, auxprod->producto.nombre, cantidad) != 0) { strcpy(aux->producto.nombre, auxprod->producto.nombre); aux->producto.stock = cantidad; //aux->producto.precio = auxprod->producto.precio * cantidad; aux1 = listaCompra; aux->sig = aux1; aux->ant = aux1->ant; aux1->ant = aux; listaCompra = aux; } } else { Lista aux, aux1; aux = new (struct ListaProducto); strcpy(aux->producto.nombre, auxprod->producto.nombre); aux->producto.stock = cantidad; //aux->producto.precio = auxprod->producto.precio; aux->sig = aux->ant = NULL; listaCompra = aux; } validarPrecio(listaCompra, lisProductos); //Muestra la lista de compras antes de finalizar system("cls"); printf("\n\tLa lista de compras es: \n\n"); printf("\t Producto\t\t Subtotal\t Cantidad\n"); printf("\t---------------------------------------------------------\n"); mostrarProductos(listaCompra); auxprod = listaCompra; while (auxprod != NULL) { total = total + auxprod->producto.precio; auxprod = auxprod->sig; } printf("\t\t\t Total = %.2f\n\n", total); } int validarProducto(Lista &lista, char *nombreproducto, int cantidad) { int band = 1; Lista aux = new(ListaProducto); aux = lista; while (aux != NULL) { band = strcmp(nombreproducto, aux->producto.nombre); if (band == 0) { aux->producto.stock = aux->producto.stock + cantidad; break; } aux = aux->sig; } return (band); } void barraCarga() { printf("\n \n\t\tPresione cualquier tecla para iniciar compra \n"); getch(); system("cls"); int x, y, i, z, a; gotoxy(25, 10); printf("CARGANDO"); for (i = 10; i<50; i++) { gotoxy(i, 13); printf("%c", 177); gotoxy(36, 10); printf("%d %c", i * 2, '%'); for (x = 50; x<70; x++) { for (y = 1; y<70; y++) { gotoxy(y, 24); } } } } void gotoxy(int x, int y) { HANDLE hcon; hcon = GetStdHandle(STD_OUTPUT_HANDLE); COORD dwPos; dwPos.X = x; dwPos.Y = y; SetConsoleCursorPosition(hcon, dwPos); } void validarStock(Lista &lista) { Lista aux = new(ListaProducto); aux = lista; if (aux != NULL) { while (aux != NULL) { if (aux->producto.stock == 0) { if (aux->ant == NULL&&aux->sig == NULL) { lista = NULL; break; } if (aux->ant == NULL) { aux->sig->ant = NULL; lista = aux->sig; } if (aux->sig == NULL) { aux->ant->sig = NULL; } if (aux->ant != NULL && aux->sig != NULL) { aux->ant->sig = aux->sig; aux->sig->ant = aux->ant; } } aux = aux->sig; } } } void guardar(ListaCliente &listacliente, fact &factura, char *archivo, int contador) { FILE *ptr; char nombre[30] = {""}; ptr = fopen(archivo, "a"); //REALIZO LA APERTURA DEL ARCHIVO if (ptr == NULL) { printf("ERROR.\n"); } else { strcpy(nombre, factura->datos.nombre); //fputs(nombre,ptr); fprintf(ptr, "Nombre: %s Apellido: %s Cedula: %d \n", nombre, factura->datos.apellido, factura->datos.cedula); fclose(ptr); } } //funcion para determinar el precio de la lisa de compras void validarPrecio(Lista &listaCompra, Lista lisProductos) { Lista aux = new(ListaProducto); int band = 1; aux = listaCompra; while (aux != NULL) { while (lisProductos != NULL) { band = strcmp(lisProductos->producto.nombre, aux->producto.nombre); if (band == 0) { aux->producto.precio = lisProductos->producto.precio * aux->producto.stock; } lisProductos = lisProductos->sig; } aux = aux->sig; } } int validarIngresoNumeros(char *mensaje) { string linea; int numero; bool repite = true; do { //fflush(stdin); printf("%s", mensaje); fflush(stdin); getline(cin, linea); if (esNumerico(linea)) { repite = false; } else { printf("Ingreso no valido.\n"); } } while (repite); numero = atoi(linea.c_str()); //cin.get(); return numero; } bool esNumerico(string linea) { bool b = true; int longitud = linea.size(); if (longitud == 0) //caundo el usuario pulsa enter { b = false; } else if (longitud == 1 && !isdigit(linea[0])) { b = false; } else { int i; if (linea[0] == '+' || linea[0] == '-') i = 1; else i = 0; while (i<longitud) { if (!isdigit(linea[i])) { b = false; break; } i++; } } return b; } int menuDireccion() { int cursor = 0; char tecla; char *opc[2] = { "SI","NO" }; for (;;) { system("cls"); printf("\n\n********************************************************\n"); printf("\n\nEsta seguro que desea eliminar el producto seleccionado?\n\n"); backgroundcolor(7); for (int i = 0; i < 2; i++) { if (cursor == i) { backgroundcolor(160); printf(" %s\t",opc[i]); backgroundcolor(7); } else { backgroundcolor(7); printf(" %s\t",opc[i] ); } } for (;;) { tecla = _getch(); if (tecla == 75) { cursor++; if (cursor == 2) { cursor = 0; } break; } if (tecla == 77) { cursor--; if (cursor == -1) { cursor = 2; } break; } if (tecla == 13) { cursor += 1; //printf("cursor = %d", cursor); /*Dependiendo de donde el cursor de enter entra en el switch*/ return cursor; } } }while (tecla != 13); return cursor; } void modificarListaCompra(Lista &listaCompra, Lista &lisProductos, Lista &listAuxiliar) { int opc, op; Lista aux2 = new (struct ListaProducto); Lista auxprod = new (struct ListaProducto); auxprod = listaCompra; aux2 = listAuxiliar; if (listaCompra == NULL) { printf("No existen productos disponibles.\n"); } else { printf(" ELIMINAR DE LA LISTA DE COMPRAS \n\n"); printf("Escoja que producto desea modificar: \n"); opc = menuTeclas(listaCompra); op = menuDireccion(); //Elimnar el producto de la lsita de compras y aumentar en la lista de productos if (op == 1) { for (int i = 0; i<opc - 1; i++) auxprod = auxprod->sig; //Se añade el producto selecionado a la lista de productos if (lisProductos != NULL) { Lista aux, aux1; aux = new (struct ListaProducto); if (validarProducto(lisProductos, auxprod->producto.nombre, auxprod->producto.stock) != 0) { strcpy(aux->producto.nombre, auxprod->producto.nombre); aux->producto.stock = auxprod->producto.stock; aux->producto.precio = auxprod->producto.precio / aux->producto.stock; aux1 = lisProductos; aux->sig = aux1; aux->ant = aux1->ant; aux1->ant = aux; lisProductos = aux; } } else { Lista aux, aux1; aux = new (struct ListaProducto); strcpy(aux->producto.nombre, auxprod->producto.nombre); aux->producto.stock = auxprod->producto.stock; aux->producto.precio = auxprod->producto.precio / aux->producto.stock; aux->sig = aux->ant = NULL; lisProductos = aux; } //Se elimina el producto de la lista de compras if (auxprod->sig == NULL && auxprod->ant == NULL) { //printf("lista nula"); nuevaCompra(listaCompra); } else if (auxprod->ant == NULL) { //printf("1"); auxprod->sig->ant = NULL; listaCompra = auxprod->sig; } else if (auxprod->sig == NULL) { //printf("2"); auxprod->ant->sig = NULL; } else if (auxprod->ant != NULL && auxprod->sig != NULL) { //printf("3"); auxprod->ant->sig = auxprod->sig; auxprod->sig->ant = auxprod->ant; } } //Devolver una cantidad de productos if (op == 2) { printf("no"); system("PAUSE"); } } } int validaCedula() { //inicializacion de variables int A[Tam], num, j, i, coc, pares, impares, digito, suma, sumtotal, res; char opc; int comprueba = 0, cedula; do { i = 10; pares = 0; suma = 0; impares = 0; digito = 0; sumtotal = 0; num = validarIngresoNumeros("\nIngrese el numero de cedula:\t"); //scanf("%d",&num); while ((num <= 1000000000) || (num >= 3000000000)) { printf("Numero incorrecto. Ingrese cedula de nuevo:\t"); scanf("%d", &num); } //Asignación de cada numero a una posición cedula = num; do { coc = num / 10; A[i] = num % 10; i--; num = coc; } while (coc != 0); pares += (A[2] + A[4] + A[6] + A[8]); //printf("pares %d\n",pares); for (j = 1; j<10; j++) { A[j] *= 2; if (j % 2 == 0) A[j] /= 2; else { if (A[j]>9) suma += A[j] - 9; else digito += A[j]; } } impares = suma + digito; //printf("impares %d\n",impares); sumtotal += impares + pares; res = 10 - (sumtotal % 10); A[1] *= 10; A[0] = (A[1] / 2 + A[2]); //printf("%d",A[0]); if (res == 10) res = 0; if (res == A[10] && A[0] <= 24) { printf("\n\t\tLa cedula es valida\n\n"); comprueba = 1; } else { printf("\t\tLa cedula es invalida\n\n"); comprueba = 0; } } while ((comprueba == 0)); return cedula; } void generarQrBasico(char dato1[]) { char *dato = dato1; // User-supplied text enum qrcodegen_Ecc errCorLvl = qrcodegen_Ecc_LOW; // Error correction level // Make and print the QR Code symbol uint8_t qrcode[qrcodegen_BUFFER_LEN_MAX]; uint8_t tempBuffer[qrcodegen_BUFFER_LEN_MAX]; bool ok = qrcodegen_encodeText(dato, tempBuffer, qrcode, errCorLvl, qrcodegen_VERSION_MIN, qrcodegen_VERSION_MAX, qrcodegen_Mask_AUTO, true); if (ok) printQr(qrcode); } static void printQr(const uint8_t qrcode[]) { int size = qrcodegen_getSize(qrcode); int border = 4; for (int y = -border; y < size + border; y++) { for (int x = -border; x < size + border; x++) { fputs((qrcodegen_getModule(qrcode, x, y) ? "\333\333" : " "), stdout); } fputs("\n", stdout); } } static void generarQr(char *mensaje) { printf("GENERADOR DE QR\n"); generarQrBasico(mensaje); system("pause"); }
ce00f8ca5290e109c1ebe991232b65040ba07b06
c4050611b5cc5f8b58ecdcb6c78b9cbe294c3da1
/source/math/math.hpp
ee2d1633ed162a99cee85946d5df51c9a4805d09
[]
no_license
RenatoUtsch/boids
138ec06718fb0d62ddbfcb6fe34e0f9945abd07c
b23af256d2c7b847d2c63fe35df13b961a33f117
refs/heads/master
2021-01-20T11:14:16.350095
2014-11-30T21:20:47
2014-11-30T21:20:47
27,350,294
3
1
null
null
null
null
UTF-8
C++
false
false
1,833
hpp
/* * Math library intended for computer graphics, animation, physics and games * (but not restricted to it). * * Copyright (c) 2014 Renato Utsch <[email protected]> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #ifndef MATH_MATH_HPP #define MATH_MATH_HPP /** * Proper inclusion of the standard math library and definition of additional * types in case they are missing. * Please use this header instead of including <cmath>. **/ #include <cmath> #ifndef M_PI #define M_PI 3.14159265358979323846 #endif // !M_PI /** * Converts from degrees to radians. **/ inline double toRads(double degrees) { return degrees * (M_PI / 180.0); } /** * Converts from radians to degrees. **/ inline double toDegrees(double rads) { return rads * (180.0 / M_PI); } #endif // !MATH_MATH_HPP
4dadd57910714d41bb996d845225e7a9767e97e7
d80ec9a928ff228cc99f8112254b6c9b449e097d
/Game/main.cpp
c47857b47e3d03c04bec06f7ff9c68d651de4e5b
[]
no_license
The-Team-7/The-KU-Journey
47a371dca693d3ecae779864ce666a7b9ea5925d
b8a3aa5ad85f414c1363d3afa7c8d8445fc2e926
refs/heads/master
2020-03-20T21:43:56.470370
2018-07-04T02:21:12
2018-07-04T02:21:12
137,756,919
0
1
null
null
null
null
UTF-8
C++
false
false
139
cpp
#include<SFML/Graphics.hpp> #include"Game.h" #include "DEFINITIONS.h" int main() { sg::Game(1920, 1080, "The KU Journey"); return 0; }
fdde0689ac5297d94b8119525d437f1b622eee3e
d6b4bdf418ae6ab89b721a79f198de812311c783
/tem/include/tencentcloud/tem/v20201221/model/CosToken.h
c66f25d2b462bf1084b142caf574e1203c653470
[ "Apache-2.0" ]
permissive
TencentCloud/tencentcloud-sdk-cpp-intl-en
d0781d461e84eb81775c2145bacae13084561c15
d403a6b1cf3456322bbdfb462b63e77b1e71f3dc
refs/heads/master
2023-08-21T12:29:54.125071
2023-08-21T01:12:39
2023-08-21T01:12:39
277,769,407
2
0
null
null
null
null
UTF-8
C++
false
false
10,262
h
/* * Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. 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. */ #ifndef TENCENTCLOUD_TEM_V20201221_MODEL_COSTOKEN_H_ #define TENCENTCLOUD_TEM_V20201221_MODEL_COSTOKEN_H_ #include <string> #include <vector> #include <map> #include <tencentcloud/core/utils/rapidjson/document.h> #include <tencentcloud/core/utils/rapidjson/writer.h> #include <tencentcloud/core/utils/rapidjson/stringbuffer.h> #include <tencentcloud/core/AbstractModel.h> namespace TencentCloud { namespace Tem { namespace V20201221 { namespace Model { /** * Cos token */ class CosToken : public AbstractModel { public: CosToken(); ~CosToken() = default; void ToJsonObject(rapidjson::Value &value, rapidjson::Document::AllocatorType& allocator) const; CoreInternalOutcome Deserialize(const rapidjson::Value &value); /** * 获取Unique request ID * @return RequestId Unique request ID * */ std::string GetRequestId() const; /** * 设置Unique request ID * @param _requestId Unique request ID * */ void SetRequestId(const std::string& _requestId); /** * 判断参数 RequestId 是否已赋值 * @return RequestId 是否已赋值 * */ bool RequestIdHasBeenSet() const; /** * 获取Bucket name * @return Bucket Bucket name * */ std::string GetBucket() const; /** * 设置Bucket name * @param _bucket Bucket name * */ void SetBucket(const std::string& _bucket); /** * 判断参数 Bucket 是否已赋值 * @return Bucket 是否已赋值 * */ bool BucketHasBeenSet() const; /** * 获取Bucket region * @return Region Bucket region * */ std::string GetRegion() const; /** * 设置Bucket region * @param _region Bucket region * */ void SetRegion(const std::string& _region); /** * 判断参数 Region 是否已赋值 * @return Region 是否已赋值 * */ bool RegionHasBeenSet() const; /** * 获取`SecretId` of temporary key * @return TmpSecretId `SecretId` of temporary key * */ std::string GetTmpSecretId() const; /** * 设置`SecretId` of temporary key * @param _tmpSecretId `SecretId` of temporary key * */ void SetTmpSecretId(const std::string& _tmpSecretId); /** * 判断参数 TmpSecretId 是否已赋值 * @return TmpSecretId 是否已赋值 * */ bool TmpSecretIdHasBeenSet() const; /** * 获取`SecretKey` of temporary key * @return TmpSecretKey `SecretKey` of temporary key * */ std::string GetTmpSecretKey() const; /** * 设置`SecretKey` of temporary key * @param _tmpSecretKey `SecretKey` of temporary key * */ void SetTmpSecretKey(const std::string& _tmpSecretKey); /** * 判断参数 TmpSecretKey 是否已赋值 * @return TmpSecretKey 是否已赋值 * */ bool TmpSecretKeyHasBeenSet() const; /** * 获取`sessionToken` of temporary key * @return SessionToken `sessionToken` of temporary key * */ std::string GetSessionToken() const; /** * 设置`sessionToken` of temporary key * @param _sessionToken `sessionToken` of temporary key * */ void SetSessionToken(const std::string& _sessionToken); /** * 判断参数 SessionToken 是否已赋值 * @return SessionToken 是否已赋值 * */ bool SessionTokenHasBeenSet() const; /** * 获取`StartTime` of temporary key acquisition * @return StartTime `StartTime` of temporary key acquisition * */ std::string GetStartTime() const; /** * 设置`StartTime` of temporary key acquisition * @param _startTime `StartTime` of temporary key acquisition * */ void SetStartTime(const std::string& _startTime); /** * 判断参数 StartTime 是否已赋值 * @return StartTime 是否已赋值 * */ bool StartTimeHasBeenSet() const; /** * 获取`ExpiredTime` of temporary key * @return ExpiredTime `ExpiredTime` of temporary key * */ std::string GetExpiredTime() const; /** * 设置`ExpiredTime` of temporary key * @param _expiredTime `ExpiredTime` of temporary key * */ void SetExpiredTime(const std::string& _expiredTime); /** * 判断参数 ExpiredTime 是否已赋值 * @return ExpiredTime 是否已赋值 * */ bool ExpiredTimeHasBeenSet() const; /** * 获取Full package path * @return FullPath Full package path * */ std::string GetFullPath() const; /** * 设置Full package path * @param _fullPath Full package path * */ void SetFullPath(const std::string& _fullPath); /** * 判断参数 FullPath 是否已赋值 * @return FullPath 是否已赋值 * */ bool FullPathHasBeenSet() const; private: /** * Unique request ID */ std::string m_requestId; bool m_requestIdHasBeenSet; /** * Bucket name */ std::string m_bucket; bool m_bucketHasBeenSet; /** * Bucket region */ std::string m_region; bool m_regionHasBeenSet; /** * `SecretId` of temporary key */ std::string m_tmpSecretId; bool m_tmpSecretIdHasBeenSet; /** * `SecretKey` of temporary key */ std::string m_tmpSecretKey; bool m_tmpSecretKeyHasBeenSet; /** * `sessionToken` of temporary key */ std::string m_sessionToken; bool m_sessionTokenHasBeenSet; /** * `StartTime` of temporary key acquisition */ std::string m_startTime; bool m_startTimeHasBeenSet; /** * `ExpiredTime` of temporary key */ std::string m_expiredTime; bool m_expiredTimeHasBeenSet; /** * Full package path */ std::string m_fullPath; bool m_fullPathHasBeenSet; }; } } } } #endif // !TENCENTCLOUD_TEM_V20201221_MODEL_COSTOKEN_H_