text
stringlengths 8
6.88M
|
|---|
// C++ for the Windows Runtime vv1.0.170303.6
// Copyright (c) 2017 Microsoft Corporation. All rights reserved.
#pragma once
#include "Windows.Devices.Bluetooth.Rfcomm.1.h"
#include "Windows.Foundation.1.h"
WINRT_EXPORT namespace winrt {
namespace ABI::Windows::Foundation::Collections {
#ifndef WINRT_GENERIC_97df6b82_d15c_597e_ba69_492207a1c108
#define WINRT_GENERIC_97df6b82_d15c_597e_ba69_492207a1c108
template <> struct __declspec(uuid("97df6b82-d15c-597e-ba69-492207a1c108")) __declspec(novtable) IVectorView<Windows::Devices::Bluetooth::Rfcomm::RfcommDeviceService> : impl_IVectorView<Windows::Devices::Bluetooth::Rfcomm::RfcommDeviceService> {};
#endif
}
namespace ABI::Windows::Foundation {
#ifndef WINRT_GENERIC_c00bc2f2_a7f8_5f3f_80d1_2808ef6bca10
#define WINRT_GENERIC_c00bc2f2_a7f8_5f3f_80d1_2808ef6bca10
template <> struct __declspec(uuid("c00bc2f2-a7f8-5f3f-80d1-2808ef6bca10")) __declspec(novtable) IAsyncOperation<winrt::Windows::Devices::Enumeration::DeviceAccessStatus> : impl_IAsyncOperation<winrt::Windows::Devices::Enumeration::DeviceAccessStatus> {};
#endif
#ifndef WINRT_GENERIC_0df56bd7_c8f6_5c32_9644_aa0bcf28d78c
#define WINRT_GENERIC_0df56bd7_c8f6_5c32_9644_aa0bcf28d78c
template <> struct __declspec(uuid("0df56bd7-c8f6-5c32-9644-aa0bcf28d78c")) __declspec(novtable) IAsyncOperation<Windows::Devices::Bluetooth::Rfcomm::RfcommDeviceService> : impl_IAsyncOperation<Windows::Devices::Bluetooth::Rfcomm::RfcommDeviceService> {};
#endif
}
namespace ABI::Windows::Foundation::Collections {
#ifndef WINRT_GENERIC_57dc41e6_8b4d_5910_9703_d7c668436852
#define WINRT_GENERIC_57dc41e6_8b4d_5910_9703_d7c668436852
template <> struct __declspec(uuid("57dc41e6-8b4d-5910-9703-d7c668436852")) __declspec(novtable) IMapView<uint32_t, Windows::Storage::Streams::IBuffer> : impl_IMapView<uint32_t, Windows::Storage::Streams::IBuffer> {};
#endif
}
namespace ABI::Windows::Foundation {
#ifndef WINRT_GENERIC_fed44828_e232_554d_85d1_2f04d1322e69
#define WINRT_GENERIC_fed44828_e232_554d_85d1_2f04d1322e69
template <> struct __declspec(uuid("fed44828-e232-554d-85d1-2f04d1322e69")) __declspec(novtable) IAsyncOperation<Windows::Devices::Bluetooth::Rfcomm::RfcommServiceProvider> : impl_IAsyncOperation<Windows::Devices::Bluetooth::Rfcomm::RfcommServiceProvider> {};
#endif
}
namespace ABI::Windows::Foundation::Collections {
#ifndef WINRT_GENERIC_5d2591df_48c5_5734_9ef1_bd639b032007
#define WINRT_GENERIC_5d2591df_48c5_5734_9ef1_bd639b032007
template <> struct __declspec(uuid("5d2591df-48c5-5734-9ef1-bd639b032007")) __declspec(novtable) IMap<uint32_t, Windows::Storage::Streams::IBuffer> : impl_IMap<uint32_t, Windows::Storage::Streams::IBuffer> {};
#endif
#ifndef WINRT_GENERIC_75f127ec_2256_5b20_8b38_8ac3f3d11819
#define WINRT_GENERIC_75f127ec_2256_5b20_8b38_8ac3f3d11819
template <> struct __declspec(uuid("75f127ec-2256-5b20-8b38-8ac3f3d11819")) __declspec(novtable) IVector<Windows::Devices::Bluetooth::Rfcomm::RfcommDeviceService> : impl_IVector<Windows::Devices::Bluetooth::Rfcomm::RfcommDeviceService> {};
#endif
#ifndef WINRT_GENERIC_64ab0132_c64c_5a87_8113_613ef356924c
#define WINRT_GENERIC_64ab0132_c64c_5a87_8113_613ef356924c
template <> struct __declspec(uuid("64ab0132-c64c-5a87-8113-613ef356924c")) __declspec(novtable) IIterator<Windows::Devices::Bluetooth::Rfcomm::RfcommDeviceService> : impl_IIterator<Windows::Devices::Bluetooth::Rfcomm::RfcommDeviceService> {};
#endif
#ifndef WINRT_GENERIC_3378e9a6_f6e2_50ea_bfee_b8109631feca
#define WINRT_GENERIC_3378e9a6_f6e2_50ea_bfee_b8109631feca
template <> struct __declspec(uuid("3378e9a6-f6e2-50ea-bfee-b8109631feca")) __declspec(novtable) IIterable<Windows::Devices::Bluetooth::Rfcomm::RfcommDeviceService> : impl_IIterable<Windows::Devices::Bluetooth::Rfcomm::RfcommDeviceService> {};
#endif
}
namespace ABI::Windows::Foundation {
#ifndef WINRT_GENERIC_ee154d83_805b_53e8_8469_90715036d013
#define WINRT_GENERIC_ee154d83_805b_53e8_8469_90715036d013
template <> struct __declspec(uuid("ee154d83-805b-53e8-8469-90715036d013")) __declspec(novtable) AsyncOperationCompletedHandler<winrt::Windows::Devices::Enumeration::DeviceAccessStatus> : impl_AsyncOperationCompletedHandler<winrt::Windows::Devices::Enumeration::DeviceAccessStatus> {};
#endif
#ifndef WINRT_GENERIC_5c772518_442f_58ed_80cb_538d34b88295
#define WINRT_GENERIC_5c772518_442f_58ed_80cb_538d34b88295
template <> struct __declspec(uuid("5c772518-442f-58ed-80cb-538d34b88295")) __declspec(novtable) AsyncOperationCompletedHandler<Windows::Devices::Bluetooth::Rfcomm::RfcommDeviceService> : impl_AsyncOperationCompletedHandler<Windows::Devices::Bluetooth::Rfcomm::RfcommDeviceService> {};
#endif
}
namespace ABI::Windows::Foundation::Collections {
#ifndef WINRT_GENERIC_82a3a3b7_e04a_5395_8487_7f94f1508ce7
#define WINRT_GENERIC_82a3a3b7_e04a_5395_8487_7f94f1508ce7
template <> struct __declspec(uuid("82a3a3b7-e04a-5395-8487-7f94f1508ce7")) __declspec(novtable) IKeyValuePair<uint32_t, Windows::Storage::Streams::IBuffer> : impl_IKeyValuePair<uint32_t, Windows::Storage::Streams::IBuffer> {};
#endif
}
namespace ABI::Windows::Foundation {
#ifndef WINRT_GENERIC_446a7f50_8f2e_51f0_aebb_1bc3d192905f
#define WINRT_GENERIC_446a7f50_8f2e_51f0_aebb_1bc3d192905f
template <> struct __declspec(uuid("446a7f50-8f2e-51f0-aebb-1bc3d192905f")) __declspec(novtable) AsyncOperationCompletedHandler<Windows::Devices::Bluetooth::Rfcomm::RfcommServiceProvider> : impl_AsyncOperationCompletedHandler<Windows::Devices::Bluetooth::Rfcomm::RfcommServiceProvider> {};
#endif
#ifndef WINRT_GENERIC_d4904ded_bc1d_5933_aecf_e42c5d465bff
#define WINRT_GENERIC_d4904ded_bc1d_5933_aecf_e42c5d465bff
template <> struct __declspec(uuid("d4904ded-bc1d-5933-aecf-e42c5d465bff")) __declspec(novtable) IAsyncOperation<Windows::Foundation::Collections::IMapView<uint32_t, Windows::Storage::Streams::IBuffer>> : impl_IAsyncOperation<Windows::Foundation::Collections::IMapView<uint32_t, Windows::Storage::Streams::IBuffer>> {};
#endif
}
namespace ABI::Windows::Foundation::Collections {
#ifndef WINRT_GENERIC_a295fa0c_c99f_5109_8ab9_91534bb48c9b
#define WINRT_GENERIC_a295fa0c_c99f_5109_8ab9_91534bb48c9b
template <> struct __declspec(uuid("a295fa0c-c99f-5109-8ab9-91534bb48c9b")) __declspec(novtable) IIterator<Windows::Foundation::Collections::IKeyValuePair<uint32_t, Windows::Storage::Streams::IBuffer>> : impl_IIterator<Windows::Foundation::Collections::IKeyValuePair<uint32_t, Windows::Storage::Streams::IBuffer>> {};
#endif
#ifndef WINRT_GENERIC_4fe7fe23_22b1_528c_881d_a4eceaef0f11
#define WINRT_GENERIC_4fe7fe23_22b1_528c_881d_a4eceaef0f11
template <> struct __declspec(uuid("4fe7fe23-22b1-528c-881d-a4eceaef0f11")) __declspec(novtable) IIterable<Windows::Foundation::Collections::IKeyValuePair<uint32_t, Windows::Storage::Streams::IBuffer>> : impl_IIterable<Windows::Foundation::Collections::IKeyValuePair<uint32_t, Windows::Storage::Streams::IBuffer>> {};
#endif
}
namespace ABI::Windows::Foundation {
#ifndef WINRT_GENERIC_92c2e4d0_7c25_596b_9135_10d1472e6968
#define WINRT_GENERIC_92c2e4d0_7c25_596b_9135_10d1472e6968
template <> struct __declspec(uuid("92c2e4d0-7c25-596b-9135-10d1472e6968")) __declspec(novtable) AsyncOperationCompletedHandler<Windows::Foundation::Collections::IMapView<uint32_t, Windows::Storage::Streams::IBuffer>> : impl_AsyncOperationCompletedHandler<Windows::Foundation::Collections::IMapView<uint32_t, Windows::Storage::Streams::IBuffer>> {};
#endif
}
namespace Windows::Devices::Bluetooth::Rfcomm {
struct IRfcommDeviceService :
Windows::Foundation::IInspectable,
impl::consume<IRfcommDeviceService>
{
IRfcommDeviceService(std::nullptr_t = nullptr) noexcept {}
};
struct IRfcommDeviceService2 :
Windows::Foundation::IInspectable,
impl::consume<IRfcommDeviceService2>,
impl::require<IRfcommDeviceService2, Windows::Devices::Bluetooth::Rfcomm::IRfcommDeviceService>
{
IRfcommDeviceService2(std::nullptr_t = nullptr) noexcept {}
};
struct IRfcommDeviceService3 :
Windows::Foundation::IInspectable,
impl::consume<IRfcommDeviceService3>,
impl::require<IRfcommDeviceService3, Windows::Devices::Bluetooth::Rfcomm::IRfcommDeviceService, Windows::Devices::Bluetooth::Rfcomm::IRfcommDeviceService2>
{
IRfcommDeviceService3(std::nullptr_t = nullptr) noexcept {}
};
struct IRfcommDeviceServiceStatics :
Windows::Foundation::IInspectable,
impl::consume<IRfcommDeviceServiceStatics>
{
IRfcommDeviceServiceStatics(std::nullptr_t = nullptr) noexcept {}
};
struct IRfcommDeviceServiceStatics2 :
Windows::Foundation::IInspectable,
impl::consume<IRfcommDeviceServiceStatics2>,
impl::require<IRfcommDeviceServiceStatics2, Windows::Devices::Bluetooth::Rfcomm::IRfcommDeviceServiceStatics>
{
IRfcommDeviceServiceStatics2(std::nullptr_t = nullptr) noexcept {}
};
struct IRfcommDeviceServicesResult :
Windows::Foundation::IInspectable,
impl::consume<IRfcommDeviceServicesResult>
{
IRfcommDeviceServicesResult(std::nullptr_t = nullptr) noexcept {}
};
struct IRfcommServiceId :
Windows::Foundation::IInspectable,
impl::consume<IRfcommServiceId>
{
IRfcommServiceId(std::nullptr_t = nullptr) noexcept {}
};
struct IRfcommServiceIdStatics :
Windows::Foundation::IInspectable,
impl::consume<IRfcommServiceIdStatics>
{
IRfcommServiceIdStatics(std::nullptr_t = nullptr) noexcept {}
};
struct IRfcommServiceProvider :
Windows::Foundation::IInspectable,
impl::consume<IRfcommServiceProvider>
{
IRfcommServiceProvider(std::nullptr_t = nullptr) noexcept {}
};
struct IRfcommServiceProvider2 :
Windows::Foundation::IInspectable,
impl::consume<IRfcommServiceProvider2>,
impl::require<IRfcommServiceProvider2, Windows::Devices::Bluetooth::Rfcomm::IRfcommServiceProvider>
{
IRfcommServiceProvider2(std::nullptr_t = nullptr) noexcept {}
using impl_IRfcommServiceProvider::StartAdvertising;
using impl_IRfcommServiceProvider2::StartAdvertising;
};
struct IRfcommServiceProviderStatics :
Windows::Foundation::IInspectable,
impl::consume<IRfcommServiceProviderStatics>
{
IRfcommServiceProviderStatics(std::nullptr_t = nullptr) noexcept {}
};
}
}
|
/**
* Copyright (C) 2017 Alibaba Group Holding Limited. 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 __mediaplayer_H
#define __mediaplayer_H
#include <map>
#include <string>
#include <multimedia/mm_types.h>
#include <multimedia/mm_errors.h>
#include <multimedia/mmlistener.h>
#include <multimedia/media_meta.h>
#include <multimedia/media_buffer.h>
namespace YUNOS_MM {
class Pipeline;
typedef MMSharedPtr<Pipeline> PipelineSP;
class MediaPlayer {
public:
enum PlayerType {
PlayerType_DEFAULT,
PlayerType_ADO,
PlayerType_COMPAT,
PlayerType_COW,
PlayerType_COWAudio,
PlayerType_LPA,
PlayerType_PROXY,
PlayerType_PROXY_Audio,
PlayerType_LOCAL_Audio,
};
static MediaPlayer * create(PlayerType type = PlayerType_DEFAULT, const void * userDefinedData = NULL);
static void destroy(MediaPlayer * player);
public:
class Listener : public MMListener {
public:
Listener(){}
virtual ~Listener(){}
enum message_type {
// only for test
MSG_NOP = 0,
// player has prepared over.
// params:
// param1: prepare result
MSG_PREPARED = 1,
// player has playback completed.
// params: none
MSG_PLAYBACK_COMPLETE = 2,
// buffering percentage
// params:
// param1: percent(0~100)
MSG_BUFFERING_UPDATE = 3,
// player has seek complted
// params:
// param1: seek result
MSG_SEEK_COMPLETE = 4,
// set video size
// params:
// param1: int width
// param2: int height
MSG_SET_VIDEO_SIZE = 5,
// player started
// params:
// param1: start result
MSG_STARTED = 6,
// player paused
// params:
// param1: pause result
MSG_PAUSED = 7,
// player stopped
// params:
// param1: stop result
MSG_STOPPED = 8,
// progressive download started
// params:
// none
MSG_PD_STARTED = 9,
// progressive download completed
// params:
// none
MSG_PD_COMPLETED = 10,
// video is captured
// params:
// param1: undefined
// param2: undefined
// obj: int32_t: width
// int32_t: height
// int32_t: buffer size
//
MSG_VIDEO_CAPTURED = 11,
MSG_VIDEO_REQUEST_IDR = 12,
MSG_SKIPPED = 20,
MSG_TIMED_TEXT = 99,
// an error occured
// params:
// param1: erro code, see mm_errors_t
MSG_ERROR = 100,
// information
// params:
// param1: see info_type
MSG_INFO = 200,
// extended information, by manufacture
// params:
// param1: see manufacture's document
MSG_INFO_EXT = 401,
// subtitle is updated
// params:
// param1: unsigned long duration: The duration of the updated subtitle
// param2: not defined
// obj: const char *, The text of the updated subtitle.
MSG_SUBTITLE_UPDATED = 202,
//MSG_SUBTITLE_DATA = 201,
MSG_DURATION_UPDATE = 300,
// video frame to update texture image
// params:
// param1: buffer index
// param2: not defined
// obj: not defined
MSG_UPDATE_TEXTURE_IMAGE = 501,
// video rotation degree
// params:
// param1: rotation degree
// param2: not defined
// obj: not defined
MSG_VIDEO_ROTATION_DEGREE = 502,
};
enum info_type {
INFO_UNKNOWN = 1,
//The player was started as the next player when another player playbak complete
INFO_STARTED_AS_NEXT = 2,
//The first video frame is pushed for rendering
INFO_RENDERING_START = 3,
// 7xx
//The video frame can't be deocded fast enough because
//the video is too complex for the decoder.At this stage, perhaps only the audio plays fine
INFO_VIDEO_TRACK_LAGGING = 700,
//In order to buffer more data, the player is internally paused temporarily.
INFO_BUFFERING_START = 701,
//The player resume playback after bufferring enough data.
INFO_BUFFERING_END = 702,
// The network bandwidth in recent past
INFO_NETWORK_BANDWIDTH = 703,
// 8xx
//If a media has been improperly interleaved or not interleaved at all,
//e.g has all the video samples first then all the audio
// ones.This situation is referred to as Bad interleaving.
//A lot of disk seek may be happening when the video is playing.
INFO_BAD_INTERLEAVING = 800,
// The media is not seekable (e.g the live stream).
INFO_NOT_SEEKABLE = 801,
// The new media metadata is available.
INFO_METADATA_UPDATE = 802,
// Error occured when seeking
INFO_SEEK_ERROR = 803,
//9xx
INFO_TIMED_TEXT_ERROR = 900,
};
};
enum parameter_keys {
// Parameters for Streaming or buffering
KEY_PARAM_CACHE_STAT_COLLECT_FREQ_MS = 1000,
KEY_PARAM_AUDIO_CHANNEL_COUNT = 1100,
KEY_PARAM_PLAYBACK_RATE_PERMILLE = 1200,
//bitrate for call active
KEY_PARAM_SOURCE_BITRATE = 1500,
//the network url
KEY_PARAM_NETSOURCE_URL = 1501,
KEY_PARAM_NETWORK_TIMEOUT = 1505,
KEY_PARAM_DISPLAY_ASPECT_RATIO = 1506,
KEY_PARAM_NETSOURCE_URL_RESPHEADER = 1507, //HTTP response header
KEY_PARAMETER_HTTPDNS = 1508, // http dns request url & method
KEY_PARAMETER_NETADAPTION = 1509, //net adaption policy
//Ado CCADD
KEY_PARAM_AUDIO_HDMI_TRANSPARENT = 1888,
KEY_PARAM_AUDIO_DOBLY_NEIGHTMODE = 1889,
KEY_PARAM_LOADSUBTITLE_AUTO = 1990,
//autumn add code
KEY_PARAM_SUBTITLE_OFFSET_TIME = 1991,
//for smb net source
KEY_PARAM_SET_APP_PACKAGENAME = 1992,
// get only
// the name of audio codec
// value type: std::string *, caller must call "delete" for delete the param
KEY_PARAM_AUDIO_CODEC_NAME = 257,
// get only
// the name of video codec
// value type: std::string *, caller must call "delete" for delete the param
KEY_PARAM_VIDEO_CODEC_NAME,
// get only
// audio stream information
// value type: AudioStreamInfo*, caller must call "delete" for delete the param
KEY_PARAM_AUDIO_STREAM_INFO,
// get only
// video stream information
// value type: AudioStreamInfo*, caller must call "delete" for delete the param
KEY_PARAM_VIDEO_STREAM_INFO,
// set only
// Sets the playback rate.
// MM_ERROR_IVALIDOPERATION occurs when streaming playback.
// No operation is performed, if rate is 0.
// The sound is muted, when playback rate is under 0.0 and over 2.0.
// value type: float &, the playback rate (-5.0x ~ 5.0x)
KEY_PARAM_PLAYBACK_RATE,
};
enum EInvokeKey {
INVOKE_ID_GET_TRACK_INFO = 1,
INVOKE_ID_ADD_EXTERNAL_SOURCE = 2,
INVOKE_ID_ADD_EXTERNAL_SOURCE_FD = 3,
INVOKE_ID_SELECT_TRACK = 4,
INVOKE_ID_UNSELECT_TRACK = 5,
INVOKE_ID_SET_VIDEO_SCALING_MODE = 6,
INVOKE_ID_PRINT_DUMP_INFO = 7,
INVOKE_ID_RESOURCE_PRIORITY = 8,
};
enum ETrackType {
TRACK_TYPE_UNKNOWN = 0,
TRACK_TYPE_VIDEO = 1,
TRACK_TYPE_AUDIO = 2,
TRACK_TYPE_TIMEDTEXT = 3,
TRACK_TYPE_SUBTITLE = 4,
};
/* Audio stream types */
typedef enum {
AS_TYPE_DEFAULT = -1, /**< default audio stream type */
AS_TYPE_MIN = 0, /**< start index of valid stream index */
AS_TYPE_VOICE_CALL = 0, /**< voice call */
AS_TYPE_SYSTEM, /**< system sound*/
AS_TYPE_RING, /**< Ring*/
AS_TYPE_MUSIC, /**< Music*/
AS_TYPE_ALARM, /**< Alarm*/
AS_TYPE_NOTIFICATION, /**< Notification*/
AS_TYPE_BT_SCO, /**< BT SCO*/
AS_TYPE_ENFORCED_AUDIBLE, /**< Sounds that cannot be muted by user and must be routed to speaker */
AS_TYPE_DTMF, /**< DTMF*/
AS_TYPE_TTS, /**< Transmitted Through Speaker.Plays over speaker only, silent on other devices.*/
AS_TYPE_FM, /**< FM */
AS_TYPE_ACCESSIBILITY, /**< accessibility talk back prompts */
AS_TYPE_REROUTING, /**< For dynamic policy output mixes */
AS_TYPE_PATCH, /**< For internal audio flinger tracks. Fixed volume */
AS_TYPE_PUBLIC_CNT = AS_TYPE_FM + 1, /**< end index for the stream type visible to app developer*/
AS_TYPE_CNT = AS_TYPE_PATCH + 1, /**< Total count of audio stream type*/
} as_type_t;
/* Play rate */
enum play_rate {
/** slow rate 1/32 */
PLAYRATE_1_32 = 1,
/** slow rate 1/16 */
PLAYRATE_1_16 = 2,
/** slow rate 1/8 */
PLAYRATE_1_8 = 4,
/** slow rate 1/4 */
PLAYRATE_1_4 = 8,
/** slow rate 1/2 */
PLAYRATE_1_2 = 16,
/** normal rate 1 */
PLAYRATE_NORMAL = 32,
/** fast rate 2*/
PLAYRATE_2 = 64,
/** fast rate 4 */
PLAYRATE_4 = 128,
/** fast rate 8 */
PLAYRATE_8 = 256,
/** fast rate 16 */
PLAYRATE_16 = 512,
/** fast rate 32 */
PLAYRATE_32 = 1024
};
public:
struct VolumeInfo {
float left;
float right;
};
virtual mm_status_t setPipeline(PipelineSP pipeline) { return MM_ERROR_UNSUPPORTED; }
virtual mm_status_t setListener(Listener * listener);
// headers: the headers to be sent together with the request for the data.
virtual mm_status_t setDataSource(const char * uri,
const std::map<std::string, std::string> * headers = NULL) = 0;
virtual mm_status_t setDataSource(const unsigned char * mem, size_t size) = 0;
virtual mm_status_t setDataSource(int fd, int64_t offset, int64_t length) = 0;
virtual mm_status_t setSubtitleSource(const char* uri) { return MM_ERROR_UNSUPPORTED; }
virtual mm_status_t setDisplayName(const char* name) { return MM_ERROR_UNSUPPORTED; }
virtual mm_status_t setNativeDisplay(void * display) { return MM_ERROR_UNSUPPORTED; }
virtual mm_status_t setVideoDisplay(void * handle) = 0;
virtual mm_status_t setVideoSurfaceTexture(void * handle) = 0;
virtual mm_status_t prepare() = 0;
virtual mm_status_t prepareAsync() = 0;
virtual mm_status_t reset() = 0;
virtual mm_status_t setVolume(const VolumeInfo & volume) = 0;
virtual mm_status_t getVolume(VolumeInfo * volume) const = 0;
virtual mm_status_t setMute(bool mute) = 0;
virtual mm_status_t getMute(bool * mute) const = 0;
virtual mm_status_t start() = 0;
virtual mm_status_t stop() = 0;
virtual mm_status_t pause() = 0;
virtual mm_status_t seek(int msec) = 0;
virtual bool isPlaying() const = 0;
virtual mm_status_t getVideoSize(int *width, int * height) const = 0;
virtual mm_status_t getCurrentPosition(int * msec) const = 0;
virtual mm_status_t getDuration(int * msec) const = 0;
virtual mm_status_t setAudioStreamType(as_type_t type) = 0;
virtual mm_status_t getAudioStreamType(as_type_t *type) = 0;
virtual mm_status_t setAudioConnectionId(const char * connectionId);
virtual const char * getAudioConnectionId() const;
virtual mm_status_t setLoop(bool loop) = 0;
virtual bool isLooping() const = 0;
// A language code in either way of ISO-639-1 or ISO-639-2. When the language is unknown or could not be determined, MM_ERROR_UNSUPPORTED will returned
virtual mm_status_t setParameter(const MediaMetaSP & meta) = 0;
virtual mm_status_t getParameter(MediaMetaSP & meta) = 0;
virtual mm_status_t invoke(const MMParam * request, MMParam * reply) = 0;
virtual mm_status_t captureVideo() = 0;
virtual mm_status_t pushData(MediaBufferSP & buffer) { return MM_ERROR_UNSUPPORTED; }
virtual mm_status_t enableExternalSubtitleSupport(bool enable) { return MM_ERROR_UNSUPPORTED; }
protected:
MediaPlayer();
virtual ~MediaPlayer();
protected:
Listener * mListener;
private:
MM_DISALLOW_COPY(MediaPlayer)
DECLARE_LOGTAG()
};
}
#endif /* __mediaplayer_H */
|
/*===================================
# Author: sjay05
# File: time.cpp
# Desc: calculate execution time
===================================*/
#include <bits/stdc++.h>
#include <time.h>
#define start_time() clock_t tStart = clock()
#define get_time (double)(clock() - tStart)/CLOCKS_PER_SEC
#define print_time() printf("Time Taken: %.6fs\n", get_time)
using namespace std;
int main() {
start_time();
int c = 0;
for (int i = 0; i < 100; i++) {
c++;
}
print_time();
return 0;
}
|
#include<iostream>
using namespace std;
int main()
{
long long int t,i,l1,flag = 0;
string s,l;
cin>>t;
while(t--)
{
cin>>s>>l;
l1 = s.length();
for(i = 0;i < l1;++i)
{
if(s[i] == l[i])
continue;
else if((s[i] == '?' && l[i] != '?')||(s[i] != '?' && l[i] == '?')||(s[i] == '?' && l[i] == '?'))
continue;
else
{
flag = 1;
break;
}
}
if(flag == 1)
cout<<"No"<<endl;
else
cout<<"Yes"<<endl;
flag = 0;
}
}
|
#include "init_devices.hpp"
#include "sfr29.h"
//
extern "C" {
extern void init_led();
extern void init_switch();
extern void init_motor();
extern void init_encoder();
}
#include "encoder_driver.h"
#include "led_driver.h"
#include "motor_driver.h"
#include "switch_driver.h"
void init_cpu();
void init_devices()
{
init_cpu();
//
init_led();
init_switch();
init_motor();
init_encoder();
}
void init_cpu()
{
prc2 = 1; /*PACRの書込み許可*/
pacr = 3; /*80ピンに設定*/
/*クロック設定*/
prc0=1;
cm21=0;
cm06=0;
prc0=0;
}
|
//
// PartyVideoDJ - YouTube crossfading app
// Copyright (C) 2008-2017 Michael Fink
//
/// \file VideoSearchView.cpp View to search for videos
//
#include "stdafx.h"
#include "resource.h"
#include "VideoSearchView.hpp"
void VideoSearchView::SearchVideo(const CString& cszText)
{
ATLVERIFY(true == Navigate(_T("http://www.youtube.com/results?search_query=") + cszText));
SetFocus(); // set focus so that user can start scrolling away
}
BOOL VideoSearchView::PreTranslateMessage(MSG* pMsg)
{
if ((pMsg->message < WM_KEYFIRST || pMsg->message > WM_KEYLAST) &&
(pMsg->message < WM_MOUSEFIRST || pMsg->message > WM_MOUSELAST))
return FALSE;
// give HTML page a chance to translate this message
return (BOOL)SendMessage(WM_FORWARDMSG, 0, (LPARAM)pMsg);
}
LRESULT VideoSearchView::OnCreate(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& bHandled)
{
PostMessage(WM_INIT_VIEW);
bHandled = FALSE;
return 0;
}
LRESULT VideoSearchView::OnInitView(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/)
{
Init();
return 0;
}
bool GetAnchorTitleByElement(CComPtr<IHTMLElement>& spElement, CString& cszTitle)
{
CComBSTR bstrTagName;
HRESULT hr = spElement->get_tagName(&bstrTagName);
CString cszTagName(bstrTagName);
cszTagName.MakeLower();
if (cszTagName == _T("a"))
{
// get title attr
CComBSTR bstrTitleAttr(_T("title"));
CComVariant varTitle;
hr = spElement->getAttribute(bstrTitleAttr, 0, &varTitle);
if (SUCCEEDED(hr))
{
cszTitle = CComBSTR(varTitle.bstrVal);
if (!cszTitle.IsEmpty())
return true;
}
// get inner element and strip all html
CComBSTR bstrText;
if (SUCCEEDED(spElement->get_innerText(&bstrText)))
{
cszTitle = bstrText;
if (!cszTitle.IsEmpty())
return true;
}
}
else
{
// check all child elements
CComPtr<IDispatch> spIDispColl;
hr = spElement->get_children(&spIDispColl);
CComPtr<IHTMLElementCollection> spElementCollection;
hr = spIDispColl.QueryInterface(&spElementCollection);
if (SUCCEEDED(hr))
{
long lIndex = 0, lMax = 0;
spElementCollection->get_length(&lMax);
for (; lIndex < lMax; lIndex++)
{
CComVariant varName, varIndex;
varIndex.ChangeType(VT_I4);
varIndex.lVal = lMax;
CComPtr<IDispatch> spIDispChildElement;
hr = spElementCollection->item(varName, varIndex, &spIDispChildElement);
CComPtr<IHTMLElement> spChildElement;
hr = spIDispChildElement.QueryInterface(&spChildElement);
if (SUCCEEDED(hr))
{
bool bFound = GetAnchorTitleByElement(spChildElement, cszTitle);
if (bFound)
return true;
}
}
}
}
return false;
}
void VideoSearchView::OnBeforeNavigate2(const CString& cszURL_, const CString& cszTargetFrameName, bool& bCancel)
{
CString cszURL(cszURL_);
ATLTRACE(_T("OnBeforeNavigate2(url = \"%s\") called\n"), cszURL.GetString());
if (!cszTargetFrameName.IsEmpty())
{
// don't open new frame
bCancel = true;
return;
}
if (cszURL.Find(_T("doubleclick.net")) != -1)
{
// don't load ad sites
bCancel = true;
return;
}
if (cszURL.Find(_T("search_query")) != -1)
{
// this one's ok
return;
}
if (cszURL.Find(_T("watch?v=")) != -1 ||
(cszURL.Find(_T("view_play_list")) != -1 &&
(cszURL.Find(_T("&v=")) != -1))
)
{
bCancel = true;
CPoint pt;
GetCursorPos(&pt);
ScreenToClient(&pt);
CComPtr<IHTMLDocument2> spDoc;
HRESULT hr = GetHtmlDocument(spDoc);
CComPtr<IHTMLElement> spElement;
hr = spDoc->elementFromPoint(pt.x, pt.y, &spElement);
if (SUCCEEDED(hr) && spElement != NULL)
{
// show context menu
CString cszTitle;
bool bRet = GetAnchorTitleByElement(spElement, cszTitle);
if (!bRet)
{
// try parent item
CComPtr<IHTMLElement> spParentElement;
hr = spElement->get_parentElement(&spParentElement);
if (SUCCEEDED(hr))
bRet = GetAnchorTitleByElement(spParentElement, cszTitle);
}
cszTitle.TrimLeft();
cszTitle.TrimRight();
if (cszTitle.IsEmpty())
return;
ReplaceHtmlEntities(cszTitle);
if (bRet)
{
int iRet = AtlMessageBox(m_hWnd, (LPCTSTR)cszTitle, _T("Add this link to Titles?"), MB_YESNO | MB_ICONQUESTION);
if (iRet == IDYES)
{
if (m_fnAddTitle != NULL)
{
// get youtube id
int iPos = cszURL.Find(_T("v="));
if (iPos != -1)
cszURL = cszURL.Mid(iPos + 2);
iPos = cszURL.Find(_T(";"));
if (iPos != -1)
cszURL = cszURL.Left(iPos);
iPos = cszURL.Find(_T("&"));
if (iPos != -1)
cszURL = cszURL.Left(iPos);
m_fnAddTitle(cszTitle, cszURL);
}
}
// re-focus on webbrowser
SetFocus();
}
else
AtlMessageBox(m_hWnd, (LPCTSTR)cszURL, _T("Invalid link"), MB_OK | MB_ICONEXCLAMATION);
}
}
}
void VideoSearchView::ReplaceHtmlEntities(CString& cszText)
{
cszText.Replace(_T("ß"), _T("ß"));
cszText.Replace(_T("&"), _T("&"));
cszText.Replace(_T("'"), _T("'"));
}
|
/********************************************************************
author: ConfigGenerator
*********************************************************************/
#ifndef __CommonTemplate__HPP__NO_CONFLICT
#define __CommonTemplate__HPP__NO_CONFLICT
#include "ConfigDataTemplate.hpp"
#include "ConfigLanguageSetting.h"
class CommonTemplate : public ConfigDataTemplate<CommonTemplate>
{
public:
static void InitData(void);
public:
std::string Key;
std::string Value;
};
#define CommonTemplateDic CommonTemplate::Dic()
#define CommonTemplateLis(contextKey) CommonTemplate::Lis(contextKey)
#define CommonTemplateTem(key) CommonTemplate::Tem(key)
#define CommonTemplateRelease CommonTemplate::Release();
#endif
|
#ifndef VECTOR_EXT_H
#define VECTOR_EXT_H
#include "ublas_ext_config.hpp"
#include "expression_types_ext.hpp"
#include "vector_expression_ext.hpp"
#include <boost\numeric\ublas\vector.hpp>
#endif //VECTOR_EXT_H
|
#include <Windows.h>
#include <iostream>
using namespace std;
namespace thread_event
{
int tickets=100;
HANDLE _event;
DWORD WINAPI threadFunc1(LPVOID lpParam)//函数形式
{
while(TRUE)
{
WaitForSingleObject(_event,INFINITE);//可以使用事件对象,如果已经是拥有者,不可再次拥有,要等
//ResetEvent(_event);//对于手工的,没用的
if(tickets>0)
{
Sleep(5);
cout<<"threadFunc1 sale tickets:"<<tickets--<<endl;
}else
{
break;
}
SetEvent(_event);
}
return 0;
}
DWORD WINAPI threadFunc2(LPVOID lpParam)
{
while(TRUE)
{
WaitForSingleObject(_event,INFINITE);
//ResetEvent(_event);//对于手工的,没用的
if(tickets>0)
{
Sleep(5);
cout<<"threadFunc2 sale tickets:"<<tickets--<<endl;
SetEvent(_event);
}else
{
SetEvent(_event);//不要放在break;之后
break;
}
}
return 0;
}
int main(int argc,char* argv[] )
{
_event=::CreateEvent(NULL,FALSE,FALSE,L"tickts") ;//manual多数为FALSE,只可一个线可以得到
//如manual为TRUE,其它线程的WaitForSingleObject(_event ,INFINITE)都可以同时执行,如再调用ResetEvent,没有实现同步,没用的
if(_event)
{
if(ERROR_ALREADY_EXISTS==GetLastError())//对有名字的
{
cout<<"only one instance can run!"<<endl;
getchar();
return 1;
}
}
::SetEvent(_event);//设置为singled,即其它线程不用等
HANDLE myThread1,myThread2;
myThread1=CreateThread(NULL,0,threadFunc1,0,0,NULL);
myThread2=CreateThread(NULL,0,threadFunc2,0,0,NULL);
CloseHandle(myThread1);//当线程执行完成会清资源
CloseHandle(myThread2);
cout<<"main Thread runing"<<endl;
Sleep(5*1000);//放弃时间片
getchar();
CloseHandle(_event);//可以关闭它
return 1;
}
};
|
/************************************************
* Project: Home Lighting Automation System
* Date: 2019-May-04
* Author: William Becerra Gonzalez
*
* Description: This project allows a user to connect via the internet and connect to a NodeMCU ESP8266
* based circuit that controlls the lighting system via a web interface shows the time and allows indicates if there are users
* in the building
*
************************************************/
#include <ESP8266WiFi.h>
#include <ESP8266WebServer.h>
#include <NTPClient.h>
#include <WifiUdp.h>
const char* ssid = "Schrodinger"; // Wifi name
const char* password = "1993Will"; // wifi password
WiFiUDP ntpUDP;
ESP8266WebServer server(80); // The default HTTP port
NTPClient timeClient(ntpUDP, "ntp1.meraka.csir.co.za");
uint8_t lightControlPin = D1;
uint8_t lightStatus = A0;
uint8_t occupiedPin = D2;
bool LEDStatus = LOW;
bool occupied = false;
bool forceLightsOn = false;
const int darknessThreshold = 350;
void setup() {
Serial.begin(115200); // Initializing serial monitor
pinMode(lightControlPin, OUTPUT);
digitalWrite(lightControlPin, LOW);
pinMode(A0, INPUT);
pinMode(occupiedPin, INPUT);
// Connecting to WIFI
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected.");
Serial.print("IP address: ");
Serial.println(WiFi.localIP());
server.on("/", root);
server.on("/on", lightsOn);
server.on("/off", lightsOff);
server.onNotFound(URLNotFound);
server.begin();
attachInterrupt(digitalPinToInterrupt(occupiedPin), IntCallback, CHANGE);
}
void IntCallback(){
if(digitalRead(D2) == HIGH && analogRead(A0) < darknessThreshold){
onSwitch();
} else if ((analogRead(A0) >= darknessThreshold || digitalRead(D2) == HIGH)){
offSwitch();
} else if (forceLightsOn == false){
offSwitch();
}else{
//nop
}
}
void loop() {
server.handleClient();
}
void lightsOn(){
onSwitch();
server.send(200, "text/html", root_html());
forceLightsOn == true;
// Serial.println("Lights Switched On");
}
void lightsOff(){
offSwitch();
server.send(200, "text/html", root_html());
forceLightsOn = false;
// Serial.println("Lights Switched OFF");
}
void root(){
//This one must set all states by reading and application logic as well as display the home.html
// if occupied and lights are off they must come on
// if occupied and lights on they stay on
// else lights off
// Must also get time and update it
// Serial.println("Client Connected");
server.send(200, "text/html", root_html());
}
void URLNotFound(){
Serial.println("Client tried a URL not found");
server.send(404, "text/plain", "URL Not Found");
}
String root_html(){
timeClient.update();
String ptr = "<!DOCTYPE html><html> \n";
ptr += "<head><meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"> \n";
ptr += "<link rel=\"icon\" href=\"data:,\"> \n";
ptr += "<style>html { font-family: Helvetica; display: inline-block; margin: 0px auto; text-align: center;} \n";
ptr += ".button { background-color: #195B6A; border: none; color: white; padding: 16px 40px; \n";
ptr += "text-decoration: none; font-size: 30px; margin: 2px; cursor: pointer;} \n";
ptr += ".button2 {background-color: #77878A;}</style></head> \n";
ptr += "<body><h1>ESP8266 Web Server</h1> \n";
ptr += "<h2> ZA Time: " + timeClient.getFormattedTime() + "</h2> \n";
String outputState = (LEDStatus == LOW) ? "OFF": "ON";
Serial.println("Lights are " + outputState);
ptr += "<p>Light Control - State " + outputState + "</p> \n";
ptr += "<p><a href=\"/on\"><button class=\"button\"> ON </button></a></p> \n";
ptr += "<p><a href=\"/off\"><button class=\"button button2\"> OFF </button></a></p> \n";
ptr += "<h2> The office is currently: " + isItOccupide() + " and it is " + isDark() + "</h2> \n";
Serial.println("The office is currently " + isItOccupide() + " and it is " + isDark());
return ptr;
}
void onSwitch(){
LEDStatus = HIGH;
digitalWrite(lightControlPin, HIGH);
// Serial.println("Lights Turned On");
}
void offSwitch(){
LEDStatus = LOW;
digitalWrite(lightControlPin, LOW);
// Serial.println("Lights Turned Off");
}
String isDark(){
return (analogRead(A0) < darknessThreshold) ? "dark" : "bright" ;
}
String isItOccupide(){
return (digitalRead(D2) == HIGH) ? "occupied" : "unoccupied" ;
}
|
#include "headers.hpp"
#ifndef WINDOWCONTROLLER_H
#define WINDOWCONTROLLER_H
class windowController{
GLuint programId;
GLFWwindow* window;
string windowName;
int width, height;
public:
windowController(string windowName, int width, int height);
GLFWwindow* getWindow();
GLuint getProgramId();
void setProgramId(GLuint programId);
void initWindow();
void setWindowContext();
void setViewPort();
void keyCallback(GLFWkeyfun cbfunc);
void mouseCallback(GLFWcursorposfun cursorCallbackFn, GLFWmousebuttonfun mouseCallbackFn, GLFWscrollfun scrollCallbackFunc);
bool isWindowClosed();
void close();
};
#endif
|
/// PROBLEMA PONTOS DE FENO uri1261
#include<bits/stdc++.h>
using namespace std;
int main(){
map<string, int> preco;
int palavras, num_tex;
cin >> palavras >> num_tex;
string str;
int val;
for(int i = 0; i < palavras; i++){
cin >> str >> val;
preco[str] = val;
}
for(int i = 0; i < num_tex; i++){
int soma = 0;
while(cin >> str, str!="."){
soma = soma + preco[str];
}
cout << soma << endl;
}
}
|
class CfgPatches
{
class SAEF_TOOLBOX_RADIATION
{
version=2;
units[]={};
weapons[]={};
author="Rabid Squirrel";
requiredVersion=0.1;
requiredAddons[]=
{
"A3_Data_F"
};
};
};
class CfgFunctions
{
class RS_Radiation
{
class Radiation
{
file = "saef_radiation\Functions";
class ChemicalDetector {};
class DeferredInit {};
class GasMaskEventHandler
{
postInit = 1;
};
class GasMaskHandler {};
class GasMaskSound {};
class GetClosestMarker {};
class GetGridInfo {};
class Init
{
postInit = 1;
};
class Zone {};
class Handler {};
class MarkerHandler {};
class MarkerAceAction {};
class Markers {};
};
};
};
class CfgSounds
{
#include "Sounds\_Sounds.hpp"
};
class RscTitles
{
#include "Images\_RscTitles.hpp"
};
class CfgMarkerBrushes
{
class CUBISM {
name="Cubism";
texture="saef_radiation\Markers\Brushes\cubism.paa";
drawBorder=0;
scope=0;
};
};
|
// Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "CoreMinimal.h"
#include "Blueprint/UserWidget.h"
#include "UI_PlayerHealthBar.generated.h"
class UProgressBar;
class UTextBlock;
UCLASS()
class THIRDPERSONSHOOTER_API UUI_PlayerHealthBar : public UUserWidget
{
GENERATED_BODY()
private:
UPROPERTY(Category="Display", BlueprintReadOnly, meta=(BindWidget, AllowPrivateAccess="true"))
UProgressBar* HealthProgress;
UPROPERTY(Category="Display", BlueprintReadOnly, meta=(BindWidget, AllowPrivateAccess="true"))
UTextBlock* CurrentHealthText;
UPROPERTY(Category="Display", BlueprintReadOnly, meta=(BindWidget, AllowPrivateAccess="true"))
UTextBlock* MaxHealthText;
public:
#pragma region Properties
UPROPERTY(Category="Color", EditAnywhere)
FLinearColor MinHealthColor;
UPROPERTY(Category="Color", EditAnywhere)
FLinearColor MaxHealthColor;
UPROPERTY(Category="Color", EditAnywhere)
float MinHealthPercent;
#pragma endregion
void SetHealthRatio(const int CurrentHealth, const int MaxHealth) const;
};
|
#include <TESTS/testcase.h>
#include <TESTS/test_assertions.h>
#include <CORE/types.h>
#include <CORE/ARCH/endian.h>
using core::endian::little;
using core::endian::big;
REGISTER_TEST_CASE(endianTestSwap8) {
const u8 in = 0x0F;
u8 lout = little(in);
u8 bout = big(in);
TEST(testing::assertEquals(in, lout));
TEST(testing::assertEquals(in, bout));
}
REGISTER_TEST_CASE(endianTestSwap16) {
const u16 in = 0x0F5F;
const u16 inSwapped = 0x5F0F;
u16 lout = little(in);
u16 bout = big(in);
if (core::endian::isLittle()) {
TEST(testing::assertEquals(in, lout));
TEST(testing::assertEquals(inSwapped, bout));
} else {
TEST(testing::assertEquals(inSwapped, lout));
TEST(testing::assertEquals(in, bout));
}
}
REGISTER_TEST_CASE(endianTestSwap32) {
const u32 in = 0x0F5F6B9B;
const u32 inSwapped = 0x9B6B5F0F;
u32 lout = little(in);
u32 bout = big(in);
if (core::endian::isLittle()) {
TEST(testing::assertEquals(in, lout));
TEST(testing::assertEquals(inSwapped, bout));
} else {
TEST(testing::assertEquals(inSwapped, lout));
TEST(testing::assertEquals(in, bout));
}
}
REGISTER_TEST_CASE(endianTestSwap64) {
const u64 in = 0x0F5F6B9BA3A59587;
const u64 inSwapped = 0x8795A5A39B6B5F0F;
u64 lout = little(in);
u64 bout = big(in);
if (core::endian::isLittle()) {
TEST(testing::assertEquals(in, lout));
TEST(testing::assertEquals(inSwapped, bout));
} else {
TEST(testing::assertEquals(inSwapped, lout));
TEST(testing::assertEquals(in, bout));
}
}
|
#include "decoder.h"
Decoder::Decoder(string _filename)
{
init(NULL);
config->TAG_IMAGE_FILE = _filename;
config->ARGS_OK = true;
}
Decoder::Decoder(int argc,char **argv)
{
init(NULL);
config->checkArgs(argc, argv);
}
Decoder::Decoder(Tagimage* _tagimage)
{
init(NULL);
tagimage = _tagimage;
if(tagimage != NULL) config->ARGS_OK = true;
}
Decoder::Decoder(Config *_config)
{
init(_config);
}
Decoder::Decoder()
{
init(NULL);
}
Decoder::~Decoder()
{
if(tagimage != NULL) delete tagimage;
if(local_config) { //'locally created' Vs 'passed in reference'
if(config != NULL) delete config;
}
}
void
Decoder::init(Config *_config)
{
config = _config;
tagimage = NULL;
local_config = false;
if( config == NULL ) {
local_config = true; //'locally created' Vs 'passed in reference'
config = new Config();
}
fuzzy = config->FUZZY;
for(int i=0; i<12; i++) tag[i] = -1;
last_mode = 1;
}
Config*
Decoder::getConfig()
{
return config;
}
void
Decoder::copyTag(int* _tag)
{
for(int i=0; i<12; i++) _tag[i] = tag[i];
}
//called once for single image processing
bool
Decoder::processTag()
{
if(!config->ARGS_OK ) return false;
if(tagimage == NULL) tagimage = new Tagimage(config);
if(!tagimage->isValid()) {
delete tagimage; tagimage = NULL;
return false;
}
if(config->VISUAL_DEBUG) config->setDebugPixmap(new Pixmap(config->TAG_IMAGE_FILE));
Threshold* threshold = new Threshold(config, tagimage);
threshold->computeEdgemap();
delete tagimage; tagimage = NULL;
delete threshold;
Shape *shapes = new Shape[config->MAX_SHAPES];
Shape *anchor = new Shape(config);
Border* border = new Border(config, shapes, anchor);
int nshapes = border->findShapes();
delete border;
if( nshapes >= 12 ){
Pattern* pattern = new Pattern(config, shapes, nshapes, anchor);
pattern->findCodeInternal(tag);
delete pattern;
}
delete anchor;
delete [] shapes;
return true;
}
//called more than once in video frame processing
bool
Decoder::processFrame(unsigned char *data, int width, int height)
{
assert(data != NULL) ;
assert( (data+(width*height)) != NULL) ;
//1. Skip frame
if(fuzzy->selectFrame(config->V_SKIP_FRAMES) == false) {
if(fuzzy->tagIsActive()) markCode(data, width, height, 0);
return false;
}
//2.Check Motion
if(fuzzy->motionDetect(data, width, height) == false) {
if(fuzzy->tagIsActive()) markCode(data, width, height, 0);
return false;
}
//3. Process Tag
config->V_GRID_WIDTH = width;
config->V_GRID_HEIGHT = height;
//config->setDebugPixmap(new Pixmap("debug.jpg"));
for(int i=0; i<12; i++) tag[i] = -1;
Threshold* threshold = new Threshold(config, data, width, height);
threshold->computeEdgemap();
delete threshold;
resetVMap(width*height);
Shape *shapes = new Shape[config->MAX_SHAPES];
Shape *anchor = new Shape(config);
Border* border = new Border(config, shapes, anchor);
int nshapes = border->findShapes();
delete border;
if( nshapes >= 12 ){
Pattern* pattern = new Pattern(config, shapes, nshapes, anchor);
pattern->findCodeExternal(tag);
delete pattern;
}
delete anchor;
delete [] shapes;
bool tagvalidity = fuzzy->validateTag(tag);
if(tagvalidity) markCode(data, width, height, 1);
return tagvalidity;
}
/*
void
Decoder::frameOverlayOnly(unsigned char *data, int width, int height)
{
if(fuzzy->tagIsActive()) markCode(data, width, height, 0);
}
*/
void
Decoder::resetVMap(int size)
{
if(config->V_MAP == NULL ) config->V_MAP = new bool[size];
for(int i=0; i < size; i++) config->V_MAP[i] = false;
}
void
Decoder::markCode(unsigned char *data, int width, int height, int mode)
{
if(mode == 0) mode = last_mode;
int block_radius = width < height ? width/50 : height/50 ;
if(block_radius<1) block_radius = 2;
assert(config->V_MAP != NULL );
RGBBYTE *thispixel;
/*float xscale = (float)width / (float)config->GRID_WIDTH ;
float yscale = (float)height / (float)config->GRID_HEIGHT ;
if(xscale == 0) xscale = 1;
if(yscale == 0) yscale = 1;*/
for(int y = block_radius; y < height-block_radius; y++){
for(int x = block_radius; x < width-block_radius; x++){
if(config->V_MAP[(y*width) + x]) {
if(mode == 1){
for(int i=(block_radius*-1); i < block_radius; i++){
for(int j=(block_radius*-1); j < block_radius; j++){
thispixel = (RGBBYTE*) data + ((y+j)*width) + (x+i) ;
thispixel->R = 0;
thispixel->G = 255;
thispixel->B = 0;
}
}
}else if(mode == 2){
for(int i=(block_radius*-1); i < block_radius; i++){
for(int j=(block_radius*-1); j < block_radius; j++){
thispixel = (RGBBYTE*) data + ((y+j)*width) + (x+i) ;
thispixel->R = 0;
thispixel->G = 255;
thispixel->B = 255;
}
}
}else if(mode == 3){
for(int i=(block_radius*-1); i < block_radius; i++){
for(int j=(block_radius*-1); j < block_radius; j++){
thispixel = (RGBBYTE*) data + ((y+j)*width) + (x+i) ;
thispixel->R = 255;
thispixel->G = 0;
thispixel->B = 0;
}
}
}
}
}
}
if(mode != 0) last_mode = mode;
}
int
Decoder::tagAge()
{
if(fuzzy->tagIsBrandNew()) return 0;
if(fuzzy->tagIsNew()) return 1;
if(fuzzy->tagIsOld()) return 2;
if(fuzzy->tagIsVeryOld()) return 3;
return 3;
}
int
Decoder::validFor()
{
return fuzzy->valid_for;
}
|
#include "SouvenirData.h"
#include <iomanip>
#include <fstream>
#include <sstream>
#include <limits>
#include <ios>
//creates a souvenir class based on the text file souvenirInfoList.txt
SouvenirData::SouvenirData() {
std::ifstream inFile;
inFile.open("C:/Users/gdfgdf/Documents/findingnemo/souvenirInfoList.txt");
while(!inFile.eof()) {
std::vector<souvenirInfo> newSouvenirs;
std::string teamName;
souvenirInfo newSouvenir;
std::string souvenirName;
float souvenirPrice;
//getting the stadium name that will hold the list of souvenirs
std::getline(inFile, teamName);
//getting the stadium's souvenir name
std::getline(inFile, souvenirName);
//taking in all the souvenirs the stadium has to offer
while(souvenirName != "~") {
//getting the souvenir's price
inFile >> souvenirPrice;
inFile.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
//setting the name and price to the struct
newSouvenir.item = souvenirName;
newSouvenir.price = souvenirPrice;
//pushing the new souvenir info into the vector
newSouvenirs.push_back(newSouvenir);
//getting the stadium's souvenir name
std::getline(inFile, souvenirName);
}//end - while
listOfSouvenirs[teamName] = newSouvenirs;
}//end - while
inFile.close();
}//end - default constructor
SouvenirData::~SouvenirData() { }//end - default constructor
//this method will make the soucenir list presistant between runs depending on
//the changes that were made to it.
void SouvenirData::updateSouvenirList() {
std::map< std::string, std::vector<souvenirInfo> >::iterator
it = listOfSouvenirs.begin();
std::map< std::string, std::vector<souvenirInfo> >::iterator
endFileCheck = listOfSouvenirs.begin();
endFileCheck++;
//opening file for update
std::ofstream outFile;
outFile.open("C:/Users/gdfgdf/Documents/findingnemo/souvenirInfoList.txt");
int sizeOfSouvs = listOfSouvenirs.size();
int i = 0;
for(; it != listOfSouvenirs.end(); it++) {
i++;
outFile << it->first << std::endl;
std::vector<souvenirInfo>::iterator it2 = it->second.begin();
for(; it2 != it->second.end(); it2++) {
outFile << it2->item << std::endl;
outFile << it2->price << std::endl;
}//end - for
outFile << "~";
if(sizeOfSouvs != i) outFile << std::endl;
}//end - for
outFile.close();
}//end - updateSouvenirList
//this method will print the data for all the stadiums
std::string SouvenirData::printAll() {
std::map< std::string, std::vector<souvenirInfo> >::iterator
it = listOfSouvenirs.begin();
std::map< std::string, std::vector<souvenirInfo> >::iterator
endFileCheck = listOfSouvenirs.begin();
endFileCheck++;
std::stringstream returnStr;
returnStr << std::setprecision(2) << std::fixed;
for(; it != listOfSouvenirs.end(); it++, endFileCheck++) {
returnStr << it->first << "\n";
std::vector<souvenirInfo>::iterator it2 = it->second.begin();
for(; it2 != it->second.end(); it2++) {
returnStr << it2->item << "\n";
returnStr << it2->price << "\n";
}//end - for
if(endFileCheck != listOfSouvenirs.end()) returnStr << "\n";
}//end - for
return returnStr.str();
}//end - printAll
//adding a souvenir to the passed in stadium. returns true if item was
//added successfully
bool SouvenirData::addSouvenir(std::string stadiumName,
std::string itemName,
float itemPrice) {
//the .count() method will return a bool if the key is in the map.
//if stadium is not in the map, return false.
if(!listOfSouvenirs.count(stadiumName)) return false;
souvenirInfo newSouvenir;
newSouvenir.item = itemName;
newSouvenir.price = itemPrice;
listOfSouvenirs.at(stadiumName).push_back(newSouvenir);
return true;
}//end - addSouvenir
//updates the price of an item. returns true if the item's price was
//updated successfully
bool SouvenirData::updatePrice(std::string stadiumName,
std::string itemName, float newPrice) {
//the .count() method will return a bool if the key is in the map.
//if stadium is not in the map, return false.
if(!listOfSouvenirs.count(stadiumName)) return false;
bool notUpdated = true;
std::vector<souvenirInfo>::iterator it = listOfSouvenirs.at(stadiumName).begin();
while(it != listOfSouvenirs.at(stadiumName).end() && notUpdated) {
//if true, the item was found and the price was updated
if(it->item == itemName) {
it->price = newPrice;
notUpdated = false;
return true;
}
it++;
}//end - while
//if this false is reached, this means there IS a stadium in the list, but
//no passed in souvenir in that sradium's shop.
return false;
}//end - updatePrice
//removes a souvenir from a stadium. returns true if removal was
//successful
bool SouvenirData::removeSouvenir(std::string stadiumName, std::string itemName) {
//the .count() method will return a bool if the key is in the map.
//if stadium is not in the map, return false.
if(!listOfSouvenirs.count(stadiumName)) return false;
std::vector<souvenirInfo>::iterator it = listOfSouvenirs.at(stadiumName).begin();
while(it != listOfSouvenirs.at(stadiumName).end()) {
//if true, the item was found and the price was updated
if(it->item == itemName) {
listOfSouvenirs.at(stadiumName).erase(it);
return true;
}
it++;
}//end - while
//if this false is reached, this means there IS a stadium in the list, but
//no passed in souvenir in that sradium's shop.
return false;
}//end - removeSouvenir
//returns the price of the souvenir at the stadium. returns -1 if not found
float SouvenirData::getPrice(std::string stadiumName, std::string souvenirName) {
//the .count() method will return a bool if the key is in the map.
//if stadium is not in the map, return false.
if(!listOfSouvenirs.count(stadiumName)) return -1.0;
std::vector<souvenirInfo>::iterator it = listOfSouvenirs.at(stadiumName).begin();
while(it != listOfSouvenirs.at(stadiumName).end()) {
//if true, the item was found and the price was updated
if(it->item == souvenirName) {
return it->price;
}
it++;
}//end - while
//if this return, item was not found
return -1.0;
}//end - getPrice
//returns a string all the souvenir's information at the passed in stadium
//returns an error message if the stadium is not found
std::map< std::string, std::vector<souvenirInfo> > SouvenirData::getAllInfoAt(std::string stadiumName) {
//the .count() method will return a bool if the key is in the map.
//if stadium is not in the map, return false.
// if(!listOfSouvenirs.count(stadiumName)) return "::ERROR:: Stadium Not Found\n";
return listOfSouvenirs;
}//end - getAllInfoAt
|
// -*- C++ -*-
//
// Copyright (C) 1998, 1999, 2000, 2002 Los Alamos National Laboratory,
// Copyright (C) 1998, 1999, 2000, 2002 CodeSourcery, LLC
//
// This file is part of FreePOOMA.
//
// FreePOOMA is free software; you can redistribute it and/or modify it
// under the terms of the Expat license.
//
// 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 Expat
// license for more details.
//
// You should have received a copy of the Expat license along with
// FreePOOMA; see the file LICENSE.
//
//-----------------------------------------------------------------------------
// Class:
// ErrorType
// ForEachRef
//-----------------------------------------------------------------------------
#ifndef POOMA_PETE_POOMAPETE_H
#define POOMA_PETE_POOMAPETE_H
//////////////////////////////////////////////////////////////////////
//-----------------------------------------------------------------------------
// Overview:
//
// This file contains POOMA specific extensions to PETE. Please refrain from
// changing other PETE files in this directory without making corresponding
// changes to the PETE repository.
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
// Typedefs:
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
// Includes:
//-----------------------------------------------------------------------------
#include "PETE/ErrorType.h"
//-----------------------------------------------------------------------------
// Forward Declarations:
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
// Reference versions of ForEach.
//-----------------------------------------------------------------------------
template<class Expr, class FTag, class CTag>
struct ForEachRef
{
typedef typename LeafFunctor<Expr, FTag>::Type_t Type_t;
inline static
const Type_t &apply(const Expr &expr, const FTag &f, const CTag &)
{
return LeafFunctor<Expr, FTag>::apply(expr, f);
}
};
template<class Expr, class FTag, class CTag>
inline const typename ForEachRef<Expr,FTag,CTag>::Type_t &
forEachRef(const Expr &e, const FTag &f, const CTag &c)
{
return ForEachRef<Expr, FTag, CTag>::apply(e, f, c);
}
template<class Op, class A, class FTag, class CTag>
struct ForEachRef<UnaryNode<Op, A>, FTag, CTag>
{
typedef typename ForEachRef<A, FTag, CTag>::Type_t TypeA_t;
typedef typename Combine1<TypeA_t, Op, CTag>::Type_t Type_t;
inline static
const Type_t &apply(const UnaryNode<Op, A> &expr, const FTag &f,
const CTag &c)
{
return Combine1<TypeA_t, Op, CTag>::
combine(ForEachRef<A, FTag, CTag>::apply(expr.child(), f, c),
c);
}
};
template<class Op, class A, class B, class FTag, class CTag>
struct ForEachRef<BinaryNode<Op, A, B>, FTag, CTag >
{
typedef typename ForEachRef<A, FTag, CTag>::Type_t TypeA_t;
typedef typename ForEachRef<B, FTag, CTag>::Type_t TypeB_t;
typedef typename Combine2<TypeA_t, TypeB_t, Op, CTag>::Type_t Type_t;
inline static
const Type_t &apply(const BinaryNode<Op, A, B> &expr, const FTag &f,
const CTag &c)
{
return Combine2<TypeA_t, TypeB_t, Op, CTag>::
combine(ForEachRef<A, FTag, CTag>::apply(expr.left(), f, c),
ForEachRef<B, FTag, CTag>::apply(expr.right(), f, c),
c);
}
};
template<class Op, class A, class B, class C, class FTag, class CTag>
struct ForEachRef<TrinaryNode<Op, A, B, C>, FTag, CTag >
{
typedef typename ForEachRef<A, FTag, CTag>::Type_t TypeA_t;
typedef typename ForEachRef<B, FTag, CTag>::Type_t TypeB_t;
typedef typename ForEachRef<C, FTag, CTag>::Type_t TypeC_t;
typedef typename Combine3<TypeA_t, TypeB_t, TypeC_t, Op, CTag>::Type_t
Type_t;
inline static
const Type_t &apply(const TrinaryNode<Op, A, B, C> &expr, const FTag &f,
const CTag &c)
{
return Combine3<TypeA_t, TypeB_t, TypeC_t, Op, CTag>::
combine(ForEachRef<A, FTag, CTag>::apply(expr.left(), f, c),
ForEachRef<B, FTag, CTag>::apply(expr.middle(), f, c),
ForEachRef<C, FTag, CTag>::apply(expr.right(), f, c),
c);
}
};
template<class T, class FTag, class CTag>
struct ForEachRef<Expression<T>, FTag, CTag>
{
typedef typename ForEachRef<T, FTag, CTag>::Type_t Type_t;
inline static
const Type_t &apply(const Expression<T> &expr, const FTag &f,
const CTag &c)
{
return ForEachRef<T, FTag, CTag>::apply(expr.expression(), f, c);
}
};
template<class T, class FTag, class CTag>
struct ForEachRef<Reference<T>, FTag, CTag>
{
typedef typename ForEachRef<T, FTag, CTag>::Type_t Type_t;
inline static
const Type_t &apply(const Reference<T> &ref, const FTag &f,
const CTag &c)
{
return ForEachRef<T, FTag, CTag>::apply(ref.reference(), f, c);
}
};
//////////////////////////////////////////////////////////////////////
#endif // POOMA_PETE_POOMAPETE_H
// ACL:rcsinfo
// ----------------------------------------------------------------------
// $RCSfile: PoomaPETE.h,v $ $Author: richard $
// $Revision: 1.4 $ $Date: 2004/11/01 18:16:56 $
// ----------------------------------------------------------------------
// ACL:rcsinfo
|
/*
* polydatafiles2csv.cc
*
* Created on: Feb 13, 2015
* Author: paulaljabar
*/
#ifdef HAS_VTK
///////////////////////////////////////////////////////////////
#include <string.h>
//#include <sys/stat.h>
//
#include <irtkImage.h>
#include <irtkMatrix.h>
#include <abcdUtils.h>
#include <vtkSmartPointer.h>
#include <vtkDoubleArray.h>
#include <vtkPoints.h>
#include <vtkPolyData.h>
#include <vtkPolyDataReader.h>
#include <vtkPolyDataWriter.h>
#include <vtkSphereSource.h>
#include <vtkTensorGlyph.h>
void usage(std::string name) {
cout << "" << endl;
cout << "" << endl;
cout << name
<< " [output.vtk] [points_1.vtk] [points_2.vtk] .... [points_N.vtk] <options> "
<< endl;
cout << "" << endl;
cout << "Generate Gaussian ellipsoids for the landmark data given in the files " << endl;
cout << "[points_1.vtk] .... [points_N.vtk]. I.e. each file is expected to have" << endl;
cout << "the same number of corresponding landmarks. The ellipsoids indicate the" << endl;
cout << "spatial spread of each landmark." << endl;
cout << "" << endl;
cout << "This is the 3-D analogue of using an interval in 1-D of, say, " << endl;
cout << " [mean - 3*SD, mean + 3*SD]" << endl;
cout << "to define a range where we expect to find nearly all the data. " << endl;
cout << "" << endl;
cout << "The axes of each ellipsoid are aligned with the principle modes of" << endl;
cout << "variation for the corresponding set of landmarks. The radius of each" << endl;
cout << "ellipsoid along each axis is proportional to the standard deviation " << endl;
cout << "of the data along that axis (see -radius option)." << endl;
cout << "" << endl;
cout << "Options:" << endl;
cout << "" << endl;
cout << "-radius [value] : Radius along each axis of the ellipsoid. The number" << endl;
cout << " given is multiplied by the standard deviation of the " << endl;
cout << " the data along the axis. Setting [value] to the following" << endl;
cout << " gives ellipsoids that are expected to capture the given" << endl;
cout << " fractions of the landmark cloud." << endl;
cout << "" << endl;
cout << " value=1 19.9% " << endl;
cout << " value=2 73.9% " << endl;
cout << " value=3 (default) 97.1% " << endl;
cout << "" << endl;
cout << "See https://upload.wikimedia.org/wikipedia/commons/a/a2/Cumulative_function_n_dimensional_Gaussians_12.2013.pdf" << endl;
cout << "" << endl;
cout << "" << endl;
/*
*
* The normal distribution in dimension 1 has an expected proprortion of the
* population given by a number of standard deviations. These can be obtained
* from the chi squared cumulative distribution function. In MatLab this is
* chi2cdf:
*
* >> [chi2cdf(1,1) chi2cdf(4,1) chi2cdf(9,1)]
0.6827 0.9545 0.9973
* In a two dimensional Gaussian, the region can be defined by the ellipsoid
* which is at a fixed Mahalonibis distance from the mean. The M. distance is
* (x - mu)^T \sigma^{-1} (x - mu) where \sigma is the covariance matrix.
* The ellipsoid has radii along its principle axes that can be expressed as multiples
* of the standard deviation along that axis. Using 1, 2 or 3 multiples
* of the standard deviation, we expect to capture the following proportions
* of the population within each of the successively larger ellipses.
*
>> [chi2cdf(1^2, 2) chi2cdf(2^2, 2) chi2cdf(3^2, 2)]
0.3935 0.8647 0.9889
* In 3-D the numbers are as follows:
*
>> [chi2cdf(1^2, 3) chi2cdf(2^2, 3) chi2cdf(3^2, 3)]
0.1987 0.7385 0.9707
*
* https://upload.wikimedia.org/wikipedia/commons/a/a2/Cumulative_function_n_dimensional_Gaussians_12.2013.pdf
*
*/
exit(1);
}
char **inputFilenames = NULL;
char *outputFileName = NULL;
int main(int argc, char **argv) {
bool ok, verbose;
double p[3];
double tensorVec[9];
double radius = 3.0;
int i, noOfPointSets, j;
int a, b;
std::string exeName = argv[0];
if (argc < 2)
usage(exeName);
int MAX_FILES = 1000;
// Parse file names and values
outputFileName = argv[1];
argc--;
argv++;
char **inputFilenames = new char *[MAX_FILES];
noOfPointSets = 0;
while ((argc > 1) && (argv[1][0] != '-')) {
inputFilenames[noOfPointSets] = argv[1];
if (!is_vtkPolyDataFile(inputFilenames[noOfPointSets])) {
cerr << "Not a vtk polydata file: " << inputFilenames[noOfPointSets]
<< endl;
usage(exeName);
}
noOfPointSets++;
argc--;
argv++;
}
if (noOfPointSets < 1) {
cerr << "No files to read." << endl;
usage(exeName);
}
if (noOfPointSets < 2) {
cerr << "Only one file. Covariance across landmarks meaningless." << endl;
exit(1);
}
verbose = false;
while (argc > 1) {
ok = false;
if ((ok == false) && (strcmp(argv[1], "-verbose") == 0)) {
argc--;
argv++;
verbose = true;
ok = true;
}
if ((ok == false) && (strcmp(argv[1], "-radius") == 0)) {
argc--;
argv++;
radius = atof(argv[1]);
argc--;
argv++;
ok = true;
}
if (ok == false) {
cerr << "Can not parse argument " << argv[1] << endl;
exit(1);
}
}
if (verbose) {
cerr << "Processing " << noOfPointSets << " files " << endl;
for (i = 0; i < noOfPointSets; i++)
cerr << " " << inputFilenames[i] << endl;
if (outputFileName != NULL)
cerr << "Writing output to " << outputFileName << endl;
}
vtkSmartPointer<vtkPolyDataReader> reader =
vtkSmartPointer<vtkPolyDataReader>::New();
reader->SetFileName(inputFilenames[0]);
reader->Update();
vtkSmartPointer<vtkPolyData> inputPoints =
vtkSmartPointer<vtkPolyData>::New();
inputPoints = reader->GetOutput();
int nPts = inputPoints->GetNumberOfPoints();
FILE *output;
output = fopen(outputFileName, "w");
double ***data = NULL;
double **meanXYZ = NULL;
data = Allocate(data, 3, nPts, noOfPointSets);
for (i = 0; i < noOfPointSets; i++) {
reader->SetFileName(inputFilenames[i]);
reader->Update();
inputPoints = reader->GetOutput();
if (inputPoints->GetNumberOfPoints() != nPts) {
cerr << "Input files have differing numbers of points." << endl;
exit(1);
}
for (j = 0; j < nPts; j++) {
// Read all points for current set.
inputPoints->GetPoint(j, p);
data[i][j][0] = p[0];
data[i][j][1] = p[1];
data[i][j][2] = p[2];
}
}
// mean location for each point
meanXYZ = Allocate(meanXYZ, 3, nPts);
for (j = 0; j < nPts; j++) {
meanXYZ[j][0] = 0;
meanXYZ[j][1] = 0;
meanXYZ[j][2] = 0;
for (i = 0; i < noOfPointSets; i++) {
meanXYZ[j][0] += data[i][j][0];
meanXYZ[j][1] += data[i][j][1];
meanXYZ[j][2] += data[i][j][2];
}
meanXYZ[j][0] /= noOfPointSets;
meanXYZ[j][1] /= noOfPointSets;
meanXYZ[j][2] /= noOfPointSets;
}
// A set of 3x3 spatial covariance matrices, one for each landmark
irtkMatrix *matrices = new irtkMatrix[nPts];
double covarElement;
// For each landmark:
for (j = 0; j < nPts; j++) {
matrices[j].Initialize(3, 3);
for (a = 0; a < 3; a++) {
for (b = a; b < 3; b++) {
covarElement = 0.0;
// Loop over sets
for (i = 0; i < noOfPointSets; i++) {
covarElement += (data[i][j][a] - meanXYZ[j][a])
* (data[i][j][b] - meanXYZ[j][b]);
}
covarElement /= (noOfPointSets - 1.0);
matrices[j](a, b) = covarElement;
matrices[j](b, a) = covarElement;
}
}
}
irtkMatrix *e1 = new irtkMatrix[nPts];
irtkMatrix *e2 = new irtkMatrix[nPts];
irtkVector *eVals = new irtkVector[nPts];
for (j = 0; j < nPts; j++) {
matrices[j].Eigenvalues(e1[j], eVals[j], e2[j]);
for (a = 0; a < 3; a++) {
// square root of variance
eVals[j](a) = sqrt(eVals[j](a));
// Scale the eigenvector.
// The scale is interpreted as a diameter by the tensor glyph.
for (b = 0; b < 3; b++) {
e1[j](b, a) *= (2.0 * radius * eVals[j](a));
}
}
}
// Locations for the ellipsoids, each will be centred
// at the mean location of the corresponding landmark
vtkPoints *outPoints = vtkPoints::New();
outPoints->SetNumberOfPoints(nPts);
for (j = 0; j < nPts; j++) {
p[0] = meanXYZ[j][0];
p[1] = meanXYZ[j][1];
p[2] = meanXYZ[j][2];
outPoints->InsertPoint(j, p);
}
// Storage for the tensor data that will be passed to the glyph filter.
vtkDoubleArray *covTensors = vtkDoubleArray::New();
covTensors->SetNumberOfTuples(nPts);
covTensors->SetNumberOfComponents(9);
for (j = 0; j < nPts; j++) {
for (a = 0; a < 3; a++) {
tensorVec[a] = e1[j](a, 0);
tensorVec[a + 3] = e1[j](a, 1);
tensorVec[a + 6] = e1[j](a, 2);
}
covTensors->InsertTuple(j, tensorVec);
}
covTensors->Squeeze();
covTensors->SetName("cov");
vtkPolyData *pdWithTensors = vtkPolyData::New();
pdWithTensors->SetPoints(outPoints);
pdWithTensors->GetPointData()->SetTensors(covTensors);
// The glyph to be used.
vtkSphereSource *sphere = vtkSphereSource::New();
sphere->SetThetaResolution(30);
sphere->SetPhiResolution(30);
// The glyph filter.
vtkTensorGlyph *glyphs = vtkTensorGlyph::New();
glyphs->SetSourceData(sphere->GetOutput());
glyphs->SetInputData(pdWithTensors);
// Don't do any calculation in the filter,
// we have done all the calculations already.
glyphs->SetExtractEigenvalues(0);
glyphs->SetThreeGlyphs(0);
glyphs->SetScaling(0);
glyphs->Update();
vtkPolyDataWriter *pdWriter = vtkPolyDataWriter::New();
pdWriter->SetFileName(outputFileName);
pdWriter->SetInputData(glyphs->GetOutput());
pdWriter->SetFileTypeToBinary();
pdWriter->Update();
pdWriter->Write();
Deallocate<double>(data);
Deallocate<double>(meanXYZ);
}
#else
#include <irtkImage.h>
int main( int argc, char *argv[] ) {
cerr << argv[0] << " needs to be compiled with the VTK library " << endl;
}
#endif
|
/***********************************************************************
created: Tue Feb 17 2009
author: Paul D Turner
*************************************************************************/
/***************************************************************************
* Copyright (C) 2004 - 2011 Paul D Turner & The CEGUI Development Team
*
* 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 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 <sstream>
#include "CEGUI/RendererModules/Ogre/Texture.h"
#include "CEGUI/Exceptions.h"
#include "CEGUI/System.h"
#include "CEGUI/RendererModules/Ogre/ImageCodec.h"
#include "CEGUI/RendererModules/Ogre/OgreMacros.h"
#include "CEGUI/RendererModules/Ogre/ResourceProvider.h"
#include "CEGUI/DataContainer.h"
#include "CEGUI/Rectf.h"
#ifdef CEGUI_USE_OGRE_TEXTURE_GPU
#include <OgreRoot.h>
#include <OgreTextureGpuManager.h>
#include <OgrePixelFormatGpuUtils.h>
#include <OgreStagingTexture.h>
#else
#include <OgreTextureManager.h>
#include <OgreHardwarePixelBuffer.h>
#endif // CEGUI_USE_OGRE_TEXTURE_GPU
#include <cstdint>
#include <sstream>
// Start of CEGUI namespace section
namespace CEGUI
{
//----------------------------------------------------------------------------//
// helper function to return byte size of image of given size in given format
static size_t calculateDataSize(const Sizef size, Texture::PixelFormat fmt)
{
switch (fmt)
{
case Texture::PixelFormat::Rgba:
return static_cast<size_t>(size.d_width * size.d_height * 4);
case Texture::PixelFormat::Rgb:
return static_cast<size_t>(size.d_width * size.d_height * 3);
case Texture::PixelFormat::Rgb565:
case Texture::PixelFormat::Rgba4444:
return static_cast<size_t>(size.d_width * size.d_height * 2);
case Texture::PixelFormat::Pvrtc2:
return (static_cast<size_t>(size.d_width * size.d_height) * 2 + 7) / 8;
case Texture::PixelFormat::Pvrtc4:
return (static_cast<size_t>(size.d_width * size.d_height) * 4 + 7) / 8;
case Texture::PixelFormat::RgbaDxt1:
return static_cast<size_t>( std::ceil(size.d_width / 4) * std::ceil(size.d_height / 4) * 8 );
case Texture::PixelFormat::RgbaDxt3:
case Texture::PixelFormat::RgbaDxt5:
return static_cast<size_t>( std::ceil(size.d_width / 4) * std::ceil(size.d_height / 4) * 16 );
default:
return 0;
}
}
//----------------------------------------------------------------------------//
std::uint32_t OgreTexture::d_textureNumber = 0;
//----------------------------------------------------------------------------//
OgreTexture::OgreTexture(const String& name, bool notNullTexture) :
#ifdef CEGUI_USE_OGRE_TEXTURE_GPU
d_texture(0),
#endif
d_isLinked(false),
d_size(0, 0),
d_dataSize(0, 0),
d_texelScaling(0, 0),
d_name(name)
{
#ifdef CEGUI_USE_OGRE_TEXTURE_GPU
if (notNullTexture)
createOgreTexture();
#else
createEmptyOgreTexture();
#endif
}
//----------------------------------------------------------------------------//
OgreTexture::OgreTexture(const String& name, const String& filename,
const String& resourceGroup) :
#ifdef CEGUI_USE_OGRE_TEXTURE_GPU
d_texture(0),
#endif
d_isLinked(false),
d_size(0, 0),
d_dataSize(0, 0),
d_texelScaling(0, 0),
d_name(name)
{
loadFromFile(filename, resourceGroup);
}
//----------------------------------------------------------------------------//
OgreTexture::OgreTexture(const String& name, const Sizef& sz) :
#ifdef CEGUI_USE_OGRE_TEXTURE_GPU
d_texture(0),
#endif
d_isLinked(false),
d_size(0, 0),
d_dataSize(0, 0),
d_texelScaling(0, 0),
d_name(name)
{
#ifdef CEGUI_USE_OGRE_TEXTURE_GPU
const Ogre::uint32 width = static_cast<Ogre::uint32>(sz.d_width);
const Ogre::uint32 height = static_cast<Ogre::uint32>(sz.d_height);
createOgreTexture(Ogre::PFG_RGBA8_UNORM, width, height);
#if 0
size_t bytesPerRow = Ogre::PixelFormatGpuUtils::getBytesPerPixel( d_texture->getPixelFormat() ) * width;
void* data = OGRE_MALLOC_SIMD( bytesPerRow * height, Ogre::MEMCATEGORY_RENDERSYS );
memset( data, 0, bytesPerRow * height );
Ogre::TextureGpuManager *textureMgr = Ogre::Root::getSingletonPtr()->getRenderSystem()->getTextureGpuManager();
Ogre::StagingTexture *stagingTexture = textureMgr->getStagingTexture(
width, height, 1u, 1u, d_texture->getPixelFormat() );
stagingTexture->startMapRegion();
Ogre::TextureBox box = stagingTexture->mapRegion( width, height, 1u, 1u, d_texture->getPixelFormat() );
box.copyFrom( data, width, height, bytesPerRow );
stagingTexture->stopMapRegion();
stagingTexture->upload( box, d_texture, 0, nullptr, nullptr, true );
textureMgr->removeStagingTexture( stagingTexture );
OGRE_FREE_SIMD(data, Ogre::MEMCATEGORY_RENDERSYS);
#if OGRE_VERSION_MINOR == 2
d_texture->notifyDataIsReady();
#endif
#endif
#else
d_texture = Ogre::TextureManager::getSingleton().createManual(
getUniqueName(), "General", Ogre::TEX_TYPE_2D,
sz.d_width, sz.d_height, 0,
Ogre::PF_A8B8G8R8);
#endif // CEGUI_USE_OGRE_TEXTURE_GPU
// throw exception if no texture was able to be created
if (OGRE_ISNULL(d_texture))
throw RendererException(
"Failed to create Texture object with spcecified size.");
d_size.d_width = static_cast<float>(d_texture->getWidth());
d_size.d_height = static_cast<float>(d_texture->getHeight());
d_dataSize = sz;
updateCachedScaleValues();
}
//----------------------------------------------------------------------------//
#ifdef CEGUI_USE_OGRE_TEXTURE_GPU
OgreTexture::OgreTexture(const String& name, Ogre::TextureGpu* tex,
bool take_ownership) :
d_texture(0),
#else
OgreTexture::OgreTexture(const String& name, Ogre::TexturePtr& tex,
bool take_ownership) :
#endif // CEGUI_USE_OGRE_TEXTURE_GPU
d_isLinked(false),
d_size(0, 0),
d_dataSize(0, 0),
d_texelScaling(0, 0),
d_name(name)
{
setOgreTexture(tex, take_ownership);
}
//----------------------------------------------------------------------------//
OgreTexture::~OgreTexture()
{
freeOgreTexture();
}
//----------------------------------------------------------------------------//
const String& OgreTexture::getName() const
{
return d_name;
}
//----------------------------------------------------------------------------//
const Sizef& OgreTexture::getSize() const
{
return d_size;
}
//----------------------------------------------------------------------------//
const Sizef& OgreTexture::getOriginalDataSize() const
{
return d_dataSize;
}
//----------------------------------------------------------------------------//
const glm::vec2& OgreTexture::getTexelScaling() const
{
return d_texelScaling;
}
//----------------------------------------------------------------------------//
void OgreTexture::loadFromFile(const String& filename,
const String& resourceGroup)
{
// get and check existence of CEGUI::System object
System* sys = System::getSingletonPtr();
if (!sys)
throw RendererException(
"CEGUI::System object has not been created!");
// load file to memory via resource provider
RawDataContainer texFile;
sys->getResourceProvider()->loadRawDataContainer(filename, texFile,
resourceGroup);
ImageCodec& ic(sys->getImageCodec());
// if we're using the integrated Ogre codec, set the file-type hint string
if (ic.getIdentifierString().substr(0, 14) == "OgreImageCodec")
{
String type;
String::size_type i = filename.find_last_of(".");
if (i != String::npos && filename.length() - i > 1)
type = filename.substr(i+1);
static_cast<OgreImageCodec&>(ic).setImageFileDataType(type);
}
Texture* res = sys->getImageCodec().load(texFile, this);
// unload file data buffer
sys->getResourceProvider()->unloadRawDataContainer(texFile);
// throw exception if data was load loaded to texture.
if (!res)
throw RendererException(
sys->getImageCodec().getIdentifierString() +
" failed to load image '" + filename + "'.");
}
//----------------------------------------------------------------------------//
void OgreTexture::loadFromMemory(const void* buffer, const Sizef& buffer_size,
PixelFormat pixel_format)
{
using namespace Ogre;
if (!isPixelFormatSupported(pixel_format))
throw InvalidRequestException(
"Data was supplied in an unsupported pixel format.");
#ifdef CEGUI_USE_OGRE_TEXTURE_GPU
Ogre::PixelFormatGpu ogrePixelFormat = toOgrePixelFormat(pixel_format);
const std::uint32_t width = static_cast<std::uint32_t>(buffer_size.d_width);
const std::uint32_t height = static_cast<std::uint32_t>(buffer_size.d_height);
size_t bytesPerPixel = Ogre::PixelFormatGpuUtils::getBytesPerPixel(ogrePixelFormat);
size_t bytesPerRow = bytesPerPixel * width;
Ogre::TextureBox srcBox( width, height, 1u, 1u, bytesPerPixel, bytesPerRow, bytesPerRow * height );
srcBox.data = const_cast<void*>( buffer );
Ogre::TextureBox dstBox( width, height, 1u, 1u, 0, 0, 0 );
if ( pixel_format == CEGUI::Texture::PixelFormat::Rgb )
{
// We need to expand the 24bpp RGB texture to 32bpp RGBA.
// This is because OGRE 2.2 no longer supports RGB
PixelFormatGpu ogrePixelFormatDst = toOgrePixelFormat(CEGUI::Texture::PixelFormat::Rgba);
dstBox.bytesPerPixel = Ogre::PixelFormatGpuUtils::getBytesPerPixel(ogrePixelFormatDst);
dstBox.bytesPerRow = dstBox.bytesPerPixel * width;
dstBox.bytesPerImage = dstBox.bytesPerRow * height;
dstBox.data = new char[dstBox.bytesPerImage];
Ogre::PixelFormatGpuUtils::bulkPixelConversion(
srcBox, ogrePixelFormat,
dstBox, ogrePixelFormatDst
);
ogrePixelFormat = ogrePixelFormatDst;
}
createOgreTexture(ogrePixelFormat, width, height);
// build a staging texture that we'll use to upload into.
Ogre::TextureGpuManager *textureMgr = Ogre::Root::getSingletonPtr()->getRenderSystem()->getTextureGpuManager();
StagingTexture* stagingTexture = textureMgr->getStagingTexture(width, height, 1u, 1u, ogrePixelFormat);
// map a region and copy data into it
stagingTexture->startMapRegion();
TextureBox box = stagingTexture->mapRegion(width, height, 1u, 1u, ogrePixelFormat);
if ( pixel_format == CEGUI::Texture::PixelFormat::Rgb )
box.copyFrom(dstBox);
else
box.copyFrom(srcBox);
stagingTexture->stopMapRegion();
// trigger upload to the gpu in the defined texture.
stagingTexture->upload(box, d_texture, 0, nullptr, nullptr, true);
if (dstBox.data)
delete static_cast<char*>(dstBox.data);
// remove the staging texture and notify that the texture is finished
textureMgr->removeStagingTexture(stagingTexture);
#if OGRE_VERSION_MINOR == 2
d_texture->notifyDataIsReady();
#endif
#else
const size_t byte_size = calculateDataSize(buffer_size, pixel_format);
char* bufferCopy = new char[byte_size];
memcpy(bufferCopy, buffer, byte_size);
const Ogre::PixelBox* pixelBox = new Ogre::PixelBox(static_cast<std::uint32_t>(buffer_size.d_width), static_cast<std::uint32_t>(buffer_size.d_height),
1, toOgrePixelFormat(pixel_format), bufferCopy);
createEmptyOgreTexture(pixel_format);
d_texture->freeInternalResources();
d_texture->setWidth(static_cast<std::uint32_t>(buffer_size.d_width));
d_texture->setHeight(static_cast<std::uint32_t>(buffer_size.d_height));
d_texture->setDepth(1);
d_texture->createInternalResources();
d_texture->getBuffer(0,0).get()->blitFromMemory(*pixelBox);
#endif // CEGUI_USE_OGRE_TEXTURE_GPU
// throw exception if no texture was able to be created
if (OGRE_ISNULL(d_texture))
throw RendererException(
"Failed to blit to Texture from memory.");
d_size.d_width = static_cast<float>(d_texture->getWidth());
d_size.d_height = static_cast<float>(d_texture->getHeight());
d_dataSize = buffer_size;
updateCachedScaleValues();
}
//----------------------------------------------------------------------------//
void OgreTexture::blitFromMemory(const void* sourceData, const Rectf& area)
{
if (OGRE_ISNULL(d_texture)) // TODO: exception?
return;
// Ogre doesn't like null data, so skip if the sourceData is null and
// area is zero size
if (sourceData == nullptr)
{
if (static_cast<int>(area.getWidth()) == 0 &&
static_cast<int>(area.getHeight()) == 0)
{
return;
}
// Here we are trying to write to a non-zero size area with null
// ptr for data
throw RendererException("blitFromMemory source is null");
}
#ifdef CEGUI_USE_OGRE_TEXTURE_GPU
Ogre::uint32 width = static_cast<Ogre::uint32>(area.getWidth());
Ogre::uint32 height = static_cast<Ogre::uint32>(area.getHeight());
size_t bytesPerPixel = Ogre::PixelFormatGpuUtils::getBytesPerPixel(d_texture->getPixelFormat());
size_t bytesPerRow = bytesPerPixel * width;
// acquire a staging texture
Ogre::TextureGpuManager *textureMgr = Ogre::Root::getSingletonPtr()->getRenderSystem()->getTextureGpuManager();
Ogre::StagingTexture *stagingTexture = textureMgr->getStagingTexture(
width, height, 1u, 1u, d_texture->getPixelFormat());
// setup the map region that we'll copy to
stagingTexture->startMapRegion();
Ogre::TextureBox box = stagingTexture->mapRegion( width, height, 1u, 1u, d_texture->getPixelFormat());
box.copyFrom(const_cast<void*>( sourceData ), width, height, bytesPerRow);
stagingTexture->stopMapRegion();
// upload the data to the gpu
// We specify a destination area based on the area rect provided as we may
// only want to upload a portion to the GPU texture area and not the entire thing.
Ogre::TextureBox dst;
dst.x = static_cast<Ogre::uint32>( area.left() );
dst.y = static_cast<Ogre::uint32>( area.top() );
dst.width = width;
dst.height = height;
dst.depth = 1u;
dst.numSlices = 1u;
stagingTexture->upload( box, d_texture, 0, nullptr, &dst );
// remove the staging texture and notify texture is prepared
textureMgr->removeStagingTexture( stagingTexture );
#else
// NOTE: const_cast because Ogre takes pointer to non-const here. Rather
// than allow that to dictate poor choices in our own APIs, we choose to
// address the issue as close to the source of the problem as possible.
Ogre::PixelBox pb(static_cast<Ogre::uint32>(area.getWidth()),
static_cast<Ogre::uint32>(area.getHeight()),
1,
d_texture->getFormat(), const_cast<void*>(sourceData));
Ogre::Box box(static_cast<Ogre::uint32>(area.left()),
static_cast<Ogre::uint32>(area.top()),
static_cast<Ogre::uint32>(area.right()),
static_cast<Ogre::uint32>(area.bottom()) );
d_texture->getBuffer()->blitFromMemory(pb, box);
#endif // CEGUI_USE_OGRE_TEXTURE_GPU
}
//----------------------------------------------------------------------------//
void OgreTexture::blitToMemory(void* targetData)
{
if (OGRE_ISNULL(d_texture)) // TODO: exception?
return;
#ifdef CEGUI_USE_OGRE_TEXTURE_GPU
throw RendererException("Unimplemented: blitToMemory for Ogre >= 2.2");
#else
Ogre::PixelBox pb(static_cast<std::uint32_t>(d_size.d_width), static_cast<std::uint32_t>(d_size.d_height),
1, d_texture->getFormat(), targetData);
d_texture->getBuffer()->blitToMemory(pb);
#endif // CEGUI_USE_OGRE_TEXTURE_GPU
}
//----------------------------------------------------------------------------//
void OgreTexture::freeOgreTexture()
{
if (!OGRE_ISNULL(d_texture) && !d_isLinked) {
#ifdef CEGUI_USE_OGRE_TEXTURE_GPU
Ogre::Root::getSingletonPtr()->getRenderSystem()->getTextureGpuManager()->destroyTexture(d_texture);
#else
Ogre::TextureManager::getSingleton().remove(d_texture->getHandle());
#endif // CEGUI_USE_OGRE_TEXTURE_GPU
}
#ifdef CEGUI_USE_OGRE_TEXTURE_GPU
d_texture = 0;
#else
OGRE_RESET(d_texture);
#endif // CEGUI_USE_OGRE_TEXTURE_GPU
}
//----------------------------------------------------------------------------//
Ogre::String OgreTexture::getUniqueName()
{
#if OGRE_VERSION < 0x10A00
Ogre::StringUtil::StrStreamType strstream;
strstream << "_cegui_ogre_" << d_textureNumber++;
return strstream.str();
#endif
#if OGRE_VERSION >= 0x10A00
Ogre::StringStream strstream;
strstream << "_cegui_ogre_" << d_textureNumber++;
return strstream.str();
#endif
}
//----------------------------------------------------------------------------//
void OgreTexture::updateCachedScaleValues()
{
//
// calculate what to use for x scale
//
const float orgW = d_dataSize.d_width;
const float texW = d_size.d_width;
// if texture and original data width are the same, scale is based
// on the original size.
// if texture is wider (and source data was not stretched), scale
// is based on the size of the resulting texture.
d_texelScaling.x = 1.0f / ((orgW == texW) ? orgW : texW);
//
// calculate what to use for y scale
//
const float orgH = d_dataSize.d_height;
const float texH = d_size.d_height;
// if texture and original data height are the same, scale is based
// on the original size.
// if texture is taller (and source data was not stretched), scale
// is based on the size of the resulting texture.
d_texelScaling.y = 1.0f / ((orgH == texH) ? orgH : texH);
}
//----------------------------------------------------------------------------//
#ifdef CEGUI_USE_OGRE_TEXTURE_GPU
void OgreTexture::setOgreTexture(Ogre::TextureGpu* texture, bool take_ownership)
#else
void OgreTexture::setOgreTexture(Ogre::TexturePtr texture, bool take_ownership)
#endif // CEGUI_USE_OGRE_TEXTURE_GPU
{
freeOgreTexture();
d_texture = texture;
d_isLinked = !take_ownership;
if (!OGRE_ISNULL(d_texture))
{
d_size.d_width = static_cast<float>(d_texture->getWidth());
d_size.d_height= static_cast<float>(d_texture->getHeight());
d_dataSize = d_size;
}
else
d_size = d_dataSize = Sizef(0, 0);
updateCachedScaleValues();
}
//----------------------------------------------------------------------------//
#ifdef CEGUI_USE_OGRE_TEXTURE_GPU
Ogre::TextureGpu* OgreTexture::getOgreTexture() const
{
return d_texture;
}
#else
Ogre::TexturePtr OgreTexture::getOgreTexture() const
{
return d_texture;
}
#endif // CEGUI_USE_OGRE_TEXTURE_GPU
//----------------------------------------------------------------------------//
bool OgreTexture::textureIsLinked() const
{
return d_isLinked;
}
//----------------------------------------------------------------------------//
bool OgreTexture::isPixelFormatSupported(const PixelFormat fmt) const
{
try
{
#ifdef CEGUI_USE_OGRE_TEXTURE_GPU
OgreTexture::toOgrePixelFormat(fmt);
return true;
#else
return Ogre::TextureManager::getSingleton().
isEquivalentFormatSupported(Ogre::TEX_TYPE_2D,
toOgrePixelFormat(fmt),
Ogre::TU_DEFAULT);
#endif // CEGUI_USE_OGRE_TEXTURE_GPU
}
catch (InvalidRequestException&)
{
return false;
}
}
//----------------------------------------------------------------------------//
#ifdef CEGUI_USE_OGRE_TEXTURE_GPU
Ogre::PixelFormatGpu OgreTexture::toOgrePixelFormat(const Texture::PixelFormat fmt)
{
switch (fmt)
{
case Texture::PixelFormat::Rgba: return Ogre::PFG_RGBA8_UNORM;
case Texture::PixelFormat::Rgb: return Ogre::PFG_RGB8_UNORM;
case Texture::PixelFormat::Rgb565: return Ogre::PFG_B5G6R5_UNORM;
case Texture::PixelFormat::Rgba4444: return Ogre::PFG_B4G4R4A4_UNORM;
case Texture::PixelFormat::Pvrtc2: return Ogre::PFG_PVRTC_RGBA2;
case Texture::PixelFormat::Pvrtc4: return Ogre::PFG_PVRTC_RGBA4;
case Texture::PixelFormat::RgbaDxt1: return Ogre::PFG_BC1_UNORM;
case Texture::PixelFormat::RgbaDxt3: return Ogre::PFG_BC2_UNORM;
case Texture::PixelFormat::RgbaDxt5: return Ogre::PFG_BC3_UNORM;
default:
throw InvalidRequestException(
"Invalid pixel format translation.");
}
}
//----------------------------------------------------------------------------//
Texture::PixelFormat OgreTexture::fromOgrePixelFormat(
const Ogre::PixelFormatGpu fmt)
{
switch (fmt)
{
case Ogre::PFG_RGBA8_UNORM: return Texture::PixelFormat::Rgba;
case Ogre::PFG_RGBA8_UNORM_SRGB: return Texture::PixelFormat::Rgba;
case Ogre::PFG_BGRA8_UNORM: return Texture::PixelFormat::Rgba;
case Ogre::PFG_BGRA8_UNORM_SRGB: return Texture::PixelFormat::Rgba;
case Ogre::PFG_RGB8_UNORM: return Texture::PixelFormat::Rgb;
case Ogre::PFG_RGB8_UNORM_SRGB: return Texture::PixelFormat::Rgb;
case Ogre::PFG_BGR8_UNORM: return Texture::PixelFormat::Rgb;
case Ogre::PFG_BGR8_UNORM_SRGB: return Texture::PixelFormat::Rgb;
case Ogre::PFG_B5G6R5_UNORM: return Texture::PixelFormat::Rgb565;
case Ogre::PFG_B4G4R4A4_UNORM: return Texture::PixelFormat::Rgba4444;
case Ogre::PFG_PVRTC_RGBA2: return Texture::PixelFormat::Pvrtc2;
case Ogre::PFG_PVRTC_RGBA4: return Texture::PixelFormat::Pvrtc4;
case Ogre::PFG_BC1_UNORM: return Texture::PixelFormat::RgbaDxt1;
case Ogre::PFG_BC1_UNORM_SRGB: return Texture::PixelFormat::RgbaDxt1;
case Ogre::PFG_BC2_UNORM: return Texture::PixelFormat::RgbaDxt3;
case Ogre::PFG_BC2_UNORM_SRGB: return Texture::PixelFormat::RgbaDxt3;
case Ogre::PFG_BC3_UNORM: return Texture::PixelFormat::RgbaDxt5;
case Ogre::PFG_BC3_UNORM_SRGB: return Texture::PixelFormat::RgbaDxt5;
default:
throw InvalidRequestException(
"Invalid pixel format translation.");
}
}
#else
Ogre::PixelFormat OgreTexture::toOgrePixelFormat(const Texture::PixelFormat fmt)
{
switch (fmt)
{
case Texture::PixelFormat::Rgba: return Ogre::PF_A8B8G8R8;
case Texture::PixelFormat::Rgb: return Ogre::PF_B8G8R8;
case Texture::PixelFormat::Rgb565: return Ogre::PF_R5G6B5;
case Texture::PixelFormat::Rgba4444: return Ogre::PF_A4R4G4B4;
case Texture::PixelFormat::Pvrtc2: return Ogre::PF_PVRTC_RGBA2;
case Texture::PixelFormat::Pvrtc4: return Ogre::PF_PVRTC_RGBA4;
case Texture::PixelFormat::RgbaDxt1: return Ogre::PF_DXT1;
case Texture::PixelFormat::RgbaDxt3: return Ogre::PF_DXT3;
case Texture::PixelFormat::RgbaDxt5: return Ogre::PF_DXT5;
default:
throw InvalidRequestException(
"Invalid pixel format translation.");
}
}
//----------------------------------------------------------------------------//
Texture::PixelFormat OgreTexture::fromOgrePixelFormat(
const Ogre::PixelFormat fmt)
{
switch (fmt)
{
case Ogre::PF_A8R8G8B8: return Texture::PixelFormat::Rgba;
case Ogre::PF_A8B8G8R8: return Texture::PixelFormat::Rgba;
case Ogre::PF_R8G8B8: return Texture::PixelFormat::Rgb;
case Ogre::PF_B8G8R8: return Texture::PixelFormat::Rgb;
case Ogre::PF_R5G6B5: return Texture::PixelFormat::Rgb565;
case Ogre::PF_A4R4G4B4: return Texture::PixelFormat::Rgba4444;
case Ogre::PF_PVRTC_RGBA2: return Texture::PixelFormat::Pvrtc2;
case Ogre::PF_PVRTC_RGBA4: return Texture::PixelFormat::Pvrtc4;
case Ogre::PF_DXT1: return Texture::PixelFormat::RgbaDxt1;
case Ogre::PF_DXT3: return Texture::PixelFormat::RgbaDxt3;
case Ogre::PF_DXT5: return Texture::PixelFormat::RgbaDxt5;
default:
throw InvalidRequestException(
"Invalid pixel format translation.");
}
}
#endif // CEGUI_USE_OGRE_TEXTURE_GPU
//----------------------------------------------------------------------------//
#ifdef CEGUI_USE_OGRE_TEXTURE_GPU
void OgreTexture::createOgreTexture(
Ogre::PixelFormatGpu pixel_format,
std::uint32_t width, std::uint32_t height,
Ogre::GpuPageOutStrategy::GpuPageOutStrategy pageOutStrategy
) {
Ogre::TextureGpuManager *textureMgr = Ogre::Root::getSingletonPtr()->getRenderSystem()->getTextureGpuManager();
d_texture = textureMgr->createOrRetrieveTexture(
getUniqueName(),
pageOutStrategy,
Ogre::TextureFlags::ManualTexture,
Ogre::TextureTypes::Type2D,
Ogre::BLANKSTRING,
0u );
d_texture->setPixelFormat(pixel_format);
d_texture->setNumMipmaps(1u);
d_texture->setResolution(width, height);
// schedule texture to be transitioned to the gpu
d_texture->_transitionTo( Ogre::GpuResidency::Resident, nullptr );
d_texture->_setNextResidencyStatus( Ogre::GpuResidency::Resident );
}
#else
void OgreTexture::createEmptyOgreTexture(PixelFormat pixel_format)
{
// try to create a Ogre::Texture with given dimensions
d_texture = Ogre::TextureManager::getSingleton().createManual(
getUniqueName(), "General", Ogre::TEX_TYPE_2D,
1, 1, 0,
toOgrePixelFormat(pixel_format));
}
#endif // CEGUI_USE_OGRE_TEXTURE_GPU
//----------------------------------------------------------------------------//
} // End of CEGUI namespace section
|
#include "RobotMovingFunctions.h"
int time_on_black = 0;
int time_on_white = 0;
void setup()
{
setIOpins();
}
void loop()
{
int lightSensorValue= analogRead(A1);
if ( lightSensorValue < 400 )
{
// BLACK area
robotLeft();
time_on_white = 0; // reset time on white
time_on_black++; // meas. time on black
delay(100);
}
else
{
// WHITE area
robotRight();
// Do similar meas.
// of time on white
delay(100);
// If time is signif.
// longer:
// robotStop();exit(0);
}
}
|
/*
2019 Oku Dan / oku_dan@yahoo.co.jp
STMicroelectronics社製LPS331AP用のI2C版ライブラリです.
使用する際はデバイスのSDAとSCLをセンサに接続してください.
内部プルアップではないので注意.
1.LPS_331AP型クラスを作成
2.Initialize()で初期化
3.Wire.setClock(400000L)でI2Cを高速モードにするとよい
4.ReadPrs(&prs),ReadTmp(&tmp)で気圧、気温読み出し
5.4に戻る
49行目ODRでサンプリングレートを変更できる(デフォルトは25Hz,25Hz)
このセンサの更新速度にデバイス側で合わせて読みだせばSTATUS_REGのチェックが不要になる
*/
#include "I2CHandler.h"
#define LPS331AP_ADDR0 0b1011100 //SA0=L(GND)
#define LPS331AP_ADDR1 0b1011101 //SA0=H(VDD)
#define LPS331AP_REF_P_XL 0x08
#define LPS331AP_REF_P_L 0x09
#define LPS331AP_REF_P_H 0x0A
#define LPS331AP_WHO_AM_I 0x0F
#define LPS331AP_WHO_AM_I_DEFAULT 0xBB
#define LPS331AP_RES_CONF 0x10
#define LPS331AP_CTRL_REG1 0x20
#define LPS331AP_CTRL_REG2 0x21
#define LPS331AP_CTRL_REG3 0x22
#define LPS331AP_INTERRUPT_CFG 0x23
#define LPS331AP_INT_SOURCE 0x24
#define LPS331AP_THS_P_L 0x25
#define LPS331AP_THS_P_H 0x26
#define LPS331AP_STATUS_REG 0x27
#define LPS331AP_PRESS_OUT_XL 0x28
#define LPS331AP_PRESS_OUT_L 0x29
#define LPS331AP_PRESS_OUT_H 0x2A
#define LPS331AP_TEMP_OUT_L 0x2B
#define LPS331AP_TEMP_OUT_H 0x2C
#define LPS331AP_AMP_CTRL 0x30
#define LPS331AP_DELTA_PRESS_XL 0x3C
#define LPS331AP_DELTA_PRESS_L 0x3D
#define LPS331AP_DELTA_PRESS_H 0x3E
#define LPS331AP_ODR 0b111
// (Hz) pressure Temperature
// 000 - One Shot One Shot
// 001 - 1 1
// 010 - 7 1
// 011 - 12.5 1
// 101 - 7 7
// 110 - 12.5 12.5
// 111 - 25 25
class LPS_331AP
{
private:
void RegistersInit();
uint8_t LPS331AP_ADDR;
public:
bool Initialize(uint8_t SA0);
bool Initialize();
bool ReadPrs(float *prs);
bool ReadTmp(float *tmp);
};
/*
#include <Wire.h>
void I2cWriteByte(uint8_t add, uint8_t reg, uint8_t data)
{
Wire.beginTransmission(add);
Wire.write(reg);
Wire.write(data);
Wire.endTransmission();
}
uint8_t I2cReadByte(uint8_t add, uint8_t reg)
{
Wire.beginTransmission(add);
Wire.write(reg);
Wire.endTransmission(false);
Wire.requestFrom(add, (uint8_t)1);
uint8_t data = Wire.read();
return data;
}
void I2cReadBytes(uint8_t add, uint8_t reg, uint8_t *data, uint8_t count)
{
byte retVal;
Wire.beginTransmission(add);
Wire.write(reg | 0x80);
Wire.endTransmission(false);
Wire.requestFrom(add, count);
for (int i = 0; i < count; i++)
{
data[i] = Wire.read();
}
}
*/
void LPS_331AP::RegistersInit(){
uint8_t tempRegValue = 0;
//Power down before change config
tempRegValue = 0;
I2cWriteByte(LPS331AP_ADDR, LPS331AP_CTRL_REG1, tempRegValue);
//Reference pressure
tempRegValue = 0;
I2cWriteByte(LPS331AP_ADDR, LPS331AP_REF_P_XL, tempRegValue);
I2cWriteByte(LPS331AP_ADDR, LPS331AP_REF_P_L, tempRegValue);
I2cWriteByte(LPS331AP_ADDR, LPS331AP_REF_P_H, tempRegValue);
//RES_CONF
//[RFU][AVGT2][AVGT1][AVGT0][AVGP3][AVGP2][AVGP1][AVGP0]
//RFU - reserved for future
//AVGT[2:0] - Temperature resolution configuration(Average of AVGT times)
// 000:1
// 001:2
// ~
// 111:128
//AVGP[3:0] - Pressure resolution configuration(Average of AVGP times)
// 0000:1
// 0001:2
// ~
// 1111:512
//Register configuration 7Ah not allowed with ODR = 25Hz/25Hz (Register CTRL_REG1).
//For ORD 25Hz/25Hz the suggested configuration for RES_CONF is 6Ah.
tempRegValue = 0b01111111;
if(LPS331AP_ODR == 0b111)tempRegValue = 0x6A; //= 0b01101010
I2cWriteByte(LPS331AP_ADDR, LPS331AP_RES_CONF, tempRegValue);
//CTRL_REG2
//[BOOT][RESERVED][RESERVED][RESERVED][RESERVED][SWRESET][AUTO_ZERO][ONE_SHOT]
//BOOT - Reboot memory content. Default value: 0
//SWRESET - Software reset. Default value: 0
//AUTO_ZERO - Autozero enable. Default value: 0
//ONE_SHOT - One shot enable. Default value: 0
tempRegValue = 0;
I2cWriteByte(LPS331AP_ADDR, LPS331AP_CTRL_REG2, tempRegValue);
//CTRL_REG3
//INTERRUPT_CFG
//INT_SOURCE
//THS_P_L
//THS_P_H
//To set about interrupt.
tempRegValue = 0;
I2cWriteByte(LPS331AP_ADDR, LPS331AP_CTRL_REG3, tempRegValue);
I2cWriteByte(LPS331AP_ADDR, LPS331AP_INTERRUPT_CFG, tempRegValue);
I2cWriteByte(LPS331AP_ADDR, LPS331AP_INT_SOURCE, tempRegValue);
I2cWriteByte(LPS331AP_ADDR, LPS331AP_THS_P_L, tempRegValue);
I2cWriteByte(LPS331AP_ADDR, LPS331AP_THS_P_H, tempRegValue);
//CTRL_REG1
//[PD][ODR2][ODR1][ODR0][DIFF_EN][DBDU][DELTA_EN][SIM]
//PD - PD: power down control(0: power-down mode; 1: active mode)
//ODR[2:0] - output data rate selection
//DIFF_EN - Interrupt circuit enable.(0: interrupt generation disabled; 1: interrupt circuit enabled)
//DBDU - block data update(0: continuous update 1: output registers not updated until MSB and LSB reading)
//DELTA_EN - delta pressure enable(1: delta pressure registers enabled. 0: disable)
//SIM - SPI Serial Interface Mode selection.(0: 4-wire interface; 1: 3-wire interface)
tempRegValue = 0b10000100;
tempRegValue |= LPS331AP_ODR << 4;
I2cWriteByte(LPS331AP_ADDR, LPS331AP_CTRL_REG1, tempRegValue);
return;
}
bool LPS_331AP::Initialize(uint8_t SA0){
uint8_t Test = I2cReadByte((SA0 == 1 ? LPS331AP_ADDR1 : LPS331AP_ADDR0), LPS331AP_WHO_AM_I);
return Test == LPS331AP_WHO_AM_I_DEFAULT;
}
bool LPS_331AP::Initialize(){
I2cInitialize();
if(Initialize(0))LPS331AP_ADDR = LPS331AP_ADDR0;
else if(Initialize(1))LPS331AP_ADDR = LPS331AP_ADDR1;
else return false;
RegistersInit();
return true;
}
bool LPS_331AP::ReadPrs(float *prs){
uint8_t status;
//STATUS_REG
//[0][0][P_OR][T_OR][0][0][P_DA][T_DA]
//P_OR - Pressure data overrun.Sampling rate is too fast.
//T_OR - Temperature data overrun.
//P_DA - Pressure data available.
//T_DA - Temperature data available.
status = I2cReadByte(LPS331AP_ADDR, LPS331AP_STATUS_REG);
if((status & 0b00000010) != 0){
uint8_t prsTempXL,prsTempL,prsTempH;
prsTempXL = I2cReadByte(LPS331AP_ADDR, LPS331AP_PRESS_OUT_XL);
prsTempL = I2cReadByte(LPS331AP_ADDR, LPS331AP_PRESS_OUT_L);
prsTempH = I2cReadByte(LPS331AP_ADDR, LPS331AP_PRESS_OUT_H);
*prs = ((uint32_t)prsTempH << 16 | (uint16_t)prsTempL << 8 | prsTempXL) / 4096.0f;
return true;
}
else return false;
}
bool LPS_331AP::ReadTmp(float *tmp){
uint8_t status;
status = I2cReadByte(LPS331AP_ADDR, LPS331AP_STATUS_REG);
if((status & 0b00000001) != 0){
uint8_t tmpTempL,tmpTempH;
tmpTempL = I2cReadByte(LPS331AP_ADDR, LPS331AP_TEMP_OUT_L);
tmpTempH = I2cReadByte(LPS331AP_ADDR, LPS331AP_TEMP_OUT_H);
*tmp = 42.5 + (int16_t)(tmpTempH << 8 | tmpTempL) / 480.0f;
return true;
}
else return false;
}
|
/***************************************************************************
# Copyright (c) 2020, NVIDIA CORPORATION. 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 NVIDIA CORPORATION 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 "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 "stdafx.h"
#include "AliasTable.h"
namespace Falcor
{
AliasTable::SharedPtr AliasTable::create(std::vector<float> weights, std::mt19937& rng)
{
return SharedPtr(new AliasTable(std::move(weights), rng));
}
void AliasTable::setShaderData(const ShaderVar& var) const
{
var["items"] = mpItems;
var["weights"] = mpWeights;
var["count"] = mCount;
var["weightSum"] = (float)mWeightSum;
}
AliasTable::AliasTable(std::vector<float> weights, std::mt19937& rng)
: mCount((uint32_t)weights.size())
{
if (weights.size() > std::numeric_limits<uint32_t>::max()) throw std::exception("Too many entries for alias table.");
std::uniform_int_distribution<uint32_t> rngDist;
mpWeights = Buffer::createStructured(sizeof(float), mCount, Resource::BindFlags::ShaderResource, Buffer::CpuAccess::None, weights.data());
mWeightSum = 0.0;
for (float f : weights) mWeightSum += f;
double factor = mCount / mWeightSum;
for (float& f : weights) f = (float)(f * factor);
std::vector<uint32_t> permutation(mCount);
for (uint32_t i = 0; i < mCount; ++i) permutation[i] = i;
std::sort(permutation.begin(), permutation.end(), [&](uint32_t a, uint32_t b) { return weights[a] < weights[b]; });
std::vector<float> thresholds(mCount);
std::vector<uint32_t> redirect(mCount);
std::vector<uint2> mergedTable(mCount);
uint32_t head = 0;
uint32_t tail = mCount - 1;
while (head != tail)
{
int i = permutation[head];
int j = permutation[tail];
thresholds[i] = weights[i];
redirect[i] = j;
weights[j] -= 1.f - weights[i];
if (head == tail - 1)
{
thresholds[j] = 1.f;
redirect[j] = j;
break;
}
else if (weights[j] < 1.f)
{
std::swap(permutation[head], permutation[tail]);
tail--;
}
else
{
head++;
}
}
for (uint32_t i = 0; i < mCount; ++i)
{
permutation[i] = i;
}
for (uint32_t i = 0; i < mCount; ++i)
{
uint32_t dst = i + (rngDist(rng) % (mCount - i));
std::swap(thresholds[i], thresholds[dst]);
std::swap(redirect[i], redirect[dst]);
std::swap(permutation[i], permutation[dst]);
}
struct Item
{
float threshold;
uint32_t indexA;
uint32_t indexB;
uint32_t _pad;
};
std::vector<Item> items(mCount);
for (uint32_t i = 0; i < mCount; ++i)
{
items[i] = { thresholds[i], redirect[i], permutation[i], 0 };
}
mpItems = Buffer::createStructured(sizeof(Item), mCount, Resource::BindFlags::ShaderResource, Buffer::CpuAccess::None, items.data());
}
}
|
#include "../lib/Right_func.h"
double right04_func(float **P_now,float **P_pre,float **P_aft,
float **Px_now,float **Px_pre,float **Px_aft,
float **Pz_now,float **Pz_pre,float **Pz_aft,
float **Vx_now,float **Vx_pre,float **Vx_aft,
float **Vz_now,float **Vz_pre,float **Vz_aft,
float **K_now,float **K_pre,float **K_aft,
float **Psa_now,float **Psa_pre,float **Psa_aft,
float **Cita_now,float **Cita_pre,float **Cita_aft,
float **V,float **Vv,float **DEN,
float **absorbx,float **absorbz,struct PARAMETER *param,
float wavelet)
{
int i,j;
for(i=param->NX+param->PML;i<param->Nx-8; i++)
{
for(j=8; j<param->Nz-8; j++)
{
Cita_aft[i][j]=1.0/(1.0+0.5*param->dt*absorbx[i][j])*(
(1.0-0.5*param->dt*absorbx[i][j])*
Cita_now[i][j]+param->dt*Psa_aft[i][j]);
}
}
return 0.0;
}
|
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
using vi = vector<int>;
#define pb push_back
#define all(x) x.begin(), x.end()
#define rep(i, a, b) for(ll i = a; i < b; ++i)
#define rsz(x, n) x.resize(n)
using pi = pair<int, int>;
#define f first
#define s second
void setIO(string name = "countcross") {
ios_base::sync_with_stdio(0); cin.tie(0);
if (name.size()) {
freopen((name + ".in").c_str(), "r", stdin);
freopen((name + ".out").c_str(), "w", stdout);
}
}
const int length = 199;
ll n, k, r;
ll board[length][length];
bool visited[length][length];
ll cnt = 0;
ll rcodes[length / 2 + 1][length / 2 + 1];
void dfs(ll x, ll y, ll px, ll py) {
if (x < 0 || x >= 2 * n || y < 0 || y >= 2 * n || visited[x][y] || board[(x + px) / 2][(y + py) / 2])
return;
visited[x][y] = true;
rcodes[x / 2][y / 2] = cnt;
vector<ll> dir = { 0, 2, 0, -2, 0 };
rep(i, 0, 4) {
ll dx = x + dir[i];
ll dy = y + dir[i + 1];
dfs(dx, dy, x, y);
}
}
int main()
{
setIO();
cin >> n >> k >> r;
rep(i, 0, r) {
ll x1, y1, x2, y2;
cin >> x1 >> y1 >> x2 >> y2;
--x1; --y1; --x2; --y2;
board[x1 + x2][y1 + y2] = 1;
}
for (ll i = 0; i < 2 * n; i += 2) {
for (ll j = 0; j < 2 * n; j += 2) {
if (!visited[i][j]) {
++cnt;
dfs(i, j, i, j);
}
}
}
vector<pair<ll, ll>> cows;
rep(i, 0, r) {
ll x, y; cin >> x >> y;
cows.push_back({ x - 1, y - 1 });
}
ll ans = 0;
rep(i, 0, k) {
rep(j, i + 1, k) {
if (rcodes[cows[i].first][cows[i].second] != rcodes[cows[j].first][cows[j].second])
++ans;
}
}
cout << ans << endl;
}
|
#include <bits/stdc++.h>
#include <cassert>
#define rep(i,n) for (int i = 0; i < (n); ++i)
#define ok() puts(ok?"Yes":"No");
template<class T> bool chmax(T &a, const T &b) { if(a < b) { a = b; return true; } return false; }
template<class T> bool chmin(T &a, const T &b) { if(a > b) { a = b; return true; } return false; }
using namespace std;
using ll = long long;
using vi = vector<int>;
using vll = vector<ll>;
using ii = pair<int, int>;
using vvi = vector<vi>;
using vii = vector<ii>;
using gt = greater<int>;
using minq = priority_queue<int, vector<int>, gt>;
using P = pair<ll,ll>;
const ll LINF = 1e18L + 1;
const int INF = 1e9 + 1;
//clang++ -std=c++11 -stdlib=libc++
int N;
vi to[100005];
int main() {
cin >> N;
rep(i,N-1) {
int a,b; cin >> a >> b; a--; b--;
to[a].push_back(b);
to[b].push_back(a);
}
minq q;
q.push(0);
vi ans;
vi visited(N);
visited[0] = 1;
while(q.size()) {
int v = q.top(); q.pop();
ans.push_back(v);
for (int u: to[v]) {
if (visited[u]) continue;
q.push(u);
visited[u] = 1;
}
}
assert(ans.size() == N);
rep(i,N) printf("%d%c", ans[i]+1, i==N-1?'\n':' ');
return 0;
}
|
#include "file_verifier.h"
#include "myqfileinfo.h"
#include "ui_appmainwindow.h"
#include <QDirIterator>
#include <QHash>
#include <QLabel>
#include <QMessageBox>
#include <QProgressBar>
#include <QMainWindow>
#include <QTransform>
#include <QPixmap>
#include <QThread>
#include <QTreeWidget>
#include <QStackedWidget>
#include <QPushButton>
#include <QUrl>
#ifndef FINDDUPLICATEFILES_H
#define FINDDUPLICATEFILES_H
class findDuplicateFiles : public QThread
{
public:
findDuplicateFiles();
void setFileAttribute(const QDir & path, const QStringList & fileTypes, Ui_AppMainWindow *ui); // ui contain all ui components reference Qlistview, QStackedWidget, prgressbar to see file scanning progress, next push button
// progressBarLabel is prgressbar label,
void run(); // call when thread is start
void stop(); // call for stop thread
private:
void findDuplicate(const QDir & path, const QStringList & fileTypes ,Ui_AppMainWindow *ui); // ui contain all ui components reference prgressIcon to see file scanning progress
void setDuplicateFilesRecordOnTree(const QString& fileName,int groupNo, const QString& filePath, const QString& fileSize, int entryColor); // add duplicate items in Qtreewidget list file name, file group number, file path, file size, entry text & background color 0 | 1, 0 for main entry, 1 for sub entry.
QHash<QString, myQFileInfo> nonDuplicateFilesRecord; // save record of multiple file with hash code
// duplicate key not exist in Qhash
QList<QString> duplicateFilesRecord; // save duplicate files as list
//int nonDuplicateFileCount=0; // save non duplicate file numbers
//int duplicateFileCount=0; // save duplicate files numbers
bool stopProgram; // for stop find file duplicate thread
// for setting attribute for thread
QDir path;
QStringList fileType;
Ui_AppMainWindow *ui; // ui pointer for access ui components
};
#endif // FINDDUPLICATEFILES_H
|
#include <iostream>
int main(void)
{
std::string str = "HI THIS IS BRAIN";
std::string *ptr = &str;
std::string &ref = str;
std::cout << "Printing pointer: " << *ptr << std::endl;
std::cout << "Printing reference: " << ref << std::endl;
}
|
#ifndef TRAFFIC_LIGHT_H
#define TRAFFIC_LIGHT_H
#include "recognitionVehicle.h"
#include "TrafficLightPins.h"
#include <stdio.h>
#include <vector>
#define RETURN_FLASHING_GREEN 2;
#define YELLOW_TIME 2
#define SECOND 1000
class MainTrafficLight {
private:
int greenTime = 5, redTime = 15;
int posledMainTLight = 0;
public:
MainTrafficLight();
void start(const Recognition& ptr);
};
class SecondTrafficLight {
private:
int greenTime = 15, redTime = 5;
int posledSecondaryTLight = 0;
public:
SecondTrafficLight();
void start(const Recognition& ptr);
};
#endif
|
/* Generated SBE (Simple Binary Encoding) message codec */
#ifndef _SBE_ORDERTYPE_H_
#define _SBE_ORDERTYPE_H_
#if defined(SBE_HAVE_CMATH)
/* cmath needed for std::numeric_limits<double>::quiet_NaN() */
# include <cmath>
# define SBE_FLOAT_NAN std::numeric_limits<float>::quiet_NaN()
# define SBE_DOUBLE_NAN std::numeric_limits<double>::quiet_NaN()
#else
/* math.h needed for NAN */
# include <math.h>
# define SBE_FLOAT_NAN NAN
# define SBE_DOUBLE_NAN NAN
#endif
#if __cplusplus >= 201103L
# include <cstdint>
# include <string>
# include <cstring>
#endif
#if __cplusplus >= 201103L
# define SBE_CONSTEXPR constexpr
# define SBE_NOEXCEPT noexcept
#else
# define SBE_CONSTEXPR
# define SBE_NOEXCEPT
#endif
#include <sbe/sbe.h>
namespace sbe {
class OrderType
{
public:
enum Value
{
market = (std::uint8_t)0,
limit = (std::uint8_t)1,
stop = (std::uint8_t)2,
NULL_VALUE = (std::uint8_t)255
};
static OrderType::Value get(const std::uint8_t value)
{
switch (value)
{
case 0: return market;
case 1: return limit;
case 2: return stop;
case 255: return NULL_VALUE;
}
throw std::runtime_error("unknown value for enum OrderType [E103]");
}
};
}
#endif
|
#include<iostream>
using namespace std;
int main()
{
int n;
cin>>n;
int line=1;
int count=1;
while(line<=n)
{
int no=1;
while(no<=line)
{
cout<<count<<" ";
count=count+1;
no++;
}
line++;
cout<<endl;
}
return 0;
}
|
#ifndef _renderFace_H_
#define _renderFace_H_
using namespace cv;
using namespace std;
#define COLOR Scalar(255, 200,0)
// drawPolyLine draws a poly line by joining
// successive points between the start and end indices.
void drawPolyline
(
Mat &im,
const vector<Point2f> &landmarks,
const int start,
const int end,
bool isClosed = false
)
{
// Gather all points between the start and end indices
vector <Point> points;
for (int i = start; i <= end; i++)
{
points.push_back(cv::Point(landmarks[i].x, landmarks[i].y));
}
// Draw polylines.
polylines(im, points, isClosed, COLOR, 2, 16);
}
#endif // _renderFace_H_
|
#include<string>
#include<memory>
#ifndef PARSER_INPUT
#define PARSER_INPUT
class Parser_Input {
public:
Parser_Input ();
~Parser_Input ();
/**
* \ingroup CXXinput
* \name File open/close:
*
*/
/**
* \ingroup CXXinput
* @{
*/
/// \brief open \e filename for parsing
int Open (const char *filename);
/// \brief close previously opened input file.
int Close ();
/** @} */
/** \ingroup CXXinput
* \name Dump input file contents:
*
*/
/** \ingroup CXXinput
* @{
*/
/** \brief Dump input file settings to stdout. */
int Fdump ();
/** \brief Dump input file settings to stdout prefixed by a delimiter */
int Fdump (const char *prefix);
/** \brief Dump input file settings to an open file with a provided prefix delimiter */
int Fdump (const char *prefix, const char *filename);
/** @} */
/** \ingroup CXXinput
* \name Read scalar values
*
*
* The following member functions are used to read a scalar input \e
* value associated with the \e keyword string. The \e keyword can
* be provided as a string or const char* pointer. If desired, a \e
* vardef argument can be included which provides a default value
* for the scalar if the requested \e keyword is not present in the
* input file.. Alternatively, you can use the Register_Var family
* of functions to provide default values. Supported numeric template
* datatypes include int, float, and double.
*/
/** \ingroup CXXinput
* @{
*/
template <typename T> int Read_Var (std::string keyword, T *value ); ///< Scalar read
template <typename T> int Read_Var (std::string keyword, T *value, T vardef); ///< Scalar read with default
template <typename T> int Read_Var (const char *keyword, T *value ); ///< Scalar read
template <typename T> int Read_Var (const char *keyword, T *value, T vardef); ///< Scalar read with default
// Character string reads
int Read_Var (const char *keyword, std::string *value); ///< Scalar
int Read_Var (const char *keyword, char **value); ///< Scalar
int Read_Var (const char *keyword, std::string *value, std::string vardef); ///< Scalar
// Bool Read Functions
int Read_Var (const char *var, bool *value, bool vardef); ///< Scalar
int Read_Var (std::string var, bool *value, bool vardef); ///< Scalar
/** @} */
/** \ingroup CXXinput
* \name Read vector values
*
* The following member functions are used to read vector valued
* input values for common intrinsic datatypes given a desired
* \e keyword. If successful, the resulting
* data is stored in the array values.
*/
/** \ingroup CXXinput
* @{
*/
template <typename T> int Read_Var_Vec (std::string keyword, T *values, int nelems); ///< Vec
template <typename T> int Read_Var_Vec (const char *keyword, T *values, int nelems); ///< Vec
template <typename T> int Read_Var_Vec (std::string keyword, T *values, int nelems, T vardef); ///< Vec
template <typename T> int Read_Var_Vec (const char *keyword, T *values, int nelems, T vardef); ///< Vec
/** @} */
/** \ingroup CXXinput
* \name Read ith vector value
*
* The following member functions are used to read the ith entry (\e elem) of
* vector valued input values for common intrinsic datatypes given a desired
* keyword. If successful, the resulting
* data is stored in \e value.
*/
/** \ingroup CXXinput
* @{
*/
template <typename T> int Read_Var_iVec (std::string keyword, T *value, int elem); ///< iVec
template <typename T> int Read_Var_iVec (const char *keyword, T *value, int elem); ///< iVec
template <typename T> int Read_Var_iVec (std::string keyword, T *value, int elem, T vardef); ///< iVec
template <typename T> int Read_Var_iVec (const char *keyword, T *value, int elem, T vardef); ///< iVec
// Character String Read Functions
int Read_Var_iVec (const char *keyword, char **value, int elem); ///<iVec
int Read_Var_iVec (const char *keyword, std::string *value, int elem); ///<iVec
/** @} */
/** \ingroup CXXinput
* \name Default value registration:
*
* The following member functions provide a mechanism to register a
* default value with the input parsing mechanism. If a particular
* \e keyword has a registered default value and is subsequently
* queried with an input file which does not contain the keyword,
* the registered default value will be returned instead. A
* convenient use for these registration functions is to provide
* sensible defaults to newly added input keywords which are not
* present in older input file revisions.
*/
/** \ingroup CXXinput
* @{
*/
void Register_Var (const char *keyword, int var); ///< Register_Var
void Register_Var (const char *keyword, float var); ///< Register_Var
void Register_Var (const char *keyword, double var); ///< Register_Var
void Register_Var (const char *keyword, bool var); ///< Register_Var
void Register_Var (const char *keyword, const char *var); ///< Register_Var
void Register_Var (const char *keyword, std::string var); ///< Register_Var
/** @} */
/**
* \ingroup CXXinput
* \name Default registration query:
*
* The following member functions can be used to query the current
* hashed values of any keyword variables which have been registered
* previously.
*/
/** \ingroup CXXinput
* @{
*/
int Get_Var (const char *keyword, int *value); ///< Get_Var
int Get_Var (const char *keyword, float *value); ///< Get_Var
int Get_Var (const char *keyword, double *value); ///< Get_Var
int Get_Var (const char *keyword, char **value); ///< Get_Var
int Get_Var (const char *keyword, std::string *value); ///< Get_Var
void PrintRegVars (const char *prefix); ///< Print
/** @} */
private:
class Parser_InputImp ; // forward declaration to Input class implementation
std::auto_ptr<Parser_InputImp> m_pimpl; // pointer to implementation
};
#endif
|
#include "FtdcProperties.hpp"
#include <map>
typedef std::map< std::string, std::string > Properties;
FtdcProperties::FtdcProperties()
{
}
|
class WordDictionary {
class TrieNode {
public:
TrieNode() {
isWord = false;
for (int i = 0; i < 26; i++) {
child[i] = nullptr;
}
}
bool isWord;
TrieNode *child[26];
};
TrieNode root;
bool search(string &word, int pos, TrieNode *node) {
if (pos == word.length()) {
return node->isWord;
} else if (word[pos] == '.') {
for (int i = 0; i < 26; i++) {
if (node->child[i]) {
bool status = search(word, pos + 1, node->child[i]);
if (status)
return true;
}
}
return false;
} else {
int value = word[pos] - 'a';
if (node->child[value]) {
return search(word, pos + 1, node->child[value]);
} else {
return false;
}
}
}
public:
/** Initialize your data structure here. */
WordDictionary() {
}
/** Adds a word into the data structure. */
void addWord(string word) {
TrieNode *node = &root;
for (int i = 0; i < word.length(); i++) {
int value = word[i] - 'a';
if (node->child[value] == nullptr)
node->child[value] = new TrieNode();
node = node->child[value];
}
node->isWord = true;
}
/** Returns if the word is in the data structure. A word could contain the dot character '.' to represent any one letter. */
bool search(string word) {
return search(word, 0, &root);
}
};
/**
* Your WordDictionary object will be instantiated and called as such:
* WordDictionary obj = new WordDictionary();
* obj.addWord(word);
* bool param_2 = obj.search(word);
*/
|
#include "lane_markings.h"
#include <cmath>
#include "engine/vertex.h"
namespace {
auto build_lane_markings()
{
using namespace apeiron::engine;
const float line_width = 0.2f;
const float line_length = 6.0f;
const float line_gap = 12.0f;
const float lane_width = 3.6f;
std::vector<Vertex_simple> vertices;
const float lw = line_width;
const float ll = line_length;
const float w = lane_width / 2.0f;
float h = 0.0f;
const int sections = 12;
int index = 0;
while (index++ < sections) {
// Left stripe
vertices.emplace_back(-w - lw, h, 0.0f);
vertices.emplace_back(-w, h, 0.0f);
vertices.emplace_back(-w - lw, h + ll, 0.0f);
vertices.emplace_back(-w, h, 0.0f);
vertices.emplace_back(-w, h + ll, 0.0f);
vertices.emplace_back(-w - lw, h + ll, 0.0f);
// Right stripe
vertices.emplace_back(w, h, 0.0f);
vertices.emplace_back(w + lw, h, 0.0f);
vertices.emplace_back(w, h + ll, 0.0f);
vertices.emplace_back(w + lw, h, 0.0f);
vertices.emplace_back(w + lw, h + ll, 0.0f);
vertices.emplace_back(w, h + ll, 0.0f);
h += line_length + line_gap;
}
return vertices;
}
} // namespace
example::Lane_markings::Lane_markings() : stripes_{build_lane_markings()}
{
set_position(0.0f, 0.05f, +100.0f);
// Rotate to xz-plane
set_rotation(glm::radians(-90.0f), 0.0f, 0.0f);
}
|
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
void inorder(TreeNode* A,TreeNode** ans,int* B)
{
if(A==NULL)return;
inorder(A->left,ans,B);
(*B)--;
if(*B==0)
{
*ans=A;
return;
}
inorder(A->right,ans,B);
}
int Solution::kthsmallest(TreeNode* A, int B) {
TreeNode* ans=NULL;
inorder(A,&ans,&B);
return ans->val;
}
|
// Copyright (c) 2012 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 SYNC_NOTIFIER_SYNC_NOTIFIER_REGISTRAR_H_
#define SYNC_NOTIFIER_SYNC_NOTIFIER_REGISTRAR_H_
#include <map>
#include "base/basictypes.h"
#include "base/observer_list.h"
#include "base/threading/thread_checker.h"
#include "sync/notifier/invalidation_util.h"
#include "sync/notifier/object_id_payload_map.h"
#include "sync/notifier/sync_notifier_observer.h"
namespace invalidation {
class ObjectId;
} // namespace invalidation
namespace syncer {
// A helper class for implementations of the SyncNotifier interface. It helps
// keep track of registered handlers and which object ID registrations are
// associated with which handlers, so implementors can just reuse the logic
// here to dispatch invalidations and other interesting notifications.
class SyncNotifierRegistrar {
public:
SyncNotifierRegistrar();
~SyncNotifierRegistrar();
// Starts sending notifications to |handler|. |handler| must not be NULL,
// and it must already be registered.
void RegisterHandler(SyncNotifierObserver* handler);
// Updates the set of ObjectIds associated with |handler|. |handler| must
// not be NULL, and must already be registered. An ID must be registered for
// at most one handler.
void UpdateRegisteredIds(SyncNotifierObserver* handler,
const ObjectIdSet& ids);
// Stops sending notifications to |handler|. |handler| must not be NULL, and
// it must already be registered. Note that this doesn't unregister the IDs
// associated with |handler|.
void UnregisterHandler(SyncNotifierObserver* handler);
// Returns the set of all IDs that are registered to some handler (even
// handlers that have been unregistered).
ObjectIdSet GetAllRegisteredIds() const;
// Sorts incoming invalidations into a bucket for each handler and then
// dispatches the batched invalidations to the corresponding handler.
// Invalidations for IDs with no corresponding handler are dropped, as are
// invalidations for handlers that are not added.
void DispatchInvalidationsToHandlers(const ObjectIdPayloadMap& id_payloads,
IncomingNotificationSource source);
// Calls the given handler method for each handler that has registered IDs.
void EmitOnNotificationsEnabled();
void EmitOnNotificationsDisabled(NotificationsDisabledReason reason);
// Needed for death tests.
void DetachFromThreadForTest();
private:
typedef std::map<invalidation::ObjectId, SyncNotifierObserver*,
ObjectIdLessThan>
IdHandlerMap;
SyncNotifierObserver* ObjectIdToHandler(const invalidation::ObjectId& id);
base::ThreadChecker thread_checker_;
ObserverList<SyncNotifierObserver> handlers_;
IdHandlerMap id_to_handler_map_;
DISALLOW_COPY_AND_ASSIGN(SyncNotifierRegistrar);
};
} // namespace syncer
#endif // SYNC_NOTIFIER_SYNC_NOTIFIER_REGISTRAR_H_
|
#ifndef RENDERER_H
#define RENDERER_H
#include <QThread>
#include <QObject>
#include <QAbstractVideoSurface>
#include <QFuture>
#include "worker.h"
#include "instructions.h"
#include "palette.h"
class Renderer : public QThread
{
Q_OBJECT
Q_PROPERTY(QAbstractVideoSurface* videoSurface READ videoSurface WRITE setVideoSurface)
Q_PROPERTY(QSize outSize READ outSize WRITE setOutSize NOTIFY outSizeChanged)
Q_PROPERTY(QSizeF calcSize READ calcSize NOTIFY calcSizeChanged)
Q_PROPERTY(qreal scale READ scale WRITE setScale NOTIFY scaleChanged)
Q_PROPERTY(QPointF calcCenter READ calcCenter WRITE setCalcCenter NOTIFY calcCenterChanged)
Q_PROPERTY(int threads READ threads WRITE setThreads NOTIFY threadsChanged)
Q_PROPERTY(int precision READ precision NOTIFY precisionChanged)
Q_PROPERTY(qreal exponent READ exponent WRITE setExponent NOTIFY exponentChanged)
Q_PROPERTY(Palette* palette READ palette WRITE setPalette)
public:
Renderer(QObject* parent = nullptr);
~Renderer();
QAbstractVideoSurface* videoSurface() const;
void setVideoSurface(QAbstractVideoSurface* surface);
// getters
QSize outSize() const;
QSizeF calcSize() const;
qreal scale() const;
QPointF calcCenter() const;
int threads() const;
int precision() const;
Palette* palette() const;
qreal exponent() const;
// setters
void setOutSize(QSize size);
void setScale(qreal scale);
void setCalcCenter(QPointF center);
void setThreads(int threads);
void setPalette(Palette* palette);
void setExponent(qreal exponent);
void setPrecision(int precision);
Q_INVOKABLE void exportTo(const QString& path) const;
signals:
void rendered(const QImage image, int precision);
void precisionChanged();
void outSizeChanged();
void calcSizeChanged();
void scaleChanged();
void calcCenterChanged();
void threadsChanged();
void exponentChanged();
protected:
// separate thread method
void run();
private:
void prepareData(const Instructions& instructions);
void drawImage(Palette* palette, size_t precision);
void updateSurfaceFormat(const QSize& size);
int getMaxIterations(qreal scale);
int getFirstIterationTarget(int max);
int getNextIterationTarget(int current, int max);
private slots:
void updateImage(const QImage& image, int precision);
private:
int m_threads;
int m_precision;
Instructions instructions;
QAbstractVideoSurface* p_surface;
QVector<MandelData> data_buffer;
QVector<QRgb> image_buffer;
QImage activeImage;
};
#endif // RENDERER_H
|
/*******************************************************************************
* Cristian Alexandrescu *
* 2163013577ba2bc237f22b3f4d006856 *
* 11a4bb2c77aca6a9927b85f259d9af10db791ce5cf884bb31e7f7a889d4fb385 *
* bc9a53289baf23d369484f5343ed5d6c *
*******************************************************************************/
/* Problem 1971. Graphics Settings */
/* http://acm.timus.ru/problem.aspx?num=1971 */
#include <iostream>
#include <string>
#include <unordered_map>
#include <cmath>
typedef double REAL;
class COption {
public:
COption(REAL lfValue, bool bIsOn = true) : m_lfValue(lfValue), m_bIsOn(bIsOn) {};
bool GetIsOn() const { return m_bIsOn; }
void SetIsOn(bool bIsOn) { m_bIsOn = bIsOn; }
REAL GetValue() const { return m_lfValue; }
void SetValue(REAL lfValue) { m_lfValue = lfValue; };
private:
REAL m_lfValue;
bool m_bIsOn;
};
void PrintPerformance(REAL lfFps) {
static const REAL LOG_10 = std::log(10.0);
static const REAL LOG_60 = std::log(60.0);
if (lfFps < LOG_10)
std::cout << "Slideshow" << std::endl;
else if (lfFps < LOG_60)
std::cout << "So-so" << std::endl;
else
std::cout << "Perfect" << std::endl;
}
int main() {
std::ios::sync_with_stdio(false);
int nNoOptions;
std::cin >> nNoOptions;
std::unordered_map<std::string, COption> oMapOptions;
REAL lfTemp = 0;
for (int nLoop = 0; nLoop < nNoOptions; nLoop++) {
std::string oOptionName;
REAL lfValue;
std::cin >> oOptionName >> lfValue;
lfValue = std::log(lfValue);
oMapOptions.emplace(oOptionName, lfValue);
lfTemp += lfValue;
}
int nW, nH, nRate;
std::cin >> nW >> nH >> nRate;
REAL lfLogRes = std::log(nW * nH);
REAL lfFps = std::log(nRate) - lfTemp - lfLogRes;
PrintPerformance(lfFps);
int nNoChanges;
std::cin >> nNoChanges;
for (int nLoop = 0; nLoop < nNoChanges; nLoop++) {
std::string oOptionName;
std::cin >> oOptionName;
if (oOptionName == "Resolution") {
//long long llTemp = static_cast<long long>(nW * nH);
lfFps += lfLogRes;
std::cin >> nW >> nH;
//nFps = static_cast<int>(nFps * llTemp / (nW * nH));
lfFps -= (lfLogRes = std::log(nW * nH));
} else {
bool bTurnOn = oOptionName == "On";
std::cin >> oOptionName;
auto oIt = oMapOptions.find(oOptionName);
if (oIt->second.GetIsOn()) {
if (!bTurnOn)
lfFps += oIt->second.GetValue();
} else {
if (bTurnOn)
lfFps -= oIt->second.GetValue();
}
oIt->second.SetIsOn(bTurnOn);
}
PrintPerformance(lfFps);
}
return 0;
}
|
#include <iostream>
using namespace std;
int main()
{
int x = 2629800; //okres zycia w wieku w niemowlecym w minutach 0-5 lat
int y = 3681720 ; // dokres zycia w wieku w dzieciecymw minutachziecko w minutach 5-12
int z = 3155760 ;//okres zycia w wieku w mlodzienczym w minutach 12-16
int dzien, miesiac, rok;
int a_dzien=30 , a_miesiac=9, a_rok=2016; // ustalona z gory data dzisiejsza
string plec;
cout<<"Podaj date urodzin: "<<endl;
cout<<"Dzien: ";
cin>>dzien;
cout<<"Miesiac: ";
cin>>miesiac;
cout<<"Rok: ";
cin>>rok;
cout<<"podaj plec :";
cin>>plec;
int wynik = 0;
int tabm[12] = {31,28,31,30,31,30,31,31,30,31,30,31};
int tabmp[12] = {31,29,31,30,31,30,31,31,30,31,30,31};
while(rok<a_rok)
{
if((rok%4==0 && !(rok%100==0)) || (rok%400==0))
{
wynik+=366;
}
else
{
wynik+=365;
}
rok++;
}
if(miesiac<a_miesiac)
{
while(miesiac<a_miesiac) //dodajemy miesiace a na koncu dodatkowo nadmiarowe dni
{
if((rok%4==0 && !(rok%100==0)) || (rok%400==0))
{
wynik+=tabmp[miesiac-1];
}
else
{
wynik+=tabm[miesiac-1];
}
miesiac++;
}
wynik+=a_dzien-dzien;
}
else if(miesiac==a_miesiac)
{
wynik+=a_dzien - dzien;
}
else if(miesiac>a_miesiac)
{
if((rok%4==0 && !(rok%100==0)) || (rok%400==0))
{
while(miesiac<a_miesiac)
{
wynik-=tabmp[miesiac];//dekrementujemy miesiace az sie zrownaja
miesiac--;
}
}
else
{
while(a_miesiac<miesiac)
{
wynik-=tabm[miesiac];
miesiac--;
}
}
wynik+=a_dzien-dzien;
}
int wynik_min= wynik*1440; //ilosc dni w przeliczeniu na miute
cout<<"dotychczas zyles :"<<wynik_min<<" minut"<<endl;
if(wynik_min<x)
{
cout<<"jestes niemowlakiem i twoje serce bilo : "<<wynik_min/130<<" razy do tej pory"<<endl;
}
if((wynik_min>x)&&(wynik_min<(x+y)))
{
cout<<"jestes dzieckiem i twoje serce bilo : "<<x/130 + (wynik_min-x)/100<<" razy do tej pory"<<endl;
}
if((wynik_min>x)&&(wynik_min>(x+y))&&(wynik_min<(x+y+z)))
{
cout<<"jestes nastolatkiem i twoje serce bilo : "<<x/130 + y/100 + (wynik_min-(x+y))/85<<" razy do tej pory"<<endl;
}
if((wynik_min>x)&&(wynik_min>(x+y))&&(wynik_min>(x+y+z)))
{
if( plec=="k"||plec=="K")
{
cout<<"jestes kobieta i twoje serce bilo : "<<x/130 + y/100 +z/85 + (wynik_min-(x+y+z))/66<<" razy do tej pory"<<endl;
}
else cout<<"jestes facetem i twoje serce bilo : "<<x/130 + y/100 +z/85 + (wynik_min-(x+y+z))/62<<" razy do tej pory"<<endl;
}
return 0;
}
|
#include <iostream>
#include <vector>
#include <opencv2/opencv.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <memory>
using namespace std;
using namespace cv;
#define WINDOW_NAME1 "[原始图]"
#define WINDOW_NAME2 "[修补后的效果图]"
// 描述: 全局变量的声明
Mat srcImage1, inpaintMask;
Point previousPoint(-1, -1); // 原来点的坐标
static void on_Mouse(int event, int x, int y, int flags, void*);
int main(int argc, char *argv[]) {
// 载入原始图并进行掩膜的初始化
Mat srcImage = imread("baboon2.jpg", -1);
if (!srcImage.data) {
printf("读取图片错误, 请确定目录下是否有imread函数指定图片存在~! \n");
return -1;
}
srcImage1 = srcImage.clone();
inpaintMask = Mat::zeros(srcImage1.size(), CV_8U);
// 显示原始图
imshow(WINDOW_NAME1, srcImage1);
// 设置鼠标回调消息
setMouseCallback(WINDOW_NAME1, on_Mouse, 0);
// 轮询按键, 根据不同的按键进行处理
while (1) {
// 获取按键键值
char c = (char)waitKey();
// 按键为ESC, 程序退出
if (c == 27) {
break;
}
// 键值为2, 恢复成原始图像
if (c == '2') {
inpaintMask = Scalar::all(0);
srcImage.copyTo(srcImage1);
imshow(WINDOW_NAME1, srcImage1);
}
// 键值为1或者空格, 进行图像修补操作
if (c == '1' || c == ' ') {
Mat inpaintedImage;
inpaint(srcImage, inpaintMask, inpaintedImage, 3, INPAINT_TELEA);
imshow(WINDOW_NAME2, inpaintedImage);
}
}
return 0;
}
// 鼠标消息回调函数
static void on_Mouse(int event, int x, int y, int flags, void*) {
// 处理鼠标左键相关信息
if (event == EVENT_LBUTTONUP || !(flags & EVENT_FLAG_LBUTTON))
previousPoint = Point(-1, -1);
else if (event == EVENT_LBUTTONDOWN)
previousPoint = Point(x, y);
// 鼠标左键按下并移动, 进行绘制
else if (event == EVENT_MOUSEMOVE && (flags & EVENT_FLAG_LBUTTON)) {
Point pt(x, y);
if (previousPoint.x < 0) {
previousPoint = pt;
}
// 绘制白色线条
line(inpaintMask, previousPoint, pt, Scalar::all(255), 5, 8, 0);
line(srcImage1, previousPoint, pt, Scalar::all(255), 5, 8, 0);
previousPoint = pt;
imshow(WINDOW_NAME1, srcImage1);
}
}
|
#pragma once
#include "../hw/api.h"
#include "constants.h"
#include "icons_manager.h"
class PasswordWidget
{
public:
enum EState
{
kStateHidden = 0,
kStatePasswordEnter,
kStateRequestSent,
kStateDrawResult,
};
PasswordWidget(API* api, IconsManager& iconsMan)
: m_api(api), m_iconsMan(iconsMan)
{
m_state = kStateHidden;
m_backgroundRect = Rect(0, 0, kBackgroundWidth, kBackgroundHeight);
m_loadingRect = Rect(220, 120, kInfoIconsWidth, kInfoIconsHeight);
m_authKey = ~0u;
m_upper = false;
m_buttons = (Button*)m_api->Malloc(kButtonsCount * sizeof(Button));
m_api->memset(m_buttons, 0, kButtonsCount * sizeof(Button));
m_cursorTimer = 0.0f;
m_api->memset(m_password, 0, sizeof(m_password));
m_passwordLen = 0;
m_request = NULL;
InitButtons();
}
void InitButtons()
{
FontInfo fi;
m_api->LCD_GetFontInfo(kFont24, &fi);
uint32_t buttonIdx = 0;
Rect rect;
rect.width = kKeyButtonWidth;
rect.height = kKeyButtonHeight;
rect.x = 22;
rect.y = 100;
for(uint32_t i = 0; i < 10; i++)
{
char symbols[] = {'1', '2', '3', '4', '5', '6', '7', '8', '9', '0'};
m_buttons[buttonIdx].type = kButtonSymbol;
m_buttons[buttonIdx].rect = rect;
m_buttons[buttonIdx].lowerCase = symbols[i];
m_buttons[buttonIdx].upperCase = symbols[i];
buttonIdx++;
rect.x += kKeyButtonWidth + kSpaceSize;
}
rect.x = 22;
rect.y += kKeyButtonHeight + kSpaceSize;
for(uint32_t i = 0; i < 10; i++)
{
char symbolsLower[] = {'q', 'w', 'e', 'r', 't', 'y', 'u', 'i', 'o', 'p'};
char symbolsUpper[] = {'Q', 'W', 'E', 'R', 'T', 'Y', 'U', 'I', 'O', 'P'};
m_buttons[buttonIdx].type = kButtonSymbol;
m_buttons[buttonIdx].rect = rect;
m_buttons[buttonIdx].lowerCase = symbolsLower[i];
m_buttons[buttonIdx].upperCase = symbolsUpper[i];
buttonIdx++;
rect.x += kKeyButtonWidth + kSpaceSize;
}
rect.x = 44;
rect.y += kKeyButtonHeight + kSpaceSize;
for(uint32_t i = 0; i < 9; i++)
{
char symbolsLower[] = {'a', 's', 'd', 'f', 'g', 'h', 'j', 'k', 'l'};
char symbolsUpper[] = {'A', 'S', 'D', 'F', 'G', 'H', 'J', 'K', 'L'};
m_buttons[buttonIdx].type = kButtonSymbol;
m_buttons[buttonIdx].rect = rect;
m_buttons[buttonIdx].lowerCase = symbolsLower[i];
m_buttons[buttonIdx].upperCase = symbolsUpper[i];
buttonIdx++;
rect.x += kKeyButtonWidth + kSpaceSize;
}
// cancel button
rect.x = 4;
rect.width = 36;
rect.height = 84;
m_buttons[buttonIdx].type = kButtonCancel;
m_buttons[buttonIdx].rect = rect;
buttonIdx++;
// accept button
rect.x = 440;
rect.width = 36;
rect.height = 84;
m_buttons[buttonIdx].type = kButtonAccept;
m_buttons[buttonIdx].rect = rect;
buttonIdx++;
// caps lock
rect.width = kKeyButtonWidth;
rect.height = kKeyButtonHeight;
rect.x = 44;
rect.y += kKeyButtonHeight + kSpaceSize;
m_buttons[buttonIdx].type = kButtonCapsLock;
m_buttons[buttonIdx].rect = rect;
buttonIdx++;
rect.x += kKeyButtonWidth + kSpaceSize;
for(uint32_t i = 0; i < 7; i++)
{
char symbolsLower[] = {'z', 'x', 'c', 'v', 'b', 'n', 'm'};
char symbolsUpper[] = {'Z', 'X', 'C', 'V', 'B', 'N', 'M'};
m_buttons[buttonIdx].type = kButtonSymbol;
m_buttons[buttonIdx].rect = rect;
m_buttons[buttonIdx].lowerCase = symbolsLower[i];
m_buttons[buttonIdx].upperCase = symbolsUpper[i];
buttonIdx++;
rect.x += kKeyButtonWidth + kSpaceSize;
}
// backspace
m_buttons[buttonIdx].type = kButtonBackspace;
m_buttons[buttonIdx].rect = rect;
buttonIdx++;
}
void Activate(const char* password)
{
m_state = kStatePasswordEnter;
m_api->strcpy(m_password, password);
m_passwordLen = m_api->strlen(password);
m_result = false;
m_cursorTimer = 0.0f;
}
void SetAuthKey(uint32_t authKey)
{
m_authKey = authKey;
}
void OnClick(uint16_t touchX, uint16_t touchY)
{
if(m_state == kStateRequestSent)
return;
for(uint32_t i = 0; i < kButtonsCount; i++)
{
Button& b = m_buttons[i];
if(!b.rect.IsPointInside(touchX, touchY))
continue;
b.pressed = true;
if(b.type == kButtonSymbol)
AddSymbol(m_upper ? b.upperCase : b.lowerCase);
else if(b.type == kButtonCapsLock)
m_upper = !m_upper;
else if(b.type == kButtonBackspace)
EraseLastSymbol();
else if(b.type == kButtonCancel)
m_state = kStateHidden;
else if(b.type == kButtonAccept && m_passwordLen > 0)
{
RequestPasswordChange();
if(m_request)
m_state = kStateRequestSent;
}
}
}
void Update(float dt)
{
if(m_state == kStatePasswordEnter)
{
m_cursorTimer += dt;
if(m_cursorTimer > 0.8f)
m_cursorTimer = 0.0f;
}
else if(m_request && m_request->done)
{
m_result = m_request->succeed && m_request->statusCode == 200;
m_api->FreeHTTPRequest(m_request);
m_request = NULL;
m_state = kStateDrawResult;
m_drawResultTimer = 0.5f;
}
else if(m_state == kStateDrawResult)
{
m_drawResultTimer -= dt;
if(m_drawResultTimer < 0.0f)
m_state = kStateHidden;
}
}
void OnRender()
{
m_api->LCD_DrawImage(m_backgroundRect, m_iconsMan.background, kBackgroundWidth * 4);
m_api->LCD_SetFont(kFont24);
m_api->LCD_SetTextColor(0xffffffff);
FontInfo fi;
m_api->LCD_GetFontInfo(kFont24, &fi);
if(m_state == kStatePasswordEnter)
{
// head
m_api->LCD_SetFont(kFont16);
m_api->LCD_DisplayStringAt(8, 8, "Change password", kTextAlignNone);
Rect line(8, 26, 180, 1);
m_api->LCD_FillRect(line, 0xffffffff);
m_api->LCD_SetFont(kFont24);
// curson rendering
uint32_t cursorOffsetX = (kBackgroundWidth - fi.charWidth * m_passwordLen) / 2;
uint32_t cursorOffsetY = 50;
Rect cursor;
cursor.x = cursorOffsetX + fi.charWidth * m_passwordLen;
cursor.y = cursorOffsetY;
cursor.width = 2;
cursor.height = fi.charHeight;
if(m_cursorTimer < 0.4f)
m_api->LCD_FillRect(cursor, 0xffffffff);
// password rendering
if(m_passwordLen)
m_api->LCD_DisplayStringAt(cursorOffsetX, cursorOffsetY, m_password, kTextAlignNone);
// buttons
uint32_t symOffsetX = (kKeyButtonWidth - fi.charWidth) / 2;
uint32_t symOffsetY = (kKeyButtonHeight - fi.charHeight) / 2;
for(uint32_t i = 0; i < kButtonsCount; i++)
{
Button& b = m_buttons[i];
if(b.type == kButtonSymbol)
{
m_api->LCD_DrawImageWithBlend(b.rect, m_iconsMan.keyButton, kKeyButtonWidth * 4);
char symbol = m_upper ? b.upperCase : b.lowerCase;
m_api->LCD_DisplayChar(b.rect.x + symOffsetX, b.rect.y + symOffsetY, symbol);
}
else if(b.type == kButtonCapsLock)
{
m_api->LCD_DrawImageWithBlend(b.rect, m_iconsMan.capslockButton, kKeyButtonWidth * 4);
}
else if(b.type == kButtonBackspace)
{
m_api->LCD_DrawImageWithBlend(b.rect, m_iconsMan.backspaceButton, kKeyButtonWidth * 4);
}
else if(b.type == kButtonCancel)
{
m_api->LCD_DrawImageWithBlend(b.rect, m_iconsMan.cancelButton, kAcceptCancelButtonWidth * 4);
}
else if(b.type == kButtonAccept)
{
m_api->LCD_DrawImageWithBlend(b.rect, m_iconsMan.acceptButton, kAcceptCancelButtonWidth * 4);
}
b.pressed = false;
}
}
else if(m_state == kStateRequestSent)
{
m_api->LCD_DrawImageWithBlend(m_loadingRect, m_iconsMan.loadingIcon, kInfoIconsWidth * 4);
}
else if(m_state == kStateDrawResult)
{
m_api->LCD_DisplayStringAt(0, 130, m_result ? "OK" : "Failed", kTextAlignCenter);
}
}
EState GetState() const
{
return m_state;
}
bool GetResult() const
{
return m_result;
}
const char* GetPassword() const
{
return m_password;
}
private:
enum EButtonType
{
kButtonSymbol = 0,
kButtonCapsLock,
kButtonBackspace,
kButtonCancel,
kButtonAccept
};
struct Button
{
EButtonType type;
Rect rect;
char lowerCase;
char upperCase;
bool pressed;
};
static const uint32_t kMaxPasswordLen = 16;
static const uint32_t kButtonsCount = 40;
static const uint32_t kSpaceSize = 4;
API* m_api;
IconsManager& m_iconsMan;
EState m_state;
Rect m_backgroundRect;
Rect m_loadingRect;
uint32_t m_authKey;
bool m_upper;
Button* m_buttons;
float m_cursorTimer;
char m_password[kMaxPasswordLen + 1];
uint32_t m_passwordLen;
HTTPRequest* m_request;
float m_drawResultTimer;
bool m_result;
void AddSymbol(char symbol)
{
if(m_passwordLen == kMaxPasswordLen)
return;
m_password[m_passwordLen] = symbol;
m_passwordLen++;
}
void EraseLastSymbol()
{
if(m_passwordLen == 0)
return;
m_password[m_passwordLen - 1] = 0;
m_passwordLen--;
}
void RequestPasswordChange()
{
m_request = m_api->AllocHTTPRequest();
if(!m_request)
return;
m_request->httpMethod = kHttpMethodPost;
m_api->sprintf(m_request->url, "http://%s:%u/change_password?auth=%x&p=%s", kServerIP, kServerPort, m_authKey, m_password);
if(!m_api->SendHTTPRequest(m_request))
m_api->FreeHTTPRequest(m_request);
}
};
|
/*Given an array A[] of size N and an integer K. Your task is to complete the function countDistinct() which prints the count of distinct numbers in all windows of size k in the array A[].
Input:
The first line of input contains an integer T denoting the number of test cases. Then T test cases follow. Each test case contains two integers N and K. Then in the next line are N space separated values of the array A[].
Output:
For each test case in a new line print the space separated values denoting counts of distinct numbers in all windows of size k in the array A[].*/
#include <bits/stdc++.h>
using namespace std;
void countDistinct(int a[], int n, int k)
{
int c = 0;
unordered_map<int, int> hashmap;
for(int i=0;i<n;++i)
{
if(hashmap.find(a[i])!=hashmap.end())
{
hashmap[a[i]]++;
}
else
{
hashmap.insert(make_pair(a[i],1));
++c;
}
if (i>k-2)
{
hashmap[a[i+1-k]]--;
cout<<c<<" ";
if(!hashmap[a[i+1-k]])
{
hashmap.erase(a[i+1-k]);
--c;
}
}
}
}
int main()
{
int t;
cin >> t;
while (t--)
{
int n, k;
cin >> n >> k;
int a[n];
for (int i = 0; i < n; ++i)
{
cin >> a[i];
}
countDistinct(a, n, k);
cout << "\n";
}
}
|
// C++ for the Windows Runtime vv1.0.170303.6
// Copyright (c) 2017 Microsoft Corporation. All rights reserved.
#pragma once
#include "Windows.ApplicationModel.Background.2.h"
WINRT_EXPORT namespace winrt {
namespace Windows::ApplicationModel::Background {
template <typename H> struct impl_BackgroundTaskCanceledEventHandler : implements<impl_BackgroundTaskCanceledEventHandler<H>, abi<BackgroundTaskCanceledEventHandler>>, H
{
impl_BackgroundTaskCanceledEventHandler(H && handler) : H(std::forward<H>(handler)) {}
HRESULT __stdcall abi_Invoke(impl::abi_arg_in<Windows::ApplicationModel::Background::IBackgroundTaskInstance> sender, Windows::ApplicationModel::Background::BackgroundTaskCancellationReason reason) noexcept override
{
try
{
(*this)(*reinterpret_cast<const Windows::ApplicationModel::Background::IBackgroundTaskInstance *>(&sender), reason);
return S_OK;
}
catch (...)
{
return impl::to_hresult();
}
}
};
template <typename H> struct impl_BackgroundTaskCompletedEventHandler : implements<impl_BackgroundTaskCompletedEventHandler<H>, abi<BackgroundTaskCompletedEventHandler>>, H
{
impl_BackgroundTaskCompletedEventHandler(H && handler) : H(std::forward<H>(handler)) {}
HRESULT __stdcall abi_Invoke(impl::abi_arg_in<Windows::ApplicationModel::Background::IBackgroundTaskRegistration> sender, impl::abi_arg_in<Windows::ApplicationModel::Background::IBackgroundTaskCompletedEventArgs> args) noexcept override
{
try
{
(*this)(*reinterpret_cast<const Windows::ApplicationModel::Background::BackgroundTaskRegistration *>(&sender), *reinterpret_cast<const Windows::ApplicationModel::Background::BackgroundTaskCompletedEventArgs *>(&args));
return S_OK;
}
catch (...)
{
return impl::to_hresult();
}
}
};
template <typename H> struct impl_BackgroundTaskProgressEventHandler : implements<impl_BackgroundTaskProgressEventHandler<H>, abi<BackgroundTaskProgressEventHandler>>, H
{
impl_BackgroundTaskProgressEventHandler(H && handler) : H(std::forward<H>(handler)) {}
HRESULT __stdcall abi_Invoke(impl::abi_arg_in<Windows::ApplicationModel::Background::IBackgroundTaskRegistration> sender, impl::abi_arg_in<Windows::ApplicationModel::Background::IBackgroundTaskProgressEventArgs> args) noexcept override
{
try
{
(*this)(*reinterpret_cast<const Windows::ApplicationModel::Background::BackgroundTaskRegistration *>(&sender), *reinterpret_cast<const Windows::ApplicationModel::Background::BackgroundTaskProgressEventArgs *>(&args));
return S_OK;
}
catch (...)
{
return impl::to_hresult();
}
}
};
}
namespace Windows::ApplicationModel::Background {
struct WINRT_EBO ActivitySensorTrigger :
Windows::ApplicationModel::Background::IActivitySensorTrigger
{
ActivitySensorTrigger(std::nullptr_t) noexcept {}
ActivitySensorTrigger(uint32_t reportIntervalInMilliseconds);
};
struct AlarmApplicationManager
{
AlarmApplicationManager() = delete;
static Windows::Foundation::IAsyncOperation<winrt::Windows::ApplicationModel::Background::AlarmAccessStatus> RequestAccessAsync();
static Windows::ApplicationModel::Background::AlarmAccessStatus GetAccessStatus();
};
struct WINRT_EBO AppBroadcastTrigger :
Windows::ApplicationModel::Background::IAppBroadcastTrigger
{
AppBroadcastTrigger(std::nullptr_t) noexcept {}
AppBroadcastTrigger(hstring_view providerKey);
};
struct WINRT_EBO AppBroadcastTriggerProviderInfo :
Windows::ApplicationModel::Background::IAppBroadcastTriggerProviderInfo
{
AppBroadcastTriggerProviderInfo(std::nullptr_t) noexcept {}
};
struct WINRT_EBO ApplicationTrigger :
Windows::ApplicationModel::Background::IApplicationTrigger
{
ApplicationTrigger(std::nullptr_t) noexcept {}
ApplicationTrigger();
};
struct WINRT_EBO ApplicationTriggerDetails :
Windows::ApplicationModel::Background::IApplicationTriggerDetails
{
ApplicationTriggerDetails(std::nullptr_t) noexcept {}
};
struct WINRT_EBO AppointmentStoreNotificationTrigger :
Windows::ApplicationModel::Background::IAppointmentStoreNotificationTrigger
{
AppointmentStoreNotificationTrigger(std::nullptr_t) noexcept {}
AppointmentStoreNotificationTrigger();
};
struct BackgroundExecutionManager
{
BackgroundExecutionManager() = delete;
static Windows::Foundation::IAsyncOperation<winrt::Windows::ApplicationModel::Background::BackgroundAccessStatus> RequestAccessAsync();
static Windows::Foundation::IAsyncOperation<winrt::Windows::ApplicationModel::Background::BackgroundAccessStatus> RequestAccessAsync(hstring_view applicationId);
static void RemoveAccess();
static void RemoveAccess(hstring_view applicationId);
static Windows::ApplicationModel::Background::BackgroundAccessStatus GetAccessStatus();
static Windows::ApplicationModel::Background::BackgroundAccessStatus GetAccessStatus(hstring_view applicationId);
};
struct WINRT_EBO BackgroundTaskBuilder :
Windows::ApplicationModel::Background::IBackgroundTaskBuilder,
impl::require<BackgroundTaskBuilder, Windows::ApplicationModel::Background::IBackgroundTaskBuilder2, Windows::ApplicationModel::Background::IBackgroundTaskBuilder3, Windows::ApplicationModel::Background::IBackgroundTaskBuilder4>
{
BackgroundTaskBuilder(std::nullptr_t) noexcept {}
BackgroundTaskBuilder();
};
struct WINRT_EBO BackgroundTaskCompletedEventArgs :
Windows::ApplicationModel::Background::IBackgroundTaskCompletedEventArgs
{
BackgroundTaskCompletedEventArgs(std::nullptr_t) noexcept {}
};
struct WINRT_EBO BackgroundTaskDeferral :
Windows::ApplicationModel::Background::IBackgroundTaskDeferral
{
BackgroundTaskDeferral(std::nullptr_t) noexcept {}
};
struct WINRT_EBO BackgroundTaskProgressEventArgs :
Windows::ApplicationModel::Background::IBackgroundTaskProgressEventArgs
{
BackgroundTaskProgressEventArgs(std::nullptr_t) noexcept {}
};
struct WINRT_EBO BackgroundTaskRegistration :
Windows::ApplicationModel::Background::IBackgroundTaskRegistration,
impl::require<BackgroundTaskRegistration, Windows::ApplicationModel::Background::IBackgroundTaskRegistration2, Windows::ApplicationModel::Background::IBackgroundTaskRegistration3>
{
BackgroundTaskRegistration(std::nullptr_t) noexcept {}
static Windows::Foundation::Collections::IMapView<GUID, Windows::ApplicationModel::Background::IBackgroundTaskRegistration> AllTasks();
static Windows::Foundation::Collections::IMapView<hstring, Windows::ApplicationModel::Background::BackgroundTaskRegistrationGroup> AllTaskGroups();
static Windows::ApplicationModel::Background::BackgroundTaskRegistrationGroup GetTaskGroup(hstring_view groupId);
};
struct WINRT_EBO BackgroundTaskRegistrationGroup :
Windows::ApplicationModel::Background::IBackgroundTaskRegistrationGroup
{
BackgroundTaskRegistrationGroup(std::nullptr_t) noexcept {}
BackgroundTaskRegistrationGroup(hstring_view id);
BackgroundTaskRegistrationGroup(hstring_view id, hstring_view name);
};
struct BackgroundWorkCost
{
BackgroundWorkCost() = delete;
static Windows::ApplicationModel::Background::BackgroundWorkCostValue CurrentBackgroundWorkCost();
};
struct WINRT_EBO BluetoothLEAdvertisementPublisherTrigger :
Windows::ApplicationModel::Background::IBluetoothLEAdvertisementPublisherTrigger
{
BluetoothLEAdvertisementPublisherTrigger(std::nullptr_t) noexcept {}
BluetoothLEAdvertisementPublisherTrigger();
};
struct WINRT_EBO BluetoothLEAdvertisementWatcherTrigger :
Windows::ApplicationModel::Background::IBluetoothLEAdvertisementWatcherTrigger
{
BluetoothLEAdvertisementWatcherTrigger(std::nullptr_t) noexcept {}
BluetoothLEAdvertisementWatcherTrigger();
};
struct WINRT_EBO CachedFileUpdaterTrigger :
Windows::ApplicationModel::Background::ICachedFileUpdaterTrigger
{
CachedFileUpdaterTrigger(std::nullptr_t) noexcept {}
CachedFileUpdaterTrigger();
};
struct WINRT_EBO CachedFileUpdaterTriggerDetails :
Windows::ApplicationModel::Background::ICachedFileUpdaterTriggerDetails
{
CachedFileUpdaterTriggerDetails(std::nullptr_t) noexcept {}
};
struct WINRT_EBO ChatMessageNotificationTrigger :
Windows::ApplicationModel::Background::IChatMessageNotificationTrigger
{
ChatMessageNotificationTrigger(std::nullptr_t) noexcept {}
ChatMessageNotificationTrigger();
};
struct WINRT_EBO ChatMessageReceivedNotificationTrigger :
Windows::ApplicationModel::Background::IChatMessageReceivedNotificationTrigger
{
ChatMessageReceivedNotificationTrigger(std::nullptr_t) noexcept {}
ChatMessageReceivedNotificationTrigger();
};
struct WINRT_EBO CommunicationBlockingAppSetAsActiveTrigger :
Windows::ApplicationModel::Background::ICommunicationBlockingAppSetAsActiveTrigger
{
CommunicationBlockingAppSetAsActiveTrigger(std::nullptr_t) noexcept {}
CommunicationBlockingAppSetAsActiveTrigger();
};
struct WINRT_EBO ContactStoreNotificationTrigger :
Windows::ApplicationModel::Background::IContactStoreNotificationTrigger
{
ContactStoreNotificationTrigger(std::nullptr_t) noexcept {}
ContactStoreNotificationTrigger();
};
struct WINRT_EBO ContentPrefetchTrigger :
Windows::ApplicationModel::Background::IContentPrefetchTrigger
{
ContentPrefetchTrigger(std::nullptr_t) noexcept {}
ContentPrefetchTrigger();
ContentPrefetchTrigger(const Windows::Foundation::TimeSpan & waitInterval);
};
struct WINRT_EBO DeviceConnectionChangeTrigger :
Windows::ApplicationModel::Background::IDeviceConnectionChangeTrigger
{
DeviceConnectionChangeTrigger(std::nullptr_t) noexcept {}
static Windows::Foundation::IAsyncOperation<Windows::ApplicationModel::Background::DeviceConnectionChangeTrigger> FromIdAsync(hstring_view deviceId);
};
struct WINRT_EBO DeviceManufacturerNotificationTrigger :
Windows::ApplicationModel::Background::IDeviceManufacturerNotificationTrigger
{
DeviceManufacturerNotificationTrigger(std::nullptr_t) noexcept {}
DeviceManufacturerNotificationTrigger(hstring_view triggerQualifier, bool oneShot);
};
struct WINRT_EBO DeviceServicingTrigger :
Windows::ApplicationModel::Background::IDeviceServicingTrigger
{
DeviceServicingTrigger(std::nullptr_t) noexcept {}
DeviceServicingTrigger();
};
struct WINRT_EBO DeviceUseTrigger :
Windows::ApplicationModel::Background::IDeviceUseTrigger
{
DeviceUseTrigger(std::nullptr_t) noexcept {}
DeviceUseTrigger();
};
struct WINRT_EBO DeviceWatcherTrigger :
Windows::ApplicationModel::Background::IDeviceWatcherTrigger
{
DeviceWatcherTrigger(std::nullptr_t) noexcept {}
};
struct WINRT_EBO EmailStoreNotificationTrigger :
Windows::ApplicationModel::Background::IEmailStoreNotificationTrigger
{
EmailStoreNotificationTrigger(std::nullptr_t) noexcept {}
EmailStoreNotificationTrigger();
};
struct WINRT_EBO GattCharacteristicNotificationTrigger :
Windows::ApplicationModel::Background::IGattCharacteristicNotificationTrigger,
impl::require<GattCharacteristicNotificationTrigger, Windows::ApplicationModel::Background::IGattCharacteristicNotificationTrigger2>
{
GattCharacteristicNotificationTrigger(std::nullptr_t) noexcept {}
GattCharacteristicNotificationTrigger(const Windows::Devices::Bluetooth::GenericAttributeProfile::GattCharacteristic & characteristic);
GattCharacteristicNotificationTrigger(const Windows::Devices::Bluetooth::GenericAttributeProfile::GattCharacteristic & characteristic, Windows::Devices::Bluetooth::Background::BluetoothEventTriggeringMode eventTriggeringMode);
};
struct WINRT_EBO GattServiceProviderTrigger :
Windows::ApplicationModel::Background::IGattServiceProviderTrigger,
impl::require<GattServiceProviderTrigger, Windows::ApplicationModel::Background::IBackgroundTrigger>
{
GattServiceProviderTrigger(std::nullptr_t) noexcept {}
static Windows::Foundation::IAsyncOperation<Windows::ApplicationModel::Background::GattServiceProviderTriggerResult> CreateAsync(hstring_view triggerId, GUID serviceUuid);
};
struct WINRT_EBO GattServiceProviderTriggerResult :
Windows::ApplicationModel::Background::IGattServiceProviderTriggerResult
{
GattServiceProviderTriggerResult(std::nullptr_t) noexcept {}
};
struct WINRT_EBO LocationTrigger :
Windows::ApplicationModel::Background::ILocationTrigger
{
LocationTrigger(std::nullptr_t) noexcept {}
LocationTrigger(Windows::ApplicationModel::Background::LocationTriggerType triggerType);
};
struct WINRT_EBO MaintenanceTrigger :
Windows::ApplicationModel::Background::IMaintenanceTrigger
{
MaintenanceTrigger(std::nullptr_t) noexcept {}
MaintenanceTrigger(uint32_t freshnessTime, bool oneShot);
};
struct WINRT_EBO MediaProcessingTrigger :
Windows::ApplicationModel::Background::IMediaProcessingTrigger
{
MediaProcessingTrigger(std::nullptr_t) noexcept {}
MediaProcessingTrigger();
};
struct WINRT_EBO MobileBroadbandDeviceServiceNotificationTrigger :
Windows::ApplicationModel::Background::IBackgroundTrigger
{
MobileBroadbandDeviceServiceNotificationTrigger(std::nullptr_t) noexcept {}
MobileBroadbandDeviceServiceNotificationTrigger();
};
struct WINRT_EBO MobileBroadbandPinLockStateChangeTrigger :
Windows::ApplicationModel::Background::IBackgroundTrigger
{
MobileBroadbandPinLockStateChangeTrigger(std::nullptr_t) noexcept {}
MobileBroadbandPinLockStateChangeTrigger();
};
struct WINRT_EBO MobileBroadbandRadioStateChangeTrigger :
Windows::ApplicationModel::Background::IBackgroundTrigger
{
MobileBroadbandRadioStateChangeTrigger(std::nullptr_t) noexcept {}
MobileBroadbandRadioStateChangeTrigger();
};
struct WINRT_EBO MobileBroadbandRegistrationStateChangeTrigger :
Windows::ApplicationModel::Background::IBackgroundTrigger
{
MobileBroadbandRegistrationStateChangeTrigger(std::nullptr_t) noexcept {}
MobileBroadbandRegistrationStateChangeTrigger();
};
struct WINRT_EBO NetworkOperatorHotspotAuthenticationTrigger :
Windows::ApplicationModel::Background::INetworkOperatorHotspotAuthenticationTrigger
{
NetworkOperatorHotspotAuthenticationTrigger(std::nullptr_t) noexcept {}
NetworkOperatorHotspotAuthenticationTrigger();
};
struct WINRT_EBO NetworkOperatorNotificationTrigger :
Windows::ApplicationModel::Background::INetworkOperatorNotificationTrigger
{
NetworkOperatorNotificationTrigger(std::nullptr_t) noexcept {}
NetworkOperatorNotificationTrigger(hstring_view networkAccountId);
};
struct WINRT_EBO PhoneTrigger :
Windows::ApplicationModel::Background::IPhoneTrigger
{
PhoneTrigger(std::nullptr_t) noexcept {}
PhoneTrigger(Windows::ApplicationModel::Calls::Background::PhoneTriggerType type, bool oneShot);
};
struct WINRT_EBO PushNotificationTrigger :
Windows::ApplicationModel::Background::IBackgroundTrigger
{
PushNotificationTrigger(std::nullptr_t) noexcept {}
PushNotificationTrigger();
PushNotificationTrigger(hstring_view applicationId);
};
struct WINRT_EBO RcsEndUserMessageAvailableTrigger :
Windows::ApplicationModel::Background::IRcsEndUserMessageAvailableTrigger
{
RcsEndUserMessageAvailableTrigger(std::nullptr_t) noexcept {}
RcsEndUserMessageAvailableTrigger();
};
struct WINRT_EBO RfcommConnectionTrigger :
Windows::ApplicationModel::Background::IRfcommConnectionTrigger
{
RfcommConnectionTrigger(std::nullptr_t) noexcept {}
RfcommConnectionTrigger();
};
struct WINRT_EBO SecondaryAuthenticationFactorAuthenticationTrigger :
Windows::ApplicationModel::Background::ISecondaryAuthenticationFactorAuthenticationTrigger
{
SecondaryAuthenticationFactorAuthenticationTrigger(std::nullptr_t) noexcept {}
SecondaryAuthenticationFactorAuthenticationTrigger();
};
struct WINRT_EBO SensorDataThresholdTrigger :
Windows::ApplicationModel::Background::ISensorDataThresholdTrigger
{
SensorDataThresholdTrigger(std::nullptr_t) noexcept {}
SensorDataThresholdTrigger(const Windows::Devices::Sensors::ISensorDataThreshold & threshold);
};
struct WINRT_EBO SmartCardTrigger :
Windows::ApplicationModel::Background::ISmartCardTrigger
{
SmartCardTrigger(std::nullptr_t) noexcept {}
SmartCardTrigger(Windows::Devices::SmartCards::SmartCardTriggerType triggerType);
};
struct WINRT_EBO SmsMessageReceivedTrigger :
Windows::ApplicationModel::Background::IBackgroundTrigger
{
SmsMessageReceivedTrigger(std::nullptr_t) noexcept {}
SmsMessageReceivedTrigger(const Windows::Devices::Sms::SmsFilterRules & filterRules);
};
struct WINRT_EBO SocketActivityTrigger :
Windows::ApplicationModel::Background::IBackgroundTrigger,
impl::require<SocketActivityTrigger, Windows::ApplicationModel::Background::ISocketActivityTrigger>
{
SocketActivityTrigger(std::nullptr_t) noexcept {}
SocketActivityTrigger();
};
struct WINRT_EBO StorageLibraryContentChangedTrigger :
Windows::ApplicationModel::Background::IStorageLibraryContentChangedTrigger
{
StorageLibraryContentChangedTrigger(std::nullptr_t) noexcept {}
static Windows::ApplicationModel::Background::StorageLibraryContentChangedTrigger Create(const Windows::Storage::StorageLibrary & storageLibrary);
static Windows::ApplicationModel::Background::StorageLibraryContentChangedTrigger CreateFromLibraries(iterable<Windows::Storage::StorageLibrary> storageLibraries);
};
struct WINRT_EBO SystemCondition :
Windows::ApplicationModel::Background::ISystemCondition
{
SystemCondition(std::nullptr_t) noexcept {}
SystemCondition(Windows::ApplicationModel::Background::SystemConditionType conditionType);
};
struct WINRT_EBO SystemTrigger :
Windows::ApplicationModel::Background::ISystemTrigger
{
SystemTrigger(std::nullptr_t) noexcept {}
SystemTrigger(Windows::ApplicationModel::Background::SystemTriggerType triggerType, bool oneShot);
};
struct WINRT_EBO TimeTrigger :
Windows::ApplicationModel::Background::ITimeTrigger
{
TimeTrigger(std::nullptr_t) noexcept {}
TimeTrigger(uint32_t freshnessTime, bool oneShot);
};
struct WINRT_EBO ToastNotificationActionTrigger :
Windows::ApplicationModel::Background::IBackgroundTrigger
{
ToastNotificationActionTrigger(std::nullptr_t) noexcept {}
ToastNotificationActionTrigger();
ToastNotificationActionTrigger(hstring_view applicationId);
};
struct WINRT_EBO ToastNotificationHistoryChangedTrigger :
Windows::ApplicationModel::Background::IBackgroundTrigger
{
ToastNotificationHistoryChangedTrigger(std::nullptr_t) noexcept {}
ToastNotificationHistoryChangedTrigger();
ToastNotificationHistoryChangedTrigger(hstring_view applicationId);
};
struct WINRT_EBO UserNotificationChangedTrigger :
Windows::ApplicationModel::Background::IBackgroundTrigger
{
UserNotificationChangedTrigger(std::nullptr_t) noexcept {}
UserNotificationChangedTrigger(Windows::UI::Notifications::NotificationKinds notificationKinds);
};
}
}
|
#include <sstream>
#include <gtest/gtest.h>
#include "hs_test_utility/test_env/data_path.hpp"
#include "hs_sfm/sfm_file_io/extrinsic_params_set_loader.hpp"
#include "hs_sfm/sfm_file_io/intrinsic_params_set_loader.hpp"
#include "hs_sfm/sfm_file_io/keyset_loader.hpp"
#include "hs_sfm/sfm_file_io/object_index_loader.hpp"
#include "hs_sfm/sfm_file_io/points_loader.hpp"
#include "hs_sfm/sfm_file_io/tracks_loader.hpp"
#include "hs_sfm/incremental/gcp_similar_transform_estimator.hpp"
#include "data_tester.hpp"
namespace
{
template <typename _Scalar>
class TestBundleAdjustmentGCPConstrainedOptimizor
{
public:
typedef _Scalar Scalar;
typedef int Err;
private:
typedef hs::sfm::incremental::GCPSimilarTransformEstimator<Scalar>
SimilarTransformEstimator;
typedef hs::sfm::incremental::DataTester<Scalar> Tester;
public:
typedef typename SimilarTransformEstimator::ExtrinsicParams ExtrinsicParams;
typedef typename SimilarTransformEstimator::IntrinsicParams IntrinsicParams;
typedef typename SimilarTransformEstimator::ExtrinsicParamsContainer
ExtrinsicParamsContainer;
typedef typename SimilarTransformEstimator::IntrinsicParamsContainer
IntrinsicParamsContainer;
typedef typename SimilarTransformEstimator::Keyset Keyset;
typedef typename SimilarTransformEstimator::KeysetContainer KeysetContainer;
typedef typename SimilarTransformEstimator::Point Point;
typedef typename SimilarTransformEstimator::PointContainer PointContainer;
private:
typedef typename SimilarTransformEstimator::Rotation Rotation;
typedef typename SimilarTransformEstimator::Translate Translate;
public:
Err operator() (
const KeysetContainer& keysets_noised,
const IntrinsicParamsContainer& intrinsic_params_set,
const ExtrinsicParamsContainer& extrinsic_params_set_absolute_true,
const PointContainer& points_absolute_true,
const hs::sfm::TrackContainer& tracks,
const hs::sfm::ViewInfoIndexer& view_info_indexer,
const hs::sfm::ObjectIndexMap& image_extrinsic_map,
const hs::sfm::ObjectIndexMap& track_point_map,
const ExtrinsicParamsContainer& extrinsic_params_set_relative_estimate,
const PointContainer& points_relative_estimate,
const KeysetContainer& keysets_gcp,
const hs::sfm::TrackContainer& tracks_gcp,
const PointContainer& gcps,
Scalar key_stddev,
const std::string& test_name) const
{
SimilarTransformEstimator similar_transform_estimator;
hs::sfm::ObjectIndexMap track_point_map_gcp;
hs::sfm::ViewInfoIndexer view_info_indexer_gcp;
PointContainer gcps_relative;
Rotation rotation_similar;
Translate translate_similar;
Scalar scale_similar;
if (similar_transform_estimator(keysets_gcp,
intrinsic_params_set,
extrinsic_params_set_relative_estimate,
tracks_gcp,
gcps,
image_extrinsic_map,
4,
key_stddev * Scalar(4),
rotation_similar,
translate_similar,
scale_similar,
track_point_map_gcp,
view_info_indexer_gcp,
gcps_relative) != 0)
{
return -1;
}
ExtrinsicParamsContainer extrinsic_params_set_absolute_estimate =
extrinsic_params_set_relative_estimate;
size_t number_of_extrinsics =
extrinsic_params_set_absolute_estimate.size();
for (size_t i = 0; i < number_of_extrinsics; i++)
{
ExtrinsicParams& extrinsic_params =
extrinsic_params_set_absolute_estimate[i];
extrinsic_params.rotation() =
extrinsic_params.rotation() * rotation_similar.Inverse();
extrinsic_params.position() =
scale_similar * (rotation_similar * extrinsic_params.position()) +
translate_similar;
}
PointContainer points_absolute_estimate = points_relative_estimate;
size_t number_of_points = points_absolute_estimate.size();
for (size_t i = 0; i < number_of_points; i++)
{
Point& point = points_absolute_estimate[i];
point = scale_similar * (rotation_similar * point) + translate_similar;
}
ExtrinsicParamsContainer extrinsic_params_set_absolute_true_reordered(
extrinsic_params_set_absolute_estimate.size());
size_t number_of_images = extrinsic_params_set_absolute_true.size();
for (size_t i = 0; i < number_of_images; i++)
{
if (image_extrinsic_map.IsValid(i))
{
extrinsic_params_set_absolute_true_reordered[image_extrinsic_map[i]] =
extrinsic_params_set_absolute_true[i];
}
}
PointContainer points_absolute_true_reordered(
points_absolute_estimate.size());
size_t number_of_tracks = points_absolute_true.size();
for (size_t i = 0; i < number_of_tracks; i++)
{
if (track_point_map.IsValid(i))
{
points_absolute_true_reordered[track_point_map[i]] =
points_absolute_true[i];
}
}
std::string extrinsic_accuracy_similar_transform_path =
test_name + "_extrinsic_accuracy_similar_transform.txt";
Tester tester;
if (tester.TestExtrinsicAccuracy(
extrinsic_params_set_absolute_true_reordered,
extrinsic_params_set_absolute_estimate,
extrinsic_accuracy_similar_transform_path,
Scalar(2)) != 0) return -1;
std::string point_accuracy_similar_transform_path =
test_name + "_point_accuracy_similar_transform.txt";
if (tester.TestPointsAccuracy(
points_absolute_true_reordered,
points_absolute_estimate,
point_accuracy_similar_transform_path,
Scalar(3)) != 0) return -1;
return 0;
}
};
TEST(TestBundleAdjustmentGCPConstrainedOptimizor, BigDataTest)
{
typedef double Scalar;
typedef int Err;
typedef TestBundleAdjustmentGCPConstrainedOptimizor<Scalar> Tester;
typedef Tester::ExtrinsicParamsContainer ExtrinsicParamsContainer;
typedef Tester::IntrinsicParamsContainer IntrinsicParamsContainer;
typedef Tester::KeysetContainer KeysetContainer;
typedef Tester::PointContainer PointContainer;
std::string test_name = "big_data";
std::string test_prefix = hs::test::getTestDataPath();
test_prefix += "sfm/incremental/" + test_name;
hs::sfm::fileio::ExtrinsicParamsSetLoader<Scalar> extrinsic_set_loader;
hs::sfm::fileio::PointsLoader<Scalar> points_loader;
hs::sfm::fileio::TracksLoader tracks_loader;
hs::sfm::fileio::IntrinsicParamsSetLoader<Scalar> intrinsic_set_loader;
hs::sfm::fileio::ObjectIndexLoader object_index_loader;
hs::sfm::fileio::KeysetLoader<Scalar> keyset_loader;
std::string extrinsic_set_absolute_true_path =
test_prefix + "_extrinsic_params_set_absolute_true.txt";
ExtrinsicParamsContainer extrinsic_params_set_absolute_true;
ASSERT_EQ(0, extrinsic_set_loader(extrinsic_set_absolute_true_path,
extrinsic_params_set_absolute_true));
std::string points_absolute_true_path =
test_prefix + "_points_absolute_true.txt";
PointContainer points_absolute_true;
ASSERT_EQ(0, points_loader(points_absolute_true_path,
points_absolute_true));
std::string gcps_path = test_prefix + "_gcps.txt";
PointContainer gcps;
ASSERT_EQ(0, points_loader(gcps_path,
gcps));
size_t number_of_images = extrinsic_params_set_absolute_true.size();
KeysetContainer keysets_noised(number_of_images);
for (size_t i = 0; i < number_of_images; i++)
{
std::stringstream ss;
ss<<test_prefix<<"_keyset_"<<i<<".txt";
std::string keyset_path;
ss>>keyset_path;
keyset_loader(keyset_path, keysets_noised[i]);
}
KeysetContainer keysets_gcp_noised(number_of_images);
for (size_t i = 0; i < number_of_images; i++)
{
std::stringstream ss;
ss<<test_prefix<<"_keyset_gcp_"<<i<<".txt";
std::string keyset_gcp_path;
ss>>keyset_gcp_path;
keyset_loader(keyset_gcp_path, keysets_gcp_noised[i]);
}
hs::sfm::ViewInfoIndexer view_info_indexer_gcp;
hs::sfm::TrackContainer tracks_gcp;
std::string tracks_gcp_path = test_prefix + "_tracks_gcp.txt";
ASSERT_EQ(0, tracks_loader(tracks_gcp_path, tracks_gcp,
view_info_indexer_gcp));
hs::sfm::ViewInfoIndexer view_info_indexer;
hs::sfm::TrackContainer tracks;
std::string tracks_path = test_prefix + "_tracks.txt";
ASSERT_EQ(0, tracks_loader(tracks_path, tracks, view_info_indexer));
IntrinsicParamsContainer intrinsic_params_set;
std::string intrinsic_set_path =
test_prefix + "_intrinsic_params_set.txt";
ASSERT_EQ(0, intrinsic_set_loader(intrinsic_set_path,
intrinsic_params_set));
std::string extrinsic_set_relative_estimate_path =
test_prefix + "_extrinsic_params_set_relative_estimate.txt";
ExtrinsicParamsContainer extrinsic_params_set_relative_estimate;
ASSERT_EQ(0, extrinsic_set_loader(
extrinsic_set_relative_estimate_path,
extrinsic_params_set_relative_estimate));
std::string points_relative_estimate_path =
test_prefix + "_points_relative_estimate.txt";
PointContainer points_relative_estimate;
ASSERT_EQ(0, points_loader(points_relative_estimate_path,
points_relative_estimate));
std::string track_point_map_path =
test_prefix + "_track_point_map.txt";
hs::sfm::ObjectIndexMap track_point_map;
ASSERT_EQ(0, object_index_loader(track_point_map_path,
track_point_map));
std::string image_extrinsic_map_path =
test_prefix + "_image_extrinsic_map.txt";
hs::sfm::ObjectIndexMap image_extrinsic_map;
ASSERT_EQ(0, object_index_loader(image_extrinsic_map_path,
image_extrinsic_map));
Tester tester;
ASSERT_EQ(0, tester(keysets_noised,
intrinsic_params_set,
extrinsic_params_set_absolute_true,
points_absolute_true,
tracks,
view_info_indexer,
image_extrinsic_map,
track_point_map,
extrinsic_params_set_relative_estimate,
points_relative_estimate,
keysets_gcp_noised,
tracks_gcp,
gcps,
1,
test_name));
}
}
|
/***********************************************************************
created: 20/2/2004
author: Paul D Turner
purpose: Defines interface for main GUI system class
*************************************************************************/
/***************************************************************************
* Copyright (C) 2004 - 2012 Paul D Turner & The CEGUI Development Team
*
* 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 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 _CEGUISystem_h_
#define _CEGUISystem_h_
#include "CEGUI/Singleton.h"
#include "CEGUI/EventSet.h"
#include <vector>
#if defined(__WIN32__) || defined(_WIN32)
# include "CEGUI/Win32StringTranscoder.h"
#else
# include "CEGUI/IconvStringTranscoder.h"
#endif
#if defined(_MSC_VER)
# pragma warning(push)
# pragma warning(disable : 4251)
#endif
namespace CEGUI
{
class TextParser;
class LegacyTextParser;
/*!
\brief
The System class is the CEGUI class that provides access to all other elements in this system.
This object must be created by the client application. The System object requires that you pass it
an initialised Renderer object which it can use to interface to whatever rendering system will be
used to display the GUI imagery.
*/
class CEGUIEXPORT System :
public Singleton<System>,
public EventSet
{
public:
static const String EventNamespace; //!< Namespace for global events
/*************************************************************************
Constants
*************************************************************************/
// event names
/** Event fired for display size changes (as notified by client code).
* Handlers are passed a const DisplayEventArgs reference with
* DisplayEventArgs::size set to the pixel size that was notifiied to the
* system.
*/
static const String EventDisplaySizeChanged;
/** Event fired when global custom TextParser is set.
* Handlers are passed a const reference to a generic EventArgs struct.
*/
static const String EventTextParserChanged;
/*************************************************************************
Construction and Destruction
*************************************************************************/
/*!
\brief
Create the System object and return a reference to it.
\param renderer
Reference to a valid Renderer object that will be used to render GUI
imagery.
\param resourceProvider
Pointer to a ResourceProvider object, or NULL to use whichever default
the Renderer provides.
\param xmlParser
Pointer to a valid XMLParser object to be used when parsing XML files,
or NULL to use a default parser.
\param imageCodec
Pointer to a valid ImageCodec object to be used when loading image
files, or NULL to use a default image codec.
\param scriptModule
Pointer to a ScriptModule object. may be NULL for none.
\param configFile
String object containing the name of a configuration file to use.
\param logFile
String object containing the name to use for the log file.
\param abi
This must be set to CEGUI_VERSION_ABI
*/
static System& create(Renderer& renderer,
ResourceProvider* resourceProvider = nullptr,
XMLParser* xmlParser = nullptr,
ImageCodec* imageCodec = nullptr,
ScriptModule* scriptModule = nullptr,
const String& configFile = "",
const String& logFile = "CEGUI.log",
const int abi = CEGUI_VERSION_ABI);
//! Destroy the System object.
static void destroy();
/*!
\brief
Retrieves CEGUI's major version as an integer
\note
API/headers major version is a macro called CEGUI_MAJOR_VERSION,
this returns the version your application is linking to
*/
static unsigned int getMajorVersion();
/*!
\brief
Retrieves CEGUI's minor version as an integer
\note
API/headers minor version is a macro called CEGUI_MINOR_VERSION,
this returns the version your application is linking to
*/
static unsigned int getMinorVersion();
/*!
\brief
Retrieves CEGUI's patch version as an integer
\note
API/headers patch version is a macro called CEGUI_PATCH_VERSION,
this returns the version your application is linking to
*/
static unsigned int getPatchVersion();
/*!
\brief
Retrieves CEGUI's "short" version ("1.2.3" for example)
\note
API/headers version can be constructed using CEGUI_*_VERSION macros,
this returns the version your application is linking to
*/
static const String& getVersion();
/*!
\brief
Retrieves CEGUI's "verbose" version, includes info about compiler, platform, etc...
\note
API/headers verbose version can be constructed using various compiler specific macros,
this returns the version your application is linking to
*/
static const String& getVerboseVersion();
/*!
\brief
Return a pointer to the Renderer object being used by the system
\return
Pointer to the Renderer object used by the system.
*/
Renderer* getRenderer(void) const {return d_renderer;}
/*!
\brief
Return singleton System object
\return
Singleton System object
*/
static System& getSingleton(void);
/*!
\brief
Return pointer to singleton System object
\return
Pointer to singleton System object
*/
static System* getSingletonPtr(void);
/*!
\brief
Retrieves internal CEGUI clipboard, optionally synced with system wide clipboard
*/
Clipboard* getClipboard() const {return d_clipboard;}
typedef std::vector<GUIContext*> GUIContextCollection;
GUIContextCollection& getGUIContexts() {return d_guiContexts;}
/*!
\brief
Depending upon the internal state, for each GUIContext this may either
re-use cached rendering from last time or trigger a full re-draw of all
elements.
*/
void renderAllGUIContexts();
/*!
\brief
Renders the contexts associated with the renderer
\todo
This needs to be actually made to check if context matches the renderer
and for that to work all the contexts need to know their renderer
\see renderAllGUIContexts
*/
void renderAllGUIContextsOnTarget(Renderer* contained_in);
/*!
\brief
Return a pointer to the ScriptModule being used for scripting within the GUI system.
\return
Pointer to a ScriptModule based object.
*/
ScriptModule* getScriptingModule(void) const;
/*!
\brief
Set the ScriptModule to be used for scripting within the GUI system.
\param scriptModule
Pointer to a ScriptModule based object, or 0 for none (be careful!)
\return
Nothing
*/
void setScriptingModule(ScriptModule* scriptModule);
/*!
\brief
Return a pointer to the ResourceProvider being used within the GUI system.
\return
Pointer to a ResourceProvider based object.
*/
ResourceProvider* getResourceProvider(void) const;
/*!
\brief
Execute a script file if possible.
\param filename
String object holding the filename of the script file that is to be executed
\param resourceGroup
Resource group identifier to be passed to the ResourceProvider when loading the script file.
*/
void executeScriptFile(const String& filename, const String& resourceGroup = "") const;
/*!
\brief
Execute a scripted global function if possible. The function should not take any parameters and should return an integer.
\param function_name
String object holding the name of the function, in the global script environment, that
is to be executed.
\return
The integer value returned from the script function.
*/
int executeScriptGlobal(const String& function_name) const;
/*!
\brief
If possible, execute script code contained in the given CEGUI::String object.
\param str
String object holding the valid script code that should be executed.
\return
Nothing.
*/
void executeScriptString(const String& str) const;
/*!
\brief
Set a new XML parser module to be used.
The current XMLParser will be cleaned up and, if owned by the system,
also deleted, as will any dynamically loaded module associated with the
XMLParser object. The newly created XMLParser object, and the
associated module will be owned by the system.
\param parserName
String object describing the name of the XML parser module to be used.
*/
void setXMLParser(const String& parserName);
/*!
\brief
Sets the XMLParser object to be used by the system.
The current XMLParser will be cleaned up and, if owned by the system,
also deleted, as will any dynamically loaded module associated with the
XMLParser object.
If the argument passed in the \a parser parameter is 0, the system will
cleanup any existing parser as described above, and revert to using
the parser provided by the default module (see getDefaultXMLParserName
and setDefaultXMLParserName).
\param parser
Pointer to the XMLParser object to be used by the system, or 0 to cause
the system to initialise a default parser.
*/
void setXMLParser(XMLParser* parser);
/*!
\brief
Return the XMLParser object.
*/
XMLParser* getXMLParser(void) const { return d_xmlParser; }
/*!
\brief
Static member to set the name of the default XML parser module that
should be used.
If you want to modify the default parser from the one compiled in, you
need to call this static member prior to instantiating the main
CEGUI::System object.
Note that calling this member to change the name of the default module
after CEGUI::System, and therefore the default xml parser, has been
created will have no real effect - the default parser name will be
updated, though no actual changes to the xml parser module will occur.
The built-in options for this are:
- XercesParser
- ExpatParser
- LibxmlParser
- TinyXMLParser
Whether these are actually available, depends upon how you built the
system. If you have some custom parser, you can provide the name of
that here to have it used as the default, though note that the
final filename of the parser module should be of the form:
[prefix]CEGUI[parserName][suffix]
where:
- [prefix] is some optional prefix; like 'lib' on linux.
- CEGUI is a required prefix.
- [parserName] is the name of the parser, as supplied to this function.
- [suffix] is the filename suffix, like .dll or .so
Final module filenames are, thus, of the form:
- CEGUIXercesParser.dll
- libCEGUIXercesParser.so
\param parserName
String describing the name of the xml parser module to be used as the
default.
\return
Nothing.
*/
static void setDefaultXMLParserName(const String& parserName);
/*!
\brief
Return the name of the currently set default xml parser module.
\return
String holding the currently set default xml parser name. Note that if
this name has been changed after instantiating the system, the name
returned may not actually correspond to the module in use.
*/
static String getDefaultXMLParserName();
/*!
\brief
Retrieve the image codec to be used by the system.
*/
ImageCodec& getImageCodec() const;
/*!
\brief
Set the image codec to be used by the system.
*/
void setImageCodec(const String& codecName);
/*!
\brief
Set the image codec to use from an existing image codec.
In this case the renderer does not take the ownership of the image codec
object.
\param codec
The ImageCodec object to be used.
*/
void setImageCodec(ImageCodec& codec);
/*!
\brief
Set the name of the default image codec to be used.
*/
static void setDefaultImageCodecName(const String& codecName);
/*!
\brief
Get the name of the default image codec.
*/
static const String& getDefaultImageCodecName();
/*!
\brief
Set the default font to be used by all new GUIContext instances
\param name
String object containing the name of the font
*/
void setDefaultFontName(const String& name);
/*!
\brief
Set the default cursor to be used by all new GUIContext instances
\param name
String object containing the name of the cursor
*/
void setDefaultCursorName(const String& name);
/*!
\brief
Set the default tooltip type to be used by all new GUIContext instances
\param name
String object containing the type name of the tooltip
*/
void setDefaultTooltipType(const String& tooltip_type);
/*!
\brief
Notification function to be called when the main display changes size.
Client code should call this function when the host window changes size,
or if the display resolution is changed in full-screen mode.
Calling this function ensures that any other parts of the system that
need to know about display size changes are notified. This affects
things such as the Cursor default constraint area, and also the
auto-scale functioning of Imagesets and Fonts.
\note
This function will also fire the System::EventDisplaySizeChanged event.
\param new_size
Size object describing the new display size in pixels.
*/
void notifyDisplaySizeChanged(const Sizef& new_size);
/*!
\brief
Return pointer to the currently set global default
TextParser object.
The returned TextParser is used for all windows that have
parsing enabled and no custom TextParser set on the window
itself.
If this global custom TextParser is set to 0, then all windows
with parsing enabled and no custom TextParser set on the
window itself will use the system's default LegacyTextParser.
*/
TextParser* getDefaultTextParser() const;
/*!
\brief
Set the global default custom TextParser object. This change
is reflected the next time an affected window reparses it's text. This
may be set to nullptr to use default CEGUI text parser.
The set TextParser is used for all windows that have
parsing enabled and no custom TextParser set on the window
itself.
*/
void setDefaultTextParser(TextParser* parser);
/*!
\brief
Invalidate all imagery and geometry caches for CEGUI managed elements.
This function will invalidate the caches used for both imagery and
geometry for all content that is managed by the core CEGUI manager
objects, causing a full and total redraw of that content. This
includes Window object's cached geometry, rendering surfaces and
rendering windows and the pointer geometry.
*/
void invalidateAllCachedRendering();
//! call this to ensure system-level time based updates occur.
bool injectTimePulse(float timeElapsed);
GUIContext& createGUIContext(RenderTarget& rt);
void destroyGUIContext(GUIContext& context);
/*!
\brief adds factories for all the basic window types
You do not need to call this manually! Standard Window factories will be
added automatically. One occasion when you will need this is if you
remove all window factories from WindowFactoryManager and want to add the
standard ones back
*/
void addStandardWindowFactories();
//! Return the system StringTranscoder object
static const StringTranscoder& getStringTranscoder();
//! Internal CEGUI version validation function.
static void performVersionTest(const int expected, const int received,
const String& func);
protected:
/*************************************************************************
Implementation Functions
*************************************************************************/
/*!
\brief
Construct a new System object
\param renderer
Reference to a valid Renderer object that will be used to render GUI
imagery.
\param resourceProvider
Pointer to a ResourceProvider object, or NULL to use whichever default
the Renderer provides.
\param xmlParser
Pointer to a valid XMLParser object to be used when parsing XML files,
or NULL to use a default parser.
\param imageCodec
Pointer to a valid ImageCodec object to be used when loading image
files, or NULL to use a default image codec.
\param scriptModule
Pointer to a ScriptModule object. may be NULL for none.
\param configFile
String object containing the name of a configuration file to use.
\param logFile
String object containing the name to use for the log file.
*/
System(Renderer& renderer, ResourceProvider* resourceProvider,
XMLParser* xmlParser, ImageCodec* imageCodec,
ScriptModule* scriptModule, const String& configFile,
const String& logFile);
System(const System& obj) = delete;
System& operator =(const System& obj) = delete;
/*!
\brief
Destructor for System objects.
*/
~System();
//! output the standard log header
void outputLogHeader();
//! create the other core system singleton objects (except the logger)
void createSingletons();
//! cleanup the core system singleton objects
void destroySingletons();
//! handle creation and initialisation of the XML parser.
void setupXMLParser();
//! handle cleanup of the XML parser
void cleanupXMLParser();
//! setup image codec
void setupImageCodec(const String& codecName);
//! cleanup image codec
void cleanupImageCodec();
//! invalidate all windows and any rendering surfaces they may be using.
void invalidateAllWindows();
/*************************************************************************
Implementation Data
*************************************************************************/
Renderer* d_renderer; //!< Holds the pointer to the Renderer object given to us in the constructor
ResourceProvider* d_resourceProvider; //!< Holds the pointer to the ResourceProvider object given to us by the renderer or the System constructor.
bool d_ourResourceProvider;
Clipboard* d_clipboard; //!< Internal clipboard with optional sync with native clipboard
NativeClipboardProvider* d_nativeClipboardProvider; //!< the default native clipboard provider (only on Win32 for now)
// scripting
ScriptModule* d_scriptModule; //!< Points to the scripting support module.
String d_termScriptName; //!< Name of the script to run upon system shutdown.
XMLParser* d_xmlParser; //!< XMLParser object we use to process xml files.
bool d_ourXmlParser; //!< true when we created the xml parser.
DynamicModule* d_parserModule; //! pointer to parser module.
static String d_defaultXMLParserName; //!< Holds name of default XMLParser
//! Holds a pointer to the image codec to use.
ImageCodec* d_imageCodec;
//! true when we created the image codec.
bool d_ourImageCodec;
/** Holds a pointer to the image codec module. If d_imageCodecModule is 0 we
* are not owner of the image codec object
*/
DynamicModule* d_imageCodecModule;
//! Holds the name of the default codec to use.
static String d_defaultImageCodecName;
//! true when we created the CEGUI::Logger based object.
bool d_ourLogger;
//! Shared instance of a parser to be used in CEGUI by default.
std::unique_ptr<LegacyTextParser> d_fallbackTextParser;
//! Currently set global text parser.
TextParser* d_defaultTextParser = nullptr;
String d_defaultFontName;
String d_defaultCursorName;
String d_defaultTooltipType;
GUIContextCollection d_guiContexts;
//! instance of class that can convert string encodings
#if defined(__WIN32__) || defined(_WIN32)
static const Win32StringTranscoder d_stringTranscoder;
#else
static const IconvStringTranscoder d_stringTranscoder;
#endif
};
} // End of CEGUI namespace section
#if defined(_MSC_VER)
# pragma warning(pop)
#endif
#endif // end of guard _CEGUISystem_h_
|
/*
* Copyright (C) 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "snapuserd_core.h"
namespace android {
namespace snapshot {
using namespace android;
using namespace android::dm;
using android::base::unique_fd;
Worker::Worker(const std::string& cow_device, const std::string& backing_device,
const std::string& control_device, const std::string& misc_name,
const std::string& base_path_merge, std::shared_ptr<SnapshotHandler> snapuserd) {
cow_device_ = cow_device;
backing_store_device_ = backing_device;
control_device_ = control_device;
misc_name_ = misc_name;
base_path_merge_ = base_path_merge;
snapuserd_ = snapuserd;
}
bool Worker::InitializeFds() {
backing_store_fd_.reset(open(backing_store_device_.c_str(), O_RDONLY));
if (backing_store_fd_ < 0) {
SNAP_PLOG(ERROR) << "Open Failed: " << backing_store_device_;
return false;
}
cow_fd_.reset(open(cow_device_.c_str(), O_RDWR));
if (cow_fd_ < 0) {
SNAP_PLOG(ERROR) << "Open Failed: " << cow_device_;
return false;
}
ctrl_fd_.reset(open(control_device_.c_str(), O_RDWR));
if (ctrl_fd_ < 0) {
SNAP_PLOG(ERROR) << "Unable to open " << control_device_;
return false;
}
// Base device used by merge thread
base_path_merge_fd_.reset(open(base_path_merge_.c_str(), O_RDWR));
if (base_path_merge_fd_ < 0) {
SNAP_PLOG(ERROR) << "Open Failed: " << base_path_merge_;
return false;
}
return true;
}
bool Worker::InitReader() {
reader_ = snapuserd_->CloneReaderForWorker();
if (!reader_->InitForMerge(std::move(cow_fd_))) {
return false;
}
return true;
}
// Start the replace operation. This will read the
// internal COW format and if the block is compressed,
// it will be de-compressed.
bool Worker::ProcessReplaceOp(const CowOperation* cow_op) {
if (!reader_->ReadData(*cow_op, &bufsink_)) {
SNAP_LOG(ERROR) << "ProcessReplaceOp failed for block " << cow_op->new_block;
return false;
}
return true;
}
bool Worker::ProcessZeroOp() {
// Zero out the entire block
void* buffer = bufsink_.GetPayloadBuffer(BLOCK_SZ);
if (buffer == nullptr) {
SNAP_LOG(ERROR) << "ProcessZeroOp: Failed to get payload buffer";
return false;
}
memset(buffer, 0, BLOCK_SZ);
return true;
}
bool Worker::ProcessCopyOp(const CowOperation*) {
return true;
}
bool Worker::ProcessXorOp(const CowOperation*) {
return true;
}
void Worker::InitializeBufsink() {
// Allocate the buffer which is used to communicate between
// daemon and dm-user. The buffer comprises of header and a fixed payload.
// If the dm-user requests a big IO, the IO will be broken into chunks
// of PAYLOAD_SIZE.
size_t buf_size = sizeof(struct dm_user_header) + PAYLOAD_SIZE;
bufsink_.Initialize(buf_size);
}
bool Worker::Init() {
InitializeBufsink();
xorsink_.Initialize(&bufsink_, BLOCK_SZ);
if (!InitializeFds()) {
return false;
}
if (!InitReader()) {
return false;
}
return true;
}
bool Worker::RunThread() {
SNAP_LOG(DEBUG) << "Processing snapshot I/O requests...";
// Start serving IO
while (true) {
if (!ProcessIORequest()) {
break;
}
}
CloseFds();
reader_->CloseCowFd();
return true;
}
bool Worker::ProcessIORequest() {
// No communication with dm-user yet
return true;
}
} // namespace snapshot
} // namespace android
|
#include<bits/stdc++.h>
using namespace std;
struct node
{
int data;
struct node* left;
struct node* right;
};
typedef struct node Node;
Node* newNode(int data)
{
Node* temp = new Node();
temp->data = data;
temp->left = NULL;
temp->right = NULL;
return temp;
}
int largest_sum_util(Node* root,map<Node*,int>& hash)
{
if(root==NULL)
{
return 0;
}
// if cur node is already processed
if(hash.find(root)!=hash.end())
{
return hash[root];
}
// if we include the cur node
int total = root->data;
if(root->left!=NULL)
{
total+=largest_sum_util(root->left->left,hash)+largest_sum_util(root->left->right,hash);
}
if(root->right!=NULL)
{
total+=largest_sum_util(root->right->left,hash)+largest_sum_util(root->right->right,hash);
}
// if we exclude the cur node
int total2 = 0;
total2 += largest_sum_util(root->left,hash)+largest_sum_util(root->right,hash);
hash[root]=max(total,total2);
return hash[root];
}
// METHOD - 1
// time complexity O(n^2)
// space complexity O(n)
int largest_sum(Node* root)
{
if(root==NULL)
{
return 0;
}
map<Node*,int> hash;
return largest_sum_util(root,hash);
}
pair<int,int> helper(Node* root)
{
if(root==NULL)
{
return make_pair(0,0);
}
pair<int,int> sum1 = helper(root->left);
pair<int,int> sum2 = helper(root->right);
pair<int,int> sum;
// if current node is included
sum.first = root->data + sum1.second + sum2.second;
// if current node is excluded
sum.second = max(sum1.first,sum1.second)+max(sum2.first,sum2.second);
return sum;
}
// METHOD - 2 (efficient method)
// pair method
// Time complexity O(n) and auxillary space O(1)
// pair<int,int> where first indicates if current node is included
// pair<int,int> where second indicates if current node is not included
int solve2(Node* root)
{
if(root==NULL)
{
return 0;
}
pair<int,int> output = helper(root);
return max(output.first,output.second);
}
int main()
{
Node* root = newNode(10);
root->left = newNode(1);
root->left->left = newNode(2);
root->left->left->left = newNode(1);
root->left->right = newNode(3);
root->left->right->left = newNode(4);
root->left->right->right = newNode(5);
cout << largest_sum(root) << endl;
cout << solve2(root) << endl;
return 0;
}
|
// XMLControler.h - Contains declaration of Function class
#pragma
#ifdef XMLCONTROLER_EXPORTS
#define XMLCONTROLER_API __declspec(dllexport)
#else
#define XMLCONTROLER_API __declspec(dllimport)
#endif
#define CUSCNTMAX 20000
#define ACCCNTMAX 20000
#include <boost/archive/xml_iarchive.hpp>
#include <boost/archive/xml_oarchive.hpp>
#include <boost/serialization/string.hpp>
#include <boost/serialization/list.hpp>
#include <boost/uuid/uuid.hpp>
#include <boost/uuid/random_generator.hpp>
#include <boost/uuid/uuid_io.hpp>
#include <list>
#include <fstream>
#include <sstream>
#include <string>
#include <iostream>
#include <vector>
#include <sstream>
#include <ctime>
const char *xmlcontroler_buildString = "XMLControler 1.0 " __DATE__ ", " __TIME__ "\n";
const int MAXACCNR = 10;
#pragma region INTERFACES
extern "C" XMLCONTROLER_API void xmlcontroler_printVersion();
extern "C" XMLCONTROLER_API int xmlcontroler_createCustomer(char* firstName, char* lastname, char* tmpplzOrt, char* tmpstrasse, int tmphausNr);
extern "C" XMLCONTROLER_API bool xmlcontroler_deleteCustomerByID(int ID);
extern "C" XMLCONTROLER_API bool xmlcontroler_deleteCustomerByUUID(char* cusUUID);
extern "C" XMLCONTROLER_API int xmlcontroler_updateCustomer(int cusID, char* firstName, char* lastname, char* tmpplzOrt, char* tmpstrasse, int tmphausNr);
extern "C" XMLCONTROLER_API int xmlcontroler_renameCustomer(int cusID, char* firstName, char* lastname);
extern "C" XMLCONTROLER_API int xmlcontroler_createAccount(int tmpType, float tmpValue);
extern "C" XMLCONTROLER_API int xmlcontroler_closeAccount(int tmpAccID);
extern "C" XMLCONTROLER_API int xmlcontroler_manageAccount(int tmpAccID, int tmpType);
extern "C" XMLCONTROLER_API bool xmlcontroler_attachAccount(int tmpAccID, int tmpCusID);
extern "C" XMLCONTROLER_API bool xmlcontroler_dettachAccount(int tmpAccID, int tmpCusID);
extern "C" XMLCONTROLER_API bool xmlcontroler_transferMoney(int tmpFromAccID, int tmpToAccID, float tmpValue);
extern "C" XMLCONTROLER_API bool xmlcontroler_depositMoney(int tmpAccID, float tmpValue);
extern "C" XMLCONTROLER_API bool xmlcontroler_withdrawMoney(int tmpAccID, float tmpValue);
extern "C" XMLCONTROLER_API bool xmlcontroler_getBankStatement(int tmpAccID);
extern "C" XMLCONTROLER_API bool xmlcontroler_getBalance(int tmpCusID);
extern "C" XMLCONTROLER_API bool xmlcontroler_getAccsByCusID(int tmpCusID, int* outParam);
extern "C" XMLCONTROLER_API bool xmlcontroler_remoteTransaction(int tmpFromAccID, int tmpToAccID, int tmpFromBIC, int tmpToBic, float tmpValue, char* tmpPurpose);
#pragma endregion
using namespace std;
#pragma region ACCOUNT
class BankAccount
{
public:
BankAccount(int tmpID, int tmpType, float tmpValue);
BankAccount();
~BankAccount();
#pragma region GETTER
int get_accID()
{
return accID;
}
float get_value()
{
return value;
}
list<string>* get_transactions()
{
return &transaction;
}
#pragma endregion
#pragma region SETTER
void set_accID(int tmpBankID)
{
accID = tmpBankID;
}
void set_type(int tmpType)
{
type = tmpType;
}
void add_ownerID(int tmpOwnerID)
{
ownerIDs.push_back(tmpOwnerID);
}
void remove_ownerID(int tmpOwnerID)
{
ownerIDs.remove(tmpOwnerID);
}
void set_value(float tmpValue)
{
value = tmpValue;
}
/*void add_transaction(string tmpTransactionString)
{
transaction.push_back(tmpTransactionString);
}*/
#pragma endregion
private:
friend class boost::serialization::access;
template<class Archive>
void serialize(Archive & ar, const unsigned int version)
{
ar & BOOST_SERIALIZATION_NVP(accID);
ar & BOOST_SERIALIZATION_NVP(value);
ar & BOOST_SERIALIZATION_NVP(ownerIDs);
ar & BOOST_SERIALIZATION_NVP(transaction);
}
int accID;
// 0 = Spar; 1 = Kredit
int type;
float value;
list<int> ownerIDs;
list<string> transaction;
};
BankAccount::BankAccount(int tmpID, int tmpType, float tmpValue)
{
accID = tmpID;
value = tmpValue;
type = tmpType;
}
BankAccount::BankAccount()
{
}
BankAccount::~BankAccount()
{
}
#pragma endregion
#pragma region CUSTOMER
class MyCustomer
{
public:
MyCustomer();
~MyCustomer();
MyCustomer(int tmpCusID, char* tmpFirstName, char* tmpLastName, char* tmpplzOrt, char* tmpstrasse, int tmphausNr);
template<class Archive>
void do_serialize(Archive & ar, const unsigned int version);
#pragma region GETTER
int get_cusID()
{
return cusID;
}
string get_firstname()
{
return firstname;
}
string get_lastname()
{
return lastname;
}
list<BankAccount>* get_bankAccounts()
{
return &bankAccounts;
}
void addBankAccount(BankAccount tmpAcc)
{
bankAccounts.push_back(tmpAcc);
}
void removeBankAccount(BankAccount it1)
{
list<BankAccount>::iterator it;
list<BankAccount>::iterator it2;
bool dataFound = false;
for (it = bankAccounts.begin(); it != bankAccounts.end(); it++)
{
if ((*it).get_accID() == it1.get_accID())
{
//saving iterator/index
it2 = it;
dataFound = true;
}
}
if (dataFound)
{
//erase object after it was found and iterator is over
bankAccounts.erase(it2);
}
}
string get_plzOrt()
{
return plzOrt;
}
string get_Straße()
{
return strasse;
}
int get_hausNr()
{
return hausNr;
}
string get_cusUUID()
{
return cusUUID;
}
#pragma endregion
#pragma region SETTER
void set_cusID(int tmpCusID)
{
cusID = tmpCusID;
}
void set_firstname(char* tmpFirstname)
{
firstname = tmpFirstname;
}
void set_lastname(char* tmpLastname)
{
lastname = tmpLastname;
}
void set_bankAccounts(list<BankAccount>* tmpBankAccounts)
{
bankAccounts = *tmpBankAccounts;
}
void set_plzOrt(char* tmpPlzOrt)
{
plzOrt = tmpPlzOrt;
}
void set_Straße(char* tmpStrasse)
{
strasse = tmpStrasse;
}
void set_hausNr(int tmpHausNr)
{
hausNr = tmpHausNr;
}
void set_cusUUID(char* tmpCusUUID)
{
cusUUID = tmpCusUUID;
}
#pragma endregion
private:
friend class boost::serialization::access;
template<class Archive>
void serialize(Archive & ar, const unsigned int version)
{
ar & BOOST_SERIALIZATION_NVP(cusID);
ar & BOOST_SERIALIZATION_NVP(cusUUID);
ar & BOOST_SERIALIZATION_NVP(firstname);
ar & BOOST_SERIALIZATION_NVP(lastname);
ar & BOOST_SERIALIZATION_NVP(plzOrt);
ar & BOOST_SERIALIZATION_NVP(strasse);
ar & BOOST_SERIALIZATION_NVP(hausNr);
ar & BOOST_SERIALIZATION_NVP(bankAccounts);
}
int cusID;
string firstname;
string lastname;
string cusUUID;
string plzOrt;
string strasse;
int hausNr;
list<BankAccount> bankAccounts;
};
MyCustomer::MyCustomer(int tmpCusID, char* tmpFirstName, char* tmpLastName, char* tmpplzOrt, char* tmpstrasse, int tmphausNr)
{
//generate uuid; notice fancy ()()
boost::uuids::uuid uuid = boost::uuids::random_generator()();
cusID = tmpCusID;
//property should be used for real implementation of ID of object - too long for manual usage in dev environment
cusUUID = boost::uuids::to_string(uuid);
firstname = tmpFirstName;
lastname = tmpLastName;
plzOrt = tmpplzOrt;
strasse = tmpstrasse;
hausNr = tmphausNr;
}
MyCustomer::MyCustomer()
{
}
MyCustomer::~MyCustomer()
{
}
template<class Archive>
void MyCustomer::do_serialize(Archive & ar, const unsigned int version)
{
serialize(ar, version);
}
#pragma endregion
#pragma region DATAROOT
class DataRoot
{
private:
static bool instanceFlag;
static DataRoot *singDataRoot;
DataRoot()
{
//private constructor
}
list<MyCustomer> bankCustomers;
list<BankAccount> bankAccounts;
friend class boost::serialization::access;
template<class Archive>
void serialize(Archive & ar, const unsigned int version)
{
ar & BOOST_SERIALIZATION_NVP(bankCustomers);
ar & BOOST_SERIALIZATION_NVP(bankAccounts);
}
template<class Archive>
void deserialize(Archive & ar, const unsigned int version)
{
ar & ar & BOOST_SERIALIZATION_NVP(bankCustomers);
ar & ar & BOOST_SERIALIZATION_NVP(bankAccounts);
}
public:
static DataRoot* getInstance();
~DataRoot()
{
instanceFlag = false;
}
static bool fileExists(const string& name) {
ifstream f(name.c_str());
return f.good();
}
//generates not existing customer ID returns -1 if error (sets Max count of customers to 20k)
static int getFreeCusID()
{
DataRoot *dr = DataRoot::getInstance();
list<MyCustomer>* tmpCusList = dr->get_bankCustomer();
list<MyCustomer>::iterator it;
bool check = false;
int i = 0;
while (!check)
{
check = true;
for (it = tmpCusList->begin(); it != tmpCusList->end(); it++)
{
if ((*it).get_cusID() == i)
{
check = false;
}
}
if (check)
return i;
if (i >= CUSCNTMAX)
{
cout << "Data storage full! Please delete a customer before creating a new one." << endl;
return -1;
}
i++;
}
return -1;
}
//generates not existing customer ID returns -1 if error (sets Max count of customers to 20k)
static int getFreeAccID()
{
DataRoot *dr = DataRoot::getInstance();
list<BankAccount>* tmpAccList = dr->get_bankAccount();
list<BankAccount>::iterator it;
bool check = false;
int i = 0;
while (!check)
{
check = true;
for (it = tmpAccList->begin(); it != tmpAccList->end(); it++)
{
if ((*it).get_accID() == i)
{
check = false;
}
}
if (check)
{
return i;
}
if (i >= ACCCNTMAX)
{
cout << "Data storage full! Please delete an account before creating a new one." << endl;
return -1;
}
i++;
}
return -1;
}
template<class Archive>
void do_serialize(Archive & ar, const unsigned int version);
template<class Archive>
void do_deserialize(Archive & ar, const unsigned int version);
void addBankAcc(BankAccount *tmpAcc)
{
bankAccounts.push_back(*tmpAcc);
}
void addCustomer(MyCustomer *tmpCus)
{
bankCustomers.push_back(*tmpCus);
}
list<MyCustomer>* get_bankCustomer()
{
return &bankCustomers;
}
list<BankAccount>* get_bankAccount()
{
return &bankAccounts;
}
};
template<class Archive>
void DataRoot::do_serialize(Archive & ar, const unsigned int version)
{
//saving data
serialize(ar, version);
}
template<class Archive>
void DataRoot::do_deserialize(Archive & ar, const unsigned int version)
{
//saving data
serialize(ar, version);
}
bool DataRoot::instanceFlag = false;
DataRoot* DataRoot::singDataRoot = NULL;
DataRoot* DataRoot::getInstance()
{
if (!instanceFlag)
{
singDataRoot = new DataRoot();
instanceFlag = true;
return singDataRoot;
}
else
{
return singDataRoot;
}
}
#pragma endregion
|
#ifndef EXCEPTION_523908571309_HEADER
#define EXCEPTION_523908571309_HEADER
#include <stdexcept>
namespace solar
{
//Exception class used by this program
//Derived from std::runtime_error(so from std::exception too)
class Exception : public std::runtime_error
{
using std::runtime_error::runtime_error;
};
}
#endif
|
class gvert{
public:
vect pos;
vect nor;
};
class gedge{
public:
gvert ** ver;
vect dir;
bool ini;
gedge(){
ini = false;
}
void set(gvert * av0, gvert * av1){
if(ini){
delete[] ver;
ini = false;
}
if(av0==NULL||av1==NULL){
return;
}
ver = new gvert*[2];
ver[0] = av0;
ver[1] = av1;
dir = norm(ver[1]->pos - ver[0]->pos);
ini = true;
}
void clear(){
ini = false;
delete[] ver;
}
};
class gtile{
public:
gvert ** ver;
vect nor;
Uint16 mat;
bool ini;
gtile(){
ini = false;
}
void set(gvert * av0, gvert * av1, gvert * av2){
if(ini){
delete[] ver;
ini = false;
}
if(av0==NULL||av1==NULL||av2==NULL){
return;
}
ver = new gvert*[3];
ver[0] = av0;
ver[1] = av1;
ver[2] = av2;
nor = (ver[2]->pos-ver[1]->pos)^(ver[0]->pos-ver[1]->pos);
ver[0]->nor += nor;
ver[1]->nor += nor;
ver[2]->nor += nor;
nor = norm(nor);
ini = true;
return;
}
void draw(){
if(!ini){return;}
//glNormalv(nor);
glNormalv(ver[0]->nor);
glTexCoord2f(0.4f*ver[0]->pos.x,0.4f*ver[0]->pos.y);
glVertexv(ver[0]->pos);
glNormalv(ver[1]->nor);
glTexCoord2f(0.4f*ver[1]->pos.x,0.4f*ver[1]->pos.y);
glVertexv(ver[1]->pos);
glNormalv(ver[2]->nor);
glTexCoord2f(0.4f*ver[2]->pos.x,0.4f*ver[2]->pos.y);
glVertexv(ver[2]->pos);
}
void clear(){
ini = false;
delete[] ver;
}
};
/*class garea{
public:
gvert ** ver; unsigned int nver;
gedge ** edg; unsigned int nedg;
gtile ** til; unsigned int ntil;
float lev;
float bx,ex,by,ey;
void build(){
}
bool under(vect ac){
if(ac.z>lev){return false;}
return true;
}
bool inside(vect ac){
if(ac.x>=bx&&ac.x<=ex&&ac.y>=by&&ac.y<=ey){
return true;
}
return false;
}
};*/
float ground_friction = 2.0f;
class ground{
private:
gvert * ver; unsigned int nver;
gedge * edg; unsigned int nedg;
gtile * til; unsigned int ntil;
public:
void init(){
unsigned int size = 16;
nver = size*size;
nedg = 3*(size-1)*(size-1);
ntil = 2*(size-1)*(size-1);
ver = new gvert[nver];
edg = new gedge[nedg];
til = new gtile[ntil];
for(unsigned int ix=0;ix<size;ix++){
for(unsigned int iy=0;iy<size;iy++){
ver[ix*size+iy].pos.set(ix*4,iy*4,-256.0f/(float)(32+(ix-size/2)*(ix-size/2)+(iy-size/2)*(iy-size/2)));
}
}
for(unsigned int ix=0;ix<size-1;ix++){
for(unsigned int iy=0;iy<size-1;iy++){
edg[3*(ix*(size-1)+iy)].set(&ver[ix*size+iy],&ver[ix*size+iy+1]);
edg[3*(ix*(size-1)+iy)+1].set(&ver[ix*size+iy],&ver[(ix+1)*size+iy]);
edg[3*(ix*(size-1)+iy)+2].set(&ver[ix*size+iy+1],&ver[(ix+1)*size+iy]);
}
}
for(unsigned int ix=0;ix<size-1;ix++){
for(unsigned int iy=0;iy<size-1;iy++){
til[2*(ix*(size-1)+iy)].set(&ver[ix*size+iy+1],&ver[ix*size+iy],&ver[(ix+1)*size+iy]);
til[2*(ix*(size-1)+iy)+1].set(&ver[(ix+1)*size+iy+1],&ver[ix*size+iy+1],&ver[(ix+1)*size+iy]);
}
}
for(unsigned int i=0;i<nver;i++){
ver[i].nor = norm(ver[i].nor);
}
}
bool insidetest(gtile * til, vect p){
if((((til->ver[1]->pos-til->ver[0]->pos)^(p-til->ver[0]->pos))*til->ver[0]->nor>=0.0f)&&
(((til->ver[2]->pos-til->ver[1]->pos)^(p-til->ver[1]->pos))*til->ver[1]->nor>=0.0f)&&
(((til->ver[0]->pos-til->ver[2]->pos)^(p-til->ver[2]->pos))*til->ver[2]->nor>=0.0f)){
return true;
}
return false;
}
vect direct(gtile * til, vect p, vect d){//d must be normalized
return p+d*((p-til->ver[0]->pos)*til->nor);
}
bool directinsidetest(gtile * til, vect p, vect d){
return insidetest(til,direct(til,p,d));
}
float depthtest(gtile * til, vect p){
return til->nor*(p-til->ver[0]->pos);
}
void roll(solid * sol, ressor * res, wheel * whe){
for(unsigned int i=0;i<ntil;i++){
vect p = direct(&til[i],res->fv->c+whe->hvd*whe->nor,-whe->top);
if(insidetest(&til[i],p)){
float d = (p-res->fv->c)*(-whe->top) - whe->rad;
if(d<res->dev&&d>=-res->mln){
res->dev = d;
res->nor = til[i].nor;
if(!whe->st){
vect nfw;
if(!whe->a){
nfw = sol->c.s + (sol->o.s^(p-sol->c.c));
}
else{
//nfw = whe->a*sec*(whe->top^whe->nor);//discrete transmission without differential
//nfw = 12*whe->a*sec*(whe->top^whe->nor) + (sol->o.s^(p-sol->c.c));//discrete transmission with differential
nfw = sol->c.s + (sol->o.s^(p-sol->c.c)) + whe->a*sec*(whe->top^whe->nor);//sliding auto-transmission
}
nfw -= (nfw*til[i].nor)*til[i].nor;
nfw -= (nfw*whe->nor)*whe->nor;
nfw = nfw*0.996f;
sol->frict((p-sol->c.c),til[i].nor,nfw,ground_friction*res->force());
whe->s = (nfw^(whe->top/whe->rad))*whe->nor;
}
else{
sol->frict((p-sol->c.c),til[i].nor,NUL,ground_friction*res->force());
}
}
}
}
}
void draw(){
for(unsigned int i=0;i<ntil;i++){
til[i].draw();
}
}
void remove(){
nver = 0;
delete[] ver;
for(unsigned int i=0;i<nedg;i++){
edg[i].clear();
}
nedg = 0;
delete[] edg;
for(unsigned int i=0;i<ntil;i++){
til[i].clear();
}
ntil = 0;
delete[] til;
}
};
|
#include "DemoJavaLexer.hpp"
#include "DemoJavaDocLexer.hpp"
#include "DemoJavaParser.hpp"
#include "antlr/TokenStreamSelector.hpp"
#include <iostream>
int main()
{
ANTLR_USING_NAMESPACE(std)
ANTLR_USING_NAMESPACE(antlr)
// Define a selector that can switch from java to javadoc
TokenStreamSelector selector;
try {
// attach java lexer to the input stream, which also creates a shared input state object
DemoJavaLexer main(cin);
main.setSelector(&selector);
// create javadoc lexer; attach to same shared input state as java lexer
DemoJavaDocLexer doclexer(main.getInputState());
doclexer.setSelector(&selector);
// notify selector about various lexers; name them for convenient reference later
selector.addInputStream(&main, "main");
selector.addInputStream(&doclexer, "doclexer");
selector.select("main"); // start with main java lexer
// Create parser attached to selector
DemoJavaParser parser(selector);
// Pull in one or more int decls with optional javadoc
parser.input();
// spin thru all tokens generated via the SELECTOR.
RefToken t;
while ( (t=selector.nextToken())->getType()!=Token::EOF_TYPE ) {
cout << t->toString() << endl;
}
}
catch(exception& e) {
cerr << "exception: " << e.what() << endl;
}
}
|
//
// Created by Nitish Mohan Shandilya on 9/9/20.
//
// Test cases vector 1a, 1b,
// Given two vectors T and R, find the score of passing test cases
// Only if all the tests in the group is passed, then only the entire group is
// a pass.
class Solution {
unordered_map<int, vector<int>> lookupMap;
void buildLookupMap(vector<string>& tests, vector<string>& results) {
string prefix = tests[0];
int prefixIndex=0;
while (prefixIndex<prefix.length() && !isdigit(prefix[prefixIndex])) {
++prefixIndex;
}
for (int i=0; i<tests.size(); ++i) {
string& test = tests[i];
int numPart = getNumber(test, prefixIndex);
auto it = lookupMap.find(numPart);
if (it == lookupMap.end()) {
lookupMap.insert({numPart, initializer_list<int>{i}});
} else {
lookupMap[numPart].push_back(i);
}
}
}
int getNumber(string& test, int prefixIndex) {
string buffer;
while (prefixIndex<test.length() && isdigit(test[prefixIndex])) {
buffer.push_back(test[prefixIndex]);
++prefixIndex;
}
return stoi(buffer);
}
public:
int computeResult(vector<string>& tests, vector<string>& results) {
buildLookupMap(tests, results);
int totalPassCount = 0;
for (auto ele : lookupMap) {
int test = ele.first;
vector<int>& rIndices = ele.second;
if (rIndices.size() == 1 && results[rIndices[0]] == "OK") {
++totalPassCount;
continue;
}
int passCount = 0;
for (int rIndex : rIndices) {
if (results[rIndex] == "OK")
++passCount;
}
if (rIndices.size() == passCount)
++totalPassCount;
}
int result = (totalPassCount*100)/lookupMap.size();
return result;
}
};
int main() {
std::cout << "Hello World!\n";
vector<string> tests =
{"codility2", "codility1a", "codility1b", "codility3"};
vector<string> results = {"OK", "OK", "OK", "Runtime"};
Solution s;
cout << s.computeResult(tests, results);
}
|
#include<bits/stdc++.h>
using namespace std;
// Right most set bit => number & (two's compliment of number( ~number+1))
int main()
{
int n;
cin >> n;
cout << n&(-n) << endl;
return 0;
}
|
#pragma once
#include <landstalker-lib/patches/game_patch.hpp>
#include <landstalker-lib/model/map.hpp>
#include <landstalker-lib/constants/map_codes.hpp>
/**
* This patch optimizes a few laggy Tibor map by removing a few ghosts which are almost unnoticeable.
*/
class PatchOptimizeTiborMaps : public GamePatch
{
public:
void alter_world(World& world) override
{
// Remove a few ghosts from laggy Tibor maps
world.map(MAP_TIBOR_808)->remove_entity(5);
world.map(MAP_TIBOR_811)->remove_entity(4);
world.map(MAP_TIBOR_812)->remove_entity(2);
world.map(MAP_TIBOR_815)->remove_entity(3);
}
};
|
// This file has been generated by Py++.
#ifndef ImageryComponentVector_hpp__pyplusplus_wrapper
#define ImageryComponentVector_hpp__pyplusplus_wrapper
void register_ImageryComponentVector_class();
#endif//ImageryComponentVector_hpp__pyplusplus_wrapper
|
#ifndef GAMESTATE_H
#define GAMESTATE_H
#include "states/State.h"
#include "models/Model.h"
#include "scene/Scene.h"
#include "maths/Camera.h"
#include <GxPhysics/GxPhysicsModel.h>
#include <pcx/signals.h>
class Graphics;
class TestPc;
class GameState : public State
{
public:
explicit GameState(Events &events, Graphics &graphics);
virtual bool update(AppParams ¶ms, Events &events, float delta) override;
virtual void render(Graphics &graphics, float blend) override;
private:
void keyPressed(int key);
Graphics &graphics;
pcx::connections cx;
Gx::PhysicsModel physics;
Model model;
Scene scene;
Camera cam;
Gx::Vec3 light;
TestPc *pc;
int shapes;
float time;
bool drawPhysics;
bool drawSkeleton;
bool hasClosed;
};
#endif // GAMESTATE_H
|
/*
* Copyright 2012 Free Software Foundation, Inc.
*
* This file is part of GNU Radio
*
* GNU Radio 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, or (at your option)
* any later version.
*
* GNU Radio 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 GNU Radio; see the file COPYING. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street,
* Boston, MA 02110-1301, USA.
*/
#include "pmt_defs.h"
#include <gruel/pmt_blob.h>
#include <boost/shared_array.hpp>
#include <stdexcept>
#define PMT_BLOB_ALIGN_MASK size_t(0x1f) //byte alignment mask of self-allocated blobs
namespace pmt {
static inline std::vector< boost::uint8_t > &extract_vec(pmt_t blob)
{
return reinterpret_cast<pmt_u8vector *>(blob.get())->d_v;
}
pmt_t pmt_make_blob(size_t len_in_bytes)
{
pmt_t blob = pmt_make_u8vector(len_in_bytes, 0);
//maybe not needed, but I wanted to call reserve
//since it can be resized to sub-max size later
extract_vec(blob).reserve(len_in_bytes);
return blob;
}
void pmt_blob_resize(pmt_t blob, size_t len_in_bytes)
{
//lazy way to ensure the type is correct
if (!pmt_is_blob(blob))
{
throw std::invalid_argument("pmt_blob_resize: got wrong type");
}
extract_vec(blob).resize(len_in_bytes);
}
void *pmt_blob_rw_data(pmt_t blob)
{
return &extract_vec(blob).front();
}
class pmt_blob
{
public:
typedef boost::shared_array<char> shart;
pmt_blob(void *, size_t, shart);
void *mem;
size_t len;
shart shar;
};
pmt_blob::pmt_blob(void *m, size_t l, shart s = shart()):
mem(m), len(l), shar(s){}
bool pmt_is_ext_blob(pmt_t obj)
{
if (!pmt_is_any(obj)) return false;
try
{
boost::any_cast<pmt_blob>(pmt_any_ref(obj));
}
catch(const boost::bad_any_cast &)
{
return false;
}
return true;
}
pmt_t pmt_make_ext_blob(size_t len)
{
pmt_blob::shart shar(new char[len + PMT_BLOB_ALIGN_MASK]);
const size_t addr = (size_t(shar.get()) + PMT_BLOB_ALIGN_MASK) & ~PMT_BLOB_ALIGN_MASK;
char *mem = reinterpret_cast<char *>(addr);
pmt_blob blob(mem, len, shar);
return pmt_make_any(blob);
}
void *pmt_ext_blob_data(pmt_t blob)
{
if (!pmt_is_ext_blob(blob))
throw pmt_wrong_type("pmt_blob_data", blob);
return boost::any_cast<pmt_blob>(pmt_any_ref(blob)).mem;
}
size_t pmt_ext_blob_length(pmt_t blob)
{
if (!pmt_is_ext_blob(blob))
throw pmt_wrong_type("pmt_blob_length", blob);
return boost::any_cast<pmt_blob>(pmt_any_ref(blob)).len;
}
void pmt_ext_blob_set_length(pmt_t blob, size_t len_in_bytes)
{
if (!pmt_is_ext_blob(blob))
throw pmt_wrong_type("pmt_blob_set_length", blob);
pmt_blob b = boost::any_cast<pmt_blob>(pmt_any_ref(blob));
b.len = len_in_bytes;
pmt_any_set(blob, b);
}
}//namespace pmt
|
/***************************************************************************
Copyright (c) 2020 Philip Fortier
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 2
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.
***************************************************************************/
#pragma once
#include "ParseAutoCompleteContext.h"
// Common parser routines
#ifdef DEBUG
// Uncomment this to get parsing debug spew. It's still very flaky
// #define PARSE_DEBUG 1
#endif
//
// Syntax parser inspired by boost's Spirit (but much less flexible and more performant)
//
#ifdef DEBUG
#define _DEBUG_PARSER(x) (x).SetName(#x);
#else
#define _DEBUG_PARSER(x)
#endif
namespace sci
{
enum class CommentType;
}
//
// A comment was detected - add it (text and endpoints) to the script.
//
template<typename TContext, typename _It>
inline void _DoComment(TContext *pContext, const _It &streamBegin, const _It &streamEnd, sci::CommentType type)
{
std::string comment;
// Transfer to string:
copy(streamBegin, streamEnd, back_inserter(comment));
// Create a new Comment syntax node and add it to the script
std::unique_ptr<sci::Comment> pComment = std::make_unique<sci::Comment>(comment, type); // TODO
if (type == sci::CommentType::Positioned)
{
// Positioned comments look bad if they are preceded by tabs, which they commonly are (e.g. after class properties)
// The find screen positioned based on an estimated tab size. This is a hack, but helps with the conversion of old games to the new syntax.
LineCol begin = streamBegin.GetPosition();
LineCol end = streamEnd.GetPosition();
int actualStart = streamBegin.CountPosition(4);
int length = end.Column() - begin.Column();
assert(begin.Line() == end.Line()); // Otherwise it shouldn't be positioned.
pComment->SetPosition(LineCol(begin.Line(), actualStart));
pComment->SetEndPosition(LineCol(end.Line(), actualStart + length));
}
else
{
pComment->SetPosition(streamBegin.GetPosition());
pComment->SetEndPosition(streamEnd.GetPosition());
}
pContext->TryAddCommentDirectly(pComment);
if (pComment)
{
pContext->Script().AddComment(move(pComment));
}
}
class EatCommentCpp
{
public:
// c++ style comments:
// // and /***/
template<typename TContext, typename _It>
static void EatWhitespaceAndComments(TContext *pContext, _It &stream)
{
bool fDone = false;
while (!fDone)
{
fDone = true;
// Eat whitespace
while (isspace(*stream))
{
fDone = false;
++stream;
}
_It streamSave(stream);
if (*stream == '/')
{
char ch = *(++stream);
if (ch == '/')
{
// Indicate we're in a comment for autocomplete's sake
if (pContext)
{
pContext->PushParseAutoCompleteContext(BlockAllChannels);
}
// Go until end of line
while ((ch = *(++stream)) && (ch != '\n')) {} // Look for \n or EOF
fDone = false; // Check for whitespace again
// Comment gathering. This may be expensive, so only do this if pContext is non-NULL
if (pContext)
{
pContext->PopParseAutoCompleteContext();
// If there were previous non-whitespace chars on this line, consider this comment "positioned".
bool foundNonWhitespace = false;
_It streamLineBegin(streamSave);
streamLineBegin.ResetLine();
while (!foundNonWhitespace && (streamLineBegin != streamSave))
{
foundNonWhitespace = !isspace(*streamLineBegin);
++streamLineBegin;
}
if (pContext->CollectComments())
{
sci::CommentType type = foundNonWhitespace ? sci::CommentType::Positioned : sci::CommentType::Indented;
_DoComment(pContext, streamSave, stream, type);
}
}
if (ch == '\n') // As opposed to EOF
{
++stream; // Move past \n now that we've done _DoComment. Otherwise the comment will be tagged as ending on the next line.
}
}
else if (ch == '*')
{
// Indicate we're in a comment for autocomplete's sake
if (pContext)
{
pContext->PushParseAutoCompleteContext(BlockAllChannels);
}
// Go until */
bool fLookingForSlash = false;
while (TRUE)
{
ch = *(++stream);
if (ch == 0)
{
break;
}
else if (ch == '*')
{
fLookingForSlash = true;
}
else if (fLookingForSlash)
{
if (ch == '/')
{
break; // We found a */
}
else
{
fLookingForSlash = false;
}
}
}
if (ch == '/') // As opposed to 0
{
++stream; // Move past '/'
}
if (pContext)
{
pContext->PopParseAutoCompleteContext();
if (pContext->CollectComments())
{
_DoComment(pContext, streamSave, stream, sci::CommentType::LeftJustified);
}
}
fDone = false; // Check for whitespace again
}
else
{
// We're done.
stream = streamSave;
fDone = true;
}
}
}
}
};
class EatCommentSemi
{
public:
// Semi-colon style comments:
// ;
template<typename TContext, typename _It>
static void EatWhitespaceAndComments(TContext *pContext, _It &stream)
{
bool fDone = false;
while (!fDone)
{
fDone = true;
// Eat whitespace
// REVIEW: We need to audit all our uses of isspace, and cast char to unsigned char before passing to isspace.
// Otherwise, isspace asserts for chars over 127.
while (isspace(*stream))
{
fDone = false;
++stream;
}
_It streamSave(stream);
if (*stream == ';')
{
// Indicate we're in a comment for autocomplete's sake
if (pContext)
{
pContext->PushParseAutoCompleteContext(BlockAllChannels);
}
char ch;
// Go until end of line, after counting the number of semicolons
int semiCount = 0;
while ((ch = *stream) && (ch == ';'))
{
semiCount++;
++stream;
}
// Now stream points to after the semicolons
while ((ch = *stream) && (ch != '\n')) { ++stream; } // Look for \n or EOF
// Now stream points to after the newline
fDone = false; // Check for whitespace again
// Comment gathering. This may be expensive, so only do this if pContext is non-NULL
if (pContext)
{
pContext->PopParseAutoCompleteContext();
// ; -> positinoed
// ;; -> indented to code level
// ;;; -> left-justified
if (pContext->CollectComments())
{
sci::CommentType type = (semiCount == 1) ? sci::CommentType::Positioned : ((semiCount == 2) ? sci::CommentType::Indented : sci::CommentType::LeftJustified);
_DoComment(pContext, streamSave, stream, type);
}
}
if (ch == '\n') // As opposed to EOF
{
++stream; // Move past \n now that we've done _DoComment. Otherwise the comment will be tagged as ending on the next line.
}
}
}
}
};
template<typename _TContext>
struct BlockAllACChannelsGuard
{
BlockAllACChannelsGuard(_TContext *pContext) : _pContext(pContext)
{
if (_pContext) _pContext->PushParseAutoCompleteContext(BlockAllChannels);
}
~BlockAllACChannelsGuard()
{
if (_pContext) _pContext->PopParseAutoCompleteContext();
}
private:
_TContext *_pContext;
};
//
// Optimized delimiter reader for SCI Script
//
// Unlike for SCI Studio script, this continues until the closing quote (instead of dealing with '+')
//
// Forced spaces are indicated by underscores.
// Underscores are indicated by \_
//
template<typename _TContext, typename _It, char Q1, char Q2>
bool _ReadStringSCI(_TContext *pContext, _It &stream, std::string &str)
{
str.clear();
if (Q1 == *stream)
{
BlockAllACChannelsGuard<_TContext> blockGuard(pContext);
char chPrev = 0;
char ch;
// Continue while no EOF, and while the character isn't the closing quote
// (unless the previous character was an escape char)
bool fEscape = false;
bool addedSpace = false;
bool lookingForSecondHex = false;
int chHex = 0;
while ((ch = *(++stream)) && ((ch != Q2) || fEscape))
{
chPrev = ch;
bool processCharNormally = true;
if (lookingForSecondHex)
{
if (isxdigit(ch))
{
chHex *= 16;
chHex += charToI(ch);
str += (char)chHex;
} // Otherwise, just ignore the whole thing
processCharNormally = false;
}
lookingForSecondHex = false;
if (fEscape)
{
processCharNormally = false;
// Last char was an escape
switch (ch)
{
case 'n':
str += '\n';
break;
case 't':
str += '\t';
break;
case '_':
// \_ is an underscore.
str += "_";
break;
case '\\':
// "\\" should output a single backslash, "\"
str += '\\';
break;
case Q2:
str += Q2;
break;
default:
if (isxdigit((uint8_t)ch))
{
chHex = charToI(ch);
lookingForSecondHex = true;
}
else
{
// The following char was not an escape char. Don't output the "\" char, just the one that followed.
processCharNormally = true; // Add the current char
}
}
}
fEscape = false;
if (processCharNormally)
{
if (isspace((uint8_t)ch))
{
// Add one space for all continguous whitespace
if (!addedSpace)
{
str += ' ';
}
addedSpace = true;
}
else
{
addedSpace = false; // Reset this
if (ch == '\\')
{
// Escape char, don't add to string.
fEscape = true;
}
else if (ch == '_')
{
// Underscores are forced spaces
str += ' ';
}
else
{
str += ch;
}
}
}
}
if (ch == Q2)
{
++stream;
return true; // We're done
}
else
{
assert(ch == 0); // EOF
return false;
}
}
return false;
}
template<typename _TContext>
class IndicateStringType
{
public:
IndicateStringType(_TContext *pContext, char c) : _pContext(pContext)
{
if (_pContext) _pContext->CurrentStringType = c;
}
~IndicateStringType()
{
if (_pContext) _pContext->CurrentStringType = 0;
}
private:
_TContext *_pContext;
};
//
// Optimized delimiter reader
//
template<typename _TContext, typename _CommentPolicy, typename _It, char Q1, char Q2>
bool _ReadStringStudio(_TContext *pContext, _It &stream, std::string &str)
{
IndicateStringType<_TContext> indicateStringType(pContext, Q1);
str.clear();
while (Q1 == *stream)
{
BlockAllACChannelsGuard<_TContext> blockGuard(pContext);
char chPrev = 0;
char ch;
// Continue while no EOF, and while the character isn't the closing quote
// (unless the previous character was an escape char)
bool fEscape = false;
while ((ch = *(++stream)) && ((ch != Q2) || (chPrev == '\\')))
{
chPrev = ch;
if (!fEscape)
{
if (ch == '\\')
{
// Escape char, don't add to strign.
fEscape = true;
}
else
{
str += ch;
}
}
else
{
// Last char was an escape char.
fEscape = false;
switch(ch)
{
case 'n':
str += '\n';
break;
case 't':
str += '\t';
break;
default:
str += ch;
break;
}
}
}
if (ch == Q2)
{
++stream;
if (*stream == '+')
{
// If we encountered a '+', then skip whitespace until we hit another open quote
// "huwehuierger"+ "gejriger"
++stream;
_CommentPolicy::EatWhitespaceAndComments<_TContext, _It>(nullptr, stream);
// ... and continue...
}
else
{
return true; // We're done
}
}
else
{
ASSERT(ch == 0); // EOF
return false;
}
}
return false;
}
int charToI(char ch);
class MatchResult
{
public:
MatchResult() = delete;
MatchResult(bool fResult) : _fResult(fResult) {}
MatchResult(const MatchResult &src) = default;
MatchResult& operator=(const MatchResult& src) = default;
~MatchResult() { }
void ChangeResult(bool result) {
_fResult = result;
}
bool Result() { return _fResult; }
private:
bool _fResult;
};
template<typename _TContext, typename _It, typename _CommentPolicy>
class ParserBase : private _CommentPolicy
{
using _CommentPolicy::EatWhitespaceAndComments;
public:
#ifdef DEBUG
void SetName(const std::string &name) { Name = name; }
std::string Name;
#endif
typedef bool(*MATCHINGFUNCTION)(const ParserBase *pParser, _TContext *pContext, _It &stream);
typedef void(*DEBUGFUNCTION)(bool fEnter, bool fResult);
typedef void(*ACTION)(MatchResult &match, const ParserBase *pParser, _TContext *pContext, const _It &stream);
struct ActionAndContext
{
ACTION pfn;
ParseAutoCompleteContext pacc;
PCSTR pszDebugName;
};
struct ActionAndContexts
{
ACTION pfn;
ParseACChannels paccs;
PCSTR pszDebugName;
};
// Fwd decl (Used for circular references in grammer descriptions)
// If an empty Parser is created (since you need to refer to it subsequently, but you can't
// define it yet), it will be endowed with this matching function.
template<typename _It>
bool static ReferenceForwarderP(const ParserBase *pParser, _TContext *pContext, _It &stream)
{
assert(FALSE);
return false; // Just a dummy return value
}
template<typename _It>
void static CopyParserVector(std::vector<std::unique_ptr<ParserBase>> &out, const std::vector<std::unique_ptr<ParserBase>> &in)
{
out.clear();
for (auto &parser : in)
{
std::unique_ptr<ParserBase> pCopy = std::make_unique<ParserBase>(*parser);
out.push_back(std::move(pCopy));
}
}
ParserBase(const ParserBase& src)
{
// Allocate new Parser objects
if (src._fOnlyRef)
{
_pa.reset(nullptr);
_psz = nullptr;
_pRef = &src;
_pfn = ReferenceForwarderP<_It>;
_pfnA = nullptr;
_pacc = NoChannels;
_pfnDebug = nullptr;
_fLiteral = false; // Doesn't matter
_fOnlyRef = false; // We're a ref, so people can copy us.
//assert(src._pfn != ReferenceForwarderP<_It>);
}
else
{
_pa.reset(src._pa ? new ParserBase(*src._pa) : nullptr);
_psz = src._psz; // Ok, because this is always a static string
_pfn = src._pfn;
_pfnA = src._pfnA;
_pacc = src._pacc;
_pfnDebug = src._pfnDebug;
_pRef = src._pRef; // Don't make a new object.
_fLiteral = src._fLiteral;
_fOnlyRef = false; // Copied parsers are temporary objects, generally, and so we shouldn't take references to them.
if (src._pfn == nullptr)
{
// No matching function means this is an empty parser... pass a ref to the source
_pRef = &src;
_pfn = ReferenceForwarderP<_It>;
assert(src._pfn != ReferenceForwarderP<_It>);
}
CopyParserVector<_It>(_parsers, src._parsers);
}
#ifdef DEBUG
Name = src.Name;
#endif
}
ParserBase& operator=(const ParserBase& src)
{
if (this != &src)
{
// Allocate new Parser objects
_pa.reset(src._pa ? new ParserBase(*src._pa) : nullptr);
_psz = src._psz; // Ok, because this is always a static string
_pfn = src._pfn;
_pfnA = src._pfnA;
_pacc = src._pacc;
_pfnDebug = src._pfnDebug;
_pRef = src._pRef; // Don't make a new object.
_fLiteral = src._fLiteral;
assert(_fOnlyRef);
if ((src._pfn == nullptr) || src._fOnlyRef)
{
//assert(FALSE); // We probably never hit this - but if we do, we should check if things are right.
// No matching function means this is an empty parser... pass a ref to the source
_pRef = &src;
_pfn = ReferenceForwarderP<_It>;
}
else
{
CopyParserVector<_It>(_parsers, src._parsers);
}
#ifdef DEBUG
Name = src.Name;
#endif
}
return *this;
}
// The default constructor will create an object that can only be copied by reference (see the copy constructor
// and == operator, and _pRef)
ParserBase() : _pfn(nullptr), _pfnA(nullptr), _pfnDebug(nullptr), _pRef(nullptr), _fLiteral(false), _fOnlyRef(true), _psz(nullptr), _pacc(NoChannels) {}
ParserBase(MATCHINGFUNCTION pfn) : _pfn(pfn), _pfnA(nullptr), _pfnDebug(nullptr), _pRef(nullptr), _fLiteral(false), _fOnlyRef(false), _psz(nullptr), _pacc(NoChannels) {}
ParserBase(MATCHINGFUNCTION pfn, const ParserBase &a) : _pfn(pfn), _pa(new ParserBase(a)), _pfnA(nullptr), _pfnDebug(nullptr), _pRef(nullptr), _fLiteral(false), _fOnlyRef(false), _psz(nullptr), _pacc(NoChannels) {}
ParserBase(MATCHINGFUNCTION pfn, const char *psz) : _pfn(pfn), _psz(psz), _pfnA(nullptr), _pfnDebug(nullptr), _pRef(nullptr), _fLiteral(false), _fOnlyRef(false), _pacc(NoChannels)
{
}
MatchResult Match(_TContext *pContext, _It &stream) const
{
assert(_pfn);
if (!_fLiteral)
{
EatWhitespaceAndComments<_TContext, _It>(pContext, stream);
}
_It streamSave(stream);
#ifdef PARSE_DEBUG
string text;
if (pContext->ParseDebug && (!Name.empty() || _psz))
{
text = stream.GetLookAhead(5);
string name = !Name.empty() ? Name : _psz;
std::stringstream ss;
string spaces;
spaces.append(pContext->ParseDebugIndent, ' ');
ss << spaces << "-->Matching " << name << " against " << text << "\n";
OutputDebugString(ss.str().c_str());
}
pContext->ParseDebugIndent++;
#endif
pContext->PushParseAutoCompleteContext(_pacc);
MatchResult result(_pRef ? _pRef->Match(pContext, stream) : (*_pfn)(this, pContext, stream));
pContext->PopParseAutoCompleteContext();
#ifdef PARSE_DEBUG
pContext->ParseDebugIndent--;
if (pContext->ParseDebug && (!Name.empty() || _psz))
{
string name = !Name.empty() ? Name : _psz;
std::stringstream ss;
string spaces;
spaces.append(pContext->ParseDebugIndent, ' ');
ss << spaces << (result.Result() ? " TRUE" : " FALSE") << "\n";
OutputDebugString(ss.str().c_str());
}
#endif
if (_pfnA)
{
(*_pfnA)(result, this, pContext, stream);
}
if (!result.Result())
{
// Revert the stream to what it was when we came in this function (after whitespace)
stream.Restore(streamSave);
}
return result;
}
// This is for actions.
ParserBase operator[](ACTION pfn)
{
assert(_pfnA == nullptr); // Ensure we're not overwriting any action.
ParserBase newOne(*this);
newOne._pfnA = pfn;
return newOne;
}
ParserBase operator[](ActionAndContext aac)
{
assert(_pfnA == nullptr); // Ensure we're not overwriting any action.
ParserBase newOne(*this);
newOne._pfnA = aac.pfn;
newOne._pacc = SetChannel(newOne._pacc, ParseAutoCompleteChannel::One, aac.pacc);
#ifdef PARSE_DEBUG
if (aac.pszDebugName)
{
newOne.Name = aac.pszDebugName;
}
#endif
return newOne;
}
ParserBase operator[](ActionAndContexts aac)
{
assert(_pfnA == nullptr); // Ensure we're not overwriting any action.
ParserBase newOne(*this);
newOne._pfnA = aac.pfn;
newOne._pacc = aac.paccs;
#ifdef PARSE_DEBUG
if (aac.pszDebugName)
{
newOne.Name = aac.pszDebugName;
}
#endif
return newOne;
}
// This is for wrapping a parser in another, such as when we want its
// Match function to always match and act as a pre-action.
// e.g. syntaxnode_d[value[FinishValueA]]
ParserBase operator[](const ParserBase &parser)
{
// This should take a parser
assert(_pa.get() == nullptr); // Ensure we're not overwriting a parser.
ParserBase newOne(*this);
// We'll contain the provided parser in ourselves.
newOne._pa.reset(new ParserBase(parser));
return newOne;
}
// Returns a parser that is literal (doesn't skip whitespace prior to matching)
ParserBase operator+()
{
ParserBase newOne(*this);
newOne._fLiteral = true;
return newOne;
}
void SetDebug(DEBUGFUNCTION pfnDebug)
{
_pfnDebug = pfnDebug;
}
void AddParser(const ParserBase &add)
{
// This is for matching functions that need an array
// Be careful the matching function hasn't been replaced with a reference forwarder!
assert(_pfn != ReferenceForwarderP<_It>);
_parsers.push_back(std::move(std::make_unique<ParserBase>(add)));
}
template<typename _TContext, typename _It, char Q1, char Q2>
bool ReadStringStudio(_TContext *pContext, _It &stream, std::string &str) const
{
return _ReadStringStudio<_TContext, _CommentPolicy, _It, Q1, Q2>(pContext, stream, str);
}
std::unique_ptr<ParserBase> _pa;
std::vector<std::unique_ptr<ParserBase>> _parsers;
const char *_psz;
// PERF: perhaps we could optimize for some cases here, and not have a matching functino (e.g. char)
MATCHINGFUNCTION _pfn;
ACTION _pfnA;
ParseACChannels _pacc;
DEBUGFUNCTION _pfnDebug;
const ParserBase *_pRef;
bool _fLiteral; // Don't skip whitespace
bool _fOnlyRef; // Only references to this parser... it's lifetime is guaranteed.
};
extern const int AltKeys[26];
template<typename _It, typename _TContext>
bool IntegerExpandedPWorker(_TContext *pContext, _It &stream)
{
int i = 0;
bool fNeg = false;
bool fRet = false;
bool fHex = false;
if (*stream == '$')
{
fHex = true;
++stream;
while (isxdigit(*stream) && (i <= (std::numeric_limits<uint16_t>::max)()))
{
i *= 16;
i += charToI(*stream);
fRet = true;
++stream;
}
}
else if (*stream == '%')
{
// Binary
fHex = true; // Seems reasonable.
++stream;
auto value = *stream;
while ((value == '0' || value == '1') && (i <= (std::numeric_limits<uint16_t>::max)()))
{
i *= 2;
i += charToI(value);
fRet = true;
++stream;
value = *stream;
}
}
else if (*stream == '`')
{
// Character literal.
++stream;
auto value = *stream;
++stream;
switch (value)
{
case '@':
{
// This is an alt key
int index = toupper(*stream) - 'A';
++stream;
if ((index >= 0) && (index < ARRAYSIZE(AltKeys)))
{
i = AltKeys[index] << 8;
fRet = true;
}
break;
}
case '#':
{
// A function key
i = toupper(*stream);
++stream;
if (i == '0') // F10 appears to be `#0
{
i += 10;
}
i = (i - '1' + 0x3b) << 8;
fRet = true;
break;
}
case '^':
{
// A control key
i = toupper(*stream) - '@';
++stream;
fRet = true;
break;
}
default:
i = (char)value; //toupper(value);
fRet = true;
break;
}
}
else
{
if (*stream == '-')
{
fNeg = true;
++stream;
}
while (isdigit(*stream) && (i <= (std::numeric_limits<uint16_t>::max)()))
{
i *= 10;
i += charToI(*stream);
fRet = true;
++stream;
}
}
if (fRet)
{
// Make sure that the number isn't followed by an alphanumeric char
fRet = !isalnum(*stream);
}
if (fNeg)
{
i = -i;
}
if (fRet)
{
if (fRet)
{
fRet = (i <= (std::numeric_limits<uint16_t>::max)());
if (!fRet)
{
pContext->ReportError(errIntegerTooLarge, stream);
}
else
{
fRet = (i >= (std::numeric_limits<int16_t>::min)());
if (!fRet)
{
pContext->ReportError(errIntegerTooSmall, stream);
}
}
}
// Let the context know so people can use it.
pContext->SetInteger(i, fNeg, fHex, stream);
}
return fRet;
}
//
// Handles negation, hex, binary, character literals, etc...
//
template<typename _It, typename _TContext, typename _CommentPolicy>
bool IntegerExpandedP(const ParserBase<_TContext, _It, _CommentPolicy> *pParser, _TContext *pContext, _It &stream)
{
return IntegerExpandedPWorker(pContext, stream);
}
|
// This file has been generated by Py++.
#ifndef PropertyInitialiserMap_hpp__pyplusplus_wrapper
#define PropertyInitialiserMap_hpp__pyplusplus_wrapper
void register_PropertyInitialiserMap_class();
#endif//PropertyInitialiserMap_hpp__pyplusplus_wrapper
|
#ifndef MATHTOOLBOX_DATA_NORMALIZATION_HPP
#define MATHTOOLBOX_DATA_NORMALIZATION_HPP
#include <Eigen/Core>
namespace mathtoolbox
{
class DataNormalizer
{
public:
/// \param data_points An n-by-m matrix representing m data points lying in an n-dimensional space.
DataNormalizer(const Eigen::MatrixXd& data_points) : m_original_data_points(data_points)
{
const int num_dims = m_original_data_points.rows();
const int num_data_points = m_original_data_points.cols();
assert(num_dims > 0);
assert(num_data_points > 0);
m_mean = Eigen::VectorXd(num_dims);
m_stdev = Eigen::VectorXd(num_dims);
for (int dim = 0; dim < num_dims; ++dim)
{
const Eigen::VectorXd one_dim_data = m_original_data_points.row(dim);
m_mean(dim) = one_dim_data.mean();
m_stdev(dim) =
std::sqrt((one_dim_data - Eigen::VectorXd::Constant(num_data_points, m_mean(dim))).squaredNorm() /
static_cast<double>(num_data_points));
}
m_normalized_data_points = Normalize(m_original_data_points);
}
/// \brief Get the normalized data points.
const Eigen::MatrixXd& GetNormalizedDataPoints() const { return m_normalized_data_points; }
/// \brief Normalize a new set of data points by the same transformation as the originally provided data points.
Eigen::MatrixXd Normalize(const Eigen::MatrixXd& data_points) const
{
const int num_dims = data_points.rows();
const int num_data_points = data_points.cols();
Eigen::MatrixXd normalized_data_points(num_dims, num_data_points);
for (int dim = 0; dim < num_dims; ++dim)
{
constexpr double epsilon = 1e-32;
const double scale = 1.0 / std::max(m_stdev(dim), epsilon);
const auto offset = Eigen::VectorXd::Constant(num_data_points, m_mean(dim));
normalized_data_points.row(dim) = scale * (data_points.row(dim) - offset.transpose());
}
return normalized_data_points;
}
/// \brief Denormalize a new set of data points that is represented as the normalized form.
Eigen::MatrixXd Denormalize(const Eigen::MatrixXd& normalized_data_points) const
{
const int num_dims = normalized_data_points.rows();
const int num_data_points = normalized_data_points.cols();
Eigen::MatrixXd data_points(num_dims, num_data_points);
for (int dim = 0; dim < num_dims; ++dim)
{
constexpr double epsilon = 1e-32;
const double scale = std::max(m_stdev(dim), epsilon);
const auto offset = Eigen::VectorXd::Constant(num_data_points, m_mean(dim));
data_points.row(dim) = scale * normalized_data_points.row(dim) + offset.transpose();
}
return data_points;
}
/// \brief Get internal parameters about the means.
const Eigen::VectorXd& GetMean() const { return m_mean; }
/// \brief Get internal parameters about the standard deviations.
const Eigen::VectorXd& GetStdev() const { return m_stdev; }
private:
const Eigen::MatrixXd m_original_data_points;
Eigen::MatrixXd m_normalized_data_points;
Eigen::VectorXd m_mean;
Eigen::VectorXd m_stdev;
};
} // namespace mathtoolbox
#endif // MATHTOOLBOX_DATA_NORMALIZATION_HPP
|
/*
* Copyright (C) 2012-2016 Open Source Robotics Foundation
*
* 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 COLLISION_BENCHMARK_TEST_MULTIPLEWORLDSTESTFRAMEWORK_H
#define COLLISION_BENCHMARK_TEST_MULTIPLEWORLDSTESTFRAMEWORK_H
#include <collision_benchmark/GazeboMultipleWorlds.hh>
#include <collision_benchmark/GazeboWorldLoader.hh>
#include <collision_benchmark/GazeboHelpers.hh>
#include <test/TestUtils.hh>
#include <gtest/gtest.h>
#include <gazebo/gazebo.hh>
#include <gazebo/physics/physics.hh>
#include <string>
#include <vector>
using collision_benchmark::GazeboPhysicsWorldTypes;
class MultipleWorldsTestFramework : public ::testing::Test
{
public:
typedef collision_benchmark::MultipleWorldsServer<
GazeboPhysicsWorldTypes::WorldState,
GazeboPhysicsWorldTypes::ModelID,
GazeboPhysicsWorldTypes::ModelPartID,
GazeboPhysicsWorldTypes::Vector3,
GazeboPhysicsWorldTypes::Wrench>
GzMultipleWorldsServer;
typedef collision_benchmark::WorldManager<GazeboPhysicsWorldTypes::WorldState,
GazeboPhysicsWorldTypes::ModelID,
GazeboPhysicsWorldTypes::ModelPartID,
GazeboPhysicsWorldTypes::Vector3,
GazeboPhysicsWorldTypes::Wrench>
GzWorldManager;
GzMultipleWorldsServer::Ptr GetServer()
{
return server ? server->GetServer() : nullptr;
}
collision_benchmark::GazeboMultipleWorlds::Ptr GetMultipleWorlds()
{
return server;
}
collision_benchmark::GazeboMultipleWorlds::ConstPtr GetMultipleWorlds() const
{
return server;
}
protected:
MultipleWorldsTestFramework()
{
}
virtual ~MultipleWorldsTestFramework()
{
}
virtual void SetUp();
virtual void TearDown();
// Forces an update of the gazebo client which may be used to view the world
// during testing. This is to help alleviate the following issue:
// The poses of the models are not always updated in the client - some
// pose messages will be skipped for the GazeboPhysicsWorld worlds,
// because physics::World::posePub is throttled. Instead of allowing to
// remove the throttling rate altoegther (which would be useful, but the
// throttling rate has a purpose after all), this function can be used
// to make the Gazebo clients(s) completely refresh the scene, which causes
// them to re-request all information about all models.
// \param[in] timoutSecs maximum timeout wait in seconds to wait for a
// client connection. Use negative value to wait forever.
// \return false if there was an error preventing the refreshing.
bool RefreshClient(const double timeoutSecs=-1);
// \brief Initializes the framework and creates the world manager, but no
// worlds are added to it.
// Throws gtest assertions so needs to be called from top-level
// test function (nested function calls will not work correctly)
// \param[in] interactiveMode load up gzclient or not
// \param[in] additionalGuis additional GUI plugins to load with gzclient
void Init(const bool interactiveMode,
const std::vector<std::string> &additionalGuis = {});
// Called from Init(), to be used by subclasses.
virtual void InitSpecific() {}
// \brief Calls Init() and loads the empty world with all the given engines.
//
// Throws gtest assertions so needs to be called from top-level
// test function (nested function calls will not work correctly)
// \param[in] engines the physics engines to load
// \param[in] interactiveMode load up gzclient or not
// \param[in] additionalGuis additional GUI plugins to load with gzclient
void InitMultipleEngines(const std::vector<std::string>& engines,
const bool interactiveMode,
const std::vector<std::string> &additionalGuis = {});
// \brief Calls Init() and loads the empty world \e numWorld times
// with the given engine by calling LoadOneEngine().
// Each world can be accessed in the world
// manager given the index [0..numWorlds-1].
//
// Throws gtest assertions so needs to be called from top-level
// test function (nested function calls will not work correctly)
//
// \param[in] engine the physics engine to load
// \param[in] numWorlds number of empty worlds to load up with the engine
// \param[in] interactiveMode load up gzclient or not
// \param[in] additionalGuis additional GUI plugins to load with gzclient
void InitOneEngine(const std::string &engine,
const unsigned int numWorlds,
const bool interactiveMode,
const std::vector<std::string> &additionalGuis = {});
// \brief Loads the empty world \e numWorld times with the given engine.
// If the world manager previously had \e n engines, then it will then have
// \e n + \e numWorld empty worlds loaded after this call.
// Each world can be accessed in the world
// manager given the index ``[n-1..n+numWorlds-1]``.
//
// Throws gtest assertions so needs to be called from top-level
// test function (nested function calls will not work correctly)
//
// \param[in] engine the physics engine to load
// \param[in] numWorlds number of empty worlds to load up with the engine
void LoadOneEngine(const std::string &engine,
const unsigned int numWorlds);
// \brief Loads a shape into *all* worlds.
// You must call Init(), InitMultipleEngines() or InitOneEngine()
// before you can use this.
//
// Throws gtest assertions so needs to be called from top-level
// test function (nested function calls will not work correctly)
void LoadShape(const collision_benchmark::Shape::Ptr &shape,
const std::string &modelName);
// \brief Loads a shape into the worlds at the given index \e worldIdx.
// You must call Init(), InitMultipleEngines() or InitOneEngine()
// before you can use this.
//
// Throws gtest assertions so needs to be called from top-level
// test function (nested function calls will not work correctly)
void LoadShape(const collision_benchmark::Shape::Ptr &shape,
const std::string &modelName,
const unsigned int worldIdx);
// \brief Loads a model into *all* worlds.
// You must call Init(), InitMultipleEngines() or InitOneEngine()
// before you can use this.
//
// Throws gtest assertions so needs to be called from top-level
// test function (nested function calls will not work correctly)
void LoadModel(const std::string &modelFile,
const std::string &modelName);
// \brief Loads a model into the worlds at the given index \e worldIdx.
// You must call Init(), InitMultipleEngines() or InitOneEngine()
// before you can use this.
//
// Throws gtest assertions so needs to be called from top-level
// test function (nested function calls will not work correctly)
void LoadModel(const std::string &modelFile,
const std::string &modelName,
const unsigned int worldIdx);
// checks that AABB of model 1 and 2 are the same in all worlds and
// returns the two AABBs
// \param bbTol tolerance for comparison of bounding box sizes. The min/max
// coordinates (per x,y,z) are allowed to vary by this much in the worlds.
// \return true if worlds are consistent, falsle otherwise
bool GetAABBs(const std::string &modelName1,
const std::string &modelName2,
const double bbTol,
collision_benchmark::GzAABB &m1,
collision_benchmark::GzAABB &m2);
private:
// the multiple worlds server which can use a client in case of interactive
// testing with gzclient
collision_benchmark::GazeboMultipleWorlds::Ptr server;
// node needed in RefreshClient()
gazebo::transport::NodePtr node;
// publisher needed in RefreshClient()
gazebo::transport::PublisherPtr pub;
};
#endif // COLLISION_BENCHMARK_TEST_MULTIPLEWORLDSTESTFRAMEWORK_H
|
/*#include <iostream>
#include <iomanip>
#include <locale>
#include <TROOT.h>
#include <TChain.h>
#include <TFile.h>
#include <TKey.h>
#include <TCollection.h>
#include <TObject.h>
#include <TList.h>
#include <fstream>
#include "vector"
#include "vector"
using std::vector;
#include <TH2.h>
#include <TStyle.h>
#include <TCanvas.h>
*/
#include "paramSet.h"
// cuts
float DHTcut=800;
float Dpt1cut=300;
float Dpt2cut=100;
float Dpt3cut=100;
float Dpt4cut=50;
float Dalphacut=2;
float DmaxIPcut=0.03;
float Djetacut = 2.;
// dont forget there is a hidden cut nalmostemergin<4!!!!!!!!!!!!!!!!!
int Dnemcut=2;
int Dntrk1=1;
float Dmetcut=0.;
float Dmasscut=2000;
float Dtheta2dcut=0.;
int EMJ16003(bool otfile, bool hasPre, const char* inputfilename,const char* outputfilename);
/*int EMJselect(bool otfile, bool hasPre, const char* inputfilename,const char* outputfilename,
float HTcut, float pt1cut, float pt2cut,float pt3cut, float pt4cut, float jetacut,float alphaMaxcut, float maxIPcut, float NemfracCut,float CemfracCut,
int ntrk1cut, int NemergingCut, bool blind,
float Dmetcut, float Dmass, float Dmasscut, float Dtheta2dcut
);
*/
std::vector<std::string> ListTH(std::string outdir,std::string binname,int htype);
void HistNorm(std::string outdir, vector<double>& norm,int nbin,float* xsec, int* nfiles, std::string* binnames);
TH1F* HistMan(std::string outdir, float goalintlum,std::string thisHIST,vector<double>& histnorm, vector<double>& outnorm,int nbin,float* xsec, int* nfiles, std::string* binnames,bool donorm);
TH2F* HistMan2(std::string outdir, float goalintlum,std::string thisHIST,vector<double>& histnorm, vector<double>& outnorm,int nbin,float* xsec, int* nfiles, std::string* binnames,bool donorm);
/*void QCDhists(int imode, std::string outdir, int ibin, float goalintlum,
int nbin, float* xsec, int* nfiles, std::string* binnames,std::string* filesnames,
std::string sumhistname,
bool hasPre,bool donorm, bool blind, bool b16003,float themass) {
*/
void QCDhists(int imode, std::string outdir, int ibin, float goalintlum,
int nbin, float* xsec, int* nfiles, std::string* binnames,std::string* filesnames,
std::string sumhistname, bool hasPre,bool donorm, bool blind, const Parmset &ps) {
std::string inputfile;
std::string outputfile;
// first make histograms for each file in each bin for the qcd sample
if(imode==2) {
for (int i=0;i<nbin;i++) nfiles[i]=1;
sumhistname="Sum2"+sumhistname;
std::cout<<"MODE2"<<std::endl;
std::cout<<outdir<<std::endl;
outdir+="Sum";
std::cout<<outdir<<std::endl;
}
std::string bbname = outdir.c_str();
std::cout<<"entering QCDhists: MODE "<<imode<<std::endl;
std::cout<<"ibin "<<ibin<<" nbin "<<nbin<<" sumhistname "<<sumhistname<<std::endl;
if(imode==0) {
std::cout<<"making histograms for each file in each bin"<<std::endl;
int i=ibin;
std::ifstream inputconfig(filesnames[i]);
std::cout<<"input config file is: "<<filesnames[i]<<std::endl;
int linecounter = 0;
while(std::getline(inputconfig,inputfile) && nfiles[i]>linecounter) {
std::cout<<"input file is "<<inputfile<<std::endl;
outputfile=bbname+"histos"+binnames[i]+"_"+std::to_string(linecounter)+".root";
std::cout<<"output file is "<<outputfile<<std::endl;
bool isQCD = binnames[i].find("QCD")!=std::string::npos;
if (isQCD) std::cout<< "it is QCD"<<std::endl;
else std::cout<< "not QCD"<<std::endl;
int itmp = EMJselect(true,hasPre,inputfile.c_str(),outputfile.c_str(),ps,blind,isQCD);
linecounter +=1;
std::cout<<"passcounts: "<<itmp<<std::endl;
} // end of loop over files
} else { // other imodes
// get normalization
// double norm[nbin];
vector<double> norm(nbin);
if(donorm) {
HistNorm(bbname,norm,nbin,xsec,nfiles,binnames); // this gives the total number of events in each bin before all selections using the eventCountPreTrigger histogram
} else{
for(int i=0;i<nbin;i++) norm[i]=1.;
}
for(int i=0;i<nbin;i++) {
std::cout<<"total number events in bin "<<i<<" is "<<norm[i]<<std::endl;
}
TH1F* countclone = new TH1F("countclone","unnormalized count",20,0,20);
for(int i=0;i<nbin;i++){
countclone->AddBinContent(i+1,norm[i]);
}
TH1F* normhst = new TH1F("normhst","counts pretrigger by bin",nbin,0.,nbin);
for(int i=0;i<nbin;i++){
normhst->AddBinContent(i+1,norm[i]);
}
std::vector<std::string> histnames = ListTH(bbname,binnames[0],1);
std::vector<std::string> histnames2 = ListTH(bbname,binnames[0],2);
//std::vector<std::string> histnames = (std::vector<std::string>) histnamesall[0];
// std::vector<std::string> histnames2 = (std::vector<std::string>) histnamesall[1];
int nhist = histnames.size();
int nhist2 = histnames2.size();
std::cout<<"num of TH1:"<< nhist<<std::endl;
std::cout<<"num of TH2:"<< nhist2<<std::endl;
//make and output summed and renormalized histograms
std::cout<<"normalizing histograms"<<std::endl;
std::vector<TH1F*> vv(nhist);
vector<double> outnorm(nbin);
for(int i=0;i<nhist;i++) {
std::cout<<" enering Histman with i = "<<i<<": "<<histnames[i]<<std::endl;
vv[i]=HistMan(bbname,goalintlum,histnames[i],norm,outnorm,nbin,xsec,nfiles,binnames,donorm);
}
std::vector<TH2F*> vv2(nhist2);
vector<double> outnorm2(nbin);
for(int i=0;i<nhist2;i++) {
std::cout<<" enering Histman2 with i = "<<i<<": "<<histnames2[i]<<std::endl;
vv2[i]=HistMan2(bbname,goalintlum,histnames2[i],norm,outnorm2,nbin,xsec,nfiles,binnames,donorm);
}
// output total event count
std::cout<<" initial event count before and after norm is"<<std::endl;
double ttotal=0;
for(int i=0;i<nbin;i++) {
std::cout<<" bin "<<i<<" norm "<<norm[i]<<" times outnorm is "<<norm[i]*outnorm[i]<<std::endl;
ttotal = ttotal + norm[i]*outnorm[i];
}
std::cout<<"total is "<<ttotal<<std::endl;;
std::cout<<"outputting histograms"<<std::endl;
outputfile=bbname+sumhistname;
TFile out(outputfile.c_str(),"RECREATE");
std::cout<<"Openning & writing to File: "<<outputfile<<std::endl;
normhst->Write();
countclone->Write();
for(int i=0;i<nhist;i++) {
vv[i]->Write();
}
for(int i=0;i<nhist2;i++) {
vv2[i]->Write();
}
}
std::cout<<"job finished succcessfully"<<std::endl;
return;
}
std::vector<std::string> ListTH(std::string outdir,std::string binname,int htype) {
std::string inputfile=outdir+"histos"+binname+"_0.root";
std::vector<std::string> thlist={};
TFile* fin = new TFile(inputfile.c_str()) ;
TList* list = fin->GetListOfKeys() ;
if (!list) { std::cout<<"<E> No keys found in file"<<std::endl; exit(1) ; }
TIter next(list) ; TKey* key ; TObject* obj ;
while (( key = (TKey*)next() )) {
obj = key->ReadObj() ;
if ( (strcmp(obj->IsA()->GetName(),"TProfile")!=0)
&& (!obj->InheritsFrom("TH2"))
&& (!obj->InheritsFrom("TH1"))
) {
std::cout<<"<W> Object "<<obj->GetName()<<" is not 1D or 2D histogram: will not be converted\n" ;
}
if (obj->InheritsFrom("TH2")){
if (htype==2){
std::cout<<"TH2 Histo name: "<<obj->GetName()<<" title: "<< obj->GetTitle()<<std::endl;
thlist.push_back(std::string(obj->GetName()));
}
} else if (obj->InheritsFrom("TH1") && htype==1){
std::cout<<"TH1 Histo name: "<<obj->GetName()<<" title: "<< obj->GetTitle()<<std::endl;
thlist.push_back(std::string(obj->GetName()));
}
}
return thlist;
}
TH1F* HistMan(std::string outdir, float goalintlum,std::string thisHIST,vector<double>& norm,vector<double>& outnorm,int nbin,float* xsec, int* nfiles, std::string* binnames,bool donorm) {
std::string inputfile;
// now add up all the files for one bin
vector<TH1F> sum(nbin);
for(int i=0;i<nbin;i++) { // for each bin
for(int j=0;j<nfiles[i];j++) { //for each file for that bin
inputfile=outdir+"histos"+binnames[i]+"_"+std::to_string(j)+".root";
TFile* in = new TFile(inputfile.c_str());
std::cout<<"Openning File: "<<inputfile<<std::endl;
if (!in->GetListOfKeys()->Contains(thisHIST.c_str())) return (new TH1F(thisHIST.c_str(),"dummy empty hist",10,0.,10.));
if(j==0) {
std::cout<<" adding up histos within a bin"<<std::endl;
sum[i] = *(static_cast<TH1F*>(in->Get(thisHIST.c_str())->Clone()));
} else {
TH1F* tmp = static_cast<TH1F*>(in->Get(thisHIST.c_str())->Clone());
sum[i].Add(tmp);
}
in->Close();
}
}
if(donorm) {
// reweight to int lum
std::cout<<" reweighting to inst lum of "<<goalintlum<<" for each bin"<<std::endl;
for(int i=0;i<nbin;i++) {
// get total number of events before filter
float ntotal = norm[i];
std::cout<<" for bin "<<i<<" number of pretrigger events is "<<ntotal<<std::endl;
float fileLum= ntotal/xsec[i];
std::cout<<" equ lum for bin is "<<fileLum<<" fb-1"<<std::endl;
outnorm[i] = goalintlum/fileLum;
std::cout<<" scaling by a factor of "<<outnorm[i]<<std::endl;
sum[i].Scale(outnorm[i]);
}
}
//add the bins
std::cout<<" adding bins"<<std::endl;
TH1F* SUM=static_cast<TH1F*>((sum[0]).Clone());
for(int i=1;i<nbin;i++) {
SUM->Add(&sum[i]);
}
return SUM;
}
TH2F* HistMan2(std::string outdir, float goalintlum,std::string thisHIST,vector<double>& norm,vector<double>& outnorm,int nbin,float* xsec, int* nfiles, std::string* binnames,bool donorm) {
std::string inputfile;
// now add up all the files for one bin
std::cout<<" adding up histos within a bin"<<std::endl;
vector<TH2F> sum(nbin);
for(int i=0;i<nbin;i++) { // for each bin
for(int j=0;j<nfiles[i];j++) { //for each file for that bin
inputfile=outdir+"histos"+binnames[i]+"_"+std::to_string(j)+".root";
TFile* in = new TFile(inputfile.c_str());
std::cout<<"Openning File: "<<inputfile<<std::endl;
if(j==0) {
sum[i] = *(static_cast<TH2F*>(in->Get(thisHIST.c_str())->Clone()));
} else {
TH2F* tmp = static_cast<TH2F*>(in->Get(thisHIST.c_str())->Clone());
sum[i].Add(tmp);
}
in->Close();
}
}
if(donorm) {
// reweight to int lum
std::cout<<" reweighting to inst lum of "<<goalintlum<<" for each bin"<<std::endl;
for(int i=0;i<nbin;i++) {
// get total number of events before filter
float ntotal = norm[i];
std::cout<<" for bin "<<i<<" number of pretrigger events is "<<ntotal<<std::endl;
float fileLum= ntotal/xsec[i];
std::cout<<" equ lum for bin is "<<fileLum<<" fb-1"<<std::endl;
outnorm[i] = goalintlum/fileLum;
std::cout<<" scaling by a factor of "<<outnorm[i]<<std::endl;
sum[i].Scale(outnorm[i]);
}
}
//add the bins
std::cout<<" adding bins"<<std::endl;
TH2F* SUM=static_cast<TH2F*>((sum[0]).Clone());
for(int i=1;i<nbin;i++) {
SUM->Add(&sum[i]);
}
return SUM;
}
void HistNorm(std::string outdir, vector<double>& norm,int nbin,float* xsec, int* nfiles, std::string* binnames) {
std::cout<<"entering HistNorm with nfiles "<<nfiles[0]<<std::endl;
std::string inputfile;
TFile * in;
// now add up all the files for one bin
vector<TH1F> sum(nbin);
for(int i=0;i<nbin;i++) { // for each bin
for(int j=0;j<nfiles[i];j++) { //for each file for that bin
inputfile=outdir+"histos"+binnames[i]+"_"+std::to_string(j)+".root";
std::cout<<i<<" "<<j<<" "<<inputfile<<std::endl;
in = new TFile(inputfile.c_str());
if(j==0) {
sum[i] = *(static_cast<TH1F*>(in->Get("eventCountPreTrigger")->Clone()));
} else {
TH1F* tmp = static_cast<TH1F*>(in->Get("eventCountPreTrigger")->Clone());
sum[i].Add(tmp);
}
in->Close();
}
}
// reweight to int lum
for(int i=0;i<nbin;i++) {
// get total number of events before filter
norm[i] = sum[i].GetBinContent(2);
std::cout<<"norm "<<i<<" "<<norm[i]<<std::endl;
}
return;
}
|
#ifndef COMMANDSPROCESSOR_H
#define COMMANDSPROCESSOR_H
#include <QSharedPointer>
#include "Commands/CommandDescriptor.h"
class CommandsProcessor : public QObject
{
Q_OBJECT
public:
CommandsProcessor();
public slots:
void processHttpReply(class QNetworkReply *reply);
// Separated mainly for testing purposes
void processCommandsList(class CommandsList *commandsList);
signals:
void commandReceived(CommandDescriptor descriptor);
};
#endif // COMMANDSLIST_H
|
/*
* TCPSession.cpp
*
* Created on: 25 Sep 2018
* Author: Thomas Maters
* Email : thomasmaters@hotmail.com (TG.Maters@student.han.nl)
*/
#include "TCPSession.hpp"
namespace Communication::TCP
{
TCPSession::TCPSession(boost::asio::io_service& io_service,
std::shared_ptr<RequestHandler>& a,
std::shared_ptr<ResponseHandler>& b,
bool keep_alive)
: socket_(io_service), keep_alive_(keep_alive), request_handler(a), response_handler(b)
{
#ifdef ENABLE_IO_DEBUG
std::cout << "TCPSession -> Constructor" << std::endl;
#endif
}
TCPSession::~TCPSession()
{
#ifdef ENABLE_IO_DEBUG
std::cout << "TCPSession -> Destructor" << std::endl;
#endif
}
void TCPSession::handleIncommingConnection()
{
boost::asio::async_read(getSocket(),
boost::asio::buffer(data_, TCP_BUFFER_SIZE),
boost::bind(&TCPSession::handleRequest,
shared_from_this(),
boost::asio::placeholders::error,
boost::asio::placeholders::bytes_transferred));
}
void TCPSession::handleReceivedResponse(bool has_response_head_and_body,
[[maybe_unused]] const boost::system::error_code& error,
std::size_t bytes_transferd)
{
#ifdef ENABLE_IO_DEBUG
std::cout << "TCPSession -> GOT RESPONSE( " << bytes_transferd << ")" << std::endl;
#endif
if (response_handler.get() != nullptr)
{
if (has_response_head_and_body)
{
std::size_t bodySize = response_handler->handleResponseHead(data_.data(), bytes_transferd);
handleResponse(bodySize, false, boost::system::error_code(), 0);
}
else
{
response_handler->handleResponse(data_.data(), bytes_transferd, ConnectionInterface::getCurrentTime());
}
}
}
void TCPSession::handleRequest(const boost::system::error_code& error, std::size_t bytes_transferd)
{
#ifdef ENABLE_IO_DEBUG
std::cout << "TCPSession -> GOT REQUEST( " << bytes_transferd << ")" << std::endl;
#endif
if (!error || error == boost::asio::error::eof)
{
if (request_handler.get() != nullptr)
{
SensorMessage response =
request_handler->handleRequest(data_.data(), bytes_transferd, ConnectionInterface::getCurrentTime());
if (response.getDataLength() > 0)
{
boost::asio::async_write(getSocket(),
boost::asio::buffer(response.getData(), response.getDataLength()),
[&]([[maybe_unused]] const boost::system::error_code& error,
[[maybe_unused]] std::size_t bytes_written) {
#ifdef ENABLE_IO_DEBUG
std::cout << "TCPSession -> WRITTEN RESPONSE( " << bytes_written << ")"
<< std::endl;
#endif
});
}
else
{
#ifdef ENABLE_IO_DEBUG
std::cout << "TCPSession -> Response to request is empty, closing connection" << std::endl;
#endif
}
}
}
else
{
#ifdef ENABLE_IO_DEBUG
std::cout << "TCPSession -> Invalid request received " << error.message() << std::endl;
#endif
}
}
}
|
#ifndef IMGUIVIEWER_CAMERA_HEADER
#define IMGUIVIEWER_CAMERA_HEADER
#include <limits>
#include "Source/Math/Math.h"
#include "Source/Units/Unit.h"
namespace solar
{
namespace openGL
{
class Shader;
}
//Abstract interface for a camera that consists of view and projection matrices stored in UBO and can follow simulated objects around.
class Camera
{
public:
static constexpr size_t noTarget = std::numeric_limits<size_t>::max();
Camera();
//Copying disabled for now
// - Policy on copying of UBO?
Camera(const Camera&) = delete;
Camera& operator=(const Camera&) = delete;
Camera(Camera&&) = default;
Camera& operator=(Camera&&) = default;
virtual ~Camera();
//Sets camera's view matrix in such way that camera is located at given positon and looks at desired target location.
virtual void LookAt(const Vec3d& newCamPos, const Vec3d& newTargetPos, const Vec3d& newUpDir = Vec3d(0.0, 1.0, 0.0));
//Updates camera if its targeted at some object.
//Calls UpdateCamera() internally
//FUTURE In future it might be used to animate its movement
void Update(const SimData& data);
//Binds this camera for next drawing.( Updates its UBO with new matrices and binds UBO to binding point associated with all shaders)
//Should be used before drawing if there are more than one camera object.
//IMPROVE: UBOs can be indexed by uniqued index based on refCount and bound to multiple binding points.
// That would allow multiple bound cameras at same time. Minimum binding points is 24 which is more than enough for all camera which will probably be the only use for UBOs anyway.
// Might get messy. With OpenGLSM and with shader remembering its UBO it can bind correct camera with its own Bind() which is already called before draw calls.
// - too many hidden dependecies
void Bind();
void UnBind();
//If shader wants to draw from a camera's point of view, then it must contain following interface block:
/* std140 uniform **blockName**
{
mat4 projection;
mat4 view;
mat4 projView;
mat4 invProj;
mat4 invView;
mat4 invProjView;
} **instanceName**;*/
void Subscribe(const openGL::Shader& shader, const std::string& blockName = "CameraMatrices") const;
//Set camera's target as object in simData[index]. Use Camera::noTarget to stop following
//To update matrices Update(simData) method must be called frequently.
void FollowObject(const size_t index) { targetObjectIndex = index; }
size_t GetFollowedObjectIndex()const { return targetObjectIndex; }
bool IsFollowing()const { return targetObjectIndex != noTarget; }
const Mat4f& ProjMatrix() const { return proj; }
const Mat4f& ViewMatrix() const { return view; }
Mat4f ProjViewMatrix() const { return proj*view; }
const Vec3d& CamPos() const { return camPos; }
const Vec3d& TargetPos() const { return targetPos; }
const Vec3d& UpDir() const { return upDir; }
const Vec3d& RightDir() const { return rightDir; }
double DistToTarget() const { return (TargetPos() - CamPos()).Length(); }
protected:
//Optional behaviour injected into Update()
virtual void UpdateCamera() {}
Mat4f proj, view;
Vec3d camPos, targetPos, upDir,rightDir;
private:
void SubmitMatrices();
uint32_t UBO;
//Index in simData array of the camera's target, 'noTarget' for none
size_t targetObjectIndex;
};
class PerspectiveCamera : public Camera
{
public:
PerspectiveCamera(float FOV, float AR, float near, float far);
};
class OrthographicCamera : public Camera
{
public:
OrthographicCamera(float width, float height, float near, float far);
};
class ScaledOrthoCamera : public Camera
{
public:
//Sets ortho projection for camera one unit from its target
ScaledOrthoCamera(float width, float height, float near, float far);
//Calls Camera::LookAt and multiplies the width and height of projection matrix with distance to target
virtual void LookAt(const Vec3d& newCamPos, const Vec3d& newTargetPos, const Vec3d& newUpDir = Vec3d(0.0, 1.0, 0.0)) override final;
private:
const Mat4f projOriginal;
};
}
#endif
|
#include <iostream>
using namespace std;
int sum[2] = {0,};
void Fibonacci(int num1, int num2, int N){
if(N <= 1){
if(N == 0){
sum[0] = 1;
sum[1] = 0;
}
else{
sum[0] = num1;
sum[1] = num2;
}
return;
}
return Fibonacci(num2, num1 + num2, N - 1);
}
int main(){
int N =0;
int T = 0;
cin >> T;
for(int i = 0; i < T ; ++i){
cin >> N;
Fibonacci(0,1, N);
printf("%d %d\n",sum[0], sum[1]);
}
}
|
#include <stdio.h>
int main(){
int N, K;
scanf("%d %d", &N, &K);
//PERSEGI 1
//baris
for(int i = 0; i < N; i++){
//kolom
for(int j = 0; j < N; j++){
printf("#");
}
printf("\n");
}
printf("\n");
//PERSEGI 2
//baris
for(int i = 1; i < N; i++){
if(i % K == 0){
//kolom
for(int j = 0; j < N; j++){
printf("#");
}
}
else {
for(int j = 0; j < N; j++){
printf(".");
}
}
printf("\n");
}
printf("\n");
for(int i = 0; i < N; i++){
//kolom
for(int j = 1; j < N; j++){
if(j % K == 0){
printf("#");
}
else{
printf(".");
}
}
printf("\n");
}
return 0;
}
|
#include <Arduino.h>
#include <ArduinoJson.h>
#include <AsyncTCP.h>
#include <ESPAsyncWebServer.h>
#include "AsyncJson.h"
#include "file_utils.hpp"
#include "networking.hpp"
#include "html_pages.hpp"
#include <driver/adc.h>
#include "time.h"
#include <ESP32Time.h>
#include <functional>
#include <esp_wifi.h>
#include <esp_bt.h>
#define JSON_STRING_BUFFER_LENGTH 1024
#define MAX_WIFI_NETWORKS 10
#define PORT 80
const int capacity = JSON_ARRAY_SIZE(3) + MAX_WIFI_NETWORKS*JSON_OBJECT_SIZE(2) + JSON_OBJECT_SIZE(2);
void startServer(ESP32Time* _rtc);
void notFound(AsyncWebServerRequest *request);
String templateProcessor(const String& var);
void getAllWifiNetworks(AsyncWebServerRequest *request);
void addNewWifiNetwork(AsyncWebServerRequest *request, JsonVariant &jsonVar);
void deleteWifiNetwork(AsyncWebServerRequest *request);
void submitEspCode(AsyncWebServerRequest *request);
bool createStravaWalkActivity(int walkDuration);
long getCurrentTimestamp();
long getCurrentEpoch();
void goToDeepSleep(long timerWakeupDelay);
struct Retryer{
std::function<bool()> retryFun;
unsigned long prevRetryMillis;
unsigned long retryInterval;
int maxRetryCount;
int currRetryCount;
};
|
#pragma once
#include "Task.h"
#include "Camera.h"
#include "../CWE/CWELib.h"
// Task of the loading scene.
class LoadingExec : public TaskBase
{
private:
CWE::Polygon mLoadingImage;
Camera mCamera;
CWE::Timer mTime;
public:
LoadingExec(int priority);
~LoadingExec();
void Update(TaskExec::List& taskList) override;
void Draw() override;
void End() override;
};
|
#include "../../include/online/tcp_server.h"
namespace keyword_suggestion {
TcpServer::TcpServer(int port, const std::string &ip)
: acceptor_(port, ip), event_loop_(acceptor_) {}
void TcpServer::Start() {
acceptor_.Init();
event_loop_.Loop();
}
void TcpServer::Stop() { event_loop_.Unloop(); }
void TcpServer::SetConnectedCallback(const TcpCallback &&callback) {
event_loop_.SetConnectedCallback(std::move(callback));
}
void TcpServer::SetReceivedCallback(const TcpCallback &&callback) {
event_loop_.SetReceivedCallback(std::move(callback));
}
void TcpServer::SetClosedCallback(const TcpCallback &&callback) {
event_loop_.SetClosedCallback(std::move(callback));
}
} // namespace keyword_suggestion
|
#include<bits/stdc++.h>
using namespace std;
struct Student{
string name="",number="";
int score;
Student(int s=0):score(s){}
};
int main(){
int N;
scanf("%d",&N);
Student Max(-1),Min(101),temp;
for(int i=0;i<N;++i){
cin>>temp.name>>temp.number>>temp.score;
if(Max.score<temp.score)
Max=temp;
if(Min.score>temp.score)
Min=temp;
}
printf("%s %s\n%s %s",Max.name.c_str(),Max.number.c_str(),Min.name.c_str(),Min.number.c_str());
return 0;
}
|
#ifndef TerraNova_UserEvent_h
#define TerraNova_UserEvent_h
namespace terranova {
struct UserEvent {
uint32_t type;
uint32_t timestamp;
void* data;
};
}
#endif
|
#include <iostream>
#include <list>
#include <algorithm>
using namespace std;
void print(list<int><)
{
list<int>::iterator it;
for(it=lt.begin();it!=lt.end();it++)
cout<<*it<<" ";
cout<<endl;
}
class sequence
{
int value;
public:
sequence(int iv):value(iv){}
int operator()()
{
return value++;
}
};
int main()
{
list<int> lt;
generate_n(back_inserter(lt),4,sequence(1)); // 函数对象值传递
print(lt);
sequence seq(11);
generate_n(back_inserter(lt),5,seq); // 函数对象引用传递
print(lt);
cin.get();
return 0;
}
/*
1 2 3 4
1 2 3 4 11 12 13 14 15
*/
|
#include <iostream>
using namespace std;
int main()
{
double a;
int b;
cout<<"boyinggizni kiriting(cm): ";
cin>>a;
cout<<"vazningizni kiriting(kg): ";
cin>>b;
a = a/100;
cout<<" sizning vazn va boyingiz balansi: "<<b/(a*a);
return 0;
}
|
#include "opencv.hpp"
using namespace cv;
using namespace std;
int main()
{
Mat srcImage = imread("alphabet.bmp", IMREAD_GRAYSCALE);
if (srcImage.empty())
return -1;
Mat tImage1 = imread("A.bmp", IMREAD_GRAYSCALE);
Mat tImage2 = imread("S.bmp", IMREAD_GRAYSCALE);
Mat tImage3 = imread("b.bmp", IMREAD_GRAYSCALE);
Mat tImage4 = imread("m.bmp", IMREAD_GRAYSCALE);
if (tImage1.empty() || tImage2.empty() ||
tImage2.empty() || tImage4.empty())
return -1;
Mat dstImage;
cvtColor(srcImage, dstImage, COLOR_GRAY2BGR);
double minVal, maxVal;
Point minLoc, maxLoc;
Mat result;
// TM_SQDIFF
matchTemplate(srcImage, tImage1, result, TM_SQDIFF);
minMaxLoc(result, &minVal, NULL, &minLoc, NULL);
rectangle(dstImage, minLoc,
Point(minLoc.x + tImage1.cols, minLoc.y + tImage1.rows), Scalar(255, 0, 0), 2);
// TM_SQDIFF_NORMED
matchTemplate(srcImage, tImage2, result, TM_SQDIFF_NORMED);
minMaxLoc(result, &minVal, NULL, &minLoc, NULL);
rectangle(dstImage, minLoc,
Point(minLoc.x + tImage2.cols, minLoc.y + tImage2.rows), Scalar(0, 255, 0), 2);
// TM_CCORR_NORMED
matchTemplate(srcImage, tImage3, result, TM_CCORR_NORMED);
minMaxLoc(result, NULL, &maxVal, NULL, &maxLoc);
rectangle(dstImage, maxLoc,
Point(maxLoc.x + tImage3.cols, maxLoc.y + tImage3.rows), Scalar(0, 0, 255), 2);
// TM_CCOEFF_NORMED
matchTemplate(srcImage, tImage4, result, TM_CCOEFF_NORMED);
minMaxLoc(result, NULL, &maxVal, NULL, &maxLoc);
rectangle(dstImage, maxLoc,
Point(maxLoc.x + tImage4.cols, maxLoc.y + tImage4.rows), Scalar(255, 0, 255), 2);
imshow("dstImage", dstImage);
waitKey();
return 0;
}
|
class Letter
{
public:
enum
{
LETTER_W = 16,
LETTER_H = LETTER_W,
LETTER_X = 10,
LETTER_Y = LETTER_X,
};
static flt LETTER_SCALE = 1.0f;
~Letter();
Letter(ImagePtr img = NULL, int width = LETTER_W, int height = LETTER_H, flt scale = LETTER_SCALE, int xcount = LETTER_X, int ycount = LETTER_Y)
{
this.image = img;
this.scale = scale;
if( img != NULL)
{
setSize(width, height, img);
}
this.xsize = xcount;
this.ysize = ycount;
}
void set(ImagePtr img = NULL, int width = LETTER_W, int height = LETTER_H)
{
this.image = img;
if( img != NULL)
{
setSize(width, height, img);
}
}
void draw(VecI2 pos, int code)
{
flt chr_u = flt(code % xsize);
flt chr_v = flt(code / xsize);
image->drawPart(
Rect(this.screenBase.x + ((pos.x ) * this.displaySize.x * this.scale), this.screenBase.y - ((pos.y + 1.0f ) * this.displaySize.y * this.scale),
this.screenBase.x + ((pos.x + 1.0f * 1) * this.displaySize.x * this.scale), this.screenBase.y - ((pos.y ) * this.displaySize.y * this.scale)),
Rect(chr_u * this.u * this.scale, chr_v * this.v * this.scale, (chr_u + 1.0f) * this.u * this.scale, (chr_v + 1.0f) * v * this.scale)
);
#if 0
flt xx = flt(pos.x);
flt yy = flt(pos.y);
D.text(0, -0.1, TextInt(pos.x) + "/"+TextInt(pos.y));
D.text(0, -0.2, TextFlt(this.screenBase.x + xx * this.u * this.scale)+", "+ TextFlt(this.screenBase.y - yy * this.v * this.scale));
D.text(0, -0.4, TextFlt(chr_u * this.u * this.scale)+", "+TextFlt(chr_v * this.v * this.scale));
D.text(0, -0.3, TextFlt(this.screenBase.x + (xx + 1.0f) * this.u * this.scale) + ", " + TextFlt(this.screenBase.y - (yy + 1.0f) * v * this.scale));
D.text(0, -0.5, TextFlt((chr_u + 1.0f) * this.u * this.scale) + ", " + TextFlt((chr_v + 1.0f) * v * this.scale));
VecI2 sc = D.screenToPixel(this.displaySize);
D.text(0, -0.6, TextInt(sc.x) + "/" + TextInt(sc.y));
#endif
}
Vec2 getDisplaySize()
{
return this.displaySize;
}
private:
ImagePtr image;
flt scale; // display size
flt u; // size of 1 letter
flt v;
Vec2 screenBase; // screenSize
Vec2 displaySize;
VecI2 letterSize;
int xsize;
int ysize;
void setSize( int width, int height, ImagePtr img )
{
this.u = flt(width) / img->w();
this.v = flt(height) / img->h();
this.letterSize = VecI2(width, height);
this.screenBase = D.pixelToScreen(VecI2(0, 0));
this.displaySize = D.pixelToScreenSize(VecI2(width, height));
}
}
|
#include<iostream>
#include<cstring>
using namespace std;
int _sum[100][100];
int dp[100][100];
int dat[100];
int n;
int ans=-1;
const int _INT_MAX=10000000;
int sum(int i,int j,int k)
{
return dat[i]*dat[(j+1)%n]*dat[(k+1)%n];
}
int main()
{
cin >>n;
for(int i=0;i<100;i++)
{
for(int j=0;j<100;j++)
{
dp[i][j]=0;
}
}
for(int i=0;i<n;i++)
{
cin >>dat[i];
dp[i][i]=0;
}
for(int p=0;p<n;p++)
{
for(int i=n-1+p;i>=p;i--)
{
for(int j=i;j<n+p;j++)
{
for(int k=i;k<j;k++)
{
int _i=i%n;
int _j=j%n;
int _k=j%n;
dp[_i][_j]=max(dp[_i][_j],dp[_i][_k]+dp[(_k+1)%n][_j]+sum(i,k,j));
}
}
}
}
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
cout <<dp[i][j]<<" ";
}
cout <<endl;
}
int ans=0;
for(int p=0;p<n;p++)
{
ans=max(ans,dp[p][(p+n-1)%n]);
}
cout <<ans<<endl;
return 0;
}
|
/*************************************************************
* > File Name : P3372.cpp
* > Author : Tony
* > Created Time : 2019年02月21日 星期四 12时31分17秒
**************************************************************/
#include <bits/stdc++.h>
#define LL long long
#define ls rt<<1
#define rs rt<<1|1
using namespace std;
const int maxn = 100010;
LL sum[maxn << 2], add[maxn << 2];
int n, q, opt, t1, t2, t3;
void pushup(int rt)
{
sum[rt] = sum[ls] + sum[rs];
}
void pushdown(int rt, int k)
{
if (!add[rt]) return;
add[ls] += add[rt];
add[rs] += add[rt];
sum[ls] += add[rt] * (k - (k >> 1));
sum[rs] += add[rt] * (k >> 1);
add[rt] = 0;
}
void update(int rt, int l, int r, int ql, int qr, int k)
{
if (ql <= l && qr >= r)
{
add[rt] += k;
sum[rt] += 1LL * k * (r - l + 1);
return;
}
pushdown(rt, r - l + 1);
int mid = (l + r) >> 1;
if (ql <= mid)
{
update(ls, l, mid, ql, qr, k);
}
if (qr > mid)
{
update(rs, mid + 1, r, ql, qr, k);
}
pushup(rt);
}
void build(int rt, int l, int r)
{
add[rt] = 0;
if (l == r)
{
scanf("%lld", &sum[rt]);
return;
}
int mid = (l + r) >> 1;
build(ls, l, mid);
build(rs, mid + 1, r);
pushup(rt);
}
LL query(int rt, int l, int r, int ql, int qr)
{
if (ql <= l && qr >= r) return sum[rt];
pushdown(rt, r - l + 1);
int mid = (l + r) >> 1;
LL ans = 0;
if (ql <= mid)
{
ans += query(ls, l, mid, ql, qr);
}
if (qr > mid)
{
ans += query(rs, mid + 1, r, ql, qr);
}
return ans;
}
int main()
{
scanf("%d %d", &n, &q);
build(1, 1, n);
while (q--)
{
scanf("%d", &opt);
if (opt == 1)
{
scanf("%d %d %d", &t1, &t2, &t3);
update(1, 1, n, t1, t2, t3);
}
if (opt == 2)
{
scanf("%d %d", &t1, &t2);
printf("%lld\n", query(1, 1, n, t1, t2));
}
}
return 0;
}
|
#include "netlist.h"
using namespace std;
int main (int argc, char * const argv[])
{
//Make sure there is at least a document present
if (argc < 2 )
{
cerr << "Error! You must enter a filename as an argument." << endl;
return -1;
}
evl_wires wires;
evl_components comps;
if (!parse_evl_file(argv[1], wires, comps))
{
return -1;
}
netlist nl;
if (!nl.create(wires, comps))
{
return -1;
}
string nl_file = string(argv[1])+".netlist";
nl.save(nl_file);
//nl.simulate(1000);
return 0;
}
|
// C++ for the Windows Runtime vv1.0.170303.6
// Copyright (c) 2017 Microsoft Corporation. All rights reserved.
#pragma once
#include "base.h"
WINRT_WARNING_PUSH
#include "internal/Windows.Storage.Streams.3.h"
#include "internal/Windows.Foundation.3.h"
#include "internal/Windows.Security.Authentication.Identity.Provider.3.h"
#include "Windows.Security.Authentication.Identity.h"
WINRT_EXPORT namespace winrt {
namespace impl {
template <typename D>
struct produce<D, Windows::Security::Authentication::Identity::Provider::ISecondaryAuthenticationFactorAuthentication> : produce_base<D, Windows::Security::Authentication::Identity::Provider::ISecondaryAuthenticationFactorAuthentication>
{
HRESULT __stdcall get_ServiceAuthenticationHmac(impl::abi_arg_out<Windows::Storage::Streams::IBuffer> value) noexcept override
{
try
{
typename D::abi_guard guard(this->shim());
*value = detach_abi(this->shim().ServiceAuthenticationHmac());
return S_OK;
}
catch (...)
{
*value = nullptr;
return impl::to_hresult();
}
}
HRESULT __stdcall get_SessionNonce(impl::abi_arg_out<Windows::Storage::Streams::IBuffer> value) noexcept override
{
try
{
typename D::abi_guard guard(this->shim());
*value = detach_abi(this->shim().SessionNonce());
return S_OK;
}
catch (...)
{
*value = nullptr;
return impl::to_hresult();
}
}
HRESULT __stdcall get_DeviceNonce(impl::abi_arg_out<Windows::Storage::Streams::IBuffer> value) noexcept override
{
try
{
typename D::abi_guard guard(this->shim());
*value = detach_abi(this->shim().DeviceNonce());
return S_OK;
}
catch (...)
{
*value = nullptr;
return impl::to_hresult();
}
}
HRESULT __stdcall get_DeviceConfigurationData(impl::abi_arg_out<Windows::Storage::Streams::IBuffer> value) noexcept override
{
try
{
typename D::abi_guard guard(this->shim());
*value = detach_abi(this->shim().DeviceConfigurationData());
return S_OK;
}
catch (...)
{
*value = nullptr;
return impl::to_hresult();
}
}
HRESULT __stdcall abi_FinishAuthenticationAsync(impl::abi_arg_in<Windows::Storage::Streams::IBuffer> deviceHmac, impl::abi_arg_in<Windows::Storage::Streams::IBuffer> sessionHmac, impl::abi_arg_out<Windows::Foundation::IAsyncOperation<winrt::Windows::Security::Authentication::Identity::Provider::SecondaryAuthenticationFactorFinishAuthenticationStatus>> result) noexcept override
{
try
{
typename D::abi_guard guard(this->shim());
*result = detach_abi(this->shim().FinishAuthenticationAsync(*reinterpret_cast<const Windows::Storage::Streams::IBuffer *>(&deviceHmac), *reinterpret_cast<const Windows::Storage::Streams::IBuffer *>(&sessionHmac)));
return S_OK;
}
catch (...)
{
*result = nullptr;
return impl::to_hresult();
}
}
HRESULT __stdcall abi_AbortAuthenticationAsync(impl::abi_arg_in<hstring> errorLogMessage, impl::abi_arg_out<Windows::Foundation::IAsyncAction> result) noexcept override
{
try
{
typename D::abi_guard guard(this->shim());
*result = detach_abi(this->shim().AbortAuthenticationAsync(*reinterpret_cast<const hstring *>(&errorLogMessage)));
return S_OK;
}
catch (...)
{
*result = nullptr;
return impl::to_hresult();
}
}
};
template <typename D>
struct produce<D, Windows::Security::Authentication::Identity::Provider::ISecondaryAuthenticationFactorAuthenticationResult> : produce_base<D, Windows::Security::Authentication::Identity::Provider::ISecondaryAuthenticationFactorAuthenticationResult>
{
HRESULT __stdcall get_Status(Windows::Security::Authentication::Identity::Provider::SecondaryAuthenticationFactorAuthenticationStatus * value) noexcept override
{
try
{
typename D::abi_guard guard(this->shim());
*value = detach_abi(this->shim().Status());
return S_OK;
}
catch (...)
{
return impl::to_hresult();
}
}
HRESULT __stdcall get_Authentication(impl::abi_arg_out<Windows::Security::Authentication::Identity::Provider::ISecondaryAuthenticationFactorAuthentication> value) noexcept override
{
try
{
typename D::abi_guard guard(this->shim());
*value = detach_abi(this->shim().Authentication());
return S_OK;
}
catch (...)
{
*value = nullptr;
return impl::to_hresult();
}
}
};
template <typename D>
struct produce<D, Windows::Security::Authentication::Identity::Provider::ISecondaryAuthenticationFactorAuthenticationStageChangedEventArgs> : produce_base<D, Windows::Security::Authentication::Identity::Provider::ISecondaryAuthenticationFactorAuthenticationStageChangedEventArgs>
{
HRESULT __stdcall get_StageInfo(impl::abi_arg_out<Windows::Security::Authentication::Identity::Provider::ISecondaryAuthenticationFactorAuthenticationStageInfo> value) noexcept override
{
try
{
typename D::abi_guard guard(this->shim());
*value = detach_abi(this->shim().StageInfo());
return S_OK;
}
catch (...)
{
*value = nullptr;
return impl::to_hresult();
}
}
};
template <typename D>
struct produce<D, Windows::Security::Authentication::Identity::Provider::ISecondaryAuthenticationFactorAuthenticationStageInfo> : produce_base<D, Windows::Security::Authentication::Identity::Provider::ISecondaryAuthenticationFactorAuthenticationStageInfo>
{
HRESULT __stdcall get_Stage(Windows::Security::Authentication::Identity::Provider::SecondaryAuthenticationFactorAuthenticationStage * value) noexcept override
{
try
{
typename D::abi_guard guard(this->shim());
*value = detach_abi(this->shim().Stage());
return S_OK;
}
catch (...)
{
return impl::to_hresult();
}
}
HRESULT __stdcall get_Scenario(Windows::Security::Authentication::Identity::Provider::SecondaryAuthenticationFactorAuthenticationScenario * value) noexcept override
{
try
{
typename D::abi_guard guard(this->shim());
*value = detach_abi(this->shim().Scenario());
return S_OK;
}
catch (...)
{
return impl::to_hresult();
}
}
HRESULT __stdcall get_DeviceId(impl::abi_arg_out<hstring> value) noexcept override
{
try
{
typename D::abi_guard guard(this->shim());
*value = detach_abi(this->shim().DeviceId());
return S_OK;
}
catch (...)
{
*value = nullptr;
return impl::to_hresult();
}
}
};
template <typename D>
struct produce<D, Windows::Security::Authentication::Identity::Provider::ISecondaryAuthenticationFactorAuthenticationStatics> : produce_base<D, Windows::Security::Authentication::Identity::Provider::ISecondaryAuthenticationFactorAuthenticationStatics>
{
HRESULT __stdcall abi_ShowNotificationMessageAsync(impl::abi_arg_in<hstring> deviceName, Windows::Security::Authentication::Identity::Provider::SecondaryAuthenticationFactorAuthenticationMessage message, impl::abi_arg_out<Windows::Foundation::IAsyncAction> result) noexcept override
{
try
{
typename D::abi_guard guard(this->shim());
*result = detach_abi(this->shim().ShowNotificationMessageAsync(*reinterpret_cast<const hstring *>(&deviceName), message));
return S_OK;
}
catch (...)
{
*result = nullptr;
return impl::to_hresult();
}
}
HRESULT __stdcall abi_StartAuthenticationAsync(impl::abi_arg_in<hstring> deviceId, impl::abi_arg_in<Windows::Storage::Streams::IBuffer> serviceAuthenticationNonce, impl::abi_arg_out<Windows::Foundation::IAsyncOperation<Windows::Security::Authentication::Identity::Provider::SecondaryAuthenticationFactorAuthenticationResult>> operation) noexcept override
{
try
{
typename D::abi_guard guard(this->shim());
*operation = detach_abi(this->shim().StartAuthenticationAsync(*reinterpret_cast<const hstring *>(&deviceId), *reinterpret_cast<const Windows::Storage::Streams::IBuffer *>(&serviceAuthenticationNonce)));
return S_OK;
}
catch (...)
{
*operation = nullptr;
return impl::to_hresult();
}
}
HRESULT __stdcall add_AuthenticationStageChanged(impl::abi_arg_in<Windows::Foundation::EventHandler<Windows::Security::Authentication::Identity::Provider::SecondaryAuthenticationFactorAuthenticationStageChangedEventArgs>> handler, event_token * token) noexcept override
{
try
{
typename D::abi_guard guard(this->shim());
*token = detach_abi(this->shim().AuthenticationStageChanged(*reinterpret_cast<const Windows::Foundation::EventHandler<Windows::Security::Authentication::Identity::Provider::SecondaryAuthenticationFactorAuthenticationStageChangedEventArgs> *>(&handler)));
return S_OK;
}
catch (...)
{
return impl::to_hresult();
}
}
HRESULT __stdcall remove_AuthenticationStageChanged(event_token token) noexcept override
{
try
{
typename D::abi_guard guard(this->shim());
this->shim().AuthenticationStageChanged(token);
return S_OK;
}
catch (...)
{
return impl::to_hresult();
}
}
HRESULT __stdcall abi_GetAuthenticationStageInfoAsync(impl::abi_arg_out<Windows::Foundation::IAsyncOperation<Windows::Security::Authentication::Identity::Provider::SecondaryAuthenticationFactorAuthenticationStageInfo>> result) noexcept override
{
try
{
typename D::abi_guard guard(this->shim());
*result = detach_abi(this->shim().GetAuthenticationStageInfoAsync());
return S_OK;
}
catch (...)
{
*result = nullptr;
return impl::to_hresult();
}
}
};
template <typename D>
struct produce<D, Windows::Security::Authentication::Identity::Provider::ISecondaryAuthenticationFactorDevicePresenceMonitoringRegistrationStatics> : produce_base<D, Windows::Security::Authentication::Identity::Provider::ISecondaryAuthenticationFactorDevicePresenceMonitoringRegistrationStatics>
{
HRESULT __stdcall abi_RegisterDevicePresenceMonitoringAsync(impl::abi_arg_in<hstring> deviceId, impl::abi_arg_in<hstring> deviceInstancePath, Windows::Security::Authentication::Identity::Provider::SecondaryAuthenticationFactorDevicePresenceMonitoringMode monitoringMode, impl::abi_arg_out<Windows::Foundation::IAsyncOperation<winrt::Windows::Security::Authentication::Identity::Provider::SecondaryAuthenticationFactorDevicePresenceMonitoringRegistrationStatus>> operation) noexcept override
{
try
{
typename D::abi_guard guard(this->shim());
*operation = detach_abi(this->shim().RegisterDevicePresenceMonitoringAsync(*reinterpret_cast<const hstring *>(&deviceId), *reinterpret_cast<const hstring *>(&deviceInstancePath), monitoringMode));
return S_OK;
}
catch (...)
{
*operation = nullptr;
return impl::to_hresult();
}
}
HRESULT __stdcall abi_RegisterDevicePresenceMonitoringWithNewDeviceAsync(impl::abi_arg_in<hstring> deviceId, impl::abi_arg_in<hstring> deviceInstancePath, Windows::Security::Authentication::Identity::Provider::SecondaryAuthenticationFactorDevicePresenceMonitoringMode monitoringMode, impl::abi_arg_in<hstring> deviceFriendlyName, impl::abi_arg_in<hstring> deviceModelNumber, impl::abi_arg_in<Windows::Storage::Streams::IBuffer> deviceConfigurationData, impl::abi_arg_out<Windows::Foundation::IAsyncOperation<winrt::Windows::Security::Authentication::Identity::Provider::SecondaryAuthenticationFactorDevicePresenceMonitoringRegistrationStatus>> operation) noexcept override
{
try
{
typename D::abi_guard guard(this->shim());
*operation = detach_abi(this->shim().RegisterDevicePresenceMonitoringAsync(*reinterpret_cast<const hstring *>(&deviceId), *reinterpret_cast<const hstring *>(&deviceInstancePath), monitoringMode, *reinterpret_cast<const hstring *>(&deviceFriendlyName), *reinterpret_cast<const hstring *>(&deviceModelNumber), *reinterpret_cast<const Windows::Storage::Streams::IBuffer *>(&deviceConfigurationData)));
return S_OK;
}
catch (...)
{
*operation = nullptr;
return impl::to_hresult();
}
}
HRESULT __stdcall abi_UnregisterDevicePresenceMonitoringAsync(impl::abi_arg_in<hstring> deviceId, impl::abi_arg_out<Windows::Foundation::IAsyncAction> result) noexcept override
{
try
{
typename D::abi_guard guard(this->shim());
*result = detach_abi(this->shim().UnregisterDevicePresenceMonitoringAsync(*reinterpret_cast<const hstring *>(&deviceId)));
return S_OK;
}
catch (...)
{
*result = nullptr;
return impl::to_hresult();
}
}
HRESULT __stdcall abi_IsDevicePresenceMonitoringSupported(bool * value) noexcept override
{
try
{
typename D::abi_guard guard(this->shim());
*value = detach_abi(this->shim().IsDevicePresenceMonitoringSupported());
return S_OK;
}
catch (...)
{
return impl::to_hresult();
}
}
};
template <typename D>
struct produce<D, Windows::Security::Authentication::Identity::Provider::ISecondaryAuthenticationFactorInfo> : produce_base<D, Windows::Security::Authentication::Identity::Provider::ISecondaryAuthenticationFactorInfo>
{
HRESULT __stdcall get_DeviceId(impl::abi_arg_out<hstring> deviceId) noexcept override
{
try
{
typename D::abi_guard guard(this->shim());
*deviceId = detach_abi(this->shim().DeviceId());
return S_OK;
}
catch (...)
{
*deviceId = nullptr;
return impl::to_hresult();
}
}
HRESULT __stdcall get_DeviceFriendlyName(impl::abi_arg_out<hstring> value) noexcept override
{
try
{
typename D::abi_guard guard(this->shim());
*value = detach_abi(this->shim().DeviceFriendlyName());
return S_OK;
}
catch (...)
{
*value = nullptr;
return impl::to_hresult();
}
}
HRESULT __stdcall get_DeviceModelNumber(impl::abi_arg_out<hstring> value) noexcept override
{
try
{
typename D::abi_guard guard(this->shim());
*value = detach_abi(this->shim().DeviceModelNumber());
return S_OK;
}
catch (...)
{
*value = nullptr;
return impl::to_hresult();
}
}
HRESULT __stdcall get_DeviceConfigurationData(impl::abi_arg_out<Windows::Storage::Streams::IBuffer> value) noexcept override
{
try
{
typename D::abi_guard guard(this->shim());
*value = detach_abi(this->shim().DeviceConfigurationData());
return S_OK;
}
catch (...)
{
*value = nullptr;
return impl::to_hresult();
}
}
};
template <typename D>
struct produce<D, Windows::Security::Authentication::Identity::Provider::ISecondaryAuthenticationFactorInfo2> : produce_base<D, Windows::Security::Authentication::Identity::Provider::ISecondaryAuthenticationFactorInfo2>
{
HRESULT __stdcall get_PresenceMonitoringMode(Windows::Security::Authentication::Identity::Provider::SecondaryAuthenticationFactorDevicePresenceMonitoringMode * value) noexcept override
{
try
{
typename D::abi_guard guard(this->shim());
*value = detach_abi(this->shim().PresenceMonitoringMode());
return S_OK;
}
catch (...)
{
return impl::to_hresult();
}
}
HRESULT __stdcall abi_UpdateDevicePresenceAsync(Windows::Security::Authentication::Identity::Provider::SecondaryAuthenticationFactorDevicePresence presenceState, impl::abi_arg_out<Windows::Foundation::IAsyncAction> result) noexcept override
{
try
{
typename D::abi_guard guard(this->shim());
*result = detach_abi(this->shim().UpdateDevicePresenceAsync(presenceState));
return S_OK;
}
catch (...)
{
*result = nullptr;
return impl::to_hresult();
}
}
HRESULT __stdcall get_IsAuthenticationSupported(bool * value) noexcept override
{
try
{
typename D::abi_guard guard(this->shim());
*value = detach_abi(this->shim().IsAuthenticationSupported());
return S_OK;
}
catch (...)
{
return impl::to_hresult();
}
}
};
template <typename D>
struct produce<D, Windows::Security::Authentication::Identity::Provider::ISecondaryAuthenticationFactorRegistration> : produce_base<D, Windows::Security::Authentication::Identity::Provider::ISecondaryAuthenticationFactorRegistration>
{
HRESULT __stdcall abi_FinishRegisteringDeviceAsync(impl::abi_arg_in<Windows::Storage::Streams::IBuffer> deviceConfigurationData, impl::abi_arg_out<Windows::Foundation::IAsyncAction> result) noexcept override
{
try
{
typename D::abi_guard guard(this->shim());
*result = detach_abi(this->shim().FinishRegisteringDeviceAsync(*reinterpret_cast<const Windows::Storage::Streams::IBuffer *>(&deviceConfigurationData)));
return S_OK;
}
catch (...)
{
*result = nullptr;
return impl::to_hresult();
}
}
HRESULT __stdcall abi_AbortRegisteringDeviceAsync(impl::abi_arg_in<hstring> errorLogMessage, impl::abi_arg_out<Windows::Foundation::IAsyncAction> result) noexcept override
{
try
{
typename D::abi_guard guard(this->shim());
*result = detach_abi(this->shim().AbortRegisteringDeviceAsync(*reinterpret_cast<const hstring *>(&errorLogMessage)));
return S_OK;
}
catch (...)
{
*result = nullptr;
return impl::to_hresult();
}
}
};
template <typename D>
struct produce<D, Windows::Security::Authentication::Identity::Provider::ISecondaryAuthenticationFactorRegistrationResult> : produce_base<D, Windows::Security::Authentication::Identity::Provider::ISecondaryAuthenticationFactorRegistrationResult>
{
HRESULT __stdcall get_Status(Windows::Security::Authentication::Identity::Provider::SecondaryAuthenticationFactorRegistrationStatus * value) noexcept override
{
try
{
typename D::abi_guard guard(this->shim());
*value = detach_abi(this->shim().Status());
return S_OK;
}
catch (...)
{
return impl::to_hresult();
}
}
HRESULT __stdcall get_Registration(impl::abi_arg_out<Windows::Security::Authentication::Identity::Provider::ISecondaryAuthenticationFactorRegistration> value) noexcept override
{
try
{
typename D::abi_guard guard(this->shim());
*value = detach_abi(this->shim().Registration());
return S_OK;
}
catch (...)
{
*value = nullptr;
return impl::to_hresult();
}
}
};
template <typename D>
struct produce<D, Windows::Security::Authentication::Identity::Provider::ISecondaryAuthenticationFactorRegistrationStatics> : produce_base<D, Windows::Security::Authentication::Identity::Provider::ISecondaryAuthenticationFactorRegistrationStatics>
{
HRESULT __stdcall abi_RequestStartRegisteringDeviceAsync(impl::abi_arg_in<hstring> deviceId, Windows::Security::Authentication::Identity::Provider::SecondaryAuthenticationFactorDeviceCapabilities capabilities, impl::abi_arg_in<hstring> deviceFriendlyName, impl::abi_arg_in<hstring> deviceModelNumber, impl::abi_arg_in<Windows::Storage::Streams::IBuffer> deviceKey, impl::abi_arg_in<Windows::Storage::Streams::IBuffer> mutualAuthenticationKey, impl::abi_arg_out<Windows::Foundation::IAsyncOperation<Windows::Security::Authentication::Identity::Provider::SecondaryAuthenticationFactorRegistrationResult>> operation) noexcept override
{
try
{
typename D::abi_guard guard(this->shim());
*operation = detach_abi(this->shim().RequestStartRegisteringDeviceAsync(*reinterpret_cast<const hstring *>(&deviceId), capabilities, *reinterpret_cast<const hstring *>(&deviceFriendlyName), *reinterpret_cast<const hstring *>(&deviceModelNumber), *reinterpret_cast<const Windows::Storage::Streams::IBuffer *>(&deviceKey), *reinterpret_cast<const Windows::Storage::Streams::IBuffer *>(&mutualAuthenticationKey)));
return S_OK;
}
catch (...)
{
*operation = nullptr;
return impl::to_hresult();
}
}
HRESULT __stdcall abi_FindAllRegisteredDeviceInfoAsync(Windows::Security::Authentication::Identity::Provider::SecondaryAuthenticationFactorDeviceFindScope queryType, impl::abi_arg_out<Windows::Foundation::IAsyncOperation<Windows::Foundation::Collections::IVectorView<Windows::Security::Authentication::Identity::Provider::SecondaryAuthenticationFactorInfo>>> deviceInfoList) noexcept override
{
try
{
typename D::abi_guard guard(this->shim());
*deviceInfoList = detach_abi(this->shim().FindAllRegisteredDeviceInfoAsync(queryType));
return S_OK;
}
catch (...)
{
*deviceInfoList = nullptr;
return impl::to_hresult();
}
}
HRESULT __stdcall abi_UnregisterDeviceAsync(impl::abi_arg_in<hstring> deviceId, impl::abi_arg_out<Windows::Foundation::IAsyncAction> result) noexcept override
{
try
{
typename D::abi_guard guard(this->shim());
*result = detach_abi(this->shim().UnregisterDeviceAsync(*reinterpret_cast<const hstring *>(&deviceId)));
return S_OK;
}
catch (...)
{
*result = nullptr;
return impl::to_hresult();
}
}
HRESULT __stdcall abi_UpdateDeviceConfigurationDataAsync(impl::abi_arg_in<hstring> deviceId, impl::abi_arg_in<Windows::Storage::Streams::IBuffer> deviceConfigurationData, impl::abi_arg_out<Windows::Foundation::IAsyncAction> result) noexcept override
{
try
{
typename D::abi_guard guard(this->shim());
*result = detach_abi(this->shim().UpdateDeviceConfigurationDataAsync(*reinterpret_cast<const hstring *>(&deviceId), *reinterpret_cast<const Windows::Storage::Streams::IBuffer *>(&deviceConfigurationData)));
return S_OK;
}
catch (...)
{
*result = nullptr;
return impl::to_hresult();
}
}
};
}
namespace Windows::Security::Authentication::Identity::Provider {
template <typename D> Windows::Security::Authentication::Identity::Provider::SecondaryAuthenticationFactorRegistrationStatus impl_ISecondaryAuthenticationFactorRegistrationResult<D>::Status() const
{
Windows::Security::Authentication::Identity::Provider::SecondaryAuthenticationFactorRegistrationStatus value {};
check_hresult(WINRT_SHIM(ISecondaryAuthenticationFactorRegistrationResult)->get_Status(&value));
return value;
}
template <typename D> Windows::Security::Authentication::Identity::Provider::SecondaryAuthenticationFactorRegistration impl_ISecondaryAuthenticationFactorRegistrationResult<D>::Registration() const
{
Windows::Security::Authentication::Identity::Provider::SecondaryAuthenticationFactorRegistration value { nullptr };
check_hresult(WINRT_SHIM(ISecondaryAuthenticationFactorRegistrationResult)->get_Registration(put_abi(value)));
return value;
}
template <typename D> Windows::Security::Authentication::Identity::Provider::SecondaryAuthenticationFactorAuthenticationStatus impl_ISecondaryAuthenticationFactorAuthenticationResult<D>::Status() const
{
Windows::Security::Authentication::Identity::Provider::SecondaryAuthenticationFactorAuthenticationStatus value {};
check_hresult(WINRT_SHIM(ISecondaryAuthenticationFactorAuthenticationResult)->get_Status(&value));
return value;
}
template <typename D> Windows::Security::Authentication::Identity::Provider::SecondaryAuthenticationFactorAuthentication impl_ISecondaryAuthenticationFactorAuthenticationResult<D>::Authentication() const
{
Windows::Security::Authentication::Identity::Provider::SecondaryAuthenticationFactorAuthentication value { nullptr };
check_hresult(WINRT_SHIM(ISecondaryAuthenticationFactorAuthenticationResult)->get_Authentication(put_abi(value)));
return value;
}
template <typename D> Windows::Foundation::IAsyncOperation<Windows::Security::Authentication::Identity::Provider::SecondaryAuthenticationFactorRegistrationResult> impl_ISecondaryAuthenticationFactorRegistrationStatics<D>::RequestStartRegisteringDeviceAsync(hstring_view deviceId, Windows::Security::Authentication::Identity::Provider::SecondaryAuthenticationFactorDeviceCapabilities capabilities, hstring_view deviceFriendlyName, hstring_view deviceModelNumber, const Windows::Storage::Streams::IBuffer & deviceKey, const Windows::Storage::Streams::IBuffer & mutualAuthenticationKey) const
{
Windows::Foundation::IAsyncOperation<Windows::Security::Authentication::Identity::Provider::SecondaryAuthenticationFactorRegistrationResult> operation;
check_hresult(WINRT_SHIM(ISecondaryAuthenticationFactorRegistrationStatics)->abi_RequestStartRegisteringDeviceAsync(get_abi(deviceId), capabilities, get_abi(deviceFriendlyName), get_abi(deviceModelNumber), get_abi(deviceKey), get_abi(mutualAuthenticationKey), put_abi(operation)));
return operation;
}
template <typename D> Windows::Foundation::IAsyncOperation<Windows::Foundation::Collections::IVectorView<Windows::Security::Authentication::Identity::Provider::SecondaryAuthenticationFactorInfo>> impl_ISecondaryAuthenticationFactorRegistrationStatics<D>::FindAllRegisteredDeviceInfoAsync(Windows::Security::Authentication::Identity::Provider::SecondaryAuthenticationFactorDeviceFindScope queryType) const
{
Windows::Foundation::IAsyncOperation<Windows::Foundation::Collections::IVectorView<Windows::Security::Authentication::Identity::Provider::SecondaryAuthenticationFactorInfo>> deviceInfoList;
check_hresult(WINRT_SHIM(ISecondaryAuthenticationFactorRegistrationStatics)->abi_FindAllRegisteredDeviceInfoAsync(queryType, put_abi(deviceInfoList)));
return deviceInfoList;
}
template <typename D> Windows::Foundation::IAsyncAction impl_ISecondaryAuthenticationFactorRegistrationStatics<D>::UnregisterDeviceAsync(hstring_view deviceId) const
{
Windows::Foundation::IAsyncAction result;
check_hresult(WINRT_SHIM(ISecondaryAuthenticationFactorRegistrationStatics)->abi_UnregisterDeviceAsync(get_abi(deviceId), put_abi(result)));
return result;
}
template <typename D> Windows::Foundation::IAsyncAction impl_ISecondaryAuthenticationFactorRegistrationStatics<D>::UpdateDeviceConfigurationDataAsync(hstring_view deviceId, const Windows::Storage::Streams::IBuffer & deviceConfigurationData) const
{
Windows::Foundation::IAsyncAction result;
check_hresult(WINRT_SHIM(ISecondaryAuthenticationFactorRegistrationStatics)->abi_UpdateDeviceConfigurationDataAsync(get_abi(deviceId), get_abi(deviceConfigurationData), put_abi(result)));
return result;
}
template <typename D> Windows::Foundation::IAsyncOperation<winrt::Windows::Security::Authentication::Identity::Provider::SecondaryAuthenticationFactorDevicePresenceMonitoringRegistrationStatus> impl_ISecondaryAuthenticationFactorDevicePresenceMonitoringRegistrationStatics<D>::RegisterDevicePresenceMonitoringAsync(hstring_view deviceId, hstring_view deviceInstancePath, Windows::Security::Authentication::Identity::Provider::SecondaryAuthenticationFactorDevicePresenceMonitoringMode monitoringMode) const
{
Windows::Foundation::IAsyncOperation<winrt::Windows::Security::Authentication::Identity::Provider::SecondaryAuthenticationFactorDevicePresenceMonitoringRegistrationStatus> operation;
check_hresult(WINRT_SHIM(ISecondaryAuthenticationFactorDevicePresenceMonitoringRegistrationStatics)->abi_RegisterDevicePresenceMonitoringAsync(get_abi(deviceId), get_abi(deviceInstancePath), monitoringMode, put_abi(operation)));
return operation;
}
template <typename D> Windows::Foundation::IAsyncOperation<winrt::Windows::Security::Authentication::Identity::Provider::SecondaryAuthenticationFactorDevicePresenceMonitoringRegistrationStatus> impl_ISecondaryAuthenticationFactorDevicePresenceMonitoringRegistrationStatics<D>::RegisterDevicePresenceMonitoringAsync(hstring_view deviceId, hstring_view deviceInstancePath, Windows::Security::Authentication::Identity::Provider::SecondaryAuthenticationFactorDevicePresenceMonitoringMode monitoringMode, hstring_view deviceFriendlyName, hstring_view deviceModelNumber, const Windows::Storage::Streams::IBuffer & deviceConfigurationData) const
{
Windows::Foundation::IAsyncOperation<winrt::Windows::Security::Authentication::Identity::Provider::SecondaryAuthenticationFactorDevicePresenceMonitoringRegistrationStatus> operation;
check_hresult(WINRT_SHIM(ISecondaryAuthenticationFactorDevicePresenceMonitoringRegistrationStatics)->abi_RegisterDevicePresenceMonitoringWithNewDeviceAsync(get_abi(deviceId), get_abi(deviceInstancePath), monitoringMode, get_abi(deviceFriendlyName), get_abi(deviceModelNumber), get_abi(deviceConfigurationData), put_abi(operation)));
return operation;
}
template <typename D> Windows::Foundation::IAsyncAction impl_ISecondaryAuthenticationFactorDevicePresenceMonitoringRegistrationStatics<D>::UnregisterDevicePresenceMonitoringAsync(hstring_view deviceId) const
{
Windows::Foundation::IAsyncAction result;
check_hresult(WINRT_SHIM(ISecondaryAuthenticationFactorDevicePresenceMonitoringRegistrationStatics)->abi_UnregisterDevicePresenceMonitoringAsync(get_abi(deviceId), put_abi(result)));
return result;
}
template <typename D> bool impl_ISecondaryAuthenticationFactorDevicePresenceMonitoringRegistrationStatics<D>::IsDevicePresenceMonitoringSupported() const
{
bool value {};
check_hresult(WINRT_SHIM(ISecondaryAuthenticationFactorDevicePresenceMonitoringRegistrationStatics)->abi_IsDevicePresenceMonitoringSupported(&value));
return value;
}
template <typename D> Windows::Foundation::IAsyncAction impl_ISecondaryAuthenticationFactorRegistration<D>::FinishRegisteringDeviceAsync(const Windows::Storage::Streams::IBuffer & deviceConfigurationData) const
{
Windows::Foundation::IAsyncAction result;
check_hresult(WINRT_SHIM(ISecondaryAuthenticationFactorRegistration)->abi_FinishRegisteringDeviceAsync(get_abi(deviceConfigurationData), put_abi(result)));
return result;
}
template <typename D> Windows::Foundation::IAsyncAction impl_ISecondaryAuthenticationFactorRegistration<D>::AbortRegisteringDeviceAsync(hstring_view errorLogMessage) const
{
Windows::Foundation::IAsyncAction result;
check_hresult(WINRT_SHIM(ISecondaryAuthenticationFactorRegistration)->abi_AbortRegisteringDeviceAsync(get_abi(errorLogMessage), put_abi(result)));
return result;
}
template <typename D> Windows::Foundation::IAsyncAction impl_ISecondaryAuthenticationFactorAuthenticationStatics<D>::ShowNotificationMessageAsync(hstring_view deviceName, Windows::Security::Authentication::Identity::Provider::SecondaryAuthenticationFactorAuthenticationMessage message) const
{
Windows::Foundation::IAsyncAction result;
check_hresult(WINRT_SHIM(ISecondaryAuthenticationFactorAuthenticationStatics)->abi_ShowNotificationMessageAsync(get_abi(deviceName), message, put_abi(result)));
return result;
}
template <typename D> Windows::Foundation::IAsyncOperation<Windows::Security::Authentication::Identity::Provider::SecondaryAuthenticationFactorAuthenticationResult> impl_ISecondaryAuthenticationFactorAuthenticationStatics<D>::StartAuthenticationAsync(hstring_view deviceId, const Windows::Storage::Streams::IBuffer & serviceAuthenticationNonce) const
{
Windows::Foundation::IAsyncOperation<Windows::Security::Authentication::Identity::Provider::SecondaryAuthenticationFactorAuthenticationResult> operation;
check_hresult(WINRT_SHIM(ISecondaryAuthenticationFactorAuthenticationStatics)->abi_StartAuthenticationAsync(get_abi(deviceId), get_abi(serviceAuthenticationNonce), put_abi(operation)));
return operation;
}
template <typename D> event_token impl_ISecondaryAuthenticationFactorAuthenticationStatics<D>::AuthenticationStageChanged(const Windows::Foundation::EventHandler<Windows::Security::Authentication::Identity::Provider::SecondaryAuthenticationFactorAuthenticationStageChangedEventArgs> & handler) const
{
event_token token {};
check_hresult(WINRT_SHIM(ISecondaryAuthenticationFactorAuthenticationStatics)->add_AuthenticationStageChanged(get_abi(handler), &token));
return token;
}
template <typename D> event_revoker<ISecondaryAuthenticationFactorAuthenticationStatics> impl_ISecondaryAuthenticationFactorAuthenticationStatics<D>::AuthenticationStageChanged(auto_revoke_t, const Windows::Foundation::EventHandler<Windows::Security::Authentication::Identity::Provider::SecondaryAuthenticationFactorAuthenticationStageChangedEventArgs> & handler) const
{
return impl::make_event_revoker<D, ISecondaryAuthenticationFactorAuthenticationStatics>(this, &ABI::Windows::Security::Authentication::Identity::Provider::ISecondaryAuthenticationFactorAuthenticationStatics::remove_AuthenticationStageChanged, AuthenticationStageChanged(handler));
}
template <typename D> void impl_ISecondaryAuthenticationFactorAuthenticationStatics<D>::AuthenticationStageChanged(event_token token) const
{
check_hresult(WINRT_SHIM(ISecondaryAuthenticationFactorAuthenticationStatics)->remove_AuthenticationStageChanged(token));
}
template <typename D> Windows::Foundation::IAsyncOperation<Windows::Security::Authentication::Identity::Provider::SecondaryAuthenticationFactorAuthenticationStageInfo> impl_ISecondaryAuthenticationFactorAuthenticationStatics<D>::GetAuthenticationStageInfoAsync() const
{
Windows::Foundation::IAsyncOperation<Windows::Security::Authentication::Identity::Provider::SecondaryAuthenticationFactorAuthenticationStageInfo> result;
check_hresult(WINRT_SHIM(ISecondaryAuthenticationFactorAuthenticationStatics)->abi_GetAuthenticationStageInfoAsync(put_abi(result)));
return result;
}
template <typename D> Windows::Storage::Streams::IBuffer impl_ISecondaryAuthenticationFactorAuthentication<D>::ServiceAuthenticationHmac() const
{
Windows::Storage::Streams::IBuffer value;
check_hresult(WINRT_SHIM(ISecondaryAuthenticationFactorAuthentication)->get_ServiceAuthenticationHmac(put_abi(value)));
return value;
}
template <typename D> Windows::Storage::Streams::IBuffer impl_ISecondaryAuthenticationFactorAuthentication<D>::SessionNonce() const
{
Windows::Storage::Streams::IBuffer value;
check_hresult(WINRT_SHIM(ISecondaryAuthenticationFactorAuthentication)->get_SessionNonce(put_abi(value)));
return value;
}
template <typename D> Windows::Storage::Streams::IBuffer impl_ISecondaryAuthenticationFactorAuthentication<D>::DeviceNonce() const
{
Windows::Storage::Streams::IBuffer value;
check_hresult(WINRT_SHIM(ISecondaryAuthenticationFactorAuthentication)->get_DeviceNonce(put_abi(value)));
return value;
}
template <typename D> Windows::Storage::Streams::IBuffer impl_ISecondaryAuthenticationFactorAuthentication<D>::DeviceConfigurationData() const
{
Windows::Storage::Streams::IBuffer value;
check_hresult(WINRT_SHIM(ISecondaryAuthenticationFactorAuthentication)->get_DeviceConfigurationData(put_abi(value)));
return value;
}
template <typename D> Windows::Foundation::IAsyncOperation<winrt::Windows::Security::Authentication::Identity::Provider::SecondaryAuthenticationFactorFinishAuthenticationStatus> impl_ISecondaryAuthenticationFactorAuthentication<D>::FinishAuthenticationAsync(const Windows::Storage::Streams::IBuffer & deviceHmac, const Windows::Storage::Streams::IBuffer & sessionHmac) const
{
Windows::Foundation::IAsyncOperation<winrt::Windows::Security::Authentication::Identity::Provider::SecondaryAuthenticationFactorFinishAuthenticationStatus> result;
check_hresult(WINRT_SHIM(ISecondaryAuthenticationFactorAuthentication)->abi_FinishAuthenticationAsync(get_abi(deviceHmac), get_abi(sessionHmac), put_abi(result)));
return result;
}
template <typename D> Windows::Foundation::IAsyncAction impl_ISecondaryAuthenticationFactorAuthentication<D>::AbortAuthenticationAsync(hstring_view errorLogMessage) const
{
Windows::Foundation::IAsyncAction result;
check_hresult(WINRT_SHIM(ISecondaryAuthenticationFactorAuthentication)->abi_AbortAuthenticationAsync(get_abi(errorLogMessage), put_abi(result)));
return result;
}
template <typename D> hstring impl_ISecondaryAuthenticationFactorInfo<D>::DeviceId() const
{
hstring deviceId;
check_hresult(WINRT_SHIM(ISecondaryAuthenticationFactorInfo)->get_DeviceId(put_abi(deviceId)));
return deviceId;
}
template <typename D> hstring impl_ISecondaryAuthenticationFactorInfo<D>::DeviceFriendlyName() const
{
hstring value;
check_hresult(WINRT_SHIM(ISecondaryAuthenticationFactorInfo)->get_DeviceFriendlyName(put_abi(value)));
return value;
}
template <typename D> hstring impl_ISecondaryAuthenticationFactorInfo<D>::DeviceModelNumber() const
{
hstring value;
check_hresult(WINRT_SHIM(ISecondaryAuthenticationFactorInfo)->get_DeviceModelNumber(put_abi(value)));
return value;
}
template <typename D> Windows::Storage::Streams::IBuffer impl_ISecondaryAuthenticationFactorInfo<D>::DeviceConfigurationData() const
{
Windows::Storage::Streams::IBuffer value;
check_hresult(WINRT_SHIM(ISecondaryAuthenticationFactorInfo)->get_DeviceConfigurationData(put_abi(value)));
return value;
}
template <typename D> Windows::Security::Authentication::Identity::Provider::SecondaryAuthenticationFactorDevicePresenceMonitoringMode impl_ISecondaryAuthenticationFactorInfo2<D>::PresenceMonitoringMode() const
{
Windows::Security::Authentication::Identity::Provider::SecondaryAuthenticationFactorDevicePresenceMonitoringMode value {};
check_hresult(WINRT_SHIM(ISecondaryAuthenticationFactorInfo2)->get_PresenceMonitoringMode(&value));
return value;
}
template <typename D> Windows::Foundation::IAsyncAction impl_ISecondaryAuthenticationFactorInfo2<D>::UpdateDevicePresenceAsync(Windows::Security::Authentication::Identity::Provider::SecondaryAuthenticationFactorDevicePresence presenceState) const
{
Windows::Foundation::IAsyncAction result;
check_hresult(WINRT_SHIM(ISecondaryAuthenticationFactorInfo2)->abi_UpdateDevicePresenceAsync(presenceState, put_abi(result)));
return result;
}
template <typename D> bool impl_ISecondaryAuthenticationFactorInfo2<D>::IsAuthenticationSupported() const
{
bool value {};
check_hresult(WINRT_SHIM(ISecondaryAuthenticationFactorInfo2)->get_IsAuthenticationSupported(&value));
return value;
}
template <typename D> Windows::Security::Authentication::Identity::Provider::SecondaryAuthenticationFactorAuthenticationStage impl_ISecondaryAuthenticationFactorAuthenticationStageInfo<D>::Stage() const
{
Windows::Security::Authentication::Identity::Provider::SecondaryAuthenticationFactorAuthenticationStage value {};
check_hresult(WINRT_SHIM(ISecondaryAuthenticationFactorAuthenticationStageInfo)->get_Stage(&value));
return value;
}
template <typename D> Windows::Security::Authentication::Identity::Provider::SecondaryAuthenticationFactorAuthenticationScenario impl_ISecondaryAuthenticationFactorAuthenticationStageInfo<D>::Scenario() const
{
Windows::Security::Authentication::Identity::Provider::SecondaryAuthenticationFactorAuthenticationScenario value {};
check_hresult(WINRT_SHIM(ISecondaryAuthenticationFactorAuthenticationStageInfo)->get_Scenario(&value));
return value;
}
template <typename D> hstring impl_ISecondaryAuthenticationFactorAuthenticationStageInfo<D>::DeviceId() const
{
hstring value;
check_hresult(WINRT_SHIM(ISecondaryAuthenticationFactorAuthenticationStageInfo)->get_DeviceId(put_abi(value)));
return value;
}
template <typename D> Windows::Security::Authentication::Identity::Provider::SecondaryAuthenticationFactorAuthenticationStageInfo impl_ISecondaryAuthenticationFactorAuthenticationStageChangedEventArgs<D>::StageInfo() const
{
Windows::Security::Authentication::Identity::Provider::SecondaryAuthenticationFactorAuthenticationStageInfo value { nullptr };
check_hresult(WINRT_SHIM(ISecondaryAuthenticationFactorAuthenticationStageChangedEventArgs)->get_StageInfo(put_abi(value)));
return value;
}
inline Windows::Foundation::IAsyncAction SecondaryAuthenticationFactorAuthentication::ShowNotificationMessageAsync(hstring_view deviceName, Windows::Security::Authentication::Identity::Provider::SecondaryAuthenticationFactorAuthenticationMessage message)
{
return get_activation_factory<SecondaryAuthenticationFactorAuthentication, ISecondaryAuthenticationFactorAuthenticationStatics>().ShowNotificationMessageAsync(deviceName, message);
}
inline Windows::Foundation::IAsyncOperation<Windows::Security::Authentication::Identity::Provider::SecondaryAuthenticationFactorAuthenticationResult> SecondaryAuthenticationFactorAuthentication::StartAuthenticationAsync(hstring_view deviceId, const Windows::Storage::Streams::IBuffer & serviceAuthenticationNonce)
{
return get_activation_factory<SecondaryAuthenticationFactorAuthentication, ISecondaryAuthenticationFactorAuthenticationStatics>().StartAuthenticationAsync(deviceId, serviceAuthenticationNonce);
}
inline event_token SecondaryAuthenticationFactorAuthentication::AuthenticationStageChanged(const Windows::Foundation::EventHandler<Windows::Security::Authentication::Identity::Provider::SecondaryAuthenticationFactorAuthenticationStageChangedEventArgs> & handler)
{
return get_activation_factory<SecondaryAuthenticationFactorAuthentication, ISecondaryAuthenticationFactorAuthenticationStatics>().AuthenticationStageChanged(handler);
}
inline factory_event_revoker<ISecondaryAuthenticationFactorAuthenticationStatics> SecondaryAuthenticationFactorAuthentication::AuthenticationStageChanged(auto_revoke_t, const Windows::Foundation::EventHandler<Windows::Security::Authentication::Identity::Provider::SecondaryAuthenticationFactorAuthenticationStageChangedEventArgs> & handler)
{
auto factory = get_activation_factory<SecondaryAuthenticationFactorAuthentication, ISecondaryAuthenticationFactorAuthenticationStatics>();
return { factory, &ABI::Windows::Security::Authentication::Identity::Provider::ISecondaryAuthenticationFactorAuthenticationStatics::remove_AuthenticationStageChanged, factory.AuthenticationStageChanged(handler) };
}
inline void SecondaryAuthenticationFactorAuthentication::AuthenticationStageChanged(event_token token)
{
get_activation_factory<SecondaryAuthenticationFactorAuthentication, ISecondaryAuthenticationFactorAuthenticationStatics>().AuthenticationStageChanged(token);
}
inline Windows::Foundation::IAsyncOperation<Windows::Security::Authentication::Identity::Provider::SecondaryAuthenticationFactorAuthenticationStageInfo> SecondaryAuthenticationFactorAuthentication::GetAuthenticationStageInfoAsync()
{
return get_activation_factory<SecondaryAuthenticationFactorAuthentication, ISecondaryAuthenticationFactorAuthenticationStatics>().GetAuthenticationStageInfoAsync();
}
inline Windows::Foundation::IAsyncOperation<winrt::Windows::Security::Authentication::Identity::Provider::SecondaryAuthenticationFactorDevicePresenceMonitoringRegistrationStatus> SecondaryAuthenticationFactorRegistration::RegisterDevicePresenceMonitoringAsync(hstring_view deviceId, hstring_view deviceInstancePath, Windows::Security::Authentication::Identity::Provider::SecondaryAuthenticationFactorDevicePresenceMonitoringMode monitoringMode)
{
return get_activation_factory<SecondaryAuthenticationFactorRegistration, ISecondaryAuthenticationFactorDevicePresenceMonitoringRegistrationStatics>().RegisterDevicePresenceMonitoringAsync(deviceId, deviceInstancePath, monitoringMode);
}
inline Windows::Foundation::IAsyncOperation<winrt::Windows::Security::Authentication::Identity::Provider::SecondaryAuthenticationFactorDevicePresenceMonitoringRegistrationStatus> SecondaryAuthenticationFactorRegistration::RegisterDevicePresenceMonitoringAsync(hstring_view deviceId, hstring_view deviceInstancePath, Windows::Security::Authentication::Identity::Provider::SecondaryAuthenticationFactorDevicePresenceMonitoringMode monitoringMode, hstring_view deviceFriendlyName, hstring_view deviceModelNumber, const Windows::Storage::Streams::IBuffer & deviceConfigurationData)
{
return get_activation_factory<SecondaryAuthenticationFactorRegistration, ISecondaryAuthenticationFactorDevicePresenceMonitoringRegistrationStatics>().RegisterDevicePresenceMonitoringAsync(deviceId, deviceInstancePath, monitoringMode, deviceFriendlyName, deviceModelNumber, deviceConfigurationData);
}
inline Windows::Foundation::IAsyncAction SecondaryAuthenticationFactorRegistration::UnregisterDevicePresenceMonitoringAsync(hstring_view deviceId)
{
return get_activation_factory<SecondaryAuthenticationFactorRegistration, ISecondaryAuthenticationFactorDevicePresenceMonitoringRegistrationStatics>().UnregisterDevicePresenceMonitoringAsync(deviceId);
}
inline bool SecondaryAuthenticationFactorRegistration::IsDevicePresenceMonitoringSupported()
{
return get_activation_factory<SecondaryAuthenticationFactorRegistration, ISecondaryAuthenticationFactorDevicePresenceMonitoringRegistrationStatics>().IsDevicePresenceMonitoringSupported();
}
inline Windows::Foundation::IAsyncOperation<Windows::Security::Authentication::Identity::Provider::SecondaryAuthenticationFactorRegistrationResult> SecondaryAuthenticationFactorRegistration::RequestStartRegisteringDeviceAsync(hstring_view deviceId, Windows::Security::Authentication::Identity::Provider::SecondaryAuthenticationFactorDeviceCapabilities capabilities, hstring_view deviceFriendlyName, hstring_view deviceModelNumber, const Windows::Storage::Streams::IBuffer & deviceKey, const Windows::Storage::Streams::IBuffer & mutualAuthenticationKey)
{
return get_activation_factory<SecondaryAuthenticationFactorRegistration, ISecondaryAuthenticationFactorRegistrationStatics>().RequestStartRegisteringDeviceAsync(deviceId, capabilities, deviceFriendlyName, deviceModelNumber, deviceKey, mutualAuthenticationKey);
}
inline Windows::Foundation::IAsyncOperation<Windows::Foundation::Collections::IVectorView<Windows::Security::Authentication::Identity::Provider::SecondaryAuthenticationFactorInfo>> SecondaryAuthenticationFactorRegistration::FindAllRegisteredDeviceInfoAsync(Windows::Security::Authentication::Identity::Provider::SecondaryAuthenticationFactorDeviceFindScope queryType)
{
return get_activation_factory<SecondaryAuthenticationFactorRegistration, ISecondaryAuthenticationFactorRegistrationStatics>().FindAllRegisteredDeviceInfoAsync(queryType);
}
inline Windows::Foundation::IAsyncAction SecondaryAuthenticationFactorRegistration::UnregisterDeviceAsync(hstring_view deviceId)
{
return get_activation_factory<SecondaryAuthenticationFactorRegistration, ISecondaryAuthenticationFactorRegistrationStatics>().UnregisterDeviceAsync(deviceId);
}
inline Windows::Foundation::IAsyncAction SecondaryAuthenticationFactorRegistration::UpdateDeviceConfigurationDataAsync(hstring_view deviceId, const Windows::Storage::Streams::IBuffer & deviceConfigurationData)
{
return get_activation_factory<SecondaryAuthenticationFactorRegistration, ISecondaryAuthenticationFactorRegistrationStatics>().UpdateDeviceConfigurationDataAsync(deviceId, deviceConfigurationData);
}
}
}
template<>
struct std::hash<winrt::Windows::Security::Authentication::Identity::Provider::ISecondaryAuthenticationFactorAuthentication>
{
size_t operator()(const winrt::Windows::Security::Authentication::Identity::Provider::ISecondaryAuthenticationFactorAuthentication & value) const noexcept
{
return winrt::impl::hash_unknown(value);
}
};
template<>
struct std::hash<winrt::Windows::Security::Authentication::Identity::Provider::ISecondaryAuthenticationFactorAuthenticationResult>
{
size_t operator()(const winrt::Windows::Security::Authentication::Identity::Provider::ISecondaryAuthenticationFactorAuthenticationResult & value) const noexcept
{
return winrt::impl::hash_unknown(value);
}
};
template<>
struct std::hash<winrt::Windows::Security::Authentication::Identity::Provider::ISecondaryAuthenticationFactorAuthenticationStageChangedEventArgs>
{
size_t operator()(const winrt::Windows::Security::Authentication::Identity::Provider::ISecondaryAuthenticationFactorAuthenticationStageChangedEventArgs & value) const noexcept
{
return winrt::impl::hash_unknown(value);
}
};
template<>
struct std::hash<winrt::Windows::Security::Authentication::Identity::Provider::ISecondaryAuthenticationFactorAuthenticationStageInfo>
{
size_t operator()(const winrt::Windows::Security::Authentication::Identity::Provider::ISecondaryAuthenticationFactorAuthenticationStageInfo & value) const noexcept
{
return winrt::impl::hash_unknown(value);
}
};
template<>
struct std::hash<winrt::Windows::Security::Authentication::Identity::Provider::ISecondaryAuthenticationFactorAuthenticationStatics>
{
size_t operator()(const winrt::Windows::Security::Authentication::Identity::Provider::ISecondaryAuthenticationFactorAuthenticationStatics & value) const noexcept
{
return winrt::impl::hash_unknown(value);
}
};
template<>
struct std::hash<winrt::Windows::Security::Authentication::Identity::Provider::ISecondaryAuthenticationFactorDevicePresenceMonitoringRegistrationStatics>
{
size_t operator()(const winrt::Windows::Security::Authentication::Identity::Provider::ISecondaryAuthenticationFactorDevicePresenceMonitoringRegistrationStatics & value) const noexcept
{
return winrt::impl::hash_unknown(value);
}
};
template<>
struct std::hash<winrt::Windows::Security::Authentication::Identity::Provider::ISecondaryAuthenticationFactorInfo>
{
size_t operator()(const winrt::Windows::Security::Authentication::Identity::Provider::ISecondaryAuthenticationFactorInfo & value) const noexcept
{
return winrt::impl::hash_unknown(value);
}
};
template<>
struct std::hash<winrt::Windows::Security::Authentication::Identity::Provider::ISecondaryAuthenticationFactorInfo2>
{
size_t operator()(const winrt::Windows::Security::Authentication::Identity::Provider::ISecondaryAuthenticationFactorInfo2 & value) const noexcept
{
return winrt::impl::hash_unknown(value);
}
};
template<>
struct std::hash<winrt::Windows::Security::Authentication::Identity::Provider::ISecondaryAuthenticationFactorRegistration>
{
size_t operator()(const winrt::Windows::Security::Authentication::Identity::Provider::ISecondaryAuthenticationFactorRegistration & value) const noexcept
{
return winrt::impl::hash_unknown(value);
}
};
template<>
struct std::hash<winrt::Windows::Security::Authentication::Identity::Provider::ISecondaryAuthenticationFactorRegistrationResult>
{
size_t operator()(const winrt::Windows::Security::Authentication::Identity::Provider::ISecondaryAuthenticationFactorRegistrationResult & value) const noexcept
{
return winrt::impl::hash_unknown(value);
}
};
template<>
struct std::hash<winrt::Windows::Security::Authentication::Identity::Provider::ISecondaryAuthenticationFactorRegistrationStatics>
{
size_t operator()(const winrt::Windows::Security::Authentication::Identity::Provider::ISecondaryAuthenticationFactorRegistrationStatics & value) const noexcept
{
return winrt::impl::hash_unknown(value);
}
};
template<>
struct std::hash<winrt::Windows::Security::Authentication::Identity::Provider::SecondaryAuthenticationFactorAuthentication>
{
size_t operator()(const winrt::Windows::Security::Authentication::Identity::Provider::SecondaryAuthenticationFactorAuthentication & value) const noexcept
{
return winrt::impl::hash_unknown(value);
}
};
template<>
struct std::hash<winrt::Windows::Security::Authentication::Identity::Provider::SecondaryAuthenticationFactorAuthenticationResult>
{
size_t operator()(const winrt::Windows::Security::Authentication::Identity::Provider::SecondaryAuthenticationFactorAuthenticationResult & value) const noexcept
{
return winrt::impl::hash_unknown(value);
}
};
template<>
struct std::hash<winrt::Windows::Security::Authentication::Identity::Provider::SecondaryAuthenticationFactorAuthenticationStageChangedEventArgs>
{
size_t operator()(const winrt::Windows::Security::Authentication::Identity::Provider::SecondaryAuthenticationFactorAuthenticationStageChangedEventArgs & value) const noexcept
{
return winrt::impl::hash_unknown(value);
}
};
template<>
struct std::hash<winrt::Windows::Security::Authentication::Identity::Provider::SecondaryAuthenticationFactorAuthenticationStageInfo>
{
size_t operator()(const winrt::Windows::Security::Authentication::Identity::Provider::SecondaryAuthenticationFactorAuthenticationStageInfo & value) const noexcept
{
return winrt::impl::hash_unknown(value);
}
};
template<>
struct std::hash<winrt::Windows::Security::Authentication::Identity::Provider::SecondaryAuthenticationFactorInfo>
{
size_t operator()(const winrt::Windows::Security::Authentication::Identity::Provider::SecondaryAuthenticationFactorInfo & value) const noexcept
{
return winrt::impl::hash_unknown(value);
}
};
template<>
struct std::hash<winrt::Windows::Security::Authentication::Identity::Provider::SecondaryAuthenticationFactorRegistration>
{
size_t operator()(const winrt::Windows::Security::Authentication::Identity::Provider::SecondaryAuthenticationFactorRegistration & value) const noexcept
{
return winrt::impl::hash_unknown(value);
}
};
template<>
struct std::hash<winrt::Windows::Security::Authentication::Identity::Provider::SecondaryAuthenticationFactorRegistrationResult>
{
size_t operator()(const winrt::Windows::Security::Authentication::Identity::Provider::SecondaryAuthenticationFactorRegistrationResult & value) const noexcept
{
return winrt::impl::hash_unknown(value);
}
};
WINRT_WARNING_POP
|
#include "Interface.h"
void Interface::boader()
{
drawAtPoint(0, 0, "〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓", "");
for (int i = 1; i < HEIGHT - 1; i++)
{
drawAtPoint(0, i, "〓", "");
drawAtPoint(WIDTH - 2, i, "〓", "");
}
drawAtPoint(0, HEIGHT - 1, "〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓", "");
}
void Interface::menuface()
{
string str = "mode con cols=" + to_string(WIDTH) + "lines=" + to_string(HEIGHT);
system(str.c_str());
SetConsoleTitle((LPCSTR)"BATTLE CITY");
boader();
drawAtPoint(12, 4, ".____ ._______._______._. .______. _____._____._________ __", "");
drawAtPoint(12, 5, "| _ \\ /\\|__. .__|__. .__| | | .____| / ____|_. ._|__. .__\\ \\ / /", "");
drawAtPoint(12, 6, "| |_) | / \\ | | | | | | | |__. | | | | | | \\ \\_/ /", "");
drawAtPoint(12, 7, "| _ < / /\\ \\ | | | | | | | __| | | | | | | \\ /", "");
drawAtPoint(12, 8, "| |_) / ____ \\| | | | | |____| |____. | |____._| |_. | | | |", "");
drawAtPoint(12, 9, "|____/_/ \\_\\_| |_| |______|______| \\_____|_____| |_| |_|", "");
drawAtPoint(42, 15, "Game Start", "");
drawAtPoint(42, 17, "Mode Change", "");
drawAtPoint(42, 19, "Exit", "");
drawAtPoint(38, 15, "※", "");
}
void Interface::random(list<Tank*> &enemy, int &count)
{
if (enemy.empty())
{
Tank* tank = new Tank(86, 2, ENEMY);
enemy.push_back(tank);
tank = new ArmoredCar(20, 2, ENEMY);
enemy.push_back(tank);
tank = new HeavyTank(50, 2, ENEMY);
enemy.push_back(tank);
if (mode == HARD)
{
tank = new DoubleTank(12, 2, ENEMY);
enemy.push_back(tank);
tank = new DoubleTank(76, 2, ENEMY);
enemy.push_back(tank);
}
}
list<Tank*>::iterator iter = enemy.begin();
while (iter != enemy.end())
{
vector<Bullet*>::iterator bullet = (*iter)->bullets.begin();
while (bullet != (*iter)->bullets.end())
{
int res = (*bullet)->run();
if (res == -1 || (*bullet)->is_coll())
bullet = (*iter)->bullets.erase(bullet);
else
{
(*bullet)->draw(true);
bullet++;
}
}
if ((*iter)->getLife() <= 0)
{
if ((*iter)->bullets.size() <= 0)
{
iter = enemy.erase(iter);
if (mode == EASY)
{
if (--count <= 0)
return;
}
Tank* tank = nullptr;
srand((unsigned)clock());
int type = 0;
if (mode == EASY || mode == NORMAL)
type = rand() % 3;
else if (mode == HARD)
{
type = rand() % 5;
}
short x = rand() % 46 + 2;
while (map.map[2][x] || map.map[2][x - 1] || map.map[2][x + 1] || map.map[3][x - 1] || map.map[3][x] || map.map[3][x + 1])
x = rand() % 46 + 2;
switch (type)
{
case 0:tank = new Tank(x * 2, 2, ENEMY); break;
case 1:tank = new ArmoredCar(x * 2, 2, ENEMY); break;
case 2:tank = new HeavyTank(x * 2, 2, ENEMY); break;
case 3:tank = new DoubleTank(x * 2, 2, ENEMY); break;
case 4:tank = new DoubleTank(x * 2, 2, ENEMY); break;
default:
break;
}
enemy.push_back(tank);
}
else
iter++;
}
else
{
srand((unsigned)clock());
DIR flag = (DIR)(rand() % 50);
if (flag >= 13 && flag <= 17 || flag >= 25 && flag <= 29)
{
DIR direct = (DIR)(flag % 4);
(*iter)->move(direct);
}
(*iter)->draw(true);
if (flag >= 3 && flag <= 6 && (*iter)->getLife())
(*iter)->addBullet();
iter++;
}
}
}
void Interface::status(list<Tank*> fri, list<Tank*> enemy, int &count)
{
list<Tank*>::iterator iter;
int i = 0;
if (mode == EASY)
{
string num = to_string(count);
drawAtPoint(110, 4, "Enemies", "");
drawAtPoint(113, 5, num.c_str(), "");
}
for (iter = fri.begin(); iter != fri.end(); iter++)
{
string name = "Player " + to_string(i + 1);
drawAtPoint(110, 23 + i * 3, name.c_str(), "");
string item = "HP: " + to_string((*iter)->getLife());
drawAtPoint(110, 23 + i * 3 + 1, item.c_str(), "");
item = "Power: " + to_string((*iter)->getPower());
drawAtPoint(110, 23 + i * 3 + 2, item.c_str(), "");
item = "Speed: " + to_string((*iter)->getSpeed());
drawAtPoint(110, 23 + i * 3 + 3, item.c_str(), "");
item = "Volume: " + to_string((*iter)->getVolume());
drawAtPoint(110, 23 + i * 3 + 4, item.c_str(), "");
i++;
}
i = 0;
for (iter = enemy.begin(); iter != enemy.end(); iter++)
{
string name = "Enemy " + to_string(i + 1);
drawAtPoint(110, 7 + i * 3, name.c_str(), "");
string life = "HP: " + to_string((*iter)->getLife());
drawAtPoint(110, 7 + i * 3 + 1, life.c_str(), "");
i++;
}
}
void Interface::buff()
{
int a;
srand((unsigned)clock());
if (rand() % 9000 >= 30 && rand() % 9000 <= 40)
{
short x = rand() % 48 + 1;
short y = rand() % 34 + 1;
BUFFTYPE type = BUFFTYPE(rand() % 4 + LIFEBUFF);
if (!map.map[y][x])
{
map.map[y][x] = new Buff(x * 2, y, BUFF, type);
map.map[y][x]->draw(true);
a = 0;
}
}
}
void Interface::win()
{
string str = "mode con cols=" + to_string(WIDTH) + "lines=" + to_string(HEIGHT);
system(str.c_str());
system("cls");
boader();
short x = 22;
short y = 10;
for (int i = 0; i < 3; i++)
{
drawAtPoint(x, y + 0, "__ ______ _ _ __ _______._ _ _", "");
drawAtPoint(x, y + 1, "\\ \\ / / __ \\| | | | \\ \\ / /_ _| \\ | | | |", "");
drawAtPoint(x, y + 2, " \\ \\_/ / | | | | | | \\ \\ /\\ / / | | | \\| | | |", "");
drawAtPoint(x, y + 3, " \\ /| | | | | | | \\ \\/ \\/ / | | | . ` | | |", "");
drawAtPoint(x, y + 4, " | | | |__| | |__| | \\ /\\ / _| |_| |\\ | |_|", "");
drawAtPoint(x, y + 5, " |_| \\____/ \\____/ \\/ \\/ |_____|_| \\_| (_)", "");
Sleep(500);
drawAtPoint(x, y + 0, " ", "");
drawAtPoint(x, y + 1, " ", "");
drawAtPoint(x, y + 2, " ", "");
drawAtPoint(x, y + 3, " ", "");
drawAtPoint(x, y + 4, " ", "");
drawAtPoint(x, y + 5, " ", "");
Sleep(500);
}
drawAtPoint(x, y + 0, "__ ______ _ _ __ _______._ _ _", "");
drawAtPoint(x, y + 1, "\\ \\ / / __ \\| | | | \\ \\ / /_ _| \\ | | | |", "");
drawAtPoint(x, y + 2, " \\ \\_/ / | | | | | | \\ \\ /\\ / / | | | \\| | | |", "");
drawAtPoint(x, y + 3, " \\ /| | | | | | | \\ \\/ \\/ / | | | . ` | | |", "");
drawAtPoint(x, y + 4, " | | | |__| | |__| | \\ /\\ / _| |_| |\\ | |_|", "");
drawAtPoint(x, y + 5, " |_| \\____/ \\____/ \\/ \\/ |_____|_| \\_| (_)", "");
drawAtPoint(x + 20, y + 10, "", "");
system("pause");
}
void Interface::gameover()
{
string str = "mode con cols=" + to_string(WIDTH) + "lines=" + to_string(HEIGHT);
system(str.c_str());
system("cls");
boader();
short x = 18;
short y = 10;
for (int i = 0; i < 3; i++)
{
drawAtPoint(x, y + 0, " _____. .__ __.______. ______ ________._____", "");
drawAtPoint(x, y + 1, " / ____| /\\ | \\/ | ____| / __ \\ \\ / / ____| __ \\", "");
drawAtPoint(x, y + 2, "| | .__. / \\ | \\ / | |__. | | | \\ \\ / /| |__ | |__) |", "");
drawAtPoint(x, y + 3, "| | |_ | / /\\ \\ | |\\/| | __| | | | |\\ \\/ / | __| | _ /", "");
drawAtPoint(x, y + 4, "| |__| |/ ____ \\| | | | |____. | |__| | \\ / | |____| | \\ \\", "");
drawAtPoint(x, y + 5, " \\_____/_/ \\_\\_| |_|______| \\____/ \\/ |______|_| \\_\\", "");
Sleep(500);
drawAtPoint(x, y + 0, " ", "");
drawAtPoint(x, y + 1, " ", "");
drawAtPoint(x, y + 2, " ", "");
drawAtPoint(x, y + 3, " ", "");
drawAtPoint(x, y + 4, " ", "");
drawAtPoint(x, y + 5, " ", "");
Sleep(500);
}
drawAtPoint(x, y + 0, " _____. .__ __.______. ______ ________._____", "");
drawAtPoint(x, y + 1, " / ____| /\\ | \\/ | ____| / __ \\ \\ / / ____| __ \\", "");
drawAtPoint(x, y + 2, "| | .__. / \\ | \\ / | |__. | | | \\ \\ / /| |__ | |__) |", "");
drawAtPoint(x, y + 3, "| | |_ | / /\\ \\ | |\\/| | __| | | | |\\ \\/ / | __| | _ /", "");
drawAtPoint(x, y + 4, "| |__| |/ ____ \\| | | | |____. | |__| | \\ / | |____| | \\ \\", "");
drawAtPoint(x, y + 5, " \\_____/_/ \\_\\_| |_|______| \\____/ \\/ |______|_| \\_\\", "");
Sleep(500);
str = "Your score is " + to_string(score);
drawAtPoint(x + 22, y + 8, str.c_str(), "");
drawAtPoint(x + 22, y + 10, "", "");
system("pause");
}
void Interface::setting()
{
string str = "mode con cols=" + to_string(WIDTH) + "lines=" + to_string(HEIGHT);
system(str.c_str());
system("cls");
boader();
short x = 24;
short y = 4;
drawAtPoint(x, y + 0, " _____.______._______._______._____._ ._. _____.", "");
drawAtPoint(x, y + 1, " / ____| .____|__. .__|__. .__|_. ._| \\ | |/ ____|", "");
drawAtPoint(x, y + 2, "| (___ | |__. | | | | | | | \\| | | __.", "");
drawAtPoint(x, y + 3, " \\___ \\| .__| | | | | | | | . ` | | |_ |", "");
drawAtPoint(x, y + 4, ".____) | |____. | | | | ._| |_| |\\ | |__| |", "");
drawAtPoint(x, y + 5, "|_____/|______| |_| |_| |_____|_| \\_|\\_____|", "");
drawAtPoint(46, y + 11, "Easy", "");
drawAtPoint(46, y + 13, "Normal", "");
drawAtPoint(46, y + 15, "Hard", "");
drawAtPoint(42, y + 11, "※", "");
int choice = 0;
int ch1, ch2;
while (1)
{
string str;
Sleep(50);
if (_kbhit())
{
ch1 = _getch();
switch (ch1)
{
case 224:
ch2 = _getch();
switch (ch2)
{
case 72:
drawAtPoint(42, y + 11 + choice * 2, " ", "");
if (choice > 0)
choice--;
drawAtPoint(42, y + 11 + choice * 2, "※", "");
break;
case 80:
drawAtPoint(42, y + 11 + choice * 2, " ", "");
if (choice < 2)
choice++;
drawAtPoint(42, y + 11 + choice * 2, "※", "");
break;
default:
break;
}
break;
case 13:
case 108:
switch (choice)
{
case 0:
mode = EASY;
break;
case 1:
mode = NORMAL;
break;
case 2:
mode = HARD;
default:
break;
}
return;
default:
//cout << ch1 << " ";
break;
}
}
}
}
int Interface::run()
{
int ch, ch2;
bool run = true;
boader();
map = {};
map.createWall();
list<Tank*> enemy;
list<Tank*> friendly;
int count = 15;
Tank test(20, 33, SELF);
friendly.push_back(&test);
drawAtPoint(104, 30, "◎", RED);
drawAtPoint(107, 30, "Add Life (up to 10)", "");
drawAtPoint(104, 31, "◎", YELLOW);
drawAtPoint(107, 31, "Add Power (up to 5)", "");
drawAtPoint(104, 32, "◎", BLUE);
drawAtPoint(107, 32, "Add Speed (up to 4)", "");
drawAtPoint(104, 33, "◎", GREEN);
drawAtPoint(107, 33, "Add Volume (up to 10)", "");
while (run)
{
if (!active)
{
gameover();
break;
}
Sleep(50);
random(enemy, count);
if (count <= 0)
{
win();
break;
}
buff();
if (_kbhit())
{
ch = _getch();
switch (ch)
{
case 224:
ch2 = _getch();
switch (ch2)
{
case 72:test.move(UP); break;
case 80:test.move(DOWN); break;
case 75:test.move(LEFT); break;
case 77:test.move(RIGHT); break;
default:
break;
}
break;
case 27:run = false; break;
case 32:
if (test.getLife())
test.addBullet();
break;
case 13:
case 108:
{
bool pause = true;
int temp;
while (pause)
{
if (_kbhit())
{
temp= _getch();
if (temp == 13 || temp == 108)
break;
}
}
}
break;
default:
//cout << ch << " ";
break;
}
}
if (test.getLife())
test.draw(true);
vector<Bullet*>::iterator iter = test.bullets.begin();
while (iter != test.bullets.end())
{
int res = (*iter)->run();
if (res == -1 || (*iter)->is_coll())
iter = test.bullets.erase(iter);
else
{
(*iter)->draw(true);
iter++;
}
}
status(friendly, enemy, count);
#ifdef DEBUG
TEST
#endif
}
return 0;
}
int Interface::menu()
{
menuface();
int choice = 0;
int ch1, ch2;
while (1)
{
string str;
Sleep(50);
if (_kbhit())
{
ch1 = _getch();
switch (ch1)
{
case 224:
ch2 = _getch();
switch (ch2)
{
case 72:
drawAtPoint(38, 15 + choice * 2, " ", "");
if (choice > 0)
choice--;
drawAtPoint(38, 15 + choice * 2, "※", "");
break;
case 80:
drawAtPoint(38, 15 + choice * 2, " ", "");
if (choice < 2)
choice++;
drawAtPoint(38, 15 + choice * 2, "※", "");
break;
default:
break;
}
break;
case 13:
case 108:
switch (choice)
{
case 0:
system("cls");
str = "mode con cols=" + to_string(WIDTH + 30) + "lines=" + to_string(HEIGHT);
system(str.c_str());
drawAtPoint(0, 0, "", "");
active = true;
SetConsoleTitle((LPCSTR)"SCORE: 0");
run();
system("cls");
menuface();
mode = EASY;
break;
case 1:
setting();
menuface();
choice = 0;
break;
case 2:return 0;
default:
break;
}
default:
//cout << ch1 << " ";
break;
}
}
}
return 0;
}
|
#ifndef _TNA_RENDERING_SCENE_H_
#define _TNA_RENDERING_SCENE_H_
#include "../math/matrix.h"
#include "../math/vector.h"
#include "../tools/colors.h"
#include "renderer.h"
#include "furious/common/dyn_array.h"
namespace tna
{
#define _TNA_RENDER_HANDLER_INVALID 0xffffffff
struct mesh_data_t;
enum class render_object_type_t
{
E_MESH,
};
struct material_desc_t
{
vector3_t m_color = TNA_COLOR_WHITE;
};
struct render_mesh_uniform_t
{
matrix4_t m_model_matrix;
material_desc_t m_material;
};
using render_handler_t = uint32_t;
struct render_header_t
{
uint32_t m_offset = 0;
render_object_type_t m_render_object_type = render_object_type_t::E_MESH;
bool m_active = false;
bool m_frustrum_visible = true;
};
struct rendering_scene_t
{
furious::DynArray<render_header_t> m_headers;
furious::DynArray<uint32_t> m_header_gaps;
render_mesh_uniform_t* m_uniforms = nullptr;
furious::DynArray<mesh_data_t*> m_meshes;
furious::DynArray<uint32_t> m_gaps;
matrix4_t m_view_mat = matrix4_t(1.0f);
matrix4_t m_proj_mat = matrix4_t(1.0f);
vector3_t m_clear_color = vector3_t(0.0f, 0.0f, 0.0f);
//size_t m_uniform_alignment;
};
void
rendering_scene_init(rendering_scene_t* scene);
void
rendering_scene_release(rendering_scene_t* scene);
render_handler_t
rendering_scene_create_object(rendering_scene_t* scene,
render_object_type_t o_type);
void
rendering_scene_destroy_object(rendering_scene_t* scene,
render_handler_t& handler);
void
rendering_scene_set_mesh(rendering_scene_t* scene, render_handler_t handler,
const char* mesh);
void
rendering_scene_set_material(rendering_scene_t* scene,
render_handler_t handler,
const material_desc_t& mat_desc);
void
rendering_scene_get_material(rendering_scene_t* scene,
render_handler_t handler,
material_desc_t* mat_desc);
void
rendering_scene_set_model_mat(rendering_scene_t* scene,
render_handler_t handler,
const matrix4_t& mat);
void
rendering_scene_set_frustrum_culling(rendering_scene_t* scene,
render_handler_t handler,
const matrix4_t& proj_matrix);
void
rendering_scene_set_view_matrix(rendering_scene_t* scene,
const matrix4_t& view_mat);
void
rendering_scene_set_proj_matrix(rendering_scene_t* scene,
const matrix4_t& projection_mat);
void
rendering_scene_set_clear_color(rendering_scene_t* scene,
const vector3_t& color);
} /* tna */
#endif /* ifndef _TNA_SCENE_H_ */
|
//В массиве размера N, заполненного случ.числами от 0 до 10, подсчитать количество элементов, встречающихся более одного раза.
#include <iostream>
#include <ctime>
using namespace std;
void initArray(int * arr, int size) {
int * end = arr + size;
for (arr; arr < end; arr++) {
*arr = rand() % 11;
}
}
void printArray(int * arr, int size) {
int * p = arr;
for (p; p < arr + size; p++) {
cout << *p << ' ';
}
cout << endl;
}
int countRepeatNums(int * arr, int size) {
int i = 0, j = 0;
int count = 0, amount = 0;
for (i = 0; i < size; i++) {
for (j = i + 1; j < size; j++) {
if (*(arr + i) == *(arr + j)) count++;
}
if (count == 1) {
amount++;
}
count = 0;
}
return amount;
}
int main()
{
setlocale(LC_ALL, "ru");
srand(time(NULL));
int N = 0;
int * arr = nullptr;
cout << "Введите количество элементов массива: ";
cin >> N;
cout << endl;
arr = new(nothrow) int[N];
if (arr != 0) {//Все таки правильнее проверять условие arr == 0!!!!
initArray(arr, N);
cout << "Массив: " << endl;
printArray(arr, N);
cout << endl;
cout << "Количество элементов, встречающихся более одного раза: " << countRepeatNums(arr, N) << endl;
}
else cout << "Ошибка выделения памяти" << endl;
delete[] arr;// и вот тут программа и срубится!!! Тяжело освободить память, если она не выделилась )))))
system("pause");
return 0;
}
|
/********************************************************/
/* fontout.c */
/* Output Raster Font and Bitmap Font with GLUT */
/********************************************************/
#include <GL/glut.h>
#include <GL/gl.h>
#include <GL/glu.h>
#include <stdarg.h>
#include <string.h>
#include <stdio.h>
void stroke_output(float x, float y, float z, float scale, char *format,...)
{
va_list args;
char buffer[200], *p;
va_start(args, format);
vsprintf_s(buffer, format, args);
va_end(args);
glPushMatrix();
glDisable(GL_LIGHTING);
glTranslatef(x, y, z);
glScalef(scale, scale, scale);
for (p = buffer; *p; p++)
glutStrokeCharacter(GLUT_STROKE_ROMAN, *p);
glEnable(GL_LIGHTING);
glPopMatrix();
}
void bitmap_output(float x, float y, float z, char *string, void *font)
{
int len, i;
glRasterPos3f(x, y, z);
len = (int) strlen(string);
for (i = 0; i < len; i++) {
glutBitmapCharacter(font, string[i]);
}
}
|
#include "AIBase.h"
#include "Manager.h"
#include "AILevel.h"
#include "Player.h"
AIBase::AIBase(unsigned short a_usX, unsigned short a_usY, unsigned int a_uiMaxArmy, unsigned short a_usOwner)
: m_usX(a_usX), m_usY(a_usY),m_usOwner(a_usOwner)
{
m_uiMaxArmyStrength = a_uiMaxArmy;
m_uiArmyStrength = m_uiMaxArmyStrength / 10;
//sets level display to white if unowned or to team colour if owned
Manager::Instance()->GetLevel()->SetCharacter(m_usX, m_usY, 178, (m_usOwner == NOPLAYER) ? 15 : Manager::Instance()->GetPlayer(m_usOwner)->GetColour());
}
AIBase::~AIBase()
{
}
void AIBase::Send(unsigned int a_uiTroopsToSend, unsigned short a_usX, unsigned short a_usY)
{
m_uiArmyStrength -= a_uiTroopsToSend;
//send a army when armies have been created
}
void AIBase::Receive(unsigned int a_uiTroopsSent, unsigned short a_usOwner)
{
if (a_usOwner == m_usOwner)
{
AddTroops(a_uiTroopsSent);
}
else
{
if (a_uiTroopsSent > m_uiArmyStrength)
{
m_usOwner = a_usOwner;
m_uiArmyStrength = min(m_uiMaxArmyStrength, a_uiTroopsSent - m_uiArmyStrength);
Manager::Instance()->GetLevel()->SetCharacter(m_usX, m_usY, 178, (m_usOwner == NOPLAYER) ? 15 : Manager::Instance()->GetPlayer(m_usOwner)->GetColour());
}
else
{
m_uiArmyStrength -= a_uiTroopsSent;
}
}
}
void AIBase::BeginTurn()
{
if (m_usOwner != NOPLAYER)//owned, replenish army
AddTroops(m_uiMaxArmyStrength / 10);
}
void AIBase::AddTroops(unsigned int a_uiTroopCount)
{
m_uiArmyStrength += a_uiTroopCount;
if (m_uiArmyStrength > m_uiMaxArmyStrength)
m_uiArmyStrength = m_uiMaxArmyStrength;
}
|
#ifndef _HS_SFM_SELF_CALIBRATION_PROJECTIVE_SYNTHETIC_GENERATOR_HPP_
#define _HS_SFM_SELF_CALIBRATION_PROJECTIVE_SYNTHETIC_GENERATOR_HPP_
#include "hs_math/linear_algebra/eigen_macro.hpp"
#include "hs_sfm/synthetic/flight_generator.hpp"
namespace hs
{
namespace sfm
{
namespace sc
{
template <typename _Scalar, typename _ImageDimension>
class ProjectiveSyntheticGenrator
{
public:
typedef _Scalar Scalar;
typedef _ImageDimension ImageDimension;
typedef int Err;
typedef hs::sfm::synthetic::FlightGenerator<Scalar, ImageDimension>
FlightGenerator;
typedef typename FlightGenerator::ExtrinsicParams ExtrinsicParams;
typedef typename FlightGenerator::ExtrinsicParamsContainer
ExtrinsicParamsContainer;
typedef typename FlightGenerator::Image Image;
typedef typename FlightGenerator::ImageContainer ImageContainer;
typedef typename FlightGenerator::Point3D Point3D;
typedef typename FlightGenerator::Point3DContainer Point3DContainer;
typedef EIGEN_MATRIX(Scalar, 3, 4) PMatrix;
typedef EIGEN_STD_VECTOR(PMatrix) PMatrixContainer;
};
}
}
}
#endif
|
#include"LinkList.h"
#include<iostream>
using namespace std;
class myList : public LinkList
{
public:
myList()
{
head = nullptr;
tail = nullptr;
Curr_size = 0;
}
void add_node_tail(int data)
{
node* temp = new node();
temp->data = data;
temp->next = nullptr;
if (head == nullptr)
{
head = temp;
tail = temp;
}
else
{
tail->next = temp;
tail = temp;
}
Curr_size++;
}
void add_node_head(int data)
{
node* temp = new node();
temp->data = data;
temp->next = nullptr;
if (head == nullptr)
{
head = temp;
tail = temp;
}
else
{
temp->next = head;
head = temp;
}
Curr_size++;
}
void remove_from_tail()
{
if (!Is_empty())
{
node* temp = head;
while (temp->next->next != nullptr)
{
temp = temp->next;
}
temp->next = nullptr;
tail = temp;
Curr_size--;
}
else
{
cout << "List is empty" << endl;
}
}
void remove_from_head()
{
if (!Is_empty())
{
node* temp = head;
head = head->next;
temp->next = nullptr;
Curr_size--;
}
else
{
cout << "List is empty" << endl;
}
}
bool Is_empty()
{
bool flag = 0;
if (Curr_size == 0)
{
flag = 1;
}
return flag;
}
int front()
{
node* temp = head;
return temp->data;
}
int back()
{
node* temp = tail;
return temp->data;
}
void display()
{
if (!Is_empty())
{
cout << "displaying all the nodes" << endl;
node* temp = head;
cout << temp->data << endl;
while (temp->next != nullptr)
{
temp = temp->next;
cout << temp->data << endl;
}
}
else
{
cout << "List is empty" << endl;
}
}
int Search(int num)
{
int count = 0;
if (!Is_empty())
{
node* temp = head;
for (int i = 0; i < Curr_size; i++)
{
if (temp->data == num)
{
count++;
}
temp = temp->next;
}
}
else
{
cout << "List is empty" << endl;
}
return count;
}
void duplicate()
{
node* temp = head;
node* temp1;
while (temp != nullptr && temp->next != nullptr)
{
temp1 = temp;
while (temp1->next != nullptr)
{
if (temp->data == temp1->next->data)
{
temp1->next = temp1->next->next;
}
else
{
temp1 = temp1->next;
}
}
temp = temp->next;
}
}
};
|
#include<stdio.h>
#include<malloc.h>
struct node{
int data;
struct node *left;
struct node *right;
};
int isBST(struct node *root){
if(root==NULL)
return 1;
if(root->left!=NULL && root->left->data > root->data)
return 0;
if(root->right!=NULL && root->right->data < root->data)
return 0;
if(!isBST(root->left) || !isBST(root->right))
return 0;
return 1;
}
struct node *newNode(int data){
struct node *node=(struct node *)malloc(sizeof(struct node ));
node->data=data;
node->right=NULL;
node->left=NULL;
return node;
}
int main(void){
struct node *root=newNode(20);
root->left=newNode(15);
root->right=newNode(22);
root->left->left=newNode(12);
root->left->right=newNode(21);
printf("%d",isBST(root));
return 0;
}
|
#ifndef PARTICULA_CHISPA_H
#define PARTICULA_CHISPA_H
#include <herramientas/vector_2d/vector_2d.h>
#include <generador_numeros.h>
#include "particula_movil_base.h"
namespace App_Juego_ObjetoJuego
{
class Particula_chispa:
public Particula_movil_base
{
//////////////////
//Interface pública...
public:
Particula_chispa(float x, float y, float tv, const DLibH::Vector_2d& v);
//////////////
// Implementación de Representable_I
public:
virtual unsigned int obtener_ciclos_representable()const;
virtual unsigned short int obtener_profundidad_ordenacion()const;
virtual void transformar_bloque(App_Graficos::Bloque_transformacion_representable &b)const;
/////////////////
//Internas.
private:
int cr, cg, cb, ca;
};
}
#endif
|
#include "stdafx.h"
#include "UOneThingWorld.h"
#include "CBox.h"
#include "CDirectionalLight.h"
#include "CCharacter.h"
IMPLEMENT_CLASS(UOneThingWorld);
UOneThingWorld::UOneThingWorld()
{
}
UOneThingWorld::~UOneThingWorld()
{
}
bool UOneThingWorld::DestroyWorld()
{
__super::DestroyWorld();
return true;
}
bool UOneThingWorld::Tick(DWORD dTime)
{
__super::Tick(dTime);
return true;
}
|
#pragma once
#include <curand.h>
#include <random>
namespace transprecision_floating_point
{
struct random_engine
{
template<typename Distribution>
static void generate(float* a, size_t size, Distribution distribution);
static void set_seed(size_t seed);
static void destroy();
private:
static void init();
static bool is_rng_init_;
static curandGenerator_t rng_;
};
bool random_engine::is_rng_init_ = false;
curandGenerator_t random_engine::rng_;
template <typename Distribution>
void random_engine::generate(float* a, size_t size, Distribution distribution)
{
init();
CHECK_CURAND_ERROR(distribution(random_engine::rng_, a, size));
}
inline void random_engine::set_seed(size_t seed)
{
init();
CHECK_CURAND_ERROR(curandSetPseudoRandomGeneratorSeed(random_engine::rng_, seed));
}
inline void random_engine::destroy()
{
CHECK_CURAND_ERROR(curandDestroyGenerator(rng_));
}
inline void random_engine::init()
{
if(random_engine::is_rng_init_) return;
CHECK_CURAND_ERROR(curandCreateGenerator(&random_engine::rng_, CURAND_RNG_PSEUDO_DEFAULT));
CHECK_CURAND_ERROR(curandSetPseudoRandomGeneratorSeed(random_engine::rng_, std::random_device{}()));
random_engine::is_rng_init_ = true;
}
struct uniform_distribution
{
curandStatus_t operator()(curandGenerator_t rng, float* a, size_t size) const
{
return curandGenerateUniform(rng, a, size);
}
};
struct normal_distribution
{
normal_distribution(float mean = 0, float stddev = 1) : mean_(mean), stddev_(stddev) {}
curandStatus_t operator()(curandGenerator_t rng, float* a, size_t size) const
{
return curandGenerateNormal(rng, a, size % 2 == 0 ? size : size + 1, mean_, stddev_);
}
private:
float mean_;
float stddev_;
};
struct normal_scaled_distribution
{
normal_scaled_distribution(float inputs) : inputs_(inputs) {}
curandStatus_t operator()(curandGenerator_t rng, float* a, size_t size) const
{
return curandGenerateNormal(rng, a, size % 2 == 0 ? size : size + 1, 0, sqrtf(2 / inputs_));
}
private:
float inputs_;
};
struct xavier_distribution
{
xavier_distribution(float inputs, float outputs) : inputs_(inputs), outputs_(outputs) {}
curandStatus_t operator()(curandGenerator_t rng, float* a, size_t size) const
{
return curandGenerateNormal(rng, a, size % 2 == 0 ? size : size + 1, 0, sqrtf(1/(inputs_*outputs_)));
}
private:
float inputs_;
float outputs_;
};
}
|
/*
BAEKJOON
17135. 캐슬 디펜스
2. DFS (궁수 선택) + DP (적 선택)
적의 위치를 모두 벡터에 미리 저장해두고 각 궁수와의 거리를 모두 체크했다.
D 이내 거리의 적들은 kill_enemy_temp 벡터에 저장한 후 sort하였다.
적들이 한 칸씩 내려올 때마다 적의 위치를 다시 찾아야해서 1번 방법보다 훨씬 오래걸린다.
**놓쳤던 부분**
궁수가 N+1 행에만 위치한다는 말인데, N+1에도 존재할 수 있다고 이해했다.
문제가 짧지만, 문제를 잘 읽읍시다..^^
**주의할 부분**
**같은 적이 여러 궁수에게 공격당할 수 있다.**
각 궁수가 적을 찾았을 때, 바로 죽이면 안된다. 죽일 수 있는 적을 찾으면 먼저 kill_enemy 배열에 적 위치를 저장해 두었다.
그리고 모든 궁수가 적을 찾은 후에 아래와 같이 한 명씩 죽이되, 이미 죽였던 적은 카운팅하지 않아야 한다.
*/
#include <iostream>
#include <vector>
#include <algorithm>
#define MAX 16
using namespace std;
int N, M, D, Answer = 0;
vector<pair<int, int>> goongsu; // 선택된 궁수
vector<pair<int, int>> enemy; // 존재하는 적
pair<int, int> kill_enemy[3]; // 죽일 선택된 적
int map[MAX][MAX];
int c_map[MAX][MAX];
int sr = 0;
void input()
{
bool find = false;
cin >> N >> M >> D;
for(int i = 1; i <= N; i++)
{
for(int j = 1; j <= M; j++)
{
cin >> map[i][j];
if(map[i][j] == 1 && find == false)
{
sr = i; find = true;
}
}
}
}
int distance(int r, int c, int rr, int cc)
{
return abs(r - rr) + abs(c - cc);
}
void copy_map()
{
for(int i = 1; i <= N; i++)
{
for(int j = 1; j <= M; j++)
{
c_map[i][j] = map[i][j];
}
}
}
void find_enemy()
{
for(int i = 1; i <= N; i++)
{
for(int j = 1; j <= M; j++)
{
if(c_map[i][j] == 1)
{
enemy.push_back(make_pair(i, j));
}
}
}
}
bool standard(pair<int, pair<int, int>> e1, pair<int, pair<int, int>> e2)
{
if(e1.first == e2.first)
{
return e1.second.second < e2.second.second;
}
else
{
return e1.first < e2.first;
}
}
int catch_enemy()
{
int kill = 0;
for(int g = 0; g < goongsu.size(); g++)
{
vector<pair<int, pair<int, int>>> kill_enemy_temp;
for(int i = 0; i < enemy.size(); i++)
{
int dist = distance(goongsu[g].first, goongsu[g].second, enemy[i].first, enemy[i].second);
if(dist <= D)
{
kill_enemy_temp.push_back(make_pair(dist, enemy[i]));
}
}
if(kill_enemy_temp.size() == 1)
{
kill_enemy[g] = kill_enemy_temp.front().second;
}
else if(kill_enemy_temp.size() > 1)
{
sort(kill_enemy_temp.begin(), kill_enemy_temp.end(), standard);
kill_enemy[g] = kill_enemy_temp.front().second;
}
else
{
kill_enemy[g] = make_pair(-1, -1);
}
}
for(int i = 0; i < goongsu.size(); i++)
{
if(kill_enemy[i].first == -1 && kill_enemy[i].second == -1) continue;
if(c_map[kill_enemy[i].first][kill_enemy[i].second] == 1)
{
c_map[kill_enemy[i].first][kill_enemy[i].second] = 0;
kill += 1;
}
}
return kill;
}
void move_enemy()
{
for(int i = N; i >= 1; i--)
{
for(int j = 1; j <= M; j++)
{
c_map[i][j] = c_map[i-1][j];
}
}
}
void start_game()
{
int sum = 0;
copy_map();
for(int t = 1; t <= N - sr + 1; t++)
{
enemy.clear();
find_enemy();
sum += catch_enemy();
if(t == N - sr + 1)
{
Answer = max(Answer, sum);
return;
}
move_enemy();
}
}
void DFS(int cnt, int c)
{
if(cnt == 3)
{
start_game();
return;
}
if(c == M+1)
{
return;
}
goongsu.push_back(make_pair(N+1, c));
DFS(cnt + 1, c + 1);
goongsu.pop_back();
DFS(cnt, c + 1);
}
void solve()
{
DFS(0, 1);
cout << Answer;
}
int main()
{
input();
solve();
return 0;
}
|
#include <fstream>
#include <iostream>
#include <string>
#include <map>
#include <vector>
#include <fstream>
#include <algorithm>
#include <string.h>
using namespace std;
int n, k;
const int big = 26 * 26 * 26 *10;
vector<int> v[big];
int main()
{
//freopen("a.txt", "r", stdin);
//fstream cin("a.txt");
scanf("%d%d", &n, &k);
int a, b;
while(k--)
{
scanf("%d%d", &a, &b);
for (int i = 0; i < b; ++i)
{
char *tmp = new char[5];
scanf("%s", tmp);
int hashIndex = (tmp[0] - 'A') * 26 * 26 * 10 + (tmp[1] - 'A') * 26 * 10 + (tmp[2] - 'A') * 10 + (tmp[3] - '0');
v[hashIndex].push_back(a);
}
}
std::vector<char *> query;
for (int i = 0; i < n; ++i)
{
char *tmp = new char[5];
scanf("%s", tmp);
query.push_back(tmp);
}
for (int i = 0; i < query.size(); ++i)
{
char *tmp = query[i];
int hashIndex = (tmp[0] - 'A') * 26 * 26 * 10 + (tmp[1] - 'A') * 26 * 10 + (tmp[2] - 'A') * 10 + (tmp[3] - '0');
printf("%s", query[i]);
if(v[hashIndex].size() == 0)
printf(" 0");
else
printf(" %d", v[hashIndex].size());
sort(v[hashIndex].begin(), v[hashIndex].end());
for (int j = 0; j < v[hashIndex].size(); ++j)
printf(" %d", v[hashIndex][j]);
printf("\n");
}
}
|
#include "Box2dWorld.h"
#include <cstring>
using namespace std;
#include "SnagForestWorld.h"
GameEntry g_gameEntries[] =
{
{"SnagForestWorld", SnagForestWorld::Create},
// {NULL, NULL}
};
int g_totalEntries = sizeof(g_gameEntries) / sizeof(g_gameEntries[0]);
|
/*
* sparql.cpp
* xSWO
*
* Created by jim on 9/9/08.
* Copyright 2008 Glamdring Inc. Enterprises. All rights reserved.
*
*/
#include "sparql.h"
////////////////////////////////////////////////////////////////////////////
//
// Main program
//
////////////////////////////////////////////////////////////////////////////
int test_sparql() {
#if 1
sparql_parser sparql;
#if 1
std::string const str = " BASE <BtC> PREFIX r8DNA: <b%k> PREFIX EjBBa: <3)M> PREFIX YX6xO: <t~r> SELECT DISTINCT ?9iVy $9dcp FROM <-Rv> FROM NAMED ioANU:EAj3M FROM <0ZQ> WHERE { ?aJKL $z5l6 TqZ.q: , ( ?xJqk [ a 'P\\\\,' @ho-jj-wV-Zi , ( ) , $KGBc ; <=$d> [ a 21 , ( ?eZ6t [ $8LsO true , ( ) , ?EESP ; ; a [ z18px:N8rKT _:fdQ0P , ( $ggWm [ a ( ) , ( ) , ?86TQ ] [ $FZ8C <a> , ( ?ANtz ) , [ a \"g\\r4\" ^^ yFSOt: , ( $Qvc3 [ </dP> +13 ; ; a ( ) , ?fXeV , [ $e6C0 false , ( ?gInH [ a [ ] ; ] ) , ( $fsyx [ ZP5G2:TVKWV ( ) , ( ) , ?L5E9 ; a [ $SC1y <umG> , ( ?yghH [ a ''''R'\\\"'P''' @QD-nc-GB-YN , ( ) , $UXuw ; ; jOurI: [ a -97 , ( ?2t_N [ $JE77 true , ( ) , ?pfDb ] [ a _:MeHdb , ( $Uuoe ) , [ <01a> ( ) , ( ?aYFc [ a Z22h3:29MC3 ; ; $eIkV ( ) , ?1Vyu , [ a \"\"\"\"t\"\"\" ] ] ) ] ] ) ] ] ) ] ] ) ] ] ) ] ] ) ] ] ) ] ] ) } ";
#else
std::string const str = " BASE <0l5> PREFIX fzmrW: <p3?> PREFIX nh.W0: <tnB> PREFIX H6acq: <gsL> SELECT DISTINCT ?Rwse $3jSw FROM <kQe> FROM NAMED b950C:qnB2z FROM <-#z> WHERE { ?EanT $btmG LdyeK: , ( ?4jKt [ a '\fG' @HU-8b-uY-pX , ( ) , $UJsD ; <o,,> [ a 91 , ( ?uWj_ [ $cCLQ true , ( ) , ?IvKM ; ; a [ nI3tL:s3LHC _:vxakc , ( $tLHf [ a ( ) , ( ) , ?6iTg ] [ $pRGx <zuE> , ( ?jmGQ ) , [ a \"g\" ] ] ) ] ] ) ] ] ) } ";
#endif
parse_info<> info = parse(str.c_str(), sparql, space_p);
std::cout << (info.full ? '+' : '-') << std::endl;
#else
std::cout << "/////////////////////////////////////////////////////////\n\n"
<< " Expression parser...\n\n"
<< "/////////////////////////////////////////////////////////\n\n"
<< "Type an expression...or [q or Q] to quit\n\n";
sparql_parser sparql;
std::string str;
while (std::getline(std::cin, str))
{
parse_info<> info = parse(str.c_str(), sparql, space_p);
std::cout << (info.full ? '+' : '-');
}
std::cout << "Bye... :-)\n" << std::endl;
#endif
return 0;
}
|
#ifndef GAMEFRAGMENT_H
#define GAMEFRAGMENT_H
#include "basefragment.h"
#include "playtable.h"
#include "card.h"
#include "dealerlogo.h"
#include "turnspark.h"
#include "winlabel.h"
#include "client_impl.h"
#include "otherplayer.h"
#include <QVector>
#include <QWidget>
#include <QPushButton>
#include <QLabel>
#include <QLineEdit>
#include <QSlider>
class GameFragment: public BaseFragment {
Q_OBJECT
public:
GameFragment();
~GameFragment();
public slots: // все ради многопоточки
void DeletePlayer(size_t player_id);
void DrawPlayer(size_t player_id, std::string nickname, size_t total_money);
void SetMinBet(int minbet);
void SetMaxBet(int maxbet);
void EndGame(bool is_admin);
void FlipTableCards();
void DeleteAllCardsFromTable();
void AddCardToTable(size_t value, size_t suit, bool upsided);
void FlipAllCards();
void DeleteAllPlayersCards();
void ShowActions();
void BlockActions();
void UnBlockActions();
void ShowStart();
void MakeDealer(size_t player_id);
void DisplayWinner(size_t player_id);
void CurrentTurn(size_t player_id);
void GiveCards(size_t player_id, size_t value1, size_t suit1, size_t value2, size_t suit2);
void FlipCards(size_t player_id);
void SetBet(size_t player_id, size_t bet);
void SetFold(size_t player_id);
void SetCall(size_t player_id);
void SetRaise(size_t player_id, size_t bet);
void SetCheck(size_t player_id);
void SetMoney(size_t player_id, size_t money);
void ClearStatus(size_t player_id);
void AvaliableActions(std::vector<bool> buttons);
void SetMoneyInBank(size_t money);
void DeleteWinnerDisplay();
void ClearBank();
private slots:
void setval();
void onBetPressed();
void onRaisePressed();
void onFoldPressed();
void onCheckPressed();
void onCallPressed();
void onLeavePressed();
void onSettingsPressed();
void onStartPressed();
void onInfoPressed();
private:
void RedrawPlayer(OtherPlayer* player);
void resizeEvent(QResizeEvent *event);
int mMinbet;
int mMaxbet;
bool is_active;
QVector<OtherPlayer*> mOtherPlayers;
PlayTable *mPlayTable;
DealerLogo *mDealerLogo;
Chips *mChips;
TurnSpark *mTurnIndicator;
QVector <Card*> CardOnTable;
QSlider *BetSlider;
QLineEdit *BetValue;
WinLabel *mWinLabel;
QVector<QPushButton*> ActionButtons;
QPushButton *CallButton;
QPushButton *BetButton;
QPushButton *RaiseButton;
QPushButton *FoldButton;
QPushButton *CheckButton;
QPushButton *LeaveButton;
QPushButton *ShowRoomInfo;
QPushButton *StartGameButton;
QPushButton *SettingsButton;
};
#endif // GAMEFRAGMENT_H
|
int Solution::removeDuplicates(vector<int> &vec) {
unordered_set<int> s;
for (int i : vec)
s.insert(i);
vec.assign( s.begin(), s.end() );
sort( vec.begin(), vec.end() );
return vec.size();
}
|
#include "ImageSaver.hh"
void ImageSaver::Compute()
{
if (!in_texture->GetData().copyToImage().saveToFile(in_path->GetData()))
{
std::string error_msg = "Failed to save image file: " + in_path->GetData();
logger.LogE() << error_msg;
throw error_msg;
}
}
ImageSaver::ImageSaver(std::string _name)
: Block(_name)
{
in_texture = new Input<sf::Texture>(this);
in_path = new Input<std::string>(this);
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.