blob_id
stringlengths 40
40
| directory_id
stringlengths 40
40
| path
stringlengths 3
264
| content_id
stringlengths 40
40
| detected_licenses
listlengths 0
85
| license_type
stringclasses 2
values | repo_name
stringlengths 5
140
| snapshot_id
stringlengths 40
40
| revision_id
stringlengths 40
40
| branch_name
stringclasses 986
values | visit_date
timestamp[us] | revision_date
timestamp[us] | committer_date
timestamp[us] | github_id
int64 3.89k
681M
⌀ | star_events_count
int64 0
209k
| fork_events_count
int64 0
110k
| gha_license_id
stringclasses 23
values | gha_event_created_at
timestamp[us] | gha_created_at
timestamp[us] | gha_language
stringclasses 145
values | src_encoding
stringclasses 34
values | language
stringclasses 1
value | is_vendor
bool 1
class | is_generated
bool 2
classes | length_bytes
int64 3
10.4M
| extension
stringclasses 122
values | content
stringlengths 3
10.4M
| authors
listlengths 1
1
| author_id
stringlengths 0
158
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
2a3c57192b3c099c76cb0dfdf1ad2a60dbeb7d43
|
485496646d476cab4106c74ded51ae82f2be3613
|
/JunQi_Zmr/JunQia/webthing.h
|
0fb2aa22601c7b12404034b281ffdda94b3a822c
|
[] |
no_license
|
DrustZ/JunQi
|
3e240c3c45e5f1ddeabd3c791ddc7fef3dc00539
|
7b2a0214e141f352652c920fa1144deb67f5717b
|
refs/heads/master
| 2020-05-26T18:00:00.346031
| 2014-09-14T15:47:03
| 2014-09-14T15:47:03
| 24,024,686
| 2
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,394
|
h
|
#ifndef WEBTHING_H
#define WEBTHING_H
#include <QObject>
#include <QVector>
#include "structs.h"
#include "windows.h"
#include "receivethread.h"
#include "sendthread.h"
class Webthing:public QObject
{
Q_OBJECT
public:
Webthing(QObject *parent = 0);
~Webthing();
void startserver(QWidget*);
void startclient(QWidget*);
void vtos();
void stov();
void swapnum(int&a, int&b);
bool sendprofile(int mode);
Receivethread *rthread;
signals:
void updateinfo(QVector<qizi>);//更新信息
void updateinitinfo(QVector<qizi>);
void kaishi();
void displayPhoto();
void displayName(QString );
void shouldrestart();
void connect_succeeded();
public slots:
void sendinfo(int mode, QVector<qizi> fangkuai);//发送信息
void getinfo(char*);
void getinitinfo(char*);
void shula();
void ye();
void yinglehaha();
void renjiaqiuhele();
void renjiatongyile();
void renjiabutongyi();
void renshulea();
void setSocket(SOCKET so);
void closed();
void started();
void shezhitouxiang(QString);
void shezhinicheng(QString);
void getupian(char* tupian);
void getname(char* name);
private:
QVector<qizi> gezi;
qizi gezizu[60];
SOCKET CSocket,Ssocket;
bool server,QH;
QWidget *qipanwidget;
QString myphotofiledir,myName,duifangname;
};
#endif // WEBTHING_H
|
[
"z1m6r3@gmail.com"
] |
z1m6r3@gmail.com
|
da71a80dd4718fa0838d195c728fb667eeff1222
|
ee32d46014c1f2fc5ec7bb833233c24237270933
|
/0149A/main.cpp
|
1acc3faf51d4caaac68ba6318169aaf91cd0cc41
|
[] |
no_license
|
boxnos/codeforces
|
42b48367d222cc58c2bc0f408469fc6a2732cec7
|
fbc358fe7ddf48d48bda29e75ef3264f9ed19852
|
refs/heads/master
| 2023-08-27T21:18:44.163264
| 2023-08-26T18:06:59
| 2023-08-26T18:06:59
| 192,764,064
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,503
|
cpp
|
#include <cstdio>
#include <utility>
#include <cctype>
#include <array>
#include <algorithm>
using namespace std;
#ifdef __linux
#define _U(s) s##_unlocked
#else
#define _U(s) _##s##_nolock
#define _CRT_DISABLE_PERFCRIT_LOCKS
#endif
#define gcu _U(getchar)
#define pcu _U(putchar)
#define _DEF(r, n, ...) inline r n(__VA_ARGS__) noexcept
#define _T template <typename T>
#define _HT template <typename H,typename... T>
#define _I inline
#define _OP(t) _I operator t()
struct _in {
#ifdef _GLIBCXX_STRING
_OP(string){string s;for(char c;c=gcu(),c!=' '&&c!='\n';)s+=c;return s;}
//_OP(string){string s;char c;while(isspace(c = gcu()));do{s+=c;}while(c=gcu(),c!=' '&&c!='\n'&&c!=EOF);return s;}
#define _S
#endif
_OP(char){char c=gcu();gcu();return c;}
_OP(double){double d; scanf("%lf",&d); gcu();return d;}
_T _OP(T){T n{},m{1},c;while(isspace(c=gcu()));if(c=='-')m=-1,c=gcu();do{n=10*n+(c-'0'),c=gcu();}while(c>='0'&&c<='9');return m*n;}
} in;
#define _SCAN(...) _DEF(bool,scan,__VA_ARGS__)
#ifdef _S
_SCAN(string &o) {int c{gcu()};if(c==EOF)return false;else{ungetc(c,stdin);string t=move(in);o=t;return true;}}
#endif
_T _SCAN(T &o) {int c{gcu()};return c==EOF?false:(ungetc(c,stdin),o=in,true);}
_HT _SCAN(H &h,T&&... t){return scan(h)&&scan(t...);}
#define _OUT(...) _DEF(void,out,__VA_ARGS__)
#define _OUTL(...) _DEF(void,outl,__VA_ARGS__)
_OUT(bool b){pcu('0'+b);}
_OUT(const char *s){while(*s)pcu(*s++);}
_OUT(char c){pcu(c);}
#ifdef _S
_OUT(string &s){for(char c:s)pcu(c);}
#endif
_T _OUT(T n){static char b[20];char *p=b;T m=n<0?pcu('-'),-1:1;
if(!n)*p++='0';else while(n)*p++=(char)(n%10*m+'0'),n/=10;while(p!=b)pcu(*--p);}
_OUTL(){out('\n');}
#ifdef _GLIBCXX_VECTOR
_T _OUT(vector<T> &v){for(T &x:v)out(&x == &v[0]?"":" "),out(x);}
#endif
_HT _OUT(H &&h, T... t){out(h);out(t...);}
template <typename... T> _OUTL(T... t){out(t...);outl();}
#define dbg(...) fprintf(stderr,__VA_ARGS__)
struct range{
int e,b=0,s=1;range(int b,int e,int s):e(e),b(b),s(s){} range(int b,int e): e(e), b(b){} range(int e):e(e){}
struct it{int v,s; it(int v,int s):v(v),s(s){} operator int()const{return v;} _I operator int&(){return v;}int operator*()const{return v;}
_I it& operator++(){v+=s;return *this;} }; it begin(){return {b,s};} it end(){return {e,s};}};
#define times(i,n) for(int i=n;i;i--)
int main() {
int k {in}, r {};
array<int, 12> a;
for (int &i: a)
i = in;
sort(rbegin(a), rend(a));
for (; r < 12 && k > 0; k -= a[r++])
;
outl(k > 0 ? -1 : r);
}
/* vim: set ts=4 noet: */
|
[
"boxnos@yahoo.com"
] |
boxnos@yahoo.com
|
86e939cecbb1fec89cf05b1288a6c92bfad50a2a
|
52507f7928ba44b7266eddf0f1a9bf6fae7322a4
|
/SDK/BP_TextInputDialog_classes.h
|
4e1200925016ac4dd20a23c2c74d2086ed0a7b18
|
[] |
no_license
|
LuaFan2/mordhau-sdk
|
7268c9c65745b7af511429cfd3bf16aa109bc20c
|
ab10ad70bc80512e51a0319c2f9b5effddd47249
|
refs/heads/master
| 2022-11-30T08:14:30.825803
| 2020-08-13T16:31:27
| 2020-08-13T16:31:27
| 287,329,560
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 5,550
|
h
|
#pragma once
// Name: Mordhau, Version: 1.0.0
#ifdef _MSC_VER
#pragma pack(push, 0x8)
#endif
namespace SDK
{
//---------------------------------------------------------------------------
// Classes
//---------------------------------------------------------------------------
// WidgetBlueprintGeneratedClass BP_TextInputDialog.BP_TextInputDialog_C
// 0x0080 (0x0288 - 0x0208)
class UBP_TextInputDialog_C : public UMordhauDialog
{
public:
struct FPointerToUberGraphFrame UberGraphFrame; // 0x0208(0x0008) (Transient, DuplicateTransient)
class UBP_TwoButtonDialog_C* BP_TwoButtonDialog; // 0x0210(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, RepNotify, Interp, NonTransactional, EditorOnly, NoDestructor, AutoWeak, ContainsInstancedReference, AssetRegistrySearchable, SimpleDisplay, AdvancedDisplay, Protected, BlueprintCallable, BlueprintAuthorityOnly, TextExportTransient, NonPIEDuplicateTransient, ExposeOnSpawn, PersistentInstance, UObjectWrapper, HasGetValueTypeHash, NativeAccessSpecifierPublic, NativeAccessSpecifierProtected, NativeAccessSpecifierPrivate)
class UEditableTextBox* NormalTextBox; // 0x0218(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, RepNotify, Interp, NonTransactional, EditorOnly, NoDestructor, AutoWeak, ContainsInstancedReference, AssetRegistrySearchable, SimpleDisplay, AdvancedDisplay, Protected, BlueprintCallable, BlueprintAuthorityOnly, TextExportTransient, NonPIEDuplicateTransient, ExposeOnSpawn, PersistentInstance, UObjectWrapper, HasGetValueTypeHash, NativeAccessSpecifierPublic, NativeAccessSpecifierProtected, NativeAccessSpecifierPrivate)
class UEditableTextBox* PasswordTextBox; // 0x0220(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, RepNotify, Interp, NonTransactional, EditorOnly, NoDestructor, AutoWeak, ContainsInstancedReference, AssetRegistrySearchable, SimpleDisplay, AdvancedDisplay, Protected, BlueprintCallable, BlueprintAuthorityOnly, TextExportTransient, NonPIEDuplicateTransient, ExposeOnSpawn, PersistentInstance, UObjectWrapper, HasGetValueTypeHash, NativeAccessSpecifierPublic, NativeAccessSpecifierProtected, NativeAccessSpecifierPrivate)
struct FText HintText; // 0x0228(0x0018) (Edit, BlueprintVisible)
struct FScriptMulticastDelegate LeftButtonClicked; // 0x0240(0x0010) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, BlueprintAssignable)
struct FScriptMulticastDelegate RightButtonClicked; // 0x0250(0x0010) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, BlueprintAssignable)
bool bIsPassword; // 0x0260(0x0001) (Edit, BlueprintVisible, ZeroConstructor, IsPlainOldData)
unsigned char UnknownData00[0x7]; // 0x0261(0x0007) MISSED OFFSET
struct FScriptMulticastDelegate TextCommitted; // 0x0268(0x0010) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, BlueprintAssignable)
struct FScriptMulticastDelegate TextChanged; // 0x0278(0x0010) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, BlueprintAssignable)
static UClass* StaticClass()
{
static auto ptr = UObject::FindClass("WidgetBlueprintGeneratedClass BP_TextInputDialog.BP_TextInputDialog_C");
return ptr;
}
void SetEnteredText(const struct FText& EnteredText);
void GetEnteredText(struct FText* Text);
void SetTitleText(const struct FText& Title);
void SetRightButtonText(const struct FText& Text);
void SetLeftButtonText(const struct FText& Text);
struct FText GetHintText();
void BndEvt__PasswordTextbox_K2Node_ComponentBoundEvent_23_OnEditableTextBoxCommittedEvent__DelegateSignature(const struct FText& Text, TEnumAsByte<ETextCommit> CommitMethod);
void BndEvt__BP_TwoButtonDialog_K2Node_ComponentBoundEvent_183_LeftButtonClicked__DelegateSignature();
void BndEvt__BP_TwoButtonDialog_K2Node_ComponentBoundEvent_187_RightButtonClicked__DelegateSignature();
void Show();
void Hide();
void BndEvt__PasswordTextBox_K2Node_ComponentBoundEvent_7_OnEditableTextBoxCommittedEvent__DelegateSignature(const struct FText& Text, TEnumAsByte<ETextCommit> CommitMethod);
void BndEvt__NormalTextBox_K2Node_ComponentBoundEvent_19_OnEditableTextBoxChangedEvent__DelegateSignature(const struct FText& Text);
void BndEvt__PasswordTextBox_K2Node_ComponentBoundEvent_20_OnEditableTextBoxChangedEvent__DelegateSignature(const struct FText& Text);
void ExecuteUbergraph_BP_TextInputDialog(int EntryPoint);
void TextChanged__DelegateSignature(const struct FText& Text);
void TextCommitted__DelegateSignature(const struct FText& Text, TEnumAsByte<ETextCommit> Commit_Method);
void RightButtonClicked__DelegateSignature();
void LeftButtonClicked__DelegateSignature();
};
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
|
[
"51294434+LuaFan2@users.noreply.github.com"
] |
51294434+LuaFan2@users.noreply.github.com
|
a912e284dbfbb5e12a2c4f9d2d71d9f303308f2a
|
f8517de40106c2fc190f0a8c46128e8b67f7c169
|
/AllJoyn/Samples/MyLivingRoom/Models/org.alljoyn.ControlPanel/AllJoynHelpers.h
|
4df47019afd9527f6684dd36658f2acc3d6d1579
|
[
"MIT"
] |
permissive
|
ferreiramarcelo/samples
|
eb77df10fe39567b7ebf72b75dc8800e2470108a
|
4691f529dae5c440a5df71deda40c57976ee4928
|
refs/heads/develop
| 2023-06-21T00:31:52.939554
| 2021-01-23T16:26:59
| 2021-01-23T16:26:59
| 66,746,116
| 0
| 0
|
MIT
| 2023-06-19T20:52:43
| 2016-08-28T02:48:20
|
C
|
UTF-8
|
C++
| false
| false
| 8,787
|
h
|
#pragma once
// The amount of time to wait (ms) for a response after sending a message before timing out.
const int c_MessageTimeoutInMilliseconds = 10000;
// The maximum length of an AllJoyn type signature allowed by the AllJoyn Core library.
const int c_MaximumSignatureLength = 255;
#define RETURN_IF_QSTATUS_ERROR(status) \
{ \
int32 alljoynStatus = static_cast<int32>(status); \
if (Windows::Devices::AllJoyn::AllJoynStatus::Ok != alljoynStatus) \
{ \
return status; \
} \
}
class AllJoynHelpers
{
public:
// The Windows::Devices::AllJoyn::AllJoynBusAttachment class wraps the alljoyn_busattachment type. This
// function gets the underlying alljoyn_busattachment.
static alljoyn_busattachment GetInternalBusAttachment(_In_ Windows::Devices::AllJoyn::AllJoynBusAttachment^ busAttachment);
// Create the alljoyn_interfacedescriptions described in introspectionXml and add them to the busAttachment.
static QStatus CreateInterfaces(_Inout_ Windows::Devices::AllJoyn::AllJoynBusAttachment^ busAttachment, _In_ PCSTR introspectionXml);
// Convert a UTF8 string to a wide character Platform::String.
static Platform::String^ MultibyteToPlatformString(_In_ PCSTR);
// Convert a wide character Platform::String to a UTF8 string.
static std::vector<char> PlatformToMultibyteString(_In_ Platform::String^ str);
// Get the service object path from an objectDescriptionArg. The objectDescriptionArg should
// come from an Announce signal.
static Platform::String^ AllJoynHelpers::GetObjectPath(_In_ alljoyn_aboutobjectdescription objectDescription, _In_ PCSTR interfaceName);
// Callback for alljoyn_about_announced_ptr.
// This callback expects the context to be of type T, which must implement the OnAnnounce function.
template<class T>
static void AnnounceHandler(
_In_ const void* context,
_In_ PCSTR name,
_In_ uint16_t version,
_In_ alljoyn_sessionport port,
_In_ alljoyn_msgarg objectDescriptionArg,
_In_ const alljoyn_msgarg aboutDataArg)
{
T^ caller = static_cast<const Platform::WeakReference*>(context)->Resolve<T>();
caller->OnAnnounce(name, version, port, objectDescriptionArg, aboutDataArg);
}
// Callback for alljoyn_proxybusobject_listener_propertieschanged_ptr.
// This callback expects the context to be of type T, which must implement the OnPropertyChanged function.
template<class T>
static void PropertyChangedHandler(_In_ alljoyn_proxybusobject obj, _In_ PCSTR interfaceName, _In_ const alljoyn_msgarg changed, _In_ const alljoyn_msgarg invalidated, _In_ void* context)
{
T^ caller = static_cast<const Platform::WeakReference*>(context)->Resolve<T>();
caller->OnPropertyChanged(obj, interfaceName, changed, invalidated);
}
// Callback for alljoyn_busobject_prop_get_ptr.
template<class T>
static QStatus PropertyGetHandler(_In_ const void* context, _In_ PCSTR interfaceName, _In_ PCSTR propertyName, _In_ alljoyn_msgarg value)
{
T^ caller = static_cast<const Platform::WeakReference*>(context)->Resolve<T>();
return caller->OnPropertyGet(interfaceName, propertyName, value);
}
// Callback for alljoyn_busobject_prop_set_ptr.
template<class T>
static QStatus PropertySetHandler(_In_ const void* context, _In_ PCSTR interfaceName, _In_ PCSTR propertyName, _In_ alljoyn_msgarg value)
{
T^ caller = static_cast<const Platform::WeakReference*>(context)->Resolve<T>();
return caller->OnPropertySet(interfaceName, propertyName, value);
}
// Callback for alljoyn_sessionlistener_sessionlost_ptr.
template<class T>
static void SessionLostHandler(_In_ const void* context, _In_ alljoyn_sessionid sessionId, _In_ alljoyn_sessionlostreason reason)
{
T^ caller = static_cast<const Platform::WeakReference*>(context)->Resolve<T>();
caller->OnSessionLost(sessionId, reason);
}
// Callback for alljoyn_sessionlistener_sessionmemberadded_ptr.
template<class T>
static void SessionMemberAddedHandler(_In_ const void* context, _In_ alljoyn_sessionid sessionId, _In_ PCSTR uniqueName)
{
T^ caller = static_cast<const Platform::WeakReference*>(context)->Resolve<T>();
caller->OnSessionMemberAdded(sessionId, uniqueName);
}
// Callback for alljoyn_sessionlistener_sessionmemberremoved_ptr.
template<class T>
static void SessionMemberRemovedHandler(_In_ const void* context, _In_ alljoyn_sessionid sessionId, _In_ PCSTR uniqueName)
{
T^ caller = static_cast<const Platform::WeakReference*>(context)->Resolve<T>();
caller->OnSessionMemberRemoved(sessionId, uniqueName);
}
// Create an AllJoyn bus object.
template<class T>
static QStatus CreateBusObject(_Inout_ Platform::WeakReference* target)
{
alljoyn_busobject_callbacks callbacks =
{
PropertyGetHandler<T>,
PropertySetHandler<T>,
nullptr,
nullptr,
};
T^ caller = target->Resolve<T>();
auto serviceObjectPath = PlatformToMultibyteString(caller->ServiceObjectPath);
alljoyn_busobject busObject = alljoyn_busobject_create(serviceObjectPath.data(), false, &callbacks, target);
if (busObject == nullptr)
{
return ER_FAIL;
}
caller->BusObject = busObject;
return ER_OK;
}
// Callback for alljoyn_sessionportlistener_acceptsessionjoiner_ptr.
// This callback expects the context to be of type T, which must implement the OnAcceptSessionJoiner function.
template<class T>
static QCC_BOOL AcceptSessionJoinerHandler(
_In_ const void* context,
_In_ alljoyn_sessionport sessionPort,
_In_ PCSTR joiner,
_In_ const alljoyn_sessionopts opts)
{
T^ caller = static_cast<const Platform::WeakReference*>(context)->Resolve<T>();
return caller->OnAcceptSessionJoiner(sessionPort, joiner, opts);
}
// Callback for alljoyn_sessionportlistener_sessionjoined_ptr.
// This callback expects the context to be of type T, which must implement the OnSessionJoined function.
template<class T>
static void SessionJoinedHandler(
_In_ const void* context,
_In_ alljoyn_sessionport sessionPort,
_In_ alljoyn_sessionid id,
_In_ PCSTR joiner)
{
T^ caller = static_cast<const Platform::WeakReference*>(context)->Resolve<T>();
caller->OnSessionJoined(sessionPort, id, joiner);
}
// Create the session for an AllJoyn producer.
template<class T>
static QStatus CreateProducerSession(_Inout_ Windows::Devices::AllJoyn::AllJoynBusAttachment^ busAttachment, _Inout_ Platform::WeakReference* target)
{
alljoyn_sessionopts opts = alljoyn_sessionopts_create(ALLJOYN_TRAFFIC_TYPE_MESSAGES, true, ALLJOYN_PROXIMITY_ANY, ALLJOYN_TRANSPORT_ANY);
alljoyn_sessionportlistener_callbacks callbacks =
{
AcceptSessionJoinerHandler<T>,
SessionJoinedHandler<T>
};
T^ producer = target->Resolve<T>();
producer->SessionPortListener = alljoyn_sessionportlistener_create(&callbacks, target);
alljoyn_sessionport sessionPort = 42;
alljoyn_busattachment_unbindsessionport(AllJoynHelpers::GetInternalBusAttachment(busAttachment), sessionPort);
RETURN_IF_QSTATUS_ERROR(alljoyn_busattachment_bindsessionport(AllJoynHelpers::GetInternalBusAttachment(busAttachment), &sessionPort, opts, producer->SessionPortListener));
producer->SessionPort = sessionPort;
alljoyn_sessionopts_destroy(opts);
return ER_OK;
}
};
// Passed to property get callbacks to allow them to report when the async operation is completed.
template<class T>
class PropertyGetContext
{
public:
void SetEvent()
{
m_event.set();
}
void Wait()
{
m_event.wait();
}
QStatus GetStatus()
{
return m_status;
}
void SetStatus(QStatus value)
{
m_status = value;
}
T GetValue()
{
return m_value;
}
void SetValue(T value)
{
m_value = value;
}
private:
Concurrency::event m_event;
QStatus m_status;
T m_value;
};
// Passed to property set callbacks to allow them to report when the async operation is completed.
class PropertySetContext
{
public:
void SetEvent()
{
m_event.set();
}
void Wait()
{
m_event.wait();
}
QStatus GetStatus()
{
return m_status;
}
void SetStatus(QStatus value)
{
m_status = value;
}
private:
Concurrency::event m_event;
QStatus m_status;
};
|
[
"artemz@microsoft.com"
] |
artemz@microsoft.com
|
7e0c75c5fc877a898df1589010e04d6cf30693df
|
3295316f85d069650a0dee5df5a64b332011a8c4
|
/NativeDLL/Wamedia/mp4muxer/include/mp4flavoridentifier.h
|
8dbe98272c034e7d0753e5a6d9f545e04bc5748b
|
[] |
no_license
|
whitespeed/UnityRealtimeCapture
|
6cf3135fbc7c5d81548cc5528e4bf381c4797fa4
|
4f1c48bb4ce2647c989b55a0867d8c2622a1060f
|
refs/heads/master
| 2020-03-08T09:18:23.853786
| 2018-04-04T10:03:11
| 2018-04-04T10:03:11
| 128,043,858
| 1
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 483
|
h
|
#pragma once
#include "mp4errors.h"
#ifdef __cplusplus
namespace libmp4operations
{
extern "C"
{
#endif // __cplusplus
typedef enum
{
MP4_FORMAT_FLAVOR_UNIDENTIFIED = 0,
MP4_FORMAT_FLAVOR_ISO_3G2_3GPP,
MP4_FORMAT_FLAVOR_APPLE_QUICK_TIME_MOV,
MP4_FORMAT_FLAVOR_FRAGMENTED_MP4
} eMP4_FORMAT_FLAVOR;
uint32_t determineMp4FormatFlavor(const char* pStrInputFilename, eMP4_FORMAT_FLAVOR* pFlavor);
#ifdef __cplusplus
}
}; // namespace libmp4operations
#endif // __cplusplus
|
[
"whitespeed@qq.com"
] |
whitespeed@qq.com
|
deee95101c825edca798ec763618a5bb98ca1c7c
|
697ddc45fde47e029c5873e9ffe0ca19f4197d24
|
/examples/FT81xmania/GD2U_JAP_SD_JPEGANIM/Parametros.ino
|
c02e620b1d1334156428736626843482e2722d4f
|
[] |
no_license
|
ggarza78/GD23ZU
|
bef5dee4bfa7f056f661955255d777a14c19d513
|
79674a4f09db0b460a32a9c6b6c1e9a38ece9fcc
|
refs/heads/master
| 2020-06-25T03:41:20.067437
| 2018-12-18T17:23:49
| 2018-12-18T17:23:49
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 680
|
ino
|
#if defined(__arm__)
extern "C" char* sbrk(int incr);
static int FreeStack() {
char top = 't';
return &top - reinterpret_cast<char*>(sbrk(0));
}
#endif
char TXP[50];
void STM32a()
{
ram = FreeStack();
FRAM=ram;
if(FRAM<=196608){SRAM=327680;}
else{SRAM=524288;}
}
void STM32()
{
GD.ColorRGB(0x00ff00); sprintf(TXP,"F_CPU: %d MHz", (F_CPU/1000000)); GD.cmd_text(25, 465, 26, 0, TXP);
GD.ColorRGB(0x00ff00); sprintf(TXP,"F_RAM: %d byte", (ram)); // GD.cmd_text(320, 465, 26, 0, TXP);
GD.cmd_text(320, 465, 26, 0, "U_RAM: %"); //GD.printNfloat(420, 465, SRAM-FRAM, 2, 26);
GD.printNfloat(390, 465, 100*(SRAM-FRAM)/SRAM, 2, 26);
}
|
[
"noreply@github.com"
] |
ggarza78.noreply@github.com
|
45531e257ed6672a0bb50b0bdf27dc79b533b004
|
db111ff94903f0b24658c328d93f5cc28b670b8d
|
/components/page_load_metrics/browser/metrics_web_contents_observer.cc
|
d9f4123665703db635e066025b92e232498f06c8
|
[
"BSD-3-Clause"
] |
permissive
|
nibilin33/chromium
|
21e505ab4c6dec858d3b0fe2bfbaf56d023d9f0d
|
3dea9ffa737bc9c9a9f58d4bab7074e3bc84f349
|
refs/heads/master
| 2023-01-16T10:54:57.353825
| 2020-04-02T04:24:11
| 2020-04-02T04:24:11
| 252,359,157
| 1
| 0
|
BSD-3-Clause
| 2020-04-02T04:57:37
| 2020-04-02T04:57:37
| null |
UTF-8
|
C++
| false
| false
| 33,365
|
cc
|
// Copyright 2015 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.
#include "components/page_load_metrics/browser/metrics_web_contents_observer.h"
#include <algorithm>
#include <ostream>
#include <string>
#include <utility>
#include "base/location.h"
#include "base/memory/ptr_util.h"
#include "base/metrics/histogram_macros.h"
#include "components/page_load_metrics/browser/page_load_metrics_embedder_interface.h"
#include "components/page_load_metrics/browser/page_load_metrics_update_dispatcher.h"
#include "components/page_load_metrics/browser/page_load_metrics_util.h"
#include "components/page_load_metrics/browser/page_load_tracker.h"
#include "components/page_load_metrics/common/page_load_timing.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/global_request_id.h"
#include "content/public/browser/media_player_id.h"
#include "content/public/browser/navigation_details.h"
#include "content/public/browser/navigation_handle.h"
#include "content/public/browser/render_frame_host.h"
#include "content/public/browser/render_process_host.h"
#include "content/public/browser/render_view_host.h"
#include "content/public/browser/web_contents.h"
#include "content/public/browser/web_contents_observer.h"
#include "content/public/browser/web_contents_user_data.h"
#include "net/base/ip_endpoint.h"
#include "net/base/net_errors.h"
#include "services/network/public/mojom/fetch_api.mojom-shared.h"
#include "third_party/blink/public/common/loader/resource_type_util.h"
#include "ui/base/page_transition_types.h"
namespace page_load_metrics {
namespace {
// Returns the HTTP status code for the current page, or -1 if no status code
// is available. Can only be called if the |navigation_handle| has committed.
int GetHttpStatusCode(content::NavigationHandle* navigation_handle) {
DCHECK(navigation_handle->HasCommitted());
const net::HttpResponseHeaders* response_headers =
navigation_handle->GetResponseHeaders();
if (!response_headers)
return -1;
return response_headers->response_code();
}
UserInitiatedInfo CreateUserInitiatedInfo(
content::NavigationHandle* navigation_handle) {
if (!navigation_handle->IsRendererInitiated())
return UserInitiatedInfo::BrowserInitiated();
return UserInitiatedInfo::RenderInitiated(
navigation_handle->HasUserGesture(),
!navigation_handle->NavigationInputStart().is_null());
}
} // namespace
// static
void MetricsWebContentsObserver::RecordFeatureUsage(
content::RenderFrameHost* render_frame_host,
const mojom::PageLoadFeatures& new_features) {
content::WebContents* web_contents =
content::WebContents::FromRenderFrameHost(render_frame_host);
MetricsWebContentsObserver* observer =
MetricsWebContentsObserver::FromWebContents(web_contents);
if (observer)
observer->OnBrowserFeatureUsage(render_frame_host, new_features);
}
MetricsWebContentsObserver::MetricsWebContentsObserver(
content::WebContents* web_contents,
std::unique_ptr<PageLoadMetricsEmbedderInterface> embedder_interface)
: content::WebContentsObserver(web_contents),
in_foreground_(web_contents->GetVisibility() !=
content::Visibility::HIDDEN),
embedder_interface_(std::move(embedder_interface)),
has_navigated_(false),
page_load_metrics_receiver_(web_contents, this) {
// Prerenders erroneously report that they are initially visible, so we
// manually override visibility state for prerender.
if (embedder_interface_->IsPrerender(web_contents))
in_foreground_ = false;
RegisterInputEventObserver(web_contents->GetRenderViewHost());
}
// static
MetricsWebContentsObserver* MetricsWebContentsObserver::CreateForWebContents(
content::WebContents* web_contents,
std::unique_ptr<PageLoadMetricsEmbedderInterface> embedder_interface) {
DCHECK(web_contents);
MetricsWebContentsObserver* metrics = FromWebContents(web_contents);
if (!metrics) {
metrics = new MetricsWebContentsObserver(web_contents,
std::move(embedder_interface));
web_contents->SetUserData(UserDataKey(), base::WrapUnique(metrics));
}
return metrics;
}
MetricsWebContentsObserver::~MetricsWebContentsObserver() {}
void MetricsWebContentsObserver::WebContentsWillSoonBeDestroyed() {
web_contents_will_soon_be_destroyed_ = true;
}
void MetricsWebContentsObserver::WebContentsDestroyed() {
// TODO(csharrison): Use a more user-initiated signal for CLOSE.
NotifyPageEndAllLoads(END_CLOSE, UserInitiatedInfo::NotUserInitiated());
// We tear down PageLoadTrackers in WebContentsDestroyed, rather than in the
// destructor, since |web_contents()| returns nullptr in the destructor, and
// PageLoadMetricsObservers can cause code to execute that wants to be able to
// access the current WebContents.
committed_load_ = nullptr;
provisional_loads_.clear();
aborted_provisional_loads_.clear();
for (auto& observer : testing_observers_)
observer.OnGoingAway();
}
void MetricsWebContentsObserver::RegisterInputEventObserver(
content::RenderViewHost* host) {
if (host != nullptr)
host->GetWidget()->AddInputEventObserver(this);
}
void MetricsWebContentsObserver::UnregisterInputEventObserver(
content::RenderViewHost* host) {
if (host != nullptr)
host->GetWidget()->RemoveInputEventObserver(this);
}
void MetricsWebContentsObserver::RenderViewHostChanged(
content::RenderViewHost* old_host,
content::RenderViewHost* new_host) {
UnregisterInputEventObserver(old_host);
RegisterInputEventObserver(new_host);
}
void MetricsWebContentsObserver::FrameDeleted(content::RenderFrameHost* rfh) {
if (committed_load_)
committed_load_->FrameDeleted(rfh);
}
void MetricsWebContentsObserver::MediaStartedPlaying(
const content::WebContentsObserver::MediaPlayerInfo& video_type,
const content::MediaPlayerId& id) {
if (!id.render_frame_host->GetMainFrame()->IsCurrent()) {
// Ignore media that starts playing in a page that was navigated away
// from.
return;
}
if (committed_load_)
committed_load_->MediaStartedPlaying(video_type, id.render_frame_host);
}
void MetricsWebContentsObserver::WillStartNavigationRequest(
content::NavigationHandle* navigation_handle) {
// Same-document navigations should never go through
// WillStartNavigationRequest.
DCHECK(!navigation_handle->IsSameDocument());
if (!navigation_handle->IsInMainFrame())
return;
WillStartNavigationRequestImpl(navigation_handle);
has_navigated_ = true;
}
void MetricsWebContentsObserver::WillStartNavigationRequestImpl(
content::NavigationHandle* navigation_handle) {
UserInitiatedInfo user_initiated_info(
CreateUserInitiatedInfo(navigation_handle));
std::unique_ptr<PageLoadTracker> last_aborted =
NotifyAbortedProvisionalLoadsNewNavigation(navigation_handle,
user_initiated_info);
int chain_size_same_url = 0;
int chain_size = 0;
if (last_aborted) {
if (last_aborted->MatchesOriginalNavigation(navigation_handle)) {
chain_size_same_url = last_aborted->aborted_chain_size_same_url() + 1;
} else if (last_aborted->aborted_chain_size_same_url() > 0) {
LogAbortChainSameURLHistogram(
last_aborted->aborted_chain_size_same_url());
}
chain_size = last_aborted->aborted_chain_size() + 1;
}
if (!ShouldTrackMainFrameNavigation(navigation_handle))
return;
// Pass in the last committed url to the PageLoadTracker. If the MWCO has
// never observed a committed load, use the last committed url from this
// WebContent's opener. This is more accurate than using referrers due to
// referrer sanitizing and origin referrers. Note that this could potentially
// be inaccurate if the opener has since navigated.
content::RenderFrameHost* opener = web_contents()->GetOpener();
const GURL& opener_url = !has_navigated_ && opener
? opener->GetLastCommittedURL()
: GURL::EmptyGURL();
const GURL& currently_committed_url =
committed_load_ ? committed_load_->url() : opener_url;
// Passing raw pointers to observers_ and embedder_interface_ is safe because
// the MetricsWebContentsObserver owns them both list and they are torn down
// after the PageLoadTracker. The PageLoadTracker does not hold on to
// committed_load_ or navigation_handle beyond the scope of the constructor.
auto insertion_result = provisional_loads_.insert(std::make_pair(
navigation_handle,
std::make_unique<PageLoadTracker>(
in_foreground_, embedder_interface_.get(), currently_committed_url,
!has_navigated_, navigation_handle, user_initiated_info, chain_size,
chain_size_same_url)));
DCHECK(insertion_result.second)
<< "provisional_loads_ already contains NavigationHandle.";
for (auto& observer : testing_observers_)
observer.OnTrackerCreated(insertion_result.first->second.get());
}
void MetricsWebContentsObserver::WillProcessNavigationResponse(
content::NavigationHandle* navigation_handle) {
auto it = provisional_loads_.find(navigation_handle);
if (it == provisional_loads_.end())
return;
it->second->WillProcessNavigationResponse(navigation_handle);
}
PageLoadTracker* MetricsWebContentsObserver::GetTrackerOrNullForRequest(
const content::GlobalRequestID& request_id,
content::RenderFrameHost* render_frame_host_or_null,
network::mojom::RequestDestination request_destination,
base::TimeTicks creation_time) {
if (request_destination == network::mojom::RequestDestination::kDocument) {
DCHECK(request_id != content::GlobalRequestID());
// The main frame request can complete either before or after commit, so we
// look at both provisional loads and the committed load to find a
// PageLoadTracker with a matching request id. See https://goo.gl/6TzCYN for
// more details.
for (const auto& kv : provisional_loads_) {
PageLoadTracker* candidate = kv.second.get();
if (candidate->HasMatchingNavigationRequestID(request_id)) {
return candidate;
}
}
if (committed_load_ &&
committed_load_->HasMatchingNavigationRequestID(request_id)) {
return committed_load_.get();
}
} else {
// Non main frame resources are always associated with the currently
// committed load. If the resource request was started before this
// navigation then it should be ignored.
if (!committed_load_ || creation_time < committed_load_->navigation_start())
return nullptr;
// Sub-frame resources have a null RFH when browser-side navigation is
// enabled, so we can't perform the RFH check below for them.
//
// TODO(bmcquade): consider tracking GlobalRequestIDs for sub-frame
// navigations in each PageLoadTracker, and performing a lookup for
// sub-frames similar to the main-frame lookup above.
if (blink::IsRequestDestinationFrame(request_destination))
return committed_load_.get();
// This was originally a DCHECK but it fails when the document load happened
// after client certificate selection.
if (!render_frame_host_or_null)
return nullptr;
// There is a race here: a completed resource for the previously committed
// page can arrive after the new page has committed. In this case, we may
// attribute the resource to the wrong page load. We do our best to guard
// against this by verifying that the RFH for the resource matches the RFH
// for the currently committed load, however there are cases where the same
// RFH is used across page loads (same origin navigations, as well as some
// cross-origin render-initiated navigations).
//
// TODO(crbug.com/738577): use a DocumentId here instead, to eliminate this
// race.
if (render_frame_host_or_null->GetMainFrame()->IsCurrent()) {
return committed_load_.get();
}
}
return nullptr;
}
void MetricsWebContentsObserver::ResourceLoadComplete(
content::RenderFrameHost* render_frame_host,
const content::GlobalRequestID& request_id,
const blink::mojom::ResourceLoadInfo& resource_load_info) {
if (!resource_load_info.final_url.SchemeIsHTTPOrHTTPS())
return;
PageLoadTracker* tracker = GetTrackerOrNullForRequest(
request_id, render_frame_host, resource_load_info.request_destination,
resource_load_info.load_timing_info.request_start);
if (tracker) {
// TODO(crbug.com/721403): Fill in data reduction proxy fields when this is
// available in the network service.
// int original_content_length =
// was_cached ? 0
// : data_reduction_proxy::util::EstimateOriginalBodySize(
// request, lofi_decider);
int original_content_length = 0;
std::unique_ptr<data_reduction_proxy::DataReductionProxyData>
data_reduction_proxy_data;
const blink::mojom::CommonNetworkInfoPtr& network_info =
resource_load_info.network_info;
ExtraRequestCompleteInfo extra_request_complete_info(
url::Origin::Create(resource_load_info.final_url),
network_info->remote_endpoint.value(),
render_frame_host->GetFrameTreeNodeId(), resource_load_info.was_cached,
resource_load_info.raw_body_bytes, original_content_length,
std::move(data_reduction_proxy_data),
resource_load_info.request_destination, resource_load_info.net_error,
std::make_unique<net::LoadTimingInfo>(
resource_load_info.load_timing_info));
tracker->OnLoadedResource(extra_request_complete_info);
}
}
void MetricsWebContentsObserver::FrameReceivedFirstUserActivation(
content::RenderFrameHost* render_frame_host) {
if (committed_load_)
committed_load_->FrameReceivedFirstUserActivation(render_frame_host);
}
void MetricsWebContentsObserver::FrameDisplayStateChanged(
content::RenderFrameHost* render_frame_host,
bool is_display_none) {
if (committed_load_)
committed_load_->FrameDisplayStateChanged(render_frame_host,
is_display_none);
}
void MetricsWebContentsObserver::FrameSizeChanged(
content::RenderFrameHost* render_frame_host,
const gfx::Size& frame_size) {
if (committed_load_)
committed_load_->FrameSizeChanged(render_frame_host, frame_size);
}
void MetricsWebContentsObserver::OnCookiesRead(
const GURL& url,
const GURL& first_party_url,
const net::CookieList& cookie_list,
bool blocked_by_policy) {
if (committed_load_)
committed_load_->OnCookiesRead(url, first_party_url, cookie_list,
blocked_by_policy);
}
void MetricsWebContentsObserver::OnCookieChange(
const GURL& url,
const GURL& first_party_url,
const net::CanonicalCookie& cookie,
bool blocked_by_policy) {
if (committed_load_)
committed_load_->OnCookieChange(url, first_party_url, cookie,
blocked_by_policy);
}
void MetricsWebContentsObserver::OnStorageAccessed(const GURL& url,
const GURL& first_party_url,
bool blocked_by_policy,
StorageType storage_type) {
if (committed_load_)
committed_load_->OnStorageAccessed(url, first_party_url, blocked_by_policy,
storage_type);
}
const PageLoadMetricsObserverDelegate&
MetricsWebContentsObserver::GetDelegateForCommittedLoad() {
DCHECK(committed_load_);
return *committed_load_.get();
}
void MetricsWebContentsObserver::ReadyToCommitNavigation(
content::NavigationHandle* navigation_handle) {
if (committed_load_)
committed_load_->ReadyToCommitNavigation(navigation_handle);
}
void MetricsWebContentsObserver::DidFinishNavigation(
content::NavigationHandle* navigation_handle) {
if (!navigation_handle->IsInMainFrame()) {
if (committed_load_ && navigation_handle->GetParentFrame() &&
navigation_handle->GetParentFrame()->GetMainFrame()->IsCurrent()) {
committed_load_->DidFinishSubFrameNavigation(navigation_handle);
committed_load_->metrics_update_dispatcher()->DidFinishSubFrameNavigation(
navigation_handle);
}
return;
}
// Not all navigations trigger the WillStartNavigationRequest callback (for
// example, navigations to about:blank). DidFinishNavigation is guaranteed to
// be called for every navigation, so we also update has_navigated_ here, to
// ensure it is set consistently for all navigations.
has_navigated_ = true;
std::unique_ptr<PageLoadTracker> navigation_handle_tracker(
std::move(provisional_loads_[navigation_handle]));
provisional_loads_.erase(navigation_handle);
// Ignore same-document navigations.
if (navigation_handle->HasCommitted() &&
navigation_handle->IsSameDocument()) {
if (navigation_handle_tracker)
navigation_handle_tracker->StopTracking();
if (committed_load_)
committed_load_->DidCommitSameDocumentNavigation(navigation_handle);
return;
}
// Ignore internally generated aborts for navigations with HTTP responses that
// don't commit, such as HTTP 204 responses and downloads.
if (!navigation_handle->HasCommitted() &&
navigation_handle->GetNetErrorCode() == net::ERR_ABORTED &&
navigation_handle->GetResponseHeaders()) {
if (navigation_handle_tracker) {
navigation_handle_tracker->DidInternalNavigationAbort(navigation_handle);
navigation_handle_tracker->StopTracking();
}
return;
}
if (navigation_handle->HasCommitted()) {
// A new navigation is committing, so finalize and destroy the tracker for
// the currently committed navigation.
FinalizeCurrentlyCommittedLoad(navigation_handle,
navigation_handle_tracker.get());
committed_load_.reset();
}
if (!navigation_handle_tracker)
return;
if (!ShouldTrackMainFrameNavigation(navigation_handle)) {
navigation_handle_tracker->StopTracking();
return;
}
if (navigation_handle->HasCommitted()) {
HandleCommittedNavigationForTrackedLoad(
navigation_handle, std::move(navigation_handle_tracker));
} else {
HandleFailedNavigationForTrackedLoad(navigation_handle,
std::move(navigation_handle_tracker));
}
}
// Handle a pre-commit error. Navigations that result in an error page will be
// ignored.
void MetricsWebContentsObserver::HandleFailedNavigationForTrackedLoad(
content::NavigationHandle* navigation_handle,
std::unique_ptr<PageLoadTracker> tracker) {
const base::TimeTicks now = base::TimeTicks::Now();
tracker->FailedProvisionalLoad(navigation_handle, now);
const net::Error error = navigation_handle->GetNetErrorCode();
// net::OK: This case occurs when the NavigationHandle finishes and reports
// !HasCommitted(), but reports no net::Error. This represents the navigation
// being stopped by the user before it was ready to commit.
// net::ERR_ABORTED: An aborted provisional load has error net::ERR_ABORTED.
const bool is_aborted_provisional_load =
error == net::OK || error == net::ERR_ABORTED;
// If is_aborted_provisional_load, the page end reason is not yet known, and
// will be updated as additional information is available from subsequent
// navigations.
tracker->NotifyPageEnd(
is_aborted_provisional_load ? END_OTHER : END_PROVISIONAL_LOAD_FAILED,
UserInitiatedInfo::NotUserInitiated(), now, true);
if (is_aborted_provisional_load)
aborted_provisional_loads_.push_back(std::move(tracker));
}
void MetricsWebContentsObserver::HandleCommittedNavigationForTrackedLoad(
content::NavigationHandle* navigation_handle,
std::unique_ptr<PageLoadTracker> tracker) {
committed_load_ = std::move(tracker);
committed_load_->Commit(navigation_handle);
DCHECK(committed_load_->did_commit());
for (auto& observer : testing_observers_)
observer.OnCommit(committed_load_.get());
}
void MetricsWebContentsObserver::FinalizeCurrentlyCommittedLoad(
content::NavigationHandle* newly_committed_navigation,
PageLoadTracker* newly_committed_navigation_tracker) {
UserInitiatedInfo user_initiated_info =
newly_committed_navigation_tracker
? newly_committed_navigation_tracker->user_initiated_info()
: CreateUserInitiatedInfo(newly_committed_navigation);
// Notify other loads that they may have been aborted by this committed
// load. is_certainly_browser_timestamp is set to false because
// NavigationStart() could be set in either the renderer or browser process.
NotifyPageEndAllLoadsWithTimestamp(
EndReasonForPageTransition(
newly_committed_navigation->GetPageTransition()),
user_initiated_info, newly_committed_navigation->NavigationStart(),
/*is_certainly_browser_timestamp=*/false);
if (committed_load_) {
bool is_non_user_initiated_client_redirect =
!IsNavigationUserInitiated(newly_committed_navigation) &&
(newly_committed_navigation->GetPageTransition() &
ui::PAGE_TRANSITION_CLIENT_REDIRECT) != 0;
if (is_non_user_initiated_client_redirect) {
committed_load_->NotifyClientRedirectTo(newly_committed_navigation);
}
}
}
void MetricsWebContentsObserver::NavigationStopped() {
// TODO(csharrison): Use a more user-initiated signal for STOP.
NotifyPageEndAllLoads(END_STOP, UserInitiatedInfo::NotUserInitiated());
}
void MetricsWebContentsObserver::OnInputEvent(
const blink::WebInputEvent& event) {
// Ignore browser navigation or reload which comes with type Undefined.
if (event.GetType() == blink::WebInputEvent::Type::kUndefined)
return;
if (committed_load_)
committed_load_->OnInputEvent(event);
}
void MetricsWebContentsObserver::FlushMetricsOnAppEnterBackground() {
// Note that, while a call to FlushMetricsOnAppEnterBackground usually
// indicates that the app is about to be backgrounded, there are cases where
// the app may not end up getting backgrounded. Thus, we should not assume
// anything about foreground / background state of the associated tab as part
// of this method call.
if (committed_load_)
committed_load_->FlushMetricsOnAppEnterBackground();
for (const auto& kv : provisional_loads_) {
kv.second->FlushMetricsOnAppEnterBackground();
}
for (const auto& tracker : aborted_provisional_loads_) {
tracker->FlushMetricsOnAppEnterBackground();
}
}
void MetricsWebContentsObserver::DidRedirectNavigation(
content::NavigationHandle* navigation_handle) {
if (!navigation_handle->IsInMainFrame())
return;
auto it = provisional_loads_.find(navigation_handle);
if (it == provisional_loads_.end())
return;
it->second->Redirect(navigation_handle);
}
void MetricsWebContentsObserver::OnVisibilityChanged(
content::Visibility visibility) {
if (web_contents_will_soon_be_destroyed_)
return;
bool was_in_foreground = in_foreground_;
in_foreground_ = visibility == content::Visibility::VISIBLE;
if (in_foreground_ == was_in_foreground)
return;
if (in_foreground_) {
if (committed_load_)
committed_load_->PageShown();
for (const auto& kv : provisional_loads_) {
kv.second->PageShown();
}
} else {
if (committed_load_)
committed_load_->PageHidden();
for (const auto& kv : provisional_loads_) {
kv.second->PageHidden();
}
}
}
// This will occur when the process for the main RenderFrameHost exits, either
// normally or from a crash. We eagerly log data from the last committed load if
// we have one.
void MetricsWebContentsObserver::RenderProcessGone(
base::TerminationStatus status) {
// Other code paths will be run for normal renderer shutdown. Note that we
// sometimes get the STILL_RUNNING value on fast shutdown.
if (status == base::TERMINATION_STATUS_NORMAL_TERMINATION ||
status == base::TERMINATION_STATUS_STILL_RUNNING) {
return;
}
// RenderProcessGone is associated with the render frame host for the
// currently committed load. We don't know if the pending navs or aborted
// pending navs are associated w/ the render process that died, so we can't be
// sure the info should propagate to them.
if (committed_load_) {
committed_load_->NotifyPageEnd(END_RENDER_PROCESS_GONE,
UserInitiatedInfo::NotUserInitiated(),
base::TimeTicks::Now(), true);
}
// If this is a crash, eagerly log the aborted provisional loads and the
// committed load. |provisional_loads_| don't need to be destroyed here
// because their lifetime is tied to the NavigationHandle.
committed_load_.reset();
aborted_provisional_loads_.clear();
}
void MetricsWebContentsObserver::NotifyPageEndAllLoads(
PageEndReason page_end_reason,
UserInitiatedInfo user_initiated_info) {
NotifyPageEndAllLoadsWithTimestamp(page_end_reason, user_initiated_info,
base::TimeTicks::Now(),
/*is_certainly_browser_timestamp=*/true);
}
void MetricsWebContentsObserver::NotifyPageEndAllLoadsWithTimestamp(
PageEndReason page_end_reason,
UserInitiatedInfo user_initiated_info,
base::TimeTicks timestamp,
bool is_certainly_browser_timestamp) {
if (committed_load_) {
committed_load_->NotifyPageEnd(page_end_reason, user_initiated_info,
timestamp, is_certainly_browser_timestamp);
}
for (const auto& kv : provisional_loads_) {
kv.second->NotifyPageEnd(page_end_reason, user_initiated_info, timestamp,
is_certainly_browser_timestamp);
}
for (const auto& tracker : aborted_provisional_loads_) {
if (tracker->IsLikelyProvisionalAbort(timestamp)) {
tracker->UpdatePageEnd(page_end_reason, user_initiated_info, timestamp,
is_certainly_browser_timestamp);
}
}
aborted_provisional_loads_.clear();
}
std::unique_ptr<PageLoadTracker>
MetricsWebContentsObserver::NotifyAbortedProvisionalLoadsNewNavigation(
content::NavigationHandle* new_navigation,
UserInitiatedInfo user_initiated_info) {
// If there are multiple aborted loads that can be attributed to this one,
// just count the latest one for simplicity. Other loads will fall into the
// OTHER bucket, though there shouldn't be very many.
if (aborted_provisional_loads_.empty())
return nullptr;
if (aborted_provisional_loads_.size() > 1)
RecordInternalError(ERR_NAVIGATION_SIGNALS_MULIPLE_ABORTED_LOADS);
std::unique_ptr<PageLoadTracker> last_aborted_load =
std::move(aborted_provisional_loads_.back());
aborted_provisional_loads_.pop_back();
base::TimeTicks timestamp = new_navigation->NavigationStart();
if (last_aborted_load->IsLikelyProvisionalAbort(timestamp)) {
last_aborted_load->UpdatePageEnd(
EndReasonForPageTransition(new_navigation->GetPageTransition()),
user_initiated_info, timestamp, false);
}
aborted_provisional_loads_.clear();
return last_aborted_load;
}
void MetricsWebContentsObserver::OnTimingUpdated(
content::RenderFrameHost* render_frame_host,
mojom::PageLoadTimingPtr timing,
mojom::FrameMetadataPtr metadata,
mojom::PageLoadFeaturesPtr new_features,
const std::vector<mojom::ResourceDataUpdatePtr>& resources,
mojom::FrameRenderDataUpdatePtr render_data,
mojom::CpuTimingPtr cpu_timing,
mojom::DeferredResourceCountsPtr new_deferred_resource_data,
mojom::InputTimingPtr input_timing_delta) {
// We may receive notifications from frames that have been navigated away
// from. We simply ignore them.
// TODO(crbug.com/1061060): We should not ignore page timings if the page is
// in bfcache.
if (!render_frame_host->GetMainFrame()->IsCurrent()) {
RecordInternalError(ERR_IPC_FROM_WRONG_FRAME);
return;
}
const bool is_main_frame = (render_frame_host->GetParent() == nullptr);
if (is_main_frame) {
// While timings arriving for the wrong frame are expected, we do not expect
// any of the errors below for main frames. Thus, we track occurrences of
// all errors below, rather than returning early after encountering an
// error.
// TODO(crbug/1061090): Update page load metrics IPC validation to ues
// mojo::ReportBadMessage.
bool error = false;
if (!committed_load_) {
RecordInternalError(ERR_IPC_WITH_NO_RELEVANT_LOAD);
error = true;
}
if (!web_contents()->GetLastCommittedURL().SchemeIsHTTPOrHTTPS()) {
RecordInternalError(ERR_IPC_FROM_BAD_URL_SCHEME);
error = true;
}
if (error)
return;
} else if (!committed_load_) {
RecordInternalError(ERR_SUBFRAME_IPC_WITH_NO_RELEVANT_LOAD);
}
if (committed_load_) {
committed_load_->metrics_update_dispatcher()->UpdateMetrics(
render_frame_host, std::move(timing), std::move(metadata),
std::move(new_features), resources, std::move(render_data),
std::move(cpu_timing), std::move(new_deferred_resource_data),
std::move(input_timing_delta));
}
}
void MetricsWebContentsObserver::UpdateTiming(
mojom::PageLoadTimingPtr timing,
mojom::FrameMetadataPtr metadata,
mojom::PageLoadFeaturesPtr new_features,
std::vector<mojom::ResourceDataUpdatePtr> resources,
mojom::FrameRenderDataUpdatePtr render_data,
mojom::CpuTimingPtr cpu_timing,
mojom::DeferredResourceCountsPtr new_deferred_resource_data,
mojom::InputTimingPtr input_timing_delta) {
content::RenderFrameHost* render_frame_host =
page_load_metrics_receiver_.GetCurrentTargetFrame();
OnTimingUpdated(render_frame_host, std::move(timing), std::move(metadata),
std::move(new_features), resources, std::move(render_data),
std::move(cpu_timing), std::move(new_deferred_resource_data),
std::move(input_timing_delta));
}
bool MetricsWebContentsObserver::ShouldTrackMainFrameNavigation(
content::NavigationHandle* navigation_handle) const {
DCHECK(navigation_handle->IsInMainFrame());
DCHECK(!navigation_handle->HasCommitted() ||
!navigation_handle->IsSameDocument());
// If there is an outer WebContents, then this WebContents is embedded into
// another one (it is either a portal or a Chrome App <webview>). Ignore these
// navigations for now.
if (web_contents()->GetOuterWebContents())
return false;
// Ignore non-HTTP schemes (e.g. chrome://).
if (!navigation_handle->GetURL().SchemeIsHTTPOrHTTPS())
return false;
// Ignore NTP loads.
if (embedder_interface_->IsNewTabPageUrl(navigation_handle->GetURL()))
return false;
if (navigation_handle->HasCommitted()) {
// Ignore Chrome error pages (e.g. No Internet connection).
if (navigation_handle->IsErrorPage())
return false;
// Ignore network error pages (e.g. 4xx, 5xx).
int http_status_code = GetHttpStatusCode(navigation_handle);
if (http_status_code > 0 &&
(http_status_code < 200 || http_status_code >= 400))
return false;
}
// TODO(crbug.com/1014174): Ignore back-forward cached navigations for now.
if (navigation_handle->IsServedFromBackForwardCache())
return false;
return true;
}
void MetricsWebContentsObserver::OnBrowserFeatureUsage(
content::RenderFrameHost* render_frame_host,
const mojom::PageLoadFeatures& new_features) {
// Since this call is coming directly from the browser, it should not pass us
// data from frames that have already been navigated away from.
DCHECK(render_frame_host->GetMainFrame()->IsCurrent());
if (!committed_load_) {
RecordInternalError(ERR_BROWSER_USAGE_WITH_NO_RELEVANT_LOAD);
return;
}
committed_load_->metrics_update_dispatcher()->UpdateFeatures(
render_frame_host, new_features);
}
void MetricsWebContentsObserver::AddTestingObserver(TestingObserver* observer) {
if (!testing_observers_.HasObserver(observer))
testing_observers_.AddObserver(observer);
}
void MetricsWebContentsObserver::RemoveTestingObserver(
TestingObserver* observer) {
testing_observers_.RemoveObserver(observer);
}
MetricsWebContentsObserver::TestingObserver::TestingObserver(
content::WebContents* web_contents)
: observer_(page_load_metrics::MetricsWebContentsObserver::FromWebContents(
web_contents)) {
observer_->AddTestingObserver(this);
}
MetricsWebContentsObserver::TestingObserver::~TestingObserver() {
if (observer_) {
observer_->RemoveTestingObserver(this);
observer_ = nullptr;
}
}
void MetricsWebContentsObserver::TestingObserver::OnGoingAway() {
observer_ = nullptr;
}
const PageLoadMetricsObserverDelegate&
MetricsWebContentsObserver::TestingObserver::GetDelegateForCommittedLoad() {
return observer_->GetDelegateForCommittedLoad();
}
void MetricsWebContentsObserver::BroadcastEventToObservers(
const void* const event_key) {
if (committed_load_)
committed_load_->BroadcastEventToObservers(event_key);
}
WEB_CONTENTS_USER_DATA_KEY_IMPL(MetricsWebContentsObserver)
} // namespace page_load_metrics
|
[
"commit-bot@chromium.org"
] |
commit-bot@chromium.org
|
48bee5b9336b226226ab59a9ac673c18be2f7d5b
|
6b2a8dd202fdce77c971c412717e305e1caaac51
|
/solutions_5709773144064000_0/C++/dinario/main.cpp
|
cca906fe58103b2d86abca0d836ffdb89539eb95
|
[] |
no_license
|
alexandraback/datacollection
|
0bc67a9ace00abbc843f4912562f3a064992e0e9
|
076a7bc7693f3abf07bfdbdac838cb4ef65ccfcf
|
refs/heads/master
| 2021-01-24T18:27:24.417992
| 2017-05-23T09:23:38
| 2017-05-23T09:23:38
| 84,313,442
| 2
| 4
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 843
|
cpp
|
#include <iostream>
#include <fstream>
#include <string.h>
#include <set>
#include <map>
#include <math.h>
#include <algorithm>
using namespace std;
#define re return
#define ll long long
const ll MOD=1E9+7;
int main(){
freopen("B-small-attempt0.in","rt",stdin);
//freopen("input.txt","rt",stdin);
freopen("out.txt","wt",stdout);
ll i,j,n,k=0,T,t;
cin>>T;
cout.precision(20);
for(t=0;t<T;++t){
double C,F,X;
cin>>C>>F>>X;
double sum=0,speed=2;
double res=0;
bool bFoo=false;
for(i=0;!bFoo;++i){
double estimateX = X/speed;
double estimateC = C/speed;
double estimateX2 = estimateC+X/(speed+F);
if(estimateX2 < estimateX){
speed+=F;
res+=estimateC;
}else {
bFoo = true;
res+=estimateX;
}
}
cout<<"Case #"<<t+1<<": "<<res<<endl;
}
re 0;
}
|
[
"eewestman@gmail.com"
] |
eewestman@gmail.com
|
17a68e715d1d16fec3078399b1b59f9b2ca160d3
|
8b3d9d31b9fc91f92d823b373eebed85b0216e6d
|
/sketches/synths/polyphonic-guitar-synth/polyphonic-guitar-synth.ino
|
2776279993a9c4b069597a0e60bf55554aa690eb
|
[
"MIT"
] |
permissive
|
runjumplabs/dreammaker_fx_sketches
|
ede710d3d43be33d60231d38590a57135f0d5c05
|
76c6ad5d7b0c1369a60950896fed5f2485b0d50e
|
refs/heads/master
| 2020-12-22T12:39:19.295525
| 2020-02-21T01:42:56
| 2020-02-21T01:42:56
| 236,784,207
| 0
| 1
|
MIT
| 2020-09-09T01:26:46
| 2020-01-28T16:41:07
|
C++
|
UTF-8
|
C++
| false
| false
| 3,620
|
ino
|
/******************************************************************************
* DreamMaker FX / www.dreammakerfx.com
*****************************************************************************/
/*
Effect name: Polyphonic guitar synth pedal
Effect description: This is a polyphonic guitar synth meaning that it tracks
multiple strings. It uses an FM synth engine along with ADSR envelope generator
and an output filter. The pedal is configured by default to use a triangle
(OSC_TRIANGLE) wave that is modulated with a sine wave (OSC_SINE). However, lots
of interesting sounds can be created by swapping these out with out types of oscillators
(e.g. OSC_SQUARE, OSC_RAMP_POS, OSC_RAMP_NEG, OSC_RANDOM, etc).
Left pot label: FM mod depth
Left pot function: The depth of the FM mod in the synthesizer
Center pot label: Attack time
Center pot function: The attack time of the synth sound (i.e. how long it takes
to ramp to full volume when you play a new string)
Right pot label: Modulation frequency
Right pot function: The frequency of the FM modulator ranging from 0.25 x the note played
to 4.25x.
Left footswitch label: Bypass
Left footswitch function: Bypasses the effect
Right footswitch label:
Right footswitch function: describe right footswitch function
Youtube Url:
Soundcloud Url: https://soundcloud.com/dreammakerfx/polyphonic-synth-guitar-effect-on-dreammaker-fx
Created by: DreamMaker
DreamMakerFx package version: 1.5.3
Sketch version: 1.0
*/
#include <dreammakerfx.h>
// Add your fx module declarations here
fx_instrument_synth synth(OSC_TRIANGLE, // Primary oscillator
OSC_RAMP_NEG, // FM mod oscillator
0.1, // FM mod depth
1.0, // Freq ratio (ratio of instrument frequency to synth frequency (1.0 = same)
2.0, // FM mod frequency ratio (1.0 = same frequency as primary oscillator)
250.0, // Attack time in milliseconds
3.0, // Filter resonance
0.6); // Filter response (0.0 to 1.0)
void setup() {
// put your setup code here, to run once:
// Initialize the pedal!
pedal.init();
// Route audio through effects from pedal.instr_in to pedal.amp_out
pedal.route_audio(synth.output, pedal.amp_out);
// Optionally use a bypass switch FOOTSWITCH_LEFT or FOOTSWITCH_RIGHT
pedal.add_bypass_button(FOOTSWITCH_LEFT);
if (true) {
pedal.print_instance_stack();
pedal.print_routing_table();
pedal.print_param_tables();
}
// Optionally use a tap tempo / delay switch
// Can also be FOOTSWITCH_LEFT or FOOTSWITCH_RIGHT but different than
// the bypass switch
// pedal.add_tap_interval_button(FOOTSWITCH_RIGHT, true);
// Run this effect
pedal.run();
}
void loop() {
// put your main code here, to run repeatedly:
// Left pot control
if (pedal.pot_left.has_changed()) {
// Left pot value is: pedal.pot_left.val
synth.set_fm_mod_depth(pedal.pot_left.val);
}
// Center pot control
if (pedal.pot_center.has_changed()) {
// Center pot value is: pedal.pot_center.val
synth.set_attack_ms(25.0 + pedal.pot_center.val*975.0);
}
// Right pot set control
if (pedal.pot_right.has_changed()) {
// Right pot value is: pedal.pot_right.val
float x = 0.25 + round(pedal.pot_right.val * 16.0)*0.25;
synth.set_fm_mod_ratio(x);
}
// Run pedal service to take care of stuff
pedal.service();
}
|
[
"dan@runjumplabs.com"
] |
dan@runjumplabs.com
|
26fbfd9c162e773bc79d7db3b707cc333a1b8e56
|
c2305575458830fbf9bdabdf26dbfc17d037dcc2
|
/Old/minimumArraySet.cpp
|
4d954c76e358ae73f44702856979e25fa110c279
|
[] |
no_license
|
shribadiger/CPPStudy
|
6adc747ebf67e903d1b00920c276d55712edd0ed
|
75aa4c1033f0c72322ab68ea320c1c120dfbfced
|
refs/heads/master
| 2023-02-19T22:38:38.372271
| 2023-02-09T08:44:30
| 2023-02-09T08:44:30
| 183,357,549
| 2
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,510
|
cpp
|
/*
Leet code program to identify minimum size of elements remove from the array
*/
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int minSetSize(vector<int> &arr)
{
std::vector<int> maxChecker;
int counter = 1;
std::sort(arr.begin(), arr.end());
for (int i = 1; i < arr.size(); i++)
{
//cout<<"\n"<<arr[i]<<":"<<arr[i-1]<<endl;
if (arr[i] == arr[i - 1])
{
counter++;
continue;
}
maxChecker.push_back(counter);
counter = 1;
}
maxChecker.push_back(counter);
std::sort(maxChecker.begin(), maxChecker.end(), greater<int>());
// printing the iterator and check the logic is working or not
std::vector<int>::iterator itr = maxChecker.begin();
cout << "\n Max Repeater List\n";
int devider = 0;
int excluder = 0;
while (itr != maxChecker.end())
{
cout << "\t" << *itr;
devider += *itr;
if (arr.size() - devider <= arr.size() / 2)
{
excluder++;
break;
}
itr++;
excluder++;
}
return excluder;
}
int main()
{
std::vector<int> input1 = {3, 3, 3, 3, 5, 5, 5, 2, 2, 7};
cout << "\n Result: " << minSetSize(input1);
std::vector<int> input2 = {7, 7, 7, 7, 7, 7};
cout << "\n Result: " << minSetSize(input2);
std::vector<int> input3 = {9, 77, 63, 22, 92, 9, 14, 54, 8, 38, 18, 19, 38, 68, 58, 19};
cout << "\n Result: " << minSetSize(input3);
// cout<<"\n Size of Input: "<<input.size();
return 0;
}
|
[
"shrikant200@gmail.com"
] |
shrikant200@gmail.com
|
7d7598898c8b3c04621809639c48717b9068b925
|
27f3ddc8ff6f5994fa1c0377dfbb0b7559f6aa90
|
/course1/algorithms/5_graphs/L_strong.cpp
|
b062f7fa98ea7acf3c972d99149e3020293d3436
|
[] |
no_license
|
vlad-mk/ifmo-kt
|
8240d6e9be6aeffc2eb5287198a367c6e23d4f4c
|
7481e2977dc986339920fd0cc69b360bcfa3d072
|
refs/heads/master
| 2023-07-03T21:01:43.823212
| 2019-01-12T06:11:10
| 2019-01-12T06:11:10
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,630
|
cpp
|
#include <cstdio>
#include <vector>
#include <algorithm>
using namespace std;
FILE *fin = fopen("strong.in", "r");
FILE *fout = fopen("strong.out", "w");
const int MAXN = 20000 + 1;
int n, m;
vector<int> g[MAXN], gr[MAXN];
vector<char> used;
vector<int> order, component, answer;
int counter = 0;
void dfs1 (int v) {
used[v] = true;
for (size_t i = 0; i < g[v].size(); ++i){
if (!used[g[v][i]]){
dfs1(g[v][i]);
}
}
order.push_back(v);
}
void dfs2 (int v) {
used[v] = true;
component.push_back(v);
for (size_t i = 0; i < gr[v].size(); ++i){
if (!used[gr[v][i]]){
dfs2 (gr[v][i]);
}
}
}
int main(int argc, char **argv) {
fscanf(fin, "%d %d", &n, &m);
answer.assign(n, 0);
for(int i = 0, v1, v2; i < m; i++) {
fscanf(fin, "%d %d", &v1, &v2);
v1--; v2--;
g[v1].push_back(v2);
gr[v2].push_back(v1);
}
used.assign(n, false);
for (int i = 0; i < n; ++i)
if (!used[i]){
dfs1(i);
}
used.assign(n, false);
for (int i = 0; i < n; ++i) {
int v = order[n-1-i];
if (!used[v]) {
dfs2(v);
if(component.size() > 0){
counter++;
for(size_t j = 0; j < component.size(); j++){
answer[component[j]] = counter;
}
}
component.clear();
}
}
fprintf(fout, "%d\n", counter);
for (int i = 0; i < n; ++i) {
fprintf(fout, "%d ", answer[i]);
}
fprintf(fout, "\n");
fclose(fin);
fclose(fout);
}
|
[
"egormkn@yandex.ru"
] |
egormkn@yandex.ru
|
f341ff88ef3dc5883f65135b2eca02023597cc15
|
768316ed72470715e641fda62a9166b610b27350
|
/05-CodeChef-Challenge/103--Art in Digital Age.cpp
|
a15a5e53544022cc0878f8d938d3b626be5a54ee
|
[] |
no_license
|
dhnesh12/codechef-solutions
|
41113bb5922156888d9e57fdc35df89246e194f7
|
55bc7a69f76306bc0c3694180195c149cf951fb6
|
refs/heads/master
| 2023-03-31T15:42:04.649785
| 2021-04-06T05:38:38
| 2021-04-06T05:38:38
| 355,063,355
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 4,837
|
cpp
|
#include <iostream>
#include <iomanip>
#include <vector>
#include <algorithm>
#include <cmath>
#include <string>
#include <map>
#include <unordered_map>
#include <set>
#include <unordered_set>
#include <bitset>
#include <sstream>
#include <deque>
#include <queue>
#include <complex>
#include <random>
#include <cassert>
#include <chrono>
using namespace std;
#define DEBUG
#define FAST ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0)
#define FIXED cout << fixed << setprecision(12)
#define int long long
#define ll long long
#define ld long double
#define pii pair<int, int>
#define pll pair<ll, ll>
#define graph vector<vector<int>>
#define pb push_back
#define pf push_front
#define popb pop_back
#define popf pop_front
#define f first
#define s second
#define hashmap unordered_map
#define hashset unordered_set
#define eps 1e-9
#define mod 1000000007
#define inf 3000000000000000007ll
#define sz(a) signed((a).size())
#define all(a) (a).begin(), (a).end()
#define rall(a) (a).rbegin(), (a).rend()
#ifdef DEBUG
mt19937 gen(857204);
#else
mt19937 gen(chrono::high_resolution_clock::now().time_since_epoch().count());
#endif
#ifdef DEBUG
template<class T> T to_dbg(T x) { return x; }
template<class T, class U> string to_dbg(pair<T, U> p) {
stringstream ss;
ss << '{' << p.f << ',' << p.s << '}';
return ss.str();
}
string to_dbg(string s) { return "\"" + s + "\""; }
template<class It> string to_dbg(It begin, It end, string d = "") {
stringstream ss;
ss << '{';
if (begin != end) ss << to_dbg(*begin++);
while (begin != end)
ss << "," << d << to_dbg(*begin++);
ss << '}';
return ss.str();
}
template<class T> string to_dbg(vector<T> a) { return to_dbg(all(a)); }
template<class T> string to_dbg(set<T> a) { return to_dbg(all(a)); }
template<class T> string to_dbg(hashset<T> a) { return to_dbg(all(a)); }
template<class T, class U> string to_dbg(map<T, U> a) { return to_dbg(all(a), "\n"); }
template<class T, class U> string to_dbg(hashmap<T, U> a) { return to_dbg(all(a), "\n"); }
template<class T> void dbgout(T x) { cout << to_dbg(x) << endl; }
template<class T, class... U>
void dbgout(T t, U... u) {
cout << to_dbg(t) << " ";
dbgout(u...);
}
#define dbg(...) cout << "[" << #__VA_ARGS__ << "] = ", dbgout(__VA_ARGS__)
#else
#define dbg(...) 0
#endif
template<class T, class U> inline bool chmax(T &x, U y) { return x < y ? x = y, 1 : 0; }
template<class T, class U> inline bool chmin(T &x, U y) { return x > y ? x = y, 1 : 0; }
template<class T> inline void sort(T &a) { sort(all(a)); }
template<class T> inline void rsort(T &a) { sort(rall(a)); }
template<class T> inline void reverse(T &a) { reverse(all(a)); }
template<class T, class U> inline istream& operator>>(istream& str, pair<T, U> &p) { return str >> p.f >> p.s; }
template<class T> inline istream& operator>>(istream& str, vector<T> &a) { for (auto &i : a) str >> i; return str; }
template<class T> inline T sorted(T a) { sort(a); return a; }
void read() {} void print() {} void println() { cout << '\n'; }
template<class T, class ...U> void read(T &x, U& ... u) { cin >> x; read(u...); }
template<class T, class ...U> void print(const T &x, const U& ... u) { cout << x; print(u...); }
template<class T, class ...U> void println(const T &x, const U& ... u) { cout << x; println(u...); }
const int N = 1200;
int a[N][N], mark[N][N];
int Check(int x,int y,int l,int r) {
for (int i = l; i <= r; i++) if (a[i][y] == 0 || mark[i][y]) return 0;
for (int i = l; i <= r; i++) if (a[i][y] != a[i][x]) return 1;
return 2;
}
void Fill(int l,int r,int j)
{
for (int i = l; i <= r; i++)
mark[i][j] = 1;
}
vector<int> Re[5];
main() {
//FAST;
int n; cin >> n;
for(int i = 1; i <= n; i++) for(int j = 1; j <= n; j++) cin >> a[i][j];
for(int i = 1; i <= n; i++) for(int j = 1; j <= n; j++) {
if (mark[i][j] || !a[i][j]) continue;
mark[i][j] = 1;
int J = j;
while (J < n && a[i][J + 1] == a[i][j]) J++, mark[i][J] = 1;
int I = i;
while (I < n)
{
bool flag = 0;
for(int u = j; u <= J; u++) if (a[i][j] != a[I + 1][u]) {flag = 1; break;}
if (flag) break;
for(int u = j; u <= J; u++) mark[I][u] = 1;
I++;
}
//cout << i << " " << I << " " << j << " " << J << "\n";
for(int x = i; x <= I; x++) for(int y = j; y <= J; y++) {
mark[x][y] = 1;
}
//dbg(i, j);
Re[0].push_back(a[i][j]);
Re[1].push_back(i);
Re[2].push_back(I);
Re[3].push_back(j);
Re[4].push_back(J);
}
cout << Re[0].size() << "\n";
for (int i = 0; i < Re[0].size(); i++)
cout << Re[0][i] << " " << Re[1][i] << " " << Re[2][i] << " " << Re[3][i] << " " << Re[4][i] << "\n";
return 0;
}
|
[
"dhneshwod@gmail.com"
] |
dhneshwod@gmail.com
|
7ae1fe8a5872b203664dc1f31a0563069113810e
|
8cf763c4c29db100d15f2560953c6e6cbe7a5fd4
|
/src/qt/qtbase/src/testlib/qxunittestlogger.cpp
|
e98ddb5e4ff440e82cbcaaf6604994b068f32b52
|
[
"LGPL-2.0-or-later",
"LGPL-2.1-only",
"GFDL-1.3-only",
"Qt-LGPL-exception-1.1",
"LicenseRef-scancode-digia-qt-commercial",
"LGPL-3.0-only",
"GPL-3.0-only",
"LicenseRef-scancode-digia-qt-preview",
"LGPL-2.1-or-later",
"GPL-1.0-or-later",
"LicenseRef-scancode-unknown-license-reference",
"GPL-2.0-only",
"BSD-3-Clause"
] |
permissive
|
chihlee/phantomjs
|
69d6bbbf1c9199a78e82ae44af072aca19c139c3
|
644e0b3a6c9c16bcc6f7ce2c24274bf7d764f53c
|
refs/heads/master
| 2021-01-19T13:49:41.265514
| 2018-06-15T22:48:11
| 2018-06-15T22:48:11
| 82,420,380
| 0
| 0
|
BSD-3-Clause
| 2018-06-15T22:48:12
| 2017-02-18T22:34:48
|
C++
|
UTF-8
|
C++
| false
| false
| 11,384
|
cpp
|
/****************************************************************************
**
** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of the QtTest module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL21$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://qt.digia.com/licensing. For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 or version 3 as published by the Free
** Software Foundation and appearing in the file LICENSE.LGPLv21 and
** LICENSE.LGPLv3 included in the packaging of this file. Please review the
** following information to ensure the GNU Lesser General Public License
** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include <QtTest/private/qxunittestlogger_p.h>
#include <QtTest/private/qtestelement_p.h>
#include <QtTest/private/qtestxunitstreamer_p.h>
#include <QtTest/qtestcase.h>
#include <QtTest/private/qtestresult_p.h>
#include <QtTest/private/qbenchmark_p.h>
#ifdef min // windows.h without NOMINMAX is included by the benchmark headers.
# undef min
#endif
#ifdef max
# undef max
#endif
#include <QtCore/qlibraryinfo.h>
#include <string.h>
QT_BEGIN_NAMESPACE
QXunitTestLogger::QXunitTestLogger(const char *filename)
: QAbstractTestLogger(filename)
, listOfTestcases(0)
, currentLogElement(0)
, errorLogElement(0)
, logFormatter(0)
, testCounter(0)
, failureCounter(0)
, errorCounter(0)
{
}
QXunitTestLogger::~QXunitTestLogger()
{
delete currentLogElement;
delete logFormatter;
}
void QXunitTestLogger::startLogging()
{
QAbstractTestLogger::startLogging();
logFormatter = new QTestXunitStreamer(this);
delete errorLogElement;
errorLogElement = new QTestElement(QTest::LET_SystemError);
}
void QXunitTestLogger::stopLogging()
{
QTestElement *iterator = listOfTestcases;
char buf[10];
currentLogElement = new QTestElement(QTest::LET_TestSuite);
currentLogElement->addAttribute(QTest::AI_Name, QTestResult::currentTestObjectName());
qsnprintf(buf, sizeof(buf), "%i", testCounter);
currentLogElement->addAttribute(QTest::AI_Tests, buf);
qsnprintf(buf, sizeof(buf), "%i", failureCounter);
currentLogElement->addAttribute(QTest::AI_Failures, buf);
qsnprintf(buf, sizeof(buf), "%i", errorCounter);
currentLogElement->addAttribute(QTest::AI_Errors, buf);
QTestElement *property;
QTestElement *properties = new QTestElement(QTest::LET_Properties);
property = new QTestElement(QTest::LET_Property);
property->addAttribute(QTest::AI_Name, "QTestVersion");
property->addAttribute(QTest::AI_PropertyValue, QTEST_VERSION_STR);
properties->addLogElement(property);
property = new QTestElement(QTest::LET_Property);
property->addAttribute(QTest::AI_Name, "QtVersion");
property->addAttribute(QTest::AI_PropertyValue, qVersion());
properties->addLogElement(property);
property = new QTestElement(QTest::LET_Property);
property->addAttribute(QTest::AI_Name, "QtBuild");
property->addAttribute(QTest::AI_PropertyValue, QLibraryInfo::build());
properties->addLogElement(property);
currentLogElement->addLogElement(properties);
currentLogElement->addLogElement(iterator);
/* For correct indenting, make sure every testcase knows its parent */
QTestElement* testcase = iterator;
while (testcase) {
testcase->setParent(currentLogElement);
testcase = testcase->nextElement();
}
currentLogElement->addLogElement(errorLogElement);
QTestElement *it = currentLogElement;
logFormatter->output(it);
QAbstractTestLogger::stopLogging();
}
void QXunitTestLogger::enterTestFunction(const char *function)
{
currentLogElement = new QTestElement(QTest::LET_TestCase);
currentLogElement->addAttribute(QTest::AI_Name, function);
currentLogElement->addToList(&listOfTestcases);
++testCounter;
}
void QXunitTestLogger::leaveTestFunction()
{
}
void QXunitTestLogger::addIncident(IncidentTypes type, const char *description,
const char *file, int line)
{
const char *typeBuf = 0;
char buf[100];
switch (type) {
case QAbstractTestLogger::XPass:
++failureCounter;
typeBuf = "xpass";
break;
case QAbstractTestLogger::Pass:
typeBuf = "pass";
break;
case QAbstractTestLogger::XFail:
typeBuf = "xfail";
break;
case QAbstractTestLogger::Fail:
++failureCounter;
typeBuf = "fail";
break;
case QAbstractTestLogger::BlacklistedPass:
typeBuf = "bpass";
break;
case QAbstractTestLogger::BlacklistedFail:
++failureCounter;
typeBuf = "bfail";
break;
default:
typeBuf = "??????";
break;
}
if (type == QAbstractTestLogger::Fail || type == QAbstractTestLogger::XPass) {
QTestElement *failureElement = new QTestElement(QTest::LET_Failure);
failureElement->addAttribute(QTest::AI_Result, typeBuf);
if (file)
failureElement->addAttribute(QTest::AI_File, file);
else
failureElement->addAttribute(QTest::AI_File, "");
qsnprintf(buf, sizeof(buf), "%i", line);
failureElement->addAttribute(QTest::AI_Line, buf);
failureElement->addAttribute(QTest::AI_Description, description);
addTag(failureElement);
currentLogElement->addLogElement(failureElement);
}
/*
Only one result can be shown for the whole testfunction.
Check if we currently have a result, and if so, overwrite it
iff the new result is worse.
*/
QTestElementAttribute* resultAttr =
const_cast<QTestElementAttribute*>(currentLogElement->attribute(QTest::AI_Result));
if (resultAttr) {
const char* oldResult = resultAttr->value();
bool overwrite = false;
if (!strcmp(oldResult, "pass")) {
overwrite = true;
}
else if (!strcmp(oldResult, "bpass")) {
overwrite = (type == QAbstractTestLogger::XPass || type == QAbstractTestLogger::Fail) || (type == QAbstractTestLogger::XFail)
|| (type == QAbstractTestLogger::BlacklistedFail);
}
else if (!strcmp(oldResult, "bfail")) {
overwrite = (type == QAbstractTestLogger::XPass || type == QAbstractTestLogger::Fail) || (type == QAbstractTestLogger::XFail);
}
else if (!strcmp(oldResult, "xfail")) {
overwrite = (type == QAbstractTestLogger::XPass || type == QAbstractTestLogger::Fail);
}
else if (!strcmp(oldResult, "xpass")) {
overwrite = (type == QAbstractTestLogger::Fail);
}
if (overwrite) {
resultAttr->setPair(QTest::AI_Result, typeBuf);
}
}
else {
currentLogElement->addAttribute(QTest::AI_Result, typeBuf);
}
if (file)
currentLogElement->addAttribute(QTest::AI_File, file);
else
currentLogElement->addAttribute(QTest::AI_File, "");
qsnprintf(buf, sizeof(buf), "%i", line);
currentLogElement->addAttribute(QTest::AI_Line, buf);
/*
Since XFAIL does not add a failure to the testlog in xunitxml, add a message, so we still
have some information about the expected failure.
*/
if (type == QAbstractTestLogger::XFail) {
QXunitTestLogger::addMessage(QAbstractTestLogger::Info, QString::fromUtf8(description), file, line);
}
}
void QXunitTestLogger::addBenchmarkResult(const QBenchmarkResult &result)
{
QTestElement *benchmarkElement = new QTestElement(QTest::LET_Benchmark);
benchmarkElement->addAttribute(
QTest::AI_Metric,
QTest::benchmarkMetricName(QBenchmarkTestMethodData::current->result.metric));
benchmarkElement->addAttribute(QTest::AI_Tag, result.context.tag.toUtf8().data());
const qreal valuePerIteration = qreal(result.value) / qreal(result.iterations);
benchmarkElement->addAttribute(QTest::AI_Value, QByteArray::number(valuePerIteration).constData());
char buf[100];
qsnprintf(buf, sizeof(buf), "%i", result.iterations);
benchmarkElement->addAttribute(QTest::AI_Iterations, buf);
currentLogElement->addLogElement(benchmarkElement);
}
void QXunitTestLogger::addTag(QTestElement* element)
{
const char *tag = QTestResult::currentDataTag();
const char *gtag = QTestResult::currentGlobalDataTag();
const char *filler = (tag && gtag) ? ":" : "";
if ((!tag || !tag[0]) && (!gtag || !gtag[0])) {
return;
}
if (!tag) {
tag = "";
}
if (!gtag) {
gtag = "";
}
QTestCharBuffer buf;
QTest::qt_asprintf(&buf, "%s%s%s", gtag, filler, tag);
element->addAttribute(QTest::AI_Tag, buf.constData());
}
void QXunitTestLogger::addMessage(MessageTypes type, const QString &message, const char *file, int line)
{
QTestElement *errorElement = new QTestElement(QTest::LET_Error);
const char *typeBuf = 0;
switch (type) {
case QAbstractTestLogger::Warn:
typeBuf = "warn";
break;
case QAbstractTestLogger::QSystem:
typeBuf = "system";
break;
case QAbstractTestLogger::QDebug:
typeBuf = "qdebug";
break;
case QAbstractTestLogger::QWarning:
typeBuf = "qwarn";
break;
case QAbstractTestLogger::QFatal:
typeBuf = "qfatal";
break;
case QAbstractTestLogger::Skip:
typeBuf = "skip";
break;
case QAbstractTestLogger::Info:
typeBuf = "info";
break;
default:
typeBuf = "??????";
break;
}
errorElement->addAttribute(QTest::AI_Type, typeBuf);
errorElement->addAttribute(QTest::AI_Description, message.toUtf8().constData());
addTag(errorElement);
if (file)
errorElement->addAttribute(QTest::AI_File, file);
else
errorElement->addAttribute(QTest::AI_File, "");
char buf[100];
qsnprintf(buf, sizeof(buf), "%i", line);
errorElement->addAttribute(QTest::AI_Line, buf);
currentLogElement->addLogElement(errorElement);
++errorCounter;
// Also add the message to the system error log (i.e. stderr), if one exists
if (errorLogElement) {
QTestElement *systemErrorElement = new QTestElement(QTest::LET_Error);
systemErrorElement->addAttribute(QTest::AI_Description, message.toUtf8().constData());
errorLogElement->addLogElement(systemErrorElement);
}
}
QT_END_NAMESPACE
|
[
"ariya.hidayat@gmail.com"
] |
ariya.hidayat@gmail.com
|
82b5bf759fd5720cae6fad5fa1432f473079ccf7
|
641fa8341d8c436ad24945bcbf8e7d7d1dd7dbb2
|
/content/browser/devtools/protocol/target_handler.cc
|
254a4ac1f18d2bf98d56f8994177e9dab1d841a7
|
[
"BSD-3-Clause"
] |
permissive
|
massnetwork/mass-browser
|
7de0dfc541cbac00ffa7308541394bac1e945b76
|
67526da9358734698c067b7775be491423884339
|
refs/heads/master
| 2022-12-07T09:01:31.027715
| 2017-01-19T14:29:18
| 2017-01-19T14:29:18
| 73,799,690
| 4
| 4
|
BSD-3-Clause
| 2022-11-26T11:53:23
| 2016-11-15T09:49:29
| null |
UTF-8
|
C++
| false
| false
| 15,389
|
cc
|
// Copyright 2016 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.
#include "content/browser/devtools/protocol/target_handler.h"
#include "content/browser/devtools/devtools_manager.h"
#include "content/browser/devtools/service_worker_devtools_agent_host.h"
#include "content/browser/frame_host/frame_tree.h"
#include "content/browser/frame_host/frame_tree_node.h"
#include "content/browser/frame_host/render_frame_host_impl.h"
namespace content {
namespace devtools {
namespace target {
using Response = DevToolsProtocolClient::Response;
namespace {
using ScopeAgentsMap =
std::map<GURL, std::unique_ptr<ServiceWorkerDevToolsAgentHost::List>>;
void GetMatchingHostsByScopeMap(
const ServiceWorkerDevToolsAgentHost::List& agent_hosts,
const std::set<GURL>& urls,
ScopeAgentsMap* scope_agents_map) {
std::set<base::StringPiece> host_name_set;
for (const GURL& url : urls)
host_name_set.insert(url.host_piece());
for (const auto& host : agent_hosts) {
if (host_name_set.find(host->scope().host_piece()) == host_name_set.end())
continue;
const auto& it = scope_agents_map->find(host->scope());
if (it == scope_agents_map->end()) {
std::unique_ptr<ServiceWorkerDevToolsAgentHost::List> new_list(
new ServiceWorkerDevToolsAgentHost::List());
new_list->push_back(host);
(*scope_agents_map)[host->scope()] = std::move(new_list);
} else {
it->second->push_back(host);
}
}
}
void AddEligibleHosts(const ServiceWorkerDevToolsAgentHost::List& list,
ServiceWorkerDevToolsAgentHost::Map* result) {
base::Time last_installed_time;
base::Time last_doomed_time;
for (const auto& host : list) {
if (host->version_installed_time() > last_installed_time)
last_installed_time = host->version_installed_time();
if (host->version_doomed_time() > last_doomed_time)
last_doomed_time = host->version_doomed_time();
}
for (const auto& host : list) {
// We don't attech old redundant Service Workers when there is newer
// installed Service Worker.
if (host->version_doomed_time().is_null() ||
(last_installed_time < last_doomed_time &&
last_doomed_time == host->version_doomed_time())) {
(*result)[host->GetId()] = host;
}
}
}
ServiceWorkerDevToolsAgentHost::Map GetMatchingServiceWorkers(
BrowserContext* browser_context,
const std::set<GURL>& urls) {
ServiceWorkerDevToolsAgentHost::Map result;
if (!browser_context)
return result;
ServiceWorkerDevToolsAgentHost::List agent_hosts;
ServiceWorkerDevToolsManager::GetInstance()
->AddAllAgentHostsForBrowserContext(browser_context, &agent_hosts);
ScopeAgentsMap scope_agents_map;
GetMatchingHostsByScopeMap(agent_hosts, urls, &scope_agents_map);
for (const auto& it : scope_agents_map)
AddEligibleHosts(*it.second.get(), &result);
return result;
}
scoped_refptr<TargetInfo> CreateInfo(DevToolsAgentHost* host) {
return TargetInfo::Create()
->set_target_id(host->GetId())
->set_title(host->GetTitle())
->set_url(host->GetURL().spec())
->set_type(host->GetType());
}
} // namespace
TargetHandler::TargetHandler()
: discover_(false),
auto_attach_(false),
wait_for_debugger_on_start_(false),
attach_to_frames_(false),
render_frame_host_(nullptr) {
}
TargetHandler::~TargetHandler() {
Detached();
}
void TargetHandler::SetRenderFrameHost(RenderFrameHostImpl* render_frame_host) {
render_frame_host_ = render_frame_host;
UpdateFrames();
}
void TargetHandler::SetClient(std::unique_ptr<Client> client) {
client_.swap(client);
}
void TargetHandler::Detached() {
SetAutoAttach(false, false);
SetDiscoverTargets(false);
for (const auto& id_host : attached_hosts_)
id_host.second->DetachClient(this);
attached_hosts_.clear();
}
void TargetHandler::UpdateServiceWorkers() {
UpdateServiceWorkers(false);
}
void TargetHandler::UpdateFrames() {
if (!auto_attach_ || !attach_to_frames_)
return;
HostsMap new_hosts;
if (render_frame_host_) {
FrameTreeNode* root = render_frame_host_->frame_tree_node();
std::queue<FrameTreeNode*> queue;
queue.push(root);
while (!queue.empty()) {
FrameTreeNode* node = queue.front();
queue.pop();
bool cross_process = node->current_frame_host()->IsCrossProcessSubframe();
if (node != root && cross_process) {
scoped_refptr<DevToolsAgentHost> new_host =
DevToolsAgentHost::GetOrCreateFor(node->current_frame_host());
new_hosts[new_host->GetId()] = new_host;
} else {
for (size_t i = 0; i < node->child_count(); ++i)
queue.push(node->child_at(i));
}
}
}
// TODO(dgozman): support wait_for_debugger_on_start_.
ReattachTargetsOfType(new_hosts, DevToolsAgentHost::kTypeFrame, false);
}
void TargetHandler::UpdateServiceWorkers(bool waiting_for_debugger) {
if (!auto_attach_)
return;
frame_urls_.clear();
BrowserContext* browser_context = nullptr;
if (render_frame_host_) {
// TODO(dgozman): do not traverse inside cross-process subframes.
for (FrameTreeNode* node :
render_frame_host_->frame_tree_node()->frame_tree()->Nodes()) {
frame_urls_.insert(node->current_url());
}
browser_context = render_frame_host_->GetProcess()->GetBrowserContext();
}
auto matching = GetMatchingServiceWorkers(browser_context, frame_urls_);
HostsMap new_hosts;
for (const auto& pair : matching)
new_hosts[pair.first] = pair.second;
ReattachTargetsOfType(
new_hosts, DevToolsAgentHost::kTypeServiceWorker, waiting_for_debugger);
}
void TargetHandler::ReattachTargetsOfType(
const HostsMap& new_hosts,
const std::string& type,
bool waiting_for_debugger) {
HostsMap old_hosts = attached_hosts_;
for (const auto& pair : old_hosts) {
if (pair.second->GetType() == type &&
new_hosts.find(pair.first) == new_hosts.end()) {
DetachFromTargetInternal(pair.second.get());
}
}
for (const auto& pair : new_hosts) {
if (old_hosts.find(pair.first) == old_hosts.end())
AttachToTargetInternal(pair.second.get(), waiting_for_debugger);
}
}
void TargetHandler::TargetCreatedInternal(DevToolsAgentHost* host) {
if (reported_hosts_.find(host->GetId()) != reported_hosts_.end())
return;
client_->TargetCreated(
TargetCreatedParams::Create()->set_target_info(CreateInfo(host)));
reported_hosts_[host->GetId()] = host;
}
void TargetHandler::TargetDestroyedInternal(
DevToolsAgentHost* host) {
auto it = reported_hosts_.find(host->GetId());
if (it == reported_hosts_.end())
return;
client_->TargetDestroyed(TargetDestroyedParams::Create()
->set_target_id(host->GetId()));
reported_hosts_.erase(it);
}
bool TargetHandler::AttachToTargetInternal(
DevToolsAgentHost* host, bool waiting_for_debugger) {
if (!host->AttachClient(this))
return false;
attached_hosts_[host->GetId()] = host;
client_->AttachedToTarget(AttachedToTargetParams::Create()
->set_target_info(CreateInfo(host))
->set_waiting_for_debugger(waiting_for_debugger));
return true;
}
void TargetHandler::DetachFromTargetInternal(DevToolsAgentHost* host) {
auto it = attached_hosts_.find(host->GetId());
if (it == attached_hosts_.end())
return;
host->DetachClient(this);
client_->DetachedFromTarget(DetachedFromTargetParams::Create()->
set_target_id(host->GetId()));
attached_hosts_.erase(it);
}
// ----------------- Protocol ----------------------
Response TargetHandler::SetDiscoverTargets(bool discover) {
if (discover_ == discover)
return Response::OK();
discover_ = discover;
if (discover_) {
DevToolsAgentHost::AddObserver(this);
} else {
DevToolsAgentHost::RemoveObserver(this);
RawHostsMap copy = reported_hosts_;
for (const auto& id_host : copy)
TargetDestroyedInternal(id_host.second);
}
return Response::OK();
}
Response TargetHandler::SetAutoAttach(
bool auto_attach, bool wait_for_debugger_on_start) {
wait_for_debugger_on_start_ = wait_for_debugger_on_start;
if (auto_attach_ == auto_attach)
return Response::FallThrough();
auto_attach_ = auto_attach;
if (auto_attach_) {
ServiceWorkerDevToolsManager::GetInstance()->AddObserver(this);
UpdateServiceWorkers();
UpdateFrames();
} else {
ServiceWorkerDevToolsManager::GetInstance()->RemoveObserver(this);
HostsMap empty;
ReattachTargetsOfType(empty, DevToolsAgentHost::kTypeFrame, false);
ReattachTargetsOfType(empty, DevToolsAgentHost::kTypeServiceWorker, false);
}
return Response::FallThrough();
}
Response TargetHandler::SetAttachToFrames(bool value) {
if (attach_to_frames_ == value)
return Response::OK();
attach_to_frames_ = value;
if (attach_to_frames_) {
UpdateFrames();
} else {
HostsMap empty;
ReattachTargetsOfType(empty, DevToolsAgentHost::kTypeFrame, false);
}
return Response::OK();
}
Response TargetHandler::SetRemoteLocations(
const std::vector<std::unique_ptr<base::DictionaryValue>>& locations) {
return Response::ServerError("Not supported");
}
Response TargetHandler::AttachToTarget(const std::string& target_id,
bool* out_success) {
// TODO(dgozman): only allow reported hosts.
scoped_refptr<DevToolsAgentHost> agent_host =
DevToolsAgentHost::GetForId(target_id);
if (!agent_host)
return Response::ServerError("No target with given id found");
*out_success = AttachToTargetInternal(agent_host.get(), false);
return Response::OK();
}
Response TargetHandler::DetachFromTarget(const std::string& target_id) {
auto it = attached_hosts_.find(target_id);
if (it == attached_hosts_.end())
return Response::InternalError("Not attached to the target");
DevToolsAgentHost* agent_host = it->second.get();
DetachFromTargetInternal(agent_host);
return Response::OK();
}
Response TargetHandler::SendMessageToTarget(
const std::string& target_id,
const std::string& message) {
auto it = attached_hosts_.find(target_id);
if (it == attached_hosts_.end())
return Response::FallThrough();
it->second->DispatchProtocolMessage(this, message);
return Response::OK();
}
Response TargetHandler::GetTargetInfo(
const std::string& target_id,
scoped_refptr<TargetInfo>* target_info) {
// TODO(dgozman): only allow reported hosts.
scoped_refptr<DevToolsAgentHost> agent_host(
DevToolsAgentHost::GetForId(target_id));
if (!agent_host)
return Response::InvalidParams("No target with given id found");
*target_info = CreateInfo(agent_host.get());
return Response::OK();
}
Response TargetHandler::ActivateTarget(const std::string& target_id) {
// TODO(dgozman): only allow reported hosts.
scoped_refptr<DevToolsAgentHost> agent_host(
DevToolsAgentHost::GetForId(target_id));
if (!agent_host)
return Response::InvalidParams("No target with given id found");
agent_host->Activate();
return Response::OK();
}
Response TargetHandler::CloseTarget(const std::string& target_id,
bool* out_success) {
scoped_refptr<DevToolsAgentHost> agent_host =
DevToolsAgentHost::GetForId(target_id);
if (!agent_host)
return Response::ServerError("No target with given id found");
*out_success = agent_host->Close();
return Response::OK();
}
Response TargetHandler::CreateBrowserContext(std::string* out_context_id) {
return Response::ServerError("Not supported");
}
Response TargetHandler::DisposeBrowserContext(const std::string& context_id,
bool* out_success) {
return Response::ServerError("Not supported");
}
Response TargetHandler::CreateTarget(const std::string& url,
const int* width,
const int* height,
const std::string* context_id,
std::string* out_target_id) {
DevToolsManagerDelegate* delegate =
DevToolsManager::GetInstance()->delegate();
if (!delegate)
return Response::ServerError("Not supported");
scoped_refptr<content::DevToolsAgentHost> agent_host =
delegate->CreateNewTarget(GURL(url));
if (!agent_host)
return Response::ServerError("Not supported");
*out_target_id = agent_host->GetId();
return Response::OK();
}
Response TargetHandler::GetTargets(
std::vector<scoped_refptr<TargetInfo>>* target_infos) {
for (const auto& host : DevToolsAgentHost::GetOrCreateAll())
target_infos->push_back(CreateInfo(host.get()));
return Response::OK();
}
// ---------------- DevToolsAgentHostClient ----------------
void TargetHandler::DispatchProtocolMessage(
DevToolsAgentHost* host,
const std::string& message) {
auto it = attached_hosts_.find(host->GetId());
if (it == attached_hosts_.end())
return; // Already disconnected.
client_->ReceivedMessageFromTarget(
ReceivedMessageFromTargetParams::Create()->
set_target_id(host->GetId())->
set_message(message));
}
void TargetHandler::AgentHostClosed(
DevToolsAgentHost* host,
bool replaced_with_another_client) {
client_->DetachedFromTarget(DetachedFromTargetParams::Create()->
set_target_id(host->GetId()));
attached_hosts_.erase(host->GetId());
}
// -------------- DevToolsAgentHostObserver -----------------
bool TargetHandler::ShouldForceDevToolsAgentHostCreation() {
return true;
}
void TargetHandler::DevToolsAgentHostCreated(DevToolsAgentHost* agent_host) {
DCHECK(attached_hosts_.find(agent_host->GetId()) == attached_hosts_.end());
TargetCreatedInternal(agent_host);
}
void TargetHandler::DevToolsAgentHostDestroyed(DevToolsAgentHost* agent_host) {
DCHECK(attached_hosts_.find(agent_host->GetId()) == attached_hosts_.end());
TargetDestroyedInternal(agent_host);
}
// -------- ServiceWorkerDevToolsManager::Observer ----------
void TargetHandler::WorkerCreated(
ServiceWorkerDevToolsAgentHost* host) {
BrowserContext* browser_context = nullptr;
if (render_frame_host_)
browser_context = render_frame_host_->GetProcess()->GetBrowserContext();
auto hosts = GetMatchingServiceWorkers(browser_context, frame_urls_);
if (hosts.find(host->GetId()) != hosts.end() && !host->IsAttached() &&
!host->IsPausedForDebugOnStart() && wait_for_debugger_on_start_) {
host->PauseForDebugOnStart();
}
}
void TargetHandler::WorkerReadyForInspection(
ServiceWorkerDevToolsAgentHost* host) {
if (ServiceWorkerDevToolsManager::GetInstance()
->debug_service_worker_on_start()) {
// When debug_service_worker_on_start is true, a new DevTools window will
// be opened in ServiceWorkerDevToolsManager::WorkerReadyForInspection.
return;
}
UpdateServiceWorkers(host->IsPausedForDebugOnStart());
}
void TargetHandler::WorkerVersionInstalled(
ServiceWorkerDevToolsAgentHost* host) {
UpdateServiceWorkers();
}
void TargetHandler::WorkerVersionDoomed(
ServiceWorkerDevToolsAgentHost* host) {
UpdateServiceWorkers();
}
void TargetHandler::WorkerDestroyed(
ServiceWorkerDevToolsAgentHost* host) {
UpdateServiceWorkers();
}
} // namespace target
} // namespace devtools
} // namespace content
|
[
"xElvis89x@gmail.com"
] |
xElvis89x@gmail.com
|
20eb356fd6461a3addd481ef0b18f6a2f516b756
|
53bc877bb575aedaf61920520959176c2392deff
|
/Chapter 13.cpp
|
96f83857e1562fea87c56b3b86d79e73d17c1d3d
|
[] |
no_license
|
jchallenger1/MyCplusplus-primer-solutions
|
70383e3b9ab5056d395e6bb317a728da209eb0c1
|
66856e138aa09d84d14127d80aab1b32da960dd2
|
refs/heads/master
| 2023-02-03T22:26:55.566372
| 2018-01-13T23:00:38
| 2018-01-13T23:00:38
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 32,346
|
cpp
|
//------------------------------------------------------------------------------------EXERCISE 13.5
/*
class HasPtr {
public:
HasPtr(const std::string &s = std::string()) : ps(new std::string(s)), i(0) { };
HasPtr(const HasPtr& temp) : ps(temp.ps), i(temp.i) {};
private:
std::string *ps;
int i;
};
HasPtr(const HasPtr& temp) : ps(temp.ps), i(temp.i) {};
//COPY OPERATOR
//USED WITH
* HasPtr m(x);
*/
//------------------------------------------------------------------------------------EXERCISE 13.8
/*
HasPtr& operator=(const HasPtr& temp) { this->ps = temp.ps; this->i = temp.i; return *this; }
//COPY ASSIGNMENT OPERATOR
//USED WITH
HasPtr m();
HasPtr x;
* x = m;
*/
//------------------------------------------------------------------------------------EXERCISE 13.11
//~HasPtr() {};
//------------------------------------------------------------------------------------EXERCISE -- HOW THESE OPERATORS WORK
/*
struct numbered {
numbered() : mysn("D") {}
numbered(numbered& temp) { temp.mysn = "CA"; this->mysn = "CB"; }//functions use copy constructors for their objects if they are not references, if they are they use the object directly.
numbered operator=(numbered& temp) { this->mysn = "BA"; temp.mysn = "BB"; cout << "CALLED" << endl; return *this; }//numbered is not a reference so it creates a new one via the a(b) copy constructor
string mysn;
};
void f(const numbered& s) { cout << s.mysn << endl; }
int main() {
numbered a, b = a, c = b;
numbered d;
d = a;
cout << d.mysn << endl;
cout << a.mysn << endl;
//f(a); f(b); f(c);
system("pause");
return 0;
}
*/
//------------------------------------------------------------------------------------EXERCISE 13.18
/*
class Employee {
public:
Employee() { unq++; };
Employee(const string& s) : name(s) { unq++; };
Employee operator=(const Employee& e) { name = e.name; unq++; };
Employee(const Employee& e) { name = e.name; unq++; };
int getNum() { return unq; };
private:
static int unq;
string name;
};
int Employee::unq = 0;
*/
//------------------------------------------------------------------------------------EXERCISE 13.22
/*
HasPtr& operator=(const HasPtr& temp) { this->i = temp.i; this->ps = new string(*(temp.ps)); return *this; };
HasPtr(const HasPtr& temp) :i(temp.i) { ps = new string(*(temp.ps)); };
~HasPtr() {delete ps;}
*/
//---------------------------------------------------------------------JUST TO KEEP INCASE
/*
class HasPtr {
public:
HasPtr(const std::string &s = std::string()) : ps(new std::string(s)), i(0) { };
HasPtr(const HasPtr& temp) : ps(temp.ps), i(temp.i) {};
HasPtr& operator=(const HasPtr& temp) { this->ps = temp.ps; this->i = temp.i; return *this; };
~HasPtr() {};
private:
std::string *ps;
int i;
};
struct myClass {
myClass() { std::cout << "myClass()" << std::endl; };
myClass(const myClass&) { std::cout << "myClass(const myClass&)" << std::endl; };
myClass operator=(const myClass& temp) { cout << "myClass(operator=)" << endl; return *this; };
~myClass() { cout << "~myClass" << endl; };
int m = 5;
};
*/
//------------------------------------------------------------------------------------EXERCISE 13.26
//SEE CHAPTER 12 FOR FULL STRBLOB.
/*
class StrBlob {
friend class StrBlobPtr;
public:
StrBlob() : strData(new vector<string>) {};
StrBlob(std::initializer_list<string> b) : strData(new vector<string>(b)) {};
StrBlob operator=(const StrBlob& temp) {
this->strData = std::make_shared<vector<string>>(new vector<string>(*(temp.strData)));
};
StrBlob(const StrBlob& temp) {
vector<string> x =*(temp.strData);
this->strData = std::make_shared<vector<string>>(x);
}
string popBack();
void pushBack(const string& t);
string front();
string back();
StrBlobPtr begin();
StrBlobPtr end();
private:
shared_ptr<vector<string>> strData;
void check(const int& integer, const string& message);
};
*/
//------------------------------------------------------------------------------------EXERCISE 13.27
/*
class HasPtr {
public:
HasPtr(const std::string &s = std::string()) : ps(new std::string(s)), i(0), use(new int(1)) {};
HasPtr(const HasPtr& temp);
HasPtr operator=(const HasPtr& temp);
~HasPtr();
private:
std::string *ps;
int i;
int* use;
};
HasPtr::HasPtr(const HasPtr& temp) : i(temp.i), use(temp.use), ps(temp.ps) {(*use)++; };
HasPtr HasPtr::operator=(const HasPtr& temp) {
(*use)--;
if (*use <= 0) {
delete ps;
delete use;
}
(*temp.use)++;
use = temp.use;
i = temp.i;
ps = temp.ps;
}
HasPtr::~HasPtr() {
--(*use);
if (*use >= 0) {
delete ps;
delete use;
}
}
*/
//------------------------------------------------------------------------------------EXERCISE 13.28
/*
class TreeNode {
public:
TreeNode() : value(""), count(0) { left = new TreeNode(); right = new TreeNode(); }
TreeNode(const TreeNode& temp) :value(temp.value), count(temp.count) {
left = temp.left;
right = temp.right;
}
TreeNode operator= (const TreeNode& temp) {
value = temp.value;
count = temp.count;
TreeNode* Templeft = temp.left;//we do this incase temp is equal to the left operand.
TreeNode* Tempright = temp.right;
delete left;
delete right;
left = Templeft;
right = Tempright;
return *this;
}
private:
std::string value;
int count;
TreeNode *left;
TreeNode *right;
};
class BinStrTree {
public:
BinStrTree() { root = new TreeNode(); };
BinStrTree(const BinStrTree& temp) : root(temp.root) {};
BinStrTree operator=(const BinStrTree& temp) {
TreeNode* tempRoot = temp.root;
delete root;
root = tempRoot;
return *this;
}
private:
TreeNode *root;
};
*/
//------------------------------------------------------------------------------------EXERCISE 13.30-13.31
//LAST IMPLENTATION(TO THIS CHAPTER) OF HASPTR
/*
#include <iostream>
#include <string>
#include <new>
#include <memory>
#include <vector>
#include <algorithm>
using std::string; using std::cout; using std::cin; using std::endl; using std::flush; using std::vector;
class HasPtr {
friend void swap(HasPtr& left, HasPtr& right);
public:
HasPtr(const std::string &s = std::string()) : ps(new std::string(s)), i(0), use(new int(1)) {};
HasPtr(const HasPtr& temp);
HasPtr& operator=(const HasPtr& temp);
bool operator<(const HasPtr& temp) const;
~HasPtr();
string& getString() const {
return *ps;
}
private:
std::string *ps;
int i;
int* use;
};
HasPtr::HasPtr(const HasPtr& temp) : i(temp.i), use(temp.use), ps(temp.ps) {(*use)++; };
HasPtr& HasPtr::operator=(const HasPtr& temp) {
auto* tempLeftPs = temp.ps;
int tempI = temp.i;
auto* tempLeftUse = temp.use;
(*use)--;
if (*use <= 0) {
delete ps;
delete use;
}
(*temp.use)++;
use = tempLeftUse;
i = tempI;
ps = tempLeftPs;
return *this;
}
bool HasPtr::operator<(const HasPtr& temp) const{
return ((this->ps->size()) < (temp.ps->size()) ? true : false);
}
HasPtr::~HasPtr() {
--(*use);
if (*use <= 0) {
delete ps;
delete use;
}
}
void swap(HasPtr& left, HasPtr& right) {
std::swap(left.i, right.i);
std::swap(left.ps, right.ps);
std::swap(left.use, right.use);
}
int main() {
//------------------------------------------------------------------------------------EXERCISE 13.30
//HasPtr HW("Hello World");
//HasPtr ME("xrdftchu");
//swap(HW, ME);
//cout << "Hello World :" << HW.getString() << "\nrandom:" << ME.getString() << endl;
//------------------------------------------------------------------------------------EXERCISE 13.31
vector<HasPtr> myHas({ HasPtr("Hello"),HasPtr("World"),HasPtr("unduefineeeed"),HasPtr("joke"),HasPtr("me") });
vector<HasPtr>::iterator begin = myHas.begin();
vector<HasPtr>::iterator end = myHas.end();
std::stable_sort(begin, end, [](const HasPtr& a, const HasPtr& b) { return a < b; });
vector<HasPtr>::iterator begin1 = myHas.begin();
vector<HasPtr>::iterator end1 = myHas.end();
std::for_each(begin1, end1, [](const HasPtr temp) {cout << temp.getString() << endl; });
system("pause");
return 0;
}
*/
//------------------------------------------------------------------------------------EXERCISE 13.34 && 13.36 && 13.37
/*
#pragma once
#ifndef EMAIL
#define EMAIL
#include <iostream>
#include <vector>
#include <string>
#include <set>
using std::vector; using std::endl; using std::set; using std::string;
class Folder;
class Message {
friend class Folder;
public:
explicit Message(const string& s = "") : contents(s) {};
Message(const Message& m);
Message& operator=(const Message& m);
~Message();
/////
void swap(Message& lhs, Message& rhs);
std::ostream& printFolders(std::ostream& os);
void save(Folder& fr);
void remove(Folder& fr);
private:
string contents;
set<Folder*> folders;
void addToFolders(const Message &m);
void removeFromFolders();
};
class Folder {
friend class Message;
public:
Folder() = default;
Folder(const string& a) : ID(a) {};
~Folder();
void addMsg(Message* ptr);
void remMsg(Message* ptr);
std::ostream& printMessages(std::ostream& os);
private:
string ID;
set<Message*> messages;
};
/////////////////////////////////////////////////////////////////////////////////////////////////////////
std::ostream& Folder::printMessages(std::ostream& os) {
for (Message* m : messages) {
os << m->contents << " ";
}
return os;
}
Folder::~Folder() {
for (Message* mesg : messages) {
delete mesg;
}
}
void Folder::addMsg(Message* ptr) {
ptr->save(*this);
}
void Folder::remMsg(Message* ptr) {
decltype(messages.end()) findMSG = messages.end();
for (auto begin = messages.begin(); begin != messages.end(); begin++) {
if ((**begin).contents == ptr->contents) {
findMSG = begin;
}
}
if (findMSG != messages.end()) {
messages.erase(findMSG);
ptr->folders.erase(this);
}
else {
throw std::runtime_error::runtime_error("There is no message to erase with contents of" + ptr->contents);
}
}
////////////////***********MESSAGE
std::ostream& Message::printFolders(std::ostream& os) {
for (Folder* folder : folders) {
os << folder->ID << " ";
}
return os;
}
void Message::save(Folder & fr) {
this->folders.insert(&fr);
fr.messages.insert(this);
}
void Message::remove(Folder & fr) {
auto iter = this->folders.find(&fr);
if (iter != this->folders.end()) {
folders.erase(iter);
fr.remMsg(this);
}
else {
throw std::runtime_error::runtime_error("There isn't a folder that contains" + this->contents);
}
}
void Message::addToFolders(const Message& m) {//we want this to have all the messages m has.
for (Folder* folder : m.folders) {
folder->addMsg(this);
}
}
void Message::removeFromFolders() {//remove the folders this message appears in.
for (Folder* folder : this->folders) {
folder->remMsg(this);
}
}
Message::Message(const Message& m) : contents(m.contents) {
addToFolders(m);
}
Message::~Message() {
removeFromFolders();
}
Message& Message::operator=(const Message& m) {
auto tempF = m.folders;
auto tempC = m.contents;
removeFromFolders();
folders = tempF;
contents = tempC;
return *this;
}
void Message::swap(Message& lhs, Message& rhs) {
std::swap(lhs.contents, rhs.contents);
std::swap(rhs.folders, lhs.folders);
}
#endif // !EMAIL
///////////////////////////////IN MAIN.CPP
#include <iostream>
#include <string>
#include <new>
#include <memory>
#include <vector>
#include "email.h"
using std::string; using std::cout; using std::cin; using std::endl; using std::flush; using std::vector;
void main() {
Folder myfolder("myfolder"), nextfolder("nextfolder"), afterfolder("afterfolder");
Message a("Hello world!");
myfolder.addMsg(&a);
nextfolder.addMsg(&a);
afterfolder.addMsg(&a);
Message b;
b = a;
a.printFolders(cout);
myfolder.printMessages(cout);
//system("pause");
}
*/
//------------------------------------------------------------------------------------EXERCISE 13.39
/*
#pragma once
#include <string>
#include <utility>
#include <memory>
#include <new>
#include <initializer_list>
using std::string; using std::pair;
class StrVec {
public:
StrVec() : // the allocator member is default initialized
elements(nullptr), first_free(nullptr), cap(nullptr) {
}
StrVec(std::initializer_list<string>&);
StrVec(const StrVec&); // copy constructor
StrVec &operator=(const StrVec&); // copy assignment
~StrVec(); // destructor
void push_back(const std::string&); // copy the element
size_t size() const { return first_free - elements; }
size_t capacity() const { return cap - elements; }
std::string *begin() const { return elements; }
std::string *end() const { return first_free; }
int memLeft() const { return cap - first_free; } // out vector.capacity
void reserve(const int&);
void resize(const int&);
void resize(const int&, const string&);
private:
std::allocator<std::string> alloc; // allocates the elements
// used by the functions that add elements to the StrVec
void chk_n_alloc() {
if (size() == capacity()) reallocate();
}
// utilities used by the copy constructor, assignment operator, and destructor
std::pair<std::string*, std::string*> alloc_n_copy // will allocate spance and copy a given range of elements.
(const std::string*, const std::string*);
void free(); // destroy the elements and free the space
void reallocate(); // get more space and copy the existing
std::string *elements; // pointer to the first element in the array
std::string *first_free; // pointer to the first free element in the array
std::string *cap; // pointer to one past the end of the array
string* StrVec::resizeNDeallocate(const int& size);
};
void StrVec::free() {
if (elements) {
while (elements != first_free) {
alloc.destroy(--first_free);
}
}
alloc.deallocate(elements, cap - elements);
}
std::pair<std::string*, std::string*> StrVec::alloc_n_copy(const std::string* lhs, const std::string* rhs) {
auto range = rhs - lhs;
string* allocB = alloc.allocate(range);
string* allocE = std::uninitialized_copy(elements, first_free, allocB);
return{allocB,allocE};
}
void StrVec::reallocate() {
auto range = (cap - elements) *2;
string* allocB = alloc.allocate(range);
string* allocE = std::uninitialized_copy(elements, first_free, allocB);
auto allocC = allocB + range;
free();
elements = allocB;
first_free = allocE;
cap = allocC;
}
StrVec::StrVec(const StrVec& temp) {
auto pairs = alloc_n_copy(temp.begin(), temp.end());
elements = pairs.first;
first_free = pairs.second = cap;
}
StrVec::~StrVec() {
free();
}
StrVec& StrVec::operator=(const StrVec& temp) {
auto pairs = alloc_n_copy(temp.begin(), temp.end());
free();
elements = pairs.first;
first_free = pairs.second = cap;
return *this;
}
StrVec::StrVec(std::initializer_list<string>& temp) {
auto range = temp.end() - temp.begin();
string* allocBegin = alloc.allocate(range);
string* allocEnd = std::uninitialized_copy(temp.begin(), temp.end(), allocBegin);
elements = allocBegin;
first_free = allocEnd;
cap = allocBegin + range;
}
void StrVec::push_back(const string& temp) {
chk_n_alloc();
alloc.construct(first_free, temp);
first_free++;
}
void StrVec::reserve(const int& size) {
cap += size;
}
string* StrVec::resizeNDeallocate(const int& size) {
if (size) {
if (size > capacity()) {//check if we add elements
alloc.allocate(size,cap);
return cap + size;
}
else {//else we destroy elements and deallocate the memory.
string* tempCap = elements + size;
int deallocate = 0;
while (cap != tempCap) {
deallocate++;
alloc.destroy(cap--);
}
alloc.deallocate(cap, deallocate);
return cap;
}
}
}
void StrVec::resize(const int& size) {
cap = resizeNDeallocate(size);
}
void StrVec::resize(const int& size, const string& temp) {
string* tempCap = resizeNDeallocate(size);
if (cap != tempCap) {
while (tempCap != cap) {
alloc.construct(cap++, temp);
}
cap = tempCap;
}
}
*/
//------------------------------------------------------------------------------------EXERCISE 13.43
/*
void StrVec::free() {
std::for_each(elements, first_free, [this](const string& temp) {
alloc.destroy(&temp);
});
alloc.deallocate(elements, cap - elements);
}
*/
//------------------------------------------------------------------------------------EXERCISE 13.44
/*
#ifndef STRING
#define STRING
class String {
public:
String() : begin(nullptr), end(nullptr) {};
String(char*,int);
~String();
std::ostream& print(std::ostream&);
private:
std::allocator<char> alloc;
char* begin;
char* end;
};
String::String(char* character,int size) {
begin = alloc.allocate(size);
end = begin + size;//off the end iterator.
int iter = 0;
for (char* fill = begin; fill != end; fill++) {
*fill = *(character + iter++);
}
}
std::ostream& String::print(std::ostream& os) {
if (begin) {
char* tempBegin = begin;
while (tempBegin != end) {
os << *tempBegin << std::flush;
tempBegin++;
}
}
return os;
}
String::~String() {
if (begin) {
for (char* tempBegin = begin; tempBegin != end; begin++) {
alloc.destroy(tempBegin);
}
alloc.deallocate(begin, end-begin);
}
}
#endif // !STRING
*/
//------------------------------------------------------------------------------------EXERCISE 13.48
/*
#pragma warning(disable: 4996)
#include <iostream>
#include <string>
#include <new>
#include <memory>
#include <vector>
#include "StrVec.h"
using std::string; using std::cout; using std::cin; using std::endl; using std::flush; using std::vector;
int main() {
vector<String> VEC{ {"Hello World",12}, {"The time is neigh",18} };
String x("ASDLASD", 8);
String y("I'm the end.", 13);
VEC.push_back(x);
VEC.push_back(y);
cout << String::copy << endl;
system("pause");
return 0;
}
*/
//-----------------------------A LITTLE PRATICE WITH MOVE ASSIGNEMNT AND MOVE CONTRUCTORS
/*
class String {
public:
String(const string& a = "", const int& b = 0) : contents(new string(a)),size(new int(b)) {};
String(String&&); //move constructor.
String& operator=(String&&); //move assignment operator
~String() { free(); }
String(String&) = delete;
String& operator=(String&) = delete;
void print() {
cout << "Contents: " << *contents << " Size of contents: " << *size << endl;
}
private:
string* contents;
int* size;
void free();
};
String::String( String&& s) {
contents = s.contents;
size = s.size;
s.contents = nullptr; s.size = nullptr;
}
String& String::operator=(String&& s) {
if (this != &s) {
free();
contents = s.contents;
size = s.size;
s.contents = nullptr; s.size = nullptr;
}
return *this;
}
void String::free() {
delete contents;
delete size;
}
int main() {
String b;
String a("Hello World!", 12);
b = std::move(a);
b.print();
system("pause");
return 0;
}
*/
//------------------------------------------------------------------------------------EXERCISE 13.49
//--------------------------------------STRING CLASS, IN 'StrVec.h'.
/*
#ifndef STRING
#define STRING
class String {
public:
String() : begin(nullptr), end(nullptr) {};
String(char*,int);
String(const String&) ;
String& operator=(const String&);
String(String&& s) : alloc(s.alloc), begin(s.begin), end(s.end) { s.begin = s.end = nullptr; s.alloc = std::allocator<char>(); };
String& operator=(String&&);
~String();
std::ostream& print(std::ostream&) const;
static int copy;
private:
std::allocator<char> alloc;
char* begin;
char* end;
};
int String::copy = 0;
String& String::operator=(String&& s) {
if (this != &s) {
for (char* iter = begin; iter != end; iter++) {//first destroy all elements in original.
alloc.destroy(iter);
}
alloc.deallocate(begin, end-begin);//then deallocate them.
begin = s.begin; //then we steal from s to our original.
end = s.end;
alloc = s.alloc;
s.begin = s.end =nullptr;//make s not equal to our original so when destructor is called it won't destroy ours.
s.alloc = std::allocator<char>();
}
return *this;
}
String::String(char* character,int size) {
begin = alloc.allocate(size);
end = begin + size;//off the end iterator.
int iter = 0;
for (char* fill = begin; fill != end; fill++) {
*fill = *(character + iter++);
}
}
inline String::String(const String & temp) {
begin = alloc.allocate(temp.end - temp.begin);
end = std::uninitialized_copy(temp.begin, temp.end, begin);
copy++;
}
inline String & String::operator=(const String & temp) {
char* orgiBegin = begin;
char* orgiEnd = end;
begin = alloc.allocate(temp.end - temp.begin);
end = std::uninitialized_copy(temp.begin, temp.end, begin);
for (char* oriTemp = orgiBegin; oriTemp != orgiEnd; oriTemp++) {
alloc.destroy(oriTemp);
}
alloc.deallocate(orgiBegin, orgiEnd - orgiBegin);
copy++;
return *this;
}
std::ostream& String::print(std::ostream& os) const {
if (begin) {
char* tempBegin = begin;
while (tempBegin != end) {
os << *tempBegin << std::flush;
tempBegin++;
}
}
return os;
}
String::~String() {
if (begin) {
for (char* tempBegin = begin; tempBegin != end; tempBegin++) {
alloc.destroy(tempBegin);
}
alloc.deallocate(begin, end-begin);
}
}
#endif // !STRING
*/
//------------------------------------------------IN MAIN.CPP
/*
#pragma warning(disable: 4996)
#include <iostream>
#include <string>
#include <new>
#include <memory>
#include <vector>
#include "StrVec.h"
using std::string; using std::cout; using std::cin; using std::endl; using std::flush; using std::vector;
int main() {
char x[] = "Hello world";
String myString(x, 12);
//String newString(std::move(myString));
String newString;
newString = std::move(myString);
newString.print(cout) << endl;
system("pause");
return 0;
}
*/
//-----------------------------------------------------MESSAGE CLASS
/*
#pragma once
#ifndef EMAIL
#define EMAIL
#include <iostream>
#include <vector>
#include <string>
#include <set>
using std::vector; using std::endl; using std::set; using std::string;
class Folder;
class Message {
friend class Folder;
public:
explicit Message(const string& s = "") : contents(s) {};
Message(const Message& m);
Message& operator=(const Message& m);
Message(Message&&);
Message& operator=(Message&&);
~Message();
/////
void swap(Message& lhs, Message& rhs);
std::ostream& printFolders(std::ostream& os);
void save(Folder& fr);
void remove(Folder& fr);
private:
string contents;
set<Folder*> folders;
void moveFolder(Message*);
void addToFolders(const Message &m);
void removeFromFolders();
};
class Folder {
friend class Message;
public:
Folder() = default;
Folder(const string& a) : ID(a) {};
~Folder();
void addMsg(Message* ptr);
void remMsg(Message* ptr);
std::ostream& printMessages(std::ostream& os);
private:
string ID;
set<Message*> messages;
};
/////////////////////////////////////////////////////////////////////////////////////////////////////////
//move assignemnt and move constructors for message.
void Message::moveFolder(Message* m) {
for (Folder* fold : m->folders) {
fold->remMsg(m);
fold->addMsg(this);
}
m->folders.clear();
}
Message::Message(Message&& m) : contents(m.contents) {
moveFolder(&m);
m.contents = "";
}
Message& Message::operator=(Message&& m) {
if (this != &m) {
moveFolder(&m);
contents = m.contents;
}
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////
std::ostream& Folder::printMessages(std::ostream& os) {
for (Message* m : messages) {
os << m->contents << " ";
}
return os;
}
Folder::~Folder() {
for (Message* mesg : messages) {
delete mesg;
}
}
void Folder::addMsg(Message* ptr) {
ptr->save(*this);
}
void Folder::remMsg(Message* ptr) {
decltype(messages.end()) findMSG = messages.end();
for (auto begin = messages.begin(); begin != messages.end(); begin++) {
if ((**begin).contents == ptr->contents) {
findMSG = begin;
}
}
if (findMSG != messages.end()) {
messages.erase(findMSG);
ptr->folders.erase(this);
}
else {
throw std::runtime_error::runtime_error("There is no message to erase with contents of" + ptr->contents);
}
}
//MESSAGESSSSS
std::ostream& Message::printFolders(std::ostream& os) {
for (Folder* folder : folders) {
os << folder->ID << " ";
}
return os;
}
void Message::save(Folder & fr) {
this->folders.insert(&fr);
fr.messages.insert(this);
}
void Message::remove(Folder & fr) {
auto iter = this->folders.find(&fr);
if (iter != this->folders.end()) {
folders.erase(iter);
fr.remMsg(this);
}
else {
throw std::runtime_error::runtime_error("There isn't a folder that contains" + this->contents);
}
}
void Message::addToFolders(const Message& m) {//we want this to have all the messages m has.
for (Folder* folder : m.folders) {
folder->addMsg(this);
}
}
void Message::removeFromFolders() {//remove the folders this message appears in.
if (!(this->folders.empty())) {
for (Folder* folder : this->folders) {
folder->remMsg(this);
}
}
}
Message::Message(const Message& m) : contents(m.contents) {
addToFolders(m);
}
Message::~Message() {
removeFromFolders();
}
Message& Message::operator=(const Message& m) {
auto tempF = m.folders;
auto tempC = m.contents;
removeFromFolders();
folders = tempF;
contents = tempC;
return *this;
}
void Message::swap(Message& lhs, Message& rhs) {
std::swap(lhs.contents, rhs.contents);
std::swap(rhs.folders, lhs.folders);
}
#endif // !EMAIL
*/
//----------------------------------------------------STRVEC
/*
#pragma once
#ifndef STRVEC
#define STRVEC
#include <string>
#include <utility>
#include <memory>
#include <new>
#include <initializer_list>
#include <algorithm>
#include <functional>
using std::string; using std::pair;
class StrVec {
public:
StrVec() : // the allocator member is default initialized
elements(nullptr), first_free(nullptr), cap(nullptr) {
}
StrVec(std::initializer_list<string>&);
StrVec(const StrVec&); // copy constructor
StrVec &operator=(const StrVec&); // copy assignment
~StrVec(); // destructor
StrVec(StrVec&&);//move constructor
StrVec& operator=(StrVec&&); //move assignment
void push_back(const std::string&); // copy the element
size_t size() const { return first_free - elements; }
size_t capacity() const { return cap - elements; }
std::string *begin() const { return elements; }
std::string *end() const { return first_free; }
int memLeft() const { return cap - first_free; } // our vector.capacity
void reserve(const int&);
void resize(const int&);
void resize(const int&, const string&);
private:
std::allocator<std::string> alloc; // allocates the elements
// used by the functions that add elements to the StrVec
void chk_n_alloc() {
if (size() == capacity()) reallocate();
}
// utilities used by the copy constructor, assignment operator, and destructor
std::pair<std::string*, std::string*> alloc_n_copy // will allocate spance and copy a given range of elements.
(const std::string*, const std::string*);
void free(); // destroy the elements and free the space
void reallocate(); // get more space and copy the existing
std::string *elements; // pointer to the first element in the array
std::string *first_free; // pointer to the first free element in the array
std::string *cap; // pointer to one past the end of the array
string* StrVec::resizeNDeallocate(const int& size);
};
StrVec::StrVec(StrVec&& sV) : alloc(sV.alloc), elements(sV.elements), first_free(sV.first_free), cap(sV.cap) {
sV.alloc = std::allocator<string>();
sV.elements = sV.cap = sV.first_free = nullptr;
}
StrVec& StrVec::operator=(StrVec&& sV) {
if (this != &sV) {
free();
alloc = sV.alloc; elements = sV.elements; first_free = sV.first_free; cap = sV.cap;
sV.elements = sV.cap = sV.first_free = nullptr;
}
}
void StrVec::free() {
if (elements) {
while (elements != first_free) {
alloc.destroy(--first_free);
}
}
alloc.deallocate(elements, cap - elements);
}
void StrVec::free() {
std::for_each(elements, first_free, [this](const string& temp) {
alloc.destroy(&temp);
});
alloc.deallocate(elements, cap - elements);
}
std::pair<std::string*, std::string*> StrVec::alloc_n_copy(const std::string* lhs, const std::string* rhs) {
auto range = rhs - lhs;
string* allocB = alloc.allocate(range);
string* allocE = std::uninitialized_copy(elements, first_free, allocB);
return{allocB,allocE};
}
void StrVec::reallocate() {
auto range = (cap - elements) *2;
string* allocB = alloc.allocate(range);
string* allocE = std::uninitialized_copy(elements, first_free, allocB);
auto allocC = allocB + range;
free();
elements = allocB;
first_free = allocE;
cap = allocC;
}
StrVec::StrVec(const StrVec& temp) {
auto pairs = alloc_n_copy(temp.begin(), temp.end());
elements = pairs.first;
first_free = pairs.second = cap;
}
StrVec::~StrVec() {
free();
}
StrVec& StrVec::operator=(const StrVec& temp) {
auto pairs = alloc_n_copy(temp.begin(), temp.end());
free();
elements = pairs.first;
first_free = pairs.second = cap;
return *this;
}
StrVec::StrVec(std::initializer_list<string>& temp) {
auto range = temp.end() - temp.begin();
string* allocBegin = alloc.allocate(range);
string* allocEnd = std::uninitialized_copy(temp.begin(), temp.end(), allocBegin);
elements = allocBegin;
first_free = allocEnd;
cap = allocBegin + range;
}
void StrVec::push_back(const string& temp) {
chk_n_alloc();
alloc.construct(first_free, temp);
first_free++;
}
void StrVec::reserve(const int& size) {
cap += size;
}
string* StrVec::resizeNDeallocate(const int& size) {
if (size) {
if (size > capacity()) {//check if we add elements
alloc.allocate(size,cap);
return cap + size;
}
else {//else we destroy elements and deallocate the memory.
string* tempCap = elements + size;
int deallocate = 0;
while (cap != tempCap) {
deallocate++;
alloc.destroy(cap--);
}
alloc.deallocate(cap, deallocate);
return cap;
}
}
}
void StrVec::resize(const int& size) {
cap = resizeNDeallocate(size);
}
void StrVec::resize(const int& size, const string& temp) {
string* tempCap = resizeNDeallocate(size);
if (cap != tempCap) {
while (tempCap != cap) {
alloc.construct(cap++, temp);
}
cap = tempCap;
}
}
#endif // !STRVEC
*/
//------------------------------------------------------------------------------------EXERCISE 13.50
/*
#pragma warning(disable: 4996)
#include <iostream>
#include <string>
#include <new>
#include <memory>
#include <vector>
#include "StrVec.h"
using std::string; using std::cout; using std::cin; using std::endl; using std::flush; using std::vector;
int main() {
vector<String> VEC{ {"Hello World",12}, {"The time is neigh",18} };
String x("ASDLASD", 8);
String y("I'm the end.", 13);
VEC.push_back(std::move(x));
VEC.push_back(std::move(y));
cout << String::copy << endl;
system("pause");
return 0;
}
*/
//------------------------------------------------------------------------------------EXERCISE 13.53
/*
HasPtr::HasPtr(HasPtr&& hP) : ps(hP.ps),i(hP.i),use(hP.use){
use++;
}
HasPtr& HasPtr::operator=(HasPtr&& hP) {
if (this != &hP) {
if (--(*use) == 0) {
delete use;
delete ps;
}
ps = hP.ps;
i = hP.i;
use = hP.use++;
}
return *this;
}
*/
//------------------------------------------------------------------------------------EXERCISE 13.55
/*
void StrBlob::pushBack(const string& t) && {
strData->push_back(t);
}
*/
|
[
"noreply@github.com"
] |
jchallenger1.noreply@github.com
|
f4a385972682954409236cd20967da31fb5226f6
|
f5ac7da57d433201a3c802e5f1611ff7914ca5bd
|
/src/ec/GF2X/affine/utils.cpp
|
730996d4a6864b923d985ef2f3784fbe2a228a64
|
[] |
no_license
|
natalikovaleva/iso-iec-9796-3
|
c4740b42001099f863b0b274d45029d8bc773a83
|
1d9926960026059dd90671c9c3d05d8b44c81900
|
refs/heads/master
| 2021-01-01T04:01:05.518073
| 2011-12-18T09:48:05
| 2011-12-18T09:48:05
| 56,810,825
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,378
|
cpp
|
#include "ec/GF2X/affine/utils.hpp"
#include "generic/gf2x_utils.hpp"
using namespace std;
using namespace NTL;
using namespace ECGF2X::Affine;
/* Smart stupid !! OCTET !! concatentaion. Be carefull! :] */
#include <stdio.h>
namespace ECGF2X
{
namespace Affine
{
ByteSeq EC2OSP(const EC_Point & Point, EC::EC2OSP_COMPRESS_MODE mode)
{
const unsigned char tY =
((mode == EC::EC2OSP_COMPRESSED) ||
(mode == EC::EC2OSP_HYBRID)) ?
EC_CPoint::compress_tY(Point) : 0;
if (Point.isZero())
return ByteSeq(0);
/* Pad - according to example of 2^m/ECNR.
* Check this. Don't see much sense */
const long Pad = L(Point.getEC().getModulus());
const unsigned int U = ((mode == EC::EC2OSP_UNCOMPRESSED) ||
(mode == EC::EC2OSP_HYBRID)) ? 1 : 0;
const unsigned int C = ((mode == EC::EC2OSP_COMPRESSED) ||
(mode == EC::EC2OSP_HYBRID)) ? 1 : 0;
const ByteSeq X(FE2OSP(Point.getX(), Pad));
const ByteSeq H(FE2OSP(4*U+C*(2+tY)));
if (U)
return H || X || FE2OSP(Point.getY(), Pad);
else
return H || X;
}
}
}
|
[
"avatar@IIT"
] |
avatar@IIT
|
0c471b5bea43d20be884bfa7d26f93b43054861d
|
269e4554569f5b6cbba877102f6b5b21e721a46f
|
/level A/A. Helpful Maths/main.cpp
|
9520e1618d0389117c45b734207ac7194787f4bb
|
[] |
no_license
|
KhaledAbdelgalil/sheet-mostafa-saad-problem-solving-
|
f1b289a8115579417b8f075ca4f792768e0c7e5d
|
4e2a72caeb3b3752b7170723a7190b1745d2f5e2
|
refs/heads/master
| 2022-04-02T08:48:52.967835
| 2020-02-01T03:47:27
| 2020-02-01T03:47:27
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 572
|
cpp
|
#include<bits/stdc++.h>
using namespace std;
int main()
{
string in,out="";
int sum1=0,sum2=0,sum3=0;
cin>>in;
for(int i=0;i<in.size();i++)
{
if(in[i]=='+') continue;
if(in[i]=='1') sum1++;
else if(in[i]=='2') sum2++;
else sum3++;
}
if(sum1>0){out+='1';sum1--;}
else if(sum2>0){out+='2';sum2--;}
else if(sum3>0){out+='3';sum3--;}
for(int i=0;i<sum1;i++)
out+="+1";
for(int i=0;i<sum2;i++)
out+="+2";
for(int i=0;i<sum3;i++)
out+="+3";
cout<<out;
return 0;
}
|
[
"khaled@github.com"
] |
khaled@github.com
|
f0653d554da8b95e36fd8bc2614b6524ea32bf7d
|
86d85900756de7245e9a06546fcd7bb02d7aa844
|
/deformationGraph.cpp
|
0ebb2877e51c7622d52591d48a2e0b38880b0691
|
[] |
no_license
|
shizsun0609tw/Embedded-Deforamtion-for-Shape-Manipulation
|
0d39a192a62c0ebf15892af42899d74bfad718ca
|
bfb644e3bcc7c5eb871b11374879a822aeb9bf1a
|
refs/heads/master
| 2023-08-27T15:02:13.789777
| 2021-11-10T09:53:45
| 2021-11-10T09:53:45
| 318,131,877
| 3
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 21,916
|
cpp
|
#include "deformationGraph.h"
DeformationGraph::DeformationGraph()
{
}
void DeformationGraph::Init(_GLMmodel* originMesh, _GLMmodel* samplingMesh)
{
this->originMesh = originMesh;
this->samplingMesh = samplingMesh;
k_nearest = 8;
w_rot = 1.0f;
w_reg = 10.0f;
w_con = 100.0f;
sample_controls = 0;
sample_nodes = samplingMesh->numvertices;
InitRotAndTrans();
CalConnectedMap();
CalSamplingVertices();
CalEmbeddedWeights();
CalDeformationGraphWeights();
default_sampling_vertices = vector<Vector3f>(sample_nodes);
for (int i = 0; i < sample_nodes; ++i)
{
default_sampling_vertices[i] = Vector3f(
samplingMesh->vertices[(i + 1) * 3 + 0],
samplingMesh->vertices[(i + 1) * 3 + 1],
samplingMesh->vertices[(i + 1) * 3 + 2]);
}
default_origin_vertices = vector<Vector3f>(originMesh->numvertices);
for (int i = 0; i < originMesh->numvertices; ++i)
{
default_origin_vertices[i] = Vector3f(
originMesh->vertices[(i + 1) * 3 + 0],
originMesh->vertices[(i + 1) * 3 + 1],
originMesh->vertices[(i + 1) * 3 + 2]);
}
for (auto iter = connectedMap.begin(); iter != connectedMap.end(); ++iter)
{
sample_edges += (*iter).second.size();
}
sample_edges /= 2;
}
void DeformationGraph::InitRotAndTrans()
{
rot.resize(sample_nodes);
trans.resize(sample_nodes);
Matrix3f temp_r = Matrix3f::Zero();
Vector3f temp_t = Vector3f::Zero();
temp_r(0, 0) = temp_r(1, 1) = temp_r(2, 2) = 1.0f;
for (int i = 0; i < sample_nodes; ++i)
{
rot[i] = temp_r;
trans[i] = temp_t;
}
}
void DeformationGraph::CalSamplingVertices()
{
for (int i = 1; i <= samplingMesh->numvertices; ++i)
{
float min = INT_MAX;
int idx = 0;
for (int j = 1; j <= originMesh->numvertices; ++j)
{
float temp = fabs(samplingMesh->vertices[i * 3 + 0] - originMesh->vertices[j * 3 + 0])
+ fabs(samplingMesh->vertices[i * 3 + 1] - originMesh->vertices[j * 3 + 1])
+ fabs(samplingMesh->vertices[i * 3 + 2] - originMesh->vertices[j * 3 + 2]);
if (temp < min)
{
min = temp;
idx = j;
}
}
sample_idices.push_back(idx);
samplingMesh->vertices[i * 3 + 0] = originMesh->vertices[idx * 3 + 0];
samplingMesh->vertices[i * 3 + 1] = originMesh->vertices[idx * 3 + 1];
samplingMesh->vertices[i * 3 + 2] = originMesh->vertices[idx * 3 + 2];
}
cout << "Fit Sample Vertices:" << sample_idices.size() << endl;
}
void DeformationGraph::CalConnectedMap()
{
for (int i = 0; i < samplingMesh->numtriangles; ++i)
{
for (int j = 0; j < 3; ++j)
{
connectedMap.insert(pair<int, set<int>>(samplingMesh->triangles[i].vindices[j], set<int>()));
connectedMap[samplingMesh->triangles[i].vindices[j]].insert(samplingMesh->triangles[i].vindices[(j + 1) % 3]);
connectedMap[samplingMesh->triangles[i].vindices[j]].insert(samplingMesh->triangles[i].vindices[(j + 2) % 3]);
}
}
}
void DeformationGraph::Run()
{
UpdateSampleVertices();
GaussainNewton();
}
void DeformationGraph::UpdateDeformationGraph()
{
for (int i = 0; i < sample_nodes; ++i)
{
samplingMesh->vertices[(i + 1) * 3 + 0] += trans[i][0];
samplingMesh->vertices[(i + 1) * 3 + 1] += trans[i][1];
samplingMesh->vertices[(i + 1) * 3 + 2] += trans[i][2];
}
}
void DeformationGraph::UpdateSampleVertices()
{
for (int i = 0; i < sample_nodes; ++i)
{
samplingMesh->vertices[(i + 1) * 3 + 0] = default_sampling_vertices[i][0];
samplingMesh->vertices[(i + 1) * 3 + 1] = default_sampling_vertices[i][1];
samplingMesh->vertices[(i + 1) * 3 + 2] = default_sampling_vertices[i][2];
}
for (int i = 0; i < originMesh->numvertices; ++i)
{
originMesh->vertices[(i + 1) * 3 + 0] = default_origin_vertices[i][0];
originMesh->vertices[(i + 1) * 3 + 1] = default_origin_vertices[i][1];
originMesh->vertices[(i + 1) * 3 + 2] = default_origin_vertices[i][2];
}
}
void DeformationGraph::UpdateOriginMesh()
{
int nodes = originMesh->numvertices;
vector<Vector3f> results(nodes);
for (int i = 0; i < nodes; ++i)
{
Vector3f result(0, 0, 0);
Vector3f vi = Vector3f(
originMesh->vertices[(i + 1) * 3 + 0],
originMesh->vertices[(i + 1) * 3 + 1],
originMesh->vertices[(i + 1) * 3 + 2]);
for (int j = 0; j < k_nearest; ++j)
{
Vector3f gj = Vector3f(
samplingMesh->vertices[(embeddedWeights[i][j].first) * 3 + 0],
samplingMesh->vertices[(embeddedWeights[i][j].first) * 3 + 1],
samplingMesh->vertices[(embeddedWeights[i][j].first) * 3 + 2]);
result += (embeddedWeights[i][j].second) * (rot[embeddedWeights[i][j].first - 1] * (vi - gj) + gj + trans[embeddedWeights[i][j].first - 1]);
}
results[i] = result;
}
for (int i = 0; i < nodes; ++i)
{
originMesh->vertices[(i + 1) * 3 + 0] = results[i][0];
originMesh->vertices[(i + 1) * 3 + 1] = results[i][1];
originMesh->vertices[(i + 1) * 3 + 2] = results[i][2];
}
}
void DeformationGraph::GaussainNewton()
{
const float epsilon = 1e-3;
const int iter_max = 5;
float err_current = 1, err_past = 2;
SparseMatrix<float> J(6 * sample_nodes + 6 * sample_edges + 3 * sample_controls, 12 * sample_nodes);
MatrixXf f, h, x(12 * sample_nodes, 1);
InitRotAndTrans();
for (int i = 0; i < sample_nodes; ++i)
{
for (int j = 0; j < 9; ++j) x(i * 12 + j, 0) = rot[i](j / 3, j % 3);
for (int j = 0; j < 3; ++j) x(i * 12 + 9 + j, 0) = trans[i](j);
}
cout << "------------------- Start -------------------" << endl;
err_current = F(x);
for (int i = 0; i < iter_max && fabs(err_past - err_current) > epsilon && err_current > epsilon; ++i)
{
err_past = err_current;
Calf(f);
CalJ(J);
SparseMatrix<float> Jt = J.transpose();
SparseMatrix<float> JtJ = J.transpose() * J;
SimplicialCholesky<SparseMatrix<float>> solver(Jt * J);
MatrixXf h = solver.solve(Jt * f);
x = h;
cout << "---------------------------------------\n";
cout << "Iteration: " << i + 1<< endl;
err_current = F(x);
cout << "Error: " << err_current << endl;
}
cout << "------------------- Finished -------------------\n" << endl;
}
void DeformationGraph::Calf(MatrixXf &f)
{
int idx = 0;
MatrixXf fx = MatrixXf::Zero(6 * sample_nodes + (3 * sample_edges) * 2 + 3 * sample_controls, 1);
// Erot
for (int i = 0; i < sample_nodes; ++i)
{
fx(idx++, 0) = rot[i].col(0).dot(rot[i].col(1)) * sqrt(w_rot);
fx(idx++, 0) = rot[i].col(0).dot(rot[i].col(2)) * sqrt(w_rot);
fx(idx++, 0) = rot[i].col(1).dot(rot[i].col(2)) * sqrt(w_rot);
fx(idx++, 0) = sqrt(w_rot);
fx(idx++, 0) = sqrt(w_rot);
fx(idx++, 0) = sqrt(w_rot);
}
// Ereg
for (int j = 0; j < sample_nodes; ++j)
{
Vector3f gj = Vector3f(
samplingMesh->vertices[(j + 1) * 3 + 0],
samplingMesh->vertices[(j + 1) * 3 + 1],
samplingMesh->vertices[(j + 1) * 3 + 2]);
for (auto iter = connectedMap[j + 1].begin(); iter != connectedMap[j + 1].end(); ++iter)
{
int k = *iter - 1;
Vector3f gk = Vector3f(
samplingMesh->vertices[(k + 1) * 3 + 0],
samplingMesh->vertices[(k + 1) * 3 + 1],
samplingMesh->vertices[(k + 1) * 3 + 2]);
Vector3f temp = (gk - gj) * sqrt(w_reg);
fx(idx++, 0) = temp(0);
fx(idx++, 0) = temp(1);
fx(idx++, 0) = temp(2);
}
}
// Econ
for (int i = 0; i < control_points_data.size(); ++i)
{
for (int j = 0; j < control_points_data[i].size(); ++j)
{
Vector3f temp = Vector3f(
control_points_data[i][j][0] - samplingMesh->vertices[control_points_id[i][j] * 3 + 0],
control_points_data[i][j][1] - samplingMesh->vertices[control_points_id[i][j] * 3 + 1],
control_points_data[i][j][2] - samplingMesh->vertices[control_points_id[i][j] * 3 + 2]) * sqrt(w_con);
fx(idx++, 0) = temp(0);
fx(idx++, 0) = temp(1);
fx(idx++, 0) = temp(2);
}
}
f = fx;
}
void DeformationGraph::CalJ(SparseMatrix<float>& J)
{
int idx = 0;
vector<Triplet<float>> Jacobi;
// Erot
for (int i = 0; i < sample_nodes; ++i)
{
Jacobi.push_back(Triplet<float>(idx, 0 + 12 * i, rot[i](0, 1)));
Jacobi.push_back(Triplet<float>(idx, 1 + 12 * i, rot[i](1, 1)));
Jacobi.push_back(Triplet<float>(idx, 2 + 12 * i, rot[i](2, 1)));
Jacobi.push_back(Triplet<float>(idx, 3 + 12 * i, rot[i](0, 0)));
Jacobi.push_back(Triplet<float>(idx, 4 + 12 * i, rot[i](1, 0)));
Jacobi.push_back(Triplet<float>(idx, 5 + 12 * i, rot[i](2, 0)));
idx++;
Jacobi.push_back(Triplet<float>(idx, 0 + 12 * i, rot[i](0, 2)));
Jacobi.push_back(Triplet<float>(idx, 1 + 12 * i, rot[i](1, 2)));
Jacobi.push_back(Triplet<float>(idx, 2 + 12 * i, rot[i](2, 2)));
Jacobi.push_back(Triplet<float>(idx, 6 + 12 * i, rot[i](0, 0)));
Jacobi.push_back(Triplet<float>(idx, 7 + 12 * i, rot[i](1, 0)));
Jacobi.push_back(Triplet<float>(idx, 8 + 12 * i, rot[i](2, 0)));
idx++;
Jacobi.push_back(Triplet<float>(idx, 3 + 12 * i, rot[i](0, 2)));
Jacobi.push_back(Triplet<float>(idx, 4 + 12 * i, rot[i](1, 2)));
Jacobi.push_back(Triplet<float>(idx, 5 + 12 * i, rot[i](2, 2)));
Jacobi.push_back(Triplet<float>(idx, 6 + 12 * i, rot[i](0, 1)));
Jacobi.push_back(Triplet<float>(idx, 7 + 12 * i, rot[i](1, 1)));
Jacobi.push_back(Triplet<float>(idx, 8 + 12 * i, rot[i](2, 1)));
idx++;
for (int j = 0; j < 9; ++j)
{
if (j == 3 || j == 6) ++idx;
Jacobi.push_back(Triplet<float>(idx, 12 * i + j, rot[i](j / 3, j % 3)));
}
idx++;
}
// Ereg
for (int j = 0; j < sample_nodes; ++j)
{
for (auto iter = connectedMap[j + 1].begin(); iter != connectedMap[j + 1].end(); ++iter)
{
int k = *iter - 1;
vector3 ekj = vector3(
samplingMesh->vertices[(k + 1) * 3 + 0] - samplingMesh->vertices[(j + 1) * 3 + 0],
samplingMesh->vertices[(k + 1) * 3 + 1] - samplingMesh->vertices[(j + 1) * 3 + 1],
samplingMesh->vertices[(k + 1) * 3 + 2] - samplingMesh->vertices[(j + 1) * 3 + 2]) * sqrt(w_reg);
for (int p = 0; p < 3; ++p)
{
for (int q = 0; q < 3; ++q)
{
Jacobi.push_back(Triplet<float>(idx, 12 * j + p * 3 + q, ekj[q]));
}
Jacobi.push_back(Triplet<float>(idx, 12 * j + 9 + p, sqrt(w_reg)));
Jacobi.push_back(Triplet<float>(idx, 12 * k + 9 + p, -sqrt(w_reg)));
idx++;
}
}
}
// Econ
for (int i = 0; i < control_points_id.size(); ++i)
{
for (int j = 0; j < control_points_id[i].size(); ++j)
{
Jacobi.push_back(Triplet<float>(idx++, 9 + 12 * (control_points_id[i][j] - 1) + 0, sqrt(w_con)));
Jacobi.push_back(Triplet<float>(idx++, 9 + 12 * (control_points_id[i][j] - 1) + 1, sqrt(w_con)));
Jacobi.push_back(Triplet<float>(idx++, 9 + 12 * (control_points_id[i][j] - 1) + 2, sqrt(w_con)));
}
}
J.setFromTriplets(Jacobi.begin(), Jacobi.end());
}
float DeformationGraph::F(MatrixXf &x)
{
float err = 0;
for (int i = 0; i < sample_nodes; ++i)
{
for (int j = 0; j < 9; ++j) rot[i](j / 3, j % 3) = x(12 * i + j, 0);
for (int j = 0; j < 3; ++j) trans[i][j] = x(12 * i + 9 + j, 0);
}
UpdateOriginMesh();
UpdateDeformationGraph();
float Erot = CalErot(), Ereg = CalEreg(), Econ = CalEcon();
cout << "Erot: " << Erot << ", Ereg: " << Ereg << ", Econ: " << Econ << endl;
err = w_rot * Erot + w_reg * Ereg + w_con * Econ;
return err;
}
float DeformationGraph::CalEreg()
{
float Ereg = 0;
for (int j = 0; j < sample_nodes; ++j)
{
Vector3f gj = Vector3f(
samplingMesh->vertices[(j + 1) * 3 + 0],
samplingMesh->vertices[(j + 1) * 3 + 1],
samplingMesh->vertices[(j + 1) * 3 + 2]);
for (auto iter = connectedMap[j + 1].begin(); iter != connectedMap[j + 1].end(); ++iter)
{
int k = *iter - 1;
Vector3f gk = Vector3f(
samplingMesh->vertices[(k + 1) * 3 + 0],
samplingMesh->vertices[(k + 1) * 3 + 1],
samplingMesh->vertices[(k + 1) * 3 + 2]);
Ereg += pow((rot[j] * (gk - gj) + gj + trans[j] - (gk + trans[k])).norm(), 2);
}
}
return Ereg;
}
float DeformationGraph::CalErot()
{
float Erot = 0;
for (int i = 0; i < sample_nodes; ++i)
{
Erot += pow(rot[i].col(0).dot(rot[i].col(1)), 2);
Erot += pow(rot[i].col(0).dot(rot[i].col(2)), 2);
Erot += pow(rot[i].col(1).dot(rot[i].col(2)), 2);
Erot += pow(rot[i].col(0).dot(rot[i].col(0)) - 1, 2);
Erot += pow(rot[i].col(1).dot(rot[i].col(1)) - 1, 2);
Erot += pow(rot[i].col(2).dot(rot[i].col(2)) - 1, 2);
}
return Erot;
}
float DeformationGraph::CalEcon()
{
float Econ = 0;
for (int i = 0; i < control_points_id.size(); ++i)
{
for (int j = 0; j < control_points_id[i].size(); ++j)
{
int idx = control_points_id[i][j];
Econ += pow(fabs(samplingMesh->vertices[idx * 3 + 0] - control_points_data[i][j][0]), 2);
Econ += pow(fabs(samplingMesh->vertices[idx * 3 + 1] - control_points_data[i][j][1]), 2);
Econ += pow(fabs(samplingMesh->vertices[idx * 3 + 2] - control_points_data[i][j][2]), 2);
}
}
return Econ;
}
void DeformationGraph::CalDeformationGraphWeights()
{
vector<vector<float>> distance(sample_nodes);
vector<vector<int>> index(sample_nodes);
for (int i = 0; i < sample_nodes; ++i)
{
vector<float> temp_d(sample_nodes);
vector<int> temp_i(sample_nodes);
vector3 temp_v;
for (int j = 0; j < sample_nodes; ++j)
{
temp_v = vector3(
samplingMesh->vertices[(i + 1) * 3 + 0] - samplingMesh->vertices[(j + 1) * 3 + 0],
samplingMesh->vertices[(i + 1) * 3 + 1] - samplingMesh->vertices[(j + 1) * 3 + 1],
samplingMesh->vertices[(i + 1) * 3 + 2] - samplingMesh->vertices[(j + 1) * 3 + 2]);
temp_d[j] = sqrt(temp_v[0] * temp_v[0] + temp_v[1] * temp_v[1] + temp_v[2] * temp_v[2]);
temp_i[j] = j;
}
distance[i] = temp_d;
index[i] = temp_i;
}
deformationGraphWeights = vector<vector<pair<int, float>>>(sample_nodes);
for (int i = 0; i < sample_nodes; ++i)
{
vector<pair<int, float>> temp_p(k_nearest + 1);
for (int j = 0; j < k_nearest + 1; ++j)
{
int idx_min = j;
for (int k = j + 1; k < sample_nodes; ++k)
{
if (distance[i][k] < distance[i][idx_min]) idx_min = k;
}
float temp = distance[i][j];
distance[i][j] = distance[i][idx_min];
distance[i][idx_min] = temp;
int temp_i = index[i][j];
index[i][j] = index[i][idx_min];
index[i][idx_min] = temp_i;
temp_p[j] = pair<int, float>(index[i][j] + 1, distance[i][j]);
}
deformationGraphWeights[i] = temp_p;
}
for (int i = 0; i < sample_nodes; ++i)
{
vector3 temp = vector3(
samplingMesh->vertices[(i + 1) * 3 + 0] - samplingMesh->vertices[deformationGraphWeights[i][k_nearest].first * 3 + 0],
samplingMesh->vertices[(i + 1) * 3 + 1] - samplingMesh->vertices[deformationGraphWeights[i][k_nearest].first * 3 + 1],
samplingMesh->vertices[(i + 1) * 3 + 2] - samplingMesh->vertices[deformationGraphWeights[i][k_nearest].first * 3 + 2]);
float d_max = sqrt(temp[0] * temp[0] + temp[1] * temp[1] + temp[2] * temp[2]);
float sum = 0;
for (int j = 0; j < k_nearest; ++j)
{
temp = vector3(
samplingMesh->vertices[(i + 1) * 3 + 0] - samplingMesh->vertices[deformationGraphWeights[i][j].first * 3 + 0],
samplingMesh->vertices[(i + 1) * 3 + 1] - samplingMesh->vertices[deformationGraphWeights[i][j].first * 3 + 1],
samplingMesh->vertices[(i + 1) * 3 + 2] - samplingMesh->vertices[deformationGraphWeights[i][j].first * 3 + 2]);
float d = sqrt(temp[0] * temp[0] + temp[1] * temp[1] + temp[2] * temp[2]);
deformationGraphWeights[i][j].second = pow(1 - d / d_max, 2);
sum += deformationGraphWeights[i][j].second;
}
for (int j = 0; j < k_nearest; ++j)
{
deformationGraphWeights[i][j].second /= sum;
if (k_nearest == 1) deformationGraphWeights[i][j].second = 1;
}
}
}
void DeformationGraph::CalEmbeddedWeights()
{
int nodes = originMesh->numvertices;
vector<vector<float>> distance(nodes);
vector<vector<int>> index(nodes);
for (int i = 0; i < nodes; ++i)
{
vector<float> temp_d(sample_nodes);
vector<int> temp_i(sample_nodes);
vector3 temp_v;
for (int j = 0; j < sample_nodes; ++j)
{
temp_v = vector3(
originMesh->vertices[(i + 1) * 3 + 0] - samplingMesh->vertices[(j + 1) * 3 + 0],
originMesh->vertices[(i + 1) * 3 + 1] - samplingMesh->vertices[(j + 1) * 3 + 1],
originMesh->vertices[(i + 1) * 3 + 2] - samplingMesh->vertices[(j + 1) * 3 + 2]);
temp_d[j] = sqrt(temp_v[0] * temp_v[0] + temp_v[1] * temp_v[1] + temp_v[2] * temp_v[2]);
temp_i[j] = j;
}
distance[i] = temp_d;
index[i] = temp_i;
}
embeddedWeights = vector<vector<pair<int, float>>>(nodes);
for (int i = 0; i < nodes; ++i)
{
vector<pair<int, float>> temp_p(k_nearest + 1);
for (int j = 0; j < k_nearest + 1; ++j)
{
int idx_min = j;
for (int k = j + 1; k < sample_nodes; ++k)
{
if (distance[i][k] < distance[i][idx_min]) idx_min = k;
}
float temp = distance[i][j];
distance[i][j] = distance[i][idx_min];
distance[i][idx_min] = temp;
int temp_i = index[i][j];
index[i][j] = index[i][idx_min];
index[i][idx_min] = temp_i;
temp_p[j] = pair<int, float>(index[i][j] + 1, distance[i][j]);
}
embeddedWeights[i] = temp_p;
}
for (int i = 0; i < nodes; ++i)
{
vector3 temp = vector3(
originMesh->vertices[(i + 1) * 3 + 0] - samplingMesh->vertices[embeddedWeights[i][k_nearest].first * 3 + 0],
originMesh->vertices[(i + 1) * 3 + 1] - samplingMesh->vertices[embeddedWeights[i][k_nearest].first * 3 + 1],
originMesh->vertices[(i + 1) * 3 + 2] - samplingMesh->vertices[embeddedWeights[i][k_nearest].first * 3 + 2]);
float d_max = sqrt(temp[0] * temp[0] + temp[1] * temp[1] + temp[2] * temp[2]);
float sum = 0;
for (int j = 0; j < k_nearest; ++j)
{
temp = vector3(
originMesh->vertices[(i + 1) * 3 + 0] - samplingMesh->vertices[embeddedWeights[i][j].first * 3 + 0],
originMesh->vertices[(i + 1) * 3 + 1] - samplingMesh->vertices[embeddedWeights[i][j].first * 3 + 1],
originMesh->vertices[(i + 1) * 3 + 2] - samplingMesh->vertices[embeddedWeights[i][j].first * 3 + 2]);
float d = sqrt(temp[0] * temp[0] + temp[1] * temp[1] + temp[2] * temp[2]);
embeddedWeights[i][j].second = pow(1 - d / d_max, 2);
sum += embeddedWeights[i][j].second;
}
for (int j = 0; j < k_nearest; ++j)
{
embeddedWeights[i][j].second /= sum;
if (k_nearest == 1) embeddedWeights[i][j].second = 1;
}
}
}
void DeformationGraph::SetControlPoints(vector<vector<int>> controlPoints)
{
control_points_id = controlPoints;
for (int i = control_points_data.size(); i < control_points_id.size(); ++i)
{
vector<vector3> temp_p;
vector3 temp_v;
for (int j = 0; j < control_points_id[i].size(); ++j)
{
temp_v = vector3(
samplingMesh->vertices[control_points_id[i][j] * 3 + 0],
samplingMesh->vertices[control_points_id[i][j] * 3 + 1],
samplingMesh->vertices[control_points_id[i][j] * 3 + 2]);
temp_p.push_back(temp_v);
}
control_points_data.push_back(temp_p);
}
sample_controls = 0;
for (int i = 0; i < controlPoints.size(); ++i)
{
sample_controls += controlPoints[i].size();
}
}
void DeformationGraph::SetControlPointsTranslate(int selectedId, vector3 vec)
{
for (int i = 0; i < control_points_id[selectedId].size(); i++)
{
int idx = control_points_id[selectedId][i];
control_points_data[selectedId][i] += vec;
}
}
vector<int> DeformationGraph::GetSamplingIndices()
{
return sample_idices;
}
|
[
"shizsun0609tw@gmail.com"
] |
shizsun0609tw@gmail.com
|
09c3f37221e9d71cc33c2034c9262fb74644e986
|
adb3e601acc0d6fc88eb43c5d38f37c323cca764
|
/Dynamic-Programming/0_1_knapsack_dynamic.cpp
|
0620db4626bd787c394eb447829674a75a8b3099
|
[] |
no_license
|
HEDAETUL-ISLAM/Algorithms
|
a7d6ed969765fae1051e70b102e6b80f3906a921
|
c46b07b058a36231cc4d5ef55c0a4e1723a25eea
|
refs/heads/master
| 2020-04-18T18:50:57.972252
| 2019-01-26T14:19:35
| 2019-01-26T14:19:35
| 122,783,176
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 788
|
cpp
|
#include <bits/stdc++.h>
using namespace std;
struct item{
int value, weight;
};
int max(int a, int b){
return (a>b)?a:b ;
}
int knapsack(int w, item arr[], int n){
int result[n+1][w+1];
for(int i=0;i<=n;i++){
for(int j=0;j<=w;j++){
if(i==0 || j==0){
result[i][j] = 0;
}
else if(arr[i-1].weight<=j){
result[i][j]=max(arr[i-1].value + result[i-1][j-arr[i-1].weight], result[i-1][j]);
}
else{
result[i][j]=result[i-1][j];
}
}
}
return result[n][w];
}
int main()
{
int w,n;
cout<<"enter the size of ur entered data: ";
cin>>n;
cout<<"enter the weitht: ";
cin>>w;
item arr[100];
cout<<"enter ur value first and then weight: ";
for(int i=0;i<n;i++){
cin>>arr[i].value;
cin>>arr[i].weight;
}
cout<<"max val is: "<<knapsack(w,arr,n);
}
|
[
"bulbulhedaytul@gmail.com"
] |
bulbulhedaytul@gmail.com
|
a88bce9d67b83a99fc6eaabd299cf32b3f1ed2bb
|
af5bd30d59fec67fcb32930896615272c453f379
|
/255.cpp
|
21ec3518ba416cad9a29b0de67ca3216be186011
|
[] |
no_license
|
FuHongbao/OJ_Code
|
e656e970855661f0b0d4e5ea719eed5b020903c5
|
bf54e32ceb4468dc15e8251e83317c03e16b8888
|
refs/heads/master
| 2020-08-04T23:56:12.680917
| 2019-10-02T11:28:17
| 2019-10-02T11:28:17
| 212,321,572
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,147
|
cpp
|
/*************************************************************************
> File Name: 255.cpp
> Author: victoria
> Mail: 1105847344@qq.com
> Created Time: 2019年06月29日 星期六 19时56分56秒
************************************************************************/
#include <iostream>
#include <algorithm>
#include <string.h>
#include <cmath>
using namespace std;
#define MAX_N 1000
struct Range {
double l, r;
}arr[MAX_N + 5];
bool cmp(struct Range a, struct Range b) {
if (a.r != b.r) return a.r < b.r;
return a.l > b.l;
}
int main() {
int n;
double d;
cin >> n >> d;
double flag = 0;
for (int i = 0; i < n ; i++) {
double x, y;
cin >> x >> y;
if (y > d) flag = 1;
arr[i].l = x - sqrt(d*d - y*y);
arr[i].r = x + sqrt(d*d - y*y);
}
if (flag) {
cout << "-1" <<endl;
return 0;
}
sort(arr, arr + n, cmp);
int ans = 1;
double index = arr[0].r;
for(int i = 1; i < n; i++) {
if (arr[i].l > index) {
index = arr[i].r;
ans += 1;
}
}
cout << ans << endl;
return 0;
}
|
[
"FuHongbao@FuHongbao.com"
] |
FuHongbao@FuHongbao.com
|
7567fb6d2881e66096918ba8b28985e2616d369c
|
5e8d200078e64b97e3bbd1e61f83cb5bae99ab6e
|
/main/source/src/protocols/carbohydrates/GlycanSampler.hh
|
a7f4d76ff26f3e905a0cccbeacaa31ed8e015342
|
[] |
no_license
|
MedicaicloudLink/Rosetta
|
3ee2d79d48b31bd8ca898036ad32fe910c9a7a28
|
01affdf77abb773ed375b83cdbbf58439edd8719
|
refs/heads/master
| 2020-12-07T17:52:01.350906
| 2020-01-10T08:24:09
| 2020-01-10T08:24:09
| 232,757,729
| 2
| 6
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 9,162
|
hh
|
// -*- mode:c++;tab-width:2;indent-tabs-mode:t;show-trailing-whitespace:t;rm-trailing-spaces:t -*-
// vi: set ts=2 noet:
//
// (c) Copyright Rosetta Commons Member Institutions.
// (c) This file is part of the Rosetta software suite and is made available under license.
// (c) The Rosetta software is developed by the contributing members of the Rosetta Commons.
// (c) For more information, see http://www.rosettacommons.org. Questions about this can be
// (c) addressed to University of Washington CoMotion, email: license@uw.edu.
/// @file protocols/carbohydrates/GlycanSampler.hh
/// @brief Main mover for Glycan Relax, which optimizes glycans in a pose.
/// @author Jared Adolf-Bryfogle (jadolfbr@gmail.com) and Jason W. Labonte (JWLabonte@jhu.edu)
#ifndef INCLUDED_protocols_carbohydrates_GlycanSampler_hh
#define INCLUDED_protocols_carbohydrates_GlycanSampler_hh
// Unit headers
#include <protocols/carbohydrates/GlycanSampler.fwd.hh>
#include <protocols/carbohydrates/LinkageConformerMover.hh>
#include <protocols/moves/Mover.hh>
#include <core/pose/Pose.fwd.hh>
#include <core/kinematics/MoveMap.fwd.hh>
#include <core/scoring/ScoreFunction.fwd.hh>
#include <core/pack/task/TaskFactory.fwd.hh>
#include <core/select/residue_selector/ResidueSelector.fwd.hh>
#include <protocols/filters/Filter.fwd.hh>
#include <protocols/moves/MonteCarlo.fwd.hh>
#include <protocols/moves/MoverContainer.fwd.hh>
#include <protocols/moves/MonteCarlo.fwd.hh>
#include <protocols/simple_moves/BackboneMover.fwd.hh>
#include <protocols/minimization_packing/MinMover.fwd.hh>
#include <protocols/minimization_packing/PackRotamersMover.fwd.hh>
#include <basic/datacache/DataMap.fwd.hh>
namespace protocols {
namespace carbohydrates {
///@brief Main mover for Glycan Relax, which optimizes glycans in a pose.
/// Each round optimizes either one residue for BB sampling, linkage, or multiple for minimization.
/// Currently uses a random sampler with a set of weights to each mover for sampling.
///
/// Weights are currently as follows:
/// .40 Phi/Psi Sugar BB Sampling
/// .20 Linkage Conformer Sampling
/// .30 Small BB Sampling - equal weight to phi, psi, or omega
/// -> .17 +/- 15 degrees
/// -> .086 +/- 45 degrees
/// -> .044 +/- 90 degrees
/// .05 GlycanTreeMinMover
/// .05 PackRotamersMover
///
/// Supports Symmetry
///
class GlycanSampler : public protocols::moves::Mover {
public:
GlycanSampler();
//@brief constructor with arguments
GlycanSampler( core::select::residue_selector::ResidueSelectorCOP selector,
core::scoring::ScoreFunctionCOP scorefxn,
core::Size rounds = 75);
// copy constructor
GlycanSampler( GlycanSampler const & src );
// destructor (important for properly forward-declaring smart-pointer members)
~GlycanSampler() override;
void
apply( core::pose::Pose & pose ) override;
public:
///@brief Set the Movemap
void
set_residue_selector(core::select::residue_selector::ResidueSelectorCOP selector );
///@brief Set a ResidueSelector for glycan residue selection, instead of the typical movemap.
void
set_selector(core::select::residue_selector::ResidueSelectorCOP selector);
///@brief Set the TaskFactory to control side-chain packing of surrounding amino acids and the OH groups of the glycans.
void
set_taskfactory(core::pack::task::TaskFactoryCOP tf);
///@brief Set the ScoreFunction
void
set_scorefunction( core::scoring::ScoreFunctionCOP scorefxn);
///@brief Each round applys a random mover to pose.
/// This setting is multiplied by the number of glycan residues in the movemap for the total number of rounds
void
set_rounds( core::Size rounds);
///@brief Set how our Conformer mover samples. Default is to do uniform sampling on the conformers instead of using the population as probabilities.
void
set_population_based_conformer_sampling(bool pop_based_sampling);
///@brief Set whether if we are sampling torsions uniformly within an SD for the LinkageConformerMover (false)
/// or sampling the gaussian (true).
/// Default false
void
set_use_gaussian_sampling(bool use_gaussian_sampling);
void
set_kt( core::Real kt);
void
set_defaults();
///@brief Use Cartesian minimization instead of Dihedral minimization.
/// Default (for now) is dihedral.
void
use_cartmin( bool use_cartmin );
///@brief Set refinement mode instead of denovo modeling mode.
void
set_refine( bool refine );
///@brief set to minimize ring torsions during minimzation. Default false.
void
set_min_rings( bool min_rings);
///@brief Set the protocol to use the refactored Shear Mover for glycan torsions at 10 % probability.
/// Default false.
void
set_use_shear( bool use_shear);
///@brief Set the protocol to randomize torsions before beginning.
/// This actually helps get to lower energy models.
/// Default True. If doing refinement, this is automatically turned off.
void
set_randomize_first( bool randomize_first );
///@brief Set the number of inner cycles for BB sampling through small/sugarBB.
/// This is multiplied by the number of glycan residues
/// Default 1
void
set_inner_bb_cycles( core::Size inner_bb_cycles );
public:
void
show( std::ostream & output=std::cout ) const override;
/// @brief parse XML tag (to use this Mover in Rosetta Scripts)
void parse_my_tag(
utility::tag::TagCOP tag,
basic::datacache::DataMap & data,
protocols::filters::Filters_map const & filters,
protocols::moves::Movers_map const & movers,
core::pose::Pose const & pose ) override;
//GlycanSampler & operator=( GlycanSampler const & src );
/// @brief required in the context of the parser/scripting scheme
moves::MoverOP
fresh_instance() const override;
/// @brief required in the context of the parser/scripting scheme
protocols::moves::MoverOP
clone() const override;
bool
reinitialize_for_each_job() const override {
return true;
}
std::string
get_name() const override;
static
std::string
mover_name();
static
void
provide_xml_schema( utility::tag::XMLSchemaDefinition & xsd );
///@brief Randomize all torsions of the subset. Used to start the protocol.
void
randomize_glycan_torsions( core::pose::Pose & pose, utility::vector1< bool > const & subset ) const;
///@brief Attempt to idealize all residues in of a set of trees. Experimental!
void
idealize_glycan_residues( core::pose::Pose & pose, utility::vector1< core::Size > const & tree_subset ) const;
public:
///@brief Get the number of glycan sampler rounds this class is set to run.
core::Size
get_glycan_sampler_rounds();
///@brief This allows us to force a number of rounds instead of doing rounds*glycan residues
void
force_total_rounds( core::Size total_rounds );
private:
void
init_objects( core::pose::Pose & pose );
void
set_cmd_line_defaults();
void
apply_to_res(
core::pose::Pose & pose,
core::Size resnum,
core::kinematics::MoveMapOP mm,
core::scoring::ScoreFunctionOP score,
core::Size round);
void
setup_default_task_factory(utility::vector1< bool > const & glycan_residues, core::pose::Pose const & pose );
void
setup_score_function();
void
setup_cartmin(core::scoring::ScoreFunctionOP scorefxn) const;
//Setup the final WeightedMover from our subsets and movemap.
void
setup_movers(
core::pose::Pose & pose,
utility::vector1< bool > const & dihedral_subset,
utility::vector1< bool > const & sugar_bb_subset,
utility::vector1< bool > const & subset);
void
setup_packer(
core::pose::Pose & pose,
utility::vector1< bool > const & full_subset );
private:
core::pack::task::TaskFactoryCOP tf_ = nullptr;
moves::MonteCarloOP mc_ = nullptr;
core::scoring::ScoreFunctionCOP scorefxn_ = nullptr;
LinkageConformerMoverOP linkage_mover_ = nullptr;
moves::RandomMoverOP weighted_random_mover_ = nullptr;
minimization_packing::MinMoverOP min_mover_ = nullptr;
minimization_packing::PackRotamersMoverOP packer_ = nullptr;
simple_moves::ShearMoverOP shear_ = nullptr;
core::Size rounds_ = 25; // cmdline
core::Real kt_ = 2.0; // cmdline
utility::vector1<std::string> accept_log_;
bool test_ = false; // cmdline
bool final_min_ = true; // cmdline
bool refine_ = false; // cmdline
core::Size total_glycan_residues_ = 0;
bool pymol_movie_ = false; // cmdline
utility::vector1< std::string > parsed_positions_;
core::Real pack_distance_ = 6.0;
bool cartmin_ = false; // cmdline
bool tree_based_min_pack_ = true; // cmdline
core::select::residue_selector::ResidueSelectorCOP selector_;
bool population_based_conformer_sampling_ = false;
bool use_gaussian_sampling_ = false;
bool min_rings_ = false;
core::Size forced_total_rounds_ = 0;
bool use_shear_ = false;
bool randomize_first_ = true;
core::Size inner_ncycles_ = 0; //For individual bb movements, multiply this by n glycans.
bool match_sampling_of_modeler_ = false; //For benchmarking
utility::vector1< bool > final_residue_subset_;
};
std::ostream &operator<< (std::ostream &os, GlycanSampler const &mover);
} //protocols
} //carbohydrates
#endif //protocols/carbohydrates_GlycanSampler_hh
|
[
"36790013+MedicaicloudLink@users.noreply.github.com"
] |
36790013+MedicaicloudLink@users.noreply.github.com
|
a4b8f935525aae61c4667c606f99c420655aae27
|
304fc20348614ff58f8ec11a012b4a464a5ddf35
|
/include/processor.h
|
f4b43a9d4e6bd182192cc87db084581897063cb4
|
[
"MIT"
] |
permissive
|
Abdo-1992/system-monitor
|
b431b2ac0e8c2cbc7e33ad8e5fb1b643681cc82c
|
e9f18f38e8e3e535fbfc7ab405bbc5c40c339d10
|
refs/heads/main
| 2023-02-04T14:06:06.279075
| 2020-12-20T20:19:56
| 2020-12-20T20:19:56
| 322,738,406
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 572
|
h
|
#ifndef PROCESSOR_H
#define PROCESSOR_H
#include <unistd.h>
#include <cctype>
#include <sstream>
#include <string>
#include <vector>
#include <iostream>
#include "linux_parser.h"
#include "process.h"
class Processor {
public:
float Utilization(); // TODO: See src/processor.cpp
void Utilization(float) ;
void calculateUtil() ;
// TODO: Declare any necessary private members
private:
float UtilizationValue ;
long long int prevuser{0}, prevnice{0}, prevsystem{0}, previrq{0}, prevsoftirq{0}, prevsteal{0}, previdle{0} , previowait{0};
};
#endif
|
[
"abdulrahman.tharwat.92@gmail.com"
] |
abdulrahman.tharwat.92@gmail.com
|
a6049440b285bea6100c834f1cf2b149a455e9cb
|
c85657463ea896571f28aaead3825b52baf199bd
|
/devices/vortex6000/src/vortex6000Main.cpp
|
7683f3138e560974554c4926fc46083ed7e6fbad
|
[] |
no_license
|
jasonhogan/sti
|
ffc9469557bf1480aae4004321d261bb5473e237
|
928428767b8c4131fa342dbbc2bf2e5cbea7340a
|
refs/heads/master
| 2021-07-12T17:55:26.696064
| 2020-08-10T20:56:56
| 2020-08-10T20:56:56
| 19,015,405
| 1
| 1
| null | 2018-04-04T03:14:44
| 2014-04-22T03:09:49
|
C++
|
UTF-8
|
C++
| false
| false
| 1,541
|
cpp
|
/*! \file gpib_hub_main.cpp
* \author David M.S. Johnson
* \brief main()
* \section license License
*
* Copyright (C) 2009 David Johnson <david.m.johnson@stanford.edu>\n
* This file is part of the Stanford Timing Interface (STI).
*
* The STI is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The STI 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 the STI. If not, see <http://www.gnu.org/licenses/>.
*/
#include <string>
#include <iostream>
#include <ORBManager.h>
#include "vortex6000Device.h"
using namespace std;
ORBManager* orbManager;
int main(int argc, char **argv)
{
orbManager = new ORBManager(argc, argv);
unsigned short gpibAddressMaster = 1;
unsigned short gpibAddressSlave = 2;
//unsigned short module = gpibAddress;
vortex6000Device scanningVortex(orbManager, "Scanning Vortex", "eplittletable.stanford.edu", gpibAddressSlave, gpibAddressSlave, false);
vortex6000Device masterVortex(orbManager, "Vortex6000", "eplittletable.stanford.edu", gpibAddressMaster, gpibAddressMaster, true);
orbManager->run();
return 0;
}
|
[
"EP@8bcac300-4d60-4aec-84ba-b7489f70e69b"
] |
EP@8bcac300-4d60-4aec-84ba-b7489f70e69b
|
f27e68ee794293174119bd210f103d4bf5a6227a
|
cda0d5938517306105c9acbe33c4024849d65841
|
/main.cpp
|
54ddaa9dda6aeb3065e0b14e2220e2bf1b779d68
|
[] |
no_license
|
Jalal14/Baket-ball
|
dec9a65baf5a8fa25f0dd3e3192434adecc0787a
|
d2cab8b4b985f0ca21ba8f7ace2b4979033a261f
|
refs/heads/master
| 2020-03-15T18:26:09.672523
| 2018-05-05T20:51:06
| 2018-05-05T20:51:06
| 132,283,483
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 10,463
|
cpp
|
/**
ballX => ball's X coordinate
ballY => ball's Y coordinate
ballR => ball's Radius
meterA => throwing angle
meterAX => throwing angle meter X coordinate
meterAY => throwing angle meter Y coordinate
meterAR => throwing angle meter radius
meterBX => speed meter X coordinate
meterBY => speed meter Y coordinate
basketX => basket X coordinate
**/
#include <windows.h>
#include <GL/glut.h>
#include <bits/stdc++.h>
#include <unistd.h>
using namespace std;
int restart = 0;
float ballX = 230,ballY = 160,ballR = 10;
int meterA = 72, speed = 60;
int meterAX = 50, meterAY = 50, meterAR = 30;
int meterBX = 100, meterBY = 50;
float basketX = 600, basketY = 300;
clock_t timeStart;
bool startGame = false;
bool success = false, crossX = false, crossY = false, crossDisplay = false;
float successX = 0;
float currentX= 0, currentState = 0;
float degree = 0;
int bestScore = 0;
int life = 5, score = 0;
void drawBall(float x, float y, float r);
void moveBall(float x, float y, float r);
void drawBasket(int basket);
void drawAngleMeter(int degree);
void drawSpeedMeter(int height);
void drawBackground();
void myInit (void);
void myDisplay(void);
void keyListener(int key,int, int);
void draw_object();
void draw_circle(float x, float y, float w, float h);
void drawFilledCircle(GLfloat x, GLfloat y, GLfloat radius){
int i;
int triangleAmount = 20; //# of triangles used to draw circle
//GLfloat radius = 0.8f; //radius
GLfloat twicePi = 2.0f * 3.1416;
glBegin(GL_TRIANGLE_FAN);
glVertex2f(x, y); // center of circle
for(i = 0; i <= triangleAmount;i++) {
glVertex2f(
x + (radius * cos(i * twicePi / triangleAmount)),
y + (radius * sin(i * twicePi / triangleAmount))
);
}
glEnd();
}
void draw_object()
{
//sky
glColor3f(0.0,0.9,0.9);
glBegin(GL_POLYGON);
glVertex2f(0,250);
glVertex2f(0,700);
glVertex2f(1100,700);
glVertex2f(1100,250);
glEnd();
//grass
glColor3f(0.0,0.9,0.0);
glBegin(GL_POLYGON);
glVertex2f(0,0);
glVertex2f(0,250);
glVertex2f(1200,250);
glVertex2f(1100,0);
glEnd();
//compound
glColor3f(0.7,0.7,0.7);
glBegin(GL_POLYGON);
glVertex2f(basketX-15,basketY-145);
glVertex2f(basketX-15,basketY-160);
glVertex2f(basketX+15,basketY-160);
glVertex2f(basketX+15,basketY-145);
glEnd();
glColor3f(1.0,1.0,1.0);
//cloud1
drawFilledCircle(50.0,400.0,20.0);
drawFilledCircle(70.0,420.0,20.5);
drawFilledCircle(80.0,390.0,21.5);
drawFilledCircle(100.0,400.0,20.0);
drawFilledCircle(120.0,420.0,20.5);
drawFilledCircle(125.0,390.0,21.5);
//cloud2
drawFilledCircle(200.0,400.0,20.0);
drawFilledCircle(220.0,420.0,20.5);
drawFilledCircle(230.0,390.0,21.5);
drawFilledCircle(250.0,400.0,20.0);
drawFilledCircle(270.0,420.0,20.5);
drawFilledCircle(280.0,390.0,21.5);
//cloud3
drawFilledCircle(400.0,400.0,20.0);
drawFilledCircle(420.0,420.0,20.5);
drawFilledCircle(430.0,390.0,21.5);
drawFilledCircle(450.0,400.0,20.0);
drawFilledCircle(470.0,420.0,20.5);
drawFilledCircle(480.0,390.0,21.5);
}
void draw_circle(float x, float y, float w, float h){
glBegin(GL_TRIANGLE_FAN);
for(int i=0; i<360; i++){
float degree = i * 3.1416 / 180.0;
glVertex2f(w*cos(degree)+x, h*sin(degree)+y);
}
glEnd();
}
void drawBackground(){
draw_object();
}
void drawBall(float x, float y, float r){
if((x > basketX-50 && x< basketX - 25) && (y> basketY-2 && y < basketY+2)){
if(success == false){
life++;
score++;
if(score>bestScore){
bestScore = score;
}
system("cls");
cout<<"score->"<<score<<"\n";
cout<<"Best score->"<<bestScore<<"\n";
}
successX = x;
success = true;
}
if(success){
x = successX;
glColor3f (1.0, 0.0, 0.0);
}
else{
glColor3f (1.0, 0.65, 0.0);
}
glBegin(GL_TRIANGLE_FAN);
for(int i=0; i<360; i++){
degree = i * 3.1416 / 180.0;
glVertex2f(r*cos(degree)+x, r*sin(degree)+y);
}
glEnd();
}
void moveBall(float x, float y, float r){
if(life<=0){
return;
}
if(!startGame){
float angle = 0;
glBegin(GL_TRIANGLE_FAN);
glColor3f (1.0, 0.65, 0.0);
if(!startGame){
for(int i=0; i<360; i++){
angle = i * 3.1416 / 180.0;
glVertex2f(ballR*cos(angle)+ballX, ballR*sin(angle)+ballY);
}
}
glEnd();
return;
}
float duration = (clock() - timeStart) / (float) CLOCKS_PER_SEC * 5;
float prX = (speed+20) * cos(meterA * 3.1416 / 180.0) * duration;
float prY = (speed+20) * sin(meterA * 3.1416 / 180.0) * duration - (0.5 * 9.8 * duration * duration);
float backX = (ballX+prX) - (basketX - 20);
if(!crossX && !crossY){
drawBall(ballX+prX, ballY+prY, r);
}else if(crossX && !crossY){
drawBall( basketX - backX, ballY+prY, r);
}else if(!crossX && crossY){
if(ballY+prY < basketY-145){
meterA = 0;
speed =0;
life--;
startGame = false;
}
else{
drawBall(currentState, basketY-145, r);
}
}else{
life--;
startGame = false;
drawBall(currentX, basketY-145, r);
meterA = 0;
speed =0;
}
if((ballX+prX < basketX - 8) && (ballX+prX > basketX - 13) && (ballY+prY < basketY + 51)){
crossX = true;
}
if(ballY+prY < basketY-145){
crossY = true;
timeStart = clock();
currentState = ballX + prX;
currentX= basketX - backX;
}
if(ballX+prX < basketX+20 && ballY+prY < basketY-145){
life--;
startGame = false;
meterA = 0;
speed =0;
}
if(ballX+prX > basketX+25 && !crossX){
life--;
startGame = false;
meterA = 0;
speed =0;
}
}
void drawLifeBar(){
int l = life;
glColor3f(1,0,0);
glBegin(GL_LINE_LOOP);
glVertex2i(50, 450);
glVertex2i(200, 450);
glVertex2i(200, 460);
glVertex2i(50, 460);
glEnd();
glBegin(GL_POLYGON);
if(life>5){
l = 5;
}
glVertex2i(50, 450);
glVertex2i(50+l*30, 450);
glVertex2i(50+l*30, 460);
glVertex2i(50, 460);
glEnd();
glColor3f(1,1,1);
glBegin(GL_LINES);
for(int i=1; i<5; i++){
glVertex2i(50+i*30, 460);
glVertex2i(50+i*30, 450);
}
glEnd();
}
void drawBasket(){
glColor3f (0.3333, 0.3333, 0.3333);
glBegin(GL_POLYGON);
glVertex2i(basketX, basketY+3);
glVertex2i(basketX-20, basketY+3);
glVertex2i(basketX-20, basketY-2);
glVertex2i(basketX, basketY-2);
glVertex2i(basketX, basketY-150);
glVertex2i(basketX+5, basketY-150);
glVertex2i(basketX+5, basketY+50);
glVertex2i(basketX, basketY+50);
glEnd();
float degree = 0;
glBegin(GL_POINTS);
for(int i=0; i<360; i++){
degree = i * 3.1416 / 180.0;
glVertex2f(20*cos(degree)+basketX-39, 7*sin(degree)+basketY);
}
glEnd();
}
void drawAngleMeter(int degree){
glColor3f (1.0, 0.0, 0.0);
float angle = 0;
glBegin(GL_POINTS);
for(int i=0; i<180; i++){
angle = i * 3.1416 / 180.0;
glVertex2f(meterAR*cos(angle)+meterAX, meterAR*sin(angle)+meterAY);
}
glEnd();
float rad = degree * 3.1416 / 180.0;
float x = meterAR*cos(rad) + meterAX;
float y = meterAR*sin(rad) + meterAY;
glBegin(GL_LINES);
glVertex2f(meterAX,meterAY);
glVertex2f(x, y);
glEnd();
}
void drawSpeedMeter(int height){
glColor3f (1.0, 0.0, 0.0);
glBegin(GL_LINE_LOOP);
glVertex2f(meterBX ,meterBY);
glVertex2f(meterBX + 10,meterBY);
glVertex2f(meterBX + 10,meterBY + 100);
glVertex2f(meterBX ,meterBY + 100);
glEnd();
glBegin(GL_POLYGON);
glVertex2f(meterBX ,meterBY );
glVertex2f(meterBX + 10,meterBY);
glVertex2f(meterBX + 10,meterBY + height);
glVertex2f(meterBX , meterBY + height);
//glVertex2f(meterBX , meterBY);
glEnd();
}
void myInit (void)
{
glClearColor(1.0, 1.0, 1.0, 1.0);
glColor3f(0.0f, 0.0f, 0.0f);
glPointSize(1.0);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluOrtho2D(0.0, 640.0, 0.0, 480.0);
}
void myDisplay(void)
{
glClear (GL_COLOR_BUFFER_BIT);
drawBackground();
drawBasket();
moveBall(ballX,ballY,ballR);
drawAngleMeter(meterA);
drawSpeedMeter(speed);
drawLifeBar();
glFlush();
glutPostRedisplay();
}
void restartGame(unsigned char key, int ,int){
switch(key){
case 'r':{
if(!life){
life = 5;
score = 0;
startGame = false;
crossX = crossY = success = false;
}
break;
}
case ' ' : {
if(!startGame){
startGame = true;
timeStart = clock();
crossX = crossY = success = false;
break;
}
}
}
}
void keyListener(int key,int, int){
switch(key){
case GLUT_KEY_LEFT: {
if(!startGame){
meterA++;
if(meterA > 90){
meterA=90;
}
}
break;
}
case GLUT_KEY_RIGHT:{
if(!startGame){
meterA--;
if(meterA < 0){
meterA=0;
}
}
break;
}
case GLUT_KEY_UP: {
if(!startGame){
speed++;
if(speed>100){
speed = 100;
}
}
break;
}
case GLUT_KEY_DOWN: {
if(!startGame){
speed--;
if(speed<0){
speed = 0;
}
} break;
}
case GLUT_KEY_END: {
if(life<=0){
exit(0);
}
}
}
}
int main(int argc, char** argv)
{
glutInitDisplayMode (GLUT_SINGLE | GLUT_RGB);
glutInitWindowSize (1080, 810);
glutInitWindowPosition (200, 200);
glutCreateWindow ("Basketball");
myInit();
glutDisplayFunc(myDisplay);
glutSpecialFunc(keyListener);
glutKeyboardFunc(restartGame);
glutMainLoop();
}
|
[
"jalaluddin_csse14@yahoo.com"
] |
jalaluddin_csse14@yahoo.com
|
93e8482fa12d4d6d54a1911f5e2bed22ac6591ef
|
ba63886c2366679dbd132a1142bd55cf8870b0bf
|
/lab_03/implementation/visitor/draw_visitor/draw_visitor.cpp
|
3b5a0727a9e4488f93d60b0a0d1f166f83e7ae45
|
[] |
no_license
|
ivaaahn/bmstu-oop
|
27d2edf96584ba784e112c7b0b69b2eab00f5f6b
|
bcbf6d289f782d5104860c60eb99f5206bf3f5d9
|
refs/heads/main
| 2023-05-13T03:19:35.359648
| 2021-06-08T11:40:47
| 2021-06-08T11:40:47
| 345,132,023
| 4
| 1
| null | 2021-03-12T13:39:46
| 2021-03-06T15:51:04
| null |
UTF-8
|
C++
| false
| false
| 1,202
|
cpp
|
//
// Created by ivaaahn on 30.05.2021.
//
#include <iostream>
#include <scene/scene.hpp>
#include "draw_visitor.hpp"
#include "drawer/drawer.hpp"
#include "objects/model/model.hpp"
DrawVisitor::DrawVisitor(const std::shared_ptr<Drawer> &drawer, const std::shared_ptr<Camera> &camera) : drawer(drawer),
camera(camera) {}
void DrawVisitor::visit(const Model &model) {
auto points = model.getDetails()->getPoints();
for (const auto &edge : model.getDetails()->getEdges())
this->drawer->drawLine(
this->projectPoint(points.at(edge.getFirst())),
this->projectPoint(points.at(edge.getSecond())));
}
Point DrawVisitor::projectPoint(const Point &point) {
Point new_point(point);
Point camera_position(this->camera->getPosition());
new_point.setX(new_point.getX() - camera_position.getX());
new_point.setY(new_point.getY() - camera_position.getY());
return new_point;
}
void DrawVisitor::visit(const Camera &camera) {}
void DrawVisitor::visit(const Scene &scene) {}
void DrawVisitor::visit(const Composite &composite) {}
|
[
"ivahnencko01@gmail.com"
] |
ivahnencko01@gmail.com
|
f34d7e2116c7eb7994519a3c2df83117a47ee80b
|
304dcc859ff1bad63ae881a096e687f7dc3de04b
|
/Test_PC_Poker/framework_externals/ExternalLib/Camel.Base/include/Camel/Base/System/SharedPtr.h
|
2b0b2a9e67d15ce784bbd8afe7ecbfa39ca5958c
|
[] |
no_license
|
idh37/testrepo
|
03e416b115563cf62a4436f7a278eda2cd05d115
|
b07cdd22bd42356522a599963f031a6294e14065
|
refs/heads/master
| 2020-07-11T00:57:34.526556
| 2019-09-10T07:22:35
| 2019-09-10T07:22:35
| 204,413,346
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,652
|
h
|
#ifndef __Camel_Base_System_TPL_SharedPtr__
#define __Camel_Base_System_TPL_SharedPtr__
#include "SystemBase.h"
#include "MPHeap.h"
#include "Interlocked.h"
#include <algorithm>
#include <cassert>
_DECLARE_NAMESPACE_CAMEL_BASE_SYSTEM_
namespace TPL
{
template<typename T>
class SharedPtr
{
private:
T *p_;
unsigned int *count_;
private:
template<typename U> friend class SharedPtr;
public:
SharedPtr(void)
: p_(NULL),
count_(static_cast<unsigned int *>(MPHeap::Alloc(NULL, sizeof(unsigned int))))
{
if (count_ == NULL)
{
throw std::bad_alloc();
}
*count_ = 1;
}
explicit SharedPtr(T *p)
: p_(p),
count_(static_cast<unsigned int *>(MPHeap::Alloc(NULL, sizeof(unsigned int))))
{
if (count_ == NULL)
{
throw std::bad_alloc();
}
*count_ = 1;
}
SharedPtr(const SharedPtr &rhs)
: p_(rhs.p_),
count_(rhs.count_)
{
Threading::Interlocked::Increment(rhs.count_);
}
template<typename U>
SharedPtr(const SharedPtr<U> &rhs)
: p_(rhs.p_),
count_(rhs.count_)
{
Threading::Interlocked::Increment(rhs.count_);
}
~SharedPtr(void)
{
if (Threading::Interlocked::Decrement(count_) == 0)
{
MPHeap::Free(NULL, count_);
count_ = NULL;
delete p_;
p_ = NULL;
}
}
void Reset(void)
{
SharedPtr().Swap(*this);
}
template<typename U>
void Reset(U *p)
{
assert(p == 0 || p != p_); // catch self-reset errors
SharedPtr(p).Swap(*this);
}
void Swap(SharedPtr &rhs)
{
std::swap(p_, rhs.p_);
std::swap(count_, rhs.count_);
}
T *GetRawPtr(void) const
{
return p_;
}
T *operator->() const
{
return p_;
}
T &operator*() const
{
return *p_;
}
friend bool operator==(const SharedPtr<T>& rhs, const SharedPtr<T>& lhs)
{
return (rhs.GetRawPtr() == lhs.GetRawPtr());
}
bool operator!() const // Enables "if (!sp) ..."
{
return p_ == NULL;
}
SharedPtr &operator=(const SharedPtr &rhs)
{
SharedPtr(rhs).Swap(*this);
return *this;
}
template<typename U>
SharedPtr &operator=(const SharedPtr<U> &rhs)
{
SharedPtr(rhs).Swap(*this);
return *this;
}
SharedPtr<T> lock() const
{
SharedPtr<T> result;
if (p_ != NULL)
{
int old_count;
do
{
old_count = *count_;
if (old_count == 0)
{
break;
}
}
while (old_count != Threading::Interlocked::CompareExchange(count_, old_count + 1, old_count));
if (old_count > 0)
{
result.p_ = p_;
result.count_ = count_;
}
}
return result;
}
};
}
_UNDECLARE_NAMESPACE_CAMEL_BASE_SYSTEM_
#endif // __Camel_Base_System_TPL_SharedPtr__
|
[
"idh37@nm-4ones.com"
] |
idh37@nm-4ones.com
|
8f2b69d618ed9a213c980a75ab8d10cf8803bfcd
|
6d0386587c23b9a9374813f30fef10cac55aa4d8
|
/gunhound/src/gunhound/vii_src/Enemy/HoundsEnemy/CEneH0008BloodSocker.h
|
8ad9b8ec9316dbc266510ecfeac8b3e2f2e6cb83
|
[] |
no_license
|
t-mat/gunhound-easybuild
|
5b3c136205917a53a5d438b0498c7ead992e2416
|
e5c6d8fc792ea0aebf86c1743375b9356c2087bb
|
refs/heads/master
| 2020-04-06T07:09:37.246153
| 2016-09-10T19:00:32
| 2016-09-10T19:00:32
| 65,155,314
| 3
| 0
| null | null | null | null |
SHIFT_JIS
|
C++
| false
| false
| 3,035
|
h
|
//--------------------------------------------------------------------------------
//
// Stage00:ボルゾイ(ブラッドサッカー)
//
//--------------------------------------------------------------------------------
class CAtkH0001Thunder;
class CEneH0008BloodSocker : public CEnemyBase , public CHoundEnemyBase
{
public:
CEneH0008BloodSocker( Sint32 x, Sint32 y );
~CEneH0008BloodSocker();
void SeqInit();
void SeqMain();
void SeqCrash();
void Draw();
//ボルゾイのカスタマイズ
void SetCustomIndex(Sint32 n);
private:
enum
{
enWeaponMax = 8,
};
//初期化
void SetInitialize();
void SetCustomize( Sint32 sBody ,Sint32 sArm , Sint32 sLeg);
void SetArms();
void WeaponReset();
//攻撃
void Atack( Sint32 sAtk );
//毎フレームの処理
void ActionMain();
//腕角度補正
void AdjustArmAngle( Sint32 ax , Sint32 ay ,Sint32 sOffset=0);
//武器チェンジ可能か?
gxBool IsWeaponChangeChance();
//-----------------------------
//攻撃
//-----------------------------
void AtackShortBurrel(); //クラッシャーを乱射
void AtackLongBurrel(); //実弾を狙い撃ちしてくる
void AtackSolidShooter(); //狙い撃ちバズーカ
void AtackShoulderMissilePod(); //追尾式ミサイル
void AtackLogGun(); //溜め打ち極太レーザー
void AtackLegPod(); //2連式巡航ミニミサイル
void AtackBodyCrasher(); //2連式巡航ミニミサイル
//-----------------------------
//ロジック制御関連
//-----------------------------
void LogicAI();
void PadControl(Sint32 n);
//-----------------------------
//パーツ番号管理用
//-----------------------------
Sint32 m_sBody;
Sint32 m_sLegs;
Sint32 m_sArms;
//-----------------------------
//攻撃制御関連
//-----------------------------
Sint32 m_sWeapon[enWeaponMax]; //武器番号保存用
Sint32 m_sWeaponNum; //手持ちの武器の数
Sint32 m_sMainWeapon; //現在選択中の武器
Sint32 m_sBackWait; //ノックバック時間
Sint32 m_sReboundWait; //バズーカ腕のリバウンド処理
Sint32 m_sTargetSeq; //ターゲット方向補正制御
Sint32 m_sArmRotation; //ターゲット方向補正用アーム角度
Sint32 m_sCrashTimer; //破壊されるまでのタイムラグ
gxBool m_bGuard; //ガード属性判定
gxBool m_bArmCrash; //アームクラッシュ
//CEffAtkLaser *m_pLaser; //レーザー制御用
CAtkH0001Thunder *m_pLaser;
gxBool m_bLaser;
//-----------------------------
//ロジック制御関連
//-----------------------------
Sint32 m_sPushControl;
Sint32 m_sTrigControl;
Sint32 m_sAtackLag; //射撃間のタイムラグ
Sint32 m_sAtackCnt; //攻撃回数
//-----------------------------
//その他
//-----------------------------
OBJ_POS_T m_Src; //初期位置
OBJ_POS_T m_Grd; //初期位置
CHitCollision m_HitKurai;
CHitCollision m_HitGuard; //ガード用
CEasyLeynos m_Leynos;
gxBool m_bSpecialVersion;
gxBool m_bEscaped;
};
|
[
"takayuki.matsuoka@gmail.com"
] |
takayuki.matsuoka@gmail.com
|
fbb569e325ff20c749da06c317acf9a85fafa13d
|
07d3e9ffed73b46227bf2087ed66c1da011f66b1
|
/beginner/Area count.cpp
|
800fad2113d3ad2203854a0baee84ad547ad6161
|
[] |
no_license
|
jinzero-kim/Coding-Algorithm
|
aab61033a900547ed69939d095c0d721c8677dd6
|
5fda3b24d74a76b798259ee5c53638bc4948a08e
|
refs/heads/master
| 2022-12-08T17:36:01.836072
| 2020-09-04T02:53:50
| 2020-09-04T02:53:50
| 287,963,344
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,226
|
cpp
|
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int m,n,k;
int map[101][101];
int a[101],t;
int dx[4] = { 0,0,-1,1 };
int dy[4] = {-1,1,0,0 };
void dfs(int i, int j) {
if (i < 0 || j < 0 || i>m - 1 || j>n - 1) return;
if (map[i][j] != 0) return;
map[i][j] = 1;
a[t]++;
for (int m = 0; m < 4; m++) {
dfs(i + dx[m], j + dy[m]);
}
}
int main(void) {
clock_t start, end;
double result;
start = clock();
scanf("%d %d %d", &m, &n, &k);
int x1,y1,x2,y2;
for (int i = 0; i < k; i++) {
scanf("%d %d %d %d", &y1, &x1, &y2, &x2);
for (int y = y1; y < y2; y++) {
for (int x = x1; x < x2; x++) {
map[x][y] = 1;
}
}
}
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (map[i][j] == 0) {
dfs(i, j);
t++;
}
}
}
printf("%d\n", t);
int temp=0;
for (int i = 0; i < t-1; i++) {
for(int j=0;j< t-1-i; j++) {
if (a[j] > a[j + 1]) {
temp = a[j];
a[j] = a[j + 1];
a[j + 1] = temp;
}
}
}
for (int i = 0; i < t; i++) {
printf("%d ", a[i]);
}
printf("\n");
end = clock();
result = (double)(end - start);
printf("%f", result/CLOCKS_PER_SEC);
return 0;
}
|
[
"noreply@github.com"
] |
jinzero-kim.noreply@github.com
|
f20de33998f9b69aa794a04fee8eaafd58e96148
|
e649acb68fc5134a3843ef2330e5c2d4070363a8
|
/H.weak_memory.cpp
|
b6be5b44195efc485fc6495577cfeef31ec18b53
|
[] |
no_license
|
jesuswr/cp-codes-and-problems
|
6483949ce896e59c471f0e0640f5c8b47f482ec3
|
770f3bf004f90015f078d5699d26cde5c33d9a28
|
refs/heads/master
| 2023-08-08T03:37:36.626572
| 2023-07-24T16:54:02
| 2023-07-24T16:54:02
| 196,292,128
| 1
| 1
| null | 2019-10-09T23:23:43
| 2019-07-11T00:26:10
|
C++
|
UTF-8
|
C++
| false
| false
| 3,028
|
cpp
|
#include <iostream>
#include <vector>
#include <queue>
#include <stack>
#include <algorithm>
#include <math.h>
#include <string>
#include <cstring>
#include <set>
#include <map>
#include <unordered_map>
using namespace std;
typedef long long ll;
typedef pair<int, int> pii;
typedef pair<int, pair<int, int>> piii;
typedef vector<int> vi;
typedef vector<pii> vii;
#define ri(a) scanf("%d", &a)
#define rii(a,b) scanf("%d %d", &a, &b)
#define riii(a,b,c) scanf("%d %d %d", &a, &b, &c)
#define rl(a) scanf("%lld", &a)
#define rll(a,b) scanf("%lld %lld", &a, &b)
#define FOR(i,n,m) for(int i=n; i<m; i++)
#define ROF(i,n,m) for(int i=n; i>m; i--)
#define pb push_back
#define lb lower_bound
#define ub upper_bound
#define F first
#define S second
const int INF = 0x3f3f3f3f;
const ll LLINF = 1e18;
const int maxN = 1e5 + 10; // CAMBIAR ESTE
// GJNM
int v, e, k;
vi G[maxN];
int START, END;
bool SPECIAL[maxN];
int father[maxN], siz[maxN];
// n es el primer elemento y m el ultimo, por ejemplo los nodos de un grafo desde el 1 al 10
void makeSet(int n, int m) {
for (int i = n; i <= m; ++i) {
father[i] = -1;
siz[i] = 0;
}
}
int find(int x) {
if (father[x] == -1) // -1 significa que es el representante del set
return x;
return father[x] = find(father[x]);
}
void unio(int x, int y) { // x y y tienen que ser los representantes
if (siz[x] > siz[y])
father[y] = x;
else {
father[x] = y;
if ( siz[x] == siz[y] ) siz[y]++;
}
}
int C[maxN];
bool check(int q) {
makeSet(0, v);
queue<int> curr;
set<int> active;
FOR(i, 0, v) {
if ( SPECIAL[i] ) {
active.insert(i);
curr.push(i);
}
}
curr.push(END), active.insert(END);
FOR(i, 0, q / 2) {
int n = curr.size();
if ( find(START) == find(END) )
return true;
FOR(j, 0, n) {
int x = curr.front(); curr.pop();
for (auto &y : G[x]) {
if ( find(x) != find(y) )
unio(find(x), find(y));
if ( !active.count(y) ) {
active.insert(y);
curr.push(y);
}
}
}
}
if ( q & 1 ) {
for (auto &i : active) {
for (auto &y : G[i]) {
if ( find(i) != find(y) && (active.count(y) > 0) )
unio(find(i), find(y));
}
}
}
return find(START) == find(END);
}
int DIST[maxN];
bool vis[maxN];
int AYUDA = INF;
void bfs(int e) {
vis[e] = true;
DIST[e] = 0;
queue<int> q;
q.push(e);
while (!q.empty()) {
int x = q.front(); q.pop();
if ( x == START )
return;
if ( SPECIAL[x] )
AYUDA = min(AYUDA, DIST[x]);
for (auto y : G[x]) {
if (!vis[y]) {
DIST[y] = DIST[x] + 1;
vis[y] = true;
q.push(y);
}
}
}
printf("-1\n");
exit(0);
}
int main() {
riii(v, e, k);
FOR(i, 0, k) {
int aux;
ri(aux);
SPECIAL[aux - 1] = true;
}
FOR(i, 0, e) {
int a, b;
rii(a, b);
a--, b--;
G[a].pb(b);
G[b].pb(a);
}
rii(START, END);
START--, END--;
bfs(END);
int lo = AYUDA, hi = DIST[START];
while ( lo < hi ) {
FOR(i, 0, v)
C[i] = -1;
int mid = lo + (hi - lo) / 2;
if ( check(mid) )
hi = mid;
else
lo = mid + 1;
}
printf("%d\n", hi);
return 0;
}
|
[
"jesuswahrman@gmail.com"
] |
jesuswahrman@gmail.com
|
e4e3ea29491d4c59cc27cfd64909e23ac8a19be2
|
75860ed58e19ee7b724428a6e99419213d3e3906
|
/src/Lists/PersistedObjectListController.hpp
|
4dec2ca1933b846662e0b8a5f3e3e62cb6cce9ab
|
[
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
nobrick/mymonero-libapp-cpp
|
2d5279dc32b0d17c190144be8c0cee6361acdc66
|
c85b24d99e07e893c98d1af83ce24f0057269c2c
|
refs/heads/master
| 2020-05-31T23:06:38.879877
| 2019-05-20T21:37:03
| 2019-05-20T21:37:03
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 7,906
|
hpp
|
//
// PersistedObjectListController.hpp
// MyMonero
//
// Copyright (c) 2014-2019, MyMonero.com
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification, are
// permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this list of
// conditions and the following disclaimer.
//
// 2. 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.
//
// 3. Neither the name of the copyright holder nor the names of its contributors may be
// used to endorse or promote products derived from this software without specific
// prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
// THE COPYRIGHT HOLDER 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.
//
//
#ifndef PersistedObjectListController_hpp
#define PersistedObjectListController_hpp
#include <string>
#include <boost/optional/optional.hpp>
#include <boost/signals2.hpp>
#include <boost/uuid/uuid.hpp> // uuid class
#include <boost/uuid/uuid_generators.hpp> // generators
#include <memory>
#include "../Persistence/document_persister.hpp"
#include "../Persistence/PersistableObject.hpp"
#include "../Dispatch/Dispatch_Interface.hpp"
#include "../Passwords/PasswordController.hpp"
namespace Lists
{
using namespace std;
using namespace boost;
using namespace document_persister;
//
// Comparators
static inline bool comparePersistableObjectSharedPtrBy_insertedAt_asc(
std::shared_ptr<Persistable::Object> l,
std::shared_ptr<Persistable::Object> r
) {
if (l->insertedAt_sSinceEpoch == none) {
return false;
}
if (r->insertedAt_sSinceEpoch == none) {
return true;
}
return *(l->insertedAt_sSinceEpoch) <= *(r->insertedAt_sSinceEpoch);
}
//
// Controllers
class Controller:
public Passwords::DeleteEverythingRegistrant,
public Passwords::ChangePasswordRegistrant
{
public:
//
// Lifecycle - Init
Controller(const CollectionName &collectionName):
_listedObjectTypeCollectionName(collectionName) // copy
{
// set dependencies then call setup()
}
Controller(const Controller&) = delete; // disable copy constructor to prevent inadvertent temporary in pointer
Controller& operator=(const Controller&) = delete;
virtual ~Controller()
{
cout << "Destructing a ListController" << endl;
tearDown();
}
//
// Dependencies
std::shared_ptr<string> documentsPath;
std::shared_ptr<Dispatch::Dispatch> dispatch_ptr;
std::shared_ptr<Passwords::Controller> passwordController;
// Then call:
void setup();
//
virtual std::shared_ptr<Lists::Controller> get_shared_ptr_from_this() = 0; // Child classes must override and implement this with shared_from_this() and by inheriting std::enabled_shared_from_this<Child>
//
virtual void overridable_deferBootUntil( // overridable
std::function<void(optional<string> err_str)> fn
) {
fn(boost::none); // make sure to call this
}
//
// Signals
boost::signals2::signal<void()> boot__did_signal;
boost::signals2::signal<void()> boot__failed_signal;
boost::signals2::signal<void()> list__updated_signal;
boost::signals2::signal<void()> record__deleted_signal;
//
// Protocols - PasswordControllerEventParticipant
std::string identifier() const
{
return uuid_string;
}
//
// Accessors
std::vector<std::shared_ptr<Persistable::Object>> records()
{ // accessing within the mutex and returning a copy so as to resolve possible mutability and consistency issues
// TODO: is this too expensive? are the pointers themselves being copied?
_records_mutex.lock();
auto r_copy = _records;
_records_mutex.unlock();
return r_copy;
}
bool hasBooted() const { return _hasBooted; }
//
// Accessors - Override
virtual std::shared_ptr<Persistable::Object> new_record(
std::shared_ptr<std::string> documentsPath,
std::shared_ptr<Passwords::PasswordProvider> passwordProvider,
const document_persister::DocumentJSON &plaintext_documentJSON
) = 0;
//
// Accessors - Overridable
virtual bool overridable_shouldSortOnEveryRecordAdditionAtRuntime()
{
return false; // default
}
virtual bool overridable_wantsRecordsAppendedNotPrepended()
{
return false; // default
}
//
// Imperatives - Execution Deferment
void onceBooted(std::function<void()> fn);
//
// Imperatives - CRUD
optional<string> givenBooted_delete(Persistable::Object &object);
optional<string> givenBooted_delete_noListUpdatedNotify(Persistable::Object &object);
//
// Imperatives - Overridable
virtual void overridable_finalizeAndSortRecords() {}
//
// Delegation - Overridable
virtual void overridable_booting_didReconstitute(std::shared_ptr<Persistable::Object> listedObjectInstance) {} // somewhat intentionally ignores errors and values which would be returned asynchronously, e.g. by way of a callback/block
//
// Delegation - Updates
void _atRuntime__record_wasSuccessfullySetUp(std::shared_ptr<Persistable::Object> listedObject); // this is to be called by subclasses
void _atRuntime__lockMutexAnd_record_wasSuccessfullySetUp_noSortNoListUpdated(std::shared_ptr<Persistable::Object> listedObject);
//
protected:
bool _hasBooted = false;
std::vector<std::shared_ptr<Persistable::Object>> _records;
std::mutex _records_mutex;
//
// Lifecycle
void setup_startObserving();
void tearDown();
void stopObserving();
//
// Delegation
void _listUpdated_records();
void __dispatchAsync_listUpdated_records();
//
private:
//
// Properties - Instance members
std::string uuid_string = boost::uuids::to_string((boost::uuids::random_generator())()); // cached
const CollectionName _listedObjectTypeCollectionName;
//
boost::signals2::connection connection__PasswordController_willDeconstructBootedStateAndClearPassword;
boost::signals2::connection connection__PasswordController_didDeconstructBootedStateAndClearPassword;
//
// Lifecycle
void setup_tryToBoot();
void startObserving_passwordController();
void setup_fetchAndReconstituteExistingRecords();
void _setup_didBoot();
void _setup_didFailToBoot(const string &err_str);
//
void _stopObserving_passwordController();
//
// Accessors
errOr_documentIds _new_idsOfPersistedRecords();
//
// Execution deferment
void _callAndFlushAllBlocksWaitingForBootToExecute();
optional<vector<std::function<void()>>> __blocksWaitingForBootToExecute = none;
//
// CRUD
void _removeFromList(Persistable::Object &object);
void _removeFromList_noListUpdatedNotify(Persistable::Object &object);
//
// Protocols - DeleteEverythingRegistrant
optional<string> passwordController_DeleteEverything();
// Protocols - ChangePasswordRegistrant
optional<Passwords::EnterPW_Fn_ValidationErr_Code> passwordController_ChangePassword();
//
// Delegation - Notifications
void PasswordController_willDeconstructBootedStateAndClearPassword();
void PasswordController_didDeconstructBootedStateAndClearPassword();
};
}
#endif /* PersistedObjectListController_hpp */
|
[
"paulshapiro@users.noreply.github.com"
] |
paulshapiro@users.noreply.github.com
|
b7142cc82c58bbf5d5f2913185946f0a5a480058
|
0ce585a428b1d1f3774a58781f99614b1bfac278
|
/libevent_http_frame/frame/libevent_http_frame.cpp
|
d88d3794dfcd3e1a2968c77a97a553b43d676d87
|
[] |
no_license
|
CaseZheng/SimpleServerFramework
|
659728d5e41f57e654873b27ab93189bf41d6ea5
|
f2c7f0019b406385a76f2e3b193a84568d0c59e5
|
refs/heads/master
| 2021-07-03T19:06:58.725622
| 2019-03-11T16:07:16
| 2019-03-11T16:07:16
| 124,250,589
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 648
|
cpp
|
#include <boost/shared_ptr.hpp>
#include "libevent_http_frame.h"
#include "log.h"
bool CLibeventHttpFrame::Init(const string &strServerName, const string &strConfPath)
{
if(!CLibeventFrame::Init(strServerName, strConfPath))
{
ERROR("Function failure CLibeventFrame::Init");
return false;
}
m_pHttpServer.reset(new CHttpServer(m_pEventBase));
if(NULL == m_pHttpServer)
{
ERROR("CHttpServer new failure");
return false;
}
if(!m_pHttpServer->Init())
{
ERROR("HttpServer Init failure");
return false;
}
DEBUG("HttpServer Init success");
return true;
}
|
[
"764307915@qq.com"
] |
764307915@qq.com
|
c1c188e308ae0fe7e7a71b0f1dcc8afaa0c42540
|
fd240741384ec0d304b3591bc6edc8548db81c54
|
/src/search-skeleton/Model/Edge/Edge_V2/EdgeV2.hpp
|
3a1f91ee315dbdfa580343fdec2fa61ab90c99bd
|
[
"MIT"
] |
permissive
|
timoninas/diploma-2020
|
686023bca4eb1703ed17f8acfc0ad3400ccefa63
|
f111ed8b5eb46627921360f1d73f27094f1031c5
|
refs/heads/master
| 2023-05-06T10:43:29.925024
| 2021-06-02T19:47:06
| 2021-06-02T19:47:06
| 330,481,173
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,375
|
hpp
|
//
// EdgeV2.hpp
// search-skeleton
//
// Created by Антон Тимонин on 05.04.2021.
//
#ifndef EdgeV2_hpp
#define EdgeV2_hpp
#include "../../GraphLabel/GraphLabel.hpp"
#include "../../Point/Point_V1/Point.hpp"
#include <stdio.h>
#include <utility>
typedef struct edge_v2 {
int numberEdge;
std::pair<int, int> numberVertices;
GraphLabels label;
edge_v2() = delete;
edge_v2(int number, int numberVertex1, int numberVertex2):
numberEdge(number),
numberVertices(std::make_pair(numberVertex1, numberVertex2)),
label(GraphLabels::notvisited) { }
bool isNotvisited() {
return label == GraphLabels::notvisited;
}
bool isVisited() {
return label == GraphLabels::visited;
}
bool isInskeleton() {
return label == GraphLabels::inskeleton;
}
void swipeVertices() {
auto tmp = numberVertices.first;
numberVertices.first = numberVertices.second;
numberVertices.second = tmp;
}
} edge_v2_t;
struct cmp_v2 {
bool operator() (const edge_v2_t &a, const edge_v2_t &b) {
return a.numberVertices.first < b.numberVertices.first || a.numberVertices.second < b.numberVertices.second;
}
};
#endif /* EdgeV2_hpp */
|
[
"dotruger.37@gmail.com"
] |
dotruger.37@gmail.com
|
c7e21c79ce487e3bac74a8bd5a338c49635898f6
|
9df55ed98688ff13caec3061237a2a0895914577
|
/main.cpp
|
bd29e05649bceeeba97307229ac0bcc781176516
|
[] |
no_license
|
tiashaun/sdl_tetris
|
f625ee0f06e642411f7a04b18b470aa0df61c1ca
|
4799cfa4b28cd21b8431f8b6a00bacfb89e794f0
|
refs/heads/master
| 2020-11-30T23:32:43.812813
| 2009-12-06T20:33:43
| 2009-12-06T20:33:43
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 165
|
cpp
|
#include <iostream>
#include <SDL/SDL.h>
#include "Game.h"
int main(int argc, char* argv[]) {
Game *game = new Game();
game->startGame();
return 0;
}
|
[
"jarod.luebbert@gmail.com"
] |
jarod.luebbert@gmail.com
|
dbacec5d5d3801ab15b513051aadd8a637fa69e6
|
eeea48b3a280f835cc2b485bb3dca0ca45d2abe6
|
/Cylinder.h
|
e23ea16c9f65645cb13b5e7451117bc00b2c6eca
|
[] |
no_license
|
astpeepman/Graphics-pipeline-shading-OpenGL-
|
ad62e9fc3fc28dda4f73388f1df2a45e9cd1d231
|
bb9fe9c82b130226c5b7d0f7ed225ce4e574d5f3
|
refs/heads/master
| 2022-12-28T13:56:22.475776
| 2020-10-06T09:56:17
| 2020-10-06T09:56:17
| 301,448,801
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 699
|
h
|
#include <GL/glew.h>
#include <GLFW/glfw3.h>
#include "3dMath.h"
#include "Shader.h"
class Cylinder
{
private:
vec3 position;
GLfloat radius;
GLfloat height;
Shader shader;
mat4 model;
GLuint vertexVBO, normalsVBO, texcoordVBO, indicesVBO;
GLuint VAO, VBO;
GLsizei indicSize;
mat4 beginModel;
public:
Cylinder() {};
Cylinder(vec3 p, GLfloat r, Shader s, GLfloat h, int numberSlices);
void draw();
void setLightParam(vec3 ambient, vec3 diff, vec3 spec);
void setLightPos(vec3 p);
void setViewPos(vec3 p);
void setproj(mat4 prj);
void setview(mat4 view);
void setmaterial(vec3 am, vec3 diff, vec3 spec, GLfloat sh);
void Rotate(GLfloat angle, vec3 axis);
void Trans(vec3 pos);
};
|
[
"62560939+astpeepman@users.noreply.github.com"
] |
62560939+astpeepman@users.noreply.github.com
|
7395c930bef12ba020a5aba9133c2b29da2d6bde
|
dff2935d74bc50140eb757079732ed5237146d6b
|
/Juce Projects/AudioManagementTemplate/Source/BasicAudioProcessor.cpp
|
0431a62e80b28ecb31e9ee005dca91154bd80a53
|
[] |
no_license
|
brenthompson2/JUCE-Summer-Project
|
242639e0baefd6b636b10ee5a1392c198f5b3780
|
c0b60d71cc238a112b35c2e91324a9f4f2d086ca
|
refs/heads/master
| 2021-07-14T06:51:31.576271
| 2017-10-19T21:09:53
| 2017-10-19T21:09:53
| 94,351,946
| 2
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,742
|
cpp
|
/*
==============================================================================
BasicAudioProcessor.cpp
Updated: 08/06/17
Author: Brendan Thompson
A Basic Audio Processor that inherits from the AudioProcessor class
==============================================================================
*/
#include "BasicAudioProcessor.h"
#include "BasicAudioProcessorEditor.h"
//==============================================================================
// Constructor & Destructor
BasicAudioProcessor::BasicAudioProcessor(){
//BasicAudioProcessorEditor* theEditor = createEditor();
}
BasicAudioProcessor::~BasicAudioProcessor(){
}
// Create The Editor
AudioProcessorEditor* BasicAudioProcessor::createEditor(){
return new BasicAudioProcessorEditor (*this);
}
// This creates new instances of the processor? I don't think it's used
AudioProcessor* JUCE_CALLTYPE createPluginFilter()
{
return new BasicAudioProcessor;
}
//==============================================================================
// Public Audio Functions
void BasicAudioProcessor::prepareToPlay (double sampleRate, int samplesPerBlockExpected){
}
void BasicAudioProcessor::processBlock (AudioBuffer<double>& buffer, MidiBuffer& midiMessages){
process (buffer, midiMessages, delayBufferDouble);
}
void BasicAudioProcessor::releaseResources(){
}
//==============================================================================
// Private Methods:
template <typename FloatType>
void BasicAudioProcessor::process (AudioBuffer<FloatType>& buffer, MidiBuffer& midiMessages, AudioBuffer<FloatType>& delayBuffer){
}
|
[
"brenthompson2@gmail.com"
] |
brenthompson2@gmail.com
|
bc6a6e3b4ef1cf1ebc7ac3fdcb061bb7fdc7d274
|
b6adedeede3e21df8038de6d27103da22e1e2a8f
|
/protections1300VValueChangesTracked.cpp
|
7d6f3131f73e924db2cfa6a5d93a16c2a62a42b2
|
[] |
no_license
|
claymore2000/AmptGUI_X_5_15
|
fdd1054e2642654b2dbb2803afec19428096f4d7
|
88591032631865d5137163ebff2f9e978a604a97
|
refs/heads/master
| 2023-03-23T18:37:30.358533
| 2021-03-18T20:08:18
| 2021-03-18T20:08:18
| 349,204,092
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 21,153
|
cpp
|
#include "protections1300VValueChangesTracked.h"
#include "amptRegisterConstants.h"
#include "amptparameterblockconstants.h"
protectionsValueChangesTracked::protectionsValueChangesTracked( void )
{
resetAllTrackedValues(true);
}
protectionsValueChangesTracked::~protectionsValueChangesTracked( void )
{
}
void protectionsValueChangesTracked::sendAllChangedValues( void )
{
}
void protectionsValueChangesTracked::resetAllTrackedValues ( bool s )
{
qDebug() << Q_FUNC_INFO << " entering ...";
if (s)
qDebug() << Q_FUNC_INFO << " INFO: called with argument of " << s;
fetCountChanged = false;
fetCount = 0;
fetThresholdChanged = false;
fetThreshold = 0;
fetDeltaCurrentChanged = false;
fetDeltaCurrent = 0;
protection1Changed = false;
protection1 = 0;
protection2Changed = false;
protection2 = 0;
protection3Changed = false;
protection3 = 0;
protection4Changed = false;
protection4 = 0;
amfTimer1Changed = false;
amfTimer1 = 0;
amfTimer2Changed = false;
amfTimer2 = 0;
amfV_OVChanged = false;
amfV_OV = 0;
amfI_OCChanged = false;
amfI_OC = 0;
amfDebugChanged = false;
amfDebug = 0;
amfMPPOffCyclesChanged = false;
amfMPPOffCycles = 0;
amfMPPTimesOffChanged = false;
amfMPPTimesOff = 0;
efInputCurrentThresholdChanged = false;
efInputCurrentThreshold = 0;
efOccurrenceThresholdChanged = false;
efOccurrenceThreshold = 0;
efCountDownTimerChanged = false;
efCountDownTimer = 0;
efAlphaNumeratorChanged = false;
efAlphaNumerator = 0;
iinLimitChanged = false;
iinLimit = 0;
iinLimitOCStepsChanged = false;
iinLimitOCSteps = 0;
iinLimitOCDelayChanged = false;
iinLimitOCDelay = 0;
iinLimitTempAmbientAdjustChanged = false;
iinLimitTempAmbientAdjust = 0;
}
bool protectionsValueChangesTracked::getFETCountChanged( void )
{
// qDebug() << Q_FUNC_INFO << " returning " << QString::number(fetCountChanged);
return fetCountChanged;
}
void protectionsValueChangesTracked::changeFETCount(const int & s)
{
// qDebug() << Q_FUNC_INFO << " new value:" << s;
fetCount = s;
fetCountChanged = true;
}
bool protectionsValueChangesTracked::getIinLimitChanged( void )
{
return iinLimitChanged;
}
void protectionsValueChangesTracked::changeIinLimit( const unsigned int & s)
{
iinLimit = s;
iinLimitChanged = true;
}
bool protectionsValueChangesTracked::getIinLimitOCStepsChanged( void )
{
return iinLimitOCStepsChanged;
}
void protectionsValueChangesTracked::changeIinLimitOCSteps(const unsigned int & s)
{
iinLimitOCSteps = s;
iinLimitOCStepsChanged = true;
}
bool protectionsValueChangesTracked::getIinLimitOCDelayChanged( void )
{
return iinLimitOCDelayChanged;
}
void protectionsValueChangesTracked::changeIinLimitOCDelay(const unsigned int & s)
{
iinLimitOCDelay = s;
iinLimitOCDelayChanged = true;
}
bool protectionsValueChangesTracked::getIinLimitTempAmbientAdjustChanged( void )
{
return iinLimitTempAmbientAdjustChanged;
}
void protectionsValueChangesTracked::changeIinLimitTempAmbientAdjust(const signed int &s)
{
iinLimitTempAmbientAdjust = s;
iinLimitTempAmbientAdjustChanged = true;
}
bool protectionsValueChangesTracked::getEFInputCurrentThresholdChanged( void )
{
return efInputCurrentThresholdChanged;
}
void protectionsValueChangesTracked::changeEFInputCurrentThreshold( const unsigned int & s)
{
qDebug() << Q_FUNC_INFO << " new value:" << s;
efInputCurrentThreshold = s;
efInputCurrentThresholdChanged = true;
}
bool protectionsValueChangesTracked::getEFOccurrenceThresholdChanged( void )
{
return efOccurrenceThresholdChanged;
}
void protectionsValueChangesTracked::changeEFOccurrenceThreshold( const unsigned int & s)
{
qDebug() << Q_FUNC_INFO << " new value:" << s;
efOccurrenceThreshold = s;
efOccurrenceThresholdChanged = true;
}
bool protectionsValueChangesTracked::getEFCountDownTimerChanged( void )
{
return efCountDownTimerChanged;
}
void protectionsValueChangesTracked::changeEFCountDownTimer( const unsigned int & s)
{
qDebug() << Q_FUNC_INFO << " new value:" << s;
efCountDownTimer = s;
efCountDownTimerChanged = true;
}
bool protectionsValueChangesTracked::getEFAlphaNumeratorChanged( void )
{
return efAlphaNumeratorChanged;
}
void protectionsValueChangesTracked::changeEFAlphaNumerator( const unsigned int & s )
{
qDebug() << Q_FUNC_INFO << " new value:" << s;
efAlphaNumerator = s;
efAlphaNumeratorChanged = true;
}
bool protectionsValueChangesTracked::getFETThresholdChanged( void )
{
// qDebug() << Q_FUNC_INFO << " returning " << QString::number(fetThresholdChanged);
return fetThresholdChanged;
}
void protectionsValueChangesTracked::changeFETThreshold(const int &s)
{
// qDebug() << Q_FUNC_INFO << " new value:" << s;
fetThreshold = s;
fetThresholdChanged = true;
}
bool protectionsValueChangesTracked::getFETDeltaCurrentChanged( void )
{
// qDebug() << Q_FUNC_INFO << " returning " << QString::number(fetDeltaCurrentChanged);
return fetDeltaCurrentChanged;
}
void protectionsValueChangesTracked::changeFETDeltaCurrent(const int &s)
{
// qDebug() << Q_FUNC_INFO << " new value:" << s;
fetDeltaCurrent = s;
fetDeltaCurrentChanged = true;
}
bool protectionsValueChangesTracked::getProtection1Changed( void )
{
qDebug() << Q_FUNC_INFO << " returning " << QString::number(protection1Changed);
return protection1Changed;
}
void protectionsValueChangesTracked::changeProtection1( const unsigned int & s)
{
qDebug() << Q_FUNC_INFO << " new value:" << s;
protection1 = s;
protection1Changed = true;
}
bool protectionsValueChangesTracked::getProtection2Changed( void )
{
// qDebug() << Q_FUNC_INFO << " returning " << QString::number(protection2Changed);
return protection2Changed;
}
void protectionsValueChangesTracked::changeProtection2( const unsigned int & s)
{
// qDebug() << Q_FUNC_INFO << " new value:" << s;
protection2 = s;
protection2Changed = true;
}
bool protectionsValueChangesTracked::getProtection3Changed( void )
{
// qDebug() << Q_FUNC_INFO << " returning " << QString::number(protection3Changed);
return protection3Changed;
}
void protectionsValueChangesTracked::changeProtection3( const unsigned int & s)
{
// qDebug() << Q_FUNC_INFO << " new value:" << s;
protection3 = s;
protection3Changed = true;
}
bool protectionsValueChangesTracked::getProtection4Changed( void )
{
// qDebug() << Q_FUNC_INFO << " returning " << QString::number(protection4Changed);
return protection4Changed;
}
void protectionsValueChangesTracked::changeProtection4( const unsigned int & s)
{
// qDebug() << Q_FUNC_INFO << " new value:" << s;
protection4 = s;
protection4Changed = true;
}
bool protectionsValueChangesTracked::getAMFTimer1Changed( void )
{
// qDebug() << Q_FUNC_INFO << " returning " << QString::number(amfTimer1Changed);
return amfTimer1Changed;
}
void protectionsValueChangesTracked::changeAMFTimer1( const unsigned int & s)
{
// qDebug() << Q_FUNC_INFO << " new value:" << s;
amfTimer1 = s;
amfTimer1Changed = true;
}
bool protectionsValueChangesTracked::getAMFTimer2Changed( void )
{
// qDebug() << Q_FUNC_INFO << " returning " << QString::number(amfTimer2Changed);
return amfTimer2Changed;
}
void protectionsValueChangesTracked::changeAMFTimer2( const unsigned int & s)
{
//qDebug() << Q_FUNC_INFO << " new value:" << s;
amfTimer2 = s;
amfTimer2Changed = true;
}
bool protectionsValueChangesTracked::getAMFV_OVChanged( void )
{
//qDebug() << Q_FUNC_INFO << " returning " << QString::number(amfV_OVChanged);
return amfV_OVChanged;
}
void protectionsValueChangesTracked::changeAMFV_OV( const unsigned int & s)
{
//qDebug() << Q_FUNC_INFO << " new value:" << s;
amfV_OV = s;
amfV_OVChanged = true;
}
bool protectionsValueChangesTracked::getAMFI_OCChanged( void )
{
//qDebug() << Q_FUNC_INFO << " returning " << QString::number(amfI_OCChanged);
return amfI_OCChanged;
}
void protectionsValueChangesTracked::changeAMFI_OC( const unsigned int & s)
{
// qDebug() << Q_FUNC_INFO << " new value:" << s;
amfI_OC = s;
amfI_OCChanged = true;
}
bool protectionsValueChangesTracked::getAMFMPPOffCyclesChanged( void )
{
// qDebug() << Q_FUNC_INFO << " returning " << QString::number(amfMPPOffCycles);
return amfMPPOffCyclesChanged;
}
void protectionsValueChangesTracked::changeAMFMPPOffCycles(const unsigned int &s)
{
//qDebug() << Q_FUNC_INFO << " new value:" << s;
amfMPPOffCycles = s;
amfMPPOffCyclesChanged = true;
}
bool protectionsValueChangesTracked::getAMFMPPTimesOffChanged( void )
{
//qDebug() << Q_FUNC_INFO << " returning " << QString::number(amfMPPTimesOff);
return amfMPPTimesOffChanged;
}
void protectionsValueChangesTracked::changeAMFMPPTimesOff(const unsigned int &s)
{
//qDebug() << Q_FUNC_INFO << " new value:" << s;
amfMPPTimesOff = s;
amfMPPTimesOffChanged = true;
}
bool protectionsValueChangesTracked::getAMFDebugChanged( void )
{
//qDebug() << Q_FUNC_INFO << " returning " << QString::number(amfDebug);
return amfDebugChanged;
}
void protectionsValueChangesTracked::changeAMFDebug(const unsigned int &s)
{
//qDebug() << Q_FUNC_INFO << " new value:" << s;
amfDebug = s;
amfDebugChanged = true;
}
void protectionsValueChangesTracked::sendAllChangedValuesToMemory( const QString intendedFor, const QString theFamily )
{
qDebug() << Q_FUNC_INFO << " send changed values to optimizer " << intendedFor << " ...";
QString aCommand;
// Need MAC address or *
QString commandPrefix("s m");
if (intendedFor == "*")
{
commandPrefix = "s ";
}
if (efInputCurrentThresholdChanged == true)
{
qDebug() << Q_FUNC_INFO << " send change of efInputCurrentThreshold:" << efInputCurrentThreshold << " to gateway.";
aCommand = commandPrefix + intendedFor + ShortIntegerRegister_SetEFInputCurrentThreshold + ShortIntegerRegisterCommand + QString::number(efInputCurrentThreshold);
qDebug() << Q_FUNC_INFO << " emit command:" << aCommand;
emit publishCommand(aCommand);
}
if (efOccurrenceThresholdChanged == true)
{
qDebug() << Q_FUNC_INFO << " send change of efOccurrenceThreshold:" << efOccurrenceThreshold << " to gateway.";
aCommand = commandPrefix + intendedFor + ByteRegister_SetEFOccurrentThreshold + ByteRegisterCommand + QString::number(efOccurrenceThreshold);
qDebug() << Q_FUNC_INFO << " emit command:" << aCommand;
emit publishCommand(aCommand);
}
if (efCountDownTimerChanged == true)
{
qDebug() << Q_FUNC_INFO << " send change of efCountDownTimer:" << efCountDownTimer << " to gateway.";
aCommand = commandPrefix + intendedFor + ByteRegister_SetEFCountDownTimer + ByteRegisterCommand + QString::number(efCountDownTimer);
qDebug() << Q_FUNC_INFO << " emit command:" << aCommand;
emit publishCommand(aCommand);
}
if (efAlphaNumeratorChanged == true)
{
qDebug() << Q_FUNC_INFO << " send change of efAlphaNumerator:" << efAlphaNumerator << " to gateway.";
aCommand = commandPrefix + intendedFor + ByteRegister_SetEFAlphaNumerator + ByteRegisterCommand + QString::number(efAlphaNumerator);
qDebug() << Q_FUNC_INFO << " emit command:" << aCommand;
emit publishCommand(aCommand);
}
if (fetCountChanged == true)
{
// qDebug() << Q_FUNC_INFO << " send change of fetCount:" << fetCount << " to gateway.";
aCommand = commandPrefix + intendedFor + ShortIntegerRegister_FETFailureCount + ShortIntegerRegisterCommand + QString::number(fetCount);
// qDebug() << Q_FUNC_INFO << " emit command:" << aCommand;
emit publishCommand(aCommand);
}
if (fetThresholdChanged == true)
{
//qDebug() << Q_FUNC_INFO << " send change of fetThreshold:" << fetThreshold << " to gateway.";
aCommand = commandPrefix + intendedFor + ShortIntegerRegister_FETCurrentThreshold + ShortIntegerRegisterCommand + QString::number(fetThreshold);
//qDebug() << Q_FUNC_INFO << " emit command:" << aCommand;
emit publishCommand(aCommand);
}
if (fetDeltaCurrentChanged == true)
{
//qDebug() << Q_FUNC_INFO << " send change of fetThreshold:" << fetDeltaCurrent << " to gateway.";
aCommand = commandPrefix + intendedFor + ShortIntegerRegister_FETDeltaI + ShortIntegerRegisterCommand + QString::number(fetDeltaCurrent);
//qDebug() << Q_FUNC_INFO << " emit command:" << aCommand;
emit publishCommand(aCommand);
}
if (protection1Changed == true)
{
if ((theFamily == Family1300V) || (theFamily == Family1300V_2nd))
{
//qDebug() << Q_FUNC_INFO << " send change of VhvVoutLimit:" << protection1 << " to gateway.";
aCommand = commandPrefix + intendedFor + ShortIntegerRegister_VhvLimitVout + ShortIntegerRegisterCommand + QString::number(protection1);
//qDebug() << Q_FUNC_INFO << " emit command:" << aCommand;
emit publishCommand(aCommand);
}
else if ((theFamily == Family1500V) || (theFamily == Family1500V_30) || (theFamily == Family1500V_2nd))
{
qDebug() << Q_FUNC_INFO << " send change of VoutLimitCount:" << protection1 << " to gateway.";
aCommand = commandPrefix + intendedFor + ShortIntegerRegister_SetVoutLimitCount + ShortIntegerRegisterCommand + QString::number(protection1);
qDebug() << Q_FUNC_INFO << " emit command:" << aCommand;
emit publishCommand(aCommand);
}
}
if (protection2Changed == true)
{
if ((theFamily == Family1300V) || (theFamily == Family1300V_2nd))
{
//qDebug() << Q_FUNC_INFO << " send change of IhvVoutLimit:" << protection2 << " to gateway.";
aCommand = commandPrefix + intendedFor + ShortIntegerRegister_IhvLimitVout + ShortIntegerRegisterCommand + QString::number(protection2);
//qDebug() << Q_FUNC_INFO << " emit command:" << aCommand;
emit publishCommand(aCommand);
}
else if ((theFamily == Family1500V) || (theFamily == Family1500V_30) || (theFamily == Family1500V_2nd))
{
qDebug() << Q_FUNC_INFO << " send change of VoutLimit:" << protection2 << " to gateway.";
aCommand = commandPrefix + intendedFor + ShortIntegerRegister_SetVoutLimit + ShortIntegerRegisterCommand + QString::number(protection2);
qDebug() << Q_FUNC_INFO << " emit command:" << aCommand;
emit publishCommand(aCommand);
}
}
if (protection3Changed == true)
{
if ((theFamily == Family1300V) || (theFamily == Family1300V_2nd))
{
//qDebug() << Q_FUNC_INFO << " send change of VhvVinsLimit:" << protection3 << " to gateway.";
aCommand = commandPrefix + intendedFor + ShortIntegerRegister_VhvLimitVins + ShortIntegerRegisterCommand + QString::number(protection3);
//qDebug() << Q_FUNC_INFO << " emit command:" << aCommand;
emit publishCommand(aCommand);
}
else if ((theFamily == Family1500V) || (theFamily == Family1500V_30) || (theFamily == Family1500V_2nd))
{
qDebug() << Q_FUNC_INFO << " send change of IoutLimitCount:" << protection3 << " to gateway.";
aCommand = commandPrefix + intendedFor + ShortIntegerRegister_SetIoutLimitCount + ShortIntegerRegisterCommand + QString::number(protection3);
qDebug() << Q_FUNC_INFO << " emit command:" << aCommand;
emit publishCommand(aCommand);
}
}
if (protection4Changed == true)
{
if ((theFamily == Family1300V) || (theFamily == Family1300V_2nd))
{
//qDebug() << Q_FUNC_INFO << " send change of IhvVinsLimit:" << protection4 << " to gateway.";
aCommand = commandPrefix + intendedFor + ShortIntegerRegister_IhvLimitVins + ShortIntegerRegisterCommand + QString::number(protection4);
//qDebug() << Q_FUNC_INFO << " emit command:" << aCommand;
emit publishCommand(aCommand);
}
else if ((theFamily == Family1500V) || (theFamily == Family1500V_30) || (theFamily == Family1500V_2nd))
{
qDebug() << Q_FUNC_INFO << " send change of IoutLimit:" << protection4 << " to gateway.";
aCommand = commandPrefix + intendedFor + ShortIntegerRegister_SetIoutLimit + ShortIntegerRegisterCommand + QString::number(protection4);
qDebug() << Q_FUNC_INFO << " emit command:" << aCommand;
emit publishCommand(aCommand);
}
}
if (amfTimer1Changed == true)
{
//qDebug() << Q_FUNC_INFO << " send change of amfTimer1:" << amfTimer1 << " to gateway.";
aCommand = commandPrefix + intendedFor + ByteRegister_AMFTimer1 + ByteRegisterCommand + QString::number(amfTimer1);
//qDebug() << Q_FUNC_INFO << " emit command:" << aCommand;
emit publishCommand(aCommand);
}
if (amfTimer2Changed == true)
{
//qDebug() << Q_FUNC_INFO << " send change of amfTimer2:" << amfTimer2 << " to gateway.";
aCommand = commandPrefix + intendedFor + ByteRegister_AMFTimer2 + ByteRegisterCommand + QString::number(amfTimer2);
//qDebug() << Q_FUNC_INFO << " emit command:" << aCommand;
emit publishCommand(aCommand);
}
if (amfV_OVChanged == true)
{
//qDebug() << Q_FUNC_INFO << " send change of amfV_OV:" << amfV_OV << " to gateway.";
aCommand = commandPrefix + intendedFor + ShortIntegerRegister_AMFV_OV + ShortIntegerRegisterCommand + QString::number(amfV_OV);
//qDebug() << Q_FUNC_INFO << " emit command:" << aCommand;
emit publishCommand(aCommand);
}
if (amfI_OCChanged == true)
{
//qDebug() << Q_FUNC_INFO << " send change of amfI_OC:" << amfI_OC << " to gateway.";
aCommand = commandPrefix + intendedFor + ShortIntegerRegister_AMFI_OC + ShortIntegerRegisterCommand + QString::number(amfI_OC);
//qDebug() << Q_FUNC_INFO << " emit command:" << aCommand;
emit publishCommand(aCommand);
}
if ((amfMPPOffCyclesChanged == true) || (amfMPPTimesOffChanged == true))
{
// qDebug() << Q_FUNC_INFO << " send change of amfMPPOffCycles:" << amfMPPOffCycles << " and/or change of amfMPPTimesOff:" << amfMPPTimesOff << " to gateway.";
// qDebug() << Q_FUNC_INFO << " (0xF0 & (amfMPPOffCycles < 4)) => " << (0x00F0 & (amfMPPOffCycles << 4)) << " from " << (amfMPPOffCycles << 4);
unsigned char value = ((0x00F0 & (amfMPPOffCycles << 4)) | (0x000F & amfMPPTimesOff));
aCommand = commandPrefix + intendedFor + ByteRegister_AMF_Timer2MPPOffCyclesAndTimesToCycle + ByteRegisterCommandInHex + QString::number(value,16);
//qDebug() << Q_FUNC_INFO << " emit command:" << aCommand;
emit publishCommand(aCommand);
}
if (amfDebugChanged == true)
{
// qDebug() << Q_FUNC_INFO << " send change of amfDebug:" << amfDebug << " to gateway.";
aCommand = commandPrefix + intendedFor + ByteRegister_AMF_Debug + ByteRegisterCommand + QString::number(amfDebug);
//qDebug() << Q_FUNC_INFO << " emit command:" << aCommand;
emit publishCommand(aCommand);
}
if (iinLimitChanged == true)
{
qDebug() << Q_FUNC_INFO << " send change of iinLimit:" << iinLimit << " to gateway.";
aCommand = commandPrefix + intendedFor + ShortIntegerRegister_IinLimit + ShortIntegerRegisterCommand + QString::number(iinLimit);
qDebug() << Q_FUNC_INFO << " emit command:" << aCommand;
emit publishCommand(aCommand);
}
if (iinLimitOCStepsChanged == true)
{
qDebug() << Q_FUNC_INFO << " send change of iinLimitOCSteps:" << iinLimitOCSteps << " to gateway.";
aCommand = commandPrefix + intendedFor + ByteRegister_SetIinLimitOCSteps + ByteRegisterCommand + QString::number(iinLimitOCSteps);
qDebug() << Q_FUNC_INFO << " emit command:" << aCommand;
emit publishCommand(aCommand);
}
if (iinLimitOCDelayChanged == true)
{
qDebug() << Q_FUNC_INFO << " send change of iinLimitOCDelay:" << iinLimitOCDelay << " to gateway.";
aCommand = commandPrefix + intendedFor + ByteRegister_SetIinLimitOCDelay + ByteRegisterCommand + QString::number(iinLimitOCDelay);
qDebug() << Q_FUNC_INFO << " emit command:" << aCommand;
emit publishCommand(aCommand);
}
if (iinLimitTempAmbientAdjustChanged == true)
{
qDebug() << Q_FUNC_INFO << " send change of iinLimitTempAmbientAdjust:" << iinLimitTempAmbientAdjust << " to gateway.";
aCommand = commandPrefix + intendedFor + ByteRegister_SetIinLimitTempAmbientAdjust + ByteRegisterCommand + QString::number(iinLimitTempAmbientAdjust);
qDebug() << Q_FUNC_INFO << " emit command:" << aCommand;
emit publishCommand(aCommand);
}
}
|
[
"lcoburn@ampt.com"
] |
lcoburn@ampt.com
|
7138122f020c522047ea09bee87629eccc35d3a6
|
18904ac4e30a87b7c9d5ae569502b60589ed47b0
|
/source/audio/audioBuffers.hpp
|
ac64c7e30e81d7087285bab4055174eb91867d07
|
[
"MIT",
"Zlib",
"Apache-2.0",
"BSD-2-Clause",
"CC0-1.0"
] |
permissive
|
JoaoBaptMG/gba-modern
|
a51bce4464e3347cbea216808bafb440347f8e0d
|
dfb5757d25cbfa7ee795fa8be521f010661b2293
|
refs/heads/master
| 2023-07-19T18:32:12.849729
| 2023-06-26T14:17:27
| 2023-06-26T14:41:45
| 201,576,240
| 83
| 5
|
MIT
| 2020-12-01T11:07:13
| 2019-08-10T03:52:52
|
C++
|
UTF-8
|
C++
| false
| false
| 667
|
hpp
|
//--------------------------------------------------------------------------------
// audioBuffers.hpp
//--------------------------------------------------------------------------------
// Declare the audio mixer's private data
//--------------------------------------------------------------------------------
#pragma once
#include "data/audio-settings.hpp"
#include <tonc.h>
// Declare the mix buffers
extern s8 audioMixBuffersLeft[2][audio::BufferSize];
extern s8 audioMixBuffersRight[2][audio::BufferSize];
extern s8* curAudioMixBufferLeft;
extern s8* curAudioMixBufferRight;
extern u32 curFrame;
// The audio vblank is internal
void audioVblank() IWRAM_CODE;
|
[
"jbaptistapsilva@yahoo.com.br"
] |
jbaptistapsilva@yahoo.com.br
|
18297347bb8a782bbdecbcac62f1e1085158c8d5
|
dc303cfe42dbb6a0e867877837e2eacc1a899e92
|
/QMediaCore/EffectEditor/sources/SoftwareSource.cpp
|
3392b10ee2f0c847043f38bf246cab2230ffde53
|
[] |
no_license
|
Romantic-LiXuefeng/QMedia
|
4c28a093fdea7dcfe692ad9bc67260ccf02ed950
|
9c12b351feeedaaa89ecf70cb347e4c10d9350fc
|
refs/heads/master
| 2023-08-26T21:06:13.147571
| 2021-10-20T03:21:07
| 2021-10-20T03:23:21
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 12,299
|
cpp
|
//
// SoftwareSource.cpp
// QMediaCore
//
// Created by spring on 20/05/2019.
// Copyright © 2017 QMedia. All rights reserved.
//
#include "Utils/Logger.h"
#include "SoftwareSource.h"
#include "MediaCore/demuxer/GeneralDemuxer.h"
#include "SoftwareFrameDrawer.h"
#include "MediaCore/core/SteadyClock.h"
#include "Utils/Logger.h"
void SoftwareSource::run() {
if (_demuxerIndex < 0 && _demuxerIndex < _demuxerList.size()) {
LOGE("SoftwareSource::run _selectIndex < 0 or _selectIndex overflow");
return;
}
while (_isStarted) {
bool bPacketOverCache = true;
for(auto& stream : _mediaStreams) {
bPacketOverCache &= (stream->getEncodedPacketQueue().size() >= _packetCacheConut);
}
if (bPacketOverCache) {
std::this_thread::sleep_for(std::chrono::milliseconds(20));
continue;
}
//demuxer is read end, wait for seek or stop
std::unique_lock<std::mutex> lock(_mutex);
while (_isStarted && _demuxerIndex >= _demuxerList.size()) {
//send empty packet to finish decode
for (auto& stream : _mediaStreams) {
EncodedPacket empty_packet(nullptr,std::numeric_limits<int64_t >::max());
stream->getEncodedPacketQueue().addPacket(empty_packet);
}
LOGI("source read end and wait");
_condition.wait(lock);
}
if (!_isStarted)
break;
EncodedPacket packet(nullptr,0);
Demuxer* demuxer = _demuxerList[_demuxerIndex].get();
int readRet = demuxer->ReadPacket(packet);
if (readRet >= 0) {
int media_stream_idx = _stream_map[packet.getEncodedBuffer()->stream_id()];
if (media_stream_idx >= 0) {
MediaStream *stream = _mediaStreams[media_stream_idx].get();
if (stream) {
packet.set_ntp_time_ms(packet.ntp_time_ms() + _duration_offset);
stream->getEncodedPacketQueue().addPacket(packet);
}
}
} else if(demuxer->IsEOF()) {
//TODO: Demuxer read end
_demuxerIndex ++;
_duration_offset += demuxer->getDuration();
if (_demuxerIndex < _demuxerList.size())
_demuxerList[_demuxerIndex]->Seek(0, _videoStreamIndex != -1 ? 0 : 1);
}
}
}
SoftwareSource::SoftwareSource(std::vector<std::string>& fileList, bool enableVideo, bool enableAudio):
_fileList(fileList), _isLoaded(false),
_enableVideo(enableVideo), _enableAudio(enableAudio),
_videoStreamIndex(-1), _audioStreamIndex(-1),
_demuxerIndex(-1){
std::memset(_stream_map, -1, sizeof(_stream_map));
_packetCacheConut = 25;
}
SoftwareSource::~SoftwareSource() {
}
bool SoftwareSource::load() {
if (_isLoaded)
return true;
for(auto& file : _fileList) {
DemuxerRef demuxer = DemuxerRef(new GeneralDemuxer());
if( demuxer->Open(file.c_str(), 0) >= 0) {
if (!_isLoaded) {
for (int i = 0; i < demuxer->getMediaStreamDescribes().size() && i < MAX_STREAMS; ++i) {
auto stream_describes = demuxer->getMediaStreamDescribes()[i];
if (stream_describes.describe.mediatype_ == MediaType::Video && _videoStreamIndex == -1 && _enableVideo) {
_stream_map[i] = static_cast<int>(_mediaStreams.size());
_mediaStreams.push_back(MediaStreamRef(new MediaStream(stream_describes)));
_mediaDescs.push_back(stream_describes.describe);
_videoStreamIndex = i;
} else if (stream_describes.describe.mediatype_ == MediaType::Audio && _audioStreamIndex == -1 && _enableAudio) {
_stream_map[i] = static_cast<int>(_mediaStreams.size());
_mediaStreams.push_back(MediaStreamRef(new MediaStream(stream_describes)));
_mediaDescs.push_back(stream_describes.describe);
_audioStreamIndex = i;
}
}
}
_demuxerList.push_back(demuxer);
_media_duration += demuxer->getDuration();
_isLoaded = true;
}
}
return _isLoaded;
}
void SoftwareSource::unload() {
_media_duration = 0;
std::memset(_stream_map, -1, sizeof(_stream_map));
_mediaStreams.clear();
_mediaDescs.clear();
_videoStreamIndex = -1;
_audioStreamIndex = -1;
_isLoaded = false;
}
bool SoftwareSource::isInit() {
return _isLoaded;
}
bool SoftwareSource::start(int64_t startMSec, int64_t endMSec) {
if (_isLoaded) {
if (_isStarted)
return true;
MediaSource::start(startMSec, endMSec);
_demuxerIndex = getDemuxerIndex(startMSec, _duration_offset);
_demuxerList[_demuxerIndex]->Seek(startMSec - _duration_offset, _videoStreamIndex != -1 ? 0 : 1);
for (auto& stream : _mediaStreams) {
stream->setMaxOutputFrameNum(2);
stream->start();
}
_isStarted = true;
_processThread = std::thread(&SoftwareSource::run, this);
}
return _isStarted;
}
void SoftwareSource::stop() {
if (_isStarted) {
{
std::unique_lock<std::mutex> lock(_mutex);
_isStarted = false;
_condition.notify_one();
}
if (_processThread.joinable())
_processThread.join();
for (auto& stream : _mediaStreams) {
stream->stop();
}
for (auto& demuxer : _demuxerList) {
demuxer->Close();
}
}
}
bool SoftwareSource::seekTo(int64_t mSec) {
if (! _isStarted)
return false;
if (mSec > _media_time_range._end) {
return false;
}
int64_t duration_offset;
int demuxerIndex = getDemuxerIndex(mSec, duration_offset);
if (demuxerIndex < 0)
return false;
_media_time_range._start = mSec;
_duration_offset = duration_offset;
_demuxerIndex = demuxerIndex;
return decodeTo(mSec);
}
bool SoftwareSource::decodeTo(int64_t mSec, bool precise) {
//check if deocde finish
auto check_frame_output = [this]()->bool{
bool bRet = false;
if (_videoStreamIndex >= 0) { //wait for first video decodeframe
bRet = _mediaStreams[_stream_map[_videoStreamIndex]]->getDecodedFrameQueue().length() > 0;
} else { //wait for first decodeframe
for (auto& stream : _mediaStreams) {
bRet |= stream->getDecodedFrameQueue().length() > 0;
}
}
return bRet;
};
std::unique_lock<std::mutex> lock(_mutex);
_condition.notify_one();
//clear all stream cache
for (auto& stream : _mediaStreams){
stream->getDecodedFrameQueue().setAbort(false);
stream->flush();
}
bool bRet = false;
auto& demuxer_seek = _demuxerList[_demuxerIndex];
demuxer_seek->Seek(mSec - _duration_offset, _videoStreamIndex != -1 ? 0 : 1);
demuxer_seek->setIgnoreBFrame(true);
for (auto& stream : _mediaStreams) {
stream->waitForFlush();
stream->setStartTimeLimit(precise? mSec : -1);
}
int flush_packet_count = 1;
//decode and wait for frame output
while (flush_packet_count > 0) {
if (_demuxerIndex >= _demuxerList.size()) { //file lists end
flush_packet_count --;
//wait for decode finished
if (_videoStreamIndex >= 0)
_mediaStreams[_stream_map[_videoStreamIndex]]->getDecodedFrameQueue().peekFrame();
else if (_audioStreamIndex >= 0)
_mediaStreams[_stream_map[_audioStreamIndex]]->getDecodedFrameQueue().peekFrame();
break;
}
//check break condition
bRet = check_frame_output();
if (bRet) break;
//check Packet OverCache condition
bool bPacketOverCache = true;
for(auto& stream : _mediaStreams) {
bPacketOverCache &= (stream->getEncodedPacketQueue().size() >= _packetCacheConut);
}
if (bPacketOverCache) {
std::this_thread::sleep_for(std::chrono::milliseconds(5));
continue;
}
//read new packet
EncodedPacket packet(nullptr,0);
auto& demuxer = _demuxerList[_demuxerIndex];
if (demuxer->ReadPacket(packet) >= 0) {
int media_stream_idx = _stream_map[packet.getEncodedBuffer()->stream_id()];
if (media_stream_idx >= 0) {
MediaStream *stream = _mediaStreams[media_stream_idx].get();
if (stream) {
//packet pts add duration_offset
int64_t new_pts = packet.ntp_time_ms() + _duration_offset;
packet.set_ntp_time_ms(new_pts);
stream->getEncodedPacketQueue().addPacket(packet);
//check if ignore b frame
if (new_pts >= mSec - 10) demuxer_seek->setIgnoreBFrame(false);
}
}
} else if(demuxer->IsEOF()) {
//TODO: Demuxer read end
_demuxerIndex ++;
_duration_offset += demuxer->getDuration();
if (_demuxerIndex < _demuxerList.size())
_demuxerList[_demuxerIndex]->Seek(0, _videoStreamIndex != -1 ? 0 : 1);
else {
//send empty packet to finish decode
for (auto& stream : _mediaStreams) {
EncodedPacket empty_packet(nullptr,std::numeric_limits<int64_t >::max());
stream->getEncodedPacketQueue().addPacket(empty_packet);
}
}
}
}
demuxer_seek->setIgnoreBFrame(false);
return bRet;
}
bool SoftwareSource::isEOF() {
return _demuxerIndex >= _demuxerList.size();
}
int SoftwareSource::getDemuxerIndex(int64_t time_ms, int64_t& time_offset) {
int index = -1;
int64_t duration = 0;
for (int i = 0; i < _demuxerList.size(); ++i) {
if (duration + _demuxerList[i]->getDuration() >= time_ms) {
time_offset = duration;
index = i;
break;
}
duration += _demuxerList[i]->getDuration();
}
return index;
}
VideoFrame SoftwareSource::readNextVideoFrame(int& error) {
error = -1;
VideoFrame videoFrame(nullptr, 0);
MediaStream* stream = _mediaStreams[_stream_map[_videoStreamIndex]].get();
if (stream->getDecodedFrameQueue().length() <=0 && stream->isEnd()) {
error = 1;
return videoFrame;
}
DecodedFrame decodedFrame = stream->getDecodedFrameQueue().popFrame();
if (decodedFrame.frame_buffer_) {
videoFrame = VideoFrame(std::dynamic_pointer_cast<VideoFrameBuffer>(decodedFrame.frame_buffer_),decodedFrame.render_time_ms());
error = 0;
}
return videoFrame;
}
AudioFrame SoftwareSource::readNextAudioFrame(int& error) {
error = -1;
AudioFrame audioFrame(nullptr, 0, 0);
MediaStream* stream = _mediaStreams[_stream_map[_audioStreamIndex]].get();
if (stream->getDecodedFrameQueue().length() <=0 && stream->isEnd()) {
error = 1;
return audioFrame;
}
DecodedFrame decodedFrame = stream->getDecodedFrameQueue().popFrame();
if (decodedFrame.frame_buffer_) {
audioFrame = AudioFrame(std::dynamic_pointer_cast<AudioFrameBuffer>(decodedFrame.frame_buffer_),decodedFrame.timestamp_ ,decodedFrame.render_time_ms());
error = 0;
}
return audioFrame;
}
VideoFrameDrawer* SoftwareSource::createVideoFrameDrawer() {
VideoFrameDrawer* videoFrameDrawer = nullptr;
RawVideoFormat videoFormat = RawVideoFormat::kUnknown;
if (_videoStreamIndex >= 0)
videoFormat = _mediaStreams[_stream_map[_videoStreamIndex]]->getMediaDescribe().describe._videodesc.format;
switch (videoFormat) {
case RawVideoFormat::kI420:
case RawVideoFormat::kYV12:
videoFrameDrawer = new YUVFrameDrawer(_videoTarget);
break;
case RawVideoFormat::kARGB:
case RawVideoFormat::kBGRA:
videoFrameDrawer = new RGBAFrameDrawer(_videoTarget);
break;
default:
break;
}
return videoFrameDrawer;
}
|
[
"spring_zhsp@163.com"
] |
spring_zhsp@163.com
|
4d0cc846279d41ef7e7e7a5133f58f2be823792a
|
42b478ff4d1a2a440ee5a4834a19aa4d04ad3f0d
|
/WindowsTextSearch/test/cpps/Entry.cpp
|
0e87f7c665836b07db730f7392ca98ed48797150
|
[] |
no_license
|
ammarsalman94/Projects
|
f86eff7e250f98086fab6835f34e4eb45558c4d9
|
aa7ed49c7ae23c288288bcf4ec119c0b57489be1
|
refs/heads/master
| 2020-12-27T07:53:48.213766
| 2020-02-02T19:45:44
| 2020-02-02T19:45:44
| 237,822,598
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,004
|
cpp
|
/////////////////////////////////////////////////////////////////////
// Entry.cpp - Test stub for NoSqlDb package //
// Ver 1.0 //
// Application: Project #1 - No-SQL Database - CSE-687 //
// Platform: Dell Inspiron 5520, Win 10, Visual Studio 2015 //
// Author: Ammar Salman, EECS, Syracuse University //
// (313) 788-4694 hoplite.90@hotmail.com //
/////////////////////////////////////////////////////////////////////
#include <iostream>
#include <string>
#include <vector>
#include "..\RegularExpression\RegularExpression.h"
#include "Element.h"
#include "NoSqlDb.h"
using namespace std;
// test stub for Element<T> and NoSQLDB<KeyType, Type>
#ifdef TEST_NOSQLDB
Element<string> TestElement() {
Element<string> e1;
e1.SetKey("key1");
e1.SetName("element1");
e1.SetCategory("C++");
e1.SetDescription("example element");
e1.SetData("i love c++");
e1.AddChild("key2");
e1.AddChild("key3");
cout << "\n Testing Element<string> ";
cout << "\n ========================= ";
cout << "\n Printing element:";
cout << "\n" << e1.ToString();
cout << "\n\n Printing element to XML:";
cout << "\n" << e1.ToXMLString();
return e1;
}
int main() {
// testing element
Element<string> e1 = TestElement();
Element<string> e2;
e2.SetKey("key2");
e2.SetName("element2");
e2.SetCategory("C#");
e2.SetDescription("example element two");
e2.SetData("i love c#");
e2.AddChild("key3");
e2.AddChild("key4");
cout << "\n\n\n Testing NoSQLDB<string> ";
cout << "\n ================================= ";
cout << "\n\n Creating database";
NoSQLDB<string> db;
cout << "\n\n Adding elements to database:";
if (db.AddEntry(e1.GetKey(), e1) && db.AddEntry(e2.GetKey(), e2))
cout << "\n Entries added:\n" << e1.ToString()
<< "\n" << e2.ToString();
cout << "\n\n Importing Database from 'database.xml'";
db.ImportXML("database.xml");
cout << "\n" << db.ToString();
cout << "\n\n Executing query: { get data='dummy' and (name='ammar' or category='python') }";
vector<string> output = db.ExecuteQuery("get data='dummy' and (name='ammar' or category='python')");
cout << "\n obtained keys and their information:";
int size = output.size();
for (int i = 0; i < size; i++)
cout << "\n Key: " << output[i] << "; Data: " << db.GetElement(output[i]).GetData()
<< "; Name: " << db.GetElement(output[i]).GetName() << "; Category: " << db.GetElement(output[i]).GetCategory();
cout << "\n\n Adding element using regular expression: ";
cout << "\n { add key='key10' name='ammar' category='mongodb' description='testquery'";
cout << "\n data = 'something' children = 'key1,key2,key3' }";
db.ExecuteQuery("add key='key10' name='ammar' category='mongodb' description='testquery' data='something' children='key1,key2,key3'");
cout << "\n Printing out the new element:\n" << db.GetElement("key10").ToString() << "\n";
db.StoreXML("database2.xml");
return 0;
}
#endif
|
[
"hoplite.90@hotmail.com"
] |
hoplite.90@hotmail.com
|
204345df446013c891d2cb0e9d0c583c2ea4aa4b
|
331140b484a3d91ed11b6aa70160e926ef249c38
|
/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/libhdfspp/lib/bindings/c/hdfs.cc
|
9a7c8b4ddba7e7931c3158389224919579ede39a
|
[
"LicenseRef-scancode-unknown",
"GPL-2.0-only",
"Apache-2.0",
"BSD-2-Clause",
"BSD-2-Clause-Views",
"LGPL-2.1-only",
"MPL-2.0",
"MPL-2.0-no-copyleft-exception",
"AGPL-3.0-only",
"BSD-3-Clause",
"LicenseRef-scancode-jdom",
"CDDL-1.1",
"LicenseRef-scancode-proprietary-license",
"CDDL-1.0",
"LicenseRef-scancode-protobuf",
"EPL-1.0",
"CC-BY-3.0",
"MIT",
"LicenseRef-scancode-unknown-license-reference",
"CC-BY-2.5",
"Classpath-exception-2.0",
"LicenseRef-scancode-other-permissive",
"GCC-exception-3.1",
"LicenseRef-scancode-public-domain",
"CC-PDDC",
"CC0-1.0"
] |
permissive
|
bazaarvoice/hadoop
|
2d7bf98b77bfc8b0197d82cc51953d5740deb8e0
|
8ab776d61e569c12ec62024415ff68e5d3b10141
|
refs/heads/trunk
| 2023-08-02T04:11:26.273318
| 2018-04-10T18:42:54
| 2018-04-10T18:42:54
| 128,986,787
| 0
| 1
|
Apache-2.0
| 2022-07-05T09:37:27
| 2018-04-10T19:46:27
|
Java
|
UTF-8
|
C++
| false
| false
| 51,539
|
cc
|
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "hdfspp/hdfspp.h"
#include "fs/filesystem.h"
#include "common/hdfs_configuration.h"
#include "common/configuration_loader.h"
#include "common/logging.h"
#include <hdfs/hdfs.h>
#include <hdfspp/hdfs_ext.h>
#include <libgen.h>
#include "limits.h"
#include <string>
#include <cstring>
#include <iostream>
#include <algorithm>
#include <functional>
using namespace hdfs;
using std::experimental::nullopt;
using namespace std::placeholders;
static constexpr tPort kDefaultPort = 8020;
/** Annotate what parts of the code below are implementatons of API functions
* and if they are normal vs. extended API.
*/
#define LIBHDFS_C_API
#define LIBHDFSPP_EXT_API
/* Separate the handles used by the C api from the C++ API*/
struct hdfs_internal {
hdfs_internal(FileSystem *p) : filesystem_(p), working_directory_("/") {}
hdfs_internal(std::unique_ptr<FileSystem> p)
: filesystem_(std::move(p)), working_directory_("/") {}
virtual ~hdfs_internal(){};
FileSystem *get_impl() { return filesystem_.get(); }
const FileSystem *get_impl() const { return filesystem_.get(); }
std::string get_working_directory() {
std::lock_guard<std::mutex> read_guard(wd_lock_);
return working_directory_;
}
void set_working_directory(std::string new_directory) {
std::lock_guard<std::mutex> write_guard(wd_lock_);
working_directory_ = new_directory;
}
private:
std::unique_ptr<FileSystem> filesystem_;
std::string working_directory_; //has to always start and end with '/'
std::mutex wd_lock_; //synchronize access to the working directory
};
struct hdfsFile_internal {
hdfsFile_internal(FileHandle *p) : file_(p) {}
hdfsFile_internal(std::unique_ptr<FileHandle> p) : file_(std::move(p)) {}
virtual ~hdfsFile_internal(){};
FileHandle *get_impl() { return file_.get(); }
const FileHandle *get_impl() const { return file_.get(); }
private:
std::unique_ptr<FileHandle> file_;
};
/* Keep thread local copy of last error string */
thread_local std::string errstr;
/* Fetch last error that happened in this thread */
LIBHDFSPP_EXT_API
int hdfsGetLastError(char *buf, int len) {
//No error message
if(errstr.empty()){
return -1;
}
//There is an error, but no room for the error message to be copied to
if(nullptr == buf || len < 1) {
return -1;
}
/* leave space for a trailing null */
size_t copylen = std::min((size_t)errstr.size(), (size_t)len);
if(copylen == (size_t)len) {
copylen--;
}
strncpy(buf, errstr.c_str(), copylen);
/* stick in null */
buf[copylen] = 0;
return 0;
}
/* Event callbacks for next open calls */
thread_local std::experimental::optional<fs_event_callback> fsEventCallback;
thread_local std::experimental::optional<file_event_callback> fileEventCallback;
struct hdfsBuilder {
hdfsBuilder();
hdfsBuilder(const char * directory);
virtual ~hdfsBuilder() {}
ConfigurationLoader loader;
HdfsConfiguration config;
optional<std::string> overrideHost;
optional<tPort> overridePort;
optional<std::string> user;
static constexpr tPort kUseDefaultPort = 0;
};
/* Error handling with optional debug to stderr */
static void ReportError(int errnum, const std::string & msg) {
errno = errnum;
errstr = msg;
#ifdef LIBHDFSPP_C_API_ENABLE_DEBUG
std::cerr << "Error: errno=" << strerror(errnum) << " message=\"" << msg
<< "\"" << std::endl;
#else
(void)msg;
#endif
}
/* Convert Status wrapped error into appropriate errno and return code */
static int Error(const Status &stat) {
const char * default_message;
int errnum;
int code = stat.code();
switch (code) {
case Status::Code::kOk:
return 0;
case Status::Code::kInvalidArgument:
errnum = EINVAL;
default_message = "Invalid argument";
break;
case Status::Code::kResourceUnavailable:
errnum = EAGAIN;
default_message = "Resource temporarily unavailable";
break;
case Status::Code::kUnimplemented:
errnum = ENOSYS;
default_message = "Function not implemented";
break;
case Status::Code::kException:
errnum = EINTR;
default_message = "Exception raised";
break;
case Status::Code::kOperationCanceled:
errnum = EINTR;
default_message = "Operation canceled";
break;
case Status::Code::kPermissionDenied:
errnum = EACCES;
default_message = "Permission denied";
break;
case Status::Code::kPathNotFound:
errnum = ENOENT;
default_message = "No such file or directory";
break;
case Status::Code::kNotADirectory:
errnum = ENOTDIR;
default_message = "Not a directory";
break;
case Status::Code::kFileAlreadyExists:
errnum = EEXIST;
default_message = "File already exists";
break;
case Status::Code::kPathIsNotEmptyDirectory:
errnum = ENOTEMPTY;
default_message = "Directory is not empty";
break;
case Status::Code::kInvalidOffset:
errnum = Status::Code::kInvalidOffset;
default_message = "Trying to begin a read past the EOF";
break;
default:
errnum = ENOSYS;
default_message = "Error: unrecognised code";
}
if (stat.ToString().empty())
ReportError(errnum, default_message);
else
ReportError(errnum, stat.ToString());
return -1;
}
static int ReportException(const std::exception & e)
{
return Error(Status::Exception("Uncaught exception", e.what()));
}
static int ReportCaughtNonException()
{
return Error(Status::Exception("Uncaught value not derived from std::exception", ""));
}
/* return false on failure */
bool CheckSystem(hdfsFS fs) {
if (!fs) {
ReportError(ENODEV, "Cannot perform FS operations with null FS handle.");
return false;
}
return true;
}
/* return false on failure */
bool CheckHandle(hdfsFile file) {
if (!file) {
ReportError(EBADF, "Cannot perform FS operations with null File handle.");
return false;
}
return true;
}
/* return false on failure */
bool CheckSystemAndHandle(hdfsFS fs, hdfsFile file) {
if (!CheckSystem(fs))
return false;
if (!CheckHandle(file))
return false;
return true;
}
optional<std::string> getAbsolutePath(hdfsFS fs, const char* path) {
//Does not support . (dot) and .. (double dot) semantics
if (!path || path[0] == '\0') {
Error(Status::InvalidArgument("getAbsolutePath: argument 'path' cannot be NULL or empty"));
return optional<std::string>();
}
if (path[0] != '/') {
//we know that working directory always ends with '/'
return fs->get_working_directory().append(path);
}
return optional<std::string>(path);
}
/**
* C API implementations
**/
LIBHDFS_C_API
int hdfsFileIsOpenForRead(hdfsFile file) {
/* files can only be open for reads at the moment, do a quick check */
if (!CheckHandle(file)){
return 0;
}
return 1; // Update implementation when we get file writing
}
LIBHDFS_C_API
int hdfsFileIsOpenForWrite(hdfsFile file) {
/* files can only be open for reads at the moment, so return false */
CheckHandle(file);
return -1; // Update implementation when we get file writing
}
int hdfsConfGetLong(const char *key, int64_t *val)
{
try
{
errno = 0;
hdfsBuilder builder;
return hdfsBuilderConfGetLong(&builder, key, val);
} catch (const std::exception & e) {
return ReportException(e);
} catch (...) {
return ReportCaughtNonException();
}
}
hdfsFS doHdfsConnect(optional<std::string> nn, optional<tPort> port, optional<std::string> user, const Options & options) {
try
{
errno = 0;
IoService * io_service = IoService::New();
FileSystem *fs = FileSystem::New(io_service, user.value_or(""), options);
if (!fs) {
ReportError(ENODEV, "Could not create FileSystem object");
return nullptr;
}
if (fsEventCallback) {
fs->SetFsEventCallback(fsEventCallback.value());
}
Status status;
if (nn || port) {
if (!port) {
port = kDefaultPort;
}
std::string port_as_string = std::to_string(*port);
status = fs->Connect(nn.value_or(""), port_as_string);
} else {
status = fs->ConnectToDefaultFs();
}
if (!status.ok()) {
Error(status);
// FileSystem's ctor might take ownership of the io_service; if it does,
// it will null out the pointer
if (io_service)
delete io_service;
delete fs;
return nullptr;
}
return new hdfs_internal(fs);
} catch (const std::exception & e) {
ReportException(e);
return nullptr;
} catch (...) {
ReportCaughtNonException();
return nullptr;
}
}
LIBHDFSPP_EXT_API
hdfsFS hdfsAllocateFileSystem(struct hdfsBuilder *bld) {
// Same idea as the first half of doHdfsConnect, but return the wrapped FS before
// connecting.
try {
errno = 0;
std::shared_ptr<IoService> io_service = IoService::MakeShared();
int io_thread_count = bld->config.GetOptions().io_threads_;
if(io_thread_count < 1) {
io_service->InitDefaultWorkers();
} else {
io_service->InitWorkers(io_thread_count);
}
FileSystem *fs = FileSystem::New(io_service, bld->user.value_or(""), bld->config.GetOptions());
if (!fs) {
ReportError(ENODEV, "Could not create FileSystem object");
return nullptr;
}
if (fsEventCallback) {
fs->SetFsEventCallback(fsEventCallback.value());
}
return new hdfs_internal(fs);
} catch (const std::exception &e) {
ReportException(e);
return nullptr;
} catch (...) {
ReportCaughtNonException();
return nullptr;
}
return nullptr;
}
LIBHDFSPP_EXT_API
int hdfsConnectAllocated(hdfsFS fs, struct hdfsBuilder *bld) {
if(!CheckSystem(fs)) {
return ENODEV;
}
if(!bld) {
ReportError(ENODEV, "No hdfsBuilder object supplied");
return ENODEV;
}
// Get C++ FS to do connect
FileSystem *fsImpl = fs->get_impl();
if(!fsImpl) {
ReportError(ENODEV, "Null FileSystem implementation");
return ENODEV;
}
// Unpack the required bits of the hdfsBuilder
optional<std::string> nn = bld->overrideHost;
optional<tPort> port = bld->overridePort;
optional<std::string> user = bld->user;
// try-catch in case some of the third-party stuff throws
try {
Status status;
if (nn || port) {
if (!port) {
port = kDefaultPort;
}
std::string port_as_string = std::to_string(*port);
status = fsImpl->Connect(nn.value_or(""), port_as_string);
} else {
status = fsImpl->ConnectToDefaultFs();
}
if (!status.ok()) {
Error(status);
return ENODEV;
}
// 0 to indicate a good connection
return 0;
} catch (const std::exception & e) {
ReportException(e);
return ENODEV;
} catch (...) {
ReportCaughtNonException();
return ENODEV;
}
return 0;
}
LIBHDFS_C_API
hdfsFS hdfsConnect(const char *nn, tPort port) {
return hdfsConnectAsUser(nn, port, "");
}
LIBHDFS_C_API
hdfsFS hdfsConnectAsUser(const char* nn, tPort port, const char *user) {
return doHdfsConnect(std::string(nn), port, std::string(user), Options());
}
LIBHDFS_C_API
hdfsFS hdfsConnectAsUserNewInstance(const char* nn, tPort port, const char *user ) {
//libhdfspp always returns a new instance
return doHdfsConnect(std::string(nn), port, std::string(user), Options());
}
LIBHDFS_C_API
hdfsFS hdfsConnectNewInstance(const char* nn, tPort port) {
//libhdfspp always returns a new instance
return hdfsConnectAsUser(nn, port, "");
}
LIBHDFSPP_EXT_API
int hdfsCancelPendingConnection(hdfsFS fs) {
// todo: stick an enum in hdfs_internal to check the connect state
if(!CheckSystem(fs)) {
return ENODEV;
}
FileSystem *fsImpl = fs->get_impl();
if(!fsImpl) {
ReportError(ENODEV, "Null FileSystem implementation");
return ENODEV;
}
bool canceled = fsImpl->CancelPendingConnect();
if(canceled) {
return 0;
} else {
return EINTR;
}
}
LIBHDFS_C_API
int hdfsDisconnect(hdfsFS fs) {
try
{
errno = 0;
if (!fs) {
ReportError(ENODEV, "Cannot disconnect null FS handle.");
return -1;
}
delete fs;
return 0;
} catch (const std::exception & e) {
return ReportException(e);
} catch (...) {
return ReportCaughtNonException();
}
}
LIBHDFS_C_API
hdfsFile hdfsOpenFile(hdfsFS fs, const char *path, int flags, int bufferSize,
short replication, tSize blocksize) {
try
{
errno = 0;
(void)flags;
(void)bufferSize;
(void)replication;
(void)blocksize;
if (!fs) {
ReportError(ENODEV, "Cannot perform FS operations with null FS handle.");
return nullptr;
}
const optional<std::string> abs_path = getAbsolutePath(fs, path);
if(!abs_path) {
return nullptr;
}
FileHandle *f = nullptr;
Status stat = fs->get_impl()->Open(*abs_path, &f);
if (!stat.ok()) {
Error(stat);
return nullptr;
}
if (f && fileEventCallback) {
f->SetFileEventCallback(fileEventCallback.value());
}
return new hdfsFile_internal(f);
} catch (const std::exception & e) {
ReportException(e);
return nullptr;
} catch (...) {
ReportCaughtNonException();
return nullptr;
}
}
LIBHDFS_C_API
int hdfsCloseFile(hdfsFS fs, hdfsFile file) {
try
{
errno = 0;
if (!CheckSystemAndHandle(fs, file)) {
return -1;
}
delete file;
return 0;
} catch (const std::exception & e) {
return ReportException(e);
} catch (...) {
return ReportCaughtNonException();
}
}
LIBHDFS_C_API
char* hdfsGetWorkingDirectory(hdfsFS fs, char *buffer, size_t bufferSize) {
try
{
errno = 0;
if (!CheckSystem(fs)) {
return nullptr;
}
std::string wd = fs->get_working_directory();
size_t size = wd.size();
if (size + 1 > bufferSize) {
std::stringstream ss;
ss << "hdfsGetWorkingDirectory: bufferSize is " << bufferSize <<
", which is not enough to fit working directory of size " << (size + 1);
Error(Status::InvalidArgument(ss.str().c_str()));
return nullptr;
}
wd.copy(buffer, size);
buffer[size] = '\0';
return buffer;
} catch (const std::exception & e) {
ReportException(e);
return nullptr;
} catch (...) {
ReportCaughtNonException();
return nullptr;
}
}
LIBHDFS_C_API
int hdfsSetWorkingDirectory(hdfsFS fs, const char* path) {
try
{
errno = 0;
if (!CheckSystem(fs)) {
return -1;
}
optional<std::string> abs_path = getAbsolutePath(fs, path);
if(!abs_path) {
return -1;
}
//Enforce last character to be '/'
std::string withSlash = *abs_path;
char last = withSlash.back();
if (last != '/'){
withSlash += '/';
}
fs->set_working_directory(withSlash);
return 0;
} catch (const std::exception & e) {
return ReportException(e);
} catch (...) {
return ReportCaughtNonException();
}
}
LIBHDFS_C_API
int hdfsAvailable(hdfsFS fs, hdfsFile file) {
//Since we do not have read ahead implemented, return 0 if fs and file are good;
errno = 0;
if (!CheckSystemAndHandle(fs, file)) {
return -1;
}
return 0;
}
LIBHDFS_C_API
tOffset hdfsGetDefaultBlockSize(hdfsFS fs) {
try {
errno = 0;
return fs->get_impl()->get_options().block_size;
} catch (const std::exception & e) {
ReportException(e);
return -1;
} catch (...) {
ReportCaughtNonException();
return -1;
}
}
LIBHDFS_C_API
tOffset hdfsGetDefaultBlockSizeAtPath(hdfsFS fs, const char *path) {
try {
errno = 0;
if (!CheckSystem(fs)) {
return -1;
}
const optional<std::string> abs_path = getAbsolutePath(fs, path);
if(!abs_path) {
return -1;
}
uint64_t block_size;
Status stat = fs->get_impl()->GetPreferredBlockSize(*abs_path, block_size);
if (!stat.ok()) {
if (stat.pathNotFound()){
return fs->get_impl()->get_options().block_size;
} else {
return Error(stat);
}
}
return block_size;
} catch (const std::exception & e) {
ReportException(e);
return -1;
} catch (...) {
ReportCaughtNonException();
return -1;
}
}
LIBHDFS_C_API
int hdfsSetReplication(hdfsFS fs, const char* path, int16_t replication) {
try {
errno = 0;
if (!CheckSystem(fs)) {
return -1;
}
const optional<std::string> abs_path = getAbsolutePath(fs, path);
if(!abs_path) {
return -1;
}
if(replication < 1){
return Error(Status::InvalidArgument("SetReplication: argument 'replication' cannot be less than 1"));
}
Status stat;
stat = fs->get_impl()->SetReplication(*abs_path, replication);
if (!stat.ok()) {
return Error(stat);
}
return 0;
} catch (const std::exception & e) {
return ReportException(e);
} catch (...) {
return ReportCaughtNonException();
}
}
LIBHDFS_C_API
int hdfsUtime(hdfsFS fs, const char* path, tTime mtime, tTime atime) {
try {
errno = 0;
if (!CheckSystem(fs)) {
return -1;
}
const optional<std::string> abs_path = getAbsolutePath(fs, path);
if(!abs_path) {
return -1;
}
Status stat;
stat = fs->get_impl()->SetTimes(*abs_path, mtime, atime);
if (!stat.ok()) {
return Error(stat);
}
return 0;
} catch (const std::exception & e) {
return ReportException(e);
} catch (...) {
return ReportCaughtNonException();
}
}
LIBHDFS_C_API
tOffset hdfsGetCapacity(hdfsFS fs) {
try {
errno = 0;
if (!CheckSystem(fs)) {
return -1;
}
hdfs::FsInfo fs_info;
Status stat = fs->get_impl()->GetFsStats(fs_info);
if (!stat.ok()) {
Error(stat);
return -1;
}
return fs_info.capacity;
} catch (const std::exception & e) {
ReportException(e);
return -1;
} catch (...) {
ReportCaughtNonException();
return -1;
}
}
LIBHDFS_C_API
tOffset hdfsGetUsed(hdfsFS fs) {
try {
errno = 0;
if (!CheckSystem(fs)) {
return -1;
}
hdfs::FsInfo fs_info;
Status stat = fs->get_impl()->GetFsStats(fs_info);
if (!stat.ok()) {
Error(stat);
return -1;
}
return fs_info.used;
} catch (const std::exception & e) {
ReportException(e);
return -1;
} catch (...) {
ReportCaughtNonException();
return -1;
}
}
void StatInfoToHdfsFileInfo(hdfsFileInfo * file_info,
const hdfs::StatInfo & stat_info) {
/* file or directory */
if (stat_info.file_type == StatInfo::IS_DIR) {
file_info->mKind = kObjectKindDirectory;
} else if (stat_info.file_type == StatInfo::IS_FILE) {
file_info->mKind = kObjectKindFile;
} else {
file_info->mKind = kObjectKindFile;
LOG_WARN(kFileSystem, << "Symlink is not supported! Reporting as a file: ");
}
/* the name of the file */
char copyOfPath[PATH_MAX];
strncpy(copyOfPath, stat_info.path.c_str(), PATH_MAX);
copyOfPath[PATH_MAX - 1] = '\0'; // in case strncpy ran out of space
char * mName = basename(copyOfPath);
size_t mName_size = strlen(mName);
file_info->mName = new char[mName_size+1];
strncpy(file_info->mName, basename(copyOfPath), mName_size + 1);
/* the last modification time for the file in seconds */
file_info->mLastMod = (tTime) stat_info.modification_time;
/* the size of the file in bytes */
file_info->mSize = (tOffset) stat_info.length;
/* the count of replicas */
file_info->mReplication = (short) stat_info.block_replication;
/* the block size for the file */
file_info->mBlockSize = (tOffset) stat_info.blocksize;
/* the owner of the file */
file_info->mOwner = new char[stat_info.owner.size() + 1];
strncpy(file_info->mOwner, stat_info.owner.c_str(), stat_info.owner.size() + 1);
/* the group associated with the file */
file_info->mGroup = new char[stat_info.group.size() + 1];
strncpy(file_info->mGroup, stat_info.group.c_str(), stat_info.group.size() + 1);
/* the permissions associated with the file encoded as an octal number (0777)*/
file_info->mPermissions = (short) stat_info.permissions;
/* the last access time for the file in seconds since the epoch*/
file_info->mLastAccess = stat_info.access_time;
}
LIBHDFS_C_API
int hdfsExists(hdfsFS fs, const char *path) {
try {
errno = 0;
if (!CheckSystem(fs)) {
return -1;
}
const optional<std::string> abs_path = getAbsolutePath(fs, path);
if(!abs_path) {
return -1;
}
hdfs::StatInfo stat_info;
Status stat = fs->get_impl()->GetFileInfo(*abs_path, stat_info);
if (!stat.ok()) {
return Error(stat);
}
return 0;
} catch (const std::exception & e) {
return ReportException(e);
} catch (...) {
return ReportCaughtNonException();
}
}
LIBHDFS_C_API
hdfsFileInfo *hdfsGetPathInfo(hdfsFS fs, const char* path) {
try {
errno = 0;
if (!CheckSystem(fs)) {
return nullptr;
}
const optional<std::string> abs_path = getAbsolutePath(fs, path);
if(!abs_path) {
return nullptr;
}
hdfs::StatInfo stat_info;
Status stat = fs->get_impl()->GetFileInfo(*abs_path, stat_info);
if (!stat.ok()) {
Error(stat);
return nullptr;
}
hdfsFileInfo *file_info = new hdfsFileInfo[1];
StatInfoToHdfsFileInfo(file_info, stat_info);
return file_info;
} catch (const std::exception & e) {
ReportException(e);
return nullptr;
} catch (...) {
ReportCaughtNonException();
return nullptr;
}
}
LIBHDFS_C_API
hdfsFileInfo *hdfsListDirectory(hdfsFS fs, const char* path, int *numEntries) {
try {
errno = 0;
if (!CheckSystem(fs)) {
*numEntries = 0;
return nullptr;
}
const optional<std::string> abs_path = getAbsolutePath(fs, path);
if(!abs_path) {
return nullptr;
}
std::vector<StatInfo> stat_infos;
Status stat = fs->get_impl()->GetListing(*abs_path, &stat_infos);
if (!stat.ok()) {
Error(stat);
*numEntries = 0;
return nullptr;
}
if(stat_infos.empty()){
*numEntries = 0;
return nullptr;
}
*numEntries = stat_infos.size();
hdfsFileInfo *file_infos = new hdfsFileInfo[stat_infos.size()];
for(std::vector<StatInfo>::size_type i = 0; i < stat_infos.size(); i++) {
StatInfoToHdfsFileInfo(&file_infos[i], stat_infos.at(i));
}
return file_infos;
} catch (const std::exception & e) {
ReportException(e);
*numEntries = 0;
return nullptr;
} catch (...) {
ReportCaughtNonException();
*numEntries = 0;
return nullptr;
}
}
LIBHDFS_C_API
void hdfsFreeFileInfo(hdfsFileInfo *hdfsFileInfo, int numEntries)
{
errno = 0;
int i;
for (i = 0; i < numEntries; ++i) {
delete[] hdfsFileInfo[i].mName;
delete[] hdfsFileInfo[i].mOwner;
delete[] hdfsFileInfo[i].mGroup;
}
delete[] hdfsFileInfo;
}
LIBHDFS_C_API
int hdfsCreateDirectory(hdfsFS fs, const char* path) {
try {
errno = 0;
if (!CheckSystem(fs)) {
return -1;
}
const optional<std::string> abs_path = getAbsolutePath(fs, path);
if(!abs_path) {
return -1;
}
Status stat;
//Use default permissions and set true for creating all non-existant parent directories
stat = fs->get_impl()->Mkdirs(*abs_path, FileSystem::GetDefaultPermissionMask(), true);
if (!stat.ok()) {
return Error(stat);
}
return 0;
} catch (const std::exception & e) {
return ReportException(e);
} catch (...) {
return ReportCaughtNonException();
}
}
LIBHDFS_C_API
int hdfsDelete(hdfsFS fs, const char* path, int recursive) {
try {
errno = 0;
if (!CheckSystem(fs)) {
return -1;
}
const optional<std::string> abs_path = getAbsolutePath(fs, path);
if(!abs_path) {
return -1;
}
Status stat;
stat = fs->get_impl()->Delete(*abs_path, recursive);
if (!stat.ok()) {
return Error(stat);
}
return 0;
} catch (const std::exception & e) {
return ReportException(e);
} catch (...) {
return ReportCaughtNonException();
}
}
LIBHDFS_C_API
int hdfsRename(hdfsFS fs, const char* oldPath, const char* newPath) {
try {
errno = 0;
if (!CheckSystem(fs)) {
return -1;
}
const optional<std::string> old_abs_path = getAbsolutePath(fs, oldPath);
const optional<std::string> new_abs_path = getAbsolutePath(fs, newPath);
if(!old_abs_path || !new_abs_path) {
return -1;
}
Status stat;
stat = fs->get_impl()->Rename(*old_abs_path, *new_abs_path);
if (!stat.ok()) {
return Error(stat);
}
return 0;
} catch (const std::exception & e) {
return ReportException(e);
} catch (...) {
return ReportCaughtNonException();
}
}
LIBHDFS_C_API
int hdfsChmod(hdfsFS fs, const char* path, short mode){
try {
errno = 0;
if (!CheckSystem(fs)) {
return -1;
}
const optional<std::string> abs_path = getAbsolutePath(fs, path);
if(!abs_path) {
return -1;
}
Status stat = FileSystem::CheckValidPermissionMask(mode);
if (!stat.ok()) {
return Error(stat);
}
stat = fs->get_impl()->SetPermission(*abs_path, mode);
if (!stat.ok()) {
return Error(stat);
}
return 0;
} catch (const std::exception & e) {
return ReportException(e);
} catch (...) {
return ReportCaughtNonException();
}
}
LIBHDFS_C_API
int hdfsChown(hdfsFS fs, const char* path, const char *owner, const char *group){
try {
errno = 0;
if (!CheckSystem(fs)) {
return -1;
}
const optional<std::string> abs_path = getAbsolutePath(fs, path);
if(!abs_path) {
return -1;
}
std::string own = (owner) ? owner : "";
std::string grp = (group) ? group : "";
Status stat;
stat = fs->get_impl()->SetOwner(*abs_path, own, grp);
if (!stat.ok()) {
return Error(stat);
}
return 0;
} catch (const std::exception & e) {
return ReportException(e);
} catch (...) {
return ReportCaughtNonException();
}
}
LIBHDFSPP_EXT_API
hdfsFileInfo * hdfsFind(hdfsFS fs, const char* path, const char* name, uint32_t * numEntries){
try {
errno = 0;
if (!CheckSystem(fs)) {
*numEntries = 0;
return nullptr;
}
std::vector<StatInfo> stat_infos;
Status stat = fs->get_impl()->Find(path, name, hdfs::FileSystem::GetDefaultFindMaxDepth(), &stat_infos);
if (!stat.ok()) {
Error(stat);
*numEntries = 0;
return nullptr;
}
//Existing API expects nullptr if size is 0
if(stat_infos.empty()){
*numEntries = 0;
return nullptr;
}
*numEntries = stat_infos.size();
hdfsFileInfo *file_infos = new hdfsFileInfo[stat_infos.size()];
for(std::vector<StatInfo>::size_type i = 0; i < stat_infos.size(); i++) {
StatInfoToHdfsFileInfo(&file_infos[i], stat_infos.at(i));
}
return file_infos;
} catch (const std::exception & e) {
ReportException(e);
*numEntries = 0;
return nullptr;
} catch (...) {
ReportCaughtNonException();
*numEntries = 0;
return nullptr;
}
}
LIBHDFSPP_EXT_API
int hdfsCreateSnapshot(hdfsFS fs, const char* path, const char* name) {
try {
errno = 0;
if (!CheckSystem(fs)) {
return -1;
}
const optional<std::string> abs_path = getAbsolutePath(fs, path);
if(!abs_path) {
return -1;
}
Status stat;
if(!name){
stat = fs->get_impl()->CreateSnapshot(*abs_path, "");
} else {
stat = fs->get_impl()->CreateSnapshot(*abs_path, name);
}
if (!stat.ok()) {
return Error(stat);
}
return 0;
} catch (const std::exception & e) {
return ReportException(e);
} catch (...) {
return ReportCaughtNonException();
}
}
LIBHDFSPP_EXT_API
int hdfsDeleteSnapshot(hdfsFS fs, const char* path, const char* name) {
try {
errno = 0;
if (!CheckSystem(fs)) {
return -1;
}
const optional<std::string> abs_path = getAbsolutePath(fs, path);
if(!abs_path) {
return -1;
}
if (!name) {
return Error(Status::InvalidArgument("hdfsDeleteSnapshot: argument 'name' cannot be NULL"));
}
Status stat;
stat = fs->get_impl()->DeleteSnapshot(*abs_path, name);
if (!stat.ok()) {
return Error(stat);
}
return 0;
} catch (const std::exception & e) {
return ReportException(e);
} catch (...) {
return ReportCaughtNonException();
}
}
int hdfsRenameSnapshot(hdfsFS fs, const char* path, const char* old_name, const char* new_name) {
try {
errno = 0;
if (!CheckSystem(fs)) {
return -1;
}
const optional<std::string> abs_path = getAbsolutePath(fs, path);
if(!abs_path) {
return -1;
}
if (!old_name) {
return Error(Status::InvalidArgument("hdfsRenameSnapshot: argument 'old_name' cannot be NULL"));
}
if (!new_name) {
return Error(Status::InvalidArgument("hdfsRenameSnapshot: argument 'new_name' cannot be NULL"));
}
Status stat;
stat = fs->get_impl()->RenameSnapshot(*abs_path, old_name, new_name);
if (!stat.ok()) {
return Error(stat);
}
return 0;
} catch (const std::exception & e) {
return ReportException(e);
} catch (...) {
return ReportCaughtNonException();
}
}
LIBHDFSPP_EXT_API
int hdfsAllowSnapshot(hdfsFS fs, const char* path) {
try {
errno = 0;
if (!CheckSystem(fs)) {
return -1;
}
const optional<std::string> abs_path = getAbsolutePath(fs, path);
if(!abs_path) {
return -1;
}
Status stat;
stat = fs->get_impl()->AllowSnapshot(*abs_path);
if (!stat.ok()) {
return Error(stat);
}
return 0;
} catch (const std::exception & e) {
return ReportException(e);
} catch (...) {
return ReportCaughtNonException();
}
}
LIBHDFSPP_EXT_API
int hdfsDisallowSnapshot(hdfsFS fs, const char* path) {
try {
errno = 0;
if (!CheckSystem(fs)) {
return -1;
}
const optional<std::string> abs_path = getAbsolutePath(fs, path);
if(!abs_path) {
return -1;
}
Status stat;
stat = fs->get_impl()->DisallowSnapshot(*abs_path);
if (!stat.ok()) {
return Error(stat);
}
return 0;
} catch (const std::exception & e) {
return ReportException(e);
} catch (...) {
return ReportCaughtNonException();
}
}
LIBHDFS_C_API
tSize hdfsPread(hdfsFS fs, hdfsFile file, tOffset position, void *buffer,
tSize length) {
try
{
errno = 0;
if (!CheckSystemAndHandle(fs, file)) {
return -1;
}
size_t len = 0;
Status stat = file->get_impl()->PositionRead(buffer, length, position, &len);
if(!stat.ok()) {
return Error(stat);
}
return (tSize)len;
} catch (const std::exception & e) {
return ReportException(e);
} catch (...) {
return ReportCaughtNonException();
}
}
LIBHDFS_C_API
tSize hdfsRead(hdfsFS fs, hdfsFile file, void *buffer, tSize length) {
try
{
errno = 0;
if (!CheckSystemAndHandle(fs, file)) {
return -1;
}
size_t len = 0;
Status stat = file->get_impl()->Read(buffer, length, &len);
if (!stat.ok()) {
return Error(stat);
}
return (tSize)len;
} catch (const std::exception & e) {
return ReportException(e);
} catch (...) {
return ReportCaughtNonException();
}
}
LIBHDFS_C_API
int hdfsUnbufferFile(hdfsFile file) {
//Currently we are not doing any buffering
CheckHandle(file);
return -1;
}
LIBHDFS_C_API
int hdfsFileGetReadStatistics(hdfsFile file, struct hdfsReadStatistics **stats) {
try
{
errno = 0;
if (!CheckHandle(file)) {
return -1;
}
*stats = new hdfsReadStatistics;
memset(*stats, 0, sizeof(hdfsReadStatistics));
(*stats)->totalBytesRead = file->get_impl()->get_bytes_read();
return 0;
} catch (const std::exception & e) {
return ReportException(e);
} catch (...) {
return ReportCaughtNonException();
}
}
LIBHDFS_C_API
int hdfsFileClearReadStatistics(hdfsFile file) {
try
{
errno = 0;
if (!CheckHandle(file)) {
return -1;
}
file->get_impl()->clear_bytes_read();
return 0;
} catch (const std::exception & e) {
return ReportException(e);
} catch (...) {
return ReportCaughtNonException();
}
}
LIBHDFS_C_API
int64_t hdfsReadStatisticsGetRemoteBytesRead(const struct hdfsReadStatistics *stats) {
return stats->totalBytesRead - stats->totalLocalBytesRead;
}
LIBHDFS_C_API
void hdfsFileFreeReadStatistics(struct hdfsReadStatistics *stats) {
errno = 0;
delete stats;
}
/* 0 on success, -1 on error*/
LIBHDFS_C_API
int hdfsSeek(hdfsFS fs, hdfsFile file, tOffset desiredPos) {
try
{
errno = 0;
if (!CheckSystemAndHandle(fs, file)) {
return -1;
}
off_t desired = desiredPos;
Status stat = file->get_impl()->Seek(&desired, std::ios_base::beg);
if (!stat.ok()) {
return Error(stat);
}
return 0;
} catch (const std::exception & e) {
return ReportException(e);
} catch (...) {
return ReportCaughtNonException();
}
}
LIBHDFS_C_API
tOffset hdfsTell(hdfsFS fs, hdfsFile file) {
try
{
errno = 0;
if (!CheckSystemAndHandle(fs, file)) {
return -1;
}
off_t offset = 0;
Status stat = file->get_impl()->Seek(&offset, std::ios_base::cur);
if (!stat.ok()) {
return Error(stat);
}
return (tOffset)offset;
} catch (const std::exception & e) {
return ReportException(e);
} catch (...) {
return ReportCaughtNonException();
}
}
/* extended API */
int hdfsCancel(hdfsFS fs, hdfsFile file) {
try
{
errno = 0;
if (!CheckSystemAndHandle(fs, file)) {
return -1;
}
static_cast<FileHandleImpl*>(file->get_impl())->CancelOperations();
return 0;
} catch (const std::exception & e) {
return ReportException(e);
} catch (...) {
return ReportCaughtNonException();
}
}
LIBHDFSPP_EXT_API
int hdfsGetBlockLocations(hdfsFS fs, const char *path, struct hdfsBlockLocations ** locations_out)
{
try
{
errno = 0;
if (!CheckSystem(fs)) {
return -1;
}
if (locations_out == nullptr) {
ReportError(EINVAL, "Null pointer passed to hdfsGetBlockLocations");
return -1;
}
const optional<std::string> abs_path = getAbsolutePath(fs, path);
if(!abs_path) {
return -1;
}
std::shared_ptr<FileBlockLocation> ppLocations;
Status stat = fs->get_impl()->GetBlockLocations(*abs_path, 0, std::numeric_limits<int64_t>::max(), &ppLocations);
if (!stat.ok()) {
return Error(stat);
}
hdfsBlockLocations *locations = new struct hdfsBlockLocations();
(*locations_out) = locations;
bzero(locations, sizeof(*locations));
locations->fileLength = ppLocations->getFileLength();
locations->isLastBlockComplete = ppLocations->isLastBlockComplete();
locations->isUnderConstruction = ppLocations->isUnderConstruction();
const std::vector<BlockLocation> & ppBlockLocations = ppLocations->getBlockLocations();
locations->num_blocks = ppBlockLocations.size();
locations->blocks = new struct hdfsBlockInfo[locations->num_blocks];
for (size_t i=0; i < ppBlockLocations.size(); i++) {
auto ppBlockLocation = ppBlockLocations[i];
auto block = &locations->blocks[i];
block->num_bytes = ppBlockLocation.getLength();
block->start_offset = ppBlockLocation.getOffset();
const std::vector<DNInfo> & ppDNInfos = ppBlockLocation.getDataNodes();
block->num_locations = ppDNInfos.size();
block->locations = new hdfsDNInfo[block->num_locations];
for (size_t j=0; j < block->num_locations; j++) {
auto ppDNInfo = ppDNInfos[j];
auto dn_info = &block->locations[j];
dn_info->xfer_port = ppDNInfo.getXferPort();
dn_info->info_port = ppDNInfo.getInfoPort();
dn_info->IPC_port = ppDNInfo.getIPCPort();
dn_info->info_secure_port = ppDNInfo.getInfoSecurePort();
char * buf;
buf = new char[ppDNInfo.getHostname().size() + 1];
strncpy(buf, ppDNInfo.getHostname().c_str(), ppDNInfo.getHostname().size() + 1);
dn_info->hostname = buf;
buf = new char[ppDNInfo.getIPAddr().size() + 1];
strncpy(buf, ppDNInfo.getIPAddr().c_str(), ppDNInfo.getIPAddr().size() + 1);
dn_info->ip_address = buf;
buf = new char[ppDNInfo.getNetworkLocation().size() + 1];
strncpy(buf, ppDNInfo.getNetworkLocation().c_str(), ppDNInfo.getNetworkLocation().size() + 1);
dn_info->network_location = buf;
}
}
return 0;
} catch (const std::exception & e) {
return ReportException(e);
} catch (...) {
return ReportCaughtNonException();
}
}
LIBHDFSPP_EXT_API
int hdfsFreeBlockLocations(struct hdfsBlockLocations * blockLocations) {
errno = 0;
if (blockLocations == nullptr)
return 0;
for (size_t i=0; i < blockLocations->num_blocks; i++) {
auto block = &blockLocations->blocks[i];
for (size_t j=0; j < block->num_locations; j++) {
auto location = &block->locations[j];
delete[] location->hostname;
delete[] location->ip_address;
delete[] location->network_location;
}
}
delete[] blockLocations->blocks;
delete blockLocations;
return 0;
}
LIBHDFS_C_API
char*** hdfsGetHosts(hdfsFS fs, const char* path, tOffset start, tOffset length) {
try
{
errno = 0;
if (!CheckSystem(fs)) {
return nullptr;
}
const optional<std::string> abs_path = getAbsolutePath(fs, path);
if(!abs_path) {
return nullptr;
}
std::shared_ptr<FileBlockLocation> ppLocations;
Status stat = fs->get_impl()->GetBlockLocations(*abs_path, start, length, &ppLocations);
if (!stat.ok()) {
Error(stat);
return nullptr;
}
const std::vector<BlockLocation> & ppBlockLocations = ppLocations->getBlockLocations();
char ***hosts = new char**[ppBlockLocations.size() + 1];
for (size_t i=0; i < ppBlockLocations.size(); i++) {
const std::vector<DNInfo> & ppDNInfos = ppBlockLocations[i].getDataNodes();
hosts[i] = new char*[ppDNInfos.size() + 1];
for (size_t j=0; j < ppDNInfos.size(); j++) {
auto ppDNInfo = ppDNInfos[j];
hosts[i][j] = new char[ppDNInfo.getHostname().size() + 1];
strncpy(hosts[i][j], ppDNInfo.getHostname().c_str(), ppDNInfo.getHostname().size() + 1);
}
hosts[i][ppDNInfos.size()] = nullptr;
}
hosts[ppBlockLocations.size()] = nullptr;
return hosts;
} catch (const std::exception & e) {
ReportException(e);
return nullptr;
} catch (...) {
ReportCaughtNonException();
return nullptr;
}
}
LIBHDFS_C_API
void hdfsFreeHosts(char ***blockHosts) {
errno = 0;
if (blockHosts == nullptr)
return;
for (size_t i = 0; blockHosts[i]; i++) {
for (size_t j = 0; blockHosts[i][j]; j++) {
delete[] blockHosts[i][j];
}
delete[] blockHosts[i];
}
delete blockHosts;
}
/*******************************************************************
* EVENT CALLBACKS
*******************************************************************/
const char * FS_NN_CONNECT_EVENT = hdfs::FS_NN_CONNECT_EVENT;
const char * FS_NN_READ_EVENT = hdfs::FS_NN_READ_EVENT;
const char * FS_NN_WRITE_EVENT = hdfs::FS_NN_WRITE_EVENT;
const char * FILE_DN_CONNECT_EVENT = hdfs::FILE_DN_CONNECT_EVENT;
const char * FILE_DN_READ_EVENT = hdfs::FILE_DN_READ_EVENT;
const char * FILE_DN_WRITE_EVENT = hdfs::FILE_DN_WRITE_EVENT;
event_response fs_callback_glue(libhdfspp_fs_event_callback handler,
int64_t cookie,
const char * event,
const char * cluster,
int64_t value) {
int result = handler(event, cluster, value, cookie);
if (result == LIBHDFSPP_EVENT_OK) {
return event_response::make_ok();
}
#ifndef LIBHDFSPP_SIMULATE_ERROR_DISABLED
if (result == DEBUG_SIMULATE_ERROR) {
return event_response::test_err(Status::Error("Simulated error"));
}
#endif
return event_response::make_ok();
}
event_response file_callback_glue(libhdfspp_file_event_callback handler,
int64_t cookie,
const char * event,
const char * cluster,
const char * file,
int64_t value) {
int result = handler(event, cluster, file, value, cookie);
if (result == LIBHDFSPP_EVENT_OK) {
return event_response::make_ok();
}
#ifndef LIBHDFSPP_SIMULATE_ERROR_DISABLED
if (result == DEBUG_SIMULATE_ERROR) {
return event_response::test_err(Status::Error("Simulated error"));
}
#endif
return event_response::make_ok();
}
LIBHDFSPP_EXT_API
int hdfsPreAttachFSMonitor(libhdfspp_fs_event_callback handler, int64_t cookie)
{
fs_event_callback callback = std::bind(fs_callback_glue, handler, cookie, _1, _2, _3);
fsEventCallback = callback;
return 0;
}
LIBHDFSPP_EXT_API
int hdfsPreAttachFileMonitor(libhdfspp_file_event_callback handler, int64_t cookie)
{
file_event_callback callback = std::bind(file_callback_glue, handler, cookie, _1, _2, _3, _4);
fileEventCallback = callback;
return 0;
}
/*******************************************************************
* BUILDER INTERFACE
*******************************************************************/
HdfsConfiguration LoadDefault(ConfigurationLoader & loader)
{
optional<HdfsConfiguration> result = loader.LoadDefaultResources<HdfsConfiguration>();
if (result)
{
return result.value();
}
else
{
return loader.NewConfig<HdfsConfiguration>();
}
}
hdfsBuilder::hdfsBuilder() : config(loader.NewConfig<HdfsConfiguration>())
{
errno = 0;
config = LoadDefault(loader);
}
hdfsBuilder::hdfsBuilder(const char * directory) :
config(loader.NewConfig<HdfsConfiguration>())
{
errno = 0;
loader.SetSearchPath(directory);
config = LoadDefault(loader);
}
LIBHDFS_C_API
struct hdfsBuilder *hdfsNewBuilder(void)
{
try
{
errno = 0;
return new struct hdfsBuilder();
} catch (const std::exception & e) {
ReportException(e);
return nullptr;
} catch (...) {
ReportCaughtNonException();
return nullptr;
}
}
LIBHDFS_C_API
void hdfsBuilderSetNameNode(struct hdfsBuilder *bld, const char *nn)
{
errno = 0;
bld->overrideHost = std::string(nn);
}
LIBHDFS_C_API
void hdfsBuilderSetNameNodePort(struct hdfsBuilder *bld, tPort port)
{
errno = 0;
bld->overridePort = port;
}
LIBHDFS_C_API
void hdfsBuilderSetUserName(struct hdfsBuilder *bld, const char *userName)
{
errno = 0;
if (userName && *userName) {
bld->user = std::string(userName);
}
}
LIBHDFS_C_API
void hdfsBuilderSetForceNewInstance(struct hdfsBuilder *bld) {
//libhdfspp always returns a new instance, so nothing to do
(void)bld;
errno = 0;
}
LIBHDFS_C_API
void hdfsFreeBuilder(struct hdfsBuilder *bld)
{
try
{
errno = 0;
delete bld;
} catch (const std::exception & e) {
ReportException(e);
} catch (...) {
ReportCaughtNonException();
}
}
LIBHDFS_C_API
int hdfsBuilderConfSetStr(struct hdfsBuilder *bld, const char *key,
const char *val)
{
try
{
errno = 0;
optional<HdfsConfiguration> newConfig = bld->loader.OverlayValue(bld->config, key, val);
if (newConfig)
{
bld->config = newConfig.value();
return 0;
}
else
{
ReportError(EINVAL, "Could not change Builder value");
return -1;
}
} catch (const std::exception & e) {
return ReportException(e);
} catch (...) {
return ReportCaughtNonException();
}
}
LIBHDFS_C_API
void hdfsConfStrFree(char *val)
{
errno = 0;
free(val);
}
LIBHDFS_C_API
hdfsFS hdfsBuilderConnect(struct hdfsBuilder *bld) {
hdfsFS fs = doHdfsConnect(bld->overrideHost, bld->overridePort, bld->user, bld->config.GetOptions());
// Always free the builder
hdfsFreeBuilder(bld);
return fs;
}
LIBHDFS_C_API
int hdfsConfGetStr(const char *key, char **val)
{
try
{
errno = 0;
hdfsBuilder builder;
return hdfsBuilderConfGetStr(&builder, key, val);
} catch (const std::exception & e) {
return ReportException(e);
} catch (...) {
return ReportCaughtNonException();
}
}
LIBHDFS_C_API
int hdfsConfGetInt(const char *key, int32_t *val)
{
try
{
errno = 0;
hdfsBuilder builder;
return hdfsBuilderConfGetInt(&builder, key, val);
} catch (const std::exception & e) {
return ReportException(e);
} catch (...) {
return ReportCaughtNonException();
}
}
//
// Extended builder interface
//
struct hdfsBuilder *hdfsNewBuilderFromDirectory(const char * configDirectory)
{
try
{
errno = 0;
return new struct hdfsBuilder(configDirectory);
} catch (const std::exception & e) {
ReportException(e);
return nullptr;
} catch (...) {
ReportCaughtNonException();
return nullptr;
}
}
LIBHDFSPP_EXT_API
int hdfsBuilderConfGetStr(struct hdfsBuilder *bld, const char *key,
char **val)
{
try
{
errno = 0;
optional<std::string> value = bld->config.Get(key);
if (value)
{
size_t len = value->length() + 1;
*val = static_cast<char *>(malloc(len));
strncpy(*val, value->c_str(), len);
}
else
{
*val = nullptr;
}
return 0;
} catch (const std::exception & e) {
return ReportException(e);
} catch (...) {
return ReportCaughtNonException();
}
}
// If we're running on a 32-bit platform, we might get 64-bit values that
// don't fit in an int, and int is specified by the java hdfs.h interface
bool isValidInt(int64_t value)
{
return (value >= std::numeric_limits<int>::min() &&
value <= std::numeric_limits<int>::max());
}
LIBHDFSPP_EXT_API
int hdfsBuilderConfGetInt(struct hdfsBuilder *bld, const char *key, int32_t *val)
{
try
{
errno = 0;
// Pull from default configuration
optional<int64_t> value = bld->config.GetInt(key);
if (value)
{
if (!isValidInt(*value)){
ReportError(EINVAL, "Builder value is not valid");
return -1;
}
*val = *value;
return 0;
}
// If not found, don't change val
ReportError(EINVAL, "Could not get Builder value");
return 0;
} catch (const std::exception & e) {
return ReportException(e);
} catch (...) {
return ReportCaughtNonException();
}
}
LIBHDFSPP_EXT_API
int hdfsBuilderConfGetLong(struct hdfsBuilder *bld, const char *key, int64_t *val)
{
try
{
errno = 0;
// Pull from default configuration
optional<int64_t> value = bld->config.GetInt(key);
if (value)
{
*val = *value;
return 0;
}
// If not found, don't change val
ReportError(EINVAL, "Could not get Builder value");
return 0;
} catch (const std::exception & e) {
return ReportException(e);
} catch (...) {
return ReportCaughtNonException();
}
}
/**
* Logging functions
**/
class CForwardingLogger : public LoggerInterface {
public:
CForwardingLogger() : callback_(nullptr) {};
// Converts LogMessage into LogData, a POD type,
// and invokes callback_ if it's not null.
void Write(const LogMessage& msg);
// pass in NULL to clear the hook
void SetCallback(void (*callback)(LogData*));
//return a copy, or null on failure.
static LogData *CopyLogData(const LogData*);
//free LogData allocated with CopyLogData
static void FreeLogData(LogData*);
private:
void (*callback_)(LogData*);
};
/**
* Plugin to forward message to a C function pointer
**/
void CForwardingLogger::Write(const LogMessage& msg) {
if(!callback_)
return;
const std::string text = msg.MsgString();
LogData data;
data.level = msg.level();
data.component = msg.component();
data.msg = text.c_str();
data.file_name = msg.file_name();
data.file_line = msg.file_line();
callback_(&data);
}
void CForwardingLogger::SetCallback(void (*callback)(LogData*)) {
callback_ = callback;
}
LogData *CForwardingLogger::CopyLogData(const LogData *orig) {
if(!orig)
return nullptr;
LogData *copy = (LogData*)malloc(sizeof(LogData));
if(!copy)
return nullptr;
copy->level = orig->level;
copy->component = orig->component;
if(orig->msg)
copy->msg = strdup(orig->msg);
copy->file_name = orig->file_name;
copy->file_line = orig->file_line;
return copy;
}
void CForwardingLogger::FreeLogData(LogData *data) {
if(!data)
return;
if(data->msg)
free((void*)data->msg);
// Inexpensive way to help catch use-after-free
memset(data, 0, sizeof(LogData));
free(data);
}
LIBHDFSPP_EXT_API
LogData *hdfsCopyLogData(LogData *data) {
return CForwardingLogger::CopyLogData(data);
}
LIBHDFSPP_EXT_API
void hdfsFreeLogData(LogData *data) {
CForwardingLogger::FreeLogData(data);
}
LIBHDFSPP_EXT_API
void hdfsSetLogFunction(void (*callback)(LogData*)) {
CForwardingLogger *logger = new CForwardingLogger();
logger->SetCallback(callback);
LogManager::SetLoggerImplementation(std::unique_ptr<LoggerInterface>(logger));
}
static bool IsLevelValid(int component) {
if(component < HDFSPP_LOG_LEVEL_TRACE || component > HDFSPP_LOG_LEVEL_ERROR)
return false;
return true;
}
// should use __builtin_popcnt as optimization on some platforms
static int popcnt(int val) {
int bits = sizeof(val) * 8;
int count = 0;
for(int i=0; i<bits; i++) {
if((val >> i) & 0x1)
count++;
}
return count;
}
static bool IsComponentValid(int component) {
if(component < HDFSPP_LOG_COMPONENT_UNKNOWN || component > HDFSPP_LOG_COMPONENT_FILESYSTEM)
return false;
if(popcnt(component) != 1)
return false;
return true;
}
LIBHDFSPP_EXT_API
int hdfsEnableLoggingForComponent(int component) {
errno = 0;
if(!IsComponentValid(component))
return -1;
LogManager::EnableLogForComponent(static_cast<LogSourceComponent>(component));
return 0;
}
LIBHDFSPP_EXT_API
int hdfsDisableLoggingForComponent(int component) {
errno = 0;
if(!IsComponentValid(component))
return -1;
LogManager::DisableLogForComponent(static_cast<LogSourceComponent>(component));
return 0;
}
LIBHDFSPP_EXT_API
int hdfsSetLoggingLevel(int level) {
errno = 0;
if(!IsLevelValid(level))
return -1;
LogManager::SetLogLevel(static_cast<LogLevel>(level));
return 0;
}
#undef LIBHDFS_C_API
#undef LIBHDFSPP_EXT_API
|
[
"james.clampffer@hp.com"
] |
james.clampffer@hp.com
|
f851a9e77831e7cdaf1b65a5f5eb8cec95caecbd
|
4963482bb50197b75e8af9dc6362308b0d7b51d0
|
/Source/UI/MainComponent.cpp
|
5a48f8db0841c534fc47b46ac630a41ebda294d8
|
[] |
no_license
|
joaomauricio5/GuitarAmpCabAndPedalboard
|
739ac0889bc638913a17ccb0ec7eed54dc14bbc4
|
0201e8c337098dc3da75ccce209506d62313cbe3
|
refs/heads/main
| 2023-07-18T07:12:15.806310
| 2021-09-06T14:16:59
| 2021-09-06T14:16:59
| 403,104,778
| 1
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 9,646
|
cpp
|
#include "MainComponent.h"
MainComponent::MainComponent(Audio& a) : audio(a),
audioSetupComp (audio.deviceManager,
0, // minimum input channels
256, // maximum input channels
0, // minimum output channels
256, // maximum output channels
false, // ability to select midi inputs
false, // ability to select midi output device
false, // treat channels as stereo pairs
false) // hide advanced options
, inputLevelMeter(audio.deviceManager, LevelMeter::MeterOutputOrInput::Input),
outputLevelMeter(audio.deviceManager, LevelMeter::MeterOutputOrInput::Output)
{
addAndMakeVisible (ampUI);
addAndMakeVisible(cabSimulatorUI);
addAndMakeVisible (audioSetupComp);
addAndMakeVisible(outputLevelMeter);
addAndMakeVisible(inputLevelMeter);
addAndMakeVisible (audioDeviceInfoDisplay);
audioDeviceInfoDisplay.setDeviceManager(&audio.deviceManager);
audioDeviceInfoDisplay.dumpDeviceInfo();
addAndMakeVisible(chorusUI);
addAndMakeVisible(phaserUI);
addAndMakeVisible(reverbUI);
addAndMakeVisible(overdriveDistortionUI);
addAndMakeVisible(fuzzDistortionUI);
addAndMakeVisible(noiseGateUI);
addAndMakeVisible(delayUI);
for (int i = 0; i < NumberOfPedals; i++)
{
addAndMakeVisible(pedalUI[i]);
addAndMakeVisible(pedalSelector[i]);
addAndMakeVisible(blankPedalUI[i]);
}
StringArray pedalsNamesList ("No Pedal", "Chorus", "Reverb", "Overdrive", "Noise Gate", "Delay", "Fuzz", "Phaser");
for (int i = 0; i < NumberOfPedals; i++)
{
pedalSelector[i].addItemList(pedalsNamesList, 1);
pedalSelector[i].addListener(this);
pedalSelector[i].setJustificationType(Justification::centred);
}
// Setting the default pedalUIs
pedalSelector[0].setSelectedId(5, sendNotification);
pedalSelector[1].setSelectedId(4, sendNotification);
pedalSelector[2].setSelectedId(2, sendNotification);
pedalSelector[3].setSelectedId(3, sendNotification);
pedalUI[0] = &noiseGateUI;
pedalUI[1] = &overdriveDistortionUI;
pedalUI[2] = &chorusUI;
pedalUI[3] = &reverbUI;
//
reverbUI.setReverbToControl(audio.getReverbAudio());
chorusUI.setChorusToControl(audio.getChorusAudio());
phaserUI.setPhaserToControl(audio.getPhaserAudio());
overdriveDistortionUI.setDistortionToControl(audio.getOverdriveDistortionAudio());
fuzzDistortionUI.setDistortionToControl(audio.getFuzzDistortionAudio());
noiseGateUI.setNoiseGateToControl(audio.getNoiseGate());
ampUI.setAmpToControl(audio.getAmp());
cabSimulatorUI.setCabSimulatorToControl(audio.getCabSimulator());
delayUI.setDelayToControl(audio.getDelay());
audio.deviceManager.addChangeListener (this);
chorusUI.pedalToggle.addListener(this);
phaserUI.pedalToggle.addListener(this);
reverbUI.pedalToggle.addListener(this);
overdriveDistortionUI.pedalToggle.addListener(this);
fuzzDistortionUI.pedalToggle.addListener(this);
noiseGateUI.pedalToggle.addListener(this);
delayUI.pedalToggle.addListener(this);
setSize (1500, 1000);
}
MainComponent::~MainComponent()
{
audio.deviceManager.removeChangeListener (this);
}
void MainComponent::paint (Graphics& g)
{
g.setColour (Colours::grey);
g.fillRect(audioSetupComp.getBounds());
g.fillRect(audioDeviceInfoDisplay.getBounds());
}
void MainComponent::resized()
{
auto fullWindowRect = getLocalBounds();
audioSetupComp.setItemHeight(getHeight()*0.02);
auto audioDeviceSetupAndInfoRect = fullWindowRect.removeFromTop(audioSetupComp.getHeight());
audioSetupComp.setBounds(audioDeviceSetupAndInfoRect.removeFromLeft(proportionOfWidth(0.6f)));
audioDeviceInfoDisplay.setBounds(audioDeviceSetupAndInfoRect);
auto inputMeterRect = fullWindowRect.removeFromTop(proportionOfHeight(0.03));
inputMeterRect.reduce(450, 5);
inputLevelMeter.setBounds(inputMeterRect);
auto outputMeterRect = fullWindowRect.removeFromBottom(proportionOfHeight(0.05));
outputMeterRect.reduce(450, 12);
outputLevelMeter.setBounds(outputMeterRect);
auto ampAndCabRect = fullWindowRect.removeFromBottom(proportionOfHeight(0.25));
ampAndCabRect.removeFromRight(100);
ampAndCabRect.removeFromLeft(100);
cabSimulatorUI.setBounds(ampAndCabRect.removeFromBottom(proportionOfHeight(0.06)));
ampUI.setBounds(ampAndCabRect);
auto pedalsRect = fullWindowRect;
pedalsRect.reduce(150, 0);
Rectangle<int> individualPedalRect[4];
for (int i = 0; i < NumberOfPedals; i++)
{
individualPedalRect[i] = pedalsRect.removeFromLeft(pedalsRect.getWidth()/ (4 - i));
individualPedalRect[i].reduce(25, 10);
pedalSelector[i].setBounds(individualPedalRect[i].removeFromTop(proportionOfHeight(0.05)));
pedalUI[i]->setBounds(individualPedalRect[i]);
}
}
void MainComponent::changeListenerCallback (ChangeBroadcaster*)
{
audioDeviceInfoDisplay.dumpDeviceInfo();
triggerAsyncUpdate(); // this is used to work around the fact that AudioDeviceSelectorComponent sometimes increases its size automatically when changing settings and ruins the layout
}
void MainComponent::handleAsyncUpdate() //this is used to work around the fact that AudioDeviceSelectorComponent sometimes increases its size automatically when changing settings and ruins the layout
{
resized();
}
void MainComponent::buttonClicked (Button* toggle)
{
if (toggle == &pedalUI[0]->pedalToggle)
audio.isPedalToggleOn[0] = pedalUI[0]->pedalToggle.getToggleState();
else if (toggle == &pedalUI[1]->pedalToggle)
audio.isPedalToggleOn[1] = pedalUI[1]->pedalToggle.getToggleState();
else if (toggle == &pedalUI[2]->pedalToggle)
audio.isPedalToggleOn[2] = pedalUI[2]->pedalToggle.getToggleState();
else if (toggle == &pedalUI[3]->pedalToggle)
audio.isPedalToggleOn[3] = pedalUI[3]->pedalToggle.getToggleState();
}
void MainComponent::comboBoxChanged (ComboBox* comboBoxThatHasChanged)
{
int comboBoxIndex;
for (int i = 0; i < NumberOfPedals; i++)
{
if (comboBoxThatHasChanged == &pedalSelector[i])
comboBoxIndex = i;
}
int optionSelected = comboBoxThatHasChanged->getSelectedId();
int pedalIndex = comboBoxIndex;
makeAllComboBoxOptionsEnabled();
makeAllOptionsSelectedUnavailableInAllComboBoxes();
if (optionSelected == 1)
{
displayAndUseDifferentPedalUI(pedalIndex, blankPedalUI[pedalIndex]);
}
else if (optionSelected == 2)
{
displayAndUseDifferentPedalUI(pedalIndex, chorusUI);
audio.setPedal(pedalIndex, Audio::PedalsAvailable::Chorus);
}
else if (optionSelected == 3)
{
displayAndUseDifferentPedalUI(pedalIndex, reverbUI);
audio.setPedal(pedalIndex, Audio::PedalsAvailable::Reverb);
}
else if (optionSelected == 4)
{
displayAndUseDifferentPedalUI(pedalIndex, overdriveDistortionUI);
audio.setPedal(pedalIndex, Audio::PedalsAvailable::Overdrive);
}
else if (optionSelected == 5)
{
displayAndUseDifferentPedalUI(pedalIndex, noiseGateUI);
audio.setPedal(pedalIndex, Audio::PedalsAvailable::NoiseGate);
}
else if (optionSelected == 6)
{
displayAndUseDifferentPedalUI(pedalIndex, delayUI);
audio.setPedal(pedalIndex, Audio::PedalsAvailable::Delay);
}
else if (optionSelected == 7)
{
displayAndUseDifferentPedalUI(pedalIndex, fuzzDistortionUI);
audio.setPedal(pedalIndex, Audio::PedalsAvailable::Fuzz);
}
else if (optionSelected == 8)
{
displayAndUseDifferentPedalUI(pedalIndex, phaserUI);
audio.setPedal(pedalIndex, Audio::PedalsAvailable::Phaser);
}
}
void MainComponent::makeAllOptionsSelectedUnavailableInAllComboBoxes() // Sets all pedal types that are already selected unavailable to choose in all comboBoxes. Restricts the user to not being able to have 2 or more pedals of the same type
{
for (int i = 0; i < NumberOfPedals; i++)
{
int currentSelectedID = pedalSelector[i].getSelectedId();
if (currentSelectedID != 1)
{
for (int z = 0; z < NumberOfPedals; z ++)
{
pedalSelector[z].setItemEnabled(currentSelectedID, false);
}
}
}
}
void MainComponent::makeAllComboBoxOptionsEnabled() // Enables all comboBox options in every comboBox
{
for (int i = 0; i < NumberOfPedals; i++)
{
for (int z = 1; z <= pedalSelector[i].getNumItems(); z++)
{
pedalSelector[i].setItemEnabled(z, true);
}
}
}
|
[
"noreply@github.com"
] |
joaomauricio5.noreply@github.com
|
a0487e8dda71db2471557894d60f9ddec4268113
|
9870e11c26c15aec3cc13bc910e711367749a7ff
|
/SPOJ/sp_375.cpp
|
fa0e7ff593c43623389d20a3db0e8e05a5df5fb8
|
[] |
no_license
|
liuq901/code
|
56eddb81972d00f2b733121505555b7c7cbc2544
|
fcbfba70338d3d10bad2a4c08f59d501761c205a
|
refs/heads/master
| 2021-01-15T23:50:10.570996
| 2016-01-16T16:14:18
| 2016-01-16T16:14:18
| 12,918,517
| 1
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 6,575
|
cpp
|
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cmath>
struct data
{
int x,l,r,left,right;
};
struct data tree[20000];
int sum,c[10001],d[10001],b[10001],r[10001],s[10001],g[10001],father[10001],heavy[10001];
int w[10001],len[10001],l[20000],e[20000],a[20000][4],h[10001][7],f[16][20000][2];
int main()
{
void work();
int i,t;
scanf("%d",&t);
for (i=1;i<=t;i++)
work();
system("pause");
return(0);
}
void work()
{
void init(int),build(),floodfill(int),change(int,int);
int lca(int,int),find(int,int);
int n,m,x,y,z,i,j,t,ans;
char order[10];
scanf("%d",&n);
init(n);
build();
e[0]=e[1]=1;
memset(g,0,sizeof(g));
g[1]=1;
l[1]=0;
floodfill(1);
memset(g,0,sizeof(g));
for (i=1;i<=e[0];i++)
l[i]=d[e[i]];
for (i=1;i<=e[0];i++)
{
if (g[e[i]])
continue;
g[e[i]]=1;
r[e[i]]=i;
}
m=(int)(log(e[0])/log(2)+0.00001);
memset(f,26,sizeof(f));
for (i=1;i<=e[0];i++)
{
f[0][i][0]=l[i];
f[0][i][1]=e[i];
}
t=1;
for (i=1;i<=m;i++)
{
for (j=1;j<=e[0];j++)
{
if (j+t>e[0])
break;
if (f[i-1][j][0]<f[i][j][0])
{
f[i][j][0]=f[i-1][j][0];
f[i][j][1]=f[i-1][j][1];
}
if (f[i-1][j+t][0]<f[i][j][0])
{
f[i][j][0]=f[i-1][j+t][0];
f[i][j][1]=f[i-1][j+t][1];
}
}
t*=2;
}
while (1)
{
scanf("%s",order);
if (order[0]=='D')
break;
scanf("%d%d%*c",&x,&y);
if (order[0]=='C')
change(x,y);
else
{
ans=-2147483647;
if (x!=y)
{
z=lca(x,y);
t=find(x,z);
if (t>ans)
ans=t;
t=find(y,z);
if (t>ans)
ans=t;
}
printf("%d\n",ans);
}
}
}
void init(int n)
{
void dfs(int,int);
int i,t,x,y,z;
int p[10000][3];
memset(b,0,sizeof(b));
for (i=1;i<=n-1;i++)
{
scanf("%d%d%d",&x,&y,&z);
a[2*i-1][0]=y;
a[2*i-1][1]=b[x];
b[x]=2*i-1;
a[2*i][0]=x;
a[2*i][1]=b[y];
b[y]=2*i;
p[i][0]=x;
p[i][1]=y;
p[i][2]=z;
}
c[0]=0;
dfs(1,0);
memset(b,0,sizeof(b));
for (i=1;i<=n-1;i++)
{
if (c[p[i][0]]>c[p[i][1]])
t=p[i][0],p[i][0]=p[i][1],p[i][1]=t;
x=p[i][0];
y=p[i][1];
z=p[i][2];
father[y]=x;
w[y]=z;
a[i][0]=y;
a[i][1]=z;
a[i][2]=b[x];
a[i][3]=0;
b[x]=i;
}
}
void dfs(int x,int father)
{
int i;
i=b[x];
c[x]=c[father]+1;
while (i!=0)
{
if (a[i][0]!=father)
dfs(a[i][0],x);
i=a[i][1];
}
}
void build()
{
int count(int);
void calc(int),search(int,int,int),make(int);
int i;
count(1);
calc(1);
sum=1;
h[1][2]=1;
search(1,1,1);
len[0]=0;
for (i=1;i<=sum;i++)
make(i);
}
int count(int x)
{
int i,t;
s[x]=1;
i=b[x];
while (i!=0)
{
t=count(a[i][0]);
s[x]+=t;
i=a[i][2];
}
return(s[x]);
}
void calc(int x)
{
int i,max,k;
k=-1;
max=0;
i=b[x];
while (i!=0)
{
heavy[a[i][0]]=0;
if (s[a[i][0]]>max)
{
max=s[a[i][0]];
k=i;
}
calc(a[i][0]);
i=a[i][2];
}
if (k!=-1)
{
a[k][3]=1;
heavy[a[k][0]]=1;
}
}
void search(int x,int t,int p)
{
int i;
i=b[x];
h[x][0]=t;
h[x][1]=p;
h[t][3]=x;
h[x][4]=h[x][5]=0;
while (i!=0)
{
if (a[i][3])
{
h[x][4]=a[i][0];
h[x][5]=i;
if (s[a[i][0]]!=1)
search(a[i][0],t,p+1);
}
else if (s[a[i][0]]!=1)
{
sum++;
h[sum][2]=a[i][0];
search(a[i][0],sum,1);
}
i=a[i][2];
}
}
void make(int t)
{
void buildtree(int,int,int);
int i,s;
i=h[t][2];
s=0;
while (i!=h[t][3])
{
s++;
len[s]=a[h[i][5]][1];
i=a[h[i][5]][0];
}
s++;
len[s]=a[h[i][5]][1];
len[0]++;
h[t][6]=len[0];
buildtree(len[0],1,s);
}
void buildtree(int x,int l,int r)
{
int mid;
mid=(l+r)/2;
tree[x].l=l;
tree[x].r=r;
if (l==r)
{
tree[x].x=len[l];
return;
}
len[0]++;
tree[x].left=len[0];
buildtree(len[0],l,mid);
len[0]++;
tree[x].right=len[0];
buildtree(len[0],mid+1,r);
if (tree[tree[x].left].x>tree[tree[x].right].x)
tree[x].x=tree[tree[x].left].x;
else
tree[x].x=tree[tree[x].right].x;
}
void floodfill(int x)
{
int i;
i=b[x];
while (i!=0)
{
g[a[i][0]]=1;
d[a[i][0]]=d[x]+1;
e[0]++;
e[e[0]]=a[i][0];
floodfill(a[i][0]);
e[0]++;
e[e[0]]=x;
i=a[i][2];
}
}
void change(int x,int y)
{
void insert(int,int,int);
int t,p;
if (!a[x][3])
{
a[x][1]=y;
w[a[x][0]]=y;
return;
}
t=h[h[father[a[x][0]]][0]][6];
p=h[father[a[x][0]]][1];
insert(t,p,y);
}
void insert(int x,int p,int t)
{
int mid;
if (tree[x].l==tree[x].r)
{
tree[x].x=t;
return;
}
mid=(tree[x].l+tree[x].r)/2;
if (p<=mid)
insert(tree[x].left,p,t);
else
insert(tree[x].right,p,t);
if (tree[tree[x].left].x>tree[tree[x].right].x)
tree[x].x=tree[tree[x].left].x;
else
tree[x].x=tree[tree[x].right].x;
}
int lca(int x,int y)
{
int t,i;
if (r[x]>r[y])
t=x,x=y,y=t;
t=(int)(log(r[y]-r[x])/log(2)+0.0001);
if (f[t][r[x]][0]<f[t][r[y]-(1<<t)+1][0])
return(f[t][r[x]][1]);
else
return(f[t][r[y]-(1<<t)+1][1]);
}
int find(int x,int root)
{
int get(int,int,int);
int t,p,q,ans;
ans=-2147483647;
while (x!=root)
{
if (!heavy[x])
{
if (w[x]>ans)
ans=w[x];
x=father[x];
continue;
}
p=h[father[x]][0];
q=h[root][0];
if (p==q)
{
t=get(h[p][6],h[root][1],h[father[x]][1]);
if (t>ans)
ans=t;
break;
}
t=get(h[p][6],1,h[father[x]][1]);
if (t>ans)
ans=t;
x=h[p][2];
}
return(ans);
}
int get(int x,int l,int r)
{
int max(int,int);
int mid;
if (l==tree[x].l && r==tree[x].r)
return(tree[x].x);
mid=(tree[x].l+tree[x].r)/2;
if (r<=mid)
return(get(tree[x].left,l,r));
if (l>mid)
return(get(tree[x].right,l,r));
return(max(get(tree[x].left,l,mid),get(tree[x].right,mid+1,r)));
}
int max(int x,int y)
{
if (x>y)
return(x);
else
return(y);
}
|
[
"liuq901@163.com"
] |
liuq901@163.com
|
d547c8da1f0de91a33e5ee71791fb5b60e6e6dd2
|
12bfb71c5e7888c2111d1b15e6a974f8076ae356
|
/lab8/RubiksCube.cpp
|
2ecfe69eae8289d7976896a13fb5ba0872d77809
|
[] |
no_license
|
ravaelamanov/Programming-HW-sem-2
|
0f96f64db5d76e7089164a161f3dd86f2d185863
|
a27ab361d30522bf04348ba67fcdd44d1ea0b097
|
refs/heads/master
| 2022-09-19T03:50:01.137786
| 2020-06-06T07:18:36
| 2020-06-06T07:18:36
| 248,932,857
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 13,067
|
cpp
|
//
// Created by Sherzod on 18.05.2020.
//
#include "RubiksCube.h"
void RubiksCube::CubeSide::read(std::istream &input) {
for (int i = 0; i < 9; i++) {
input >> side_[i];
}
}
void RubiksCube::CubeSide::write(std::ostream &output) const {
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
output << side_[i * 3 + j] << " ";
}
output << "\n";
}
output << "\n";
}
int &RubiksCube::CubeSide::operator[](size_t index) {
if (index < 0 || index >= 9)
throw std::out_of_range("Index out of bounds!\n");
else
return side_[index];
}
const int &RubiksCube::CubeSide::operator[](size_t index) const {
if (index < 0 || index >= 9)
throw std::out_of_range("Index out of bounds!\n");
else
return side_[index];
}
std::istream &operator>>(std::istream &input, RubiksCube &cube) {
for (int i = 0; i < 6; i++) {
cube[i].read(input);
}
return input;
}
std::ostream &operator<<(std::ostream &output, const RubiksCube &cube) {
for (int i = 0; i < 6; i++) {
cube[i].write(output);
}
return output;
}
void RubiksCube::toConsole() const {
std::string sides[6] = {"DOWN", "FRONT", "RIGHT", "BACK", "LEFT", "TOP"};
for (int i = 0; i < 6; i++) {
std::cout << sides[i] << "\n";
(*this)[i].write(std::cout);
}
}
RubiksCube::CubeSide &RubiksCube::operator[](std::size_t index) {
if (index < 0 || index >= 6)
throw std::out_of_range("Index out of bounds!");
else
return sides_[index];
}
const RubiksCube::CubeSide &RubiksCube::operator[](std::size_t index) const {
if (index < 0 || index >= 6)
throw std::out_of_range("Index out of bounds!");
else
return sides_[index];
}
void RubiksCube::rotate(int side, bool dir) {
// std::cout << side << " " << dir << "\n";
switch (side) {
case FRONT: {
rotateFront(dir);
break;
}
case TOP: {
rotateTop(dir);
break;
}
case RIGHT: {
rotateRight(dir);
break;
}
case BACK: {
rotateBack(dir);
break;
}
case DOWN: {
rotateDown(dir);
break;
}
case LEFT: {
rotateLeft(dir);
break;
}
default: {
std::cout << "Error!\n";
}
}
}
void RubiksCube::rotateFront(bool isClockwise) {
int oldLeft[3] = {sides_[LEFT][8], sides_[LEFT][5], sides_[LEFT][2]};
int oldTop[3] = {sides_[TOP][6], sides_[TOP][7], sides_[TOP][8]};
int oldRight[3] = {sides_[RIGHT][6], sides_[RIGHT][3], sides_[RIGHT][0]};
int oldDown[3] = {sides_[DOWN][0], sides_[DOWN][1], sides_[DOWN][2]};
if (isClockwise) {
//trdl -> ltrd;
//update top
sides_[TOP][6] = oldLeft[0];
sides_[TOP][7] = oldLeft[1];
sides_[TOP][8] = oldLeft[2];
//update right
sides_[RIGHT][0] = oldTop[0];
sides_[RIGHT][3] = oldTop[1];
sides_[RIGHT][6] = oldTop[2];
//update down
sides_[DOWN][0] = oldRight[0];
sides_[DOWN][1] = oldRight[1];
sides_[DOWN][2] = oldRight[2];
//update left
sides_[LEFT][2] = oldDown[0];
sides_[LEFT][5] = oldDown[1];
sides_[LEFT][8] = oldDown[2];
}
else {
//trdl -> rtld;
//update top
sides_[TOP][6] = oldRight[2];
sides_[TOP][7] = oldRight[1];
sides_[TOP][8] = oldRight[0];
//update right
sides_[RIGHT][0] = oldDown[2];
sides_[RIGHT][3] = oldDown[1];
sides_[RIGHT][6] = oldDown[0];
//update down
sides_[DOWN][0] = oldLeft[2];
sides_[DOWN][1] = oldLeft[1];
sides_[DOWN][2] = oldLeft[0];
//update left
sides_[LEFT][2] = oldTop[2];
sides_[LEFT][5] = oldTop[1];
sides_[LEFT][8] = oldTop[0];
}
rotateSide(FRONT, isClockwise);
}
void RubiksCube::rotateTop(bool isClockwise) {
int oldBack[3] = {sides_[BACK][0], sides_[BACK][1], sides_[BACK][2]};
int oldRight[3] = {sides_[RIGHT][0], sides_[RIGHT][1], sides_[RIGHT][2]};
int oldFront[3] = {sides_[FRONT][0], sides_[FRONT][1], sides_[FRONT][2]};
int oldLeft[3] = {sides_[LEFT][0], sides_[LEFT][1], sides_[LEFT][2]};
if (isClockwise) {
sides_[BACK][0] = oldLeft[0];
sides_[BACK][1] = oldLeft[1];
sides_[BACK][2] = oldLeft[2];
sides_[RIGHT][0] = oldBack[0];
sides_[RIGHT][1] = oldBack[1];
sides_[RIGHT][2] = oldBack[2];
sides_[FRONT][0] = oldRight[0];
sides_[FRONT][1] = oldRight[1];
sides_[FRONT][2] = oldRight[2];
sides_[LEFT][0] = oldFront[0];
sides_[LEFT][1] = oldFront[1];
sides_[LEFT][2] = oldFront[2];
}
else {
sides_[BACK][0] = oldRight[0];
sides_[BACK][1] = oldRight[1];
sides_[BACK][2] = oldRight[2];
sides_[RIGHT][0] = oldFront[0];
sides_[RIGHT][1] = oldFront[1];
sides_[RIGHT][2] = oldFront[2];
sides_[FRONT][0] = oldLeft[0];
sides_[FRONT][1] = oldLeft[1];
sides_[FRONT][2] = oldLeft[2];
sides_[LEFT][0] = oldBack[0];
sides_[LEFT][1] = oldBack[1];
sides_[LEFT][2] = oldBack[2];
}
rotateSide(TOP, isClockwise);
}
void RubiksCube::rotateRight(bool isClockwise) {
int oldTop[3] = {sides_[TOP][8], sides_[TOP][5], sides_[TOP][2]};
int oldBack[3] = {sides_[BACK][6], sides_[BACK][3], sides_[BACK][0]};
int oldDown[3] = {sides_[DOWN][2], sides_[DOWN][5], sides_[DOWN][8]};
int oldFront[3] = {sides_[FRONT][2], sides_[FRONT][5], sides_[FRONT][8]};
if (isClockwise) {
sides_[TOP][2] = oldFront[0];
sides_[TOP][5] = oldFront[1];
sides_[TOP][8] = oldFront[2];
sides_[BACK][0] = oldTop[0];
sides_[BACK][3] = oldTop[1];
sides_[BACK][6] = oldTop[2];
sides_[DOWN][2] = oldBack[0];
sides_[DOWN][5] = oldBack[1];
sides_[DOWN][8] = oldBack[2];
sides_[FRONT][2] = oldDown[0];
sides_[FRONT][5] = oldDown[1];
sides_[FRONT][8] = oldDown[2];
}
else {
sides_[TOP][2] = oldBack[0];
sides_[TOP][5] = oldBack[1];
sides_[TOP][8] = oldBack[2];
sides_[BACK][0] = oldDown[2];
sides_[BACK][3] = oldDown[1];
sides_[BACK][6] = oldDown[0];
sides_[DOWN][2] = oldFront[0];
sides_[DOWN][5] = oldFront[1];
sides_[DOWN][8] = oldFront[2];
sides_[FRONT][2] = oldTop[2];
sides_[FRONT][5] = oldTop[1];
sides_[FRONT][8] = oldTop[0];
}
rotateSide(RIGHT, isClockwise);
}
void RubiksCube::rotateBack(bool isClockwise) {
int oldTop[3] = {sides_[TOP][2], sides_[TOP][1], sides_[TOP][0]};
int oldLeft[3] = {sides_[LEFT][0], sides_[LEFT][3], sides_[LEFT][6]};
int oldDown[3] = {sides_[DOWN][6], sides_[DOWN][7], sides_[DOWN][8]};
int oldRight[3] = {sides_[RIGHT][2], sides_[RIGHT][5], sides_[RIGHT][8]};
if (isClockwise) {
sides_[TOP][0] = oldRight[0];
sides_[TOP][1] = oldRight[1];
sides_[TOP][2] = oldRight[2];
sides_[LEFT][0] = oldTop[0];
sides_[LEFT][3] = oldTop[1];
sides_[LEFT][6] = oldTop[2];
sides_[DOWN][6] = oldLeft[0];
sides_[DOWN][7] = oldLeft[1];
sides_[DOWN][8] = oldLeft[2];
sides_[RIGHT][2] = oldDown[2];
sides_[RIGHT][5] = oldDown[1];
sides_[RIGHT][8] = oldDown[0];
}
else {
sides_[TOP][0] = oldLeft[2];
sides_[TOP][1] = oldLeft[1];
sides_[TOP][2] = oldLeft[0];
sides_[LEFT][0] = oldDown[0];
sides_[LEFT][3] = oldDown[1];
sides_[LEFT][6] = oldDown[2];
sides_[DOWN][6] = oldRight[2];
sides_[DOWN][7] = oldRight[1];
sides_[DOWN][8] = oldRight[0];
sides_[RIGHT][2] = oldTop[2];
sides_[RIGHT][5] = oldTop[1];
sides_[RIGHT][8] = oldTop[0];
}
rotateSide(BACK, isClockwise);
}
void RubiksCube::rotateDown(bool isClockwise) {
int oldFront[3] = {sides_[FRONT][6], sides_[FRONT][7], sides_[FRONT][8]};
int oldRight[3] = {sides_[RIGHT][6], sides_[RIGHT][7], sides_[RIGHT][8]};
int oldBack[3] = {sides_[BACK][6], sides_[BACK][7], sides_[BACK][8]};
int oldLeft[3] = {sides_[LEFT][6], sides_[LEFT][7], sides_[LEFT][8]};
if (isClockwise) {
sides_[FRONT][6] = oldLeft[0];
sides_[FRONT][7] = oldLeft[1];
sides_[FRONT][8] = oldLeft[2];
sides_[RIGHT][6] = oldFront[0];
sides_[RIGHT][7] = oldFront[1];
sides_[RIGHT][8] = oldFront[2];
sides_[BACK][6] = oldRight[0];
sides_[BACK][7] = oldRight[1];
sides_[BACK][8] = oldRight[2];
sides_[LEFT][6] = oldBack[0];
sides_[LEFT][7] = oldBack[1];
sides_[LEFT][8] = oldBack[2];
}
else {
sides_[FRONT][6] = oldRight[0];
sides_[FRONT][7] = oldRight[1];
sides_[FRONT][8] = oldRight[2];
sides_[RIGHT][6] = oldBack[0];
sides_[RIGHT][7] = oldBack[1];
sides_[RIGHT][8] = oldBack[2];
sides_[BACK][6] = oldLeft[0];
sides_[BACK][7] = oldLeft[1];
sides_[BACK][8] = oldLeft[2];
sides_[LEFT][6] = oldFront[0];
sides_[LEFT][7] = oldFront[1];
sides_[LEFT][8] = oldFront[2];
}
rotateSide(DOWN, isClockwise);
}
void RubiksCube::rotateLeft(bool isClockwise) {
int oldTop[3] = {sides_[TOP][0], sides_[TOP][3], sides_[TOP][6]};
int oldFront[3] = {sides_[FRONT][0], sides_[FRONT][3], sides_[FRONT][6]};
int oldDown[3] = {sides_[DOWN][0], sides_[DOWN][3], sides_[DOWN][6]};
int oldBack[3] = {sides_[BACK][2], sides_[BACK][5], sides_[BACK][8]};
if (isClockwise) {
sides_[TOP][0] = oldBack[2];
sides_[TOP][3] = oldBack[1];
sides_[TOP][6] = oldBack[0];
sides_[FRONT][0] = oldTop[0];
sides_[FRONT][3] = oldTop[1];
sides_[FRONT][6] = oldTop[2];
sides_[DOWN][0] = oldFront[0];
sides_[DOWN][3] = oldFront[1];
sides_[DOWN][6] = oldFront[2];
sides_[BACK][2] = oldDown[2];
sides_[BACK][5] = oldDown[1];
sides_[BACK][8] = oldDown[0];
}
else {
sides_[TOP][0] = oldFront[0];
sides_[TOP][3] = oldFront[1];
sides_[TOP][6] = oldFront[2];
sides_[FRONT][0] = oldDown[0];
sides_[FRONT][3] = oldDown[1];
sides_[FRONT][6] = oldDown[2];
sides_[DOWN][0] = oldBack[2];
sides_[DOWN][3] = oldBack[1];
sides_[DOWN][6] = oldBack[0];
sides_[BACK][2] = oldTop[2];
sides_[BACK][5] = oldTop[1];
sides_[BACK][8] = oldTop[0];
}
rotateSide(LEFT, isClockwise);
}
void RubiksCube::rotateSide(int side, bool isClockwise) {
CubeSide oldSide = sides_[side];
if (isClockwise) {
sides_[side][0] = oldSide[6];
sides_[side][1] = oldSide[3];
sides_[side][2] = oldSide[0];
sides_[side][3] = oldSide[7];
sides_[side][4] = oldSide[4];
sides_[side][5] = oldSide[1];
sides_[side][6] = oldSide[8];
sides_[side][7] = oldSide[5];
sides_[side][8] = oldSide[2];
}
else {
sides_[side][0] = oldSide[2];
sides_[side][1] = oldSide[5];
sides_[side][2] = oldSide[8];
sides_[side][3] = oldSide[1];
sides_[side][4] = oldSide[4];
sides_[side][5] = oldSide[7];
sides_[side][6] = oldSide[0];
sides_[side][7] = oldSide[3];
sides_[side][8] = oldSide[6];
}
}
bool RubiksCube::checkCube() const {
int cnt[6] = {0};
//check centres
for (int i = 0; i < 6; i++) {
if (cnt[sides_[i][4]] > 0)
return false;
else cnt[sides_[i][4]]++;
}
//check other
for (int i = 0; i < 6; i++) {
for (int j = 0; j < 9; j++) {
if (j == 4)
continue;
cnt[sides_[i][j]]++;
}
}
for (int i = 0; i < 6; i++) {
if (cnt[i] != 9)
return false;
}
return true;
}
bool RubiksCube::operator==(const RubiksCube &other) const {
for (int i = 0; i < 6; i++) {
for (int j = 0; j < 9; j++) {
if ((*this)[i][j] != other[i][j])
return false;
}
}
return true;
}
void RubiksCube::shuffle() {
std::srand(time(nullptr));
int rotationsCnt = rand() % 100 + 100;
for (int i = 0; i < rotationsCnt; i++) {
rotate(rand() % 6, rand() % 2);
}
}
|
[
"noreply@github.com"
] |
ravaelamanov.noreply@github.com
|
e52c2a00b4800ca7df0be3322cbbf0cfa06aa0a7
|
68c8eead2f74f6acfe1dfd25aca5d4c09d2c9c92
|
/src/opencv-code/precomp.hpp
|
8787f1b3c0f162e8aaea84cc23c264eb06d3b342
|
[] |
no_license
|
rmeesters/GnomeVision-2020
|
22379dea5968954c88d261a76f5d1e8d6a494856
|
0ddce4ddcbe55ae5bbad9bf3496e7a5d2135e86e
|
refs/heads/master
| 2020-12-18T13:26:23.932184
| 2020-02-09T17:36:43
| 2020-02-09T17:36:43
| 235,399,387
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 9,453
|
hpp
|
/*M///////////////////////////////////////////////////////////////////////////////////////
//
// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
// By downloading, copying, installing or using the software you agree to this license.
// If you do not agree to this license, do not download, install,
// copy or use the software.
//
//
// Intel License Agreement
// For Open Source Computer Vision Library
//
// Copyright (C) 2000, Intel Corporation, all rights reserved.
// Third party copyrights are property of their respective owners.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistribution's of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistribution's 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.
//
// * The name of Intel Corporation may not be used to endorse or promote products
// derived from this software without specific prior written permission.
//
// This software is provided by the copyright holders and contributors "as is" and
// any express or implied warranties, including, but not limited to, the implied
// warranties of merchantability and fitness for a particular purpose are disclaimed.
// In no event shall the Intel Corporation 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.
//
//M*/
#ifndef __HIGHGUI_H_
#define __HIGHGUI_H_
#include "cvconfig.h"
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/highgui/highgui_c.h"
#include "opencv2/imgproc/imgproc_c.h"
// #include "opencv3/core/core.hpp"
#include "opencv2/videoio/videoio_c.h"
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <limits.h>
#include <ctype.h>
#include <assert.h>
#if defined WIN32 || defined WINCE
#if !defined _WIN32_WINNT
#ifdef HAVE_MSMF
#define _WIN32_WINNT 0x0600 // Windows Vista
#else
#define _WIN32_WINNT 0x0500 // Windows 2000
#endif
#endif
#include <windows.h>
#undef small
#undef min
#undef max
#undef abs
#endif
#ifdef HAVE_TEGRA_OPTIMIZATION
#include "opencv2/highgui/highgui_tegra.hpp"
#endif
/* Errors */
#define HG_OK 0 /* Don't bet on it! */
#define HG_BADNAME -1 /* Bad window or file name */
#define HG_INITFAILED -2 /* Can't initialize HigHGUI */
#define HG_WCFAILED -3 /* Can't create a window */
#define HG_NULLPTR -4 /* The null pointer where it should not appear */
#define HG_BADPARAM -5
#define __BEGIN__ __CV_BEGIN__
#define __END__ __CV_END__
#define EXIT __CV_EXIT__
#define CV_WINDOW_MAGIC_VAL 0x00420042
#define CV_TRACKBAR_MAGIC_VAL 0x00420043
/***************************** CvCapture structure ******************************/
struct CvCapture
{
virtual ~CvCapture() {}
virtual double getProperty(int) { return 0; }
virtual bool setProperty(int, double) { return 0; }
virtual bool grabFrame() { return true; }
virtual IplImage* retrieveFrame(int) { return 0; }
virtual int getCaptureDomain() { return CV_CAP_ANY; } // Return the type of the capture object: CV_CAP_VFW, etc...
};
/*************************** CvVideoWriter structure ****************************/
struct CvVideoWriter
{
virtual ~CvVideoWriter() {}
virtual bool writeFrame(const IplImage*) { return false; }
};
CvCapture * cvCreateCameraCapture_V4L( int index );
CvCapture * cvCreateCameraCapture_DC1394( int index );
CvCapture * cvCreateCameraCapture_DC1394_2( int index );
CvCapture* cvCreateCameraCapture_MIL( int index );
CvCapture* cvCreateCameraCapture_Giganetix( int index );
CvCapture * cvCreateCameraCapture_CMU( int index );
CV_IMPL CvCapture * cvCreateCameraCapture_TYZX( int index );
CvCapture* cvCreateFileCapture_Win32( const char* filename );
CvCapture* cvCreateCameraCapture_VFW( int index );
CvCapture* cvCreateFileCapture_VFW( const char* filename );
CvVideoWriter* cvCreateVideoWriter_Win32( const char* filename, int fourcc,
double fps, CvSize frameSize, int is_color );
CvVideoWriter* cvCreateVideoWriter_VFW( const char* filename, int fourcc,
double fps, CvSize frameSize, int is_color );
CvCapture* cvCreateCameraCapture_DShow( int index );
CvCapture* cvCreateCameraCapture_MSMF( int index );
CvCapture* cvCreateFileCapture_MSMF (const char* filename);
CvVideoWriter* cvCreateVideoWriter_MSMF( const char* filename, int fourcc,
double fps, CvSize frameSize, int is_color );
CvCapture* cvCreateCameraCapture_OpenNI( int index );
CvCapture* cvCreateFileCapture_OpenNI( const char* filename );
CvCapture* cvCreateCameraCapture_Android( int index );
CvCapture* cvCreateCameraCapture_XIMEA( int index );
CvCapture* cvCreateCameraCapture_AVFoundation(int index);
CvCapture* cvCreateCameraCapture_IntelPerC(int index);
CVAPI(int) cvHaveImageReader(const char* filename);
CVAPI(int) cvHaveImageWriter(const char* filename);
CvCapture* cvCreateFileCapture_Images(const char* filename);
CvVideoWriter* cvCreateVideoWriter_Images(const char* filename);
CvCapture* cvCreateFileCapture_XINE (const char* filename);
#define CV_CAP_GSTREAMER_1394 0
#define CV_CAP_GSTREAMER_V4L 1
#define CV_CAP_GSTREAMER_V4L2 2
#define CV_CAP_GSTREAMER_FILE 3
CvCapture* cvCreateCapture_GStreamer(int type, const char *filename);
CvCapture* cvCreateFileCapture_FFMPEG_proxy(const char* filename);
CvVideoWriter* cvCreateVideoWriter_FFMPEG_proxy( const char* filename, int fourcc,
double fps, CvSize frameSize, int is_color );
CvCapture * cvCreateFileCapture_QT (const char * filename);
CvCapture * cvCreateCameraCapture_QT (const int index);
CvVideoWriter* cvCreateVideoWriter_QT ( const char* filename, int fourcc,
double fps, CvSize frameSize, int is_color );
CvCapture* cvCreateFileCapture_AVFoundation (const char * filename);
CvVideoWriter* cvCreateVideoWriter_AVFoundation( const char* filename, int fourcc,
double fps, CvSize frameSize, int is_color );
CvCapture * cvCreateCameraCapture_Unicap (const int index);
CvCapture * cvCreateCameraCapture_PvAPI (const int index);
CvVideoWriter* cvCreateVideoWriter_GStreamer( const char* filename, int fourcc,
double fps, CvSize frameSize, int is_color );
//Yannick Verdie 2010
void cvSetModeWindow_W32(const char* name, double prop_value);
void cvSetModeWindow_GTK(const char* name, double prop_value);
void cvSetModeWindow_CARBON(const char* name, double prop_value);
void cvSetModeWindow_COCOA(const char* name, double prop_value);
double cvGetModeWindow_W32(const char* name);
double cvGetModeWindow_GTK(const char* name);
double cvGetModeWindow_CARBON(const char* name);
double cvGetModeWindow_COCOA(const char* name);
double cvGetPropWindowAutoSize_W32(const char* name);
double cvGetPropWindowAutoSize_GTK(const char* name);
double cvGetRatioWindow_W32(const char* name);
double cvGetRatioWindow_GTK(const char* name);
double cvGetOpenGlProp_W32(const char* name);
double cvGetOpenGlProp_GTK(const char* name);
//for QT
#if defined (HAVE_QT)
double cvGetModeWindow_QT(const char* name);
void cvSetModeWindow_QT(const char* name, double prop_value);
double cvGetPropWindow_QT(const char* name);
void cvSetPropWindow_QT(const char* name,double prop_value);
double cvGetRatioWindow_QT(const char* name);
void cvSetRatioWindow_QT(const char* name,double prop_value);
double cvGetOpenGlProp_QT(const char* name);
#endif
/*namespace cv
{
class CV_EXPORTS BaseWindow
{
public:
BaseWindow(const String& name, int flags=0);
virtual ~BaseWindow();
virtual void close();
virtual void show(const Mat& mat);
virtual void resize(Size size);
virtual void move(Point topleft);
virtual Size size() const;
virtual Point topLeft() const;
virtual void setGeometry(Point topLeft, Size size);
virtual void getGeometry(Point& topLeft, Size& size) const;
virtual String getTitle() const;
virtual void setTitle(const String& str);
virtual String getName() const;
virtual void setScaleMode(int mode);
virtual int getScaleMode();
virtual void setScrollPos(double pos);
virtual double getScrollPos() const;
virtual void setScale(double scale);
virtual double getScale() const;
virtual Point getImageCoords(Point pos) const;
virtual Scalar getPixelValue(Point pos, const String& colorspace=String()) const;
virtual void addTrackbar( const String& trackbar, int low, int high, int step );
};
typedef Ptr<BaseWindow> Window;
}*/
#endif /* __HIGHGUI_H_ */
|
[
"meesters.rich@gmail.com"
] |
meesters.rich@gmail.com
|
e5e48a82a475ad2ae3d337063469492e629854be
|
a9e308c81c27a80c53c899ce806d6d7b4a9bbbf3
|
/SDK/include/WildMagic4/SDK/Include/Wm4RandomHypersphere.h
|
afa93fd1ac7c896e60460fbd8ea26246689be25b
|
[
"BSL-1.0"
] |
permissive
|
NikitaNikson/xray-2_0
|
00d8e78112d7b3d5ec1cb790c90f614dc732f633
|
82b049d2d177aac15e1317cbe281e8c167b8f8d1
|
refs/heads/master
| 2023-06-25T16:51:26.243019
| 2020-09-29T15:49:23
| 2020-09-29T15:49:23
| 390,966,305
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,550
|
h
|
// Geometric Tools, LLC
// Copyright (c) 1998-2010
// Distributed under the Boost Software License, Version 1.0.
// http://www.boost.org/LICENSE_1_0.txt
// http://www.geometrictools.com/License/Boost/LICENSE_1_0.txt
//
// File Version: 4.10.0 (2009/11/18)
#ifndef WM4RANDOMHYPERSPHERE_H
#define WM4RANDOMHYPERSPHERE_H
#include "Wm4FoundationLIB.h"
#include "Wm4System.h"
namespace Wm4
{
// Generate N random points on the hypersphere in D-space,
//
// x_1^2 + ... + x_D^2 = 1
//
// The function selects a random angle in [0,2*pi) and partitions
// the equation into
//
// x_1^2 + ... + x_{D/2}^2 = (cos(A))^2
//
// and
//
// x_{D/2+1}^2 + ... + x_D^2 = (sin(A))^2
//
// The function initializes all components of P to 1. The partitioned
// components are updated as x_i *= cos(A) for 0 <= i < D/2 and
// x_i *= sin(A) for D/2 <= i < D. The function is recursively called
// on the partitioned components.
WM4_FOUNDATION_ITEM void RandomPointOnHypersphere (int iDimension,
double* adPoint);
// An attempt to determine the uniformity of N randomly generated
// points P[0] through P[N-1] on the hypersphere. Select a positive
// angle. For each point P[i] count the number H[i] of random points
// P[j] which lie in the cone with axis P[i] and specified angle. For
// N suitably large, H[i] should be constant for all i. To be really
// sure of the uniformity, you should look at other cones whose axes
// are not the sample points. However, this requires generating random
// points to get the axes and, well, you can see the problem...
WM4_FOUNDATION_ITEM void Histogram (int iDimension, double dAngle,
int iQuantity, double** aadPoint, int* aiHistogram);
//An example of how to use these functions.
//
//void TestRandomHyperspherePoints ()
//{
// const int iQuantity = 4096;
// const int iDimension = 3;
// int i;
//
// double** aadPoint = WM4_NEW double*[iQuantity];
// aadPoint[0] = WM4_NEW double[iQuantity*iDimension];
// for (i = 1; i < iQuantity; i++)
// aadPoint[i] = &aadPoint[0][iDimension*i];
//
// for (i = 0; i < iQuantity; i++)
// RandomPointOnHypersphere(iDimension,aadPoint[i]);
//
// int* aiHistogram = WM4_NEW int[iQuantity];
// double dAngle = 0.5;
// Histogram(iDimension,dAngle,iQuantity,aadPoint,aiHistogram);
//
// ofstream ostr("histo.txt");
// for (i = 0; i < iQuantity; i++)
// ostr << i << ' ' << aiHistogram[i] << endl;
//
// WM4_DELETE[] aiHistogram;
// WM4_DELETE[] aadPoint[0];
// WM4_DELETE[] aadPoint;
//}
}
#endif
|
[
"loxotron@bk.ru"
] |
loxotron@bk.ru
|
6951c61901ad8d1d8c9d51f2dd83e6535b2e9fe2
|
745d39cad6b9e11506d424f008370b5dcb454c45
|
/BOJ/16000/16212.cpp
|
942f93a1f95a9765c35fa1e1c85b294da89305eb
|
[] |
no_license
|
nsj6646/PS
|
0191a36afa0c04451d704d8120dc25f336988a17
|
d53c111a053b159a0fb584ff5aafc18556c54a1c
|
refs/heads/master
| 2020-04-28T09:18:43.333045
| 2019-06-19T07:19:03
| 2019-06-19T07:19:03
| 175,162,727
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 291
|
cpp
|
#include <bits/stdc++.h>
using namespace std;
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(0);
int n;
cin>>n;
vector<int> v(n);
for(int i=0;i<n;++i){
cin>>v[i];
}
sort(v.begin(),v.end());
for(int x:v){
cout<<x<<' ';
}
return 0;
}
|
[
"nsj6646@gmail.com"
] |
nsj6646@gmail.com
|
a1df2f00efba8b1a277da7deb9fca819dda14c56
|
a1fbf16243026331187b6df903ed4f69e5e8c110
|
/cs/sdk/3d_sdk/maya/ver-8.5/devkit/ExternalWebBrowser/Windows/src/PlugIn/gecko-sdk/include/nsIDOMDocumentType.h
|
f7b4adbbe3889283e6b9416285df5e6318dc785b
|
[
"LicenseRef-scancode-warranty-disclaimer",
"BSD-2-Clause"
] |
permissive
|
OpenXRay/xray-15
|
ca0031cf1893616e0c9795c670d5d9f57ca9beff
|
1390dfb08ed20997d7e8c95147ea8e8cb71f5e86
|
refs/heads/xd_dev
| 2023-07-17T23:42:14.693841
| 2021-09-01T23:25:34
| 2021-09-01T23:25:34
| 23,224,089
| 64
| 23
|
NOASSERTION
| 2019-04-03T17:50:18
| 2014-08-22T12:09:41
|
C++
|
UTF-8
|
C++
| false
| false
| 5,534
|
h
|
/*
* DO NOT EDIT. THIS FILE IS GENERATED FROM d:/BUILDS/tinderbox/Mozilla1.7/WINNT_5.0_Clobber/mozilla/dom/public/idl/core/nsIDOMDocumentType.idl
*/
#ifndef __gen_nsIDOMDocumentType_h__
#define __gen_nsIDOMDocumentType_h__
#ifndef __gen_nsIDOMNode_h__
#include "nsIDOMNode.h"
#endif
/* For IDL files that don't want to include root IDL files. */
#ifndef NS_NO_VTABLE
#define NS_NO_VTABLE
#endif
/* starting interface: nsIDOMDocumentType */
#define NS_IDOMDOCUMENTTYPE_IID_STR "a6cf9077-15b3-11d2-932e-00805f8add32"
#define NS_IDOMDOCUMENTTYPE_IID \
{0xa6cf9077, 0x15b3, 0x11d2, \
{ 0x93, 0x2e, 0x00, 0x80, 0x5f, 0x8a, 0xdd, 0x32 }}
class NS_NO_VTABLE nsIDOMDocumentType : public nsIDOMNode {
public:
NS_DEFINE_STATIC_IID_ACCESSOR(NS_IDOMDOCUMENTTYPE_IID)
/**
* Each Document has a doctype attribute whose value is either null
* or a DocumentType object.
* The nsIDOMDocumentType interface in the DOM Core provides an
* interface to the list of entities that are defined for the document.
*
* For more information on this interface please see
* http://www.w3.org/TR/DOM-Level-2-Core/
*
* @status FROZEN
*/
/* readonly attribute DOMString name; */
NS_IMETHOD GetName(nsAString & aName) = 0;
/* readonly attribute nsIDOMNamedNodeMap entities; */
NS_IMETHOD GetEntities(nsIDOMNamedNodeMap * *aEntities) = 0;
/* readonly attribute nsIDOMNamedNodeMap notations; */
NS_IMETHOD GetNotations(nsIDOMNamedNodeMap * *aNotations) = 0;
/* readonly attribute DOMString publicId; */
NS_IMETHOD GetPublicId(nsAString & aPublicId) = 0;
/* readonly attribute DOMString systemId; */
NS_IMETHOD GetSystemId(nsAString & aSystemId) = 0;
/* readonly attribute DOMString internalSubset; */
NS_IMETHOD GetInternalSubset(nsAString & aInternalSubset) = 0;
};
/* Use this macro when declaring classes that implement this interface. */
#define NS_DECL_NSIDOMDOCUMENTTYPE \
NS_IMETHOD GetName(nsAString & aName); \
NS_IMETHOD GetEntities(nsIDOMNamedNodeMap * *aEntities); \
NS_IMETHOD GetNotations(nsIDOMNamedNodeMap * *aNotations); \
NS_IMETHOD GetPublicId(nsAString & aPublicId); \
NS_IMETHOD GetSystemId(nsAString & aSystemId); \
NS_IMETHOD GetInternalSubset(nsAString & aInternalSubset);
/* Use this macro to declare functions that forward the behavior of this interface to another object. */
#define NS_FORWARD_NSIDOMDOCUMENTTYPE(_to) \
NS_IMETHOD GetName(nsAString & aName) { return _to GetName(aName); } \
NS_IMETHOD GetEntities(nsIDOMNamedNodeMap * *aEntities) { return _to GetEntities(aEntities); } \
NS_IMETHOD GetNotations(nsIDOMNamedNodeMap * *aNotations) { return _to GetNotations(aNotations); } \
NS_IMETHOD GetPublicId(nsAString & aPublicId) { return _to GetPublicId(aPublicId); } \
NS_IMETHOD GetSystemId(nsAString & aSystemId) { return _to GetSystemId(aSystemId); } \
NS_IMETHOD GetInternalSubset(nsAString & aInternalSubset) { return _to GetInternalSubset(aInternalSubset); }
/* Use this macro to declare functions that forward the behavior of this interface to another object in a safe way. */
#define NS_FORWARD_SAFE_NSIDOMDOCUMENTTYPE(_to) \
NS_IMETHOD GetName(nsAString & aName) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetName(aName); } \
NS_IMETHOD GetEntities(nsIDOMNamedNodeMap * *aEntities) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetEntities(aEntities); } \
NS_IMETHOD GetNotations(nsIDOMNamedNodeMap * *aNotations) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetNotations(aNotations); } \
NS_IMETHOD GetPublicId(nsAString & aPublicId) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetPublicId(aPublicId); } \
NS_IMETHOD GetSystemId(nsAString & aSystemId) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetSystemId(aSystemId); } \
NS_IMETHOD GetInternalSubset(nsAString & aInternalSubset) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetInternalSubset(aInternalSubset); }
#if 0
/* Use the code below as a template for the implementation class for this interface. */
/* Header file */
class nsDOMDocumentType : public nsIDOMDocumentType
{
public:
NS_DECL_ISUPPORTS
NS_DECL_NSIDOMDOCUMENTTYPE
nsDOMDocumentType();
private:
~nsDOMDocumentType();
protected:
/* additional members */
};
/* Implementation file */
NS_IMPL_ISUPPORTS1(nsDOMDocumentType, nsIDOMDocumentType)
nsDOMDocumentType::nsDOMDocumentType()
{
/* member initializers and constructor code */
}
nsDOMDocumentType::~nsDOMDocumentType()
{
/* destructor code */
}
/* readonly attribute DOMString name; */
NS_IMETHODIMP nsDOMDocumentType::GetName(nsAString & aName)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
/* readonly attribute nsIDOMNamedNodeMap entities; */
NS_IMETHODIMP nsDOMDocumentType::GetEntities(nsIDOMNamedNodeMap * *aEntities)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
/* readonly attribute nsIDOMNamedNodeMap notations; */
NS_IMETHODIMP nsDOMDocumentType::GetNotations(nsIDOMNamedNodeMap * *aNotations)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
/* readonly attribute DOMString publicId; */
NS_IMETHODIMP nsDOMDocumentType::GetPublicId(nsAString & aPublicId)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
/* readonly attribute DOMString systemId; */
NS_IMETHODIMP nsDOMDocumentType::GetSystemId(nsAString & aSystemId)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
/* readonly attribute DOMString internalSubset; */
NS_IMETHODIMP nsDOMDocumentType::GetInternalSubset(nsAString & aInternalSubset)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
/* End of implementation class template. */
#endif
#endif /* __gen_nsIDOMDocumentType_h__ */
|
[
"paul-kv@yandex.ru"
] |
paul-kv@yandex.ru
|
2d2417d04062b5250820515da4c114d3c9013c2d
|
0f6b28bf6dfdc14808b5849455abc41ad7a79466
|
/AI/8-puzzle/firstchioce/firstChioce.cpp
|
5e5132739ab3c2a1ac1204c2ad72be7d717e1a76
|
[] |
no_license
|
warsonchou/AI
|
c18e73bff3de953e56b6eded022ae9f096d4047d
|
42fca33773e527911e4db3109722676bb809d8c1
|
refs/heads/master
| 2021-05-31T04:14:43.491229
| 2016-02-25T03:31:12
| 2016-02-25T03:31:12
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 4,339
|
cpp
|
// 使用曼哈顿距离来到度量好坏
// first choice version
#include "iostream"
#include "algorithm"
#include "stdlib.h"
#include "stdio.h"
#include "time.h"
using namespace std;
const int range = 100;
void getRandomStart(int a[3][3]) {
int i, j, num;
bool isPut[9];
memset(isPut, false, sizeof(isPut));
for (i = 0; i < 3; i++) {
for (j = 0; j < 3; j++) {
while(1) {
srand((unsigned) time(NULL));
num = rand() % 9;
if (isPut[num]) {
continue;
} else {
isPut[num] = true;
a[i][j] = num + 1;
break;
}
}
}
}
}
bool isReached(int a[3][3]) {
int i, j;
for (i = 0; i < 3; i++) {
for (j = 0; j < 3; j++) {
if (a[i][j] != i * 3 + j + 1)
break;
}
}
return (i == 3 && j == 3);
}
int getDistance(int target, int x, int y) {
int shouldX = target / 3 + 1, shouldY = target % 3;
if (shouldY == 0) {
shouldX--;
shouldY = 3;
}
return (abs(shouldX - x) + abs(shouldY - y));
}
int getH(int a[3][3]) {
int i, j, sum = 0;
for (i = 0; i < 3; i++) {
for (j = 0; j < 3; j++) {
if (a[i][j] == 9)
continue;
sum += getDistance(a[i][j], i + 1, j + 1);
}
}
return sum;
}
bool hillClimb(int a[3][3]) {
int i, j, h, loops, posxofspace, posyofspace, x[4] = {0, 0, 1, -1}, y[4] ={1, -1, 0, 0}, currentH, bestx, bestH, besty, temp;
bool direction[4];
// get the position of 9
for (i = 0; i < 3; i++) {
for (j = 0; j < 3; j++) {
if (a[i][j] == 9)
break;
}
if (a[i][j] == 9)
break;
}
posxofspace = i;
posyofspace = j;
currentH = getH(a);
bestH = currentH;
bestx = posxofspace;
besty = posyofspace;
for (loops = 0; loops < 10000; loops++) {
memset(direction, false, sizeof(direction));
int count = 0;
while(1) {
count++;
srand((unsigned) time(NULL));
i = rand() % 4;
if (posxofspace + x[i] >=0 && posxofspace + x[i] < 3 && posyofspace + y[i] < 3 && posyofspace + y[i] >= 0) {
temp = a[posxofspace][posyofspace];
a[posxofspace][posyofspace] = a[posxofspace + x[i]][posyofspace + y[i]];
a[posxofspace + x[i]][posyofspace + y[i]] = temp;
h = getH(a);
// 还原回来原来的状态
temp = a[posxofspace][posyofspace];
a[posxofspace][posyofspace] = a[posxofspace + x[i]][posyofspace + y[i]];
a[posxofspace + x[i]][posyofspace + y[i]] = temp;
if (h < bestH) {
bestx = posxofspace + x[i];
besty = posyofspace + y[i];
bestH = h;
break;
}
}
if (count == 4)
break;
}
if (isReached(a))
break;
if (bestH == currentH) {
for (int g = 0; g < range; g++) {
i = rand() % 4;
if (posxofspace + x[i] >=0 && posxofspace + x[i] < 3 && posyofspace + y[i] < 3 && posyofspace + y[i] >= 0) {
temp = a[posxofspace][posyofspace];
a[posxofspace][posyofspace] = a[posxofspace + x[i]][posyofspace + y[i]];
a[posxofspace + x[i]][posyofspace + y[i]] = temp;
h = getH(a);
if (h > currentH) {
// 还原回来原来的状态
temp = a[posxofspace][posyofspace];
a[posxofspace][posyofspace] = a[posxofspace + x[i]][posyofspace + y[i]];
a[posxofspace + x[i]][posyofspace + y[i]] = temp;
} else {
posxofspace += x[i];
posyofspace += y[i];
}
}
}
if (bestH == currentH)
return false;
} else {
currentH = bestH;
temp = a[posxofspace][posyofspace];
a[posxofspace][posyofspace] = a[bestx][besty];
a[bestx][besty] = temp;
posxofspace = bestx;
posyofspace = besty;
}
}
// cout << currentH << endl;
return isReached(a);
}
int main(int argc, char const *argv[])
{
int i, j, k, count = 0, a[3][3], test[3][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}, test1[3][3] = {{7, 2, 4}, {5, 9, 6}, {8 ,3 ,1}};
while(cin >> a[0][0]) {
// getRandomStart(a);
for (j = 0; j < 3; j++) {
for (k = 0; k < 3; k++) {
if (k == 0 && j == 0)
continue;
cin >> a[j][k];
}
}
// for (j = 0; j < 3; j++) {
// for (k = 0; k < 3; k++) {
// cout << a[j][k] << " ";
// }
// }
// cout << endl;
if (hillClimb(a)) {
count++;
}
// for (j = 0; j < 3; j++) {
// for (k = 0; k < 3; k++) {
// cout << a[j][k] << " ";
// }
// }
// cout << endl << endl;
}
cout << "FirstChioce HillClimb algorithm in solving the 8-puzzle problem:\nSolved percentage: ";
cout << ((double)count / (double)10000 * (double)100) << "%" << endl;
return 0;
}
|
[
"1129134022@qq.com"
] |
1129134022@qq.com
|
36218916249b629db40665712be2b46f6df1b321
|
6d8d760e9b1b2bebdbf1177bc52b7b0bf5319fed
|
/data/tplcache/6295c1fea5c50f198b71ab2ede809999.inc
|
943a7911fcd0fc97549c0db1b240491eb163e7df
|
[] |
no_license
|
xiaolaifeng/cms
|
eda2eda59d3a4b9159b6888d3b5b56994d626c26
|
17308ad59ba0c85b1757d633c48d36059ab7a615
|
refs/heads/master
| 2016-09-11T02:07:01.120174
| 2015-01-02T04:46:17
| 2015-01-02T04:46:17
| 25,720,169
| 1
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 693
|
inc
|
{dede:pagestyle maxwidth='800' pagepicnum='12' ddmaxwidth='200' row='3' col='4' value='3'/}
{dede:img ddimg='/uploads/allimg/141007/1-14100G54010-lp.png' text='' width='320' height='568'} /uploads/allimg/141007/1-14100G54010.png {/dede:img}
{dede:img ddimg='/uploads/allimg/141007/1-14100G54014-lp.png' text='' width='320' height='568'} /uploads/allimg/141007/1-14100G54014.png {/dede:img}
{dede:img ddimg='/uploads/allimg/141007/1-14100G54016-lp.png' text='' width='320' height='568'} /uploads/allimg/141007/1-14100G54016.png {/dede:img}
{dede:img ddimg='/uploads/allimg/141007/1-14100G54020-lp.png' text='' width='320' height='568'} /uploads/allimg/141007/1-14100G54020.png {/dede:img}
|
[
"xiaofeng_hero@163.com"
] |
xiaofeng_hero@163.com
|
e3f25b525e9909e48bd122e105bdb81ea1531f02
|
ce4a3f0f6fad075b6bd2fe7d84fd9b76b9622394
|
/CTRTextureGouraudAdd.cpp
|
34303a450deccf92ff7a79ce99d1de6eaa1168cb
|
[] |
no_license
|
codetiger/IrrNacl
|
c630187dfca857c15ebfa3b73fd271ef6bad310f
|
dd0bda2fb1c2ff46813fac5e11190dc87f83add7
|
refs/heads/master
| 2021-01-13T02:10:24.919588
| 2012-07-22T06:27:29
| 2012-07-22T06:27:29
| 4,461,459
| 5
| 2
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 12,730
|
cpp
|
// Copyright (C) 2002-2011 Nikolaus Gebhardt
// This file is part of the "Irrlicht Engine".
// For conditions of distribution and use, see copyright notice in irrlicht.h
#include "IrrCompileConfig.h"
#include "CTRTextureGouraud.h"
#ifdef _IRR_COMPILE_WITH_SOFTWARE_
namespace irr
{
namespace video
{
class CTRTextureGouraudAdd : public CTRTextureGouraud
{
public:
//! constructor
CTRTextureGouraudAdd(IZBuffer* zbuffer);
//! draws an indexed triangle list
virtual void drawIndexedTriangleList(S2DVertex* vertices, s32 vertexCount, const u16* indexList, s32 triangleCount);
protected:
};
//! constructor
CTRTextureGouraudAdd::CTRTextureGouraudAdd(IZBuffer* zbuffer)
: CTRTextureGouraud(zbuffer)
{
#ifdef _DEBUG
setDebugName("CTRTextureGouraudAdd");
#endif
}
//! draws an indexed triangle list
void CTRTextureGouraudAdd::drawIndexedTriangleList(S2DVertex* vertices, s32 vertexCount, const u16* indexList, s32 triangleCount)
{
const S2DVertex *v1, *v2, *v3;
u16 color;
f32 tmpDiv; // temporary division factor
f32 longest; // saves the longest span
s32 height; // saves height of triangle
u16* targetSurface; // target pointer where to plot pixels
s32 spanEnd; // saves end of spans
f32 leftdeltaxf; // amount of pixels to increase on left side of triangle
f32 rightdeltaxf; // amount of pixels to increase on right side of triangle
s32 leftx, rightx; // position where we are
f32 leftxf, rightxf; // same as above, but as f32 values
s32 span; // current span
u16 *hSpanBegin, *hSpanEnd; // pointer used when plotting pixels
s32 leftR, leftG, leftB, rightR, rightG, rightB; // color values
s32 leftStepR, leftStepG, leftStepB,
rightStepR, rightStepG, rightStepB; // color steps
s32 spanR, spanG, spanB, spanStepR, spanStepG, spanStepB; // color interpolating values while drawing a span.
s32 leftTx, rightTx, leftTy, rightTy; // texture interpolating values
s32 leftTxStep, rightTxStep, leftTyStep, rightTyStep; // texture interpolating values
s32 spanTx, spanTy, spanTxStep, spanTyStep; // values of Texturecoords when drawing a span
core::rect<s32> TriangleRect;
s32 leftZValue, rightZValue;
s32 leftZStep, rightZStep;
s32 spanZValue, spanZStep; // ZValues when drawing a span
TZBufferType* zTarget, *spanZTarget; // target of ZBuffer;
lockedSurface = (u16*)RenderTarget->lock();
lockedZBuffer = ZBuffer->lock();
lockedTexture = (u16*)Texture->lock();
for (s32 i=0; i<triangleCount; ++i)
{
v1 = &vertices[*indexList];
++indexList;
v2 = &vertices[*indexList];
++indexList;
v3 = &vertices[*indexList];
++indexList;
// back face culling
if (BackFaceCullingEnabled)
{
s32 z = ((v3->Pos.X - v1->Pos.X) * (v3->Pos.Y - v2->Pos.Y)) -
((v3->Pos.Y - v1->Pos.Y) * (v3->Pos.X - v2->Pos.X));
if (z < 0)
continue;
}
//near plane clipping
if (v1->ZValue<0 && v2->ZValue<0 && v3->ZValue<0)
continue;
// sort for width for inscreen clipping
if (v1->Pos.X > v2->Pos.X) swapVertices(&v1, &v2);
if (v1->Pos.X > v3->Pos.X) swapVertices(&v1, &v3);
if (v2->Pos.X > v3->Pos.X) swapVertices(&v2, &v3);
if ((v1->Pos.X - v3->Pos.X) == 0)
continue;
TriangleRect.UpperLeftCorner.X = v1->Pos.X;
TriangleRect.LowerRightCorner.X = v3->Pos.X;
// sort for height for faster drawing.
if (v1->Pos.Y > v2->Pos.Y) swapVertices(&v1, &v2);
if (v1->Pos.Y > v3->Pos.Y) swapVertices(&v1, &v3);
if (v2->Pos.Y > v3->Pos.Y) swapVertices(&v2, &v3);
TriangleRect.UpperLeftCorner.Y = v1->Pos.Y;
TriangleRect.LowerRightCorner.Y = v3->Pos.Y;
if (!TriangleRect.isRectCollided(ViewPortRect))
continue;
// calculate height of triangle
height = v3->Pos.Y - v1->Pos.Y;
if (!height)
continue;
// calculate longest span
longest = (v2->Pos.Y - v1->Pos.Y) / (f32)height * (v3->Pos.X - v1->Pos.X) + (v1->Pos.X - v2->Pos.X);
spanEnd = v2->Pos.Y;
span = v1->Pos.Y;
leftxf = (f32)v1->Pos.X;
rightxf = (f32)v1->Pos.X;
leftZValue = v1->ZValue;
rightZValue = v1->ZValue;
leftR = rightR = video::getRed(v1->Color)<<8;
leftG = rightG = video::getGreen(v1->Color)<<8;
leftB = rightB = video::getBlue(v1->Color)<<8;
leftTx = rightTx = v1->TCoords.X;
leftTy = rightTy = v1->TCoords.Y;
targetSurface = lockedSurface + span * SurfaceWidth;
zTarget = lockedZBuffer + span * SurfaceWidth;
if (longest < 0.0f)
{
tmpDiv = 1.0f / (f32)(v2->Pos.Y - v1->Pos.Y);
rightdeltaxf = (v2->Pos.X - v1->Pos.X) * tmpDiv;
rightZStep = (s32)((v2->ZValue - v1->ZValue) * tmpDiv);
rightStepR = (s32)(((s32)(video::getRed(v2->Color)<<8) - rightR) * tmpDiv);
rightStepG = (s32)(((s32)(video::getGreen(v2->Color)<<8) - rightG) * tmpDiv);
rightStepB = (s32)(((s32)(video::getBlue(v2->Color)<<8) - rightB) * tmpDiv);
rightTxStep = (s32)((v2->TCoords.X - rightTx) * tmpDiv);
rightTyStep = (s32)((v2->TCoords.Y - rightTy) * tmpDiv);
tmpDiv = 1.0f / (f32)height;
leftdeltaxf = (v3->Pos.X - v1->Pos.X) * tmpDiv;
leftZStep = (s32)((v3->ZValue - v1->ZValue) * tmpDiv);
leftStepR = (s32)(((s32)(video::getRed(v3->Color)<<8) - leftR) * tmpDiv);
leftStepG = (s32)(((s32)(video::getGreen(v3->Color)<<8) - leftG) * tmpDiv);
leftStepB = (s32)(((s32)(video::getBlue(v3->Color)<<8) - leftB) * tmpDiv);
leftTxStep = (s32)((v3->TCoords.X - leftTx) * tmpDiv);
leftTyStep = (s32)((v3->TCoords.Y - leftTy) * tmpDiv);
}
else
{
tmpDiv = 1.0f / (f32)height;
rightdeltaxf = (v3->Pos.X - v1->Pos.X) * tmpDiv;
rightZStep = (s32)((v3->ZValue - v1->ZValue) * tmpDiv);
rightStepR = (s32)(((s32)(video::getRed(v3->Color)<<8) - rightR) * tmpDiv);
rightStepG = (s32)(((s32)(video::getGreen(v3->Color)<<8) - rightG) * tmpDiv);
rightStepB = (s32)(((s32)(video::getBlue(v3->Color)<<8) - rightB) * tmpDiv);
rightTxStep = (s32)((v3->TCoords.X - rightTx) * tmpDiv);
rightTyStep = (s32)((v3->TCoords.Y - rightTy) * tmpDiv);
tmpDiv = 1.0f / (f32)(v2->Pos.Y - v1->Pos.Y);
leftdeltaxf = (v2->Pos.X - v1->Pos.X) * tmpDiv;
leftZStep = (s32)((v2->ZValue - v1->ZValue) * tmpDiv);
leftStepR = (s32)(((s32)(video::getRed(v2->Color)<<8) - leftR) * tmpDiv);
leftStepG = (s32)(((s32)(video::getGreen(v2->Color)<<8) - leftG) * tmpDiv);
leftStepB = (s32)(((s32)(video::getBlue(v2->Color)<<8) - leftB) * tmpDiv);
leftTxStep = (s32)((v2->TCoords.X - leftTx) * tmpDiv);
leftTyStep = (s32)((v2->TCoords.Y - leftTy) * tmpDiv);
}
// do it twice, once for the first half of the triangle,
// end then for the second half.
for (s32 triangleHalf=0; triangleHalf<2; ++triangleHalf)
{
if (spanEnd > ViewPortRect.LowerRightCorner.Y)
spanEnd = ViewPortRect.LowerRightCorner.Y;
// if the span <0, than we can skip these spans,
// and proceed to the next spans which are really on the screen.
if (span < ViewPortRect.UpperLeftCorner.Y)
{
// we'll use leftx as temp variable
if (spanEnd < ViewPortRect.UpperLeftCorner.Y)
{
leftx = spanEnd - span;
span = spanEnd;
}
else
{
leftx = ViewPortRect.UpperLeftCorner.Y - span;
span = ViewPortRect.UpperLeftCorner.Y;
}
leftxf += leftdeltaxf*leftx;
rightxf += rightdeltaxf*leftx;
targetSurface += SurfaceWidth*leftx;
zTarget += SurfaceWidth*leftx;
leftZValue += leftZStep*leftx;
rightZValue += rightZStep*leftx;
leftR += leftStepR*leftx;
leftG += leftStepG*leftx;
leftB += leftStepB*leftx;
rightR += rightStepR*leftx;
rightG += rightStepG*leftx;
rightB += rightStepB*leftx;
leftTx += leftTxStep*leftx;
leftTy += leftTyStep*leftx;
rightTx += rightTxStep*leftx;
rightTy += rightTyStep*leftx;
}
// the main loop. Go through every span and draw it.
while (span < spanEnd)
{
leftx = (s32)(leftxf);
rightx = (s32)(rightxf + 0.5f);
// perform some clipping
// thanks to a correction by hybrid
// calculations delayed to correctly propagate to textures etc.
s32 tDiffLeft=0, tDiffRight=0;
if (leftx<ViewPortRect.UpperLeftCorner.X)
tDiffLeft=ViewPortRect.UpperLeftCorner.X-leftx;
else
if (leftx>ViewPortRect.LowerRightCorner.X)
tDiffLeft=ViewPortRect.LowerRightCorner.X-leftx;
if (rightx<ViewPortRect.UpperLeftCorner.X)
tDiffRight=ViewPortRect.UpperLeftCorner.X-rightx;
else
if (rightx>ViewPortRect.LowerRightCorner.X)
tDiffRight=ViewPortRect.LowerRightCorner.X-rightx;
// draw the span
if (rightx + tDiffRight - leftx - tDiffLeft)
{
tmpDiv = 1.0f / (f32)(rightx - leftx);
spanZStep = (s32)((rightZValue - leftZValue) * tmpDiv);
spanZValue = leftZValue+tDiffLeft*spanZStep;
spanStepR = (s32)((rightR - leftR) * tmpDiv);
spanR = leftR+tDiffLeft*spanStepR;
spanStepG = (s32)((rightG - leftG) * tmpDiv);
spanG = leftG+tDiffLeft*spanStepG;
spanStepB = (s32)((rightB - leftB) * tmpDiv);
spanB = leftB+tDiffLeft*spanStepB;
spanTxStep = (s32)((rightTx - leftTx) * tmpDiv);
spanTx = leftTx + tDiffLeft*spanTxStep;
spanTyStep = (s32)((rightTy - leftTy) * tmpDiv);
spanTy = leftTy+tDiffLeft*spanTyStep;
hSpanBegin = targetSurface + leftx+tDiffLeft;
spanZTarget = zTarget + leftx+tDiffLeft;
hSpanEnd = targetSurface + rightx+tDiffRight;
while (hSpanBegin < hSpanEnd)
{
if (spanZValue > *spanZTarget)
{
//*spanZTarget = spanZValue;
color = lockedTexture[((spanTy>>8)&textureYMask) * lockedTextureWidth + ((spanTx>>8)&textureXMask)];
s32 basis = *hSpanBegin;
s32 r = (video::getRed(basis)<<3) + (video::getRed(color)<<3);
if (r > 255) r = 255;
s32 g = (video::getGreen(basis)<<3) + (video::getGreen(color)<<3);
if (g > 255) g = 255;
s32 b = (video::getBlue(basis)<<3) + (video::getBlue(color)<<3);
if (b > 255) b = 255;
*hSpanBegin = video::RGB16(r, g, b);
}
spanR += spanStepR;
spanG += spanStepG;
spanB += spanStepB;
spanTx += spanTxStep;
spanTy += spanTyStep;
spanZValue += spanZStep;
++hSpanBegin;
++spanZTarget;
}
}
leftxf += leftdeltaxf;
rightxf += rightdeltaxf;
++span;
targetSurface += SurfaceWidth;
zTarget += SurfaceWidth;
leftZValue += leftZStep;
rightZValue += rightZStep;
leftR += leftStepR;
leftG += leftStepG;
leftB += leftStepB;
rightR += rightStepR;
rightG += rightStepG;
rightB += rightStepB;
leftTx += leftTxStep;
leftTy += leftTyStep;
rightTx += rightTxStep;
rightTy += rightTyStep;
}
if (triangleHalf>0) // break, we've gout only two halves
break;
// setup variables for second half of the triangle.
if (longest < 0.0f)
{
tmpDiv = 1.0f / (v3->Pos.Y - v2->Pos.Y);
rightdeltaxf = (v3->Pos.X - v2->Pos.X) * tmpDiv;
rightxf = (f32)v2->Pos.X;
rightZValue = v2->ZValue;
rightZStep = (s32)((v3->ZValue - v2->ZValue) * tmpDiv);
rightR = video::getRed(v2->Color)<<8;
rightG = video::getGreen(v2->Color)<<8;
rightB = video::getBlue(v2->Color)<<8;
rightStepR = (s32)(((s32)(video::getRed(v3->Color)<<8) - rightR) * tmpDiv);
rightStepG = (s32)(((s32)(video::getGreen(v3->Color)<<8) - rightG) * tmpDiv);
rightStepB = (s32)(((s32)(video::getBlue(v3->Color)<<8) - rightB) * tmpDiv);
rightTx = v2->TCoords.X;
rightTy = v2->TCoords.Y;
rightTxStep = (s32)((v3->TCoords.X - rightTx) * tmpDiv);
rightTyStep = (s32)((v3->TCoords.Y - rightTy) * tmpDiv);
}
else
{
tmpDiv = 1.0f / (v3->Pos.Y - v2->Pos.Y);
leftdeltaxf = (v3->Pos.X - v2->Pos.X) * tmpDiv;
leftxf = (f32)v2->Pos.X;
leftZValue = v2->ZValue;
leftZStep = (s32)((v3->ZValue - v2->ZValue) * tmpDiv);
leftR = video::getRed(v2->Color)<<8;
leftG = video::getGreen(v2->Color)<<8;
leftB = video::getBlue(v2->Color)<<8;
leftStepR = (s32)(((s32)(video::getRed(v3->Color)<<8) - leftR) * tmpDiv);
leftStepG = (s32)(((s32)(video::getGreen(v3->Color)<<8) - leftG) * tmpDiv);
leftStepB = (s32)(((s32)(video::getBlue(v3->Color)<<8) - leftB) * tmpDiv);
leftTx = v2->TCoords.X;
leftTy = v2->TCoords.Y;
leftTxStep = (s32)((v3->TCoords.X - leftTx) * tmpDiv);
leftTyStep = (s32)((v3->TCoords.Y - leftTy) * tmpDiv);
}
spanEnd = v3->Pos.Y;
}
}
RenderTarget->unlock();
ZBuffer->unlock();
Texture->unlock();
}
} // end namespace video
} // end namespace irr
#endif // _IRR_COMPILE_WITH_SOFTWARE_
namespace irr
{
namespace video
{
ITriangleRenderer* createTriangleRendererTextureGouraudAdd(IZBuffer* zbuffer)
{
#ifdef _IRR_COMPILE_WITH_SOFTWARE_
return new CTRTextureGouraudAdd(zbuffer);
#else
return 0;
#endif // _IRR_COMPILE_WITH_SOFTWARE_
}
} // end namespace video
} // end namespace irr
|
[
"smackallgames@smackall-2bbd93.(none)"
] |
smackallgames@smackall-2bbd93.(none)
|
122c26ad61b675ac7a70687447a2c90b0a067f85
|
19eb97436a3be9642517ea9c4095fe337fd58a00
|
/private/shell/ext/mydocs/src/viewcb.h
|
9b16d1c997fd3360d81d407b2cded1de7e65ffb7
|
[] |
no_license
|
oturan-boga/Windows2000
|
7d258fd0f42a225c2be72f2b762d799bd488de58
|
8b449d6659840b6ba19465100d21ca07a0e07236
|
refs/heads/main
| 2023-04-09T23:13:21.992398
| 2021-04-22T11:46:21
| 2021-04-22T11:46:21
| 360,495,781
| 2
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 898
|
h
|
#ifndef __viewcb_h
#define __viewcb_h
/*-----------------------------------------------------------------------------
/ CMyDocsViewCB
/----------------------------------------------------------------------------*/
class CMyDocsViewCB : public IShellFolderViewCB, CUnknown
{
private:
IShellFolderView * m_psfv;
IShellFolderViewCB * m_psfvcb;
LPITEMIDLIST m_pidlReal;
public:
CMyDocsViewCB(IShellFolderView * psfv, LPITEMIDLIST pidl);
~CMyDocsViewCB();
STDMETHOD(SetRealCB)(IShellFolderViewCB * psfvcb);
// IUnknown
STDMETHOD(QueryInterface)(REFIID riid, LPVOID* ppvObject);
STDMETHOD_(ULONG, AddRef)();
STDMETHOD_(ULONG, Release)();
// IShellFolderViewCB
STDMETHOD(MessageSFVCB)(UINT uMsg, WPARAM wParam, LPARAM lParam);
};
#endif
|
[
"mehmetyilmaz3371@gmail.com"
] |
mehmetyilmaz3371@gmail.com
|
1ee76788bf6a3a28eceb229f676eded53643e4ca
|
95c367e58a79fd5a933dc0a2043adadccec5630c
|
/External/boost_1_63_0/boost/spirit/home/lex/lexer/lexertl/functor.hpp
|
260e4dcc507a66548d94c2f6acc1dc7dbad237cb
|
[
"BSL-1.0"
] |
permissive
|
fl4re/COLLADAMobu
|
cf06fa2462d6655407ebc0502a6f25c7274dee84
|
4a81bec2b1d98b23311f13255fd9182c570a9b3d
|
refs/heads/master
| 2020-05-24T02:34:55.534671
| 2017-04-12T16:06:28
| 2017-04-12T16:06:28
| 84,808,624
| 0
| 0
| null | 2017-04-12T22:13:17
| 2017-03-13T09:35:38
|
C++
|
UTF-8
|
C++
| false
| false
| 11,900
|
hpp
|
// Copyright (c) 2001-2011 Hartmut Kaiser
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#if !defined(BOOST_SPIRIT_LEX_LEXER_FUNCTOR_NOV_18_2007_1112PM)
#define BOOST_SPIRIT_LEX_LEXER_FUNCTOR_NOV_18_2007_1112PM
#if defined(_MSC_VER)
#pragma once
#endif
#include <boost/mpl/bool.hpp>
#include <boost/detail/iterator.hpp>
#include <boost/detail/workaround.hpp>
#include <boost/spirit/home/lex/lexer/pass_flags.hpp>
#include <boost/assert.hpp>
#if 0 != __COMO_VERSION__ || !BOOST_WORKAROUND(BOOST_MSVC, <= 1310)
#define BOOST_SPIRIT_STATIC_EOF 1
#define BOOST_SPIRIT_EOF_PREFIX static
#else
#define BOOST_SPIRIT_EOF_PREFIX
#endif
namespace boost { namespace spirit { namespace lex { namespace lexertl
{
///////////////////////////////////////////////////////////////////////////
//
// functor is a template usable as the functor object for the
// multi_pass iterator allowing to wrap a lexertl based dfa into a
// iterator based interface.
//
// Token: the type of the tokens produced by this functor
// this needs to expose a constructor with the following
// prototype:
//
// Token(std::size_t id, std::size_t state,
// Iterator start, Iterator end)
//
// where 'id' is the token id, state is the lexer state,
// this token has been matched in, and 'first' and 'end'
// mark the start and the end of the token with respect
// to the underlying character stream.
// FunctorData:
// this is expected to encapsulate the shared part of the
// functor (see lex/lexer/lexertl/functor_data.hpp for an
// example and documentation).
// Iterator: the type of the underlying iterator
// SupportsActors:
// this is expected to be a mpl::bool_, if mpl::true_ the
// functor invokes functors which (optionally) have
// been attached to the token definitions.
// SupportState:
// this is expected to be a mpl::bool_, if mpl::true_ the
// functor supports different lexer states,
// otherwise no lexer state is supported.
//
///////////////////////////////////////////////////////////////////////////
template <typename Token
, template <typename, typename, typename, typename> class FunctorData
, typename Iterator = typename Token::iterator_type
, typename SupportsActors = mpl::false_
, typename SupportsState = typename Token::has_state>
class functor
{
public:
typedef typename
boost::detail::iterator_traits<Iterator>::value_type
char_type;
private:
// Needed by compilers not implementing the resolution to DR45. For
// reference, see
// http://www.open-std.org/JTC1/SC22/WG21/docs/cwg_defects.html#45.
typedef typename Token::token_value_type token_value_type;
friend class FunctorData<Iterator, SupportsActors, SupportsState
, token_value_type>;
// Helper template allowing to assign a value on exit
template <typename T>
struct assign_on_exit
{
assign_on_exit(T& dst, T const& src)
: dst_(dst), src_(src) {}
~assign_on_exit()
{
dst_ = src_;
}
T& dst_;
T const& src_;
private:
// silence MSVC warning C4512: assignment operator could not be generated
assign_on_exit& operator= (assign_on_exit const&);
};
public:
functor()
#if defined(__PGI)
: eof()
#endif
{}
#if BOOST_WORKAROUND(BOOST_MSVC, <= 1310)
// somehow VC7.1 needs this (meaningless) assignment operator
functor& operator=(functor const& rhs)
{
return *this;
}
#endif
///////////////////////////////////////////////////////////////////////
// interface to the iterator_policies::split_functor_input policy
typedef Token result_type;
typedef functor unique;
typedef FunctorData<Iterator, SupportsActors, SupportsState
, token_value_type> shared;
BOOST_SPIRIT_EOF_PREFIX result_type const eof;
///////////////////////////////////////////////////////////////////////
typedef Iterator iterator_type;
typedef typename shared::semantic_actions_type semantic_actions_type;
typedef typename shared::next_token_functor next_token_functor;
typedef typename shared::get_state_name_type get_state_name_type;
// this is needed to wrap the semantic actions in a proper way
typedef typename shared::wrap_action_type wrap_action_type;
///////////////////////////////////////////////////////////////////////
template <typename MultiPass>
static result_type& get_next(MultiPass& mp, result_type& result)
{
typedef typename result_type::id_type id_type;
shared& data = mp.shared()->ftor;
for(;;)
{
if (data.get_first() == data.get_last())
#if defined(BOOST_SPIRIT_STATIC_EOF)
return result = eof;
#else
return result = mp.ftor.eof;
#endif
data.reset_value();
Iterator end = data.get_first();
std::size_t unique_id = boost::lexer::npos;
bool prev_bol = false;
// lexer matching might change state
std::size_t state = data.get_state();
std::size_t id = data.next(end, unique_id, prev_bol);
if (boost::lexer::npos == id) { // no match
#if defined(BOOST_SPIRIT_LEXERTL_DEBUG)
std::string next;
Iterator it = data.get_first();
for (std::size_t i = 0; i < 10 && it != data.get_last(); ++it, ++i)
next += *it;
std::cerr << "Not matched, in state: " << state
<< ", lookahead: >" << next << "<" << std::endl;
#endif
return result = result_type(0);
}
else if (0 == id) { // EOF reached
#if defined(BOOST_SPIRIT_STATIC_EOF)
return result = eof;
#else
return result = mp.ftor.eof;
#endif
}
#if defined(BOOST_SPIRIT_LEXERTL_DEBUG)
{
std::string next;
Iterator it = end;
for (std::size_t i = 0; i < 10 && it != data.get_last(); ++it, ++i)
next += *it;
std::cerr << "Matched: " << id << ", in state: "
<< state << ", string: >"
<< std::basic_string<char_type>(data.get_first(), end) << "<"
<< ", lookahead: >" << next << "<" << std::endl;
if (data.get_state() != state) {
std::cerr << "Switched to state: "
<< data.get_state() << std::endl;
}
}
#endif
// account for a possibly pending lex::more(), i.e. moving
// data.first_ back to the start of the previously matched token.
bool adjusted = data.adjust_start();
// set the end of the matched input sequence in the token data
data.set_end(end);
// invoke attached semantic actions, if defined, might change
// state, id, data.first_, and/or end
BOOST_SCOPED_ENUM(pass_flags) pass =
data.invoke_actions(state, id, unique_id, end);
if (data.has_value()) {
// return matched token using the token value as set before
// using data.set_value(), advancing 'data.first_' past the
// matched sequence
assign_on_exit<Iterator> on_exit(data.get_first(), end);
return result = result_type(id_type(id), state, data.get_value());
}
else if (pass_flags::pass_normal == pass) {
// return matched token, advancing 'data.first_' past the
// matched sequence
assign_on_exit<Iterator> on_exit(data.get_first(), end);
return result = result_type(id_type(id), state, data.get_first(), end);
}
else if (pass_flags::pass_fail == pass) {
#if defined(BOOST_SPIRIT_LEXERTL_DEBUG)
std::cerr << "Matching forced to fail" << std::endl;
#endif
// if the data.first_ got adjusted above, revert this adjustment
if (adjusted)
data.revert_adjust_start();
// one of the semantic actions signaled no-match
data.reset_bol(prev_bol);
if (state != data.get_state())
continue; // retry matching if state has changed
// if the state is unchanged repeating the match wouldn't
// move the input forward, causing an infinite loop
return result = result_type(0);
}
#if defined(BOOST_SPIRIT_LEXERTL_DEBUG)
std::cerr << "Token ignored, continuing matching" << std::endl;
#endif
// if this token needs to be ignored, just repeat the matching,
// while starting right after the current match
data.get_first() = end;
}
}
// set_state are propagated up to the iterator interface, allowing to
// manipulate the current lexer state through any of the exposed
// iterators.
template <typename MultiPass>
static std::size_t set_state(MultiPass& mp, std::size_t state)
{
std::size_t oldstate = mp.shared()->ftor.get_state();
mp.shared()->ftor.set_state(state);
#if defined(BOOST_SPIRIT_LEXERTL_DEBUG)
std::cerr << "Switching state from: " << oldstate
<< " to: " << state
<< std::endl;
#endif
return oldstate;
}
template <typename MultiPass>
static std::size_t get_state(MultiPass& mp)
{
return mp.shared()->ftor.get_state();
}
template <typename MultiPass>
static std::size_t
map_state(MultiPass const& mp, char_type const* statename)
{
return mp.shared()->ftor.get_state_id(statename);
}
// we don't need this, but it must be there
template <typename MultiPass>
static void destroy(MultiPass const&) {}
};
#if defined(BOOST_SPIRIT_STATIC_EOF)
///////////////////////////////////////////////////////////////////////////
// eof token
///////////////////////////////////////////////////////////////////////////
template <typename Token
, template <typename, typename, typename, typename> class FunctorData
, typename Iterator, typename SupportsActors, typename SupportsState>
typename functor<Token, FunctorData, Iterator, SupportsActors, SupportsState>::result_type const
functor<Token, FunctorData, Iterator, SupportsActors, SupportsState>::eof =
typename functor<Token, FunctorData, Iterator, SupportsActors
, SupportsState>::result_type();
#endif
}}}}
#undef BOOST_SPIRIT_EOF_PREFIX
#undef BOOST_SPIRIT_STATIC_EOF
#endif
|
[
"franck.ohayon@starbreeze.com"
] |
franck.ohayon@starbreeze.com
|
4c8a716bfba9cc8e25b3041c6201fa18e90e6596
|
ea12fed4c32e9c7992956419eb3e2bace91f063a
|
/zombie/code/exporter/3dsplugin/src/n3dsmaterial/nabstractpropbuilder.cc
|
2bee889a35355417bed7fdde40b22ce9b3110114
|
[] |
no_license
|
ugozapad/TheZombieEngine
|
832492930df28c28cd349673f79f3609b1fe7190
|
8e8c3e6225c2ed93e07287356def9fbdeacf3d6a
|
refs/heads/master
| 2020-04-30T11:35:36.258363
| 2011-02-24T14:18:43
| 2011-02-24T14:18:43
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 12,605
|
cc
|
#include "precompiled/pchn3dsmaxexport.h"
#pragma warning( push, 3 )
#include "Max.h"
#pragma warning( pop )
#include "n3dsmaterial/nabstractpropbuilder.h"
#include "kernel/nkernelserver.h"
#include "nscene/nscenenode.h"
#include "nmaterial/nmaterialnode.h"
nClass* nAbstractPropBuilder::nmaterialnode = 0;
nClass* nAbstractPropBuilder::nsurfacenode = 0;
nAbstractPropBuilder::nAbstractPropBuilder() :
thisType(nAbstractPropBuilder::NONE),
stringValid(false),
matTypeIsValid(false)
{
n_assert(nKernelServer::ks);
nmaterialnode = nKernelServer::ks->FindClass("nmaterialnode");
n_assert(nmaterialnode);
nsurfacenode = nKernelServer::ks->FindClass("nsurfacenode");
n_assert(nsurfacenode);
}
int
__cdecl
nAbstractPropBuilder::TextureSorter(const varTexture* elm0, const varTexture* elm1)
{
return strcmp(elm0->varName.Get(), elm1->varName.Get() );
}
int
__cdecl
nAbstractPropBuilder::AnimSorter( const nString* elm0, const nString* elm1)
{
n_assert(elm0);
n_assert(elm1);
return strcmp( elm0->Get(), elm1->Get() );
}
int
__cdecl
nAbstractPropBuilder::FloatSorter(const varFloat* elm0, const varFloat* elm1)
{
return strcmp(elm0->varName.Get(), elm1->varName.Get() );
}
int
__cdecl
nAbstractPropBuilder::IntSorter(const varInt* elm0, const varInt* elm1)
{
return strcmp(elm0->varName.Get(), elm1->varName.Get() );
}
int
__cdecl
nAbstractPropBuilder::VectorSorter(const varVector* elm0, const varVector* elm1)
{
return strcmp(elm0->varName.Get(), elm1->varName.Get() );
}
int
__cdecl
nAbstractPropBuilder::ShaderSorter(const varShader* elm0, const varShader* elm1)
{
return strcmp(elm0->varName.Get(), elm1->varName.Get() );
}
void
nAbstractPropBuilder::SetTexture ( const varTexture& var)
{
this->stringValid = false;
varTexture var2(var);
var2.texName.ToLower();
this->textures.Append ( var );
}
const nAbstractPropBuilder::nSortedTextures&
nAbstractPropBuilder::GetTextureArray() const
{
return this->textures;
}
nAbstractPropBuilder::nSortedTextures&
nAbstractPropBuilder::GetTextureArray()
{
return this->textures;
}
void
nAbstractPropBuilder::SetInt ( const varInt& var)
{
this->stringValid = false;
this->integers.Append( var );
}
void
nAbstractPropBuilder::SetFloat ( const varFloat& var)
{
this->stringValid = false;
this->floats.Append( var );
}
void
nAbstractPropBuilder::SetVector ( const varVector& var)
{
this->stringValid = false;
this->vectors.Append( var );
}
void
nAbstractPropBuilder::SetAnim ( const nString& pathAnim)
{
this->stringValid = false;
this->anims.Append(pathAnim);
}
void
nAbstractPropBuilder::SetShader ( const varShader& var)
{
n_assert( this->thisType == NONE || this->thisType == NSURFACE);
this->stringValid = false;
this->thisType = NSURFACE;
this->shaders.Append( var );
}
void
nAbstractPropBuilder::SetMaterial( const nMatTypePropBuilder& val)
{
n_assert( this->thisType == NONE || this->thisType == NMATERIAL );
this->stringValid = false;
this->thisType = NMATERIAL;
this->matType = val;
this->matTypeIsValid = true;
}
//------------------------------------------------------------------------------
/**
Set type Libaray.
@parama val. The original material type for future conversion
*/
void
nAbstractPropBuilder::SetMatType( const nMatTypePropBuilder& val)
{
n_assert( this->thisType == NONE || this->thisType == NMATERIAL || this->thisType == SHADERTYPELIBRARY );
this->stringValid = false;
this->matType = val;
this->matTypeIsValid = true;
}
//------------------------------------------------------------------------------
/**
Set type Libaray.
@param name The name's material in Library
@parama val. The original material type for future conversion
*/
void
nAbstractPropBuilder::SetMaterialTypeFromLibrary( const char* name , const nMatTypePropBuilder& val)
{
n_assert( this->thisType == NONE || this->thisType == SHADERTYPELIBRARY );
this->stringValid = false;
this->thisType = SHADERTYPELIBRARY;
this->matType = val;
this->matTypeIsValid = true;
this->materialTypeNameInLibrary = name;
}
//------------------------------------------------------------------------------
/**
Set type Libaray.
@param name The name's material in Library
@parama val. The original material type for future conversion
*/
void
nAbstractPropBuilder::SetMaterialTypeFromLibrary( const char* name)
{
n_assert( this->thisType == NONE || this->thisType == SHADERTYPELIBRARY );
this->stringValid = false;
this->thisType = SHADERTYPELIBRARY;
this->materialTypeNameInLibrary = name;
}
//------------------------------------------------------------------------------
/**
*/
const char*
nAbstractPropBuilder::GetMaterialTypeName() const
{
return this->materialTypeNameInLibrary.Get();
}
//------------------------------------------------------------------------------
/**
*/
bool
nAbstractPropBuilder::IsInvalidShader() const
{
n_assert ( this->thisType == SHADERTYPELIBRARY );
return (this->materialTypeNameInLibrary.IsEmpty()) || (this->materialTypeNameInLibrary == "invalid" );
}
//------------------------------------------------------------------------------
/**
*/
bool
nAbstractPropBuilder::IsCustomShader() const
{
return (this->materialTypeNameInLibrary == "custom" );
}
const char*
nAbstractPropBuilder::GetUniqueString()
{
int idx;
if (! this->stringValid )
{
char buf[255];
stringKey="";
switch (thisType)
{
case NONE:
stringKey+="NONE#";
break;
case NMATERIAL:
stringKey+="NMATERIAL#";//+material+"/";
if (this->matTypeIsValid)
{
stringKey += this->matType.GetUniqueString();
stringKey +="/";
}
break;
case NSURFACE:
stringKey+="NSURFACE#";
for (idx = 0; idx < shaders.Size() ; idx ++)
{
varShader& shader = shaders[idx];
stringKey+= shader.varName + "." + shader.val+"/";
}
break;
case SHADERTYPELIBRARY:
stringKey+="SHADERLIBRARY#";
stringKey+=this->materialTypeNameInLibrary;
// If the material is custom get the matType properties
if (this->matTypeIsValid && (this->IsInvalidShader() || this->IsCustomShader() ) )
{
stringKey += this->matType.GetUniqueString();
stringKey +="/";
}
}
stringKey+="TEX#";
for (idx=0; idx < textures.Size() ; idx++)
{
varTexture& texture = textures[idx];
stringKey += texture.varName +"." + texture.texName + "/";
}
stringKey+="INT#";
for ( idx=0; idx < integers.Size(); idx++)
{
varInt& integer = integers[idx];
sprintf(buf,".%i#", integer.val);
stringKey += integer.varName + buf;
}
stringKey+="FLOAT#";
for (idx=0; idx < floats.Size(); idx ++)
{
varFloat& var = floats[idx];
sprintf(buf,".%f#", var.val );
stringKey += var.varName + buf;
}
stringKey+="VECTOR#";
for (idx = 0; idx< vectors.Size(); idx ++)
{
varVector& var = vectors[idx];
sprintf(buf,".%f_%f_%f_%f#", var.val.x, var.val.y, var.val.z, var.val.w);
stringKey += var.varName + buf;
}
stringKey+="ANIMS$";
for (idx = 0 ; idx < anims.Size() ; idx ++)
{
stringKey += anims[idx] + "$";
}
this->stringValid = true;
}
return this->stringKey.Get();
}
void
nAbstractPropBuilder::SetTo( nAbstractShaderNode* node)
{
n_assert(nKernelServer::ks);
int idx;
switch (thisType)
{
case NONE:
break;
case NMATERIAL:
if ( node->IsA(nmaterialnode))
{
//nMaterialNode* MaterialNode = (nMaterialNode*) node;
//MaterialNode->SetMaterial( this->material.Get() );
}
break;
case NSURFACE:
if ( node->IsA(nsurfacenode) )
{
nSurfaceNode* SurfaceNode = (nSurfaceNode*) node;
for (idx = 0; idx < shaders.Size() ; idx ++)
{
varShader& var = shaders[idx];
SurfaceNode->SetShader( nVariableServer::StringToFourCC(var.varName.Get()) , var.val.Get() );
}
}
break;
case SHADERTYPELIBRARY:
break;
}
for (idx = 0; idx < textures.Size() ; idx ++)
{
varTexture& var = textures[idx];
node->SetTexture( nShaderState::StringToParam( var.varName.Get()),
var.texName.Get() );
}
for (idx = 0; idx < floats.Size(); idx ++)
{
varFloat& var = floats[idx];
node->SetFloat( nShaderState::StringToParam( var.varName.Get()),
var.val);
}
for (idx = 0; idx < integers.Size(); idx++)
{
varInt& var = integers[idx];
node->SetInt( nShaderState::StringToParam( var.varName.Get())
, var.val);
}
for (idx = 0; idx < vectors.Size(); idx++)
{
varVector& var = vectors[idx];
node->SetVector( nShaderState::StringToParam( var.varName.Get() ),
var.val);
}
for (idx = 0 ; idx < anims.Size() ; idx ++)
{
node->AddAnimator( anims[idx].Get() );
}
}
void
nAbstractPropBuilder::operator +=(const nAbstractPropBuilder& rhs)
{
switch (rhs.thisType)
{
case NONE:
break;
case NMATERIAL:
if (this->thisType == NONE || this->thisType == NMATERIAL)
{
this->thisType = NMATERIAL;
if (rhs.matTypeIsValid)
{
this->matTypeIsValid = true;
this->matType += rhs.matType;
}
}
break;
case NSURFACE:
if (this->thisType == NONE || this->thisType == NSURFACE)
{
this->thisType = NSURFACE;
this->shaders += rhs.shaders;
}
break;
case SHADERTYPELIBRARY:
if (this->thisType == NONE || this->thisType == SHADERTYPELIBRARY)
{
this->thisType = SHADERTYPELIBRARY;
this->matTypeIsValid = true;
this->matType += rhs.matType;
if ( this->thisType == NONE )
{
this->materialTypeNameInLibrary = rhs.materialTypeNameInLibrary;
}
}
}
this->textures+= rhs.textures;
this->integers+= rhs.integers;
this->floats+= rhs.floats;
this->vectors+= rhs.vectors;
this->stringValid = false;
}
const char*
nAbstractPropBuilder::GetNameClass()
{
switch (thisType )
{
case nAbstractPropBuilder::NONE:
return "nabstractshadernode";
break;
case nAbstractPropBuilder::NMATERIAL :
return "nmaterialnode";
break;
case nAbstractPropBuilder::NSURFACE :
return "nsurfacenode";
break;
case nAbstractPropBuilder::SHADERTYPELIBRARY :
return "nmaterialnode";
break;
}
return "";
}
void
nAbstractPropBuilder::Reduce()
{
//@ todo remove unnecesary variables, textures , etc.... by material properties
}
|
[
"magarcias@c1fa4281-9647-0410-8f2c-f027dd5e0a91"
] |
magarcias@c1fa4281-9647-0410-8f2c-f027dd5e0a91
|
e50dfbf3493132b4631611703d23ff5f7b5b1fe7
|
889070c36584bf72670ead396b2c0932b9cb2f2d
|
/vish.cpp
|
49bb0161ac86526d97fb362265da05afdff43058
|
[] |
no_license
|
viralipurbey/CompetitiveProgramminCodingNinjas
|
2586cb1f688265c29e66a50da906424986f98fa8
|
7fa063930a92f02efbdcf9afe55252df9e0299a6
|
refs/heads/master
| 2022-11-27T06:44:22.829945
| 2020-08-02T07:20:19
| 2020-08-02T07:20:19
| 257,389,120
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,373
|
cpp
|
#include <stdio.h>
#include<bits/stdc++.h>
#define ll long long
using namespace std;
ll count(ll a[],ll k,ll sti,ll endi)
{
ll sum = 0;
if(sti < endi)
{
ll midi = (sti+endi)/2;
sum += count(a,k,sti,midi);
sum += count(a,k,midi+1,endi);
ll li = sti;
ll ri=midi+1;
vector<ll> temp;
while(li <= midi && ri <= endi)
{
if(a[li] > a[ri])
{
temp.push_back(a[ri]);
if(a[li] - a[ri] >= k)
{
sum += (midi+1-li);
}
ri++;
}
else
{
temp.push_back(a[li]);
if(a[ri] - a[li] >= k)
{
sum += (endi + 1-ri);
}
li++;
}
}
while(li <= midi)
{
temp.push_back(a[li++]);
}
while( ri <= midi)
{
temp.push_back(a[ri++]);
}
for(ll i = sti, k = 0; i <= endi; i++, k++){
a[i] = temp[k];
}
}
return sum;
}
int main(void) {
// your code goes here
ll n;
cin>>n;
ll k;
cin>>k;
ll arr[n];
for(ll i=0;i<n;i++)
{
ll ele;
cin>>ele;
arr[i] = ele;
}
cout<<count(arr,k,0,n-1)<<endl;
//delete []arr;
return 0;
}
|
[
"viralipurbey4567@gmail.com"
] |
viralipurbey4567@gmail.com
|
e11167364bc8d27de7b4e5dc9c98a3abb11c4596
|
74474c3e970b3c640e74bb9ac41c961593b88c31
|
/src/webserver/Cookie.cpp
|
ccdcb72f4dbdbf90fa43edf210a597c23bbae586
|
[] |
no_license
|
tglane/webServPP
|
c95d755659d53d13b1effcd686eac3d1eb7462a0
|
53758fa3b23e0e898c1fd909707935a37607ff70
|
refs/heads/master
| 2021-06-22T15:24:20.606906
| 2021-02-08T21:31:21
| 2021-02-08T21:31:21
| 191,049,911
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,374
|
cpp
|
//
// Created by timog on 24.02.19.
//
#include "Cookie.hpp"
namespace webserv
{
Cookie::Cookie(string name, string value, bool httpOnly, bool secure, string comment, string domain, string max_age,
string path, int expires)
{
m_name = std::move(name);
m_value = std::move(value);
m_http_only = httpOnly;
m_secure = secure;
m_comment = std::move(comment);
m_domain = std::move(domain);
m_max_age = std::move(max_age);
m_path = std::move(path);
if(expires > 0) { set_expiry_date(expires); }
}
string Cookie::build_header()
{
string header = "Set-Cookie: " + m_name + "=" + m_value;
if(!m_comment.empty()) { header.append("; Comment=" + m_comment); }
if(!m_domain.empty()) { header.append("; Domain=" + m_domain); }
if(!m_max_age.empty()) { header.append("; Max-Age=" + m_max_age); }
if(!m_path.empty()) { header.append("; Path=" + m_path); }
if(m_http_only) { header.append("; HttpOnly"); }
if(m_secure) { header.append("; secure"); }
if(!m_expires.empty()) { header.append("; Expires=" + m_expires); }
return header;
}
void Cookie::set_expiry_date(int days)
{
std::chrono::time_point<std::chrono::system_clock> e(std::chrono::system_clock::now() + std::chrono::hours(days * 24));
std::time_t t(std::chrono::system_clock::to_time_t(e));
m_expires = std::ctime(&t);
}
}
|
[
"timo.glane@gmail.com"
] |
timo.glane@gmail.com
|
0e24840b48a7f7dce6a8fc38fd8d760fb5c3efc9
|
2c362195203bb7ee9d8595b028ac8087ca3f0be3
|
/Smart_Strings/Owned_Pointers.cpp
|
b6fe8c16a47f7b2d645819d8d842dc7b86878d45
|
[] |
no_license
|
syed789/Assignment_02_-_Smart_Strings
|
15bbf9807712077b86760d079d34b0301f353bb0
|
943a0e4e92aa4ffc3b0740177896d56064efc387
|
refs/heads/master
| 2020-06-10T20:12:44.826951
| 2016-12-08T00:30:51
| 2016-12-08T00:30:51
| 75,887,484
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,423
|
cpp
|
#include <iostream>
using namespace std;
// String Buffer class
class String_Buffer {
private:
// string buffer
char* string_buffer;
// string size
int size;
public:
// default constructor
String_Buffer()
{
string_buffer = NULL;
size = 0;
}
// destructor
~String_Buffer()
{
delete[size] string_buffer;
size = 0;
}
// parametrized / overload constructor
void load_string(char* string, int length)
{
allocate(length);
for (int i = 0; i < length; ++i)
{
string_buffer[i] = string[i];
}
}
// returns character at specified index
char char_at(int index) const
{
if (index < size)
{
return string_buffer[index];
}
else
{
cout << "Error! Index out of bound!";
return ' ';
}
}
// returns size of string buffer
int length() const
{
return size;
}
// allocate memory
void allocate(int length)
{
delete[] string_buffer;
string_buffer = new char[length];
size = length;
}
// appends character at the end
void append(char character)
{
char* new_string = new char[size + 1];
for (int i = 0; i < size; i++)
{
new_string[i] = string_buffer[i];
}
new_string[size] = character;
delete[size] string_buffer;
string_buffer = new_string;
++size;
}
void print()
{
for (int i = 0; i < size; i++)
{
cout << string_buffer[i];
}
}
};
// String class
class String {
private:
String_Buffer* string_buffer;
bool owner;
public:
// default constructor
String()
{
string_buffer = NULL;
owner = 0;
}
// parametrized / overload constructor
String(char* input_string, int length)
{
string_buffer = new String_Buffer;
string_buffer->load_string(input_string, length);
}
// parametrized / overload constructor
String(String& source)
{
this->owner = true;
source.owner = false;
this->string_buffer = source.string_buffer;
}
// destructor
~String()
{
if (owner)
{
delete string_buffer;
}
else
{
string_buffer = NULL;
}
}
// returns character at specified index
char char_at(int index) const
{
if (string_buffer != NULL)
{
return string_buffer->char_at(index);
}
return ' ';
}
// returns size of string buffer
int length() const
{
if (string_buffer != NULL)
{
return string_buffer->length();
}
return 0;
}
// appends character at the end of string
void append(char character)
{
if (string_buffer == NULL)
{
string_buffer = new String_Buffer;
}
string_buffer->append(character);
}
void print()
{
if (string_buffer != NULL)
{
string_buffer->print();
}
}
};
int main(void)
{
cout << "OUTER SCOPE" << endl << endl;
String string_1("HELLO", 5);
cout << "String 1: ";
string_1.print();
cout << endl << endl;
{
cout << "INNER SCOPE" << endl << endl;
String string_2(string_1);
cout << "String 2: ";
string_2.print();
cout << endl << endl;
cout << "String 1: ";
string_1.print();
cout << endl << endl;
string_1.append(' ');
string_1.append('F');
string_1.append('A');
string_1.append('H');
string_1.append('A');
string_1.append('D');
string_1.append('!');
cout << "After append \" FAHAD!\" in String 1" << endl << endl;
cout << "String 1: ";
string_1.print();
cout << endl << endl;
cout << "String 2: ";
string_2.print();
cout << endl << endl;
}
cout << "OUTER SCOPE" << endl << endl;
cout << "String 1: ";
string_1.print();
cout << endl << endl;
return 0;
}
|
[
"14bscsstayyab@seecs.edu.pk"
] |
14bscsstayyab@seecs.edu.pk
|
2f7c53e6eca61a4d65b5a9090d33a226af61dcdd
|
f18fc611d43a332493e082cfd1ebed01a50d29f2
|
/flakor/base/entity/Scene.cpp
|
5f79fa8b26db8d973d705db58191744703f06ca6
|
[] |
no_license
|
7heaven/Flakor
|
011995263f92d47179e79bd93527e32b660dfe5a
|
357d93db8592df9476b26cb43593eab7e6b652db
|
refs/heads/master
| 2020-12-27T15:14:11.269061
| 2014-12-03T09:59:30
| 2014-12-03T09:59:30
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 377
|
cpp
|
#include "targetMacros.h"
#include "base/entity/Scene.h"
FLAKOR_NS_BEGIN
Scene::Scene()
{
relativeAnchorPoint = false;
setAnchorPoint(MakePoint(0.5,0.5));
}
Scene::~Scene()
{
}
Scene* Scene::create()
{
Scene *pRet = new Scene();
if (pRet && pRet->init())
{
pRet->autorelease();
return pRet;
}
else
{
FK_SAFE_DELETE(pRet);
return NULL;
}
}
FLAKOR_NS_END
|
[
"saint@aliyun.com"
] |
saint@aliyun.com
|
373dcdcddb1d1fa32b2095e20088a06a5b729804
|
b668dd9561e7cc31fd31471277cccb266bf8474a
|
/source/tetrixboard.cpp
|
67101ee7158e7405c0eb2987e05ad336851c363d
|
[] |
no_license
|
wu-hua-guo/Myteris
|
968316860c5e4d7c089fbbdb0619862506376974
|
544e990cf3afcbd51c128ad7c38c498b597d1345
|
refs/heads/master
| 2020-03-22T13:44:42.055910
| 2018-07-09T14:49:44
| 2018-07-09T14:49:44
| 140,128,866
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 8,644
|
cpp
|
#include <QtWidgets>
#include "tetrixboard.h"
class QDebug;
//! [0]
TetrixBoard::TetrixBoard(QWidget *parent)
: QFrame(parent)
{
setFrameStyle(QFrame::Panel | QFrame::Sunken);
setFocusPolicy(Qt::StrongFocus);
isStarted = false;
isPaused = false;
clearBoard();
nextPiece.setRandomShape();
}
//! [0]
//! [1]
void TetrixBoard::setNextPieceLabel(QLabel *label)
{
nextPieceLabel = label;
}
//! [1]
//! [2]
QSize TetrixBoard::sizeHint() const
{
QSize size=QSize(BoardWidth * 15 + frameWidth() * 2,
BoardHeight * 15 + frameWidth() * 2);
//qDebug()<<"sizeHint:"<<size;
return size;
}
QSize TetrixBoard::minimumSizeHint() const
//! [2] //! [3]
{
return QSize(BoardWidth * 5 + frameWidth() * 2,
BoardHeight * 5 + frameWidth() * 2);
}
//! [3]
//! [4]
void TetrixBoard::start()
{
if (isPaused)
return;
isStarted = true;
isWaitingAfterLine = false;
numLinesRemoved = 0;
numPiecesDropped = 0;
score = 0;
level = 1;
clearBoard();
emit linesRemovedChanged(numLinesRemoved);
emit scoreChanged(score);
emit levelChanged(level);
newPiece();
timer.start(timeoutTime(), this);
}
//! [4]
//! [5]
void TetrixBoard::pause()
{
if (!isStarted)
return;
isPaused = !isPaused;
if (isPaused) {
timer.stop();
} else {
timer.start(timeoutTime(), this);
}
update();
//! [5] //! [6]
}
//! [6]
//! [7]
void TetrixBoard::paintEvent(QPaintEvent *event)
{
// static int i=0;
//qDebug()<<tr("paintEvent %1").arg(i++);
QFrame::paintEvent(event);
QPainter painter(this);
QRect rect = contentsRect();
//! [7]
// if (isPaused) {
// painter.drawText(rect, Qt::AlignCenter, tr("Pause"));
// return;
// }
//! [8]
int boardTop = rect.bottom() - BoardHeight*squareHeight();
for (int y = 0; y < BoardHeight; ++y) {
for (int x = 0; x < BoardWidth; ++x) {
TetrixShape shape = shapeAt(x, y);
if (shape != NoShape)
drawSquare(painter, rect.left() + x * squareWidth(),
boardTop + y * squareHeight(), shape);
}
//! [8] //! [9]
}
//! [9]
//! [10]
if (curPiece.shape() != NoShape) {
for (int i = 0; i < 4; ++i) {
int x = curX + curPiece.x(i);
int y = curY + curPiece.y(i);
drawSquare(painter, rect.left() + x * squareWidth(),
boardTop + y * squareHeight(),
curPiece.shape());
}
//! [10] //! [11]
}
//! [11] //! [12]
}
//! [12]
//! [13]
void TetrixBoard::keyPressEvent(QKeyEvent *event)
{
if (!isStarted || isPaused || curPiece.shape() == NoShape) {
QFrame::keyPressEvent(event);
return;
}
//! [13]
//! [14]
switch (event->key()) {
case Qt::Key_Left:
tryMove(curPiece, curX - 1, curY);
break;
case Qt::Key_A:
tryMove(curPiece, curX - 1, curY);
break;
case Qt::Key_Right:
tryMove(curPiece, curX + 1, curY);
break;
case Qt::Key_D:
tryMove(curPiece, curX + 1, curY);
break;
case Qt::Key_Down:
tryMove(curPiece.rotatedRight(), curX, curY);
break;
case Qt::Key_S:
oneLineDown();
break;
case Qt::Key_Up:
tryMove(curPiece.rotatedLeft(), curX, curY);
break;
case Qt::Key_W:
tryMove(curPiece.rotatedLeft(), curX, curY);
break;
case Qt::Key_Space:
dropDown();
break;
default:
QFrame::keyPressEvent(event);
}
//! [14]
}
//! [15]
void TetrixBoard::timerEvent(QTimerEvent *event)
{
if (event->timerId() == timer.timerId()) {
if (isWaitingAfterLine) {
isWaitingAfterLine = false;
newPiece();
timer.start(timeoutTime(), this);
} else {
oneLineDown();
}
} else {
QFrame::timerEvent(event);
//! [15] //! [16]
}
//! [16] //! [17]
}
//! [17]
//! [18]
void TetrixBoard::clearBoard()
{
for (int i = 0; i < BoardHeight * BoardWidth; ++i)
board[i] = NoShape;
}
//! [18]
//! [19]
void TetrixBoard::dropDown()
{
int dropHeight = 0;
int newY = curY;
while (newY < BoardHeight) {
if (!tryMove(curPiece, curX, newY + 1))
break;
++newY;
++dropHeight;
}
pieceDropped(dropHeight);
//! [19] //! [20]
}
//! [20]
//! [21]
void TetrixBoard::oneLineDown()
{
if (!tryMove(curPiece, curX, curY + 1))
pieceDropped(0);
}
//! [21]
//! [22]
void TetrixBoard::pieceDropped(int dropHeight)
{
for (int i = 0; i < 4; ++i) {
int x = curX + curPiece.x(i);
int y = curY + curPiece.y(i);
shapeAt(x, y) = curPiece.shape();
}
++numPiecesDropped;
if (numPiecesDropped % 25 == 0) {
++level;
timer.start(timeoutTime(), this);
emit levelChanged(level);
}
score += dropHeight + 7;
emit scoreChanged(score);
removeFullLines();
if (!isWaitingAfterLine)
newPiece();
//! [22] //! [23]
}
//! [23]
//! [24]
void TetrixBoard::removeFullLines()
{
int numFullLines = 0;
for (int y = 0; y < BoardHeight; ++y) {
bool lineIsFull = true;
for (int x = 0; x < BoardWidth; ++x) {
if (shapeAt(x, y) == NoShape) {
lineIsFull = false;
break;
}
}
if (lineIsFull) {
//! [24] //! [25]
++numFullLines;
for (int k = y; k > 0; --k) {
for (int x = 0; x < BoardWidth; ++x)
shapeAt(x, k) = shapeAt(x, k - 1);
}
//! [25] //! [26]
for (int x = 0; x < BoardWidth; ++x)
shapeAt(x, 0) = NoShape;
}
//! [26] //! [27]
}
//! [27]
//! [28]
if (numFullLines > 0) {
numLinesRemoved += numFullLines;
score += 10 * numFullLines;
emit linesRemovedChanged(numLinesRemoved);
emit scoreChanged(score);
timer.start(500, this);
isWaitingAfterLine = true;
curPiece.setShape(NoShape);
update();
}
//! [28] //! [29]
}
//! [29]
//! [30]
void TetrixBoard::newPiece()
{
curPiece = nextPiece;
curX = BoardWidth / 2 -2;
curY = -curPiece.minY();
qDebug()<<curY;
if (!tryMove(curPiece, curX, curY)) {
curPiece.setShape(NoShape);
timer.stop();
isStarted = false;
return;
}
nextPiece.setRandomShape();
showNextPiece();
//! [30] //! [31]
}
//! [31]
//! [32]
void TetrixBoard::showNextPiece()
{
if (!nextPieceLabel)
return;
int dx = nextPiece.maxX() - nextPiece.minX() + 1;
int dy = nextPiece.maxY() - nextPiece.minY() + 1;
QPixmap pixmap(dx * squareWidth(), dy * squareHeight());
QPainter painter(&pixmap);
painter.fillRect(pixmap.rect(), nextPieceLabel->palette().background());
for (int i = 0; i < 4; ++i) {
int x = nextPiece.x(i) - nextPiece.minX();
int y = nextPiece.y(i) - nextPiece.minY();
drawSquare(painter, x * squareWidth(), y * squareHeight(),
nextPiece.shape());
}
nextPieceLabel->setPixmap(pixmap);
//! [32] //! [33]
}
//! [33]
//! [34]
bool TetrixBoard::tryMove(const TetrixPiece &newPiece, int newX, int newY)
{
for (int i = 0; i < 4; ++i) {
int x = newX + newPiece.x(i);
int y = newY + newPiece.y(i);
//qDebug()<<x<<y;
if (x < 0 || x >= BoardWidth || y < 0 || y >= BoardHeight)
return false;
if (shapeAt(x, y) != NoShape)
return false;
}
//! [34]
//! [35]
curPiece = newPiece;
curX = newX;
curY = newY;
update();
return true;
}
//! [35]
//! [36]
void TetrixBoard::drawSquare(QPainter &painter, int x, int y, TetrixShape shape)
{
static const QRgb colorTable[8] = {
0x000000, 0xCC6666, 0x66CC66, 0x6666CC,
0xCCCC66, 0xCC66CC, 0x66CCCC, 0xDAAA00
};
QColor color = colorTable[int(shape)];
// !1 绘制一个边框宽度为1的矩形
painter.fillRect(x + 1, y + 1, squareWidth() - 2, squareHeight() - 2,
color);
painter.setPen(color.light());
painter.drawLine(x, y + squareHeight() - 1, x, y);
painter.drawLine(x, y, x + squareWidth() - 1, y);
painter.setPen(color.dark());
painter.drawLine(x + 1, y + squareHeight() - 1,
x + squareWidth() - 1, y + squareHeight() - 1);
painter.drawLine(x + squareWidth() - 1, y + squareHeight() - 1,
x + squareWidth() - 1, y + 1);
// !1
}
//! [36]
|
[
"2206757071@qq.com"
] |
2206757071@qq.com
|
f69b885084c9cf74fe193810bbb1a9c435dd559e
|
6712863f4ba992d6b02e603b8c18c5a098c681eb
|
/lab/lab 28-05-2018/lab.cpp
|
5865b35cb80f95487034b1d3ba7a6e52ec205587
|
[] |
no_license
|
Hasanul-Bari/oop
|
b141c95492d73c84baa0a3217d11beca5353f3c4
|
aa4efdebf83e5e9f1907effc081191aa6fee25e8
|
refs/heads/master
| 2021-05-17T02:51:48.875156
| 2020-12-31T14:00:44
| 2020-12-31T14:00:44
| 250,583,528
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 518
|
cpp
|
#include<iostream>
using namespace std;
class student
{
int sid;
char name;
int level;
float marks;
float gp;
public:
void get(void)
{
cin>>sid>>marks;
}
void put(void)
{
cout<<sid<<"\t"<<marks<<endl;
}
};
int main()
{
student s[5];
cout<<"Enter 5 objects"<<endl;
for( int i=0; i<5; i++)
{
s[i].get();
}
cout<<"Entered objects are"<<endl;
for( int i=0; i<5; i++)
{
s[i].put();
}
return 0;
}
|
[
"hasanul.bari.hasan96@gmail.com"
] |
hasanul.bari.hasan96@gmail.com
|
484d26c21d64174b4c0d92a9f6665e706368a585
|
a06a9ae73af6690fabb1f7ec99298018dd549bb7
|
/_Library/_Include/boost/asio/read.hpp
|
bc114db39e51934b3bce64ec56e7a47bf73b68e7
|
[] |
no_license
|
longstl/mus12
|
f76de65cca55e675392eac162dcc961531980f9f
|
9e1be111f505ac23695f7675fb9cefbd6fa876e9
|
refs/heads/master
| 2021-05-18T08:20:40.821655
| 2020-03-29T17:38:13
| 2020-03-29T17:38:13
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 26,006
|
hpp
|
//
// read.hpp
// ~~~~~~~~
//
// Copyright (c) 2003-2015 Christopher M. Kohlhoff (chris at kohlhoff dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
#ifndef BOOST_ASIO_READ_HPP
#define BOOST_ASIO_READ_HPP
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
# pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include <boost/asio/detail/config.hpp>
#include <cstddef>
#include <boost/asio/async_result.hpp>
#include <boost/asio/basic_streambuf_fwd.hpp>
#include <boost/asio/error.hpp>
#include <boost/asio/detail/push_options.hpp>
namespace boost {
namespace asio {
/**
* @defgroup read boost::asio::read
*
* @brief Attempt to read a certain amount of data from a stream before
* returning.
*/
/*@{*/
/// Attempt to read a certain amount of data from a stream before returning.
/**
* This function is used to read a certain number of bytes of data from a
* stream. The call will block until one of the following conditions is true:
*
* @li The supplied buffers are full. That is, the bytes transferred is equal to
* the sum of the buffer sizes.
*
* @li An error occurred.
*
* This operation is implemented in terms of zero or more calls to the stream's
* read_some function.
*
* @param s The stream from which the data is to be read. The type must support
* the SyncReadStream concept.
*
* @param buffers One or more buffers into which the data will be read. The sum
* of the buffer sizes indicates the maximum number of bytes to read from the
* stream.
*
* @returns The number of bytes transferred.
*
* @throws boost::system::system_error Thrown on failure.
*
* @par Example
* To read into a single data buffer use the @ref buffer function as follows:
* @code boost::asio::read(s, boost::asio::buffer(data, size)); @endcode
* See the @ref buffer documentation for information on reading into multiple
* buffers in one go, and how to use it with arrays, boost::array or
* std::vector.
*
* @note This overload is equivalent to calling:
* @code boost::asio::read(
* s, buffers,
* boost::asio::transfer_all()); @endcode
*/
template <typename SyncReadStream, typename MutableBufferSequence>
std::size_t read(SyncReadStream& s, const MutableBufferSequence& buffers);
/// Attempt to read a certain amount of data from a stream before returning.
/**
* This function is used to read a certain number of bytes of data from a
* stream. The call will block until one of the following conditions is true:
*
* @li The supplied buffers are full. That is, the bytes transferred is equal to
* the sum of the buffer sizes.
*
* @li An error occurred.
*
* This operation is implemented in terms of zero or more calls to the stream's
* read_some function.
*
* @param s The stream from which the data is to be read. The type must support
* the SyncReadStream concept.
*
* @param buffers One or more buffers into which the data will be read. The sum
* of the buffer sizes indicates the maximum number of bytes to read from the
* stream.
*
* @param ec Set to indicate what error occurred, if any.
*
* @returns The number of bytes transferred.
*
* @par Example
* To read into a single data buffer use the @ref buffer function as follows:
* @code boost::asio::read(s, boost::asio::buffer(data, size), ec); @endcode
* See the @ref buffer documentation for information on reading into multiple
* buffers in one go, and how to use it with arrays, boost::array or
* std::vector.
*
* @note This overload is equivalent to calling:
* @code boost::asio::read(
* s, buffers,
* boost::asio::transfer_all(), ec); @endcode
*/
template <typename SyncReadStream, typename MutableBufferSequence>
std::size_t read(SyncReadStream& s, const MutableBufferSequence& buffers,
boost::system::error_code& ec);
/// Attempt to read a certain amount of data from a stream before returning.
/**
* This function is used to read a certain number of bytes of data from a
* stream. The call will block until one of the following conditions is true:
*
* @li The supplied buffers are full. That is, the bytes transferred is equal to
* the sum of the buffer sizes.
*
* @li The completion_condition function object returns 0.
*
* This operation is implemented in terms of zero or more calls to the stream's
* read_some function.
*
* @param s The stream from which the data is to be read. The type must support
* the SyncReadStream concept.
*
* @param buffers One or more buffers into which the data will be read. The sum
* of the buffer sizes indicates the maximum number of bytes to read from the
* stream.
*
* @param completion_condition The function object to be called to determine
* whether the read operation is complete. The signature of the function object
* must be:
* @code std::size_t completion_condition(
* // Result of latest read_some operation.
* const boost::system::error_code& error,
*
* // Number of bytes transferred so far.
* std::size_t bytes_transferred
* ); @endcode
* A return value of 0 indicates that the read operation is complete. A non-zero
* return value indicates the maximum number of bytes to be read on the next
* call to the stream's read_some function.
*
* @returns The number of bytes transferred.
*
* @throws boost::system::system_error Thrown on failure.
*
* @par Example
* To read into a single data buffer use the @ref buffer function as follows:
* @code boost::asio::read(s, boost::asio::buffer(data, size),
* boost::asio::transfer_at_least(32)); @endcode
* See the @ref buffer documentation for information on reading into multiple
* buffers in one go, and how to use it with arrays, boost::array or
* std::vector.
*/
template <typename SyncReadStream, typename MutableBufferSequence,
typename CompletionCondition>
std::size_t read(SyncReadStream& s, const MutableBufferSequence& buffers,
CompletionCondition completion_condition);
/// Attempt to read a certain amount of data from a stream before returning.
/**
* This function is used to read a certain number of bytes of data from a
* stream. The call will block until one of the following conditions is true:
*
* @li The supplied buffers are full. That is, the bytes transferred is equal to
* the sum of the buffer sizes.
*
* @li The completion_condition function object returns 0.
*
* This operation is implemented in terms of zero or more calls to the stream's
* read_some function.
*
* @param s The stream from which the data is to be read. The type must support
* the SyncReadStream concept.
*
* @param buffers One or more buffers into which the data will be read. The sum
* of the buffer sizes indicates the maximum number of bytes to read from the
* stream.
*
* @param completion_condition The function object to be called to determine
* whether the read operation is complete. The signature of the function object
* must be:
* @code std::size_t completion_condition(
* // Result of latest read_some operation.
* const boost::system::error_code& error,
*
* // Number of bytes transferred so far.
* std::size_t bytes_transferred
* ); @endcode
* A return value of 0 indicates that the read operation is complete. A non-zero
* return value indicates the maximum number of bytes to be read on the next
* call to the stream's read_some function.
*
* @param ec Set to indicate what error occurred, if any.
*
* @returns The number of bytes read. If an error occurs, returns the total
* number of bytes successfully transferred prior to the error.
*/
template <typename SyncReadStream, typename MutableBufferSequence,
typename CompletionCondition>
std::size_t read(SyncReadStream& s, const MutableBufferSequence& buffers,
CompletionCondition completion_condition, boost::system::error_code& ec);
#if !defined(BOOST_ASIO_NO_IOSTREAM)
/// Attempt to read a certain amount of data from a stream before returning.
/**
* This function is used to read a certain number of bytes of data from a
* stream. The call will block until one of the following conditions is true:
*
* @li The supplied buffer is full (that is, it has reached maximum size).
*
* @li An error occurred.
*
* This operation is implemented in terms of zero or more calls to the stream's
* read_some function.
*
* @param s The stream from which the data is to be read. The type must support
* the SyncReadStream concept.
*
* @param b The basic_streambuf object into which the data will be read.
*
* @returns The number of bytes transferred.
*
* @throws boost::system::system_error Thrown on failure.
*
* @note This overload is equivalent to calling:
* @code boost::asio::read(
* s, b,
* boost::asio::transfer_all()); @endcode
*/
template <typename SyncReadStream, typename Allocator>
std::size_t read(SyncReadStream& s, basic_streambuf<Allocator>& b);
/// Attempt to read a certain amount of data from a stream before returning.
/**
* This function is used to read a certain number of bytes of data from a
* stream. The call will block until one of the following conditions is true:
*
* @li The supplied buffer is full (that is, it has reached maximum size).
*
* @li An error occurred.
*
* This operation is implemented in terms of zero or more calls to the stream's
* read_some function.
*
* @param s The stream from which the data is to be read. The type must support
* the SyncReadStream concept.
*
* @param b The basic_streambuf object into which the data will be read.
*
* @param ec Set to indicate what error occurred, if any.
*
* @returns The number of bytes transferred.
*
* @note This overload is equivalent to calling:
* @code boost::asio::read(
* s, b,
* boost::asio::transfer_all(), ec); @endcode
*/
template <typename SyncReadStream, typename Allocator>
std::size_t read(SyncReadStream& s, basic_streambuf<Allocator>& b,
boost::system::error_code& ec);
/// Attempt to read a certain amount of data from a stream before returning.
/**
* This function is used to read a certain number of bytes of data from a
* stream. The call will block until one of the following conditions is true:
*
* @li The supplied buffer is full (that is, it has reached maximum size).
*
* @li The completion_condition function object returns 0.
*
* This operation is implemented in terms of zero or more calls to the stream's
* read_some function.
*
* @param s The stream from which the data is to be read. The type must support
* the SyncReadStream concept.
*
* @param b The basic_streambuf object into which the data will be read.
*
* @param completion_condition The function object to be called to determine
* whether the read operation is complete. The signature of the function object
* must be:
* @code std::size_t completion_condition(
* // Result of latest read_some operation.
* const boost::system::error_code& error,
*
* // Number of bytes transferred so far.
* std::size_t bytes_transferred
* ); @endcode
* A return value of 0 indicates that the read operation is complete. A non-zero
* return value indicates the maximum number of bytes to be read on the next
* call to the stream's read_some function.
*
* @returns The number of bytes transferred.
*
* @throws boost::system::system_error Thrown on failure.
*/
template <typename SyncReadStream, typename Allocator,
typename CompletionCondition>
std::size_t read(SyncReadStream& s, basic_streambuf<Allocator>& b,
CompletionCondition completion_condition);
/// Attempt to read a certain amount of data from a stream before returning.
/**
* This function is used to read a certain number of bytes of data from a
* stream. The call will block until one of the following conditions is true:
*
* @li The supplied buffer is full (that is, it has reached maximum size).
*
* @li The completion_condition function object returns 0.
*
* This operation is implemented in terms of zero or more calls to the stream's
* read_some function.
*
* @param s The stream from which the data is to be read. The type must support
* the SyncReadStream concept.
*
* @param b The basic_streambuf object into which the data will be read.
*
* @param completion_condition The function object to be called to determine
* whether the read operation is complete. The signature of the function object
* must be:
* @code std::size_t completion_condition(
* // Result of latest read_some operation.
* const boost::system::error_code& error,
*
* // Number of bytes transferred so far.
* std::size_t bytes_transferred
* ); @endcode
* A return value of 0 indicates that the read operation is complete. A non-zero
* return value indicates the maximum number of bytes to be read on the next
* call to the stream's read_some function.
*
* @param ec Set to indicate what error occurred, if any.
*
* @returns The number of bytes read. If an error occurs, returns the total
* number of bytes successfully transferred prior to the error.
*/
template <typename SyncReadStream, typename Allocator,
typename CompletionCondition>
std::size_t read(SyncReadStream& s, basic_streambuf<Allocator>& b,
CompletionCondition completion_condition, boost::system::error_code& ec);
#endif // !defined(BOOST_ASIO_NO_IOSTREAM)
/*@}*/
/**
* @defgroup async_read boost::asio::async_read
*
* @brief Start an asynchronous operation to read a certain amount of data from
* a stream.
*/
/*@{*/
/// Start an asynchronous operation to read a certain amount of data from a
/// stream.
/**
* This function is used to asynchronously read a certain number of bytes of
* data from a stream. The function call always returns immediately. The
* asynchronous operation will continue until one of the following conditions is
* true:
*
* @li The supplied buffers are full. That is, the bytes transferred is equal to
* the sum of the buffer sizes.
*
* @li An error occurred.
*
* This operation is implemented in terms of zero or more calls to the stream's
* async_read_some function, and is known as a <em>composed operation</em>. The
* program must ensure that the stream performs no other read operations (such
* as async_read, the stream's async_read_some function, or any other composed
* operations that perform reads) until this operation completes.
*
* @param s The stream from which the data is to be read. The type must support
* the AsyncReadStream concept.
*
* @param buffers One or more buffers into which the data will be read. The sum
* of the buffer sizes indicates the maximum number of bytes to read from the
* stream. Although the buffers object may be copied as necessary, ownership of
* the underlying memory blocks is retained by the caller, which must guarantee
* that they remain valid until the handler is called.
*
* @param handler The handler to be called when the read operation completes.
* Copies will be made of the handler as required. The function signature of the
* handler must be:
* @code void handler(
* const boost::system::error_code& error, // Result of operation.
*
* std::size_t bytes_transferred // Number of bytes copied into the
* // buffers. If an error occurred,
* // this will be the number of
* // bytes successfully transferred
* // prior to the error.
* ); @endcode
* Regardless of whether the asynchronous operation completes immediately or
* not, the handler will not be invoked from within this function. Invocation of
* the handler will be performed in a manner equivalent to using
* boost::asio::io_service::post().
*
* @par Example
* To read into a single data buffer use the @ref buffer function as follows:
* @code
* boost::asio::async_read(s, boost::asio::buffer(data, size), handler);
* @endcode
* See the @ref buffer documentation for information on reading into multiple
* buffers in one go, and how to use it with arrays, boost::array or
* std::vector.
*
* @note This overload is equivalent to calling:
* @code boost::asio::async_read(
* s, buffers,
* boost::asio::transfer_all(),
* handler); @endcode
*/
template <typename AsyncReadStream, typename MutableBufferSequence,
typename ReadHandler>
BOOST_ASIO_INITFN_RESULT_TYPE(ReadHandler,
void (boost::system::error_code, std::size_t))
async_read(AsyncReadStream& s, const MutableBufferSequence& buffers,
BOOST_ASIO_MOVE_ARG(ReadHandler) handler);
/// Start an asynchronous operation to read a certain amount of data from a
/// stream.
/**
* This function is used to asynchronously read a certain number of bytes of
* data from a stream. The function call always returns immediately. The
* asynchronous operation will continue until one of the following conditions is
* true:
*
* @li The supplied buffers are full. That is, the bytes transferred is equal to
* the sum of the buffer sizes.
*
* @li The completion_condition function object returns 0.
*
* @param s The stream from which the data is to be read. The type must support
* the AsyncReadStream concept.
*
* @param buffers One or more buffers into which the data will be read. The sum
* of the buffer sizes indicates the maximum number of bytes to read from the
* stream. Although the buffers object may be copied as necessary, ownership of
* the underlying memory blocks is retained by the caller, which must guarantee
* that they remain valid until the handler is called.
*
* @param completion_condition The function object to be called to determine
* whether the read operation is complete. The signature of the function object
* must be:
* @code std::size_t completion_condition(
* // Result of latest async_read_some operation.
* const boost::system::error_code& error,
*
* // Number of bytes transferred so far.
* std::size_t bytes_transferred
* ); @endcode
* A return value of 0 indicates that the read operation is complete. A non-zero
* return value indicates the maximum number of bytes to be read on the next
* call to the stream's async_read_some function.
*
* @param handler The handler to be called when the read operation completes.
* Copies will be made of the handler as required. The function signature of the
* handler must be:
* @code void handler(
* const boost::system::error_code& error, // Result of operation.
*
* std::size_t bytes_transferred // Number of bytes copied into the
* // buffers. If an error occurred,
* // this will be the number of
* // bytes successfully transferred
* // prior to the error.
* ); @endcode
* Regardless of whether the asynchronous operation completes immediately or
* not, the handler will not be invoked from within this function. Invocation of
* the handler will be performed in a manner equivalent to using
* boost::asio::io_service::post().
*
* @par Example
* To read into a single data buffer use the @ref buffer function as follows:
* @code boost::asio::async_read(s,
* boost::asio::buffer(data, size),
* boost::asio::transfer_at_least(32),
* handler); @endcode
* See the @ref buffer documentation for information on reading into multiple
* buffers in one go, and how to use it with arrays, boost::array or
* std::vector.
*/
template <typename AsyncReadStream, typename MutableBufferSequence,
typename CompletionCondition, typename ReadHandler>
BOOST_ASIO_INITFN_RESULT_TYPE(ReadHandler,
void (boost::system::error_code, std::size_t))
async_read(AsyncReadStream& s, const MutableBufferSequence& buffers,
CompletionCondition completion_condition,
BOOST_ASIO_MOVE_ARG(ReadHandler) handler);
#if !defined(BOOST_ASIO_NO_IOSTREAM)
/// Start an asynchronous operation to read a certain amount of data from a
/// stream.
/**
* This function is used to asynchronously read a certain number of bytes of
* data from a stream. The function call always returns immediately. The
* asynchronous operation will continue until one of the following conditions is
* true:
*
* @li The supplied buffer is full (that is, it has reached maximum size).
*
* @li An error occurred.
*
* This operation is implemented in terms of zero or more calls to the stream's
* async_read_some function, and is known as a <em>composed operation</em>. The
* program must ensure that the stream performs no other read operations (such
* as async_read, the stream's async_read_some function, or any other composed
* operations that perform reads) until this operation completes.
*
* @param s The stream from which the data is to be read. The type must support
* the AsyncReadStream concept.
*
* @param b A basic_streambuf object into which the data will be read. Ownership
* of the streambuf is retained by the caller, which must guarantee that it
* remains valid until the handler is called.
*
* @param handler The handler to be called when the read operation completes.
* Copies will be made of the handler as required. The function signature of the
* handler must be:
* @code void handler(
* const boost::system::error_code& error, // Result of operation.
*
* std::size_t bytes_transferred // Number of bytes copied into the
* // buffers. If an error occurred,
* // this will be the number of
* // bytes successfully transferred
* // prior to the error.
* ); @endcode
* Regardless of whether the asynchronous operation completes immediately or
* not, the handler will not be invoked from within this function. Invocation of
* the handler will be performed in a manner equivalent to using
* boost::asio::io_service::post().
*
* @note This overload is equivalent to calling:
* @code boost::asio::async_read(
* s, b,
* boost::asio::transfer_all(),
* handler); @endcode
*/
template <typename AsyncReadStream, typename Allocator, typename ReadHandler>
BOOST_ASIO_INITFN_RESULT_TYPE(ReadHandler,
void (boost::system::error_code, std::size_t))
async_read(AsyncReadStream& s, basic_streambuf<Allocator>& b,
BOOST_ASIO_MOVE_ARG(ReadHandler) handler);
/// Start an asynchronous operation to read a certain amount of data from a
/// stream.
/**
* This function is used to asynchronously read a certain number of bytes of
* data from a stream. The function call always returns immediately. The
* asynchronous operation will continue until one of the following conditions is
* true:
*
* @li The supplied buffer is full (that is, it has reached maximum size).
*
* @li The completion_condition function object returns 0.
*
* This operation is implemented in terms of zero or more calls to the stream's
* async_read_some function, and is known as a <em>composed operation</em>. The
* program must ensure that the stream performs no other read operations (such
* as async_read, the stream's async_read_some function, or any other composed
* operations that perform reads) until this operation completes.
*
* @param s The stream from which the data is to be read. The type must support
* the AsyncReadStream concept.
*
* @param b A basic_streambuf object into which the data will be read. Ownership
* of the streambuf is retained by the caller, which must guarantee that it
* remains valid until the handler is called.
*
* @param completion_condition The function object to be called to determine
* whether the read operation is complete. The signature of the function object
* must be:
* @code std::size_t completion_condition(
* // Result of latest async_read_some operation.
* const boost::system::error_code& error,
*
* // Number of bytes transferred so far.
* std::size_t bytes_transferred
* ); @endcode
* A return value of 0 indicates that the read operation is complete. A non-zero
* return value indicates the maximum number of bytes to be read on the next
* call to the stream's async_read_some function.
*
* @param handler The handler to be called when the read operation completes.
* Copies will be made of the handler as required. The function signature of the
* handler must be:
* @code void handler(
* const boost::system::error_code& error, // Result of operation.
*
* std::size_t bytes_transferred // Number of bytes copied into the
* // buffers. If an error occurred,
* // this will be the number of
* // bytes successfully transferred
* // prior to the error.
* ); @endcode
* Regardless of whether the asynchronous operation completes immediately or
* not, the handler will not be invoked from within this function. Invocation of
* the handler will be performed in a manner equivalent to using
* boost::asio::io_service::post().
*/
template <typename AsyncReadStream, typename Allocator,
typename CompletionCondition, typename ReadHandler>
BOOST_ASIO_INITFN_RESULT_TYPE(ReadHandler,
void (boost::system::error_code, std::size_t))
async_read(AsyncReadStream& s, basic_streambuf<Allocator>& b,
CompletionCondition completion_condition,
BOOST_ASIO_MOVE_ARG(ReadHandler) handler);
#endif // !defined(BOOST_ASIO_NO_IOSTREAM)
/*@}*/
} // namespace asio
} // namespace boost
#include <boost/asio/detail/pop_options.hpp>
#include <boost/asio/impl/read.hpp>
#endif // BOOST_ASIO_READ_HPP
/////////////////////////////////////////////////
// vnDev.Games - Trong.LIVE - DAO VAN TRONG //
////////////////////////////////////////////////////////////////////////////////
|
[
"adm.fael.hs@gmail.com"
] |
adm.fael.hs@gmail.com
|
6a8a4f962e338fc9e65d8984f44ce536a62d84a8
|
1ee6daace32d2b103cc29f36e836d23426dd76de
|
/553e4a8d6d656372d3000000/code/RobotAI.cpp
|
c7707cc7215eefb2ec56e3eab739a7a88b55a798
|
[
"Apache-2.0"
] |
permissive
|
MechEmpire/Mechempire-meches
|
874ae3360c74e25573cb5bc2c3872f2696258744
|
aa95b15f061f4179c9061595e73c7127587cc4df
|
refs/heads/master
| 2021-01-14T12:27:01.390406
| 2015-06-06T07:42:03
| 2015-06-06T07:42:03
| 35,320,888
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 23,793
|
cpp
|
#include "RobotAI.h"
#include<iostream>
RobotAI::RobotAI()
{
}
RobotAI::~RobotAI()
{
}
//-----------------------------------------------------
//1.必须完成的战斗核心
//-----------------------------------------------------
static int frame = 0;
void RobotAI::Update(RobotAI_Order& order,const RobotAI_BattlefieldInformation& info,int myID)
{
//帧操纵函数
//功能:在每一帧被调用,完成你的机甲在这一帧的动作决策
//参数:order ... 机甲操纵指令,你在函数体中给它赋值以操纵机甲在这一帧的行为
// info ... 战场信息
// myID ... 自己机甲在info中robot数组对应的下标
// (这几个参数的详细说明在开发手册可以找到,你也可以在RobotAIstruct.h中直接找到它们的代码)
auto me = info.robotInformation[myID];
auto tag = info.robotInformation[1 - myID];
/*静态成员列表*/
static int hp_tag = tag.hp;
/*静态成员列表*/
//开火操作
if (frame != 0)
{
onFire1(order, info, myID);
}
onTag1(order, info, myID);
//躲避操纵
//isDodeg——判断是否执行躲避函数,如果执行则为true,将跳过后面的移动函数优先躲避
//bullet ——最近的子弹
bool isDodge = false;
//int b_index_nearest = GetNearetBul(order, info, myID);
//if (b_index_nearest != -1)//如果有敌方子弹则进行躲避判断
//{
// auto bullet = info.bulletInformation[b_index_nearest];
// isDodge = onDodge(order, info, myID, bullet);
//}
//获取地方子弹数组,并按距离升序排列
int b_tag = 0;
for (int b_index = 0; b_index <= info.num_bullet; b_index++)
{
auto bullet = info.bulletInformation[b_index];
if (bullet.launcherID == myID)continue;
b_tag++;
}
if (frame < 500)
{
/* cout << "zhen下面" << frame << endl << "无序数组" << endl;*/
for (int b_index = 0; b_index <= info.num_bullet; b_index++)
{
auto bullet = info.bulletInformation[b_index];
if (bullet.launcherID == myID)continue;
//cout << dis(info.bulletInformation[b_index].circle, me.circle) << " & ";
}
//cout << endl;
}
int *bulArray = new int[b_tag];
int bulArray_index = 0;
for (int b_index = 0; b_index <= info.num_bullet; b_index++)
{
auto bullet = info.bulletInformation[b_index];
if (bullet.launcherID == myID)continue;
bulArray[bulArray_index] = b_index;
bulArray_index++;
}
/*if (frame < 500)
{
cout << "未排数组" << GetNearetBul(order, info, myID) << "^" << bulArray[0] << endl;
for (int i = 0; i < bulArray_index; i++)
cout << dis(info.bulletInformation[bulArray[i]].circle, me.circle) << " & ";
cout << endl;
}*/
for (int i = bulArray_index; i > 0; i--)
{
for (int j = 0; j < bulArray_index-1; j++)
{
if (dis(info.bulletInformation[bulArray[j]].circle, me.circle) <=
dis(info.bulletInformation[bulArray[j + 1]].circle, me.circle) )
continue;
else
{
int temp = bulArray[j + 1];
bulArray[j + 1] = bulArray[j];
bulArray[j] = temp;
}
}
}
if (bulArray_index!=0)//如果有敌方子弹则进行躲避判断
{
int b_index_nearest = bulArray[0];
//if (frame < 500)
//{
// cout << "有序数组" << GetNearetBul(order, info, myID) << "^" << bulArray[0] << endl;
// for (int i = 0; i < bulArray_index; i++)
// cout << dis(info.bulletInformation[bulArray[i]].circle, me.circle) << " & ";
// cout << endl;
//}
auto bullet = info.bulletInformation[b_index_nearest];
//isDodge = onDodge(order, info, myID, bullet);
}
isDodge = onDodge2(order, info, myID);
//正常移动操作
//isDodge = false;
if (!isDodge)
{
onMove1(order, info, myID, tag.circle);
}
//静态变量更新
hp_tag = tag.hp;
frame++;
delete bulArray;
}
void RobotAI::ChooseArmor(weapontypename& weapon,enginetypename& engine,bool a)
{
//挑选装备函数
//功能:在战斗开始时为你的机甲选择合适的武器炮塔和引擎载具
//参数:weapon ... 代表你选择的武器,在函数体中给它赋值
// engine ... 代表你选择的引擎,在函数体中给它赋值
//tip: 括号里的参数是枚举类型 weapontypename 或 enginetypename
// 开发文档中有详细说明,你也可以在RobotAIstruct.h中直接找到它们的代码
//tip: 最后一个bool是没用的。。那是一个退化的器官
srand(time(0));
MyCar = rand() % 2+ 1;
MyCar = AFV_Esaw;
if (MyCar == AFV_Esaw)//幽灵电锯
{
weapon = WT_ElectricSaw;
engine = ET_AFV;
}
if (MyCar == AFV_Prism)//幽灵光棱
{
weapon = WT_Prism;
engine = ET_AFV;
}
if (MyCar == AFV_WT_Machinegun)
{
weapon = WT_Machinegun;
engine = ET_AFV;
}
}
//-----------------------------------------------------
//2.个性信息
//-----------------------------------------------------
string RobotAI::GetName()
{
//返回你的机甲的名字
return "艾欧尼亚闪电";
}
string RobotAI::GetAuthor()
{
//返回机甲制作人或团队的名字
return "爆炸何";
}
//返回一个(-255,255)之间的机甲武器炮塔的颜色偏移值(红、绿、蓝)
//你可以在flash客户端的参数预览中预览颜色搭配的效果
int RobotAI::GetWeaponRed()
{
//返回一个-255-255之间的整数,代表武器红色的偏移值
return color;
}
int RobotAI::GetWeaponGreen()
{
//返回一个-255-255之间的整数,代表武器绿色的偏移值
return color;
}
int RobotAI::GetWeaponBlue()
{
//返回一个-255-255之间的整数,代表武器蓝色的偏移值
return color;
}
//返回一个(-255,255)之间的机甲引擎载具的颜色偏移值(红、绿、蓝)
//你可以在flash客户端的参数预览中预览颜色搭配的效果
int RobotAI::GetEngineRed()
{
//返回一个-255-255之间的数,代表载具红色的偏移值
return color;
}
int RobotAI::GetEngineGreen()
{
//返回一个-255-255之间的整数,代表载具绿色的偏移值
return color;
}
int RobotAI::GetEngineBlue()
{
//返回一个-255-255之间的整数,代表载具蓝色的偏移值
return color;
}
//-----------------------------------------------------
//3.用不用随你的触发函数
//-----------------------------------------------------
void RobotAI::onBattleStart(const RobotAI_BattlefieldInformation& info,int myID)
{
//一场战斗开始时被调用,可能可以用来初始化
//参数:info ... 战场信息
// myID ... 自己机甲在info中robot数组对应的下标
}
void RobotAI::onBattleEnd(const RobotAI_BattlefieldInformation& info,int myID)
{
//一场战斗结束时被调用,可能可以用来析构你动态分配的内存空间(如果你用了的话)
//参数:info ... 战场信息
// myID ... 自己机甲在info中robot数组对应的下标
system("Pause");
}
void RobotAI::onSomeoneFire(int fireID)
{
//有机甲开火时被调用
//参数:fireID ... 开火的机甲下标
}
void RobotAI::onHit(int launcherID,bullettypename btn)
{
//被子弹击中时被调用
//参数:btn ... 击中你的子弹种类(枚举类型)
}
//TODO:这里可以实现你自己的函数
//判断和敌方之间是否有障碍物,ArID为障碍物ID
bool RobotAI::HaveBarrier(const RobotAI_BattlefieldInformation& info,const int myID,const int ArID)
{
auto me = info.robotInformation[myID];
auto tag = info.robotInformation[1 - myID];
Circle obs_circle = info.obstacle[ArID];
double pdis = pointdis(me.circle, tag.circle, obs_circle);
if (pdis > info.obstacle[ArID].r)
return false;
else
{
if (((me.circle.y - obs_circle.y)*(tag.circle.y - obs_circle.y)) &&
((me.circle.x - obs_circle.x)*(tag.circle.x - obs_circle.x)))
return false;
else
return true;
}
}
bool RobotAI::HaveBarrier(const RobotAI_BattlefieldInformation& info, const int myID, Circle obs_circle)
{
auto me = info.robotInformation[myID];
auto tag = info.robotInformation[1 - myID];
double c = dis(tag.circle, obs_circle);
double b = obs_circle.r;
double a = sqrt(c*c - b*b);
double rotaob = abvalue( atan2(b ,a) * 180 / PI);
double rota1 = atan2(obs_circle.y-tag.circle.y, obs_circle.x-tag.circle.x) * 180 / PI;//障碍物和tag夹角
double c2 = dis(tag.circle, me.circle);
double b2 = me.circle.r;
double a2 = sqrt(c2*c2 - b2*b2);
double rotame = abvalue(atan2(b2, a2) * 180 / PI);
double rota2 = atan2(me.circle.y - tag.circle.y, me.circle.x - tag.circle.x) * 180 / PI;//我方和tag夹角
double r1 = rota2 + rotame;
double r2 = rota2 - rotame;
double t1 = rota1 + rotaob;
double t2 = rota1 - rotaob;
AngleAdjust(r1); AngleAdjust(r2); AngleAdjust(t1); AngleAdjust(t2);
if (r1 <= t1&&r2 >= t2)
return true;
else
return false;
}
int RobotAI::GetNearetBul(RobotAI_Order& order, const RobotAI_BattlefieldInformation& info, const int myID)
{
auto me = info.robotInformation[myID];
//cout << "地图上子弹数量" << info.num_bullet + 1 << endl;
int b_index_near = -1;
int b_tag = 0;//敌方子弹数
for (int b_index = 0; b_index <= info.num_bullet; b_index++)
{
//cout << "判断第" << b_index << "子弹" << endl;
auto bullet = info.bulletInformation[b_index];
if (bullet.launcherID == myID)
{
continue;
}
b_tag++;
if (b_tag == 1)b_index_near = b_index;
//cout << "第" << b_index << "子弹是敌方子弹" << endl;
if (dis(bullet.circle, me.circle) <= dis(info.bulletInformation[b_index_near].circle, me.circle))
b_index_near = b_index;
}
//cout << "最近!" << b_index_near << endl;
return b_index_near;//如果没有找到最近的敌方子弹就返回-1
}
void RobotAI::onTag1(RobotAI_Order& order,const RobotAI_BattlefieldInformation& info, const int myID)//瞄准函数(不带预判)
{
auto me = info.robotInformation[myID];
auto tag = info.robotInformation[1 - myID];
double dx = tag.circle.x - me.circle.x;
double dy = tag.circle.y - me.circle.y;
double Rota = atan2(dy, dx) * 180 / PI;
double wpRota = info.robotInformation[myID].weaponRotation;
double offset = wpRota - Rota;
if (abvalue(offset) >= 180)
{
if (offset > 0)
order.wturn = 1;
else
order.wturn = -1;
}
else{
if (offset > 0)
order.wturn = -1;
else
order.wturn = 1;
}
}
double RobotAI::onTagRota(const RobotAI_BattlefieldInformation& info, const int myID)
{
auto me = info.robotInformation[myID];
auto tag = info.robotInformation[1 - myID];
double dx = tag.circle.x - me.circle.x;
double dy = tag.circle.y - me.circle.y;
double Rota = atan2(dy, dx) * 180 / PI;
double wpRota = info.robotInformation[myID].weaponRotation;
double offset = wpRota - Rota;
return offset;
}
void RobotAI::onMove1(RobotAI_Order& order, const RobotAI_BattlefieldInformation& info, const int myID, const Circle circle_tag)
{
onMove1(order, info, myID, circle_tag.x, circle_tag.y);
}
void RobotAI::onMove1(RobotAI_Order& order, const RobotAI_BattlefieldInformation& info, const int myID,const double x_tag,const double y_tag)
{
auto me = info.robotInformation[myID];
double dx = x_tag - me.circle.x;
double dy = y_tag - me.circle.y;
double Rota = atan2(dy, dx) * 180 / PI;
onMove1(order, info, myID, Rota);
}
void RobotAI::onMoveCircle(RobotAI_Order& order, const RobotAI_BattlefieldInformation& info, const int myID, const double x_tag, const double y_tag)
{
auto me = info.robotInformation[myID];
double dx = x_tag - me.circle.x;
double dy = y_tag - me.circle.y;
double Rota = atan2(dy, dx) * 180 / PI;
Circle tag_circle;
tag_circle.x = x_tag;
tag_circle.y = y_tag;
if (dis(me.circle, tag_circle) <= me.circle.r)
order.run = 0;
else
onMove1(order, info, myID, Rota);
}
void RobotAI::onMove1(RobotAI_Order& order, const RobotAI_BattlefieldInformation& info, const int myID, const double rota_tag)
{
auto me = info.robotInformation[myID];
double Rota = rota_tag;
double Rota_eng = me.engineRotation;
double offset = Rota_eng - Rota;
switch (MyCar)
{
case AFV_Esaw:
case AFV_WT_Machinegun:
case AFV_Prism:
if (abvalue(offset) >= 180)
{
if (offset > 0)
order.eturn = 1;
else
order.eturn = -1;
}
else{
if (offset > 0)
order.eturn = -1;
else
order.eturn = 1;
}
order.run = 1;
break;
default:
break;
}
}
void RobotAI::onFire1(RobotAI_Order& order, const RobotAI_BattlefieldInformation& info, const int myID)
{
auto me = info.robotInformation[myID];
auto tag = info.robotInformation[1 - myID];
switch (MyCar)
{
case AFV_Esaw:
if (tag.weaponTypeName == WT_ElectricSaw)
{
if (
!HaveBarrier(info, myID, 0) &&
!HaveBarrier(info, myID, 1) &&
(onTagRota(info, myID)<3) &&
(onTagRota(info, myID)>-3) &&
dis(me.circle, tag.circle)<120 + tag.circle.r
)
order.fire = 1;
break;
}
if (
!HaveBarrier(info, myID, 0) &&
!HaveBarrier(info, myID, 1) &&
dis(me.circle, tag.circle)<95 + tag.circle.r
)
order.fire = 1;
break;
case AFV_Prism:
case AFV_WT_Machinegun:
if (
!HaveBarrier(info, myID, 0) &&
!HaveBarrier(info, myID, 1) &&
(onTagRota(info, myID)<3)&&
(onTagRota(info, myID)>-3)
)
order.fire = 1;
break;
default:
break;
}
}
bool RobotAI::onDodge(RobotAI_Order& order, const RobotAI_BattlefieldInformation& info, const int myID,const RobotAI_BulletInformation& bullet)
//躲闪函数,如果发出了躲避命令,则返回true;
{
auto me = info.robotInformation[myID];
auto tag = info.robotInformation[1-myID];
bool inHitRange = dis(bullet.circle, me.circle) <= 0.6 * me.circle.r *getBulletSpeed(bullet.type);//判断在监控范围内再躲
double Rota_bulv = atan2(bullet.vy, bullet.vx) * 180 / PI;//子弹速度方向
double Rota_bulv_ag = Rota_bulv - 180;//子弹速度反方向
double tag_vrota = atan2(tag.vy, tag.vx) * 180 / PI;//对方机甲移动方向
AngleAdjust(Rota_bulv_ag);
auto Type_Bul = bullet.type;
switch (MyCar)
{
case AFV_Esaw:
case AFV_Prism:
case AFV_WT_Machinegun:
if (order.fire == 1)
return false;
switch (tag.weaponTypeName)
{
case WT_Shotgun:
case WT_Machinegun:
if ((tag.remainingAmmo + 2)*getBulletDamage(bullet.type) < me.hp ||
(dis(me.circle, tag.circle) <= me.circle.r * 3) )
{
onMove1(order, info, myID, tag.circle);
return true;
}
else{
int arsen;
if (dis(info.arsenal[0].circle, me.circle) >= dis(info.arsenal[1].circle, me.circle))
arsen = 1; else arsen = 0;
if (info.arsenal[arsen].respawning_time == 0)
{
onMove1(order, info, myID, info.arsenal[arsen].circle);
return true;
}
if (dis(me.circle, info.obstacle[0]) >= dis(me.circle, info.obstacle[1]))
return onDodgeCircle(order, info, myID, tag.circle, info.obstacle[1]);
else
return onDodgeCircle(order, info, myID, tag.circle, info.obstacle[0]);
}
case WT_Cannon:
case WT_Apollo:
case WT_PlasmaTorch:
if ( (tag.remainingAmmo+2)*getBulletDamage(bullet.type) < me.hp||
(dis(me.circle, tag.circle) <= me.circle.r * 3) )
{
onMove1(order, info, myID, tag.circle );
return true;
}
else{
if (dis(me.circle, info.obstacle[0]) >= dis(me.circle, info.obstacle[1]))
return onDodgeCircle(order, info, myID, tag.circle, info.obstacle[1]);
else
return onDodgeCircle(order, info, myID, tag.circle, info.obstacle[0]);
}
//接近型躲避方案1
//AngleAdjust(tag_vrota);
//if (tag_vrota>me.engineRotation)
//{
// order.eturn = 1;
// order.run = 1;
//}
//else
//{
// order.eturn = -1;
// order.run = 1;
//}
//直接绕圈躲避方案2
return false;
break;
default:
//躲低速子弹,躲避方案3
if (!inHitRange)
{
return false;
}
if (me.engineRotation >= Rota_bulv_ag)
order.eturn = -1;
else
order.eturn = 1;
order.run = 1;
return true;
break;
}
break;
/*…………………………………………………………*/
return false;
}
}
bool RobotAI::onDodge2(RobotAI_Order& order, const RobotAI_BattlefieldInformation& info, const int myID)
//躲闪函数,如果发出了躲避命令,则返回true;
{
auto me = info.robotInformation[myID];
auto tag = info.robotInformation[1 - myID];
double dy = me.circle.y-tag.circle.y;
double dx = me.circle.x - tag.circle.x;
double Rota_bulv = tag.engineRotation-atan2(dy, dx) * 180 / PI;//子弹速度方向
AngleAdjust(Rota_bulv);
bool isNear;
switch (MyCar)
{
case AFV_Esaw:
case AFV_Prism:
case AFV_WT_Machinegun:
if (order.fire == 1)
return false;
switch (tag.weaponTypeName)
{
case WT_Shotgun:
if ((tag.remainingAmmo + 1) * 50 < me.hp ||
(dis(me.circle, tag.circle) <= me.circle.r *2))
{
onMove1(order, info, myID, tag.circle);
return true;
}
else{
int arsen;
if (dis(info.arsenal[0].circle, me.circle) >= dis(info.arsenal[1].circle, me.circle))
arsen = 1; else arsen = 0;
if (info.arsenal[arsen].respawning_time == 0&&
dis(info.arsenal[arsen].circle,tag.circle)>=700)
{
onMove1(order, info, myID, info.arsenal[arsen].circle);
return true;
}
if (dis(me.circle, info.obstacle[0]) >= dis(me.circle, info.obstacle[1]))
return onDodgeCircle(order, info, myID, tag.circle, info.obstacle[1]);
else
return onDodgeCircle(order, info, myID, tag.circle, info.obstacle[0]);
}
break;
case WT_Machinegun:
if ((tag.remainingAmmo + 5)*7 < me.hp||
(dis(me.circle, tag.circle) <= me.circle.r * 2)
)
{
onMove1(order, info, myID, tag.circle);
return true;
}
else{
int arsen;
if (dis(info.arsenal[0].circle, me.circle) >= dis(info.arsenal[1].circle, me.circle))
arsen = 1; else arsen = 0;
if (info.arsenal[arsen].respawning_time == 0)
{
onMove1(order, info, myID, info.arsenal[arsen].circle);
return true;
}
if (dis(me.circle, info.obstacle[0]) >= dis(me.circle, info.obstacle[1]))
return onDodgeCircle(order, info, myID, tag.circle, info.obstacle[1]);
else
return onDodgeCircle(order, info, myID, tag.circle, info.obstacle[0]);
}
break;
case WT_Cannon:
case WT_Apollo:
case WT_PlasmaTorch:
if ((tag.remainingAmmo + 2)*25 < me.hp ||
(dis(me.circle, tag.circle) <= me.circle.r * 3)
)
{
onMove1(order, info, myID, tag.circle);
return true;
}
int arsen;
if (dis(me.circle, info.obstacle[0]) >= dis(me.circle, info.obstacle[1]))
return onDodgeCircle(order, info, myID, tag.circle, info.obstacle[1]);
else
return onDodgeCircle(order, info, myID, tag.circle, info.obstacle[0]);
//接近型躲避方案1
//AngleAdjust(tag_vrota);
//if (tag_vrota>me.engineRotation)
//{
// order.eturn = 1;
// order.run = 1;
//}
//else
//{
// order.eturn = -1;
// order.run = 1;
//}
//直接绕圈躲避方案2
return false;
break;
default:
//躲低速子弹,躲避方案3
return false;
}
break;
/*…………………………………………………………*/
return false;
}
}
bool RobotAI::onDodgeCircle(RobotAI_Order& order, const RobotAI_BattlefieldInformation& info, const int myID, const Circle tag, const Circle ob){
if (HaveBarrier(info, myID, ob))
{
order.run = 0;
return true;
}
//if (dis(ob, info.robotInformation[myID].circle) <= ob.r * 2)
//{
// cout << "在圈后" << endl;
// order.run = 0;
// return true;
//}
double a = tag.x - ob.x;
double b = tag.y - ob.y;
double c = sqrt(a*a + b*b);
double tagx = ob.x - dis(info.robotInformation[myID].circle,ob)*a / c;
double tagy = ob.y - dis(info.robotInformation[myID].circle,ob)*b / c;
onMoveCircle(order, info, myID, tagx, tagy);
return true;
}
bool RobotAI::WillNotHit(const RobotAI_BulletInformation& bullet, const RobotAI_RobotInformation& rotinfo)
//判断在之后短时间内绝对不可能达到的子弹
{
double Rota_bul = atan2(bullet.vy, bullet.vx) * 180 / PI;//子弹射击方向角
AngleAdjust(Rota_bul);
Beam bulbeam;
bulbeam.x = bullet.circle.x;
bulbeam.y = bullet.circle.y;
bulbeam.rotation = Rota_bul;
bool HitTest=HitTestBeamCircle(bulbeam, rotinfo.circle);//碰撞测试
double Rota_engine = rotinfo.engineRotation;
double Rota_engine_downb = AnglePlus(Rota_engine, -90);
double Rota_engine_upb = AnglePlus(Rota_engine, 90);
bool vRotaTest = (Rota_bul<Rota_engine_upb && Rota_bul>Rota_engine_downb);//子弹角度测试
double dy = bullet.circle.y - rotinfo.circle.y;
double dx = bullet.circle.x - rotinfo.circle.x;
double Rota_place = atan2(dy, dx) * 180 / PI;
AngleAdjust(Rota_place);
bool pRotaTest = (Rota_place<Rota_engine_upb && Rota_place>Rota_engine_downb);
if (!HitTest&&vRotaTest&&pRotaTest)
return true;//如果不会打到了就返回true
else return false;
}
bool RobotAI::WillHit(const RobotAI_BulletInformation& bullet, const RobotAI_RobotInformation& rotinfo)
//判断子弹能否击中rotinfo
{
//double pointdis_me_bul = pointdis(
// bullet.circle.x,
// bullet.circle.y,
// bullet.circle.x + bullet.vx,
// bullet.circle.y + bullet.vy,
// rotinfo.circle.x,
// rotinfo.circle.y
// );
//double Rota = atan2(rotinfo.circle.y - bullet.circle.y,
// rotinfo.circle.x- bullet.circle.x) * 180 / PI;//子弹为原点,子弹和机甲中心所构成的角
//double Rota_bul = atan2(bullet.vy-rotinfo.vx, bullet.vx-rotinfo.vy) * 180 / PI;//子弹相对机甲射击方向角
//double dis_me_bul = sqrt(dis(bullet.circle, rotinfo.circle));
//double Rota_hit = atan2(
// rotinfo.circle.r,
// sqrt(dis_me_bul*dis_me_bul - rotinfo.circle.r*rotinfo.circle.r)
// );//能击中的角度范围
//if (
// pointdis_me_bul <= rotinfo.circle.r &&
// (Rota_bul<Rota + abvalue(Rota_hit) || Rota_bul>Rota - abvalue(Rota_hit))
// )
// return true;
//else
// return false;
double Rota_bul = atan2(bullet.vy, bullet.vx ) * 180 / PI;//子弹射击方向角
AngleAdjust(Rota_bul);
Beam bulbeam;
bulbeam.x = bullet.circle.x;
bulbeam.y = bullet.circle.y;
bulbeam.rotation = Rota_bul;
return HitTestBeamCircle(bulbeam, rotinfo.circle);
}
double RobotAI::abvalue(double x)
{
if (x >= 0)
return x;
else
return -x;
}
double RobotAI::pointdis(double x1, double y1, double x2, double y2, double x3, double y3)
//返回(x3,y3)到(x1,y1),(x2,y2)连线的距离
{
double A = (y2 - y1) / (x2 - x1);
double B = -1.0;
double C = y1 - (y2 - y1)*x1 / (x2 - x1);
double son = A*x3 + B*y3 + C;
double Abvalue = son / sqrt(A*A + B*B);
if (Abvalue > 0)
return Abvalue;
else
return -Abvalue;
}
double pointdis(double k, double x1, double y1, double x3, double y3)
{
double A = k;
double B = -1.0;
double C = y1 - k*x1;
double son = A*x3 + B*y3 + C;
double Abvalue = son / sqrt(A*A + B*B);
if (Abvalue > 0)
return Abvalue;
else
return -Abvalue;
}
double RobotAI::pointdis(const Circle a1, const Circle a2, const Circle a3)
{
return pointdis(a1.x, a1.y, a2.x, a2.y, a3.x, a3.y);
}
double RobotAI::dis(double x1, double y1, double x2, double y2) {
return sqrt((x2 - x1)*(x2 - x1) + (y2 - y1)*(y2 - y1));
}
double RobotAI::dis(const Circle& a, const Circle& b){
return dis(a.x, a.y, b.x, b.y);
}
|
[
"tairyguo@gmail.com"
] |
tairyguo@gmail.com
|
64a04d0fa7d7aa7e632d9071251e6a13e6b4fd5e
|
dc603c3d2bf052384f1157a6c9c83ff08a60bd86
|
/src/draw/css/parser/CSSTokenizerInputStream.h
|
e6e0e1b99252b3ea11746b07fdabb764cff7d964
|
[
"MIT"
] |
permissive
|
cyllene-project/Rubric
|
b9d9d6246904acbf1a8e84a6ec353f3db766c5ef
|
dae36e7a0801b35056dfb676c2f9c60faaaa09f8
|
refs/heads/master
| 2020-06-04T17:46:58.512132
| 2019-07-19T15:23:59
| 2019-07-19T15:23:59
| 192,129,479
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 4,204
|
h
|
// Copyright 2014 The Chromium Authors. All rights reserved.
// Copyright (C) 2016 Apple Inc. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#pragma once
namespace WebCore {
constexpr LChar kEndOfFileMarker = 0;
class CSSTokenizerInputStream {
CSSTokenizerInputStream(const CSSTokenizerInputStream&) = delete;
CSSTokenizerInputStream& operator=(const CSSTokenizerInputStream&) = delete;
public:
explicit CSSTokenizerInputStream(const std::string& input);
// Gets the char in the stream replacing NUL characters with a unicode
// replacement character. Will return (NUL) kEndOfFileMarker when at the
// end of the stream.
UChar nextInputChar() const
{
if (m_offset >= m_stringLength)
return '\0';
UChar result = (*m_string)[m_offset];
return result ? result : 0xFFFD;
}
// Gets the char at lookaheadOffset from the current stream position. Will
// return NUL (kEndOfFileMarker) if the stream position is at the end.
// NOTE: This may *also* return NUL if there's one in the input! Never
// compare the return value to '\0'.
UChar peekWithoutReplacement(unsigned lookaheadOffset) const
{
if ((m_offset + lookaheadOffset) >= m_stringLength)
return '\0';
return (*m_string)[m_offset + lookaheadOffset];
}
void advance(unsigned offset = 1) { m_offset += offset; }
void pushBack(UChar cc)
{
--m_offset;
ASSERT_UNUSED(cc, nextInputChar() == cc);
}
double getDouble(unsigned start, unsigned end) const;
template<bool characterPredicate(UChar)>
unsigned skipWhilePredicate(unsigned offset)
{
if (m_string->is8Bit()) {
const LChar* characters8 = m_string->characters8();
while ((m_offset + offset) < m_stringLength && characterPredicate(characters8[m_offset + offset]))
++offset;
} else {
const UChar* characters16 = m_string->characters16();
while ((m_offset + offset) < m_stringLength && characterPredicate(characters16[m_offset + offset]))
++offset;
}
return offset;
}
void advanceUntilNonWhitespace();
unsigned length() const { return m_stringLength; }
unsigned offset() const { return std::min(m_offset, m_stringLength); }
std::string_view rangeAt(unsigned start, unsigned length) const
{
assert(start + length <= m_stringLength);
return StringView(m_string.get()).substring(start, length); // FIXME: Should make a constructor on StringView for this.
}
private:
size_t m_offset;
const size_t m_stringLength;
std::shared_ptr<StringImpl> m_string;
};
} // namespace WebCore
|
[
"chebizarro@gmail.com"
] |
chebizarro@gmail.com
|
7069e7eb869ab45174e16cf9c0fdc79c5c50204b
|
47f53bed9d6a4e8f2f84c1931ebe773cf58256b9
|
/lib/CATGUI/CAT3DView.cpp
|
a3c09b951b17fd161c0ff6fad34572b0fa2cb43b
|
[
"Libpng",
"LicenseRef-scancode-unknown-license-reference",
"MIT",
"Zlib",
"LicenseRef-scancode-warranty-disclaimer"
] |
permissive
|
michaelellison/Mike-s-Demo-App
|
a105ac46bbd29df0403423190579d24e0c4a4746
|
c0ba505e935bb1d98925c3b6bf04d3d5e2afa19a
|
refs/heads/master
| 2021-01-17T06:28:45.247677
| 2011-06-09T00:25:00
| 2011-06-09T00:25:00
| 1,840,197
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 18,890
|
cpp
|
// ------------------------------------------------------------------
// CAT3DView.cpp
// Copyright (c) 2002-2011 Mike Ellison.
// Quick hack to wedge it from old GUI to new.... needs work.
// ------------------------------------------------------------------
#include "CAT3DView.h"
#include "CATWindow.h"
#include "CATCursor.h"
#include "CATUtil.h"
#include "CATEventDefs.h"
// Include opengl libs for 3D
#include "gl\gl.h"
#include "gl\glu.h"
CATFloat32 kMinRotate = 0.0001f;
int kRotateTimer = 100;
CAT3DView::CAT3DView( const CATString& element,
const CATString& rootDir)
: CATControlWnd(element, rootDir)
{
// Defaults
// Register a window class for the 3D view
fWindowAtom = 0;
fDisplayList = -1;
fAxisList = -1;
fRotateSpeed = 0.0f;
f3DXYTranslating = false; // Are we moving the view?
f3DXYRotating = false; // Rotating it?
f3DZTranslating = false; // Translating on Z?
f3DZRotating = false; // Rotating on Z?
fStereoView = false; // Stereo mode?
fFullScreen = false; // Full screen mode?
fTracking = false;
fLastMouseX = 0; // Last known position of the mouse with a button down
fLastMouseY = 0;
memset(&fOrgRect,0,sizeof(RECT));
// Start out at origin for view
fViewX = fViewY = fViewZ = 0.0;
fViewRotX = fViewRotY = fViewRotZ = 0.0;
fCursor.SetType(CATCURSOR_HAND);
}
// Destructor
CAT3DView::~CAT3DView()
{
// Kill the display list if we got one
if (fDisplayList != -1)
{
glDeleteLists(fDisplayList,1);
}
if (fAxisList != -1)
{
glDeleteLists(fAxisList,1);
}
}
// We draw the 3D stuff after the main CodeRock GUI draws, so that
// it won't be scaled with the other stuff.
//
void CAT3DView::PostDraw( CATDRAWCONTEXT hdc,
const CATRect& updateRect)
{
HDC odc;
PAINTSTRUCT ps;
// Begin a paint operation
odc = BeginPaint(fHwnd, &ps);
// Make the OpenGL RC current for drawing
::wglMakeCurrent(odc,fHRC);
// Clear the window - we should double buffer here....
::glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
// Store the current matrix - we should be in modelview mode right now
::glPushMatrix();
// Translate first, then rotate Z/Y/X to our current camera view
::glTranslatef(fViewX, fViewY, fViewZ);
::glRotatef(fViewRotZ,0,0,1);
::glRotatef(fViewRotY,0,1,0);
::glRotatef(fViewRotX,1,0,0);
GLfloat ambient[] = {1.6f, 1.6f, 1.6f, 1.0f};
glLightModelfv(GL_LIGHT_MODEL_AMBIENT, ambient);
GLfloat lightColor1[] = {1.0f, 1.0f, 1.0f, 1.0f};
GLfloat lightPos1[] = {fViewX, fViewY, fMaxZ, 0.0f};
glLightfv(GL_LIGHT0, GL_DIFFUSE, lightColor1);
glLightfv(GL_LIGHT0, GL_POSITION, lightPos1);
// Draw anything in our display list
if (fDisplayList != -1)
{
::glCallList(fDisplayList);
}
if (fAxisList != -1)
{
::glCallList(fAxisList);
}
// Restore the default view matrix
::glPopMatrix();
// Flush out all drawing commands
::glFlush();
::SwapBuffers(odc);
// End the session with the OpenGL RC
::wglMakeCurrent(NULL,NULL);
// End Paint session
EndPaint(fHwnd,&ps);
}
// This is more or less our OnSize() event, 'cept it's different
// for Post-drawn controls as they don't have the scaling and such
// applied to them like all the other controls do...
CATResult CAT3DView::RectFromAttribs()
{
CATResult res = CATControlWnd::RectFromAttribs();
CATRect rect = this->GetRectAbs();
// Move the 3D window to our new location - don't redraw it yet
MoveWindow( fHwnd,
rect.left,
rect.top,
rect.Width(),
rect.Height(),
FALSE);
// Make the OpenGL RC current for our window
HDC hdc = GetDC(fHwnd);
::wglMakeCurrent(hdc,fHRC);
GLsizei glw, glh;
glw = rect.Width();
glh = rect.Height();
// Reset the viewport, persepective, and matrix
::glViewport(0,0,glw,glh);
::glMatrixMode(GL_PROJECTION);
::glLoadIdentity();
::gluPerspective(45.0,
(CATFloat64)glw/(CATFloat64)glh,
fabs(fMaxZ-fMinZ)/10, // 1 to 100 for viewing. Hey, sounds good to me ;)
fabs(fMaxZ-fMinZ)*10); // might actually calc this or something later, but for objects
// with a 12" z-depth, should work pretty well...
// Switch to model view for our next draw, and reset the matrix
// We perform the view translations/rotations during the draw.
::glMatrixMode(GL_MODELVIEW);
::glLoadIdentity();
// Release the RC and DC
::wglMakeCurrent(NULL,NULL);
ReleaseDC(fHwnd, hdc);
return res;
}
bool CAT3DView::OnControlEvent(const CATEvent& eventMsg, CATInt32& returnVal)
{
switch (eventMsg.fEventCode)
{
case CATEVENT_WINDOWS_EVENT:
{
returnVal = (CATInt32)CAT3DViewProc(
(HWND)eventMsg.fIntParam1,
(UINT)eventMsg.fIntParam2,
(WPARAM)eventMsg.fIntParam3,
(LPARAM)eventMsg.fIntParam4);
}
break;
default:
break;
}
return false;
}
// This is the raw Win32 window proc for the 3D view window.
// Handle mousing and stuff here...
LRESULT CALLBACK CAT3DView::CAT3DViewProc( HWND hwnd,
UINT uMsg,
WPARAM wParam,
LPARAM lParam)
{
// Get our "this" pointer from the window. WARNING: will not be true on WM_CREATE
// (it is set on WM_CREATE though from the datastructure in lParam for window creation)
CAT3DView* wnd3d = (CAT3DView*)GetWindowLongPtr(hwnd,GWLP_USERDATA);
switch (uMsg)
{
// Mouse has left the building.
// Bail out of any mouse-down stuff we were doing.
case WM_KILLFOCUS:
wnd3d->f3DXYTranslating = false;
wnd3d->f3DXYRotating = false;
wnd3d->f3DZTranslating = false;
wnd3d->f3DZRotating = false;
break;
// This gets called anytime the mouse moves within our window
// check button-down motions
case WM_MOUSEMOVE:
{
// Find the XY offsets from the last location of the mouse
CATFloat32 xOff = (CATFloat32)(((CATInt16)LOWORD(lParam) - wnd3d->fLastMouseX));
CATFloat32 yOff = (CATFloat32)(((CATInt16)HIWORD(lParam) - wnd3d->fLastMouseY));
// Figure out what to do
wnd3d->On3DMouseMove(
xOff,
yOff,
(wParam & MK_LBUTTON) > 0,
(wParam & MK_MBUTTON) > 0,
(wParam & MK_RBUTTON) > 0);
// Save the last mouse position
wnd3d->fLastMouseX = (CATInt16)LOWORD(lParam);
wnd3d->fLastMouseY = (CATInt16)HIWORD(lParam);
return TRUE;
}
break;
case WM_TIMER:
if ((wParam == kRotateTimer) && (wnd3d->fRotateSpeed > kMinRotate))
{
// This time, the ratios are based from a full circle / window size
CATFloat32 ratio = (360.0f) / (CATFloat32)(wnd3d->fRect.right - wnd3d->fRect.left);
wnd3d->fViewRotY += wnd3d->fRotateSpeed * ratio;
while (wnd3d->fViewRotY > 360)
wnd3d->fViewRotY -= 360;
wnd3d->MarkDirty();
}
break;
case WM_CREATE:
// Store our "this" pointer with the window
{
LPCREATESTRUCT lpc = (LPCREATESTRUCT)lParam;
SetWindowLongPtr(hwnd,GWLP_USERDATA,(LONG)lpc->lpCreateParams);
// SetWindowLong's don't take effect until the next SetWindowPos, so flush it now
// before we get a message that might want to use the this pointer...
SetWindowPos(hwnd,0,0,0,0,0,SWP_FRAMECHANGED|SWP_NOMOVE|SWP_NOZORDER|SWP_NOSIZE);
::SetTimer(hwnd,kRotateTimer,40,0);
}
return 0;
break;
// Yukky blinkies go away.
case WM_ERASEBKGND:
return TRUE;
break;
case WM_DESTROY:
// When the window is destroyed, we should destroy our
// OpenGL context as well.
::KillTimer(hwnd,kRotateTimer);
::wglMakeCurrent(0,0);
::wglDeleteContext(wnd3d->fHRC);
wnd3d->fHRC = 0;
return 0;
break;
}
return DefWindowProc(hwnd,uMsg,wParam,lParam);
}
void CAT3DView::SetRotateSpeed(CATFloat32 speed)
{
fRotateSpeed = speed;
}
// Handle mouse movements / buttons in 3D window
void CAT3DView::On3DMouseMove(CATFloat32 xOff, CATFloat32 yOff, bool leftBtn, bool midBtn, bool rightBtn)
{
CATFloat32 xRatio; // x-motion ratio, generally a ratio of "What we're adjusting" / "Width of Window Mouse is in"
CATFloat32 yRatio; // y-motion ratio, generally a ratio of "What we're adjusting" / "Height of Window Mouse is in"
CATFloat32 ratio; // If x and y adjust similar stuff, we might want to pick a speed that is somewhere between
// the two but equal so things work as expected for the operator...
bool wasTracking = fTracking;
// Calc width/height of the view rectangle
CATInt32 wndWidth = this->fRect.right - this->fRect.left;
CATInt32 wndHeight = this->fRect.bottom - this->fRect.top;
// right mouse button controls normal translation on XY axis
if (rightBtn)
{
// If we just put the button down, then don't translate anything yet,
// just set the location for the last mouse position and start the
// translation process...
if (!f3DXYTranslating)
{
f3DXYTranslating = true;
}
else
{
// xRatio is the (width of the object) / (width of view window)
// yRatio is the (height of object) / (height of view window)
//
// With these ratios, we can move the mouse exactly one screen to move the object across the screen.
// However, if we got a long skinny object, this "feels" weird, so we take the average of the two.
xRatio = (fMaxX - fMinX) / (CATFloat32)(wndWidth);
yRatio = (fMaxY - fMinY) / (CATFloat32)(wndHeight);
// Average ratio
ratio = (xRatio + yRatio)/2;
// Translate XY by our mouse offsets * ratio.
// Note that for Y, the view's (0,0) point is in top-left, so we invert motion.
fViewX += xOff*ratio;
fViewY -= yOff*ratio;
}
}
else
{
// No more mouse button = no more translating.
f3DXYTranslating = false;
}
// Middle button - Z translation
// Z translation is performed similarly to XY translation,
// only it's just on the Z axis.
//
// Note that if both the middle AND the left button are down, we're going to do
// Z-rotation instead (further down in dah code...)
if (midBtn && !(leftBtn))
{
if (!f3DZTranslating)
{
f3DZTranslating = true;
f3DZRotating = false;
}
else
{
// We allow motion on either X or Y by the mouse to change Z
xRatio = (fMaxZ - fMinZ) / (CATFloat32)(wndWidth);
yRatio = (fMaxZ - fMinZ) / (CATFloat32)(wndHeight);
// Translation on Z = xMovement*xRatio + yMovement*yRatio
fViewZ += ((xOff * xRatio) + (yOff*yRatio));
}
}
else
{
f3DZTranslating = false;
}
// Now for rotational fun -
// Left button (alone) performs rotation on the X and Y Axis
// Note: if both left and middle are down, we do Z-Rotation (see farther below...)
if (leftBtn && !(midBtn))
{
if (!f3DXYRotating)
{
f3DXYRotating = true;
f3DZRotating = false;
}
else
{
// This time, the ratios are based from a full circle / window size
xRatio = (360.0f) / (CATFloat32)(wndWidth);
yRatio = (360.0f) / (CATFloat32)(wndHeight);
ratio = (xRatio + yRatio)/2;
// Add rotations to our view
fViewRotX += yOff * ratio;
fViewRotY += xOff * ratio;
// Keep the rotations legal in degrees
// We use while in case for some reason the mouse movement
// was really really big - probably not necessary, but not
// particularly costly either.
while (fViewRotX > 360) fViewRotX -= 360;
while (fViewRotX < 0) fViewRotX += 360;
while (fViewRotY > 360) fViewRotY -= 360;
while (fViewRotY < 0) fViewRotY += 360;
}
}
else
{
// End rotating stuff.
f3DXYRotating = false;
}
// Z-Rotation
// Left button with Middle button performs rotation on the Z Axis
if (leftBtn && midBtn)
{
if (!f3DZRotating)
{
f3DZTranslating = false;
f3DXYRotating = false;
f3DZRotating = true;
}
else
{
// This time, the ratios are based from a full circle / window size
xRatio = (360.0f) / (CATFloat32)(wndWidth);
yRatio = (360.0f) / (CATFloat32)(wndHeight);
// Z rotation is a combination of y movement and x movement
fViewRotZ += (yOff * yRatio) + (xOff * xRatio);
// Keep the rotations legal in degrees
while (fViewRotZ > 360) fViewRotZ -= 360;
while (fViewRotZ < 0) fViewRotZ += 360;
}
}
else
{
// End rotating stuff.
f3DZRotating = false;
}
// If we're doing something, force a redraw.
if (f3DXYRotating || f3DXYTranslating || f3DZTranslating || f3DZRotating)
{
MarkDirty();
}
if (!wasTracking)
{
if (leftBtn || rightBtn || midBtn)
{
fTracking = true;
::SetCapture(fControlWnd);
}
}
else
{
if (fTracking)
{
if (!(leftBtn || rightBtn || midBtn))
{
::ReleaseCapture();
fTracking = false;
}
}
}
}
// Center the viewport to our object
void CAT3DView::CenterViewport()
{
// Zero rotations
this->fViewRotX = 0.0;
this->fViewRotY = 0.0;
this->fViewRotZ = 0.0;
// Look at center, a little back on Z
this->fViewX = (fMaxX + fMinX)/2;
this->fViewY = (fMaxY + fMinY)/2;
this->fViewZ = (CATFloat32)((fMinZ - fabs((fMaxZ - fMinZ))*2 ));
}
void CAT3DView::SetAxisDisplay(bool on, bool corner)
{
// Connect to the OpenGL RC
HDC hdc = GetDC(this->fHwnd);
::wglMakeCurrent(hdc,fHRC);
// Delete old axis display
if (fAxisList != -1)
{
::glDeleteLists(fAxisList,1);
fAxisList = -1;
}
// If we are just turning it off, bail now.
if (on == false)
{
return;
}
// Create a new list
fAxisList = ::glGenLists(1);
// Start list compiling
::glNewList(fAxisList,GL_COMPILE);
{
::glBegin(GL_LINES);
// Draw vertex lines
// X-axis
glColor3f(1,0,0);
glVertex3f(0,0,0);
glVertex3f(12,0,0);
// Y - axis
glColor3f(0,1,0);
glVertex3f(0,0,0);
glVertex3f(0,12,0);
// Z - axis
glColor3f(0,0,1);
glVertex3f(0,0,0);
glVertex3f(0,0,12);
::glEnd();
// End the list operations
} ::glEndList();
// Release OpenGL and DC
::wglMakeCurrent(NULL,NULL);
ReleaseDC(this->fHwnd, hdc);
}
// Auto-facet for scanned information
void CAT3DView::Set3dFacets( CATC3DPoint* pointArray, CATInt32 numScans, CATInt32 height, bool triangles)
{
// Connect to the OpenGL RC
HDC hdc = GetDC(this->fHwnd);
::wglMakeCurrent(hdc,fHRC);
// Nuke the old display list if there is one
if (fDisplayList != -1)
{
::glDeleteLists(fDisplayList,1);
fDisplayList = -1;
}
if ((pointArray == 0) || (numScans == 0) || (height == 0))
{
return;
}
// Create a new list
fDisplayList = ::glGenLists(1);
CATC3DPoint* curPoint = pointArray;
// We want to track our min/max positions of the object -
// start 'em out here or bail if we can't get the point.
fMinX = fMaxX = (CATFloat32)curPoint->x;
fMinY = fMaxY = -(CATFloat32)curPoint->y;
fMinZ = fMaxZ = (CATFloat32)curPoint->z;
// Start list compiling
::glNewList(fDisplayList,GL_COMPILE);
{
::glBegin(GL_QUADS);
{
// Loop through all the points in the list and
// store 'em into the display list. Also
// compile our min/max locations for the object.
for (CATInt32 x = 0; x < numScans - 1; x++)
{
for (CATInt32 y = 0; y < height - 1; y++)
{
CATC3DPoint *tlPoint, *trPoint, *blPoint, *brPoint;
tlPoint = &pointArray[x*height + y];
trPoint = &pointArray[(x + 1)*height + y];
blPoint = &pointArray[x*height + y + 1];
brPoint = &pointArray[(x + 1)*height + y + 1];
if ((tlPoint->x == 0) && (tlPoint->y == 0) && (tlPoint->z == 0)) continue;
if ((trPoint->x == 0) && (trPoint->y == 0) && (trPoint->z == 0)) continue;
if ((blPoint->x == 0) && (blPoint->y == 0) && (blPoint->z == 0)) continue;
if ((brPoint->x == 0) && (brPoint->y == 0) && (brPoint->z == 0)) continue;
::glColor3f( ((GLfloat)(tlPoint->color.r)/255.0f),
((GLfloat)(tlPoint->color.g)/255.0f),
((GLfloat)(tlPoint->color.b)/255.0f));
// Set location
::glVertex3f( (CATFloat32)tlPoint->x,
-(CATFloat32)tlPoint->y,
(CATFloat32)tlPoint->z );
::glColor3f( ((GLfloat)(trPoint->color.r)/255.0f),
((GLfloat)(trPoint->color.g)/255.0f),
((GLfloat)(trPoint->color.b)/255.0f));
// Set location
::glVertex3f( (CATFloat32)trPoint->x,
-(CATFloat32)trPoint->y,
(CATFloat32)trPoint->z );
::glColor3f( ((GLfloat)(brPoint->color.r)/255.0f),
((GLfloat)(brPoint->color.g)/255.0f),
((GLfloat)(brPoint->color.b)/255.0f));
// Set location
::glVertex3f( (CATFloat32)brPoint->x,
-(CATFloat32)brPoint->y,
(CATFloat32)brPoint->z );
::glColor3f( ((GLfloat)(blPoint->color.r)/255.0f),
((GLfloat)(blPoint->color.g)/255.0f),
((GLfloat)(blPoint->color.b)/255.0f));
// Set location
::glVertex3f( (CATFloat32)blPoint->x,
-(CATFloat32)blPoint->y,
(CATFloat32)blPoint->z );
// Track min/max
fMinX = min(fMinX,(CATFloat32)tlPoint->x);
fMaxX = max(fMaxX,(CATFloat32)tlPoint->x);
fMinY = min(fMinY,-(CATFloat32)tlPoint->y);
fMaxY = max(fMaxY,-(CATFloat32)tlPoint->y);
fMinZ = min(fMinZ,(CATFloat32)tlPoint->z);
fMaxZ = max(fMaxZ,(CATFloat32)tlPoint->z);
}
}
}
// End the points operations
::glEnd();
// End the list operations
} ::glEndList();
// Center the viewport to look at the object
RectFromAttribs();
CenterViewport();
// Release OpenGL and DC
::wglMakeCurrent(NULL,NULL);
ReleaseDC(this->fHwnd, hdc);
}
void CAT3DView::OnParentCreate()
{
fWindowType = "CAT3DView";
// Register a window class for us..
// Set up the Win32 structure for creating a window for our 3D OpenGL view
WNDCLASS wc;
wc.style = CS_HREDRAW|CS_VREDRAW;
wc.lpfnWndProc = CAT3DViewProc;
wc.cbClsExtra = 0;
wc.cbWndExtra = 0;
wc.hInstance = gApp->GetInstance();
wc.hIcon = NULL;
wc.hCursor = 0;
wc.hbrBackground = (HBRUSH)(COLOR_WINDOW+1);
wc.lpszMenuName = 0;
wc.lpszClassName = fWindowType;
fWindowAtom = RegisterClass(&wc);
CATControlWnd::OnParentCreate();
fHwnd = CATControlWnd::GetControlWndHndl();
// Now create the OpenGL objects needed for this window....
// Why telling it I want a damned color pixel takes so many zeros,
// I may never understand...
PIXELFORMATDESCRIPTOR pfd = {
sizeof(PIXELFORMATDESCRIPTOR),
1,
PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER,
PFD_TYPE_RGBA,
24,
0,0,0,
0,0,0,
0,0,
0,0,0,0,0,
16,
0,
0,
PFD_MAIN_PLANE,
0,
0,
0,
0};
// Set pixel format and get an openGL RC
HDC hdc = GetDC(fHwnd);
// Pick our pixel format for the DC and set it
fPixelFormat = ::ChoosePixelFormat(hdc,&pfd);
SetPixelFormat(hdc,fPixelFormat,&pfd);
// Create the openGL context and store
fHRC = ::wglCreateContext(hdc);
// Make it current
::wglMakeCurrent(hdc,fHRC);
// Set our clear color to 0
::glClearColor(0.0f,0.0f,0.0f,0.0f);
::glClearDepth(1.0f);
// Enable depth checking and smooth points at size 2
::glEnable(GL_DEPTH_TEST);
::glEnable(GL_POINT_SMOOTH);
glEnable(GL_COLOR_MATERIAL);
glEnable(GL_DEPTH_TEST);
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glEnable(GL_LIGHTING);
glEnable(GL_LIGHT0);
glShadeModel(GL_SMOOTH);
::glPointSize(2);
// Unset the context
::wglMakeCurrent(0,0);
ReleaseDC(fHwnd, hdc);
}
|
[
"me@michaelellison.me"
] |
me@michaelellison.me
|
c65385ba0b57b9c24e5148df1b2ea84f08dee214
|
de3b55be8224007e01e79000d8d9800ff9da1ac3
|
/hash/hash/Hashing.cpp
|
81d96805c3977095d23806b627f7ac9b2dbf8c0e
|
[] |
no_license
|
katherin2096/ADA
|
7f22cb566239fec5dba36200f6d12fa403008d26
|
ac1c0c73c2d0808cd2024f3ce185099e1460f18e
|
refs/heads/master
| 2022-06-03T03:10:38.815242
| 2020-05-01T00:20:26
| 2020-05-01T00:20:26
| 260,348,475
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,003
|
cpp
|
#include "Hashing.h"
#include <cstdio>
#include <string>
#include <fstream>
#include "Hashing.h"
#include <iostream>
//#include <bits/types/FILE.h>
#include <cstring>
#include <tuple>
#include <functional>
using namespace std;
Hashing::Hashing(int size, string filepath) {
this->size = size;
this->filepath = filepath;
setup();
}
// Main Functions
Node Hashing::search(int key) {
return get<1>(search_data(key, &Hashing::is_same_key));
}
double Hashing::time_spent() {
int amount = 0;
Node node = Node::empty_node();
int items_count = 0;
for (int i = 0; i < size; i++) {
node = get_item(i);
if (!node.is_empty) {
items_count++;
amount += time_spent(node.key);
}
}
return amount / (double)items_count;
}
// Search type functions
bool Hashing::is_same_key(Node node, int key) {
return !node.is_empty && node.key == key;
}
bool Hashing::empty_node(Node node, int key) {
return node.is_empty;
}
bool Hashing::previous_node(Node node, int key) {
return get_item(node.next).key == key;
}
// Advanced
void Hashing::delete_item(int position) {
set_item(Node::empty_node(), position);
}
int Hashing::item_position(int key) {
return get<0>(search_data(key, &Hashing::is_same_key));
}
int Hashing::time_spent(int key) {
return get<2>(search_data(key, &Hashing::is_same_key));
}
// Receives key to be used to find positions, and criteria
// that will identify proper position, if exists
// Returns position, node at position and amount of iterations to find
tuple<int, Node, int> Hashing::search_data(
int key,
bool(Hashing::* criteria)(Node, int),
int(Hashing::* position_calculator)(int, int, Node)) {
int position = (this->*position_calculator)(-1, key, Node::empty_node());
Node node = get_item(position);
int counter = 1;
while (!(this->*criteria)(node, key)) {
position = (this->*position_calculator)(position, key, node);
// Has searched entire file
if (counter > this->size || position == -1) {
return make_tuple(-1, Node::empty_node(), counter);
}
node = get_item(position);
counter++;
}
return make_tuple(position, node, counter);
}
// Config
void Hashing::setup() {
// Check if file exists
if (!ifstream(filepath)) {
fstream file(filepath, ios::binary | ios::app);
if (file.is_open()) {
// Fills file with empty nodes
for (int i = 0; i < this->size; i++) {
Node node = Node::empty_node();
file.write((char*)&node, sizeof(Node));
}
file.close();
}
}
}
// File manipulation
Node Hashing::get_item(int position) {
ifstream file(filepath, ios::binary);
Node* searched = (Node*)malloc(sizeof(Node));
if (file.is_open()) {
file.seekg(sizeof(Node) * position, ios_base::beg);
file.read((char*)searched, sizeof(Node));
file.close();
}
return *searched;
}
void Hashing::set_item(Node node, int position) {
fstream file(filepath, ios::binary | ios::in | ios::out);
if (file.is_open()) {
file.seekp(sizeof(Node) * position, ios_base::beg);
file.write((char*)&node, sizeof(Node));
file.close();
}
}
|
[
"38145569+katherin2096@users.noreply.github.com"
] |
38145569+katherin2096@users.noreply.github.com
|
f31b657238964f0d43a1a68e3fc918d1ff027da2
|
7d66dfb8210fb31ecce8a7d758f8ffa0d6b06b8a
|
/chrome/browser/chromeos/login/login_ui_keyboard_browsertest.cc
|
3e5b8d1b6df38f41b8e5e142e6c46c6ef3c673ac
|
[
"BSD-3-Clause"
] |
permissive
|
souldanger/iridium-browser
|
e5cb80d7e9bc8b54b1cd8b187913584d4f60ef06
|
260fd220fbd10a976ebd32d2266f05070b0e421e
|
refs/heads/master
| 2023-02-24T09:03:11.671406
| 2015-05-04T12:30:46
| 2017-04-24T13:59:34
| 90,760,286
| 1
| 0
| null | 2017-05-09T15:11:56
| 2017-05-09T15:11:56
| null |
UTF-8
|
C++
| false
| false
| 9,415
|
cc
|
// Copyright 2014 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.
#include "base/command_line.h"
#include "base/location.h"
#include "base/message_loop/message_loop.h"
#include "base/single_thread_task_runner.h"
#include "base/threading/thread_task_runner_handle.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/chromeos/input_method/input_method_persistence.h"
#include "chrome/browser/chromeos/language_preferences.h"
#include "chrome/browser/chromeos/login/login_manager_test.h"
#include "chrome/browser/chromeos/login/startup_utils.h"
#include "chrome/browser/chromeos/login/test/oobe_screen_waiter.h"
#include "chrome/browser/chromeos/login/ui/login_display_host.h"
#include "chrome/browser/ui/webui/chromeos/login/signin_screen_handler.h"
#include "chrome/common/pref_names.h"
#include "chromeos/chromeos_switches.h"
#include "components/prefs/pref_service.h"
#include "content/public/test/test_utils.h"
namespace chromeos {
namespace {
const char kTestUser1[] = "test-user1@gmail.com";
const char kTestUser2[] = "test-user2@gmail.com";
const char kTestUser3[] = "test-user3@gmail.com";
void Append_en_US_InputMethods(std::vector<std::string>* out) {
out->push_back("xkb:us::eng");
out->push_back("xkb:us:intl:eng");
out->push_back("xkb:us:altgr-intl:eng");
out->push_back("xkb:us:dvorak:eng");
out->push_back("xkb:us:dvp:eng");
out->push_back("xkb:us:colemak:eng");
out->push_back("xkb:us:workman:eng");
out->push_back("xkb:us:workman-intl:eng");
chromeos::input_method::InputMethodManager::Get()->MigrateInputMethods(out);
}
class FocusPODWaiter {
public:
FocusPODWaiter() : focused_(false), runner_(new content::MessageLoopRunner) {
GetOobeUI()->signin_screen_handler()->SetFocusPODCallbackForTesting(
base::Bind(&FocusPODWaiter::OnFocusPOD, base::Unretained(this)));
}
~FocusPODWaiter() {
GetOobeUI()->signin_screen_handler()->SetFocusPODCallbackForTesting(
base::Closure());
}
void OnFocusPOD() {
ASSERT_TRUE(base::MessageLoopForUI::IsCurrent());
focused_ = true;
if (runner_.get()) {
base::ThreadTaskRunnerHandle::Get()->PostTask(
FROM_HERE,
base::Bind(&FocusPODWaiter::ExitMessageLoop, base::Unretained(this)));
}
}
void ExitMessageLoop() { runner_->Quit(); }
void Wait() {
if (focused_)
return;
runner_->Run();
GetOobeUI()->signin_screen_handler()->SetFocusPODCallbackForTesting(
base::Closure());
runner_ = NULL;
}
private:
OobeUI* GetOobeUI() {
OobeUI* oobe_ui = LoginDisplayHost::default_host()->GetOobeUI();
CHECK(oobe_ui);
return oobe_ui;
}
bool focused_;
scoped_refptr<content::MessageLoopRunner> runner_;
};
} // anonymous namespace
class LoginUIKeyboardTest : public chromeos::LoginManagerTest {
public:
LoginUIKeyboardTest() : LoginManagerTest(false) {}
~LoginUIKeyboardTest() override {}
void SetUpOnMainThread() override {
user_input_methods.push_back("xkb:fr::fra");
user_input_methods.push_back("xkb:de::ger");
chromeos::input_method::InputMethodManager::Get()->MigrateInputMethods(
&user_input_methods);
LoginManagerTest::SetUpOnMainThread();
}
// Should be called from PRE_ test so that local_state is saved to disk, and
// reloaded in the main test.
void InitUserLRUInputMethod() {
PrefService* local_state = g_browser_process->local_state();
input_method::SetUserLRUInputMethodPreferenceForTesting(
kTestUser1, user_input_methods[0], local_state);
input_method::SetUserLRUInputMethodPreferenceForTesting(
kTestUser2, user_input_methods[1], local_state);
}
protected:
std::vector<std::string> user_input_methods;
};
IN_PROC_BROWSER_TEST_F(LoginUIKeyboardTest, PRE_CheckPODScreenDefault) {
RegisterUser(kTestUser1);
RegisterUser(kTestUser2);
StartupUtils::MarkOobeCompleted();
}
// Check default IME initialization, when there is no IME configuration in
// local_state.
IN_PROC_BROWSER_TEST_F(LoginUIKeyboardTest, CheckPODScreenDefault) {
js_checker().ExpectEQ("$('pod-row').pods.length", 2);
std::vector<std::string> expected_input_methods;
Append_en_US_InputMethods(&expected_input_methods);
EXPECT_EQ(expected_input_methods,
input_method::InputMethodManager::Get()
->GetActiveIMEState()
->GetActiveInputMethodIds());
}
IN_PROC_BROWSER_TEST_F(LoginUIKeyboardTest, PRE_CheckPODScreenWithUsers) {
RegisterUser(kTestUser1);
RegisterUser(kTestUser2);
InitUserLRUInputMethod();
StartupUtils::MarkOobeCompleted();
}
// TODO(crbug.com/602951): Test is flaky.
IN_PROC_BROWSER_TEST_F(LoginUIKeyboardTest, DISABLED_CheckPODScreenWithUsers) {
js_checker().ExpectEQ("$('pod-row').pods.length", 2);
EXPECT_EQ(user_input_methods[0],
input_method::InputMethodManager::Get()
->GetActiveIMEState()
->GetCurrentInputMethod()
.id());
std::vector<std::string> expected_input_methods;
Append_en_US_InputMethods(&expected_input_methods);
// Active IM for the first user (active user POD).
expected_input_methods.push_back(user_input_methods[0]);
EXPECT_EQ(expected_input_methods,
input_method::InputMethodManager::Get()
->GetActiveIMEState()
->GetActiveInputMethodIds());
FocusPODWaiter waiter;
js_checker().Evaluate("$('pod-row').focusPod($('pod-row').pods[1])");
waiter.Wait();
EXPECT_EQ(user_input_methods[1],
input_method::InputMethodManager::Get()
->GetActiveIMEState()
->GetCurrentInputMethod()
.id());
}
class LoginUIKeyboardTestWithUsersAndOwner : public chromeos::LoginManagerTest {
public:
LoginUIKeyboardTestWithUsersAndOwner() : LoginManagerTest(false) {}
~LoginUIKeyboardTestWithUsersAndOwner() override {}
void SetUpCommandLine(base::CommandLine* command_line) override {
LoginManagerTest::SetUpCommandLine(command_line);
command_line->AppendSwitch(switches::kStubCrosSettings);
LoginManagerTest::SetUpCommandLine(command_line);
}
void SetUpOnMainThread() override {
user_input_methods.push_back("xkb:fr::fra");
user_input_methods.push_back("xkb:de::ger");
user_input_methods.push_back("xkb:pl::pol");
chromeos::input_method::InputMethodManager::Get()->MigrateInputMethods(
&user_input_methods);
CrosSettings::Get()->SetString(kDeviceOwner, kTestUser3);
LoginManagerTest::SetUpOnMainThread();
}
// Should be called from PRE_ test so that local_state is saved to disk, and
// reloaded in the main test.
void InitUserLRUInputMethod() {
PrefService* local_state = g_browser_process->local_state();
input_method::SetUserLRUInputMethodPreferenceForTesting(
kTestUser1, user_input_methods[0], local_state);
input_method::SetUserLRUInputMethodPreferenceForTesting(
kTestUser2, user_input_methods[1], local_state);
input_method::SetUserLRUInputMethodPreferenceForTesting(
kTestUser3, user_input_methods[2], local_state);
local_state->SetString(language_prefs::kPreferredKeyboardLayout,
user_input_methods[2]);
}
void CheckGaiaKeyboard();
protected:
std::vector<std::string> user_input_methods;
};
void LoginUIKeyboardTestWithUsersAndOwner::CheckGaiaKeyboard() {
std::vector<std::string> expected_input_methods;
// kPreferredKeyboardLayout is now set to last focused POD.
expected_input_methods.push_back(user_input_methods[0]);
// Locale default input methods (the first one also is hardware IM).
Append_en_US_InputMethods(&expected_input_methods);
EXPECT_EQ(expected_input_methods,
input_method::InputMethodManager::Get()
->GetActiveIMEState()
->GetActiveInputMethodIds());
}
IN_PROC_BROWSER_TEST_F(LoginUIKeyboardTestWithUsersAndOwner,
PRE_CheckPODScreenKeyboard) {
RegisterUser(kTestUser1);
RegisterUser(kTestUser2);
RegisterUser(kTestUser3);
InitUserLRUInputMethod();
StartupUtils::MarkOobeCompleted();
}
IN_PROC_BROWSER_TEST_F(LoginUIKeyboardTestWithUsersAndOwner,
CheckPODScreenKeyboard) {
js_checker().ExpectEQ("$('pod-row').pods.length", 3);
std::vector<std::string> expected_input_methods;
// Owner input method.
expected_input_methods.push_back(user_input_methods[2]);
// Locale default input methods (the first one also is hardware IM).
Append_en_US_InputMethods(&expected_input_methods);
// Active IM for the first user (active user POD).
expected_input_methods.push_back(user_input_methods[0]);
EXPECT_EQ(expected_input_methods,
input_method::InputMethodManager::Get()
->GetActiveIMEState()
->GetActiveInputMethodIds());
// Switch to Gaia.
js_checker().Evaluate("$('add-user-button').click()");
OobeScreenWaiter(OobeScreen::SCREEN_GAIA_SIGNIN).Wait();
CheckGaiaKeyboard();
// Switch back.
js_checker().Evaluate("$('gaia-signin').cancel()");
OobeScreenWaiter(OobeScreen::SCREEN_ACCOUNT_PICKER).Wait();
EXPECT_EQ(expected_input_methods,
input_method::InputMethodManager::Get()
->GetActiveIMEState()
->GetActiveInputMethodIds());
}
} // namespace chromeos
|
[
"commit-bot@chromium.org"
] |
commit-bot@chromium.org
|
1f80fab377c76adb00557d6376cda5f006c46e52
|
bfe6df5301221a56f2328923506cc4a1839e8077
|
/Version 1.x/Source/dpagesourcewindow.cc
|
8b0795b7dfb6ce82afe0e8568ae018c48fe220b3
|
[] |
no_license
|
elementakion/dooble
|
64f7ca6f8468f3e15d65841b647b99f93f0efdeb
|
5406278697eb462c0a3a5d388067738bbf60aa79
|
refs/heads/master
| 2021-01-14T09:55:13.356385
| 2015-04-03T16:51:24
| 2015-04-03T16:51:24
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 11,343
|
cc
|
/*
** Copyright (c) 2008 - present, Alexis Megas.
** All rights reserved.
**
** Redistribution and use in source and binary forms, with or without
** modification, are permitted provided that the following conditions
** are met:
** 1. Redistributions of source code must retain the above copyright
** notice, this list of conditions and the following disclaimer.
** 2. 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.
** 3. The name of the author may not be used to endorse or promote products
** derived from Dooble without specific prior written permission.
**
** DOOBLE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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
** DOOBLE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <QUrl>
#include <QFile>
#include <QPrinter>
#include <QSettings>
#include <QCloseEvent>
#include <QFileDialog>
#include <QTextStream>
#include <QPrintDialog>
#include <QDesktopServices>
#include <QPrintPreviewDialog>
#include "dooble.h"
#include "dpagesourcewindow.h"
dpagesourcewindow::dpagesourcewindow(QWidget *parent,
const QUrl &url,
const QString &html):QMainWindow()
{
ui.setupUi(this);
#ifdef Q_OS_MAC
setAttribute(Qt::WA_MacMetalStyle, false);
#if QT_VERSION >= 0x050000
setWindowFlags(windowFlags() & ~Qt::WindowFullscreenButtonHint);
#endif
statusBar()->setSizeGripEnabled(false);
#endif
m_findLineEditPalette = ui.findLineEdit->palette();
ui.textBrowser->setPlainText(html);
connect(ui.actionPrint, SIGNAL(triggered(void)), this,
SLOT(slotPrint(void)));
connect(ui.actionPrint_Preview, SIGNAL(triggered(void)), this,
SLOT(slotPrintPreview(void)));
connect(ui.actionClose, SIGNAL(triggered(void)), this,
SLOT(slotClose(void)));
connect(ui.actionFind, SIGNAL(triggered(void)), this,
SLOT(slotShowFind(void)));
connect(ui.actionSave_As, SIGNAL(triggered(void)), this,
SLOT(slotSavePageAs(void)));
connect(ui.hideFindToolButton, SIGNAL(clicked(void)), this,
SLOT(slotHideFind(void)));
connect(ui.findLineEdit, SIGNAL(returnPressed(void)), this,
SLOT(slotNextFind(void)));
connect(ui.findLineEdit, SIGNAL(textEdited(const QString &)), this,
SLOT(slotNextFind(const QString &)));
connect(ui.actionWrap_Lines, SIGNAL(toggled(bool)),
this, SLOT(slotWrapLines(bool)));
connect(ui.nextToolButton, SIGNAL(clicked(void)),
this, SLOT(slotNextFind(void)));
connect(ui.previousToolButton, SIGNAL(clicked(void)),
this, SLOT(slotPreviousFind(void)));
if(!url.isEmpty())
setWindowTitle(tr("Dooble Web Browser - Page Source (") +
url.toString(QUrl::StripTrailingSlash) + tr(")"));
else
setWindowTitle(tr("Dooble Web Browser - Page Source"));
if(url.path().isEmpty() || url.path() == "/")
fileName = "source";
else if(url.path().contains("/"))
{
fileName = url.path();
fileName = fileName.mid(fileName.lastIndexOf("/") + 1);
}
else
fileName = url.path();
ui.actionWrap_Lines->setChecked
(dooble::s_settings.value("pageSource/wrapLines", false).toBool());
slotWrapLines(ui.actionWrap_Lines->isChecked());
slotSetIcons();
slotHideFind();
if(parent)
{
if(parent->height() == height() &&
parent->width() == width())
setGeometry(parent->geometry());
else
{
QPoint p(parent->pos());
int X = 0;
int Y = 0;
if(parent->width() >= width())
X = p.x() + (parent->width() - width()) / 2;
else
X = p.x() - (width() - parent->width()) / 2;
if(parent && parent->height() >= height())
Y = p.y() + (parent->height() - height()) / 2;
else
Y = p.y() - (height() - parent->height()) / 2;
move(X, Y);
}
}
else
move(100, 100);
show();
}
dpagesourcewindow::~dpagesourcewindow()
{
}
void dpagesourcewindow::slotClose(void)
{
close();
}
void dpagesourcewindow::closeEvent(QCloseEvent *event)
{
QMainWindow::closeEvent(event);
deleteLater();
}
void dpagesourcewindow::slotPrint(void)
{
QPrinter printer;
QPrintDialog printDialog(&printer, this);
#ifdef Q_OS_MAC
printDialog.setAttribute(Qt::WA_MacMetalStyle, false);
#endif
if(printDialog.exec() == QDialog::Accepted)
ui.textBrowser->print(&printer);
}
void dpagesourcewindow::slotPrintPreview(void)
{
QPrinter printer;
QPrintPreviewDialog printDialog(&printer, this);
#ifdef Q_OS_MAC
printDialog.setAttribute(Qt::WA_MacMetalStyle, false);
#endif
printDialog.setWindowModality(Qt::WindowModal);
connect(&printDialog,
SIGNAL(paintRequested(QPrinter *)),
this,
SLOT(slotTextEditPrintPreview(QPrinter *)));
if(printDialog.exec() == QDialog::Accepted)
ui.textBrowser->print(&printer);
}
void dpagesourcewindow::slotTextEditPrintPreview(QPrinter *printer)
{
if(printer)
ui.textBrowser->print(printer);
}
void dpagesourcewindow::slotHideFind(void)
{
ui.findFrame->setVisible(false);
}
void dpagesourcewindow::slotShowFind(void)
{
ui.findFrame->setVisible(true);
ui.findLineEdit->setFocus();
ui.findLineEdit->selectAll();
#ifdef Q_OS_MAC
static int fixed = 0;
if(!fixed)
{
QColor color(255, 255, 255);
QPalette palette(ui.findLineEdit->palette());
palette.setColor(ui.findLineEdit->backgroundRole(), color);
ui.findLineEdit->setPalette(palette);
fixed = 1;
}
#endif
}
void dpagesourcewindow::keyPressEvent(QKeyEvent *event)
{
if(event && event->key() == Qt::Key_Escape)
ui.findFrame->setVisible(false);
QMainWindow::keyPressEvent(event);
}
void dpagesourcewindow::slotNextFind(void)
{
slotNextFind(ui.findLineEdit->text());
}
void dpagesourcewindow::slotNextFind(const QString &text)
{
QTextDocument::FindFlags findFlags = 0;
if(ui.matchCaseCheckBox->isChecked())
findFlags |= QTextDocument::FindCaseSensitively;
if(ui.textBrowser->find(text, findFlags) || text.isEmpty())
{
ui.findLineEdit->setPalette(m_findLineEditPalette);
if(text.isEmpty())
ui.textBrowser->moveCursor(QTextCursor::PreviousCharacter);
}
else
{
if(ui.textBrowser->textCursor().anchor() ==
ui.textBrowser->textCursor().position())
{
if(!ui.textBrowser->textCursor().atEnd())
{
QColor color(240, 128, 128); // Light Coral
QPalette palette(ui.findLineEdit->palette());
palette.setColor(ui.findLineEdit->backgroundRole(), color);
ui.findLineEdit->setPalette(palette);
}
else
ui.textBrowser->moveCursor(QTextCursor::Start);
}
else
{
ui.textBrowser->moveCursor(QTextCursor::Start);
slotNextFind(text);
}
}
}
void dpagesourcewindow::slotPreviousFind(void)
{
slotPreviousFind(ui.findLineEdit->text());
}
void dpagesourcewindow::slotPreviousFind(const QString &text)
{
QTextDocument::FindFlags findFlags = QTextDocument::FindBackward;
if(ui.matchCaseCheckBox->isChecked())
findFlags |= QTextDocument::FindCaseSensitively;
if(ui.textBrowser->find(text, findFlags) || text.isEmpty())
ui.findLineEdit->setPalette(m_findLineEditPalette);
else
{
if(ui.textBrowser->textCursor().anchor() ==
ui.textBrowser->textCursor().position())
{
QColor color(240, 128, 128); // Light Coral
QPalette palette(ui.findLineEdit->palette());
palette.setColor(ui.findLineEdit->backgroundRole(), color);
ui.findLineEdit->setPalette(palette);
}
else
{
ui.textBrowser->moveCursor(QTextCursor::End);
slotPreviousFind(text);
}
}
}
void dpagesourcewindow::slotSavePageAs(void)
{
QString path(dooble::s_settings.value("settingsWindow/myRetrievedFiles",
"").toString());
QFileInfo fileInfo(path);
QFileDialog fileDialog(this);
if(!fileInfo.isReadable() || !fileInfo.isWritable())
#if QT_VERSION >= 0x050000
path = QStandardPaths::writableLocation(QStandardPaths::DesktopLocation);
#else
path = QDesktopServices::storageLocation
(QDesktopServices::DesktopLocation);
#endif
#ifdef Q_OS_MAC
fileDialog.setAttribute(Qt::WA_MacMetalStyle, false);
#endif
fileDialog.setOption
(QFileDialog::DontUseNativeDialog,
!dooble::s_settings.value("settingsWindow/useNativeFileDialogs",
false).toBool());
fileDialog.setWindowTitle(tr("Dooble Web Browser: Save Page Source As"));
fileDialog.setFileMode(QFileDialog::AnyFile);
fileDialog.setDirectory(path);
fileDialog.setLabelText(QFileDialog::Accept, tr("Save"));
fileDialog.setAcceptMode(QFileDialog::AcceptSave);
fileDialog.selectFile(fileName);
if(fileDialog.exec() == QDialog::Accepted)
{
QStringList list(fileDialog.selectedFiles());
if(!list.isEmpty())
{
QFile file(list.at(0));
if(file.open(QIODevice::WriteOnly | QIODevice::Text))
{
QTextStream out(&file);
out << ui.textBrowser->toPlainText();
file.close();
}
}
}
}
void dpagesourcewindow::slotWrapLines(bool checked)
{
QSettings settings;
settings.setValue("pageSource/wrapLines", checked);
dooble::s_settings["pageSource/wrapLines"] = checked;
if(checked)
ui.textBrowser->setLineWrapMode(QTextEdit::WidgetWidth);
else
ui.textBrowser->setLineWrapMode(QTextEdit::NoWrap);
}
void dpagesourcewindow::slotSetIcons(void)
{
QSettings settings
(dooble::s_settings.value("iconSet").toString(), QSettings::IniFormat);
settings.beginGroup("pageSourceWindow");
ui.actionPrint->setIcon(QIcon(settings.value("actionPrint").toString()));
ui.actionPrint_Preview->setIcon
(QIcon(settings.value("actionPrint_Preview").toString()));
ui.actionClose->setIcon(QIcon(settings.value("actionClose").toString()));
ui.actionFind->setIcon(QIcon(settings.value("actionFind").toString()));
ui.actionSave_As->setIcon
(QIcon(settings.value("actionSave_As").toString()));
ui.hideFindToolButton->setIcon
(QIcon(settings.value("hideFindToolButton").toString()));
ui.nextToolButton->setIcon
(QIcon(settings.value("nextToolButton").toString()));
ui.previousToolButton->setIcon
(QIcon(settings.value("previousToolButton").toString()));
setWindowIcon(QIcon(settings.value("windowIcon").toString()));
}
#ifdef Q_OS_MAC
#if QT_VERSION >= 0x050000 && QT_VERSION < 0x050300
bool dpagesourcewindow::event(QEvent *event)
{
if(event)
if(event->type() == QEvent::WindowStateChange)
if(windowState() == Qt::WindowNoState)
{
/*
** Minimizing the window on OS 10.6.8 and Qt 5.x will cause
** the window to become stale once it has resurfaced.
*/
hide();
show();
update();
}
return QMainWindow::event(event);
}
#else
bool dpagesourcewindow::event(QEvent *event)
{
return QMainWindow::event(event);
}
#endif
#else
bool dpagesourcewindow::event(QEvent *event)
{
return QMainWindow::event(event);
}
#endif
|
[
"textbrowser@gmail.com"
] |
textbrowser@gmail.com
|
01e8ec44b80deffdd92d33706685a9deabbffac3
|
ea12fed4c32e9c7992956419eb3e2bace91f063a
|
/zombie/code/zombie/nscene/src/nscene/nsurfacenode_main.cc
|
74d5e83ef12b4c20b501095b24518e59c6cfe3b1
|
[] |
no_license
|
ugozapad/TheZombieEngine
|
832492930df28c28cd349673f79f3609b1fe7190
|
8e8c3e6225c2ed93e07287356def9fbdeacf3d6a
|
refs/heads/master
| 2020-04-30T11:35:36.258363
| 2011-02-24T14:18:43
| 2011-02-24T14:18:43
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 10,575
|
cc
|
#include "precompiled/pchnscene.h"
//------------------------------------------------------------------------------
// nsurfacenode_main.cc
// (C) 2002 RadonLabs GmbH
//------------------------------------------------------------------------------
#include "nscene/nsurfacenode.h"
#include "nscene/nsceneshader.h"
#include "nscene/nscenegraph.h"
#include "nscene/nshadertree.h"
#include "gfx2/ngfxserver2.h"
#include "gfx2/nshader2.h"
#include "gfx2/ntexture2.h"
#include "kernel/ntimeserver.h"
#include "nscene/ncscene.h"
#include "entity/nentity.h"
#include "kernel/ndebug.h"
#include "nscene/nanimator.h"
nNebulaScriptClass(nSurfaceNode, "nabstractshadernode");
//------------------------------------------------------------------------------
/**
*/
nSurfaceNode::nSurfaceNode() :
shaderArray(4, 4)
{
// empty
}
//------------------------------------------------------------------------------
/**
*/
nSurfaceNode::~nSurfaceNode()
{
this->UnloadResources();
}
//------------------------------------------------------------------------------
/**
Unload all shaders.
*/
void
nSurfaceNode::UnloadShaders()
{
int i;
for (i = 0; i < this->shaderArray.Size(); i++)
{
if (this->shaderArray[i].IsShaderValid())
{
this->shaderArray[i].GetShader()->Release();
this->shaderArray[i].Invalidate();
}
}
for (i = 0; i < this->shaderTreeArray.Size(); ++i)
{
if (this->shaderTreeArray[i].isvalid())
{
this->shaderTreeArray[i]->Release();
this->shaderTreeArray[i].invalidate();
}
}
}
//------------------------------------------------------------------------------
/**
Load shader resources.
*/
bool
nSurfaceNode::LoadShaders()
{
// load shaders
int i;
for (i = 0; i < this->shaderArray.Size(); i++)
{
ShaderEntry& shaderEntry = this->shaderArray[i];
if (!shaderEntry.IsShaderValid() && shaderEntry.GetName())
{
#if 0 // keep this commented while the shader database is not used
// try to get shader by name from shader repository
int shaderIndex = nSceneServer::Instance()->FindShader(shaderEntry.GetName());
if (shaderIndex != -1)
{
nSceneShader& sceneShader = nSceneServer::Instance()->GetShaderAt(shaderIndex);
if (!sceneShader.IsValid())
{
sceneShader.Validate();
n_assert(sceneShader.IsValid());
}
sceneShader.GetShaderObject()->AddRef();
shaderEntry.SetShaderIndex(shaderIndex);
shaderEntry.SetShader(sceneShader.GetShaderObject());
}
else
#endif
{
// create a new empty shader object
nShader2* shd = nGfxServer2::Instance()->NewShader(shaderEntry.GetName());
n_assert(shd);
if (!shd->IsLoaded())
{
// load shader resource file
shd->SetFilename(shaderEntry.GetName());
}
if (shd)
{
// register shader object in scene shader database
nSceneShader sceneShader;
sceneShader.SetShader(shaderEntry.GetName());// filename
sceneShader.SetShaderName(shaderEntry.GetName());// shader name
int shaderIndex = nSceneServer::Instance()->FindShader(shaderEntry.GetName());
if (shaderIndex == -1)
{
shaderIndex = nSceneServer::Instance()->AddShader(sceneShader);
n_assert(shaderIndex != -1);
}
// set shader object and index for local entry
shaderEntry.SetShader(shd);
shaderEntry.shaderIndex = shaderIndex;
// create a degenerate decision tree for use in the render path
nShaderTree* shaderTree = static_cast<nShaderTree*>( kernelServer->New("nshadertree") );
n_assert( shaderTree );
shaderTree->BeginNode( nVariable::InvalidHandle, 0 );
shaderTree->SetShaderObject( shd );
shaderTree->SetShaderIndexAt( 0, shaderIndex );
shaderTree->EndNode();
this->shaderTreeArray.Set( shaderEntry.GetPassIndex(), shaderTree );
}
}
}
}
return true;
}
//------------------------------------------------------------------------------
/**
Load the resources needed by this object.
*/
bool
nSurfaceNode::LoadResources()
{
if (this->LoadShaders())
{
if (nAbstractShaderNode::LoadResources())
{
return true;
}
}
return false;
}
//------------------------------------------------------------------------------
/**
Unload the resources if refcount has reached zero.
*/
void
nSurfaceNode::UnloadResources()
{
nAbstractShaderNode::UnloadResources();
this->UnloadShaders();
}
//------------------------------------------------------------------------------
/**
Find shader object associated with fourcc code.
*/
nSurfaceNode::ShaderEntry*
nSurfaceNode::FindShaderEntry(nFourCC fourcc) const
{
int i;
int numShaders = this->shaderArray.Size();
for (i = 0; i < numShaders; i++)
{
ShaderEntry& shaderEntry = this->shaderArray[i];
if (shaderEntry.GetFourCC() == fourcc)
{
return &shaderEntry;
}
}
// fallthrough: no loaded shader matches this fourcc code
return 0;
}
//------------------------------------------------------------------------------
/**
Return number of levels.
*/
int
nSurfaceNode::GetNumLevels()
{
return (this->shaderArray.Size() > 0) ? 1 : 0;
}
//------------------------------------------------------------------------------
/**
Return number of passes for a level
*/
int
nSurfaceNode::GetNumLevelPasses(int /*level*/)
{
return this->shaderArray.Size();
}
//------------------------------------------------------------------------------
/**
Return number of passes for a level
*/
int
nSurfaceNode::GetLevelPassIndex(int level, int pass)
{
n_assert_return((level == 0) && (pass < this->shaderArray.Size()), -1);
return this->shaderArray[pass].GetPassIndex();
}
//------------------------------------------------------------------------------
/**
*/
nShaderTree*
nSurfaceNode::GetShaderTree(int /*level*/, int passIndex)
{
n_assert(passIndex < this->shaderTreeArray.Size());
return this->shaderTreeArray[passIndex];
}
//------------------------------------------------------------------------------
/**
*/
void
nSurfaceNode::SetShader(nFourCC fourcc, const char* name)
{
n_assert(name);
ShaderEntry* shaderEntry = this->FindShaderEntry(fourcc);
if (shaderEntry)
{
shaderEntry->Invalidate();
shaderEntry->SetName(name);
}
else
{
ShaderEntry newShaderEntry(fourcc, name);
this->shaderArray.Append(newShaderEntry);
}
}
//------------------------------------------------------------------------------
/**
*/
const char*
nSurfaceNode::GetShader(nFourCC fourcc) const
{
ShaderEntry* shaderEntry = this->FindShaderEntry(fourcc);
if (shaderEntry)
{
return shaderEntry->GetName();
}
else
{
return 0;
}
}
//------------------------------------------------------------------------------
/**
*/
bool
nSurfaceNode::IsTextureUsed(nShaderState::Param /*param*/)
{
#if 0
// check in all shaders if anywhere the texture specified by param is used
int i;
int numShaders = this->shaderArray.Size();
for (i = 0; i < numShaders; i++)
{
const ShaderEntry& shaderEntry = this->shaderArray[i];
// first be sure that the shader entry could be loaded
if (shaderEntry.IsShaderValid())
{
nShader2* shader = shaderEntry.GetShader();
if (shader->IsParameterUsed(param))
{
return true;
}
}
}
// fallthrough: texture not used by any shader
return false;
#else
return true;
#endif
}
//------------------------------------------------------------------------------
/**
Setup shader attributes before rendering instances of this scene node.
FIXME
*/
bool
nSurfaceNode::Apply(nSceneGraph* sceneGraph)
{
n_assert(sceneGraph);
int shaderIndex = sceneGraph->GetShaderIndex();
if (shaderIndex != -1)
{
nSceneShader& sceneShader = nSceneServer::Instance()->GetShaderAt(shaderIndex);
nGfxServer2::Instance()->SetShader(sceneShader.GetShaderObject());
nAbstractShaderNode::Apply(sceneGraph);
return true;
}
return false;
}
//------------------------------------------------------------------------------
/**
Update shader and set as current shader in the gfx server.
- 15-Jan-04 floh AreResourcesValid()/LoadResources() moved to scene server
*/
bool
nSurfaceNode::Render(nSceneGraph* sceneGraph, nEntityObject* entityObject)
{
n_assert(sceneGraph);
n_assert(entityObject);
//nShader2* shader = nSceneServer::Instance()->GetShaderAt(sceneGraph->GetShaderIndex()).GetShaderObject();
// invoke shader manipulators
this->InvokeAnimators(entityObject);
/*
//nGfxServer2* gfxServer = nGfxServer2::Instance();
// set texture transforms (that can be animated)
//n_assert(nGfxServer2::MaxTextureStages >= 4);
static matrix44 m;
this->textureTransform[0].getmatrix44(m);
gfxServer->SetTransform(nGfxServer2::Texture0, m);
this->textureTransform[1].getmatrix44(m);
gfxServer->SetTransform(nGfxServer2::Texture1, m);
*/
// transfer the rest of per-instance (animated, overriden) parameters
// per instance-set parameters are handled at Apply()
// also, shader overrides are handled at nGeometryNode::Render()
nAbstractShaderNode::Render(sceneGraph, entityObject);
return true;
}
|
[
"magarcias@c1fa4281-9647-0410-8f2c-f027dd5e0a91"
] |
magarcias@c1fa4281-9647-0410-8f2c-f027dd5e0a91
|
cf0079b50392ef28a65d7161fffcfeff53a44a11
|
da9985577c307a6f2b00f2d6afd6654d06a9230a
|
/src/commonlib/kslib/anet/src/anet/ipackethandler.h
|
67106ae44aa87599e7de99427aca9a8f0c8c6c6a
|
[] |
no_license
|
charpty/kingso
|
e720bd247efd7b1b7674c089947d9adb9963f4a1
|
c65cd16a7aa38f9dfa37f66320bc8e42b30c8662
|
refs/heads/master
| 2023-08-09T09:47:51.121529
| 2019-03-03T15:28:14
| 2019-03-03T15:28:14
| 173,532,203
| 4
| 12
| null | 2020-10-13T12:12:18
| 2019-03-03T04:51:21
|
C++
|
UTF-8
|
C++
| false
| false
| 1,088
|
h
|
#ifndef ANET_IPACKETHANDLER_H_
#define ANET_IPACKETHANDLER_H_
namespace anet {
class Packet;
class IPacketHandler {
public:
enum HPRetCode {
KEEP_CHANNEL = 0,
CLOSE_CHANNEL = 1,
FREE_CHANNEL = 2
};
/**
* This function is used in Client. When ANET receive response,
* it will call handlePacket() to deal with response packet.
* User use ANET send requests and use handlePacket() deal
* with response. This function is Called in
* Connection::handlePacket().
* In some exceptions, ControlPacket(such as TimeoutPacket,
* BadPacket) will be received. Obviously, you should consider
* all these exceptions in you implementation.
*
* @param packet response packet or ControlPacket
* @param args it's used to indicate which request packet this
* respose packet corresponding. It's the same as args you used
* in Connection::posePacket().
* @return not used temporary.
*/
virtual HPRetCode handlePacket(Packet *packet, void *args) = 0;
};
}
#endif /*IPACHETHANDLER_H_*/
|
[
"charpty@gmail.com"
] |
charpty@gmail.com
|
7589d43a7b791287c6505d22fb04531097645f27
|
83ed1e2f176133c03a5f6dfa504b8df15ae71efb
|
/c/DMD/DMD10/Variable_r_ext/txt2txt.cpp
|
97dc75deb9d9109340dc85d80c2aada4a6021394
|
[] |
no_license
|
jmborr/code
|
319db14f28e1dea27f9fc703be629f171e6bd95f
|
32720b57699bf01803367566cdc5fff2b6bce810
|
refs/heads/master
| 2022-03-09T16:11:07.455402
| 2019-10-28T15:03:01
| 2019-10-28T15:03:01
| 23,627,627
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 59,752
|
cpp
|
#include "pseudoAA.h"
#include "pseudoPep.h"
#include "PDBLib.h"
#include "random.h"
#include "pseudoTXT.h"
#include <cstring>
using namespace std;
int isKeywords(string line){
//cout << sizeof(txtKeyWords)/sizeof(string) << endl;
for(int i=0; i<sizeof(txtKeyWords)/sizeof(string); i++){
if(txtKeyWords[i]==line) return i+1;
}
return 0;
}
inline void str2ch(const string line, char* buf){
line.copy(buf, line.length());
buf[line.length()]='\0';
}
void process_txt(const char* txt, double& size, vector<double>& xyz){
ifstream in(txt);
string line;
int theKey=0;
int tmpKey=0;
char buf[1024];
int iatom, itype;
double x,y,z;
double vx, vy, vz;
while(getline(in, line)){
tmpKey=isKeywords(line);
if(theKey){
if(!tmpKey){
//not a key
if(!isComments(line)){
//not a comment --> data entry line
switch(theKey){
case 1://SYSTEM SIZE
str2ch(line, buf);
sscanf(buf, "%lf", &size);//read size
break;
case 8://list of atoms
str2ch(line, buf);
sscanf(buf, "%ld %ld %lf %lf %lf %lf %lf %lf",
&iatom, &itype, &x, &y, &z, &vx, &vy, &vz);
xyz.push_back(x);
xyz.push_back(y);
xyz.push_back(z);
break;
default:
break;
}
}
}
else if(theKey!=tmpKey){
theKey=tmpKey;
}
}
else if(tmpKey){
theKey=tmpKey;
}
}
in.close();
}
void single_bond_sprint(char* buf, double ave, double dev){
sprintf(buf, "%lf %lf", ave*(1.0-dev), ave*(1.0+dev));
}
void single_bond_sprint_len(char* buf, double ave, double len_dev){
sprintf(buf, "%lf %lf", ave-len_dev, ave+len_dev);
}
void double_bond_sprint(char* buf, double l_ave, double l_dev,
double r_ave, double r_dev){
if(l_ave*(1.0+l_dev) > r_ave*(1.0-r_dev)){
cerr << "Error: overlaping bonds" << endl;
exit(1);
}
sprintf(buf, "%lf %lf %lf %lf %lf %lf",
l_ave*(1.0-l_dev), l_ave*(1.0+l_dev), -max_height,
r_ave*(1.0-r_dev), max_height, r_ave*(1.0+r_dev));
}
void type_sprint(char* buf, dmd_atom_t type, double mass, double hdr, double ir){
if(ir==0) ir = hdr + eps;
sprintf(buf, "%ld %lf %lf %lf", type, mass, hdr, ir);
}
double getTriDev_angle(double a, double b, double dev, double theta, double& c){
c = sqrt(a*a+b*b-2.0*a*b*cos(theta));
double dummy = (a-b*cos(theta))/c*a;
double dummy1= (b-a*cos(theta))/c*b;
dummy = sqrt(dummy*dummy + dummy1*dummy1)*dev;
dummy1 = dummy/c;
return dummy1;
}
double getTriDev_length(double a, double b, double dev, double c){
double theta = acos((a*a+b*b-c*c)/(2.0*a*b));
double dummy = (a-b*cos(theta))/c*a;
double dummy1= (b-a*cos(theta))/c*b;
dummy = sqrt(dummy*dummy + dummy1*dummy1)*dev;
dummy1 = dummy/c;
return dummy1;
}
void list_atom_sprint(char* buf, int index, dmd_atom_t type, vec& r, vec& v){
sprintf(buf,"%-4ld %-4ld %18.13lf %18.13lf %18.13lf %18.13lf %18.13lf %18.13lf",
index, type, r.getX(), r.getY(), r.getZ(),
v.getX(), v.getY(), v.getZ());
}
void el_col_sprint(char* buf, dmd_atom_t a, dmd_atom_t b, double min_d){
sprintf(buf, "%ld %ld %lf", a, b, min_d);
}
void sel_col_sprint(char* buf, dmd_atom_t a, dmd_atom_t b, double hdr, double min_d,
int nstep=1, double e=Dihedral_E){
double delta = min_d - hdr;
double step = delta/nstep;
int pt = sprintf(buf, "%ld %ld %lf", a, b, hdr);
double dist = hdr;
for(int i=0; i<nstep; i++){
dist += step;
pt += sprintf(&buf[pt], " %lf %lf", dist, e);
}
}
void hp_sprint(char* buf, dmd_atom_t a, dmd_atom_t b,
double hd, double id, double e){
if( ir_ext>0 ){
sprintf(buf, "%ld %ld %lf %lf %lf %lf %lf",
a, b, hd, id, -fabs(e), id+ir_ext, -fabs(e)/2.0);
}
else{ sprintf(buf, "%ld %ld %lf %lf %lf", a, b, hd, id, -fabs(e));}
}
void sb_sprint(char* buf, dmd_atom_t a, dmd_atom_t b,
double hd, double id, double e){
if( ir_ext>0 ){
sprintf(buf, "%ld %ld %lf %lf %lf %lf %lf %lf %lf",
a, b, hd, id-ir_ext, -fabs(e), id, -fabs(e)/4.0, id+ir_ext,
-fabs(e)/4.0);
}
else{
sprintf(buf, "%ld %ld %lf %lf %lf", a, b, hd, id, -fabs(e));
}
}
void rsb_sprint(char* buf, dmd_atom_t a, dmd_atom_t b,
double hd, double id, double e){
if( ir_ext>0 ){
sprintf(buf, "%ld %ld %lf %lf %lf %lf %lf %lf %lf",
a, b, hd, id-ir_ext, fabs(e), id, fabs(e)/4.0,
id+ir_ext, fabs(e)/4.0);
}
else{
sprintf(buf, "%ld %ld %lf %lf %lf", a, b, hd, id, fabs(e));
}
}
void printSYS_SIZE(ostream& out, double size, int dimension=3){
out << txtKeyWords[SYS_SIZE] << endl;
for(int i=0; i<dimension; i++){
out << size << " ";
}
out << endl;
}
void printNUM_ATOMS(ostream& out, pseudoPep& p,
int np=1, int ng=0){
out << txtKeyWords[NUM_ATOMS] << endl;
int nTotal = ng;
pseudoAA* lastAA = p.getResidue(p.getLength()-1);
atom* lastAtom = NULL;
if(lastAtom=lastAA->getG2());
else if(lastAtom=lastAA->getD());
else if(lastAtom=lastAA->getG());
else if(lastAtom=lastAA->getCB());
else if(lastAtom=lastAA->getCA());
else{
cerr << "last amino acids is not a protein!!" << endl;
exit(1);
}
nTotal += np*lastAtom->getIndex();
out << nTotal << endl;
}
void printATOM_TYPE(ostream& out){
out << txtKeyWords[TYPE_ATOMS] << endl;
char buf[1024];
/*generic atoms*/
/*N*/
type_sprint(buf, _N_, N_M, N_HDR, 0.0);
out << buf << endl;
/*C*/
type_sprint(buf, _C_, C_M, C_HDR, 0.0);
out << buf << endl;
/*O*/
type_sprint(buf, _O_, O_M, O_HDR, 0.0);
out << buf << endl;
/*CA*/
type_sprint(buf, _CA_, CA_M, CA_HDR, 0.0);
out << buf << endl;
/*CB*/
type_sprint(buf, _CB_, CB_M, CB_HDR, 0.0);
out << buf << endl;
/*PRO_N*/
type_sprint(buf, _PRO_N_, N_M, N_HDR, 0.0);
out << buf << endl;
/*NP*/
type_sprint(buf, _N_HB_, N_M, N_HDR, 0.0);
out << buf << endl;
/*OP*/
type_sprint(buf, _O_HB_, O_M, O_HDR, 0.0);
out << buf << endl;
/*CB atoms*/
int type_shift = _CYS_CB_;
for(int i=0; i<20; i++){
dmd_atom_t cb_t = static_cast<dmd_atom_t>(type_shift + i);
if(i!=GLY){
type_sprint(buf, cb_t, CB_M, CB_HDR, 0.0);
}
else{/*gly CB is a never-used type*/
type_sprint(buf, cb_t, 1.0, eps, eps);
}
out << buf << endl;
}
/*CG atoms*/
type_shift = _CYS_CG_;
for(int i=0; i<20; i++){
dmd_atom_t cg_t = static_cast<dmd_atom_t>(type_shift + i);
if(i!=ALA && i!=GLY){
const double* cg_para = G1_CONST[i];
type_sprint(buf, cg_t, cg_para[G1_M], cg_para[G1_HDR], cg_para[G1_IR]);
}
else{/*ala, gly CG is a never-used type*/
type_sprint(buf, cg_t, 1.0, eps, eps);
}
out << buf << endl;
}
/*CG2 atoms*/
/*ILE*/
type_sprint(buf, _ILE_CG2_, ILE_G2[G2_M], ILE_G2[G2_HDR], ILE_G2[G2_IR]);
out << buf << endl;
/*THR*/
type_sprint(buf, _THR_CG2_, THR_G2[G2_M], THR_G2[G2_HDR], THR_G2[G2_IR]);
out << buf << endl;
/*VAL*/
type_sprint(buf, _VAL_CG2_, VAL_G2[G2_M], VAL_G2[G2_HDR], VAL_G2[G2_IR]);
out << buf << endl;
/*CD atoms*/
/*ARG*/
type_sprint(buf, _ARG_CD_, ARG_D[D_M], ARG_D[D_HDR], ARG_D[D_IR]);
out << buf << endl;
/*LYS*/
type_sprint(buf, _LYS_CD_, LYS_D[D_M], LYS_D[D_HDR], LYS_D[D_IR]);
out << buf << endl;
/*TRP*/
type_sprint(buf, _TRP_CD_, TRP_D[D_M], TRP_D[D_HDR], TRP_D[D_IR]);
out << buf << endl;
/*DERIVED HBA types*/
type_sprint(buf, _ASP_HBA_,
G1_CONST[ASP][G1_M], G1_CONST[ASP][G1_HDR], G1_CONST[ASP][G1_IR]);
out << buf << endl;
type_sprint(buf, _ASN_HBA_,
G1_CONST[ASN][G1_M], G1_CONST[ASN][G1_HDR], G1_CONST[ASN][G1_IR]);
out << buf << endl;
type_sprint(buf, _GLN_HBA_,
G1_CONST[GLN][G1_M], G1_CONST[GLN][G1_HDR], G1_CONST[GLN][G1_IR]);
out << buf << endl;
type_sprint(buf, _GLU_HBA_,
G1_CONST[GLU][G1_M], G1_CONST[GLU][G1_HDR], G1_CONST[GLU][G1_IR]);
out << buf << endl;
type_sprint(buf, _SER_HBA_,
G1_CONST[SER][G1_M], G1_CONST[SER][G1_HDR], G1_CONST[SER][G1_IR]);
out << buf << endl;
type_sprint(buf, _THR_HBA_,
THR_G2[G2_M], THR_G2[G2_HDR], THR_G2[G2_IR]);
out << buf << endl;
/*derived HBD types*/
type_sprint(buf, _ASN_HBD_,
G1_CONST[ASN][G1_M], G1_CONST[ASN][G1_HDR], G1_CONST[ASN][G1_IR]);
out << buf << endl;
type_sprint(buf, _GLN_HBD_,
G1_CONST[GLN][G1_M], G1_CONST[GLN][G1_HDR], G1_CONST[GLN][G1_IR]);
out << buf << endl;
type_sprint(buf, _SER_HBD_,
G1_CONST[SER][G1_M], G1_CONST[SER][G1_HDR], G1_CONST[SER][G1_IR]);
out << buf << endl;
type_sprint(buf, _THR_HBD_,
THR_G2[G2_M], THR_G2[G2_HDR], THR_G2[G2_IR]);
out << buf << endl;
}
void printNONEL_COL(ostream& out){
out << txtKeyWords[NONEL_COL] << endl;
char buf[1024];
/*mainchain hydogen related*/
/*O-N*/
sprintf(buf, "%ld %ld %lf %lf 0.0000", _N_, _O_, min_NO, HB_N_O[2]);
out << buf << endl;
sprintf(buf, "%ld %ld %lf %lf 0.0000", _N_, _O_HB_, min_NO, HB_N_O[2]);
out << buf << endl;
sprintf(buf, "%ld %ld %lf %lf 0.0000", _N_HB_, _O_HB_, min_NO, HB_N_O[2]);
out << buf << endl;
sprintf(buf, "%ld %ld %lf %lf 0.0000", _N_HB_, _O_, min_NO, HB_N_O[2]);
out << buf << endl;
/*N-C*/
sprintf(buf, "%ld %ld %lf %lf 0.0000", _N_, _C_, min_NC, HB_N_C[4]);
out << buf << endl;
sprintf(buf, "%ld %ld %lf %lf 0.0000", _N_HB_, _C_, min_NC, HB_N_C[4]);
out << buf << endl;
/*O-C*/
sprintf(buf, "%ld %ld %lf %lf 0.0000", _O_, _C_, min_CO, HB_O_C[3]);
out << buf << endl;
sprintf(buf, "%ld %ld %lf %lf 0.0000", _O_HB_, _C_, min_CO, HB_O_C[3]);
out << buf << endl;
/*O-Ca*/
sprintf(buf, "%ld %ld %lf %lf 0.0000", _O_, _CA_, min_OCa, HB_O_CA[3]);
out << buf << endl;
sprintf(buf, "%ld %ld %lf %lf 0.0000", _O_HB_, _CA_, min_OCa, HB_O_CA[3]);
out << buf << endl;
/*N-N*/
sel_col_sprint(buf, _N_, _N_, hdr_NN, min_NN, 2, Dihedral_E/2);
out << buf << endl;
sel_col_sprint(buf, _N_, _N_HB_, hdr_NN, min_NN, 2, Dihedral_E/2);
out << buf << endl;
sel_col_sprint(buf, _N_HB_, _N_HB_, hdr_NN, min_NN, 2, Dihedral_E/2);
out << buf << endl;
sel_col_sprint(buf, _N_, _PRO_N_, hdr_NN, min_PRO_NN, 1, Dihedral_E/2.0);
out << buf << endl;
sel_col_sprint(buf, _N_HB_, _PRO_N_, hdr_NN, min_PRO_NN, 1, Dihedral_E/2.0);
out << buf << endl;
sel_col_sprint(buf, _PRO_N_, _PRO_N_, hdr_NN, min_PRO_NN, 1, Dihedral_E/2.0);
out << buf << endl;
int type_shift = _CYS_CB_;
/*O-Cb, OP-Cb*/
sel_col_sprint(buf, _O_, _CB_, hdr_OCb, min_OCb, 2, Dihedral_E/2);
out << buf << endl;
sel_col_sprint(buf, _O_HB_, _CB_, hdr_OCb, min_OCb, 2, Dihedral_E/2);
out << buf << endl;
for(int i=0; i<20; i++){
dmd_atom_t cb_t = static_cast<dmd_atom_t>(type_shift + i);
if(cb_t!=_PRO_CB_){
sel_col_sprint(buf, _O_, cb_t, hdr_OCb, min_OCb, 2, Dihedral_E/2);
out << buf << endl;
sel_col_sprint(buf, _O_HB_, cb_t, hdr_OCb, min_OCb, 2, Dihedral_E/2);
out << buf << endl;
}
else{
sel_col_sprint(buf, _O_, cb_t, hdr_PRO_OCb, min_PRO_OCb, 2, Dihedral_E/2.0);
out << buf << endl;
sel_col_sprint(buf, _O_HB_, cb_t, hdr_PRO_OCb, min_PRO_OCb, 2, Dihedral_E/2.0);
out << buf << endl;
}
}
/*PRO_CB-N*/
sel_col_sprint(buf, _N_, _PRO_CB_, hdr_NCb, min_PRO_NCb, 5, Dihedral_E);
out << buf << endl;
sel_col_sprint(buf, _N_HB_, _PRO_CB_, hdr_NCb, min_PRO_NCb, 5, Dihedral_E);
out << buf << endl;
sel_col_sprint(buf, _PRO_N_, _PRO_CB_, hdr_NCb, min_PRO_NCb, 5, Dihedral_E);
out << buf << endl;
/*sidechain main related*/
/*HBA*/
sprintf(buf, "%ld %ld %lf %lf 0.0000", _N_, _ASP_CG_,
N_HDR+G1_CONST[ASP][G1_HDR], HB_ASP_N[1]);
out << buf << endl;
sprintf(buf, "%ld %ld %lf %lf 0.0000", _N_, _ASN_CG_,
N_HDR+G1_CONST[ASN][G1_HDR], HB_ASN_N[1]);
out << buf << endl;
sprintf(buf, "%ld %ld %lf %lf 0.0000", _N_, _GLN_CG_,
N_HDR+G1_CONST[GLN][G1_HDR], HB_GLN_N[1]);
out << buf << endl;
sprintf(buf, "%ld %ld %lf %lf 0.0000", _N_, _GLU_CG_,
N_HDR+G1_CONST[GLU][G1_HDR], HB_GLU_N[1]);
out << buf << endl;
sprintf(buf, "%ld %ld %lf %lf 0.0000", _N_, _SER_CG_, min_NO, HB_SER_N[1]);
out << buf << endl;
sprintf(buf, "%ld %ld %lf %lf 0.0000", _N_, _THR_CG2_, min_NO, HB_THR_N[1]);
out << buf << endl;
sprintf(buf, "%ld %ld %lf %lf 0.0000", _N_HB_, _ASP_CG_,
N_HDR+G1_CONST[ASP][G1_HDR], HB_ASP_N[1]);
out << buf << endl;
sprintf(buf, "%ld %ld %lf %lf 0.0000", _N_HB_, _ASN_CG_,
N_HDR+G1_CONST[ASN][G1_HDR], HB_ASN_N[1]);
out << buf << endl;
sprintf(buf, "%ld %ld %lf %lf 0.0000", _N_HB_, _GLN_CG_,
N_HDR+G1_CONST[GLN][G1_HDR], HB_GLN_N[1]);
out << buf << endl;
sprintf(buf, "%ld %ld %lf %lf 0.0000", _N_HB_, _GLU_CG_,
N_HDR+G1_CONST[GLU][G1_HDR], HB_GLU_N[1]);
out << buf << endl;
sprintf(buf, "%ld %ld %lf %lf 0.0000", _N_HB_, _SER_CG_, min_NO, HB_SER_N[1]);
out << buf << endl;
sprintf(buf, "%ld %ld %lf %lf 0.0000", _N_HB_, _THR_CG2_, min_NO, HB_THR_N[1]);
out << buf << endl;
/*HBD*/
sprintf(buf, "%ld %ld %lf %lf 0.0000", _O_, _ASN_CG_,
O_HDR+G1_CONST[ASN][G1_HDR], HBD_ASN_O[1]);
out << buf << endl;
sprintf(buf, "%ld %ld %lf %lf 0.0000", _O_, _GLN_CG_,
O_HDR+G1_CONST[GLN][G1_HDR], HBD_GLN_O[1]);
out << buf << endl;
sprintf(buf, "%ld %ld %lf %lf 0.0000", _O_, _SER_CG_,
HBD_SER_O[0], HBD_SER_O[1]);
out << buf << endl;
sprintf(buf, "%ld %ld %lf %lf 0.0000", _O_, _THR_CG2_,
HBD_THR_O[0], HBD_THR_O[1]);
out << buf << endl;
sprintf(buf, "%ld %ld %lf %lf 0.0000", _O_HB_, _ASN_CG_,
O_HDR+G1_CONST[ASN][G1_HDR], HBD_ASN_O[1]);
out << buf << endl;
sprintf(buf, "%ld %ld %lf %lf 0.0000", _O_HB_, _GLN_CG_,
O_HDR+G1_CONST[GLN][G1_HDR], HBD_GLN_O[1]);
out << buf << endl;
sprintf(buf, "%ld %ld %lf %lf 0.0000", _O_HB_, _SER_CG_,
HBD_SER_O[0], HBD_SER_O[1]);
out << buf << endl;
sprintf(buf, "%ld %ld %lf %lf 0.0000", _O_HB_, _THR_CG2_,
HBD_THR_O[0], HBD_THR_O[1]);
out << buf << endl;
/*define hydrophobic interaction*/
dmd_atom_t type_i, type_j;
double hdr_i, hdr_j;
double ir_i, ir_j;
for(int i=0; i<sizeof(dmd_atom_hp)/sizeof(hp_t); i++){
if(dmd_atom_hp[i]!=IRRELEVANT){
/*type determination of ith atom*/
type_i = static_cast<dmd_atom_t>(_CYS_CB_+i);
if(type_i>=_CYS_CB_ && type_i<=_PRO_CB_){
hdr_i = CB_HDR;
ir_i = CB_IR;
}
else if(type_i>=_CYS_CG_ && type_i<=_PRO_CG_){
hdr_i = G1_CONST[type_i-_CYS_CG_][G1_HDR];
ir_i = G1_CONST[type_i-_CYS_CG_][G1_IR];
}
else if(type_i==_ILE_CG2_){
hdr_i = ILE_G2[G2_HDR];
ir_i = ILE_G2[G2_IR];
}
else if(type_i==_THR_CG2_){
hdr_i = THR_G2[G2_HDR];
ir_i = THR_G2[G2_IR];
}
else if(type_i==_VAL_CG2_) {
hdr_i = VAL_G2[G2_HDR];
ir_i = VAL_G2[G2_IR];
}
else if(type_i==_ARG_CD_){
hdr_i = ARG_D[D_HDR];
ir_i = ARG_D[D_IR];
}
else if(type_i==_LYS_CD_){
hdr_i = LYS_D[D_HDR];
ir_i = LYS_D[D_IR];
}
else if(type_i==_TRP_CD_){
hdr_i = TRP_D[D_HDR];
ir_i = TRP_D[D_IR];
}
for(int j=i; j<sizeof(dmd_atom_hp)/sizeof(hp_t); j++){
/*type determination of ith atom*/
if(dmd_atom_hp[j]!=IRRELEVANT){
type_j = static_cast<dmd_atom_t>(_CYS_CB_+j);
if(type_j>=_CYS_CB_ && type_j<=_PRO_CB_){
hdr_j = CB_HDR;
ir_j = CB_IR;
}
else if(type_j>=_CYS_CG_ && type_j<=_PRO_CG_){
hdr_j = G1_CONST[type_j-_CYS_CG_][G1_HDR];
ir_j = G1_CONST[type_j-_CYS_CG_][G1_IR];
}
else if(type_j==_ILE_CG2_){
hdr_j = ILE_G2[G2_HDR];
ir_j = ILE_G2[G2_IR];
}
else if(type_j==_THR_CG2_){
hdr_j = THR_G2[G2_HDR];
ir_j = THR_G2[G2_IR];
}
else if(type_j==_VAL_CG2_){
hdr_j = VAL_G2[G2_HDR];
ir_j = VAL_G2[G2_IR];
}
else if(type_j==_ARG_CD_){
hdr_j = ARG_D[D_HDR];
ir_j = ARG_D[D_IR];
}
else if(type_j==_LYS_CD_){
hdr_j = LYS_D[D_HDR];
ir_j = LYS_D[D_IR];
}
else if(type_j==_TRP_CD_){
hdr_j = TRP_D[D_HDR];
ir_j = TRP_D[D_IR];
}
/*determine the interaction potential*/
if(dmd_atom_hp[i]==APOLOR && dmd_atom_hp[j]==APOLOR){/*APOLOR-APOLOR*/
if((type_i==_PHE_CG_ || type_i==_TRP_CD_ || type_i==_TYR_CG_ || type_i==_PRO_CG_) &&
(type_j==_PHE_CG_ || type_j==_TRP_CD_ || type_j==_TYR_CG_ || type_j==_PRO_CG_)){
/*AROMATIC interaction is more than HYDROPHOBIC;
The interaction potential will be assigned later
{PHE,TYR,TRP,PRO}--{PHE,TYR,TRP,PRO}*/
}
else{
hp_sprint(buf, type_i, type_j, hdr_i+hdr_j, ir_i+ir_j,
HP_E);
out << buf << endl;
}
}
else if((dmd_atom_hp[i]==APOLOR && dmd_atom_hp[j]==AMPHI) ||
(dmd_atom_hp[i]==AMPHI && dmd_atom_hp[j]==APOLOR)){
if((type_i==_PHE_CG_ || type_i==_TRP_CD_ || type_i==_TYR_CG_ || type_i==_PRO_CG_) &&
(type_j==_PHE_CG_ || type_j==_TRP_CD_ || type_j==_TYR_CG_ || type_j==_PRO_CG_)){
/*PRO as an amphipatic amino acid with aromatic ring, it has a strong
AROMATIC interaction with hydrophobic aromatic residues;
The interaction is assgined later
{PHE,TYR,TRP,PRO}--{PHE,TYR,TRP,PRO}*/
}
else{
hp_sprint(buf, type_i, type_j, hdr_i+hdr_j, ir_i+ir_j,
HA_E);
out << buf << endl;
}
}
}
}
}
}
/*end the definition of HYDROPHOBIC interactions*/
/*SB related:
We treat the Electrostatic interaction as short-range attraction*/
double hcd = 0;
double itd = 0;
/*ARG(D)-ASP(G)*/
hcd = ARG_D[D_HDR]+G1_CONST[ASP][G1_HDR];
itd = ARG_D[D_IR] +G1_CONST[ASP][G1_IR];
sb_sprint(buf, _ARG_CD_, _ASP_CG_, hcd, itd, SB_E);
out << buf << endl;
sb_sprint(buf, _ARG_CD_, _ASP_HBA_, hcd, itd, SB_E);
out << buf << endl;
/*ARG(D)-GLU(G)*/
hcd = ARG_D[D_HDR]+G1_CONST[GLU][G1_HDR];
itd = ARG_D[D_IR] +G1_CONST[GLU][G1_IR];
sb_sprint(buf, _ARG_CD_, _GLU_CG_, hcd, itd, SB_E);
out << buf << endl;
sb_sprint(buf, _ARG_CD_, _GLU_HBA_, hcd, itd, SB_E);
out << buf << endl;
/*ARG(D)-LYS(D)*/
hcd = ARG_D[D_HDR]+LYS_D[D_HDR];
itd = ARG_D[D_IR] +LYS_D[D_IR];
rsb_sprint(buf, _ARG_CD_, _LYS_CD_, hcd, itd, SB_E);
out << buf << endl;
/*ARG-ARG*/
hcd = ARG_D[D_HDR]+ARG_D[D_HDR];
itd = ARG_D[D_IR] +ARG_D[D_IR];
rsb_sprint(buf, _ARG_CD_, _ARG_CD_, hcd, itd, SB_E);
out << buf << endl;
/*LYS-ASP*/
hcd = LYS_D[D_HDR]+G1_CONST[ASP][G1_HDR];
itd = LYS_D[D_IR] +G1_CONST[ASP][G1_IR];
sb_sprint(buf, _LYS_CD_, _ASP_CG_, hcd, itd, SB_E);
out << buf << endl;
sb_sprint(buf, _LYS_CD_, _ASP_HBA_, hcd, itd, SB_E);
out << buf << endl;
/*LYS-GLU*/
hcd = LYS_D[D_HDR]+G1_CONST[GLU][G1_HDR];
itd = LYS_D[D_IR] +G1_CONST[GLU][G1_IR];
sb_sprint(buf, _LYS_CD_, _GLU_CG_, hcd, itd, SB_E);
out << buf << endl;
sb_sprint(buf, _LYS_CD_, _GLU_HBA_, hcd, itd, SB_E);
out << buf << endl;
/*LYS-LYS*/
hcd = LYS_D[D_HDR]+LYS_D[D_HDR];
itd = LYS_D[D_IR] +LYS_D[D_IR];
rsb_sprint(buf, _LYS_CD_, _LYS_CD_, hcd, itd, SB_E);
out << buf << endl;
/*GLU-ASP*/
hcd = G1_CONST[GLU][G1_HDR]+G1_CONST[ASP][G1_HDR];
itd = G1_CONST[GLU][G1_IR] +G1_CONST[ASP][G1_IR];
rsb_sprint(buf, _GLU_CG_, _ASP_CG_, hcd, itd, SB_E);
out << buf << endl;
rsb_sprint(buf, _GLU_HBA_, _ASP_CG_, hcd, itd, SB_E);
out << buf << endl;
rsb_sprint(buf, _GLU_CG_, _ASP_HBA_, hcd, itd, SB_E);
out << buf << endl;
rsb_sprint(buf, _GLU_HBA_, _ASP_HBA_, hcd, itd, SB_E);
out << buf << endl;
/*GLU-GLU*/
hcd = G1_CONST[GLU][G1_HDR]+G1_CONST[GLU][G1_HDR];
itd = G1_CONST[GLU][G1_IR] +G1_CONST[GLU][G1_IR];
rsb_sprint(buf, _GLU_CG_, _GLU_CG_, hcd, itd, SB_E);
out << buf << endl;
rsb_sprint(buf, _GLU_HBA_, _GLU_CG_, hcd, itd, SB_E);
out << buf << endl;
rsb_sprint(buf, _GLU_CG_, _GLU_HBA_, hcd, itd, SB_E);
out << buf << endl;
rsb_sprint(buf, _GLU_HBA_, _GLU_HBA_, hcd, itd, SB_E);
out << buf << endl;
/*ASP-ASP*/
hcd = G1_CONST[ASP][G1_HDR]+G1_CONST[ASP][G1_HDR];
itd = G1_CONST[ASP][G1_IR] +G1_CONST[ASP][G1_IR];
rsb_sprint(buf, _ASP_CG_, _ASP_CG_, hcd, itd, SB_E);
out << buf << endl;
rsb_sprint(buf, _ASP_HBA_, _ASP_CG_, hcd, itd, SB_E);
out << buf << endl;
rsb_sprint(buf, _ASP_CG_, _ASP_HBA_, hcd, itd, SB_E);
out << buf << endl;
rsb_sprint(buf, _ASP_HBA_, _ASP_HBA_, hcd, itd, SB_E);
out << buf << endl;
/*end SB*/
/*define the AROMATIC interactions*/
/*ARO --- ARO; the hardcore diameter is increased due to ringpacking*/
/*PHE-PHE*/
if( ir_ext>0 ){
sprintf(buf, "%ld %ld %lf %lf %lf %lf %lf", _PHE_CG_, _PHE_CG_,
ARO_R_PHE+ARO_R_PHE, G1_CONST[PHE][G1_IR] + G1_CONST[PHE][G1_IR],
-fabs(AROMATIC_E),
G1_CONST[PHE][G1_IR] + G1_CONST[PHE][G1_IR]+ir_ext,
-fabs(AROMATIC_E)/2.0);
}
else{
sprintf(buf, "%ld %ld %lf %lf %lf", _PHE_CG_, _PHE_CG_,
ARO_R_PHE+ARO_R_PHE, G1_CONST[PHE][G1_IR] + G1_CONST[PHE][G1_IR],
-fabs(AROMATIC_E) ) ;
}
out << buf << endl;
/*PHE-TRP*/
if( ir_ext>0 ){
sprintf(buf, "%ld %ld %lf %lf %lf %lf %lf", _PHE_CG_, _TRP_CD_,
ARO_R_PHE+ARO_R_TRP,
G1_CONST[PHE][G1_IR] + TRP_D[D_IR], -fabs(AROMATIC_E),
G1_CONST[PHE][G1_IR] + TRP_D[D_IR]+ir_ext, -fabs(AROMATIC_E)/2.0);
}
else{
sprintf(buf, "%ld %ld %lf %lf %lf", _PHE_CG_, _TRP_CD_,
ARO_R_PHE+ARO_R_TRP,
G1_CONST[PHE][G1_IR] + TRP_D[D_IR], -fabs(AROMATIC_E) );
}
out << buf << endl;
/*TRP-TRP*/
if( ir_ext>0 ){
sprintf(buf, "%ld %ld %lf %lf %lf %lf %lf", _TRP_CD_, _TRP_CD_,
ARO_R_TRP+ARO_R_TRP,
TRP_D[D_IR] +TRP_D[D_IR], -fabs(AROMATIC_E),
TRP_D[D_IR] +TRP_D[D_IR]+ir_ext, -fabs(AROMATIC_E)/2.0);
}
else{
sprintf(buf, "%ld %ld %lf %lf %lf", _TRP_CD_, _TRP_CD_,
ARO_R_TRP+ARO_R_TRP,
TRP_D[D_IR] +TRP_D[D_IR], -fabs(AROMATIC_E) );
}
out << buf << endl;
/*TRP-TYR*/
if( ir_ext>0 ){
sprintf(buf, "%ld %ld %lf %lf %lf %lf %lf", _TRP_CD_, _TYR_CG_,
ARO_R_TRP + ARO_R_TYR,
TRP_D[D_IR] +G1_CONST[TYR][G1_IR], -fabs(AROMATIC_E),
TRP_D[D_IR] +G1_CONST[TYR][G1_IR]+ir_ext, -fabs(AROMATIC_E)/2.0);
}
else{
sprintf(buf, "%ld %ld %lf %lf %lf", _TRP_CD_, _TYR_CG_,
ARO_R_TRP + ARO_R_TYR,
TRP_D[D_IR] +G1_CONST[TYR][G1_IR], -fabs(AROMATIC_E) );
}
out << buf << endl;
/*PHE-TYR*/
if( ir_ext>0 ){
sprintf(buf, "%ld %ld %lf %lf %lf %lf %lf", _PHE_CG_, _TYR_CG_,
ARO_R_PHE + ARO_R_TYR,
G1_CONST[PHE][G1_IR] +G1_CONST[TYR][G1_IR], -fabs(AROMATIC_E),
G1_CONST[PHE][G1_IR] +G1_CONST[TYR][G1_IR]+ir_ext,
-fabs(AROMATIC_E)/2.0);
}
else{
sprintf(buf, "%ld %ld %lf %lf %lf", _PHE_CG_, _TYR_CG_,
ARO_R_PHE + ARO_R_TYR,
G1_CONST[PHE][G1_IR] +G1_CONST[TYR][G1_IR], -fabs(AROMATIC_E) );
}
out << buf << endl;
/*TYR-TYR*/
if( ir_ext>0 ){
sprintf(buf, "%ld %ld %lf %lf %lf %lf %lf", _TYR_CG_, _TYR_CG_,
ARO_R_TYR + ARO_R_TYR,
G1_CONST[TYR][G1_IR] +G1_CONST[TYR][G1_IR], -fabs(AROMATIC_E),
G1_CONST[TYR][G1_IR] +G1_CONST[TYR][G1_IR]+ir_ext,
-fabs(AROMATIC_E)/2.0);
}
else{
sprintf(buf, "%ld %ld %lf %lf %lf", _TYR_CG_, _TYR_CG_,
ARO_R_TYR + ARO_R_TYR,
G1_CONST[TYR][G1_IR] +G1_CONST[TYR][G1_IR], -fabs(AROMATIC_E) );
}
out << buf << endl;
/*ARO---PRO*/
/*TRP-PRO*/
if( ir_ext>0 ){
sprintf(buf, "%ld %ld %lf %lf %lf %lf %lf", _TRP_CD_, _PRO_CG_,
TRP_D[D_HDR]+G1_CONST[PRO][G1_HDR],
TRP_D[D_IR] +G1_CONST[PRO][G1_IR], -fabs(ARO_PRO_E),
TRP_D[D_IR] +G1_CONST[PRO][G1_IR]+ir_ext, -fabs(ARO_PRO_E)/2.0);
}
else{
sprintf(buf, "%ld %ld %lf %lf %lf", _TRP_CD_, _PRO_CG_,
TRP_D[D_HDR]+G1_CONST[PRO][G1_HDR],
TRP_D[D_IR] +G1_CONST[PRO][G1_IR], -fabs(ARO_PRO_E) );
}
out << buf << endl;
/*TYR-PRO*/
if( ir_ext>0 ){
sprintf(buf, "%ld %ld %lf %lf %lf %lf %lf", _TYR_CG_, _PRO_CG_,
G1_CONST[TYR][G1_HDR]+G1_CONST[PRO][G1_HDR],
G1_CONST[TYR][G1_IR] +G1_CONST[PRO][G1_IR], -fabs(ARO_PRO_E),
G1_CONST[TYR][G1_IR] +G1_CONST[PRO][G1_IR]+ir_ext,
-fabs(ARO_PRO_E)/2.0);
}
else{
sprintf(buf, "%ld %ld %lf %lf %lf", _TYR_CG_, _PRO_CG_,
G1_CONST[TYR][G1_HDR]+G1_CONST[PRO][G1_HDR],
G1_CONST[TYR][G1_IR] +G1_CONST[PRO][G1_IR], -fabs(ARO_PRO_E) );
}
out << buf << endl;
/*PHE-PRO*/
if( ir_ext>0 ){
sprintf(buf, "%ld %ld %lf %lf %lf %lf %lf", _PHE_CG_, _PRO_CG_,
G1_CONST[PHE][G1_HDR]+G1_CONST[PRO][G1_HDR],
G1_CONST[PHE][G1_IR] +G1_CONST[PRO][G1_IR], -fabs(ARO_PRO_E),
G1_CONST[PHE][G1_IR] +G1_CONST[PRO][G1_IR]+ir_ext,
-fabs(ARO_PRO_E)/2.0);
}
else{
sprintf(buf, "%ld %ld %lf %lf %lf", _PHE_CG_, _PRO_CG_,
G1_CONST[PHE][G1_HDR]+G1_CONST[PRO][G1_HDR],
G1_CONST[PHE][G1_IR] +G1_CONST[PRO][G1_IR], -fabs(ARO_PRO_E) );
}
out << buf << endl;
/*HIS?*/
/*end the definition of AROMATIC interactions*/
}
void printEL_COL(ostream& out){
out << txtKeyWords[EL_COL] << endl;
char buf[1024];
/*N-C*/
/*
el_col_sprint(buf, _N_, _C_, min_NC);
out << buf << endl;
el_col_sprint(buf, _N_HB_, _C_, min_NC);
out << buf << endl;
*/
el_col_sprint(buf, _PRO_N_, _C_, min_NC);
out << buf << endl;
/*N-Cb*/
el_col_sprint(buf, _N_, _CB_, min_NCb);
out << buf << endl;
el_col_sprint(buf, _N_HB_, _CB_, min_NCb);
out << buf << endl;
el_col_sprint(buf, _PRO_N_, _CB_, min_NCb);
out << buf << endl;
int type_shift = _CYS_CB_;
for(int i=0; i<20; i++){
dmd_atom_t cb_t = static_cast<dmd_atom_t>(type_shift + i);
if(cb_t!=_PRO_CB_){
el_col_sprint(buf, _N_, cb_t, min_NCb);
out << buf << endl;
el_col_sprint(buf, _N_HB_, cb_t, min_NCb);
out << buf << endl;
el_col_sprint(buf, _PRO_N_, cb_t, min_NCb);
out << buf << endl;
}
}
/*C-CB*/
el_col_sprint(buf, _C_, _CB_, min_CCb);
out << buf << endl;
for(int i=0; i<20; i++){
dmd_atom_t cb_t = static_cast<dmd_atom_t>(type_shift + i);
el_col_sprint(buf, _C_, cb_t, min_CCb);
out << buf << endl;
}
/*O-Ca, OP-Ca*/
/*
el_col_sprint(buf, _O_, _CA_, min_OCa);
out << buf << endl;
el_col_sprint(buf, _O_HB_, _CA_, min_OCa);
out << buf << endl;
*/
/*main chain hydrogen bonding related*/
/*NP-OP*/
/*
el_col_sprint(buf, _N_HB_, _O_HB_, min_NO);
out << buf << endl;
el_col_sprint(buf, _N_HB_, _O_, min_NO);
out << buf << endl;
el_col_sprint(buf, _N_, _O_HB_, min_NO);
out << buf << endl;
*/
/*side-main hydrogen bonding related*/
el_col_sprint(buf, _N_, _ASP_HBA_, N_HDR+G1_CONST[ASP][G1_HDR]);
out << buf << endl;
el_col_sprint(buf, _N_, _ASN_HBA_, N_HDR+G1_CONST[ASN][G1_HDR]);
out << buf << endl;
el_col_sprint(buf, _N_, _GLN_HBA_, N_HDR+G1_CONST[GLN][G1_HDR]);
out << buf << endl;
el_col_sprint(buf, _N_, _GLU_HBA_, N_HDR+G1_CONST[GLU][G1_HDR]);
out << buf << endl;
el_col_sprint(buf, _N_, _SER_HBA_, min_NO);
out << buf << endl;
el_col_sprint(buf, _N_, _THR_HBA_, min_NO);
out << buf << endl;
el_col_sprint(buf, _N_HB_, _ASP_HBA_, N_HDR+G1_CONST[ASP][G1_HDR]);
out << buf << endl;
el_col_sprint(buf, _N_HB_, _ASN_HBA_, N_HDR+G1_CONST[ASN][G1_HDR]);
out << buf << endl;
el_col_sprint(buf, _N_HB_, _GLN_HBA_, N_HDR+G1_CONST[GLN][G1_HDR]);
out << buf << endl;
el_col_sprint(buf, _N_HB_, _GLU_HBA_, N_HDR+G1_CONST[GLU][G1_HDR]);
out << buf << endl;
el_col_sprint(buf, _N_HB_, _SER_HBA_, min_NO);
out << buf << endl;
el_col_sprint(buf, _N_HB_, _THR_HBA_, min_NO);
out << buf << endl;
el_col_sprint(buf, _O_, _ASN_HBD_, O_HDR+G1_CONST[ASN][G1_HDR]);
out << buf << endl;
el_col_sprint(buf, _O_, _GLN_HBD_, O_HDR+G1_CONST[GLN][G1_HDR]);
out << buf << endl;
el_col_sprint(buf, _O_, _SER_HBD_, HBD_SER_O[0]);
out << buf << endl;
el_col_sprint(buf, _O_, _THR_HBD_, HBD_THR_O[0]);
out << buf << endl;
el_col_sprint(buf, _O_HB_, _ASN_HBD_, O_HDR+G1_CONST[ASN][G1_HDR]);
out << buf << endl;
el_col_sprint(buf, _O_HB_, _GLN_HBD_, O_HDR+G1_CONST[GLN][G1_HDR]);
out << buf << endl;
el_col_sprint(buf, _O_HB_, _SER_HBD_, HBD_SER_O[0]);
out << buf << endl;
el_col_sprint(buf, _O_HB_, _THR_HBD_, HBD_THR_O[0]);
out << buf << endl;
el_col_sprint(buf, _O_, _ASN_HBA_, O_HDR+G1_CONST[ASN][G1_HDR]);
out << buf << endl;
el_col_sprint(buf, _O_HB_, _ASN_HBA_, O_HDR+G1_CONST[ASN][G1_HDR]);
out << buf << endl;
el_col_sprint(buf, _N_, _ASN_HBD_, N_HDR+G1_CONST[ASN][G1_HDR]);
out << buf << endl;
el_col_sprint(buf, _N_HB_, _ASN_HBD_, N_HDR+G1_CONST[ASN][G1_HDR]);
out << buf << endl;
el_col_sprint(buf, _O_, _GLN_HBA_, O_HDR+G1_CONST[GLN][G1_HDR]);
out << buf << endl;
el_col_sprint(buf, _O_HB_, _GLN_HBA_, O_HDR+G1_CONST[GLN][G1_HDR]);
out << buf << endl;
el_col_sprint(buf, _N_, _GLN_HBD_, N_HDR+G1_CONST[GLN][G1_HDR]);
out << buf << endl;
el_col_sprint(buf, _N_HB_, _GLN_HBD_, N_HDR+G1_CONST[GLN][G1_HDR]);
out << buf << endl;
el_col_sprint(buf, _O_, _SER_HBA_, HBD_SER_O[0]);
out << buf << endl;
el_col_sprint(buf, _O_HB_, _SER_HBA_, HBD_SER_O[0]);
out << buf << endl;
el_col_sprint(buf, _N_, _SER_HBD_, min_NO);
out << buf << endl;
el_col_sprint(buf, _N_HB_, _SER_HBD_, min_NO);
out << buf << endl;
el_col_sprint(buf, _O_, _THR_HBA_, HBD_THR_O[0]);
out << buf << endl;
el_col_sprint(buf, _O_HB_, _THR_HBA_, HBD_THR_O[0]);
out << buf << endl;
el_col_sprint(buf, _N_, _THR_HBD_, min_NO);
out << buf << endl;
el_col_sprint(buf, _N_HB_, _THR_HBD_, min_NO);
out << buf << endl;
}
void printBOND_TYPE(ostream& out){
out << txtKeyWords[LINK_PAIRS] << endl;
char buf[1024];
/*N-Ca, Ca_N1*/
double n_len;
double n_dev = getTriDev_angle(CA_C, C_N, BOND_DEV, CA_C_N*rpi, n_len);
double_bond_sprint(buf, N_CA, BOND_DEV, n_len, n_dev);
out << _N_ << " " << _CA_ << " " << buf << endl;
/*Ca-C, C-Ca1*/
n_dev = getTriDev_angle(C_N, N_CA, BOND_DEV, C_N_CA*rpi, n_len);
double_bond_sprint(buf, CA_C, BOND_DEV, n_len, n_dev);
out << _C_ << " " << _CA_ << " " << buf << endl;
/*C-N1, N-C*/
n_dev = getTriDev_angle(N_CA, CA_C, BOND_DEV, N_CA_C*rpi, n_len);
double_bond_sprint(buf, C_N, BOND_DEV, n_len, n_dev);
out << _N_ << " " << _C_ << " " << buf << endl;
/*CA-CB*/
single_bond_sprint(buf, CA_CB, BOND_DEV);
out << _CA_ << " " << _CB_ << " " << buf << endl;
/*CA-PRO_CB*/
out << _CA_ << " " << _PRO_CB_ << " " << buf << endl;
/*N-CB*/
n_dev = getTriDev_angle(N_CA, CA_CB, BOND_DEV, N_CA_CB*rpi, n_len);
single_bond_sprint(buf, n_len, n_dev);
out << _N_ << " " << _CB_ << " " << buf << endl;
/*N-PRO_CB*/
n_dev = getTriDev_angle(N_CA, CA_CB, BOND_DEV, PRO_N_CA_CB*rpi, n_len);
single_bond_sprint(buf, n_len, n_dev);
out << _N_ << " " << _PRO_CB_ << " " << buf << endl;
/*C-CB*/
n_dev = getTriDev_angle(CA_C, CA_CB, BOND_DEV, C_CA_CB*rpi, n_len);
single_bond_sprint(buf, n_len, n_dev);
out << _C_ << " " << _CB_ << " " << buf << endl;
/*C-PRO_CB,
C-PRO_CB1, used to fix the phi angle of PRO*/
n_dev = getTriDev_angle(CA_C, CA_CB, BOND_DEV, PRO_C_CA_CB*rpi, n_len);
double_bond_sprint(buf, n_len, n_dev, PRO_C_CB, PRO_C_CB_D/PRO_C_CB);
out << _C_ << " " << _PRO_CB_ << " " << buf << endl;
/*C-C, used to alow certain phi region for PRO*/
sprintf(buf, "%ld %ld %lf %lf", _C_, _C_, PRO_C_C1_MIN, PRO_C_C1_MAX);
out << buf << endl;
/*C-O*/
single_bond_sprint(buf, C_O, BOND_DEV_O);
out << _C_ << " " << _O_ << " " << buf << endl;
/*CA-O*/
n_dev = getTriDev_angle(CA_C, C_O, BOND_DEV_O, CA_C_O*rpi, n_len);
single_bond_sprint(buf, n_len, n_dev);
out << _O_ << " " << _CA_ << " " << buf << endl;
/*O-N1*/
n_dev = getTriDev_angle(C_O, C_N, BOND_DEV_O, (360.0-CA_C_N-CA_C_O)*rpi, n_len);
single_bond_sprint(buf, n_len, n_dev);
out << _O_ << " " << _N_ << " " << buf << endl;
/*CA-CA*/
double c_ca = sqrt(C_N*C_N + N_CA*N_CA - 2.0*C_N*N_CA*cos(C_N_CA*rpi));
n_dev = getTriDev_angle(CA_C, c_ca, BOND_DEV, CA_C_CA*rpi, n_len);
single_bond_sprint(buf, n_len, n_dev);
out << _CA_ << " " << _CA_ << " " << buf << endl;
/*CG-CB, CG-CA and C-CG, N-CG*/
int type_shift = _CYS_CG_;
for(int i=0; i<20; i++){
dmd_atom_t cg_t = static_cast<dmd_atom_t>(type_shift + i);
if(i!=ALA && i!=GLY){
const double* cg_para = G1_CONST[i];
if(cg_para[G1_CB_D]==0){
single_bond_sprint(buf, cg_para[G1_CB], BOND_DEV_G);
}
else{
single_bond_sprint_len(buf, cg_para[G1_CB], cg_para[G1_CB_D]);
}
if(i!=PRO)
out << _CB_ << " " << cg_t << " " << buf << endl;
else
out << _PRO_CB_ << " " << cg_t << " " << buf << endl;
if(cg_para[G1_CA_D]==0){
n_dev = getTriDev_length(cg_para[G1_CB], CA_CB, BOND_DEV_G, cg_para[G1_CA]);
single_bond_sprint(buf, cg_para[G1_CA], n_dev);
}
else{
single_bond_sprint_len(buf, cg_para[G1_CA], cg_para[G1_CA_D]);
}
out << _CA_ << " " << cg_t << " " << buf << endl;
/*N-CG, C-CG*/
const double* dihedral = Dihedral_C_CG[i];
if(dihedral[0]!=INF){
//c-cg
sprintf(buf, "%ld %ld %lf %lf %lf %lf %lf %lf %lf %lf",
_C_, cg_t,
Dihedral_MIN,
dihedral[0], Dihedral_E,
dihedral[1], -Dihedral_E,
dihedral[2], Dihedral_E,
Dihedral_MAX);
out << buf << endl;
//n-cg
sprintf(buf, "%ld %ld %lf %lf",
_N_, cg_t, Dihedral_MIN, Dihedral_MAX);
out << buf << endl;
}
if(i==PRO){//different constraint for PROLINE
single_bond_sprint_len(buf, PRO_N_CG, PRO_N_CG_D);
out << _N_ << " " << cg_t << " " << buf << endl;
/*this constraint is actually used to
avoid the small distance of c-PRO_CB*/
single_bond_sprint_len(buf, PRO_C_CG, PRO_C_CG_D);
out << _C_ << " " << cg_t << " " << buf << endl;
}
}
}
/*ILE, G2*/
//CG2-CB
single_bond_sprint(buf, ILE_G2[G2_CB], BOND_DEV_G);
out << _CB_ << " " << _ILE_CG2_ << " " << buf << endl;
//CG2-CA
n_dev = getTriDev_length(CA_CB, ILE_G2[G2_CB], BOND_DEV_G, ILE_G2[G2_CA]);
single_bond_sprint(buf, ILE_G2[G2_CA], n_dev);
out << _CA_ << " " << _ILE_CG2_ << " " << buf << endl;
//CG2-CG1
//n_dev = getTriDev_length(ILE_G2[G2_CB], G1_CONST[ILE][G1_CB],
//BOND_DEV_G, ILE_G2[G1_G2]);
n_dev = ILE_G2[CG_G2_D]/ILE_G2[G1_G2];
single_bond_sprint(buf, ILE_G2[G1_G2], n_dev);
out << _ILE_CG_ << " " << _ILE_CG2_ << " " << buf << endl;
//N-CG2
sprintf(buf, "%ld %ld %lf %lf",
_N_, _ILE_CG2_, Dihedral_MIN, Dihedral_MAX);
out << buf << endl;
//C-CG2
const double* dihedral = Dihedral_C_CG[ILE];
sprintf(buf, "%ld %ld %lf %lf",
_C_, _ILE_CG2_, Dihedral_MIN, Dihedral_MAX);
out << buf << endl;
/*THR, G2*/
//CG2-CB
single_bond_sprint(buf, THR_G2[G2_CB], BOND_DEV_G);
out << _CB_ << " " << _THR_CG2_ << " " << buf << endl;
//CG2-CA
n_dev = getTriDev_length(CA_CB, THR_G2[G2_CB], BOND_DEV_G, THR_G2[G2_CA]);
single_bond_sprint(buf, THR_G2[G2_CA], n_dev);
out << _CA_ << " " << _THR_CG2_ << " " << buf << endl;
//CG2-CG1
n_dev = getTriDev_length(THR_G2[G2_CB], G1_CONST[THR][G1_CB],
BOND_DEV_G, THR_G2[G1_G2]);
single_bond_sprint(buf, THR_G2[G1_G2], n_dev);
out << _THR_CG_ << " " << _THR_CG2_ << " " << buf << endl;
//N-CG2
sprintf(buf, "%ld %ld %lf %lf",
_N_, _THR_CG2_, Dihedral_MIN, Dihedral_MAX);
out << buf << endl;
//C-CG2
sprintf(buf, "%ld %ld %lf %lf",
_C_, _THR_CG2_, Dihedral_MIN, Dihedral_MAX);
out << buf << endl;
/*VAL, G2*/
//CG2-CB
single_bond_sprint(buf, VAL_G2[G2_CB], BOND_DEV_G);
out << _CB_ << " " << _VAL_CG2_ << " " << buf << endl;
//CG2-CA
n_dev = getTriDev_length(CA_CB, VAL_G2[G2_CB], BOND_DEV_G, VAL_G2[G2_CA]);
single_bond_sprint(buf, VAL_G2[G2_CA], n_dev);
out << _CA_ << " " << _VAL_CG2_ << " " << buf << endl;
//CG2-CG1
n_dev = getTriDev_length(VAL_G2[G2_CB], G1_CONST[VAL][G1_CB],
BOND_DEV_G, VAL_G2[G1_G2]);
single_bond_sprint(buf, VAL_G2[G1_G2], n_dev);
out << _VAL_CG_ << " " << _VAL_CG2_ << " " << buf << endl;
//N-CG2
sprintf(buf, "%ld %ld %lf %lf",
_N_, _VAL_CG2_, Dihedral_MIN, Dihedral_MAX);
out << buf << endl;
//C-CG2
sprintf(buf, "%ld %ld %lf %lf",
_C_, _VAL_CG2_, Dihedral_MIN, Dihedral_MAX);
out << buf << endl;
/*TRP, CD*/
/*CD-CG*/
single_bond_sprint(buf, TRP_D[D_CG], BOND_DEV_G);
out << _TRP_CG_ << " " << _TRP_CD_ << " " << buf << endl;
/*CD-CB*/
n_dev = getTriDev_length(G1_CONST[TRP][G1_CB], TRP_D[D_CG], BOND_DEV_G, TRP_D[D_CB]);
single_bond_sprint(buf, TRP_D[D_CB], n_dev);
out << _TRP_CD_ << " " << _CB_ << " " << buf << endl;
/*CD-CA; Dihedral*/
sprintf(buf, "%ld %ld %lf %lf %lf %lf %lf %lf %lf %lf",
_CA_, _TRP_CD_,
Dihedral_MIN,
Dihedral_TRP_D[0], Dihedral_E,
Dihedral_TRP_D[1], -Dihedral_E,
Dihedral_TRP_D[2], Dihedral_E,
Dihedral_MAX);
out << buf << endl;
/*ARG, CD*/
/*CD-CG*/
single_bond_sprint(buf, ARG_D[D_CG], BOND_DEV_G);
out << _ARG_CG_ << " " << _ARG_CD_ << " " << buf << endl;
/*CD-CB*/
n_dev = ARG_D[D_CB_D]/ARG_D[D_CB];
single_bond_sprint(buf, ARG_D[D_CB], n_dev);
out << _ARG_CD_ << " " << _CB_ << " " << buf << endl;
/*LYS, CD*/
/*CD-CG*/
single_bond_sprint(buf, LYS_D[D_CG], BOND_DEV_G);
out << _LYS_CG_ << " " << _LYS_CD_ << " " << buf << endl;
/*CD-CB*/
n_dev = LYS_D[D_CB_D]/LYS_D[D_CB];
single_bond_sprint(buf, LYS_D[D_CB], n_dev);
out << _LYS_CD_ << " " << _CB_ << " " << buf << endl;
/*mainchain hydrogen bond related*/
/*NP-OP*/
sprintf(buf,"%ld %ld %lf %lf %lf %lf 0.00000", _N_HB_, _O_HB_,
HB_N_O[0], HB_N_O[1], -fabs(EHB_M_M)/4.0, HB_N_O[2]+eps);
out << buf << endl;
/*NP-C*/
sprintf(buf, "%ld %ld %lf %lf %lf %lf %lf %lf %lf %lf 0.00000",
_N_HB_, _C_,
HB_N_C[0],
HB_N_C[1], fabs(EHB_M_M)/4.0,
HB_N_C[2], fabs(EHB_M_M)/4.0,
HB_N_C[3], -fabs(EHB_M_M)/4.0,
HB_N_C[4]+eps);
out << buf << endl;
//sprintf(buf, "%ld %ld %lf %lf",
//_N_HB_, _C_,
//HB_N_C[1],
//HB_N_C[2]),
//out << buf << endl;
/*OP-C*/
sprintf(buf, "%ld %ld %lf %lf %lf %lf %lf %lf 0.00000",
_O_HB_, _C_,
HB_O_C[0],
HB_O_C[1], fabs(EHB_M_M)/2.0,
HB_O_C[2], -fabs(EHB_M_M)/4.0,
HB_O_C[3]+eps);
out << buf << endl;
//sprintf(buf, "%ld %ld %lf %lf",
// _O_HB_, _C_,
// HB_O_C[1],
// HB_O_C[2]);
//out << buf << endl;
/*OP-CA*/
sprintf(buf, "%ld %ld %lf %lf %lf %lf %lf %lf 0.0000",
_O_HB_, _CA_,
HB_O_CA[0],
HB_O_CA[1], fabs(EHB_M_M)/2.0,
HB_O_CA[2], -fabs(EHB_M_M)/4.0,
HB_O_CA[3]+eps);
out << buf << endl;
//sprintf(buf, "%ld %ld %lf %lf",
// _O_HB_, _CA_,
// HB_O_CA[1],
// HB_O_CA[2]);
//out << buf << endl;
/*side-main hydrogen bond related*/
//HBA
/*ASP*/
sprintf(buf, "%ld %ld %lf %lf %lf", _N_HB_, _ASP_HBA_,
HB_ASP_N[0], HB_ASP_N[1]+eps, -fabs(EHB_S_M));
out << buf << endl;
sprintf(buf, "%ld %ld %lf %lf", _ASP_HBA_, _C_,
HB_ASP_C[0], HB_ASP_C[1]);
out << buf << endl;
sprintf(buf, "%ld %ld %lf %lf", _ASP_HBA_, _CA_,
HB_ASP_CA[0], HB_ASP_CA[1]);
out << buf << endl;
/*ASN*/
sprintf(buf, "%ld %ld %lf %lf %lf", _N_HB_, _ASN_HBA_,
HB_ASN_N[0], HB_ASN_N[1]+eps, -fabs(EHB_S_M));
out << buf << endl;
sprintf(buf, "%ld %ld %lf %lf", _ASN_HBA_, _C_,
HB_ASN_C[0], HB_ASN_C[1]);
out << buf << endl;
sprintf(buf, "%ld %ld %lf %lf", _ASN_HBA_, _CA_,
HB_ASN_CA[0], HB_ASN_CA[1]);
out << buf << endl;
// /*GLU*/
// sprintf(buf, "%ld %ld %lf %lf %lf", _N_HB_, _GLU_HBA_,
// HB_GLU_N[0], HB_GLU_N[1]+eps, -fabs(EHB_S_M));
// out << buf << endl;
// sprintf(buf, "%ld %ld %lf %lf", _GLU_HBA_, _C_,
// HB_GLU_C[0], HB_GLU_C[1]);
// out << buf << endl;
// sprintf(buf, "%ld %ld %lf %lf", _GLU_HBA_, _CA_,
// HB_GLU_CA[0], HB_GLU_CA[1]);
// out << buf << endl;
// /*GLN*/
// sprintf(buf, "%ld %ld %lf %lf %lf", _N_HB_, _GLN_HBA_,
// HB_GLN_N[0], HB_GLN_N[1]+eps, -fabs(EHB_S_M));
// out << buf << endl;
// sprintf(buf, "%ld %ld %lf %lf", _GLN_HBA_, _C_,
// HB_GLN_C[0], HB_GLN_C[1]);
// out << buf << endl;
// sprintf(buf, "%ld %ld %lf %lf", _GLN_HBA_, _CA_,
// HB_GLN_CA[0], HB_GLN_CA[1]);
// out << buf << endl;
/*SER*/
sprintf(buf, "%ld %ld %lf %lf %lf", _N_HB_, _SER_HBA_,
HB_SER_N[0], HB_SER_N[1]+eps, -fabs(EHB_S_M));
out << buf << endl;
sprintf(buf, "%ld %ld %lf %lf", _SER_HBA_, _C_,
HB_SER_C[0], HB_SER_C[1]);
out << buf << endl;
sprintf(buf, "%ld %ld %lf %lf", _SER_HBA_, _CA_,
HB_SER_CA[0], HB_SER_CA[1]);
out << buf << endl;
/*THR*/
sprintf(buf, "%ld %ld %lf %lf %lf", _N_HB_, _THR_HBA_,
HB_THR_N[0], HB_THR_N[1]+eps, -fabs(EHB_S_M));
out << buf << endl;
sprintf(buf, "%ld %ld %lf %lf", _THR_HBA_, _C_,
HB_THR_C[0], HB_THR_C[1]);
out << buf << endl;
sprintf(buf, "%ld %ld %lf %lf", _THR_HBA_, _CA_,
HB_THR_CA[0], HB_THR_CA[1]);
out << buf << endl;
//HBD
// sprintf(buf, "%ld %ld %lf %lf %lf", _O_HB_, _ASN_HBD_,
// HBD_ASN_O[0], HBD_ASN_O[1]+eps, -fabs(EHB_S_M));
// out << buf << endl;
// sprintf(buf, "%ld %ld %lf %lf", _C_, _ASN_HBD_,
// HBD_ASN_C[0], HBD_ASN_C[1]);
// out << buf << endl;
// sprintf(buf, "%ld %ld %lf %lf %lf", _O_HB_, _GLN_HBD_,
// HBD_GLN_O[0], HBD_GLN_O[1]+eps, -fabs(EHB_S_M));
// out << buf << endl;
// sprintf(buf, "%ld %ld %lf %lf", _C_, _GLN_HBD_,
// HBD_GLN_C[0], HBD_GLN_C[1]);
// out << buf << endl;
sprintf(buf, "%ld %ld %lf %lf %lf", _O_HB_, _SER_HBD_,
HBD_SER_O[0], HBD_SER_O[1]+eps, -fabs(EHB_S_M));
out << buf << endl;
sprintf(buf, "%ld %ld %lf %lf", _C_, _SER_HBD_,
HBD_SER_C[0], HBD_SER_C[1]);
out << buf << endl;
sprintf(buf, "%ld %ld %lf %lf %lf", _O_HB_, _THR_HBD_,
HBD_THR_O[0], HBD_THR_O[1]+eps, -fabs(EHB_S_M));
out << buf << endl;
sprintf(buf, "%ld %ld %lf %lf", _C_, _THR_HBD_,
HBD_THR_C[0], HBD_THR_C[1]);
out << buf << endl;
}
void printREACT(ostream& out){
out << txtKeyWords[REACT] << endl;
char buf[1024];
/*mainchain hydrogen bonding*/
sprintf(buf, "%ld %ld %ld %ld 1",
_N_, _O_, _N_HB_, _O_HB_);
out << buf << endl;
sprintf(buf, "%ld %ld %ld %ld 1",
_N_, _C_, _N_HB_, _C_);
out << buf << endl;
sprintf(buf, "%ld %ld %ld %ld 1",
_O_, _C_, _O_HB_, _C_);
out << buf << endl;
sprintf(buf, "%ld %ld %ld %ld 1",
_O_, _CA_, _O_HB_, _CA_);
out << buf << endl;
/*side-main hydrogen bonding*/
sprintf(buf, "%ld %ld %ld %ld 1",
_N_, _ASP_CG_, _N_HB_, _ASP_HBA_);
out << buf << endl;
sprintf(buf, "%ld %ld %ld %ld 1",
_N_, _ASN_CG_, _N_HB_, _ASN_HBA_);
out << buf << endl;
// sprintf(buf, "%ld %ld %ld %ld 1",
// _N_, _GLU_CG_, _N_HB_, _GLU_HBA_);
// out << buf << endl;
// sprintf(buf, "%ld %ld %ld %ld 1",
// _N_, _GLN_CG_, _N_HB_, _GLN_HBA_);
// out << buf << endl;
sprintf(buf, "%ld %ld %ld %ld 1",
_N_, _SER_CG_, _N_HB_, _SER_HBA_);
out << buf << endl;
sprintf(buf, "%ld %ld %ld %ld 1",
_N_, _THR_CG2_, _N_HB_, _THR_HBA_);
out << buf << endl;
// sprintf(buf, "%ld %ld %ld %ld 1",
// _C_, _ASN_CG_, _O_HB_, _ASN_HBD_);
// out << buf << endl;
// sprintf(buf, "%ld %ld %ld %ld 1",
// _C_, _GLN_CG_, _O_HB_, _GLN_HBD_);
// out << buf << endl;
sprintf(buf, "%ld %ld %ld %ld 1",
_O_, _SER_CG_, _O_HB_, _SER_HBD_);
out << buf << endl;
sprintf(buf, "%ld %ld %ld %ld 1",
_O_, _THR_CG_, _O_HB_, _THR_HBD_);
out << buf << endl;
}
void printATOM_LIST(ostream& out, pseudoPep& p, vector<double>xyz, randomGenerator& r){
out << txtKeyWords[LIST_ATOMS] << endl;
char buf[1024];
vec v;
vec pos;
int index=1;
atom* CB;
atom* CG;
atom* CG2;
atom* CD;
dmd_atom_t type;
for(int i=0; i<p.getLength(); i++){
pseudoAA* theAA = p.getResidue(i);
/*N*/
v = vec(r.nextGauss(), r.nextGauss(), r.nextGauss());
pos = vec(xyz[3*index-3],xyz[3*index-2],xyz[3*index-1]);
if(theAA->getID()==PRO){
list_atom_sprint(buf, index++, _PRO_N_, pos, v);
}
else{
if(i==0)/*first N atom will be hydrogen-active!*/
list_atom_sprint(buf, index++, _N_HB_, pos, v);
else
list_atom_sprint(buf, index++, _N_, pos, v);
}
out << buf << endl;
/*C*/
v = vec(r.nextGauss(), r.nextGauss(), r.nextGauss());
pos = vec(xyz[3*index-3],xyz[3*index-2],xyz[3*index-1]);
list_atom_sprint(buf, index++, _C_, pos, v);
out << buf << endl;
/*O*/
v = vec(r.nextGauss(), r.nextGauss(), r.nextGauss());
pos = vec(xyz[3*index-3],xyz[3*index-2],xyz[3*index-1]);
if(i<p.getLength()-1){
list_atom_sprint(buf, index++, _O_, pos, v);
}
else{
list_atom_sprint(buf, index++, _O_HB_, pos, v);
}
out << buf << endl;
/*CA*/
pos = vec(xyz[3*index-3],xyz[3*index-2],xyz[3*index-1]);
v = vec(r.nextGauss(), r.nextGauss(), r.nextGauss());
list_atom_sprint(buf, index++, _CA_, pos, v);
out << buf << endl;
/*CB*/
if(CB = theAA->getCB()){
type = static_cast<dmd_atom_t>(theAA->getID()+_CYS_CB_);
v = vec(r.nextGauss(), r.nextGauss(), r.nextGauss());
pos = vec(xyz[3*index-3],xyz[3*index-2],xyz[3*index-1]);
list_atom_sprint(buf, index++, type, pos, v);
out << buf << endl;
/*CG*/
if(CG = theAA->getG()){
type = static_cast<dmd_atom_t>(theAA->getID()+_CYS_CG_);
double mass = G1_CONST[theAA->getID()][G1_M];
v = vec(r.nextGauss(), r.nextGauss(), r.nextGauss())/sqrt(mass);
pos = vec(xyz[3*index-3],xyz[3*index-2],xyz[3*index-1]);
list_atom_sprint(buf, index++, type, pos, v);
out << buf << endl;
/*CG2*/
if(CG2 = theAA->getG2()){
if(theAA->getID()==ILE) type = _ILE_CG2_;
else if(theAA->getID()==THR) type = _THR_CG2_;
else if(theAA->getID()==VAL) type = _VAL_CG2_;
else{
cerr << "error in type" << endl;
exit(1);
}
v = vec(r.nextGauss(), r.nextGauss(), r.nextGauss());
pos = vec(xyz[3*index-3],xyz[3*index-2],xyz[3*index-1]);
list_atom_sprint(buf, index++, type, pos, v);
out << buf << endl;
}
/*CD*/
if(CD = theAA->getD()){
if(theAA->getID()==TRP) type = _TRP_CD_;
else if(theAA->getID()==ARG) type = _ARG_CD_;
else if(theAA->getID()==LYS) type = _LYS_CD_;
else{
cerr << "error in type" << endl;
exit(1);
}
v = vec(r.nextGauss(), r.nextGauss(), r.nextGauss());
pos = vec(xyz[3*index-3],xyz[3*index-2],xyz[3*index-1]);
list_atom_sprint(buf, index++, type, pos, v);
out << buf << endl;
}
}
}
}
}
void printBOND_LIST(ostream& out, pseudoPep& p){
out << txtKeyWords[LIST_BONDS] << endl;
char buf[1024];
for(int i=0; i<p.getLength(); i++){
/*intra amino acids*/
pseudoAA* theAA = p.getResidue(i);
/*N-CA*/
out << theAA->getN()->getIndex() << " " << theAA->getCA()->getIndex() << endl;
/*CA-C*/
out << theAA->getCA()->getIndex() << " " << theAA->getC()->getIndex() << endl;
/*N-C*/
out << theAA->getN()->getIndex() << " " << theAA->getC()->getIndex() << endl;
/*C-O*/
out << theAA->getC()->getIndex() << " " << theAA->getO()->getIndex() << endl;
/*CA-O*/
out << theAA->getCA()->getIndex() << " " << theAA->getO()->getIndex() << endl;
if(theAA->getCB()){/*not GLY*/
/*CA-CB*/
out << theAA->getCA()->getIndex() << " " << theAA->getCB()->getIndex() << endl;
/*N-CB*/
out << theAA->getN()->getIndex() << " " << theAA->getCB()->getIndex() << endl;
/*C-CB*/
out << theAA->getC()->getIndex() << " " << theAA->getCB()->getIndex() << endl;
if(theAA->getG()){/*not ALA*/
/*CB-CG*/
out << theAA->getCB()->getIndex() << " " << theAA->getG()->getIndex() << endl;
/*CA-CG*/
out << theAA->getCA()->getIndex() << " " << theAA->getG()->getIndex() << endl;
/*N-CG, C-CG*/
int id = theAA->getID();
if(Dihedral_C_CG[id][0]!=INF){
out << theAA->getC()->getIndex() << " " << theAA->getG()->getIndex() << endl;
out << theAA->getN()->getIndex() << " " << theAA->getG()->getIndex() << endl;
}
if(theAA->getG2()){/*beta-branched*/
/*CG2-CB*/
out << theAA->getCB()->getIndex() << " " << theAA->getG2()->getIndex() << endl;
/*CG2-CA*/
out << theAA->getCA()->getIndex() << " " << theAA->getG2()->getIndex() << endl;
/*CG2-CG*/
out << theAA->getG()->getIndex() << " " << theAA->getG2()->getIndex() << endl;
/*C-CG2*/
out << theAA->getC()->getIndex() << " " << theAA->getG2()->getIndex() << endl;
/*N-CG2*/
out << theAA->getN()->getIndex() << " " << theAA->getG2()->getIndex() << endl;
}
if(theAA->getD()){
dmd_atom_t dt;
if(theAA->getID()==ARG) dt = _ARG_CD_;
else if(theAA->getID()==LYS) dt = _LYS_CD_;
else if(theAA->getID()==TRP) dt = _TRP_CD_;
/*CG-CD*/
out << theAA->getG()->getIndex() << " " << theAA->getD()->getIndex() << endl;
/*CB-CD*/
out << theAA->getCB()->getIndex() << " " << theAA->getD()->getIndex() << endl;
/*CA-CD---Dihedral of TRP*/
if(theAA->getID()==TRP){
out << theAA->getCA()->getIndex() << " " << theAA->getD()->getIndex() << endl;
}
}
}
}
/*extra constraints for PRO*/
if(theAA->getID()==PRO){
out << theAA->getN()->getIndex() << " " << theAA->getG()->getIndex() << endl;
}
/*inter amino acids*/
if(i>0){
pseudoAA* preAA = p.getResidue(i-1);
/*Ca0 -- N1*/
out << preAA->getCA()->getIndex() << " " << theAA->getN()->getIndex() << endl;
/*C0 -- Ca1*/
out << preAA->getC()->getIndex() << " " << theAA->getCA()->getIndex() << endl;
/*C0 -- N1*/
out << preAA->getC()->getIndex() << " " << theAA->getN()->getIndex() << endl;
/*O0--N1*/
out << preAA->getO()->getIndex() << " " << theAA->getN()->getIndex() << endl;
/*Ca0 -- Ca1*/
out << preAA->getCA()->getIndex() << " " << theAA->getCA()->getIndex() << endl;
if(theAA->getID()==PRO){
out << preAA->getC()->getIndex() << " " << theAA->getCB()->getIndex() << endl;
out << preAA->getC()->getIndex() << " " << theAA->getG()->getIndex() << endl;
out << preAA->getC()->getIndex() << " " << theAA->getC()->getIndex() << endl;
}
}
}
}
void printPERM_BOND_LIST(ostream& out, pseudoPep& p){
out << txtKeyWords[LIST_PERM_BONDS] << endl;
char buf[1024];
for(int i=0; i<p.getLength(); i++){
/*intra amino acids*/
pseudoAA* theAA = p.getResidue(i);
/*N-CA*/
out << theAA->getN()->getIndex() << " " << theAA->getCA()->getIndex() << " "
<< _N_ << " " << _CA_ << endl;
/*CA-C*/
out << theAA->getCA()->getIndex() << " " << theAA->getC()->getIndex() << " "
<< _CA_ << " " << _C_ << endl;
/*N-C*/
out << theAA->getN()->getIndex() << " " << theAA->getC()->getIndex() << " "
<< _N_ << " " << _C_ << endl;
/*C-O*/
out << theAA->getC()->getIndex() << " " << theAA->getO()->getIndex() << " "
<< _C_ << " " << _O_ << endl;
/*CA-O*/
out << theAA->getCA()->getIndex() << " " << theAA->getO()->getIndex() << " "
<< _CA_ << " " << _O_ << endl;
if(theAA->getCB()){/*not GLY*/
dmd_atom_t cbt = _CB_;
if(theAA->getID()==PRO) cbt = _PRO_CB_;
/*CA-CB*/
out << theAA->getCA()->getIndex() << " " << theAA->getCB()->getIndex() << " "
<< _CA_ << " " << cbt << endl;
/*N-CB*/
out << theAA->getN()->getIndex() << " " << theAA->getCB()->getIndex() << " "
<< _N_ << " " << cbt << endl;
/*C-CB*/
out << theAA->getC()->getIndex() << " " << theAA->getCB()->getIndex() << " "
<< _C_ << " " << cbt << endl;
if(theAA->getG()){/*not ALA*/
dmd_atom_t gt = static_cast<dmd_atom_t>(_CYS_CG_ + theAA->getID());
/*CB-CG*/
out << theAA->getCB()->getIndex() << " " << theAA->getG()->getIndex() << " "
<< cbt << " " << gt << endl;
/*CA-CG*/
out << theAA->getCA()->getIndex() << " " << theAA->getG()->getIndex() << " "
<< _CA_ << " " << gt << endl;
if(Dihedral_C_CG[theAA->getID()][0]!=INF){
/*N-CG*/
out << theAA->getN()->getIndex() << " " << theAA->getG()->getIndex() << " "
<< _N_ << " " << gt << endl;
/*C-CG*/
out << theAA->getC()->getIndex() << " " << theAA->getG()->getIndex() << " "
<< _C_ << " " << gt << endl;
}
if(theAA->getG2()){/*beta-branched*/
dmd_atom_t g2t;
if(theAA->getID() == ILE) g2t = _ILE_CG2_;
else if(theAA->getID() == THR) g2t = _THR_CG2_;
else if(theAA->getID() == VAL) g2t = _VAL_CG2_;
/*CB-CG2*/
out << theAA->getCB()->getIndex() << " " << theAA->getG2()->getIndex() << " "
<< cbt << " " << g2t << endl;
/*CA-CG2*/
out << theAA->getCA()->getIndex() << " " << theAA->getG2()->getIndex() << " "
<< _CA_ << " " << g2t << endl;
/*CG-CG2*/
out << theAA->getG()->getIndex() << " " << theAA->getG2()->getIndex() << " "
<< gt << " " << g2t << endl;
/*N-CG2*/
out << theAA->getN()->getIndex() << " " << theAA->getG2()->getIndex() << " "
<< _N_ << " " << g2t << endl;
/*C-CG2*/
out << theAA->getC()->getIndex() << " " << theAA->getG2()->getIndex() << " "
<< _C_ << " " << g2t << endl;
}
if(theAA->getD()){/*bulky residues with Cd*/
dmd_atom_t dt;
if(theAA->getID()==ARG) dt = _ARG_CD_;
else if(theAA->getID()==LYS) dt = _LYS_CD_;
else if(theAA->getID()==TRP) dt = _TRP_CD_;
/*CG-CD*/
out << theAA->getG()->getIndex() << " " << theAA->getD()->getIndex() << " "
<< gt << " " << dt << endl;
/*CB-CD*/
out << theAA->getCB()->getIndex() << " " << theAA->getD()->getIndex() << " "
<< cbt << " " << dt << endl;
/*CA-CD, TRP--Dihedral*/
if(theAA->getID()==TRP){
out << theAA->getCA()->getIndex() << " " << theAA->getD()->getIndex() << " "
<< _CA_ << " " << _TRP_CD_ << endl;
}
}
/*extra constraints for PRO: N-CG*/
if(theAA->getID()==PRO){
out << theAA->getN()->getIndex() << " " << theAA->getG()->getIndex() << " "
<< _N_ << " " << gt << endl;
}
}
}
/*inter amino acids*/
if(i>0){
pseudoAA* preAA = p.getResidue(i-1);
/*Ca0 -- N1*/
out << preAA->getCA()->getIndex() << " " << theAA->getN()->getIndex() << " "
<< _CA_ << " " << _N_ << endl;
/*C0 -- Ca1*/
out << preAA->getC()->getIndex() << " " << theAA->getCA()->getIndex() << " "
<< _C_ << " " << _CA_ << endl;
/*C0 -- N1*/
out << preAA->getC()->getIndex() << " " << theAA->getN()->getIndex() << " "
<< _C_ << " " << _N_ << endl;
/*O0--N1*/
out << preAA->getO()->getIndex() << " " << theAA->getN()->getIndex() << " "
<< _O_ << " " << _N_ << endl;
/*Ca0 -- Ca1*/
out << preAA->getCA()->getIndex() << " " << theAA->getCA()->getIndex() << " "
<< _CA_ << " " << _CA_ << endl;
if(theAA->getID()==PRO){
out << preAA->getC()->getIndex() << " " << theAA->getCB()->getIndex() << " "
<< _C_ << " " << _PRO_CB_ << endl;
out << preAA->getC()->getIndex() << " " << theAA->getG()->getIndex() << " "
<< _C_ << " " << _PRO_CG_ << endl;
out << preAA->getC()->getIndex() << " " << theAA->getC()->getIndex() << " "
<< _C_ << " " << _C_ << endl;
}
}
}
}
void printHBA_LIST(ostream& out, pseudoPep& p){
out << txtKeyWords[HB_LIST] << endl;
char buf[1024];
for(int i=0; i<p.getLength(); i++){
/*N*/
if(i>0){
sprintf(buf, "%ld %ld %ld %ld",
p.getResidue(i)->getN()->getIndex(), i,
p.getResidue(i-1)->getC()->getIndex(),
p.getResidue(i)->getCA()->getIndex());
out << buf << endl;
}
/*O*/
if(i<p.getLength()-1){
sprintf(buf, "%ld %ld %ld",
p.getResidue(i)->getO()->getIndex(), i,
p.getResidue(i)->getC()->getIndex());
out << buf << endl;
}
/*HBA*/
aa_t type = static_cast<aa_t>(p.getResidue(i)->getID());
/*do not consider GLN/GLU*/
if(type==ASP || type==ASN || type==SER){
sprintf(buf, "%ld %ld", p.getResidue(i)->getG()->getIndex(), i);
out << buf << endl;
}
else if(type==THR){
sprintf(buf, "%ld %ld", p.getResidue(i)->getG2()->getIndex(), i);
out << buf << endl;
}
}
}
void print_GID(ostream& out, pseudoPep& p){
out << txtKeyWords[GID_LIST] << endl;
char buf[1024];
for(int i=0; i<p.getLength(); i++){
aa_t type = static_cast<aa_t>(p.getResidue(i)->getID());
if(type!=GLY){
/*CB*/
sprintf(buf, "%ld %ld", p.getResidue(i)->getCB()->getIndex(), i);
out << buf<< endl;
/*CG*/
if(type!=ALA){
sprintf(buf, "%ld %ld", p.getResidue(i)->getG()->getIndex(), i);
out << buf << endl;
/*CG2*/
if(type==ILE || type==VAL || type==THR){
sprintf(buf, "%ld %ld", p.getResidue(i)->getG2()->getIndex(), i);
out << buf << endl;
}
/*CD*/
if(type==ARG || type==LYS || type==TRP){
sprintf(buf, "%ld %ld", p.getResidue(i)->getD()->getIndex(), i);
out << buf << endl;
}
}
}
}
}
vec getCM(pseudoPep& p){
vec tmp(0,0,0);
int natom=0;
for(int i=0; i<p.getLength(); i++){
pseudoAA* theAA = p.getResidue(i);
tmp += *theAA->getN()->getR(); natom++;
tmp += *theAA->getC()->getR(); natom++;
tmp += *theAA->getO()->getR(); natom++;
tmp += *theAA->getCA()->getR(); natom++;
if(theAA->getCB()) {
tmp += *theAA->getCB()->getR();
natom++;
if(theAA->getG()){
tmp += *theAA->getG()->getR();
natom++;
if(theAA->getG2()){
tmp += *theAA->getG2()->getR();
natom++;
}
if(theAA->getD()){
tmp += *theAA->getD()->getR();
natom++;
}
}
}
}
tmp /= static_cast<double>(natom);
return tmp;
}
typedef enum {
NON_ENER_KEY=-1,E_HB_MM=0, E_HB_SM, E_HH, E_HA, E_SB, E_AROMATIC, E_ARO_PRO, E_ROTAMER
} ener_t;
const static char* ener_key[] = {
"E_HB_MM",
"E_HB_SM",
"E_HH",
"E_HA",
"E_SB",
"E_AROMATIC",
"E_ARO_PRO",
"E_ROTAMER"
};
void process_para(const char* para_f){
FILE* in = fopen(para_f,"r");
char keyword[100];
char val[100];
ener_t key;
if(!in) cerr << "Can not open the parameter file!\n" << endl;
while(!feof(in)){
fscanf(in, "%s%s", keyword, val);
key = NON_ENER_KEY;
for(int i=0; i<sizeof(ener_key)/sizeof(char*); i++){
if(strcmp(ener_key[i], keyword)==0){
key = static_cast<ener_t>(i);
break;
}
}
switch(key){
case E_HB_MM:
setMMHB_E(atof(val));
break;
case E_HB_SM:
setSMHB_E(atof(val));
break;
case E_HH:
setHP_E(atof(val));
break;
case E_HA:
setHA_E(atof(val));
break;
case E_SB:
setSB_E(atof(val));
break;
case E_AROMATIC:
setAROMATIC_E(atof(val));
break;
case E_ARO_PRO:
setARO_PRO_E(atof(val));
break;
case E_ROTAMER:
setDI_E(atof(val));
break;
default:
break;
}
}
fclose(in);
}
int main(int argc, char* argv[]){
if(argc<5){
cout << "usage: command seq relaxedTXT E_Para_F ir_ext [is_ExN]" << endl;
cout << "ir_ext: external radius. If set to zero, then we do not add external radius";
cout << " is_ExN -- OPT parameter to exclude neightbouring interaction: 0/1" << endl;
exit(1);
}
process_para(argv[3]);
ir_ext = atof( argv[4] );
int is_en=0;
if(argc==6){
is_en = atoi(argv[5]);
}
pseudoPep p(argv[1], (input_t)0);
pseudoAA* lastAA=p.getResidue(p.getLength()-1);
lastAA->getO()->getR()->Rotate(*lastAA->getCA()->getR(),*lastAA->getC()->getR(), -PI/3.0);
p.makeIndex();
randomGenerator ran(_RAN2_, -100);
double size;
vec cm = getCM(p);
vec shift = vec(size/2.0, size/2.0, size/2.0) - cm;
p.shift(shift);
vector<double>xyz;
process_txt(argv[2], size, xyz);
/*create the TXT*/
printSYS_SIZE(cout, size);
printNUM_ATOMS(cout, p);
printATOM_TYPE(cout);
printNONEL_COL(cout);
printEL_COL(cout);
printBOND_TYPE(cout);
printREACT(cout);
printATOM_LIST(cout, p, xyz, ran);
printBOND_LIST(cout, p);
printPERM_BOND_LIST(cout, p);
printHBA_LIST(cout, p);
if(is_en) print_GID(cout, p);
/*END of the txt output*/
}
|
[
"borreguero@gmail.com"
] |
borreguero@gmail.com
|
9c7f46fbe2f48dfd946d5f9ded8a91c8b1003304
|
79cb191be612b15d12c791381d290f256e3d5406
|
/Framework Praktikum 2/Matrix4.cpp
|
8680b6a6eb9096e623a68df2819acbc5167ddd03
|
[] |
no_license
|
cr4ckl1n/GEMCAD-1
|
ccea1fe523549f94cde6d0d9d35bfe170dd3489d
|
935770d5e1dc3edc8819662ad506e1cdd5dffcec
|
refs/heads/master
| 2021-01-10T13:18:44.096448
| 2016-01-27T08:30:30
| 2016-01-27T08:30:30
| 47,255,637
| 0
| 3
| null | 2016-01-27T08:30:32
| 2015-12-02T11:04:20
|
C++
|
MacCentralEurope
|
C++
| false
| false
| 5,607
|
cpp
|
// ========================================================================= //
// Authors: Matthias Bein //
// mailto:matthias.bein@igd.fraunhofer.de //
// //
// GRIS - Graphisch Interaktive Systeme //
// Technische Universitšt Darmstadt //
// Fraunhoferstrasse 5 //
// D-64283 Darmstadt, Germany //
// //
// Creation Date: 29.10.2013 //
// ========================================================================= //
#include "Matrix4.h"
#include <stdio.h> // cout
#include <iostream> // cout
Matrix4f::Matrix4f()
{
for(unsigned int row = 0; row < 4; ++row)
{
for(unsigned int column = 0; column < 4; ++column)
{
if(row == column)
values[row][column] = 1.0f;
else
values[row][column] = 0.0f;
}
}
}
Matrix4f::Matrix4f(float val)
{
for(unsigned int row = 0; row < 4; ++row)
{
for(unsigned int column = 0; column < 4; ++column)
{
values[row][column] = val;
}
}
}
Matrix4f Matrix4f::operator* (const Matrix4f& rightMatrix) const
{
// start with 0-matrix
Matrix4f result(0.0f);
for(int row =0 ; row < 4; row ++)
{
for( int col = 0 ; col < 4 ; col ++)
{
result.values[row][col] = this->values[row][0] * rightMatrix.values[0][col]
+this->values[row][1] * rightMatrix.values[1][col]
+ this->values[row][2] * rightMatrix.values[2][col]
+ this->values[row][3] * rightMatrix.values[3][col];
Matrix4f test= Matrix4f::values[row][col];
// printf("%d", test);
}
}
return result;
}
Vec4f Matrix4f::operator* (const Vec4f& vec) const
{
// start with 0-vector
Vec4f result;
for(int row =0 ; row < 4; row ++)
{
for( int col = 0 ; col < 4 ; col ++)
{
result[row] = this->values[row][0] * vec[0]
+this->values[row][1] * vec[1]
+ this->values[row][2] * vec[2]
+ this->values[row][3] * vec[3];
}
}
return result;
}
Vec3f Matrix4f::operator*(const Vec3f& vec) const
{
Vec4f v4(vec.x, vec.y, vec.z, 1.0f);
Vec4f result = *this * v4;
result.homogenize();
return Vec3f(result.x, result.y, result.z);
}
std::ostream& operator<< (std::ostream& os, const Matrix4f& matrix)
{
os << matrix.values[0][0] << ", " << matrix.values[0][1] << ", " << matrix.values[0][2] << ", " << matrix.values[0][3] << std::endl
<< matrix.values[1][0] << ", " << matrix.values[1][1] << ", " << matrix.values[1][2] << ", " << matrix.values[1][3] << std::endl
<< matrix.values[2][0] << ", " << matrix.values[2][1] << ", " << matrix.values[2][2] << ", " << matrix.values[2][3] << std::endl
<< matrix.values[3][0] << ", " << matrix.values[3][1] << ", " << matrix.values[3][2] << ", " << matrix.values[3][3];
return os;
}
// ==================================================
Matrix4f Matrix4f::rotationXMatrix(float angle)
{
Matrix4f result;
result.values[1][1] = std::cosf(angle);
result.values[1][2] = - std::sinf(angle);
result.values[2][1] = std::sinf(angle);
result.values[2][2] = std::cosf(angle);
return result;
}
Matrix4f Matrix4f::rotationYMatrix(float angle)
{
Matrix4f result;
result.values[0][0] = std::cosf(angle);
result.values[0][2] = std::sinf(angle);
result.values[2][0] = -std::sinf(angle);
result.values[2][2] = std::cosf(angle);
return result;
}
Matrix4f Matrix4f::rotationZMatrix(float angle)
{
Matrix4f result;
result.values[0][0] = std::cosf(angle);
result.values[0][1] = - std::sinf(angle);
result.values[1][0] = std::sinf(angle);
result.values[1][1] = std::cosf(angle);
return result;
}
Matrix4f Matrix4f::scaleMatrix(float sx, float sy, float sz){
Matrix4f result;
result.values[0][0] = sx;
result.values[1][1] = sy;
result.values[2][2] = sz;
return result;
}
Matrix4f Matrix4f::translateMatrix(int dx, int dy, int dz){
Matrix4f result;
result.values[0][3] = dx;
result.values[1][3] = dy;
result.values[2][3] = dz;
return result;
}
Matrix4f Matrix4f::quaternion(double a, double b, double c, double d){
Matrix4f result;
result.values[0][0] = (a*a) + (b*b) - (c*c) -(d*d);
result.values[1][0] = 2.0f*((b*c) -(a*d));
result.values[2][0] = 2.0f*(b*d+a*c);
result.values[0][1] = 2.0f*(b*c+a*d);
result.values[1][1] = (a*a) - (b*b) + (c*c) - (d*d);
result.values[2][1] = 2.0f*(c*d-a*b);
result.values[0][2] = 2.0f*(b*d-a*c);
result.values[1][2] = 2.0f*(c*d+a*b);
result.values[2][2] = (a*a)-(b*b)-(c*c)+(d*d);
return result;
}
Matrix4f Matrix4f::test_Multiplikation(){
Matrix4f a(1.0f);
Matrix4f b(1.0f);
float c=2.0f;
for (int row=0 ; row < 4 ; row++){
for(int col=0; col < 4; col++){
a.values[row][col] = a.values[row][col] +c;
b.values[row][col] = a.values[row][col] +(2.0f*c);
}
}
std::cout << a << std::endl;
std::cout << b << std::endl;
Matrix4f result = a.operator*(b);
std::cout << result << std::endl;
return result;
}
Vec4f Matrix4f::test_vecMult(){
Matrix4f a(2.0f);
Vec4f b;
b[3] = 1.0f;
b.x = 2.0f;
b.y = 3.0f;
b.z = 4.0f;
std::cout << b << std::endl;
std::cout << "\n" << std::endl;
std::cout << a << std::endl;
std::cout << "\n" << std::endl;
Vec4f result = a.operator*(b);
std::cout << result << std::endl;
return result;
}
// ==================================================
|
[
"cr4kl1n@gmail.com"
] |
cr4kl1n@gmail.com
|
d23236156489e847368bd1cd87e77cd030ede2e9
|
d79408a9616a8ff8ac9375b9fffaa45ae6698fd5
|
/src/rpc/rawtransaction.cpp
|
a4745ac25c4341ca87809c750df9d380ab44bad3
|
[
"MIT"
] |
permissive
|
Schepses/nero
|
6c77f5df6afd36a6ebcb14af1d8257d918d7bda7
|
7ec5e3a6c7f1c75f5ec15b1f4d0bcb9cdc0ec9b0
|
refs/heads/master
| 2020-03-07T13:43:18.425050
| 2018-03-28T12:27:27
| 2018-03-28T12:27:27
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 39,564
|
cpp
|
// Copyright (c) 2010 Satoshi Nakamoto
// Copyright (c) 2009-2015 The Bitcoin Core developers
// Copyright (c) 2014-2017 The Nero Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "base58.h"
#include "chain.h"
#include "coins.h"
#include "consensus/validation.h"
#include "core_io.h"
#include "init.h"
#include "keystore.h"
#include "validation.h"
#include "merkleblock.h"
#include "net.h"
#include "policy/policy.h"
#include "primitives/transaction.h"
#include "rpc/server.h"
#include "script/script.h"
#include "script/script_error.h"
#include "script/sign.h"
#include "script/standard.h"
#include "txmempool.h"
#include "uint256.h"
#include "utilstrencodings.h"
#include "instantx.h"
#ifdef ENABLE_WALLET
#include "wallet/wallet.h"
#endif
#include <stdint.h>
#include <boost/assign/list_of.hpp>
#include <univalue.h>
using namespace std;
void ScriptPubKeyToJSON(const CScript& scriptPubKey, UniValue& out, bool fIncludeHex)
{
txnouttype type;
vector<CTxDestination> addresses;
int nRequired;
out.push_back(Pair("asm", ScriptToAsmStr(scriptPubKey)));
if (fIncludeHex)
out.push_back(Pair("hex", HexStr(scriptPubKey.begin(), scriptPubKey.end())));
if (!ExtractDestinations(scriptPubKey, type, addresses, nRequired)) {
out.push_back(Pair("type", GetTxnOutputType(type)));
return;
}
out.push_back(Pair("reqSigs", nRequired));
out.push_back(Pair("type", GetTxnOutputType(type)));
UniValue a(UniValue::VARR);
BOOST_FOREACH(const CTxDestination& addr, addresses)
a.push_back(CBitcoinAddress(addr).ToString());
out.push_back(Pair("addresses", a));
}
void TxToJSON(const CTransaction& tx, const uint256 hashBlock, UniValue& entry)
{
uint256 txid = tx.GetHash();
entry.push_back(Pair("txid", txid.GetHex()));
entry.push_back(Pair("size", (int)::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION)));
entry.push_back(Pair("version", tx.nVersion));
entry.push_back(Pair("locktime", (int64_t)tx.nLockTime));
UniValue vin(UniValue::VARR);
BOOST_FOREACH(const CTxIn& txin, tx.vin) {
UniValue in(UniValue::VOBJ);
if (tx.IsCoinBase())
in.push_back(Pair("coinbase", HexStr(txin.scriptSig.begin(), txin.scriptSig.end())));
else {
in.push_back(Pair("txid", txin.prevout.hash.GetHex()));
in.push_back(Pair("vout", (int64_t)txin.prevout.n));
UniValue o(UniValue::VOBJ);
o.push_back(Pair("asm", ScriptToAsmStr(txin.scriptSig, true)));
o.push_back(Pair("hex", HexStr(txin.scriptSig.begin(), txin.scriptSig.end())));
in.push_back(Pair("scriptSig", o));
// Add address and value info if spentindex enabled
CSpentIndexValue spentInfo;
CSpentIndexKey spentKey(txin.prevout.hash, txin.prevout.n);
if (GetSpentIndex(spentKey, spentInfo)) {
in.push_back(Pair("value", ValueFromAmount(spentInfo.satoshis)));
in.push_back(Pair("valueSat", spentInfo.satoshis));
if (spentInfo.addressType == 1) {
in.push_back(Pair("address", CBitcoinAddress(CKeyID(spentInfo.addressHash)).ToString()));
} else if (spentInfo.addressType == 2) {
in.push_back(Pair("address", CBitcoinAddress(CScriptID(spentInfo.addressHash)).ToString()));
}
}
}
in.push_back(Pair("sequence", (int64_t)txin.nSequence));
vin.push_back(in);
}
entry.push_back(Pair("vin", vin));
UniValue vout(UniValue::VARR);
for (unsigned int i = 0; i < tx.vout.size(); i++) {
const CTxOut& txout = tx.vout[i];
UniValue out(UniValue::VOBJ);
out.push_back(Pair("value", ValueFromAmount(txout.nValue)));
out.push_back(Pair("valueSat", txout.nValue));
out.push_back(Pair("n", (int64_t)i));
UniValue o(UniValue::VOBJ);
ScriptPubKeyToJSON(txout.scriptPubKey, o, true);
out.push_back(Pair("scriptPubKey", o));
// Add spent information if spentindex is enabled
CSpentIndexValue spentInfo;
CSpentIndexKey spentKey(txid, i);
if (GetSpentIndex(spentKey, spentInfo)) {
out.push_back(Pair("spentTxId", spentInfo.txid.GetHex()));
out.push_back(Pair("spentIndex", (int)spentInfo.inputIndex));
out.push_back(Pair("spentHeight", spentInfo.blockHeight));
}
vout.push_back(out);
}
entry.push_back(Pair("vout", vout));
if (!hashBlock.IsNull()) {
entry.push_back(Pair("blockhash", hashBlock.GetHex()));
BlockMap::iterator mi = mapBlockIndex.find(hashBlock);
if (mi != mapBlockIndex.end() && (*mi).second) {
CBlockIndex* pindex = (*mi).second;
if (chainActive.Contains(pindex)) {
entry.push_back(Pair("height", pindex->nHeight));
entry.push_back(Pair("confirmations", 1 + chainActive.Height() - pindex->nHeight));
entry.push_back(Pair("time", pindex->GetBlockTime()));
entry.push_back(Pair("blocktime", pindex->GetBlockTime()));
} else {
entry.push_back(Pair("height", -1));
entry.push_back(Pair("confirmations", 0));
}
}
}
}
UniValue getrawtransaction(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 2)
throw runtime_error(
"getrawtransaction \"txid\" ( verbose )\n"
"\nNOTE: By default this function only works sometimes. This is when the tx is in the mempool\n"
"or there is an unspent output in the utxo for this transaction. To make it always work,\n"
"you need to maintain a transaction index, using the -txindex command line option.\n"
"\nReturn the raw transaction data.\n"
"\nIf verbose=0, returns a string that is serialized, hex-encoded data for 'txid'.\n"
"If verbose is non-zero, returns an Object with information about 'txid'.\n"
"\nArguments:\n"
"1. \"txid\" (string, required) The transaction id\n"
"2. verbose (numeric, optional, default=0) If 0, return a string, other return a json object\n"
"\nResult (if verbose is not set or set to 0):\n"
"\"data\" (string) The serialized, hex-encoded data for 'txid'\n"
"\nResult (if verbose > 0):\n"
"{\n"
" \"hex\" : \"data\", (string) The serialized, hex-encoded data for 'txid'\n"
" \"txid\" : \"id\", (string) The transaction id (same as provided)\n"
" \"size\" : n, (numeric) The transaction size\n"
" \"version\" : n, (numeric) The version\n"
" \"locktime\" : ttt, (numeric) The lock time\n"
" \"vin\" : [ (array of json objects)\n"
" {\n"
" \"txid\": \"id\", (string) The transaction id\n"
" \"vout\": n, (numeric) \n"
" \"scriptSig\": { (json object) The script\n"
" \"asm\": \"asm\", (string) asm\n"
" \"hex\": \"hex\" (string) hex\n"
" },\n"
" \"sequence\": n (numeric) The script sequence number\n"
" }\n"
" ,...\n"
" ],\n"
" \"vout\" : [ (array of json objects)\n"
" {\n"
" \"value\" : x.xxx, (numeric) The value in " + CURRENCY_UNIT + "\n"
" \"n\" : n, (numeric) index\n"
" \"scriptPubKey\" : { (json object)\n"
" \"asm\" : \"asm\", (string) the asm\n"
" \"hex\" : \"hex\", (string) the hex\n"
" \"reqSigs\" : n, (numeric) The required sigs\n"
" \"type\" : \"pubkeyhash\", (string) The type, eg 'pubkeyhash'\n"
" \"addresses\" : [ (json array of string)\n"
" \"neroaddress\" (string) nero address\n"
" ,...\n"
" ]\n"
" }\n"
" }\n"
" ,...\n"
" ],\n"
" \"blockhash\" : \"hash\", (string) the block hash\n"
" \"confirmations\" : n, (numeric) The confirmations\n"
" \"time\" : ttt, (numeric) The transaction time in seconds since epoch (Jan 1 1970 GMT)\n"
" \"blocktime\" : ttt (numeric) The block time in seconds since epoch (Jan 1 1970 GMT)\n"
"}\n"
"\nExamples:\n"
+ HelpExampleCli("getrawtransaction", "\"mytxid\"")
+ HelpExampleCli("getrawtransaction", "\"mytxid\" 1")
+ HelpExampleRpc("getrawtransaction", "\"mytxid\", 1")
);
LOCK(cs_main);
uint256 hash = ParseHashV(params[0], "parameter 1");
bool fVerbose = false;
if (params.size() > 1)
fVerbose = (params[1].get_int() != 0);
CTransaction tx;
uint256 hashBlock;
if (!GetTransaction(hash, tx, Params().GetConsensus(), hashBlock, true))
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "No information available about transaction");
string strHex = EncodeHexTx(tx);
if (!fVerbose)
return strHex;
UniValue result(UniValue::VOBJ);
result.push_back(Pair("hex", strHex));
TxToJSON(tx, hashBlock, result);
return result;
}
UniValue gettxoutproof(const UniValue& params, bool fHelp)
{
if (fHelp || (params.size() != 1 && params.size() != 2))
throw runtime_error(
"gettxoutproof [\"txid\",...] ( blockhash )\n"
"\nReturns a hex-encoded proof that \"txid\" was included in a block.\n"
"\nNOTE: By default this function only works sometimes. This is when there is an\n"
"unspent output in the utxo for this transaction. To make it always work,\n"
"you need to maintain a transaction index, using the -txindex command line option or\n"
"specify the block in which the transaction is included in manually (by blockhash).\n"
"\nReturn the raw transaction data.\n"
"\nArguments:\n"
"1. \"txids\" (string) A json array of txids to filter\n"
" [\n"
" \"txid\" (string) A transaction hash\n"
" ,...\n"
" ]\n"
"2. \"block hash\" (string, optional) If specified, looks for txid in the block with this hash\n"
"\nResult:\n"
"\"data\" (string) A string that is a serialized, hex-encoded data for the proof.\n"
"\nExamples:\n"
+ HelpExampleCli("gettxoutproof", "'[\"mytxid\",...]'")
+ HelpExampleCli("gettxoutproof", "'[\"mytxid\",...]' \"blockhash\"")
+ HelpExampleRpc("gettxoutproof", "[\"mytxid\",...], \"blockhash\"")
);
set<uint256> setTxids;
uint256 oneTxid;
UniValue txids = params[0].get_array();
for (unsigned int idx = 0; idx < txids.size(); idx++) {
const UniValue& txid = txids[idx];
if (txid.get_str().length() != 64 || !IsHex(txid.get_str()))
throw JSONRPCError(RPC_INVALID_PARAMETER, string("Invalid txid ")+txid.get_str());
uint256 hash(uint256S(txid.get_str()));
if (setTxids.count(hash))
throw JSONRPCError(RPC_INVALID_PARAMETER, string("Invalid parameter, duplicated txid: ")+txid.get_str());
setTxids.insert(hash);
oneTxid = hash;
}
LOCK(cs_main);
CBlockIndex* pblockindex = NULL;
uint256 hashBlock;
if (params.size() > 1)
{
hashBlock = uint256S(params[1].get_str());
if (!mapBlockIndex.count(hashBlock))
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found");
pblockindex = mapBlockIndex[hashBlock];
} else {
CCoins coins;
if (pcoinsTip->GetCoins(oneTxid, coins) && coins.nHeight > 0 && coins.nHeight <= chainActive.Height())
pblockindex = chainActive[coins.nHeight];
}
if (pblockindex == NULL)
{
CTransaction tx;
if (!GetTransaction(oneTxid, tx, Params().GetConsensus(), hashBlock, false) || hashBlock.IsNull())
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Transaction not yet in block");
if (!mapBlockIndex.count(hashBlock))
throw JSONRPCError(RPC_INTERNAL_ERROR, "Transaction index corrupt");
pblockindex = mapBlockIndex[hashBlock];
}
CBlock block;
if(!ReadBlockFromDisk(block, pblockindex, Params().GetConsensus()))
throw JSONRPCError(RPC_INTERNAL_ERROR, "Can't read block from disk");
unsigned int ntxFound = 0;
BOOST_FOREACH(const CTransaction&tx, block.vtx)
if (setTxids.count(tx.GetHash()))
ntxFound++;
if (ntxFound != setTxids.size())
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "(Not all) transactions not found in specified block");
CDataStream ssMB(SER_NETWORK, PROTOCOL_VERSION);
CMerkleBlock mb(block, setTxids);
ssMB << mb;
std::string strHex = HexStr(ssMB.begin(), ssMB.end());
return strHex;
}
UniValue verifytxoutproof(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() != 1)
throw runtime_error(
"verifytxoutproof \"proof\"\n"
"\nVerifies that a proof points to a transaction in a block, returning the transaction it commits to\n"
"and throwing an RPC error if the block is not in our best chain\n"
"\nArguments:\n"
"1. \"proof\" (string, required) The hex-encoded proof generated by gettxoutproof\n"
"\nResult:\n"
"[\"txid\"] (array, strings) The txid(s) which the proof commits to, or empty array if the proof is invalid\n"
"\nExamples:\n"
+ HelpExampleCli("verifytxoutproof", "\"proof\"")
+ HelpExampleRpc("gettxoutproof", "\"proof\"")
);
CDataStream ssMB(ParseHexV(params[0], "proof"), SER_NETWORK, PROTOCOL_VERSION);
CMerkleBlock merkleBlock;
ssMB >> merkleBlock;
UniValue res(UniValue::VARR);
vector<uint256> vMatch;
if (merkleBlock.txn.ExtractMatches(vMatch) != merkleBlock.header.hashMerkleRoot)
return res;
LOCK(cs_main);
if (!mapBlockIndex.count(merkleBlock.header.GetHash()) || !chainActive.Contains(mapBlockIndex[merkleBlock.header.GetHash()]))
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found in chain");
BOOST_FOREACH(const uint256& hash, vMatch)
res.push_back(hash.GetHex());
return res;
}
UniValue createrawtransaction(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() < 2 || params.size() > 3)
throw runtime_error(
"createrawtransaction [{\"txid\":\"id\",\"vout\":n},...] {\"address\":amount,\"data\":\"hex\",...} ( locktime )\n"
"\nCreate a transaction spending the given inputs and creating new outputs.\n"
"Outputs can be addresses or data.\n"
"Returns hex-encoded raw transaction.\n"
"Note that the transaction's inputs are not signed, and\n"
"it is not stored in the wallet or transmitted to the network.\n"
"\nArguments:\n"
"1. \"transactions\" (string, required) A json array of json objects\n"
" [\n"
" {\n"
" \"txid\":\"id\", (string, required) The transaction id\n"
" \"vout\":n (numeric, required) The output number\n"
" }\n"
" ,...\n"
" ]\n"
"2. \"outputs\" (string, required) a json object with outputs\n"
" {\n"
" \"address\": x.xxx (numeric or string, required) The key is the nero address, the numeric value (can be string) is the " + CURRENCY_UNIT + " amount\n"
" \"data\": \"hex\", (string, required) The key is \"data\", the value is hex encoded data\n"
" ...\n"
" }\n"
"3. locktime (numeric, optional, default=0) Raw locktime. Non-0 value also locktime-activates inputs\n"
"\nResult:\n"
"\"transaction\" (string) hex string of the transaction\n"
"\nExamples\n"
+ HelpExampleCli("createrawtransaction", "\"[{\\\"txid\\\":\\\"myid\\\",\\\"vout\\\":0}]\" \"{\\\"address\\\":0.01}\"")
+ HelpExampleCli("createrawtransaction", "\"[{\\\"txid\\\":\\\"myid\\\",\\\"vout\\\":0}]\" \"{\\\"data\\\":\\\"00010203\\\"}\"")
+ HelpExampleRpc("createrawtransaction", "\"[{\\\"txid\\\":\\\"myid\\\",\\\"vout\\\":0}]\", \"{\\\"address\\\":0.01}\"")
+ HelpExampleRpc("createrawtransaction", "\"[{\\\"txid\\\":\\\"myid\\\",\\\"vout\\\":0}]\", \"{\\\"data\\\":\\\"00010203\\\"}\"")
);
LOCK(cs_main);
RPCTypeCheck(params, boost::assign::list_of(UniValue::VARR)(UniValue::VOBJ)(UniValue::VNUM), true);
if (params[0].isNull() || params[1].isNull())
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, arguments 1 and 2 must be non-null");
UniValue inputs = params[0].get_array();
UniValue sendTo = params[1].get_obj();
CMutableTransaction rawTx;
if (params.size() > 2 && !params[2].isNull()) {
int64_t nLockTime = params[2].get_int64();
if (nLockTime < 0 || nLockTime > std::numeric_limits<uint32_t>::max())
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, locktime out of range");
rawTx.nLockTime = nLockTime;
}
for (unsigned int idx = 0; idx < inputs.size(); idx++) {
const UniValue& input = inputs[idx];
const UniValue& o = input.get_obj();
uint256 txid = ParseHashO(o, "txid");
const UniValue& vout_v = find_value(o, "vout");
if (!vout_v.isNum())
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, missing vout key");
int nOutput = vout_v.get_int();
if (nOutput < 0)
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, vout must be positive");
uint32_t nSequence = (rawTx.nLockTime ? std::numeric_limits<uint32_t>::max() - 1 : std::numeric_limits<uint32_t>::max());
CTxIn in(COutPoint(txid, nOutput), CScript(), nSequence);
rawTx.vin.push_back(in);
}
set<CBitcoinAddress> setAddress;
vector<string> addrList = sendTo.getKeys();
BOOST_FOREACH(const string& name_, addrList) {
if (name_ == "data") {
std::vector<unsigned char> data = ParseHexV(sendTo[name_].getValStr(),"Data");
CTxOut out(0, CScript() << OP_RETURN << data);
rawTx.vout.push_back(out);
} else {
CBitcoinAddress address(name_);
if (!address.IsValid())
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, string("Invalid Nero address: ")+name_);
if (setAddress.count(address))
throw JSONRPCError(RPC_INVALID_PARAMETER, string("Invalid parameter, duplicated address: ")+name_);
setAddress.insert(address);
CScript scriptPubKey = GetScriptForDestination(address.Get());
CAmount nAmount = AmountFromValue(sendTo[name_]);
CTxOut out(nAmount, scriptPubKey);
rawTx.vout.push_back(out);
}
}
return EncodeHexTx(rawTx);
}
UniValue decoderawtransaction(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() != 1)
throw runtime_error(
"decoderawtransaction \"hexstring\"\n"
"\nReturn a JSON object representing the serialized, hex-encoded transaction.\n"
"\nArguments:\n"
"1. \"hex\" (string, required) The transaction hex string\n"
"\nResult:\n"
"{\n"
" \"txid\" : \"id\", (string) The transaction id\n"
" \"size\" : n, (numeric) The transaction size\n"
" \"version\" : n, (numeric) The version\n"
" \"locktime\" : ttt, (numeric) The lock time\n"
" \"vin\" : [ (array of json objects)\n"
" {\n"
" \"txid\": \"id\", (string) The transaction id\n"
" \"vout\": n, (numeric) The output number\n"
" \"scriptSig\": { (json object) The script\n"
" \"asm\": \"asm\", (string) asm\n"
" \"hex\": \"hex\" (string) hex\n"
" },\n"
" \"sequence\": n (numeric) The script sequence number\n"
" }\n"
" ,...\n"
" ],\n"
" \"vout\" : [ (array of json objects)\n"
" {\n"
" \"value\" : x.xxx, (numeric) The value in " + CURRENCY_UNIT + "\n"
" \"n\" : n, (numeric) index\n"
" \"scriptPubKey\" : { (json object)\n"
" \"asm\" : \"asm\", (string) the asm\n"
" \"hex\" : \"hex\", (string) the hex\n"
" \"reqSigs\" : n, (numeric) The required sigs\n"
" \"type\" : \"pubkeyhash\", (string) The type, eg 'pubkeyhash'\n"
" \"addresses\" : [ (json array of string)\n"
" \"XwnLY9Tf7Zsef8gMGL2fhWA9ZmMjt4KPwg\" (string) Nero address\n"
" ,...\n"
" ]\n"
" }\n"
" }\n"
" ,...\n"
" ],\n"
"}\n"
"\nExamples:\n"
+ HelpExampleCli("decoderawtransaction", "\"hexstring\"")
+ HelpExampleRpc("decoderawtransaction", "\"hexstring\"")
);
LOCK(cs_main);
RPCTypeCheck(params, boost::assign::list_of(UniValue::VSTR));
CTransaction tx;
if (!DecodeHexTx(tx, params[0].get_str()))
throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "TX decode failed");
UniValue result(UniValue::VOBJ);
TxToJSON(tx, uint256(), result);
return result;
}
UniValue decodescript(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() != 1)
throw runtime_error(
"decodescript \"hex\"\n"
"\nDecode a hex-encoded script.\n"
"\nArguments:\n"
"1. \"hex\" (string) the hex encoded script\n"
"\nResult:\n"
"{\n"
" \"asm\":\"asm\", (string) Script public key\n"
" \"hex\":\"hex\", (string) hex encoded public key\n"
" \"type\":\"type\", (string) The output type\n"
" \"reqSigs\": n, (numeric) The required signatures\n"
" \"addresses\": [ (json array of string)\n"
" \"address\" (string) nero address\n"
" ,...\n"
" ],\n"
" \"p2sh\",\"address\" (string) address of P2SH script wrapping this redeem script (not returned if the script is already a P2SH).\n"
"}\n"
"\nExamples:\n"
+ HelpExampleCli("decodescript", "\"hexstring\"")
+ HelpExampleRpc("decodescript", "\"hexstring\"")
);
RPCTypeCheck(params, boost::assign::list_of(UniValue::VSTR));
UniValue r(UniValue::VOBJ);
CScript script;
if (params[0].get_str().size() > 0){
vector<unsigned char> scriptData(ParseHexV(params[0], "argument"));
script = CScript(scriptData.begin(), scriptData.end());
} else {
// Empty scripts are valid
}
ScriptPubKeyToJSON(script, r, false);
UniValue type;
type = find_value(r, "type");
if (type.isStr() && type.get_str() != "scripthash") {
// P2SH cannot be wrapped in a P2SH. If this script is already a P2SH,
// don't return the address for a P2SH of the P2SH.
r.push_back(Pair("p2sh", CBitcoinAddress(CScriptID(script)).ToString()));
}
return r;
}
/** Pushes a JSON object for script verification or signing errors to vErrorsRet. */
static void TxInErrorToJSON(const CTxIn& txin, UniValue& vErrorsRet, const std::string& strMessage)
{
UniValue entry(UniValue::VOBJ);
entry.push_back(Pair("txid", txin.prevout.hash.ToString()));
entry.push_back(Pair("vout", (uint64_t)txin.prevout.n));
entry.push_back(Pair("scriptSig", HexStr(txin.scriptSig.begin(), txin.scriptSig.end())));
entry.push_back(Pair("sequence", (uint64_t)txin.nSequence));
entry.push_back(Pair("error", strMessage));
vErrorsRet.push_back(entry);
}
UniValue signrawtransaction(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 4)
throw runtime_error(
"signrawtransaction \"hexstring\" ( [{\"txid\":\"id\",\"vout\":n,\"scriptPubKey\":\"hex\",\"redeemScript\":\"hex\"},...] [\"privatekey1\",...] sighashtype )\n"
"\nSign inputs for raw transaction (serialized, hex-encoded).\n"
"The second optional argument (may be null) is an array of previous transaction outputs that\n"
"this transaction depends on but may not yet be in the block chain.\n"
"The third optional argument (may be null) is an array of base58-encoded private\n"
"keys that, if given, will be the only keys used to sign the transaction.\n"
#ifdef ENABLE_WALLET
+ HelpRequiringPassphrase() + "\n"
#endif
"\nArguments:\n"
"1. \"hexstring\" (string, required) The transaction hex string\n"
"2. \"prevtxs\" (string, optional) An json array of previous dependent transaction outputs\n"
" [ (json array of json objects, or 'null' if none provided)\n"
" {\n"
" \"txid\":\"id\", (string, required) The transaction id\n"
" \"vout\":n, (numeric, required) The output number\n"
" \"scriptPubKey\": \"hex\", (string, required) script key\n"
" \"redeemScript\": \"hex\" (string, required for P2SH) redeem script\n"
" }\n"
" ,...\n"
" ]\n"
"3. \"privatekeys\" (string, optional) A json array of base58-encoded private keys for signing\n"
" [ (json array of strings, or 'null' if none provided)\n"
" \"privatekey\" (string) private key in base58-encoding\n"
" ,...\n"
" ]\n"
"4. \"sighashtype\" (string, optional, default=ALL) The signature hash type. Must be one of\n"
" \"ALL\"\n"
" \"NONE\"\n"
" \"SINGLE\"\n"
" \"ALL|ANYONECANPAY\"\n"
" \"NONE|ANYONECANPAY\"\n"
" \"SINGLE|ANYONECANPAY\"\n"
"\nResult:\n"
"{\n"
" \"hex\" : \"value\", (string) The hex-encoded raw transaction with signature(s)\n"
" \"complete\" : true|false, (boolean) If the transaction has a complete set of signatures\n"
" \"errors\" : [ (json array of objects) Script verification errors (if there are any)\n"
" {\n"
" \"txid\" : \"hash\", (string) The hash of the referenced, previous transaction\n"
" \"vout\" : n, (numeric) The index of the output to spent and used as input\n"
" \"scriptSig\" : \"hex\", (string) The hex-encoded signature script\n"
" \"sequence\" : n, (numeric) Script sequence number\n"
" \"error\" : \"text\" (string) Verification or signing error related to the input\n"
" }\n"
" ,...\n"
" ]\n"
"}\n"
"\nExamples:\n"
+ HelpExampleCli("signrawtransaction", "\"myhex\"")
+ HelpExampleRpc("signrawtransaction", "\"myhex\"")
);
#ifdef ENABLE_WALLET
LOCK2(cs_main, pwalletMain ? &pwalletMain->cs_wallet : NULL);
#else
LOCK(cs_main);
#endif
RPCTypeCheck(params, boost::assign::list_of(UniValue::VSTR)(UniValue::VARR)(UniValue::VARR)(UniValue::VSTR), true);
vector<unsigned char> txData(ParseHexV(params[0], "argument 1"));
CDataStream ssData(txData, SER_NETWORK, PROTOCOL_VERSION);
vector<CMutableTransaction> txVariants;
while (!ssData.empty()) {
try {
CMutableTransaction tx;
ssData >> tx;
txVariants.push_back(tx);
}
catch (const std::exception&) {
throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "TX decode failed");
}
}
if (txVariants.empty())
throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "Missing transaction");
// mergedTx will end up with all the signatures; it
// starts as a clone of the rawtx:
CMutableTransaction mergedTx(txVariants[0]);
// Fetch previous transactions (inputs):
CCoinsView viewDummy;
CCoinsViewCache view(&viewDummy);
{
LOCK(mempool.cs);
CCoinsViewCache &viewChain = *pcoinsTip;
CCoinsViewMemPool viewMempool(&viewChain, mempool);
view.SetBackend(viewMempool); // temporarily switch cache backend to db+mempool view
BOOST_FOREACH(const CTxIn& txin, mergedTx.vin) {
const uint256& prevHash = txin.prevout.hash;
CCoins coins;
view.AccessCoins(prevHash); // this is certainly allowed to fail
}
view.SetBackend(viewDummy); // switch back to avoid locking mempool for too long
}
bool fGivenKeys = false;
CBasicKeyStore tempKeystore;
if (params.size() > 2 && !params[2].isNull()) {
fGivenKeys = true;
UniValue keys = params[2].get_array();
for (unsigned int idx = 0; idx < keys.size(); idx++) {
UniValue k = keys[idx];
CBitcoinSecret vchSecret;
bool fGood = vchSecret.SetString(k.get_str());
if (!fGood)
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid private key");
CKey key = vchSecret.GetKey();
if (!key.IsValid())
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Private key outside allowed range");
tempKeystore.AddKey(key);
}
}
#ifdef ENABLE_WALLET
else if (pwalletMain)
EnsureWalletIsUnlocked();
#endif
// Add previous txouts given in the RPC call:
if (params.size() > 1 && !params[1].isNull()) {
UniValue prevTxs = params[1].get_array();
for (unsigned int idx = 0; idx < prevTxs.size(); idx++) {
const UniValue& p = prevTxs[idx];
if (!p.isObject())
throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "expected object with {\"txid'\",\"vout\",\"scriptPubKey\"}");
UniValue prevOut = p.get_obj();
RPCTypeCheckObj(prevOut, boost::assign::map_list_of("txid", UniValue::VSTR)("vout", UniValue::VNUM)("scriptPubKey", UniValue::VSTR));
uint256 txid = ParseHashO(prevOut, "txid");
int nOut = find_value(prevOut, "vout").get_int();
if (nOut < 0)
throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "vout must be positive");
vector<unsigned char> pkData(ParseHexO(prevOut, "scriptPubKey"));
CScript scriptPubKey(pkData.begin(), pkData.end());
{
CCoinsModifier coins = view.ModifyCoins(txid);
if (coins->IsAvailable(nOut) && coins->vout[nOut].scriptPubKey != scriptPubKey) {
string err("Previous output scriptPubKey mismatch:\n");
err = err + ScriptToAsmStr(coins->vout[nOut].scriptPubKey) + "\nvs:\n"+
ScriptToAsmStr(scriptPubKey);
throw JSONRPCError(RPC_DESERIALIZATION_ERROR, err);
}
if ((unsigned int)nOut >= coins->vout.size())
coins->vout.resize(nOut+1);
coins->vout[nOut].scriptPubKey = scriptPubKey;
coins->vout[nOut].nValue = 0; // we don't know the actual output value
}
// if redeemScript given and not using the local wallet (private keys
// given), add redeemScript to the tempKeystore so it can be signed:
if (fGivenKeys && scriptPubKey.IsPayToScriptHash()) {
RPCTypeCheckObj(prevOut, boost::assign::map_list_of("txid", UniValue::VSTR)("vout", UniValue::VNUM)("scriptPubKey", UniValue::VSTR)("redeemScript",UniValue::VSTR));
UniValue v = find_value(prevOut, "redeemScript");
if (!v.isNull()) {
vector<unsigned char> rsData(ParseHexV(v, "redeemScript"));
CScript redeemScript(rsData.begin(), rsData.end());
tempKeystore.AddCScript(redeemScript);
}
}
}
}
#ifdef ENABLE_WALLET
const CKeyStore& keystore = ((fGivenKeys || !pwalletMain) ? tempKeystore : *pwalletMain);
#else
const CKeyStore& keystore = tempKeystore;
#endif
int nHashType = SIGHASH_ALL;
if (params.size() > 3 && !params[3].isNull()) {
static map<string, int> mapSigHashValues =
boost::assign::map_list_of
(string("ALL"), int(SIGHASH_ALL))
(string("ALL|ANYONECANPAY"), int(SIGHASH_ALL|SIGHASH_ANYONECANPAY))
(string("NONE"), int(SIGHASH_NONE))
(string("NONE|ANYONECANPAY"), int(SIGHASH_NONE|SIGHASH_ANYONECANPAY))
(string("SINGLE"), int(SIGHASH_SINGLE))
(string("SINGLE|ANYONECANPAY"), int(SIGHASH_SINGLE|SIGHASH_ANYONECANPAY))
;
string strHashType = params[3].get_str();
if (mapSigHashValues.count(strHashType))
nHashType = mapSigHashValues[strHashType];
else
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid sighash param");
}
bool fHashSingle = ((nHashType & ~SIGHASH_ANYONECANPAY) == SIGHASH_SINGLE);
// Script verification errors
UniValue vErrors(UniValue::VARR);
// Sign what we can:
for (unsigned int i = 0; i < mergedTx.vin.size(); i++) {
CTxIn& txin = mergedTx.vin[i];
const CCoins* coins = view.AccessCoins(txin.prevout.hash);
if (coins == NULL || !coins->IsAvailable(txin.prevout.n)) {
TxInErrorToJSON(txin, vErrors, "Input not found or already spent");
continue;
}
const CScript& prevPubKey = coins->vout[txin.prevout.n].scriptPubKey;
txin.scriptSig.clear();
// Only sign SIGHASH_SINGLE if there's a corresponding output:
if (!fHashSingle || (i < mergedTx.vout.size()))
SignSignature(keystore, prevPubKey, mergedTx, i, nHashType);
// ... and merge in other signatures:
BOOST_FOREACH(const CMutableTransaction& txv, txVariants) {
txin.scriptSig = CombineSignatures(prevPubKey, mergedTx, i, txin.scriptSig, txv.vin[i].scriptSig);
}
ScriptError serror = SCRIPT_ERR_OK;
if (!VerifyScript(txin.scriptSig, prevPubKey, STANDARD_SCRIPT_VERIFY_FLAGS, MutableTransactionSignatureChecker(&mergedTx, i), &serror)) {
TxInErrorToJSON(txin, vErrors, ScriptErrorString(serror));
}
}
bool fComplete = vErrors.empty();
UniValue result(UniValue::VOBJ);
result.push_back(Pair("hex", EncodeHexTx(mergedTx)));
result.push_back(Pair("complete", fComplete));
if (!vErrors.empty()) {
result.push_back(Pair("errors", vErrors));
}
return result;
}
UniValue sendrawtransaction(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 3)
throw runtime_error(
"sendrawtransaction \"hexstring\" ( allowhighfees instantsend )\n"
"\nSubmits raw transaction (serialized, hex-encoded) to local node and network.\n"
"\nAlso see createrawtransaction and signrawtransaction calls.\n"
"\nArguments:\n"
"1. \"hexstring\" (string, required) The hex string of the raw transaction)\n"
"2. allowhighfees (boolean, optional, default=false) Allow high fees\n"
"3. instantsend (boolean, optional, default=false) Use InstantSend to send this transaction\n"
"\nResult:\n"
"\"hex\" (string) The transaction hash in hex\n"
"\nExamples:\n"
"\nCreate a transaction\n"
+ HelpExampleCli("createrawtransaction", "\"[{\\\"txid\\\" : \\\"mytxid\\\",\\\"vout\\\":0}]\" \"{\\\"myaddress\\\":0.01}\"") +
"Sign the transaction, and get back the hex\n"
+ HelpExampleCli("signrawtransaction", "\"myhex\"") +
"\nSend the transaction (signed hex)\n"
+ HelpExampleCli("sendrawtransaction", "\"signedhex\"") +
"\nAs a json rpc call\n"
+ HelpExampleRpc("sendrawtransaction", "\"signedhex\"")
);
LOCK(cs_main);
RPCTypeCheck(params, boost::assign::list_of(UniValue::VSTR)(UniValue::VBOOL)(UniValue::VBOOL));
// parse hex string from parameter
CTransaction tx;
if (!DecodeHexTx(tx, params[0].get_str()))
throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "TX decode failed");
uint256 hashTx = tx.GetHash();
bool fOverrideFees = false;
if (params.size() > 1)
fOverrideFees = params[1].get_bool();
bool fInstantSend = false;
if (params.size() > 2)
fInstantSend = params[2].get_bool();
CCoinsViewCache &view = *pcoinsTip;
const CCoins* existingCoins = view.AccessCoins(hashTx);
bool fHaveMempool = mempool.exists(hashTx);
bool fHaveChain = existingCoins && existingCoins->nHeight < 1000000000;
if (!fHaveMempool && !fHaveChain) {
// push to local node and sync with wallets
if (fInstantSend && !instantsend.ProcessTxLockRequest(tx, *g_connman)) {
throw JSONRPCError(RPC_TRANSACTION_ERROR, "Not a valid InstantSend transaction, see debug.log for more info");
}
CValidationState state;
bool fMissingInputs;
if (!AcceptToMemoryPool(mempool, state, tx, false, &fMissingInputs, false, !fOverrideFees)) {
if (state.IsInvalid()) {
throw JSONRPCError(RPC_TRANSACTION_REJECTED, strprintf("%i: %s", state.GetRejectCode(), state.GetRejectReason()));
} else {
if (fMissingInputs) {
throw JSONRPCError(RPC_TRANSACTION_ERROR, "Missing inputs");
}
throw JSONRPCError(RPC_TRANSACTION_ERROR, state.GetRejectReason());
}
}
} else if (fHaveChain) {
throw JSONRPCError(RPC_TRANSACTION_ALREADY_IN_CHAIN, "transaction already in block chain");
}
if(!g_connman)
throw JSONRPCError(RPC_CLIENT_P2P_DISABLED, "Error: Peer-to-peer functionality missing or disabled");
g_connman->RelayTransaction(tx);
return hashTx.GetHex();
}
|
[
"root@DS792121.clientshostname.com"
] |
root@DS792121.clientshostname.com
|
2e8005a997839cfa728fc00f6bc089f56ad2384e
|
16ce45e5ad8aead05730b118cef3be4523636ca3
|
/src/49. Group Anagrams/main.cpp
|
3b97b1fb125ca31d021ac1b83161dfd4c88c70b4
|
[
"MIT"
] |
permissive
|
sheepduke/leetcode
|
9a23d3392310e0ba91cae8e9cb557d85cddc6ccc
|
7808b3370e4c3e19b2b0bc2bcee62f659906c3eb
|
refs/heads/master
| 2020-05-02T21:56:22.689703
| 2019-10-30T03:35:02
| 2019-10-30T03:35:02
| 178,235,715
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,065
|
cpp
|
/*
Given an array of strings, group anagrams together.
Example:
Input: ["eat", "tea", "tan", "ate", "nat", "bat"],
Output:
[
["ate","eat","tea"],
["nat","tan"],
["bat"]
]
Note:
All inputs will be in lowercase.
The order of your output does not matter.
*/
#include "../util/common.hpp"
class Solution {
public:
vector<vector<string>> groupAnagrams(vector<string>& strs) {
auto hash_to_vector = map<string, vector<string>>();
for (auto str: strs) {
auto hash = str;
sort(begin(hash), end(hash));
if (hash_to_vector.find(hash) == end(hash_to_vector)) {
hash_to_vector[hash] = vector<string>{str};
}
else {
hash_to_vector[hash].push_back(str);
}
}
auto result = vector<vector<string>>();
for (auto pair: hash_to_vector) {
result.push_back(pair.second);
}
return result;
}
};
int main() {
Solution solution;
auto input = vector<string>{
"eat", "tea", "tan", "ate", "nat", "bat"
};
cout << solution.groupAnagrams(input) << endl;
return 0;
}
|
[
"sheepduke@gmail.com"
] |
sheepduke@gmail.com
|
e927b31f3f5f82fa4202f157ee94bef9a06d025c
|
46bc6200b2e8e060f5e319ac8e2d6701fdf38793
|
/Koramu/ScriptManager.h
|
6432716915fe6f1beffda3a354e84cb47b9d0ccd
|
[] |
no_license
|
ariogato/Koramu
|
31937a01e53bab8f6cae5c4b14e32d5c135f7326
|
55502dd61cdb434c7364f1a03105ccaa62247123
|
refs/heads/master
| 2021-11-10T20:23:13.789728
| 2021-11-08T15:37:31
| 2021-11-08T15:37:31
| 74,519,918
| 4
| 0
| null | null | null | null |
ISO-8859-1
|
C++
| false
| false
| 1,844
|
h
|
#pragma once
#include <string>
#include <map>
#include "Script.h"
namespace LuaRegistrations
{
class BaseLuaRegistration;
}
/* Dies ist eine Singleton Klasse, die nach dem Vorbild des TextureManagers alle Lua Skripte
* mit den dazugehörigen Methoden, Tabellen, etc. organisiert.
* über den ScriptManager können andere Klassen auf Lua Methoden zugreifen
*/
class ScriptManager
{
private:
ScriptManager(); // Konstruktor
~ScriptManager(); // Destruktor
bool m_isInit; // Zeigt an, ob init() bereits aufgerufen wurde
lua_State* m_pLuaState; // In diesem Member ist praktisch alles gespeichert, das mit der Kommunikation mit Lua zu tun hat
std::map<std::string, Script*>* m_pScriptMap; // Dictionary, in dem jeder ID ein Script zugeordnet wird
std::vector<LuaRegistrations::BaseLuaRegistration*> m_registrations; // Alle Funktionen, Variablen, etc., die an Lua weiterzugeben sind
// Wichtig für Singleton
static ScriptManager* s_pInstance;
public:
bool init(); // Initialisiert all das, was für Lua gebraucht wird (i.e. luaL_newstate(), etc.)
Script& getScriptById(std::string id) const; // Gibt das der übergebenen id zugehörigen Script zurück
void removeScriptFromMap(std::string id); // Entfernt ein Skript (die Lua Referenz & das Objekt)
void callFunction(const char* table, const char* func); // Ruft eine Funktion 'func' aus der globalen Tabelle 'table' auf
void addRegistration(LuaRegistrations::BaseLuaRegistration* reg); // Fügt dem Vektor aus Registrierungen ein weiteres Element hinzu
// getter-Funktionen
lua_State* getLuaState() { return m_pLuaState; }
// Wichtig für Singleton
static ScriptManager* Instance();
static void destroy();
};
typedef ScriptManager TheScriptManager;
|
[
"ario2000.ad@gmail.com"
] |
ario2000.ad@gmail.com
|
3d2c7332c6e711bb9c4d909bb660f6aab7622f7f
|
6e20207f8aff0f0ad94f05bd025810c6b10a1d5f
|
/SDK/GlimpseShopkeeperNPC_classes.h
|
ee02910d9ba7389cbd1d0680fba4b6eb20c054b2
|
[] |
no_license
|
zH4x-SDK/zWeHappyFew-SDK
|
2a4e246d8ee4b58e45feaa4335f1feb8ea618a4a
|
5906adc3edfe1b5de86b7ef0a0eff38073e12214
|
refs/heads/main
| 2023-08-17T06:05:18.561339
| 2021-08-27T13:36:09
| 2021-08-27T13:36:09
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 840
|
h
|
#pragma once
// Name: WeHappyFew, Version: 1.8.8
#ifdef _MSC_VER
#pragma pack(push, 0x8)
#endif
namespace SDK
{
//---------------------------------------------------------------------------
// Classes
//---------------------------------------------------------------------------
// BlueprintGeneratedClass GlimpseShopkeeperNPC.GlimpseShopkeeperNPC_C
// 0x0048 (0x1FD8 - 0x1F90)
class AGlimpseShopkeeperNPC_C : public AGlimpseAICharacter
{
public:
unsigned char UnknownData00[0x48]; // 0x1F90(0x0048) MISSED OFFSET
static UClass* StaticClass()
{
static auto ptr = UObject::FindClass("BlueprintGeneratedClass GlimpseShopkeeperNPC.GlimpseShopkeeperNPC_C");
return ptr;
}
void UserConstructionScript();
};
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
|
[
"zp2kshield@gmail.com"
] |
zp2kshield@gmail.com
|
5260027aa62ddbdf628d6155fbd42137e23b243c
|
401cc62accb8f5630fe6531cf8faf911e4ff6dae
|
/Utilities.cpp
|
2f70af973840bc2c9cc5a02d19c3bba149eb2692
|
[
"MIT"
] |
permissive
|
soulhez/VkColors
|
c2f7926548b2b99f22a6d040690a31bdff30ed12
|
98acef13fb990311e7185af1195e58984e86238f
|
refs/heads/master
| 2020-12-11T04:55:28.756081
| 2019-05-22T21:35:57
| 2019-05-22T21:35:57
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 936
|
cpp
|
#include "Utilities.h"
#include <fstream>
#include <stdexcept>
std::vector<char> loadFile(const std::string& path) {
std::ifstream file = std::ifstream(path, std::ios::binary | std::ios::ate);
if (!file) throw std::runtime_error("Could not open file");
std::vector<char> result;
result.resize(file.tellg());
file.seekg(0, std::ios::beg);
file.read(result.data(), result.size());
return result;
}
vk::ShaderModule loadShader(vk::Device& device, const std::string& path) {
std::vector<char> data = loadFile(path);
vk::ShaderModuleCreateInfo info = {};
info.code = std::move(data);
return vk::ShaderModule(device, info);
}
size_t align(size_t ptr, size_t align) {
size_t unalign = ptr % align;
if (unalign != 0) {
return ptr + (align - unalign);
} else {
return ptr;
}
}
int32_t length2(glm::ivec3 v) {
return v.x * v.x + v.y * v.y + v.z * v.z;
}
|
[
"vazgriz@gmail.com"
] |
vazgriz@gmail.com
|
38ee073dc35957ed694a581005ef2bdfc2a8411e
|
c5ad94c5f44ea26bfcd67f0b88862b895fe965d2
|
/MIPSCompiler/Compiler.cpp
|
31acbf5d2752d2b8f57fa1fb6ef78fd77e450e8b
|
[] |
no_license
|
Gongzq5/SYSU-Computer-Organization-And-Design
|
2540ecfe7f24983d04b643b0ae676c2f9b04da37
|
04f4eb160d0469382cb941b79af82ee466c49ab0
|
refs/heads/master
| 2020-03-19T12:18:09.227802
| 2018-07-09T01:20:50
| 2018-07-09T01:20:50
| 136,509,221
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 5,988
|
cpp
|
/*
* @Time 2018/06/05 16:33
* @Author Zequn Gong
*
* Compile MIPS code to binary code
*/
#include <stdio.h>
#include <memory.h>
#include <string.h>
#include <stdlib.h>
#include <iostream>
#include <map>
using namespace std;
std::string instruction;
/*
// // If you want single one, just change to use this map.
// std::map<string, string> op2code = {
// {"add", "000000"},
// {"sub", "000010"},
// {"addi", "000001"},
// {"or", "010010"},
// {"and", "010001"},
// {"ori", "010000"},
// {"sll", "011000"},
// {"slt", "100110"},
// {"slti", "011011"},
// {"beq", "110000"},
// {"bne", "110001"},
// {"sltiu", "100111"},
// {"sw", "100110"},
// {"lw", "100111"},
// {"bltz", "110110"},
// {"j", "111000"},
// {"jr", "111001"},
// {"jal", "111010"},
// {"halt", "111111"}
// };
*/
std::map<string, string> op2code = {
{"add", "000000"},
{"sub", "000001"},
{"addi", "000010"},
{"or", "010000"},
{"and", "010001"},
{"ori", "010010"},
{"sll", "011000"},
{"slt", "100110"},
{"slti", "011011"},
{"bne", "110001"},
{"sltiu", "100111"},
{"sw", "110000"},
{"lw", "110001"},
{"beq", "110100"},
{"bltz", "110110"},
{"j", "111000"},
{"jr", "111001"},
{"jal", "111010"},
{"halt", "111111"}
};
/*
* Type introducation
* 1: op rd rs rt
* 2: op rt rs immediate
* 3: op rd rt sa
* 4: op rt immediate(rs)
* 5: op rs rt immediate
* 6: op rs immediate
* 7: op addr
* 8: op rs
* 9: op null
*/
std::map<string, int> op2type = {
{"add", 1},
{"sub", 1},
{"addi", 2},
{"or", 1},
{"and", 1},
{"ori", 2},
{"sll", 3},
{"slt", 1},
{"slti", 2},
{"sltiu", 2},
{"sw", 4},
{"lw", 4},
{"beq", 5},
{"bne", 5},
{"bltz", 6},
{"j", 7},
{"jr", 8},
{"jal", 7},
{"halt", 9}
};
void trim_last_16_from_32 (char* dest, char* source) {
int begin = 16;
for (int i=begin; i<begin+16; i++) {
dest[i-begin] = source[i];
}
dest[16] = 0;
return;
}
std::string convert() {
std::string opCommand;
std::cin >> opCommand;
instruction = op2code[opCommand];
if (opCommand == "") {
return "wrong";
}
std::cerr << "[" << opCommand << "] over" << endl;
int rs, rt, rd, sa, immediate;
long long int addr;
char tmps[6], tmpt[6], tmpd[6], tmpsa[6], tmpaddr[27], tmpimm_32[33];
char rss[6], rts[6], rds[6], sas[6], immediates[17], addrs[27], immediates_32[33];
int type = op2type[opCommand];
switch (type) {
// 1: op rd rs rt
case 1:
scanf(" $%d , $%d , $%d", &rd, &rs, &rt);
ltoa(rd, tmpd, 2); ltoa(rt, tmpt, 2); ltoa(rs, tmps, 2);
sprintf(rss, "%05s", tmps);
sprintf(rds, "%05s", tmpd);
sprintf(rts, "%05s", tmpt);
instruction = instruction + rss + rts + rds + "00000" + "000000";
break;
// 2: op rt rs immediate
case 2:
scanf(" $%d , $%d , %d", &rt, &rs, &immediate);
ltoa(rt, tmpt, 2); ltoa(rs, tmps, 2); ltoa(immediate, tmpimm_32, 2);
sprintf(rts, "%05s", tmpt);
sprintf(rss, "%05s", tmps);
sprintf(immediates_32, "%032s", tmpimm_32);
trim_last_16_from_32(immediates, immediates_32);
instruction = instruction + rss + rts + immediates;
break;
// 3: op rd rt sa
case 3:
scanf(" $%d , $%d , %d", &rd, &rt, &sa);
ltoa(rd, tmpd, 2); ltoa(rt, tmpt, 2); ltoa(sa, tmpsa, 2);
sprintf(rds, "%05s", tmpd);
sprintf(rts, "%05s", tmpt);
sprintf(sas, "%05s", tmpsa);
instruction = instruction + "00000" + rts + rds + sas + "000000";
break;
// 4: op rt immediate(rs)
case 4:
scanf(" $%d , %d ( $%d )", &rt, &immediate, &rs);
ltoa(rt, tmpt, 2); ltoa(immediate, tmpimm_32, 2); ltoa(rs, tmps, 2);
sprintf(rts, "%05s", tmpt);
sprintf(immediates_32, "%032s", tmpimm_32);
trim_last_16_from_32(immediates, immediates_32);
sprintf(rss, "%05s", tmps);
instruction = instruction + rss + rts + immediates;
break;
// 5: op rs rt immediate
case 5:
scanf(" $%d , $%d , %d", &rs, &rt, &immediate);
ltoa(rs, tmps, 2); ltoa(rt, tmpt, 2); ltoa(immediate, tmpimm_32, 2);
sprintf(rss, "%05s", tmps);
sprintf(rts, "%05s", tmpt);
sprintf(immediates_32, "%032s", tmpimm_32);
trim_last_16_from_32(immediates, immediates_32);
instruction = instruction + rss + rts + immediates;
break;
// 6: op rs immediate
case 6:
scanf(" $%d , %d", &rs, &immediate);
ltoa(rs, tmps, 2); ltoa(immediate, tmpimm_32, 2);
sprintf(rss, "%05s", tmps);
sprintf(immediates_32, "%016s", tmpimm_32);
trim_last_16_from_32(immediates, immediates_32);
instruction = instruction + rss + "00000" + immediates;
break;
// 7: op addr
case 7:
scanf("%x", &addr);
addr /= 4;
ltoa(addr, tmpaddr, 2);
sprintf(addrs, "%026s", tmpaddr);
instruction = instruction + addrs;
break;
// 8: op rs
case 8:
scanf(" $%d", &rs);
ltoa(rs, tmps, 2);
sprintf(rss, "%05s", tmps);
instruction = instruction + rss + "00000" + "00000" + "00000" + "000000";
break;
// 9: op null
case 9:
instruction = instruction + "00000000000000000000000000";
break;
default: break;
};
return instruction;
}
int main(void) {
freopen("out.txt", "w", stdout);
while (true) {
if ("wrong" == convert()) {
return 0;
}
cout << instruction << endl;
}
return 0;
}
|
[
"765194873@qq.com"
] |
765194873@qq.com
|
d590a825873fd24da451812f74e35fee50807b98
|
f2609d00ba6e66f4bbd909c796d68361867a497e
|
/Player.cpp
|
ec03be1c8ff4bd692647cc67b372aa58759a0195
|
[] |
no_license
|
filosmusic/BaseCode
|
e655c68520c8b66b436822ab79aefecfe88d5681
|
bbaa22823a1eaae5cfcce80a8afb7067986209f5
|
refs/heads/master
| 2021-01-14T08:50:09.930051
| 2015-11-28T20:54:10
| 2015-11-28T20:54:10
| 43,768,213
| 0
| 0
| null | 2015-10-06T17:56:43
| 2015-10-06T17:56:42
| null |
UTF-8
|
C++
| false
| false
| 3,538
|
cpp
|
#include "Player.h"
#include "TextureManager.h"
#include "game.h"
#include "inputManager.h"
#include <iostream>
using namespace std;
#define UP SDL_SCANCODE_W
#define DOWN SDL_SCANCODE_S
#define RIGHT SDL_SCANCODE_D
#define LEFT SDL_SCANCODE_A
Player::Player() {
this->spriteCol = 0;
this->spriteRow = 0;
this->xDirection = 0;
this->yDirection = 0;
this->speed = 0;
this->maxSpeed = 5;
this->accel = 0.01;
this->friction = 0.005;
this->startMove = 0;
}
Player::~Player() {
}
GameObject * Player::create() {
return new Player();
}
void Player::load(LoaderParams* params) {
this->setId(params->getId());
this->position.setX((float)params->getX());
this->position.setY((float)params->getY());
this->width = params->getWidth();
this->height = params->getHeight();
}
void Player::draw() {
TextureManager::getInstance()->drawFrame(
this->textureID,
this->position.getX(),
this->position.getY(),
this->width,
this->height,
this->spriteRow,
this->spriteCol,
Game::getInstance()->getRenderer()
);
}
void Player::update() {
//SET SPEED
if (xDirection != 0 || yDirection != 0) {
//ACCELERATION
if (startMove == 0) startMove = SDL_GetTicks();
speed += (accel - friction) * (SDL_GetTicks() - startMove);
startMove = SDL_GetTicks();
if (speed > maxSpeed) speed = maxSpeed;
} else {
//DECELERATION
if (startMove == 0) startMove = SDL_GetTicks();
speed -= friction * (SDL_GetTicks() - startMove);
startMove = SDL_GetTicks();
if (speed < 0.0f) speed = 0.0f;
else if (speed == 0.0f) startMove = 0.0f;
}
if (speed != 0) {
//MOVEMENT X
spriteCol = (int)((SDL_GetTicks() / 120) % nCols);
if (xDirection > 0) {
position += Vector2(speed, 0);
spriteRow = 2;
}
else if (xDirection < 0) {
position -= Vector2(speed, 0);
spriteRow = 1;
}
//MOVEMENT Y
if (yDirection > 0) {
position += Vector2(0, speed);
spriteRow = 0;
}
else if (yDirection < 0) {
position -= Vector2(0, speed);
spriteRow = 3;
}
//FIX POSITION
if (position.getX() + (width / 2) >(SDL_GetWindowSurface(Game::getInstance()->getWindow())->w))
position.setX(SDL_GetWindowSurface(Game::getInstance()->getWindow())->w - (width / 2));
if (position.getX() < (width / 2))
position.setX((width / 2));
if (position.getY() + (height / 2) > (SDL_GetWindowSurface(Game::getInstance()->getWindow())->h))
position.setY(SDL_GetWindowSurface(Game::getInstance()->getWindow())->h - (height / 2));
if (position.getY() < (height / 2))
position.setY((height / 2));
} else spriteCol = 0;
}
void Player::handleEvents(SDL_Event e) {
InputManager* input = InputManager::getInstance();
//X AXIS
if (input->isKeyPressed(LEFT) || input->isKeyPressed(RIGHT)) {
if (input->isKeyPressed(LEFT)) xDirection = -1;
if (input->isKeyPressed(RIGHT)) xDirection = 1;
} else xDirection = 0;
//Y AXIS
if (input->isKeyPressed(DOWN) || input->isKeyPressed(UP)) {
if (input->isKeyPressed(DOWN)) yDirection = 1;
if (input->isKeyPressed(UP)) yDirection = -1;
} else yDirection = 0;
}
void Player::clean() {
}
void Player::setTexture(std::string textureID, std::string texturePath, int nCols, int nRows) {
this->textureID = textureID;
this->texturePath = texturePath;
this->nCols = nCols;
this->nRows = nRows;
}
void Player::setTexture(std::string textureID, int nCols, int nRows) {
this->textureID = textureID;
this->nCols = nCols;
this->nRows = nRows;
}
std::string Player::getTextureId() {
return textureID;
}
std::string Player::getTexturePath() {
return texturePath;
}
|
[
"filosmusic@hotmail.com"
] |
filosmusic@hotmail.com
|
7488e4cb87fefd3c5b39f32a47a38b45f2fd63b3
|
5849b70aac97193a486155c59e58b34a3fdab20f
|
/Terrain.h
|
2517bed0464e789d952eed8fb4cd174e80a9cda6
|
[] |
no_license
|
widavies/5607-Final
|
5feb27da89a5ce207081a14113e49bf417b7e25e
|
1d939cac0eb4a35c25e59e46b0256b410e3bfaaa
|
refs/heads/master
| 2023-04-19T14:39:03.154505
| 2021-05-08T05:51:28
| 2021-05-08T05:51:28
| 361,471,638
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 647
|
h
|
#pragma once
#include "RawModel.h"
#include "ModelTexture.h"
#include "ModelLoader.h"
#define SIZE 800
#define VERTEX_COUNT 128
class Terrain {
public:
Terrain(int gridX, int gridZ, ModelLoader& loader, ModelTexture* texture) : _texture(texture) {
_x = gridX * SIZE;
_z = gridZ * SIZE;
_model = generateTerrain(loader);
}
RawModel& getModel() {
return _model;
}
ModelTexture* getTexture() {
return _texture;
}
float getX() {
return _x;
}
float getZ() {
return _z;
}
private:
float _x, _z;
RawModel _model;
ModelTexture* _texture;
RawModel generateTerrain(ModelLoader& loader);
};
|
[
"wdavies973@gmail.com"
] |
wdavies973@gmail.com
|
01610748b5c716a5ed3ca870dbe434abc0c2f4f0
|
6b2a8dd202fdce77c971c412717e305e1caaac51
|
/solutions_2755486_0/C++/Takuma/C.cpp
|
71fdb2b5eb59626e1d78df7c916092d99e2d3490
|
[] |
no_license
|
alexandraback/datacollection
|
0bc67a9ace00abbc843f4912562f3a064992e0e9
|
076a7bc7693f3abf07bfdbdac838cb4ef65ccfcf
|
refs/heads/master
| 2021-01-24T18:27:24.417992
| 2017-05-23T09:23:38
| 2017-05-23T09:23:38
| 84,313,442
| 2
| 4
| null | null | null | null |
GB18030
|
C++
| false
| false
| 1,634
|
cpp
|
// C.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cmath>
#define maxn ( 105 )
#define BASE ( 500 )
using namespace std;
struct Tnode{
int day, west, east, s;
}attack[ maxn ];
int wall[ 2005 ], M, N, day, Ni, Wi, Ei, Si, delta_d, delta_p, delta_s, now, testcase;
bool cmp( Tnode a, Tnode b ){
return a.day<b.day;
}
int _tmain( int argc, _TCHAR* argv[ ] ){
freopen( "C-small-attempt0.in", "r", stdin );
freopen( "out.txt", "w", stdout );
scanf( "%d", &testcase );
for ( now=1;testcase--;now++ ){
scanf( "%d", &N );
printf( "Case #%d: ", now );
M=0;
for ( int i=0;i<N;i++ ){
scanf( "%d%d%d%d%d%d%d%d", &day, &Ni, &Wi, &Ei, &Si, &delta_d, &delta_p, &delta_s );
for ( int j=0;j<Ni;j++ ){
attack[ M ].day=day;
attack[ M ].west=Wi;
attack[ M ].east=Ei;
attack[ M ].s=Si;
day+=delta_d;
Wi+=delta_p;
Ei+=delta_p;
Si+=delta_s;
M++;
}
}
sort( attack, attack+M, cmp );
memset( wall, 0, sizeof( wall ) );
int res=0;
for ( int i=0, prei=-1;i<M;i++ ){
bool ok=false;
for ( int j=attack[ i ].west;j<attack[ i ].east && !ok;j++ )
if ( wall[ j+BASE ]<attack[ i ].s ) ok=true;
if ( ok )
res++;
if ( i==M-1 || attack[ i ].day!=attack[ i+1 ].day ){
for ( int j=prei+1;j<=i;j++ ){
for ( int k=attack[ j ].west;k<attack[ j ].east;k++ )
if ( wall[ k+BASE ]<attack[ j ].s )
wall[ k+BASE ]=attack[ j ].s;
}
prei=i;
}
}
printf( "%d\n", res );
}
return 0;
}
|
[
"eewestman@gmail.com"
] |
eewestman@gmail.com
|
f3ada1fdf961eefeddf365fd1fadc4c20c458450
|
b3cbf86f1704e0d62ca2fbb952a692a2de580c88
|
/2-2/cardMatch/cardmatch.cpp
|
e108efb08dbcefc7335faca8138b3973c7b8587a
|
[] |
no_license
|
WoosungMichael/CSE
|
e343846c44db52089430a5b6e8d09fa59ba0ada9
|
937f0d366cd69bedc3aaf2b1cccefa08515ec124
|
refs/heads/master
| 2023-05-09T12:35:39.879861
| 2021-06-02T05:00:17
| 2021-06-02T05:00:17
| 327,325,348
| 1
| 0
| null | null | null | null |
UHC
|
C++
| false
| false
| 7,578
|
cpp
|
//2017112148 김우성
#include "Common.h"
#include "P2017112148.h"
P2017112148::P2017112148() //생성자
{
for (int i = 0; i < BOARD_SIZE; i++) {
for (int j = 0; j < BOARD_SIZE; j++) { //가능한 모든 인덱스의 조합을 2차원 벡터를 이용하여 넣어준다.
vector<int> v2;
v2.push_back(i);
v2.push_back(j); //size가 2인 v2벡터를 만들고
v.push_back(v2); //v에 v 벡터를 push_back해준다.
}
}
}
Point P2017112148::inputFirst() //첫번째 카드를 뽑을 때 어떤 카드를 뽑을지를 정하는 함수
{
for (int s = 0; s < v.size(); s++) { //현재 아직 짝을 이루지 못한 가능한 모든 인덱스의 조합을 돌면서
Point p(v[s][0], v[s][1]); //v[s][0],v[s][1]의 위치를 가지는 p객체 선언
if (isOpenSet()) {//아직 짝지어지지 않은 이미 오픈된 카드쌍이 있는 경우
if (myboard[v[s][0]][v[s][1]] == index + 1) {//아직 짝지어지지 않은 오픈된 값(index+1)을 가진 카드의 인덱스 [v[s][0]][v[s][1]]을 찾은 경우
Point p2(v[s][0], v[s][1]); //그 위치를 가지는 Point객체 p2를 선언
p_first = p2; //첫번째 선택에서 뽑은 카드의 위치로 p2를 저장
was_zero = false; //첫번째 카드를 뽑을 때 원래 오픈되어있던 카드를 뽑았음을 표시
return p2; //p2객체 반환
}
}
else { //아직 짝지어지지 않은 오픈된 카드쌍이 없는 경우
if (myboard[v[s][0]][v[s][1]] != 0) { //이미 오픈된 카드인 경우
continue; //반복문의 다음 인덱스로 돌아가도록 한다.
}
else { //아직 오픈되지 않은 카드인 경우
p_first = p; //첫번째 선택에서 뽑은 카드의 위치로 p를 저장
was_zero = true; //첫번째 카드를 뽑을 때 원래 오픈되어있지않던 카드를 뽑았음을 표시
return p; //p객체 반환
}
}//아직 짝지어지지 않은 오픈된 카드쌍이 없는 경우, 이미 오픈된 카드를 먼저 뽑는 것 보다 아직 오픈 되지않은 카드를 먼저 오픈하는것이 효과적이다. 이는 첫번째 때, 아직 오픈 되지않은 카드를 뽑음으로서 두번째 카드를 뽑을 때 1장이라도 더 많은 오픈된 카드와 첫번째 카드를 비교해보고 뽑을 수 있기 때문이다.
}
}
Point P2017112148::inputSecond() //두번째 카드를 뽑을 때 어떤 카드를 뽑을지를 정하는 함수
{
if (was_zero == true) { //첫번째 카드를 뽑을 당시 뽑은 카드에 적힌 수를 몰랐던 경우 //isOpenSet이 falsed였던 경우
Point p(v[0][0], v[0][1]); //아래의 조건문을 모두 만족하지 않을 경우 반환할 v[0][0],v[0][1]의 위치를 가지는 p객체 선언
for (int s = 0; s < v.size(); s++) { //현재 아직 짝을 이루지 못한 가능한 모든 인덱스의 조합을 돌면서
if (myboard[v[s][0]][v[s][1]] == myboard[p_first.getX()][p_first.getY()] && ((v[s][0] != p_first.getX()) || (v[s][1] != p_first.getY()))) { //첫번째 뽑은 카드와 같은 값을 가졌고 첫번째 뽑은 카드도 아닌 카드의 인덱스 [v[s][0]][v[s][1]]을 찾은 경우
Point p2(v[s][0],v[s][1]); //두번째 선택에서 뽑을 카드의 위치로 p를 저장
return p2; //p2객체 반환
}
}
for (int s = 0; s < v.size(); s++) { //현재 아직 짝을 이루지 못한 가능한 모든 인덱스의 조합을 돌면서
if (myboard[v[s][0]][v[s][1]] == 0) { //아직 오픈되지 않은 카드인 경우
Point p2(v[s][0], v[s][1]); //이 위치를 두번째 선택에서 뽑을 카드의 위치로 p에 저장
return p2; //p2객체 반환
}
else { //이미 오픈된 카드인 경우
continue; //반복문의 다음 인덱스로 돌아가도록 한다.
}
}
return p; //p객체 반환
}
else { //첫번째 카드를 뽑을 당시 뽑은 카드에 적힌 수를 알았던 경우 //isOpenSet이 true였던 경우
for (int s = 0; s < v.size(); s++) { //현재 아직 짝을 이루지 못한 가능한 모든 인덱스의 조합을 돌면서
if (myboard[v[s][0]][v[s][1]] == myboard[p_first.getX()][p_first.getY()] && ((v[s][0] != p_first.getX()) || (v[s][1] != p_first.getY()))) { //첫번째 뽑은 카드와 같은 값을 가졌고 이미 짝을 맞춘 카드도 아니고 첫번째 뽑은 카드도 아닌 카드의 인덱스 [v[s][0]][v[s][1]]을 찾은 경우
Point p2(v[s][0],v[s][1]); //이 위치를 두번째 선택에서 뽑을 카드의 위치로 p2에 저장
return p2; //p2객체 반환
}
}
}
}
void P2017112148::checkCardInfo(Point point, int card) //플레이어가 카드를 오픈했을 때, 이를 확인하고 수행할 작업을 행하는 함수 //카드의 값을 알게 되는 경우, 이를 카드 뒤집기에 활용할 수 있으므로 이를 저장해둔다.
{
if (myboard[point.getX()][point.getY()] == 0) { //선택되어 오픈된 카드가 이전까지 아직 오픈되지 않은 카드였던 경우
myboard[point.getX()][point.getY()] = card; //myboard의 해당 위치에 오픈된 카드의 값을 저장해준다.
count[card - 1]++; //오픈된 카드의 값을 가지는 오픈되었지만 매치되지않은 카드 수를 1 증가시킨다.
}
}
void P2017112148::matchedCard(Point p1, Point p2, int card) //플레이어가 한 턴에 오픈한 두 카드가 새롭게 짝을 이루게 되었을 때의 작업을 행하는 함수 //이미 짝을 찾은 카드는 다시 뽑지 않아야 더 이길 확률을 높일 수 있으므로 짝을 찾은 여부를 저장한다.
{
mymatched[p1.getX()][p1.getY()] = true; //myboard의 p1의 위치에 값을 이미 짝을 맞췄음을 나타내는 true를 저장한다.
mymatched[p2.getX()][p2.getY()] = true; //myboard의 p2의 위치에 값을 이미 짝을 맞췄음을 나타내는 true를 저장한다.
count[card - 1] -= 2; //오픈된 카드의 값을 가지는 오픈되었지만 매치되지않은 카드 수를 2 감소시킨다. (주어진 2장이 매치되었기때문에)
for (int i = 0; i < v.size(); i++) { //현재 아직 짝을 이루진 못한 가능한 모든 인덱스의 조합을 가지는 벡터를 돌면서
if ((v[i][0] == p1.getX() && v[i][1] == p1.getY()) || (v[i][0] == p2.getX() && v[i][1] == p2.getY())) { //p1또는 p2의 인덱스 조합과 같은 값을 가지는 조합을 찾으면
v.erase(v.begin()+i); //더 이상 그 인덱스 조합은 짝을 이루지 못한 인덱스의 조합이 아니므로 해당하는 벡터를 지워준다.
i--; //주어진 for문은 계속 돌아가야하는데 위에서 erase를 하면 erase된 뒤부분의 인덱스가 땡겨져 다시 지워진 바로 직후의 인덱스에 대해서는 검사가 이루어지지 않으므로 이를 검사해주기 위해 i--를 해준다.
}
}
}
bool P2017112148::isOpenSet() //이미 오픈된 카드들 중 아직 매치가 안된 카드쌍이 존재하는지를 반환하는 함수 //이 경우에는 가장 우선적으로 이러한 카드쌍을 뽑아야하므로 이 경우에 대해 확인해주는 함수를 작성하였다.
{
bool isOpenSet = false; //isOpenSet을 false로 초기화
for (int i = 0; i < LAST_CARD_NUMBER; i++) { //모든 count배열의 인덱스에 대해
if (count[i] >= 2) { //이미 오픈된 카드들 중 같은 값을 가지는 카드가 2장 이상인 경우
isOpenSet = true; //isOpenSet을 true로 변경
index = i; //count[i]가 2 이상이 되도록 하는 i의 값을 index에 저장
return isOpenSet; //isOpenSet의 true값 반환
}
}
return isOpenSet; //isOpenSet의 false값 반환
}
|
[
"woosung0420k@naver.com"
] |
woosung0420k@naver.com
|
e4a77853a86e5160066d1f56f882436cab894677
|
242221d71c0db162b1821fbaa2fc0a8439a44e98
|
/Lab5-6/Lab5-6/OnlineSession.h
|
4c98fd99f3009fedcc64b14712a33e53d18a08d4
|
[] |
no_license
|
BereDarius/oop-course
|
c4098e31a13b5308da10d52c0ff2dde8f96c038b
|
2f574e280b0524c958d1131e7a890c08391784a7
|
refs/heads/master
| 2023-04-08T09:50:33.201681
| 2021-04-03T11:17:13
| 2021-04-03T11:17:13
| 354,260,819
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 543
|
h
|
#pragma once
#include "Request.h";
class OnlineSession : public Request {
public:
OnlineSession(int id, Date dd, float price, char* subj, std::string url, int time) : Request(id, dd, price, subj) {
m_url = url;
m_time = time;
}
OnlineSession(const Request request);
OnlineSession(const OnlineSession& offline_session);
friend ostream& operator<<(ostream& output, const Request& r);
friend istream& operator>>(istream& input, Request& r);
private:
std::string m_url; // nu mai trebuie RULE OF THREE
int m_time;
};
|
[
"noreply@github.com"
] |
BereDarius.noreply@github.com
|
a8024bdf919b025fc735a6547e1bbdb688593e0e
|
3af68b32aaa9b7522a1718b0fc50ef0cf4a704a9
|
/cpp/A/B/D/B/C/AABDBC.h
|
229083dea784fb12643b1db83dcdddff8b752393
|
[] |
no_license
|
devsisters/2021-NDC-ICECREAM
|
7cd09fa2794cbab1ab4702362a37f6ab62638d9b
|
ac6548f443a75b86d9e9151ff9c1b17c792b2afd
|
refs/heads/master
| 2023-03-19T06:29:03.216461
| 2021-03-10T02:53:14
| 2021-03-10T02:53:14
| 341,872,233
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 67
|
h
|
#ifndef AABDBC_H
namespace AABDBC {
std::string run();
}
#endif
|
[
"nakhyun@devsisters.com"
] |
nakhyun@devsisters.com
|
cabe35183e174385d4de43f13f7fb4d63c9f7b5c
|
c1014fa42d8ed378910bcf19292ac30bebca9c94
|
/CSES/DP/Grid Paths.cpp
|
032d63cd1c72994aa7cfa5b29ba2d622d423fdec
|
[] |
no_license
|
nuwaa650/Hacktoberfest_21
|
b4aee80fbd097dfb4b67417f7b1c4dfafb80a974
|
17eda0576a244614c0f5c5d0a4188bad2ecc86ca
|
refs/heads/main
| 2023-08-21T15:40:11.188785
| 2021-10-31T18:05:37
| 2021-10-31T18:05:37
| 422,869,249
| 0
| 3
| null | 2021-10-31T18:05:38
| 2021-10-30T12:02:50
|
C++
|
UTF-8
|
C++
| false
| false
| 897
|
cpp
|
#include<bits/stdc++.h>
using namespace std;
#define pb push_back
#define inf 1e18
#define mp make_pair
#define mod 1000000007
typedef vector<int> vi;
typedef long long int lli;
typedef pair<lli,lli> pii;
long long gcd(long long a, long long b) { return b == 0 ? a : gcd(b, a % b); }
long long lcm(long long a, long long b) { return a / gcd(a, b) * b; }
int main(){
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int n;
cin>>n;
vector<string> s(n+1);
for(int i=0;i<n;i++) cin>>s[i];
vector<vector<lli>>dp(n+1,vector<lli>(n+1,0));
dp[n][n]=1;
for(int i=n;i>0;i--){
for(int j=n;j>0;j--){
if(s[i-1][j-1]!='*'){
dp[i-1][j]+=dp[i][j];
dp[i][j-1]+=dp[i][j];
dp[i-1][j]%=mod;
dp[i][j-1]%=mod;
}
}
}
(s[0][0]!='*')?cout<<dp[1][1]:cout<<0;
return 0;
}
|
[
"noreply@github.com"
] |
nuwaa650.noreply@github.com
|
6fa81dd5da8e06749cf2e2768cc28834c18bdbb8
|
d6437d847b7e1298d4d3fe61a5c3b84cd3dd504b
|
/dstreader/src/THB1D.cxx
|
0aa8e28665eee6ddd8aaa04ddfc845744e42160e
|
[] |
no_license
|
adamjaro/star-upc
|
607c92edd3200687c31689552a238e16d742407e
|
b858f2ca09f90710ce18145debba638672f4a8c4
|
refs/heads/master
| 2023-03-15T18:00:29.818523
| 2023-03-10T23:16:36
| 2023-03-10T23:16:36
| 140,722,696
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 4,652
|
cxx
|
//c++ headers
#include <iostream>
#include <sstream>
#include <iomanip>
#include <vector>
#include <string>
//ROOT headers
#include "TMath.h"
//local headers
#include "THB1D.h"
using namespace std;
//_____________________________________________________________________________
THB1D::THB1D() {
//cout << "THB1D" << endl;
fHeight = 30;
SetHeight(fHeight);
fLeftMarg = 9;
fTotHeight=0;
fDigLines.reserve(10);
}//THB1D
//_____________________________________________________________________________
THB1D::THB1D(const char *name, const char *title, Int_t nbins, Double_t xmin, Double_t xmax):
TH1D(name, title, nbins, xmin, xmax) {
fHeight = 30;
SetHeight(fHeight);
fLeftMarg = 9;
fTotHeight=0;
fDigLines.reserve(10);
fLogy = kFALSE;
}//THB1D
//_____________________________________________________________________________
THB1D::~THB1D() {
//cout << "~THB1D" << endl;
}//~THB1D
//_____________________________________________________________________________
void THB1D::SetHeight(Int_t h) {
fHeight = h;
fYLabels.clear();
fYLabels.reserve(fHeight);
fHistLines.clear();
fHistLines.reserve(fHeight);
}//SetHeight
//_____________________________________________________________________________
ostream& operator<<(std::ostream& os, THB1D& hx) {
//Y axis labels
Int_t lyval=0;
Int_t yunit = 1;
Int_t ytick = (Int_t) ceil( hx.GetMaximum()/hx.fHeight/yunit );
ytick *= yunit;
for(Int_t i=0; i<hx.fHeight; i++) {
hx.fYLabels.push_back(string(""));
}
for(vector<string>::iterator it = hx.fYLabels.begin(); it != hx.fYLabels.end(); it++) {
lyval += ytick;
stringstream st;
st << lyval;
*it = st.str();
}
//fill histogram representation strings
Int_t yprev=0;
Int_t nbins = hx.GetNbinsX();
for(Int_t i=0; i<hx.fHeight; i++) {
hx.fHistLines.push_back(string(nbins, ' '));
}
for(Int_t ibin=1; ibin <= nbins; ibin++) {
if( ((Int_t) hx.GetBinContent(ibin)) == 0 ) continue;
Int_t ypos = (Int_t) hx.GetBinContent(ibin)/ytick;
if( ypos >= hx.fHeight ) {
ypos = hx.fHeight-1;
}
hx.fHistLines[ypos].replace(ibin-1, 1, "-");
if( ibin == 1 ) {
yprev = ypos;
continue;
}
if( ypos > yprev ) {
for(Int_t yc = yprev; yc < ypos; yc++) {
hx.fHistLines[yc].replace(ibin-1, 1, "I");
}
}
if( yprev > ypos ) {
for(Int_t yc = ypos; yc < yprev; yc++) {
hx.fHistLines[yc].replace(ibin-2, 1, "I");
}
}
yprev = ypos;
}
//bin content
Int_t maxdig = (Int_t)( log10(hx.GetMaximum()) + 1 );
for(Int_t i=0; i<maxdig; i++) {
hx.fDigLines.push_back(string(nbins, ' '));
}
for(Int_t ibin=1; ibin <= nbins; ibin++) {
Int_t cnt = (Int_t) hx.GetBinContent(ibin);
stringstream st;
st.width(maxdig);
st.fill('_');
st << right << cnt;
string scnt( st.str() );
string sdig;
for(Int_t idig=0; idig<maxdig; idig++) {
sdig = scnt[idig];
if( sdig == "_" ) continue;
hx.fDigLines[idig].replace(ibin-1, 1, sdig);
}
}
//print the histogram
Int_t toth = hx.fTotHeight;
Int_t digmarg = maxdig + 1;
Int_t ilin = hx.fHeight-1;
os << endl; toth--;
for(vector<string>::reverse_iterator it = hx.fYLabels.rbegin(); it != hx.fYLabels.rend(); it++) {
os.width(hx.fLeftMarg);
os << right << *it;
os.width(digmarg);
os << " ";
os.width(nbins+2);
os << hx.fHistLines[ilin--] << endl; toth--;
}
os << endl; toth--;
for(Int_t idig=0; idig<maxdig; idig++) {
os.width(hx.fLeftMarg);
if( idig==0 ) {
os << "CONTENTS";
} else {
os << " ";
}
os.width(digmarg);
//os << " ";
os << pow(10,maxdig-idig-1);
os.width(nbins+2);
os << hx.fDigLines[idig] << endl; toth--;
}
os << endl; toth--;
//entries, overflow and underflow
os.width(hx.fLeftMarg);
os << "ENTRIES" << " = ";
os.width(9);
os << left << hx.GetEntries();
os << "UNDERFLOW = ";
os.width(4);
os << hx.GetBinContent(0);
os << " OVERFLOW = ";
os << hx.GetBinContent(nbins+1);
os << endl; toth--;
os << endl; toth--;
while( toth-- > 0 ) {
os << endl;// toth--;
}
//os << "size: " << hx.fHistLines.size() << endl;
//os << "capacity: " << hx.fHistLines.capacity() << endl;
//clean-up
hx.fYLabels.clear();
hx.fHistLines.clear();
hx.fDigLines.clear();
//os << "size: " << hx.fHistLines.size() << endl;
//os << "capacity: " << hx.fHistLines.capacity() << endl;
//os << "ftoth: " << hx.fTotHeight << endl;
//os << "toth: " << toth;
//os << "ytick: " << ytick;
return os;
}
|
[
"jaroslav.adam@cern.ch"
] |
jaroslav.adam@cern.ch
|
28ef5e09a4bd59857ca44aa31ccc2314a16cd3e7
|
e20151c58b3b035f8cc08e72d292add2581f46f3
|
/CG_skel_2017/CG_skel_w_MFC/InitShader.cpp
|
fb10b5ac8bb318b13b720548371bcaeb12474080
|
[] |
no_license
|
dolbb/ComputerGraphics
|
f2a1133bb7377fe1d0c9e0df11a510da9a18f1cd
|
84227b475c85c868742643cb68dd0db8823ee4da
|
refs/heads/master
| 2021-09-05T14:36:13.654943
| 2018-01-28T22:31:27
| 2018-01-28T22:31:27
| 108,871,834
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,354
|
cpp
|
#include "stdafx.h"
#include "GL/glew.h"
#include "GL/freeglut.h"
#include "GL/freeglut_ext.h"
#include "InitShader.h"
#include <iostream>
// Create a NULL-terminated string by reading the provided file
static char*
readShaderSource(const char* shaderFile)
{
FILE* fp = fopen(shaderFile, "r");
if ( fp == NULL ) { return NULL; }
fseek(fp, 0L, SEEK_END);
long size = ftell(fp);
fseek(fp, 0L, SEEK_SET);
char* buf = new char[size + 1];
fread(buf, 1, size, fp);
buf[size] = '\0';
fclose(fp);
return buf;
}
// Create a GLSL program object from vertex and fragment shader files
GLuint
InitShader(const char* vShaderFile, const char* fShaderFile)
{
struct Shader {
const char* filename;
GLenum type;
GLchar* source;
} shaders[2] = {
{ vShaderFile, GL_VERTEX_SHADER, NULL },
{ fShaderFile, GL_FRAGMENT_SHADER, NULL }
};
GLuint program = glCreateProgram();
for ( int i = 0; i < 2; ++i ) {
Shader& s = shaders[i];
s.source = readShaderSource( s.filename );
if ( shaders[i].source == NULL ) {
std::cerr << "Failed to read " << s.filename << std::endl;
exit( EXIT_FAILURE );
}
GLuint shader = glCreateShader( s.type );
glShaderSource( shader, 1, (const GLchar**) &s.source, NULL );
glCompileShader( shader );
GLint compiled;
glGetShaderiv( shader, GL_COMPILE_STATUS, &compiled );
if ( !compiled ) {
std::cerr << s.filename << " failed to compile:" << std::endl;
GLint logSize;
glGetShaderiv( shader, GL_INFO_LOG_LENGTH, &logSize );
char* logMsg = new char[logSize];
glGetShaderInfoLog( shader, logSize, NULL, logMsg );
std::cerr << logMsg << std::endl;
delete [] logMsg;
exit( EXIT_FAILURE );
}
delete [] s.source;
glAttachShader( program, shader );
}
/* link and error check */
glLinkProgram(program);
GLint linked;
glGetProgramiv( program, GL_LINK_STATUS, &linked );
if ( !linked ) {
std::cerr << "Shader program failed to link" << std::endl;
GLint logSize;
glGetProgramiv( program, GL_INFO_LOG_LENGTH, &logSize);
char* logMsg = new char[logSize];
glGetProgramInfoLog( program, logSize, NULL, logMsg );
std::cerr << logMsg << std::endl;
delete [] logMsg;
exit( EXIT_FAILURE );
}
/* use program object */
glUseProgram(program);
return program;
}
|
[
"dolbb@campus.technion.ac.il"
] |
dolbb@campus.technion.ac.il
|
10a05799dac0686ccc5d60d0f57064e9cec97120
|
00c018a0d1a98c617d23ad84ea3097796d6eb772
|
/third_party/blink/renderer/core/layout/ng/ng_fragmentation_utils.h
|
c75aae900c003c952697f6fb41a67107af00c34b
|
[
"BSD-3-Clause",
"LGPL-2.0-or-later",
"LicenseRef-scancode-warranty-disclaimer",
"LGPL-2.1-only",
"GPL-1.0-or-later",
"GPL-2.0-only",
"LGPL-2.0-only",
"BSD-2-Clause",
"LicenseRef-scancode-other-copyleft",
"MIT",
"Apache-2.0"
] |
permissive
|
Ambyjkl/chromium
|
14ea14729df5e6ecdfbe5c996855c73740b5304f
|
23b2a91ba2010775480846cf8df64aeb7dba3db3
|
refs/heads/master
| 2023-03-10T21:18:50.899286
| 2019-11-22T02:46:17
| 2019-11-22T02:46:17
| 223,312,529
| 0
| 0
|
BSD-3-Clause
| 2019-11-22T03:04:16
| 2019-11-22T03:04:14
| null |
UTF-8
|
C++
| false
| false
| 11,376
|
h
|
// Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_LAYOUT_NG_NG_FRAGMENTATION_UTILS_H_
#define THIRD_PARTY_BLINK_RENDERER_CORE_LAYOUT_NG_NG_FRAGMENTATION_UTILS_H_
#include "third_party/blink/renderer/core/layout/ng/geometry/ng_box_strut.h"
#include "third_party/blink/renderer/core/layout/ng/ng_block_break_token.h"
#include "third_party/blink/renderer/core/layout/ng/ng_block_node.h"
#include "third_party/blink/renderer/core/layout/ng/ng_box_fragment_builder.h"
#include "third_party/blink/renderer/core/layout/ng/ng_constraint_space.h"
#include "third_party/blink/renderer/core/layout/ng/ng_physical_container_fragment.h"
#include "third_party/blink/renderer/core/style/computed_style_constants.h"
#include "third_party/blink/renderer/platform/geometry/layout_unit.h"
namespace blink {
class NGLayoutResult;
// Join two adjacent break values specified on break-before and/or break-
// after. avoid* values win over auto values, and forced break values win over
// avoid* values. |first_value| is specified on an element earlier in the flow
// than |second_value|. This method is used at class A break points [1], to join
// the values of the previous break-after and the next break-before, to figure
// out whether we may, must, or should not break at that point. It is also used
// when propagating break-before values from first children and break-after
// values on last children to their container.
//
// [1] https://drafts.csswg.org/css-break/#possible-breaks
EBreakBetween JoinFragmentainerBreakValues(EBreakBetween first_value,
EBreakBetween second_value);
// Return true if the specified break value has a forced break effect in the
// current fragmentation context.
bool IsForcedBreakValue(const NGConstraintSpace&, EBreakBetween);
// Return true if the specified break value means that we should avoid breaking,
// given the current fragmentation context.
template <typename Property>
bool IsAvoidBreakValue(const NGConstraintSpace&, Property);
// Return true if we're resuming layout after a previous break.
inline bool IsResumingLayout(const NGBlockBreakToken* token) {
return token && !token->IsBreakBefore();
}
// Calculate the final "break-between" value at a class A or C breakpoint. This
// is the combination of all break-before and break-after values that met at the
// breakpoint.
EBreakBetween CalculateBreakBetweenValue(NGLayoutInputNode child,
const NGLayoutResult&,
const NGBoxFragmentBuilder&);
// Calculate the appeal of breaking before this child.
NGBreakAppeal CalculateBreakAppealBefore(const NGConstraintSpace&,
NGLayoutInputNode child,
const NGLayoutResult&,
const NGBoxFragmentBuilder&,
bool has_container_separation);
// Calculate the appeal of breaking inside this child.
NGBreakAppeal CalculateBreakAppealInside(const NGConstraintSpace& space,
NGBlockNode child,
const NGLayoutResult&);
// Return the block space that was available in the current fragmentainer at the
// start of the current block formatting context. Note that if the start of the
// current block formatting context is in a previous fragmentainer, the size of
// the current fragmentainer is returned instead.
inline LayoutUnit FragmentainerSpaceAtBfcStart(const NGConstraintSpace& space) {
DCHECK(space.HasKnownFragmentainerBlockSize());
return space.FragmentainerBlockSize() - space.FragmentainerOffsetAtBfc();
}
// Adjust a box strut (margins, borders, scrollbars, and/or padding) to take
// fragmentation into account. Leading block margin, border, scrollbar or
// padding should only take up space in the first fragment generated from a
// node.
inline void AdjustForFragmentation(const NGBlockBreakToken* break_token,
NGBoxStrut* box_strut) {
if (LIKELY(!break_token))
return;
if (break_token->IsBreakBefore())
return;
box_strut->block_start = LayoutUnit();
}
// Set up a child's constraint space builder for block fragmentation. The child
// participates in the same fragmentation context as parent_space. If the child
// establishes a new formatting context, |fragmentainer_offset_delta| must be
// set to the offset from the parent block formatting context, or, if the parent
// formatting context starts in a previous fragmentainer; the offset from the
// current fragmentainer block-start.
void SetupFragmentation(const NGConstraintSpace& parent_space,
LayoutUnit fragmentainer_offset_delta,
NGConstraintSpaceBuilder*,
bool is_new_fc);
// Write fragmentation information to the fragment builder after layout.
void FinishFragmentation(const NGConstraintSpace&,
LayoutUnit block_size,
LayoutUnit intrinsic_block_size,
LayoutUnit previously_consumed_block_size,
LayoutUnit space_left,
NGBoxFragmentBuilder*);
// Outcome of considering (and possibly attempting) breaking before a child.
enum class NGBreakStatus {
// Continue layout. No break was inserted before the child (but there may be
// a break inside).
kContinue,
// A break was inserted before the child. Discard the child fragment and
// finish layout of the container. If there was a break inside the child, it
// will be discarded along with the child fragment.
kBrokeBefore,
// The child couldn't fit here, but no break was inserted before the child,
// as it was an unappealing place to break, and we have a better earlier
// breakpoint. We now need to abort the current layout, and go back and
// re-layout to said earlier breakpoint.
kNeedsEarlierBreak
};
// Insert a fragmentainer break before the child if necessary. In that case, the
// previous in-flow position will be updated, we'll return |kBrokeBefore|. If we
// don't break inside, we'll consider the appeal of doing so anyway (and store
// it as the most appealing break point so far if that's the case), since we
// might have to go back and break here. Return |kContinue| if we're to continue
// laying out. If |kNeedsEarlierBreak| is returned, it means that we ran out of
// space, but shouldn't break before the child, but rather abort layout, and
// re-layout to a previously found good breakpoint. If
// |has_container_separation| is true, it means that we're at a valid
// breakpoint. We obviously prefer valid breakpoints, but sometimes we need to
// break at undesirable locations. Class A breakpoints occur between block
// siblings. Class B breakpoints between line boxes. Both these breakpoint
// classes imply that we're already past the first in-flow child in the
// container, but there's also another way of achieving container separation:
// class C breakpoints. Those occur if there's a positive gap between the
// block-start content edge of the container and the block-start margin edge of
// the first in-flow child. https://www.w3.org/TR/css-break-3/#possible-breaks
NGBreakStatus BreakBeforeChildIfNeeded(const NGConstraintSpace&,
NGLayoutInputNode child,
const NGLayoutResult&,
LayoutUnit fragmentainer_block_offset,
bool has_container_separation,
NGBoxFragmentBuilder*);
// Insert a break before the child, and propagate space shortage if needed.
void BreakBeforeChild(const NGConstraintSpace&,
NGLayoutInputNode child,
const NGLayoutResult&,
LayoutUnit fragmentainer_block_offset,
NGBreakAppeal,
bool is_forced_break,
NGBoxFragmentBuilder*);
// Propagate the block-size of unbreakable content. This is used to inflate the
// initial minimal column block-size when balancing columns, before we calculate
// a tentative (or final) column block-size. Unbreakable content will actually
// fragment if the columns aren't large enough, and we want to prevent that, if
// possible.
inline void PropagateUnbreakableBlockSize(LayoutUnit block_size,
LayoutUnit fragmentainer_block_offset,
NGBoxFragmentBuilder* builder) {
// Whatever is before the block-start of the fragmentainer isn't considered to
// intersect with the fragmentainer, so subtract it (by adding the negative
// offset).
if (fragmentainer_block_offset < LayoutUnit())
block_size += fragmentainer_block_offset;
builder->PropagateTallestUnbreakableBlockSize(block_size);
}
// Propagate space shortage to the builder and beyond, if appropriate. This is
// something we do during column balancing, when we already have a tentative
// column block-size, as a means to calculate by how much we need to stretch the
// columns to make everything fit.
void PropagateSpaceShortage(const NGConstraintSpace&,
const NGLayoutResult&,
LayoutUnit fragmentainer_block_offset,
NGBoxFragmentBuilder*);
// Move past the breakpoint before the child, if possible, and return true. Also
// update the appeal of breaking before or inside the child (if we're not going
// to break before it). If false is returned, it means that we need to break
// before the child (or even earlier).
bool MovePastBreakpoint(const NGConstraintSpace& space,
NGLayoutInputNode child,
const NGLayoutResult& layout_result,
LayoutUnit fragmentainer_block_offset,
NGBreakAppeal appeal_before,
NGBoxFragmentBuilder* builder);
// If the appeal of breaking before or inside the child is the same or higher
// than any previous breakpoint we've found, set a new breakpoint in the
// builder, and update appeal accordingly.
void UpdateEarlyBreakAtBlockChild(const NGConstraintSpace&,
NGBlockNode child,
const NGLayoutResult&,
NGBreakAppeal appeal_before,
NGBoxFragmentBuilder*);
// Attempt to insert a soft break before the child, and return true if we did.
// If false is returned, it means that the desired breakpoint is earlier in the
// container, and that we need to abort and re-layout to that breakpoint.
bool AttemptSoftBreak(const NGConstraintSpace&,
NGLayoutInputNode child,
const NGLayoutResult&,
LayoutUnit fragmentainer_block_offset,
NGBreakAppeal appeal_before,
NGBoxFragmentBuilder*);
} // namespace blink
#endif // THIRD_PARTY_BLINK_RENDERER_CORE_LAYOUT_NG_NG_FRAGMENTATION_UTILS_H_
|
[
"commit-bot@chromium.org"
] |
commit-bot@chromium.org
|
5a496d0bd1d3b569c0acac032cc04486137d4598
|
ac8e6ecd711e2c4d8ec12435a32d53d57f14f875
|
/C4BoardPartWidget.hpp
|
c61b9c1c78a475a3feb0d11cc3a06d12c7e28b02
|
[] |
no_license
|
starring94/connect4
|
1de5bb725b535d8286ac4f9941dc8545d1673012
|
7e0b42187a2650efb2c85e7cb8b3a0f3df4772a3
|
refs/heads/master
| 2023-04-29T12:29:28.940934
| 2021-05-17T21:52:21
| 2021-05-17T21:52:21
| 363,424,119
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 648
|
hpp
|
#ifndef C4BOARDPARTWIDGET_HPP_INCLUDED
#define C4BOARDPARTWIDGET_HPP_INCLUDED
#include "BasicWidget.hpp"
#include "C4PieceWidget.hpp"
class C4PieceWidget;
class C4BoardPartWidget : public BasicWidget {
protected:
int m_radius;
int m_relativePositionX;
int m_relativePositionY;
public:
C4BoardPartWidget(window* parent, int x, int y, int partSize);
virtual void handleWidgetEvent(genv::event event);
//virtual bool isMouseInside(Mouse &mouse);
virtual void drawWidget();
virtual std::string getValues();
void updateRelativePositionFromPiece(C4PieceWidget* widget);
};
#endif // C4BOARDPARTWIDGET_HPP_INCLUDED
|
[
"kovinor123@gmail.com"
] |
kovinor123@gmail.com
|
d7830067513037fe3a125cdb9762766258141ce6
|
c75e00a4569cf9eb5392f48f81623f6d7991ce3e
|
/Jungding/Snowboard/ResourceManager/Type/GdsVertexBuffer.cpp
|
23d9fdd561199c35e69f081ef7ac13d1b2d1d2a6
|
[] |
no_license
|
rodrigobmg/choding
|
b90dd63ff3916d969ca625134553e1ff034e1de8
|
7b559066e0c0989720a507c011bbfd0168c7de8f
|
refs/heads/master
| 2021-01-01T03:41:36.274647
| 2012-04-02T07:03:21
| 2012-04-02T07:03:21
| 57,394,584
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,954
|
cpp
|
#include "stdafx.h"
GdsVertexBuffer::GdsVertexBuffer()
:m_Vertex_Maxcount(0)
, m_FVF( GDSVERTEX::FVF )
, m_iStartVertexIndex(0)
, m_VertexSize(0)
, m_iEndVertexIndex(0)
{
}
GdsVertexBuffer::~GdsVertexBuffer()
{
vRelease();
}
void GdsVertexBuffer::vClear()
{
m_pBuffer.clear();
m_Vertex_Maxcount = 0;
}
HRESULT GdsVertexBuffer::vRelease()
{
Free();
vClear();
return S_OK;
}
HRESULT GdsVertexBuffer::vLoadResource( LPDIRECT3DDEVICE9 device )
{
return S_OK;
}
void GdsVertexBuffer::Alloc()
{
if ( m_pVB != NULL && m_Vertex_Maxcount > 0 )
{
RESMGR.AllocVertexBuffer( m_pVB , m_Vertex_Maxcount* sizeof(GDSVERTEX) );
if ( m_pVB == NULL )
return;
VOID* pI;
if( FAILED( m_pVB->Lock( 0 , m_Vertex_Maxcount*sizeof(GDSVERTEX), (void**)&pI, 0 ) ) )
return;
GDSVERTEX* p = (GDSVERTEX*)pI;
for ( size_t i=0 ; i < m_Vertex_Maxcount ; i++ )
{
*p++ = m_pBuffer.at(i);
}
m_pVB->Unlock();
m_VertexSize = sizeof(GDSVERTEX);
m_iEndVertexIndex = m_Vertex_Maxcount;
}
}
void GdsVertexBuffer::Update()
{
VOID* pI;
if( FAILED( m_pVB->Lock( 0 , m_Vertex_Maxcount*sizeof(GDSVERTEX), (void**)&pI, 0 ) ) )
return;
GDSVERTEX* p = (GDSVERTEX*)pI;
for ( size_t i=0 ; i < m_Vertex_Maxcount ; i++ )
{
*p++ = m_pBuffer.at(i);
}
m_pVB->Unlock();
}
void GdsVertexBuffer::Free()
{
if ( m_pVB )
{
RESMGR.FreeVertexBuffer( m_pVB );
m_pBuffer.clear();
}
}
void GdsVertexBuffer::AddVertex( GDSVERTEX& vertex )
{
m_Vertex_Maxcount++;
m_pBuffer.push_back( vertex );
}
void GdsVertexBuffer::GetVertexFromIndex(int index , GDSVERTEX& vertex )
{
if( index < m_pBuffer.size() && index >= 0 )
{
vertex = m_pBuffer.at(index);
}
}
void GdsVertexBuffer::SetVertexToIndex( int index , GDSVERTEX& vertex )
{
if( index >= 0 && index < m_pBuffer.size() )
{
GDSVERTEX& p = m_pBuffer.at(index);
p = vertex;
}
}
|
[
"LeeOneHyo@gmail.com"
] |
LeeOneHyo@gmail.com
|
5dbfa5f3fba6ad7d954c1e5a3344935ddf1a15cc
|
dbec01ac3551d4dd2e1efbed81f6b1701a416fe3
|
/Models/AgileTrafficLight2/TrafficLightMVP2/MVP2Config/TrafficLightSystem.cpp
|
196ee0ae9a36924ce2024785785588f855866a46
|
[
"MIT"
] |
permissive
|
ceobkdn/Agile-Model-Based-Systems-Engineering-Cookbook
|
8bebdb3892b12c6efc13a0bb8c71f34f0c81c119
|
459c90a7b5af0aa9c16f517fd6caafc39d83f545
|
refs/heads/main
| 2023-03-23T05:58:06.611129
| 2021-03-16T08:29:14
| 2021-03-16T08:29:14
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 11,144
|
cpp
|
/********************************************************************
Rhapsody : 9.0
Login : Bruce
Component : TrafficLightMVP2
Configuration : MVP2Config
Model Element : TrafficLightSystem
//! Generated Date : Tue, 8, Dec 2020
File Path : TrafficLightMVP2/MVP2Config/TrafficLightSystem.cpp
*********************************************************************/
//#[ ignore
#define NAMESPACE_PREFIX
#define _OMSTATECHART_ANIMATED
//#]
//## auto_generated
#include "TrafficLightSystem.h"
//#[ ignore
#define Default_TrafficLightSystem_TrafficLightSystem_SERIALIZE OM_NO_OP
//#]
//## package Default
//## class TrafficLightSystem
TrafficLightSystem::TrafficLightSystem(IOxfActive* theActiveContext) {
NOTIFY_REACTIVE_CONSTRUCTOR(TrafficLightSystem, TrafficLightSystem(), 0, Default_TrafficLightSystem_TrafficLightSystem_SERIALIZE);
setActiveContext(theActiveContext, false);
{
{
primaryThru.setShouldDelete(false);
}
{
secondaryThru.setShouldDelete(false);
}
{
primaryTurn.setShouldDelete(false);
}
{
secondaryTurn.setShouldDelete(false);
}
}
initRelations();
initStatechart();
}
TrafficLightSystem::~TrafficLightSystem() {
NOTIFY_DESTRUCTOR(~TrafficLightSystem, true);
}
ThruLane* TrafficLightSystem::getPrimaryThru() const {
return (ThruLane*) &primaryThru;
}
TurnLane* TrafficLightSystem::getPrimaryTurn() const {
return (TurnLane*) &primaryTurn;
}
ThruLane* TrafficLightSystem::getSecondaryThru() const {
return (ThruLane*) &secondaryThru;
}
TurnLane* TrafficLightSystem::getSecondaryTurn() const {
return (TurnLane*) &secondaryTurn;
}
bool TrafficLightSystem::startBehavior() {
bool done = true;
done &= primaryThru.startBehavior();
done &= primaryTurn.startBehavior();
done &= secondaryThru.startBehavior();
done &= secondaryTurn.startBehavior();
done &= OMReactive::startBehavior();
return done;
}
void TrafficLightSystem::initRelations() {
{
primaryThru.get_pOutThru()->setItsEvLaneDone_ProxyReceptionInterface(secondaryThru.get_pInThru()->getItsEvLaneDone_ProxyReceptionInterface());
}
{
secondaryThru.get_pOutThru()->setItsEvLaneDone_ProxyReceptionInterface(primaryThru.get_pInThru()->getItsEvLaneDone_ProxyReceptionInterface());
}
{
primaryThru.get_pTurn()->setItsEvGoTurn_ProxyReceptionInterface(primaryTurn.get_pThru()->getItsEvGoTurn_ProxyReceptionInterface());
}{
primaryTurn.get_pThru()->setItsEvTurnDone_ProxyReceptionInterface(primaryThru.get_pTurn()->getItsEvTurnDone_ProxyReceptionInterface());
primaryTurn.get_pThru()->setItsEvCarArrive_ProxyReceptionInterface(primaryThru.get_pTurn()->getItsEvCarArrive_ProxyReceptionInterface());
}
{
secondaryThru.get_pTurn()->setItsEvGoTurn_ProxyReceptionInterface(secondaryTurn.get_pThru()->getItsEvGoTurn_ProxyReceptionInterface());
}{
secondaryTurn.get_pThru()->setItsEvTurnDone_ProxyReceptionInterface(secondaryThru.get_pTurn()->getItsEvTurnDone_ProxyReceptionInterface());
secondaryTurn.get_pThru()->setItsEvCarArrive_ProxyReceptionInterface(secondaryThru.get_pTurn()->getItsEvCarArrive_ProxyReceptionInterface());
}
}
void TrafficLightSystem::initStatechart() {
rootState_subState = OMNonState;
rootState_active = OMNonState;
}
void TrafficLightSystem::setActiveContext(IOxfActive* theActiveContext, bool activeInstance) {
OMReactive::setActiveContext(theActiveContext, activeInstance);
{
primaryThru.setActiveContext(theActiveContext, false);
secondaryThru.setActiveContext(theActiveContext, false);
primaryTurn.setActiveContext(theActiveContext, false);
secondaryTurn.setActiveContext(theActiveContext, false);
}
}
void TrafficLightSystem::destroy() {
primaryThru.destroy();
primaryTurn.destroy();
secondaryThru.destroy();
secondaryTurn.destroy();
OMReactive::destroy();
}
void TrafficLightSystem::rootState_entDef() {
{
NOTIFY_STATE_ENTERED("ROOT");
NOTIFY_TRANSITION_STARTED("0");
NOTIFY_STATE_ENTERED("ROOT.Ready");
rootState_subState = Ready;
rootState_active = Ready;
NOTIFY_TRANSITION_TERMINATED("0");
}
}
IOxfReactive::TakeEventStatus TrafficLightSystem::rootState_processEvent() {
IOxfReactive::TakeEventStatus res = eventNotConsumed;
switch (rootState_active) {
// State Ready
case Ready:
{
if(IS_EVENT_TYPE_OF(exStart_Default_id))
{
NOTIFY_TRANSITION_STARTED("1");
NOTIFY_STATE_EXITED("ROOT.Ready");
NOTIFY_STATE_ENTERED("ROOT.sendaction_2");
pushNullTransition();
rootState_subState = sendaction_2;
rootState_active = sendaction_2;
//#[ state sendaction_2.(Entry)
primaryThru.GEN(evGo(TRUE,"Primary Thru"));
//#]
NOTIFY_TRANSITION_TERMINATED("1");
res = eventConsumed;
}
}
break;
// State sendaction_2
case sendaction_2:
{
if(IS_EVENT_TYPE_OF(OMNullEventId))
{
NOTIFY_TRANSITION_STARTED("2");
popNullTransition();
NOTIFY_STATE_EXITED("ROOT.sendaction_2");
NOTIFY_STATE_ENTERED("ROOT.sendaction_3");
pushNullTransition();
rootState_subState = sendaction_3;
rootState_active = sendaction_3;
//#[ state sendaction_3.(Entry)
secondaryThru.GEN(evGo(FALSE,"Secondary"));
//#]
NOTIFY_TRANSITION_TERMINATED("2");
res = eventConsumed;
}
}
break;
// State sendaction_3
case sendaction_3:
{
if(IS_EVENT_TYPE_OF(OMNullEventId))
{
NOTIFY_TRANSITION_STARTED("3");
popNullTransition();
NOTIFY_STATE_EXITED("ROOT.sendaction_3");
NOTIFY_STATE_ENTERED("ROOT.sendaction_4");
pushNullTransition();
rootState_subState = sendaction_4;
rootState_active = sendaction_4;
//#[ state sendaction_4.(Entry)
primaryTurn.GEN(evGo(FALSE,"Primary Turn"));
//#]
NOTIFY_TRANSITION_TERMINATED("3");
res = eventConsumed;
}
}
break;
// State sendaction_4
case sendaction_4:
{
if(IS_EVENT_TYPE_OF(OMNullEventId))
{
NOTIFY_TRANSITION_STARTED("4");
popNullTransition();
NOTIFY_STATE_EXITED("ROOT.sendaction_4");
NOTIFY_STATE_ENTERED("ROOT.sendaction_5");
pushNullTransition();
rootState_subState = sendaction_5;
rootState_active = sendaction_5;
//#[ state sendaction_5.(Entry)
secondaryTurn.GEN(evGo(FALSE,"Secondary Turn"));
//#]
NOTIFY_TRANSITION_TERMINATED("4");
res = eventConsumed;
}
}
break;
// State sendaction_5
case sendaction_5:
{
if(IS_EVENT_TYPE_OF(OMNullEventId))
{
NOTIFY_TRANSITION_STARTED("5");
popNullTransition();
NOTIFY_STATE_EXITED("ROOT.sendaction_5");
NOTIFY_STATE_ENTERED("ROOT.Running");
rootState_subState = Running;
rootState_active = Running;
NOTIFY_TRANSITION_TERMINATED("5");
res = eventConsumed;
}
}
break;
default:
break;
}
return res;
}
#ifdef _OMINSTRUMENT
//#[ ignore
void OMAnimatedTrafficLightSystem::serializeRelations(AOMSRelations* aomsRelations) const {
aomsRelations->addRelation("primaryThru", true, true);
aomsRelations->ADD_ITEM(&myReal->primaryThru);
aomsRelations->addRelation("secondaryThru", true, true);
aomsRelations->ADD_ITEM(&myReal->secondaryThru);
aomsRelations->addRelation("primaryTurn", true, true);
aomsRelations->ADD_ITEM(&myReal->primaryTurn);
aomsRelations->addRelation("secondaryTurn", true, true);
aomsRelations->ADD_ITEM(&myReal->secondaryTurn);
}
void OMAnimatedTrafficLightSystem::rootState_serializeStates(AOMSState* aomsState) const {
aomsState->addState("ROOT");
switch (myReal->rootState_subState) {
case TrafficLightSystem::Ready:
{
Ready_serializeStates(aomsState);
}
break;
case TrafficLightSystem::Running:
{
Running_serializeStates(aomsState);
}
break;
case TrafficLightSystem::sendaction_2:
{
sendaction_2_serializeStates(aomsState);
}
break;
case TrafficLightSystem::sendaction_3:
{
sendaction_3_serializeStates(aomsState);
}
break;
case TrafficLightSystem::sendaction_4:
{
sendaction_4_serializeStates(aomsState);
}
break;
case TrafficLightSystem::sendaction_5:
{
sendaction_5_serializeStates(aomsState);
}
break;
default:
break;
}
}
void OMAnimatedTrafficLightSystem::sendaction_5_serializeStates(AOMSState* aomsState) const {
aomsState->addState("ROOT.sendaction_5");
}
void OMAnimatedTrafficLightSystem::sendaction_4_serializeStates(AOMSState* aomsState) const {
aomsState->addState("ROOT.sendaction_4");
}
void OMAnimatedTrafficLightSystem::sendaction_3_serializeStates(AOMSState* aomsState) const {
aomsState->addState("ROOT.sendaction_3");
}
void OMAnimatedTrafficLightSystem::sendaction_2_serializeStates(AOMSState* aomsState) const {
aomsState->addState("ROOT.sendaction_2");
}
void OMAnimatedTrafficLightSystem::Running_serializeStates(AOMSState* aomsState) const {
aomsState->addState("ROOT.Running");
}
void OMAnimatedTrafficLightSystem::Ready_serializeStates(AOMSState* aomsState) const {
aomsState->addState("ROOT.Ready");
}
//#]
IMPLEMENT_REACTIVE_META_P(TrafficLightSystem, Default, Default, false, OMAnimatedTrafficLightSystem)
#endif // _OMINSTRUMENT
/*********************************************************************
File Path : TrafficLightMVP2/MVP2Config/TrafficLightSystem.cpp
*********************************************************************/
|
[
"45961039+packt-pradeeps@users.noreply.github.com"
] |
45961039+packt-pradeeps@users.noreply.github.com
|
a477c58c46a7ffd919a3bbb9c111ff937191d955
|
f02edd2114db35a5534343c03ed25ce4eda5211f
|
/decToBinStrings.cpp
|
d3b05029211adb59154410fc4673fba949a46eb0
|
[] |
no_license
|
princeKhale/DigitalFilterCAD
|
b727572b941736adbd3e66ed327f6dce0b4eda91
|
23916cee01b5e8ae416f74462697e59bf819e3ee
|
refs/heads/master
| 2020-04-05T19:05:27.583198
| 2018-12-15T01:24:57
| 2018-12-15T01:24:57
| 157,118,052
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,882
|
cpp
|
#include <bitset>
#include <iostream>
#include <cstdlib>
#include <stdlib.h>
int main(int argc, char *argv[]) {
//Get input
double n = std::stod(argv[1]);
if(abs(n) > 127){
std::cout << "Error: Coefficient magnitude too large";
return 1;
}
char biNum[65];
//Split the input into the integer and fractional portions
bool neg = false;
if (n<0){
neg = true;
n = abs(n);
}
int integer = n;
double fraction = n-integer;
//Integer binary digits
int i = 0;
while (i<8) {
biNum[7-i] = '0' + integer % 2;
integer = integer / 2;
i++;
}
//Binary point
biNum[8] = '_';
i++;
//Fractional binary digits
while (i<65){
fraction *= 2;
int fract_bit = fraction;
if (fract_bit){
fraction -= fract_bit;
biNum[i] = '1';
} else {
biNum[i] = '0';
}
i++;
}
//Two's complement if the coefficient was negative
if(neg){
//Flip ones and zeros
for (i=0; i<65; i++){
if(biNum[i] == '1'){
biNum[i] = '0';
} else if(biNum[i] == '0'){
biNum[i] = '1';
}
}
//Add one
int carry = 1;
for (i=64; i>=0; i--){
if(biNum[i] != '_'){
char sum = biNum[i] + carry;
if (sum != '2'){
biNum[i] = sum;
carry = 0;
} else {
biNum[i] = '0';
carry = 1;
}
}
}
}
//Display output
for(i=0; i<65; i++){
std::cout << biNum[i];
}
std::cout << std::endl;
return 0;
}
|
[
"noreply@github.com"
] |
princeKhale.noreply@github.com
|
4a986e5576d8281150c170e02dfae074c294f573
|
bac2e3150dad528691b93c7b7d0ca4959cece801
|
/others/xPlusYCardProblem.cpp
|
66acd9b3104f8b7095c34fd1f43418446abd6f4e
|
[] |
no_license
|
bbvch13531/algorithm
|
78c566bcac9dd642dd81ad4d6aca10fa50746cfb
|
cf2737d2ffe7f1ef53841c273ff460e38e397ebf
|
refs/heads/master
| 2023-01-06T05:24:55.207768
| 2022-12-21T11:17:49
| 2022-12-21T11:17:49
| 164,439,044
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,120
|
cpp
|
//
// xPlusYCardProblem.cpp
// Algorithm
//
// Created by KyungYoung Heo on 2018. 7. 28..
// Copyright © 2018년 KyungYoung Heo. All rights reserved.
//
#include <iostream>
using namespace std;
string process(string str);
bool isFinished(string str);
void flipCard(string& str, int index);
int main(void){
string input,res;
cin>>input;
res = process(input);
cout<<res<<endl;
return 0;
}
string process(string str){
int len = str.length();
for(int i = 0; i<len; i++){
for(int j=i; j<len-1; j++){
if(str[j]=='0') continue;
else{
flipCard(str,j);
flipCard(str,j+1);
}
cout<<str<<endl;
}
}
if(str[len-1] == '1'){
str[len-1] = '0';
cout<<str<<endl;
}
return str;
}
bool isFinished(string str){
for(int i=0; i<str.length() - 1; i++){
if(str[i]=='1') return false;
}
return true;
}
void flipCard(string& strp, int index){
if(strp[index] == '1') strp[index]='0';
else strp[index]='1';
return;
}
|
[
"bbvch13531@gmail.com"
] |
bbvch13531@gmail.com
|
9d120febe3a9229a8070e72022b4c415b9a1933a
|
87b0a0cc6d5c1477b3b4942f544b84c9bcaa281b
|
/aitu_sorosorosibaku/src/Gimmick/EnergyBullet.cpp
|
ee1770aea969b976c631b47063a1e639c2ed48be
|
[] |
no_license
|
yuki-nakano/TeamProduction_2_firstSemester
|
bb3830e302573976ef89ba608744fbbc5779888e
|
b3e6bda9a7cac14400661156ff04dea2ac80bd26
|
refs/heads/master
| 2023-06-05T04:06:52.444348
| 2021-06-27T16:43:10
| 2021-06-27T16:43:10
| 373,681,446
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,305
|
cpp
|
#include "EnergyBullet.h"
EnergyBullet::~EnergyBullet()
{
}
bool EnergyBullet::Exec(float player_posx_, float player_posy_)
{
if (!isAlive) { return false; }
AddCount();
Move();
IsCollidePlayer(player_posx_, player_posy_);
if (IsFinished())
{
isAlive = false;
}
return true;
}
void EnergyBullet::Draw()
{
if (!isAlive) { return; }
DrawGraph(pos.X - gimmickWidht / 2, pos.Y - gimmickWidht / 2, textureManager->GetTextureDate(TextureDate::kEnergyBullet_left), TRUE);
// DrawBox(pos.X, pos.Y, pos.X + gimmickWidht, pos.Y + gimmickHeight, GetColor(0, 0, 0), FALSE);
}
void EnergyBullet::Spown(float player_posx_, float player_posy_)
{
if (isAlive) { return; }
isAlive = true;
pos.Y = player_posy_;
pos.X = Widht + gimmickWidht;
}
void EnergyBullet::IsCollidePlayer(float player_posx_, float player_posy_)
{
if (powf(player_posx_ - pos.X, 2.0f) <= powf((PlayerWidht + gimmickWidht) / 2, 2.0f) &&
powf(player_posy_ - PlayerHeight / 2 - pos.Y, 2.0f) <= powf((PlayerHeight + gimmickHeight) / 2, 2.0f))
{
gameManager->SetIsCollide(true);
isAlive = false;
}
}
void EnergyBullet::Move()
{
pos.X -= speed;
}
void EnergyBullet::AddCount()
{
count++;
if (count % 20 == 19)
{
animationCount += 1;
}
}
bool EnergyBullet::IsFinished()
{
return pos.X + gimmickWidht < 0;
}
|
[
"nyuki0614@gmail.com"
] |
nyuki0614@gmail.com
|
20f100bd9a27835ed617f1331c7468df503cf4e9
|
d377590bb4e636ab642e748ca221bb9bd9b83a81
|
/sessio6/ex3/MyGLWidget.h
|
b0ea54b6ff26a0ddc2b9590d6dff5caf0ea2ed86
|
[] |
no_license
|
ArnauRamon/FIB-IDI-Labs
|
f39e0b0f57fcb34492827a7c2e7b5da56c50c7d0
|
b2946ca9092d6e03398970a80f1f722d2ab153a6
|
refs/heads/master
| 2022-03-11T09:40:00.074707
| 2019-11-16T16:25:06
| 2019-11-16T16:25:06
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,690
|
h
|
#define GLM_FORCE_RADIANS
#include <QOpenGLFunctions_3_3_Core>
#include <QOpenGLWidget>
#include <QOpenGLShader>
#include <QOpenGLShaderProgram>
#include <QKeyEvent>
#include "glm/glm.hpp"
#include "glm/gtc/matrix_transform.hpp"
#include "model.h"
class MyGLWidget : public QOpenGLWidget, protected QOpenGLFunctions_3_3_Core
{
Q_OBJECT
public:
MyGLWidget (QWidget *parent=0);
~MyGLWidget ();
protected:
// initializeGL - Aqui incluim les inicialitzacions del contexte grafic.
virtual void initializeGL ( );
// paintGL - Mètode cridat cada cop que cal refrescar la finestra.
// Tot el que es dibuixa es dibuixa aqui.
virtual void paintGL ( );
// resizeGL - És cridat quan canvia la mida del widget
virtual void resizeGL (int width, int height);
// keyPressEvent - Es cridat quan es prem una tecla
virtual void keyPressEvent (QKeyEvent *event);
private:
void createBuffers ();
void carregaShaders ();
void modelTransform ();
// --------------------------------
// ----- LES MEVES FUNCIONS -------
// --------------------------------
void projectTransform();
void viewTransform();
void iniCamera();
void carregarModel();
void pintaHomer();
void pintaTerra();
void carregaTerra();
void modelTransformTerra();
// Sessio 5
void calculaCapsaContenidoraHomer();
void calculaCentreRadi();
void calculaCapsaContenidoraPatricio();
void carregarPatricio();
void pintaPatricio();
void mousePressEvent (QMouseEvent *e);
void mouseReleaseEvent(QMouseEvent *);
void mouseMoveEvent(QMouseEvent *e);
typedef enum {NONE, ROTATE} InteractiveAction;
InteractiveAction DoingInteractive;
// Sessio 6
void modelTransformPatricio2();
void pintaPatricio2();
void calculaCapsaEscena();
void calculaCentreRadiEscena();
GLuint projLoc, viewLoc;
glm::vec3 VRP, OBS, UP;
float ra, zNear, zFar, FOV;
float radi, radiEscena;
glm::vec3 modelMinim, modelMaxim, centre, escenaMaxim, escenaMinim, centreEscena;
Model homer;
Model patricio;
GLuint VAOhomer, VBOhomerVertex, VBOhomerMaterial;
GLuint VAOpatricio, VBOpatricioVertex, VBOpatricioMaterial;
float antigaX, antigaY, rotaX, rotaY;
float rotacio;
GLuint VAOterra, VBOterraVertex, VBOterraColor;
// --------------------------------
// attribute locations
GLuint vertexLoc, colorLoc;
// uniform locations
GLuint transLoc;
// VAO i VBO names
//GLuint VAO_Casa, VBO_CasaPos, VBO_CasaCol;
// Program
QOpenGLShaderProgram *program;
// Internal vars
float scale;
glm::vec3 pos;
};
|
[
"ana.gabriela.mestre@est.fib.upc.edu"
] |
ana.gabriela.mestre@est.fib.upc.edu
|
87e7b59a8bf9eb09acdfb7788046e97b9c084a9e
|
cc9ae71207dc667c2e0be27671ced5c86f2f71a3
|
/test/oldstudy/class_fun.cpp
|
c450701affda8c3b7a4499a732b4d0fa809bd115
|
[] |
no_license
|
xm0629/c-study
|
aed8480aa30b35637bfca307e009eb8b827b328d
|
26183be9c91b2b53bd71b6693fe6d39823bc5d63
|
refs/heads/master
| 2020-04-09T11:35:48.047562
| 2019-03-30T15:27:01
| 2019-03-30T15:27:01
| 160,316,327
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 645
|
cpp
|
// 带参数的构造函数
# include <iostream>
using namespace std;
class Box
{
public:
Box(int, int, int); // 带参数的构造函数
int volume();
private:
int height;
int width;
int length;
};
//在类外定义带参数的构造函数
Box::Box(int h, int w, int len)
{
height = h;
width = w;
length = len;
}
int Box::volume()
{
return height*width*length;
}
int main()
{
Box box1(12, 25, 30);
cout << "The volume of box1 is " << box1.volume() << endl;
Box box2(15, 30, 21);
cout << "The volume of box2 is " << box2.volume() << endl;
return 0;
}
|
[
"920972751@qq.com"
] |
920972751@qq.com
|
91dbe0453bb6260b70f55a27665dad5b9df8f90f
|
b93f4b53bd4e87b13478eb310a503031e58c47cd
|
/work-directory/PowerOfThree/main.cpp
|
8a751ef85849d738910e21bf83a7c3a9fcee428f
|
[] |
no_license
|
eugenemavrin/leetcode
|
65437c5d1f92a369ad2ab70ee80c88bbc5d05a01
|
35516fedbd766ffa4ed686866bffe5fa2d03d305
|
refs/heads/master
| 2023-03-23T16:50:59.806695
| 2021-03-14T21:06:52
| 2021-03-14T21:06:52
| 337,873,647
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 541
|
cpp
|
#include <iostream>
using namespace std;
class Solution {
public:
bool isPowerOfThree(int n) {
// Runtime: 8 ms, 89%
// Memory Usage: 5.9 MB, 81%
if (n == 1)
return true;
const int three = 3;
if (n % three != 0 && n > 1)
return false;
n = n / three;
int res = 1;
while (res < n) {
res *= three;
}
return res == n;
}
};
int main()
{
Solution s;
cout << s.isPowerOfThree(1) << endl;
return 0;
}
|
[
"e.mavrin@skoltech.ru"
] |
e.mavrin@skoltech.ru
|
a14029da149a281b32e591384ddf3f34ff744177
|
168c0dca487228f7682febfef1aaafe87e0006aa
|
/03/ex02/FragTrap.cpp
|
155df2b4fd78fdc6212b057b6411c5ba232b17c2
|
[] |
no_license
|
yaksaer/42-CPP-Module
|
d22f50e35c8cac8d41ccee0691e3670719086ce8
|
e1faddb142ef00eb0aa54f1cff4d40b63f9f521e
|
refs/heads/master
| 2022-03-29T17:22:27.363929
| 2020-01-10T17:45:47
| 2020-01-10T17:45:47
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,614
|
cpp
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* FragTrap.cpp :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: ncolomer <ncolomer@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2019/12/18 17:00:28 by ncolomer #+# #+# */
/* Updated: 2019/12/27 14:23:22 by ncolomer ### ########.fr */
/* */
/* ************************************************************************** */
#include "FragTrap.hpp"
std::string FragTrap::quotes[FragTrap::nbrQuotes] = {
"Take that!",
"Get off my lawn!",
"Coffee? Black... like my soul.",
"I am Fire, I am Death!",
"Lightening! Kukachow!"
};
FragTrap::FragTrap(std::string const &name):
ClapTrap(name)
{
std::cout << this->name << ": Recompiling my combat code !" << std::endl;
this->meleeAttackDamage = 30;
this->rangedAttackDamage = 20;
this->armorDamageReduction = 5;
}
FragTrap::FragTrap(FragTrap const &other):
ClapTrap(other.name)
{
std::cout << this->name << ": Recompiling my combat code !" << std::endl;
ClapTrap::copy(other);
}
FragTrap::~FragTrap()
{
std::cout << this->name << ": Argh arghargh death gurgle gurglegurgle urgh... death." << std::endl;
}
FragTrap &FragTrap::operator=(FragTrap const &other)
{
ClapTrap::copy(other);
return (*this);
}
void FragTrap::meleeAttack(std::string const &target)
{
std::cout << this->name << " attacks "
<< target << " at melee, causing "
<< this->meleeAttackDamage << " points of damage!" << std::endl;
}
void FragTrap::rangedAttack(std::string const &target)
{
std::cout << this->name << " attacks "
<< target << " at range, causing "
<< this->rangedAttackDamage << " points of damage!" << std::endl;
}
void FragTrap::vaulthunter_dot_exe(std::string const &target)
{
if (this->energyPoints >= 25)
{
this->energyPoints -= 25;
std::cout << this->name << ": "
<< FragTrap::quotes[rand() % FragTrap::nbrQuotes] << std::endl
<< this->name << " attacks "
<< target << " for " << ((rand() % this->meleeAttackDamage) + 1)
<< " points of damage!" << std::endl;
}
else
{
std::cout << "FR4G-TP " << this->name
<< " is out of energy!" << std::endl;
}
}
|
[
"ncolomer@e2r2p4.42.fr"
] |
ncolomer@e2r2p4.42.fr
|
c76c87e765af4f7867f37d73f1853e2b3c94a2e5
|
4d209d683e5fcd03f7ffeff999ee47adb3b8fcc3
|
/WarpTPS/Dib.cpp
|
7b5d5a3ece3fd339d9b3e2026d7c2c4c11f98f13
|
[] |
no_license
|
yuzhuqingyun/pheonixrt
|
6aebed75b78f4ac5db162429955901d963b5de49
|
6d5f2229362cedef111eea5ffea85c5022565f9b
|
refs/heads/master
| 2016-09-05T10:05:06.204029
| 2014-10-24T04:21:55
| 2014-10-24T04:21:55
| 32,519,414
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 9,413
|
cpp
|
////////////////////////////////////////////////////////////////
// PixieLib(TM) Copyright 1997-1999 Paul DiLascia
// If this code works, it was written by Paul DiLascia.
// If not, I don't know who wrote it.
//
// CDib - Device Independent Bitmap.CDib is derived from CBitmap, so
// you can use it with other MFC functions that use bitmaps.
//
#include "StdAfx.h"
#include "Dib.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
const int MAXPALCOLORS = 256;
IMPLEMENT_DYNAMIC(CDib, CObject)
CDib::CDib()
{
memset(&m_bm, 0, sizeof(m_bm));
m_hdd = NULL;
}
CDib::~CDib()
{
DeleteObject();
}
// helper to make a copy
void CDib::CopyPixels(CDib* pFrom)
{
// get the number of bytes-per-pixel for each
BITMAP srcBitmap;
pFrom->GetBitmap(&srcBitmap);
int nSrcBytesPerPixel = (srcBitmap.bmBitsPixel+7)/8;
// ensure the scan line width is on a LONG boundary
int nSrcWidthBytes = 4 * ((srcBitmap.bmWidth * nSrcBytesPerPixel + 3) / 4);
BITMAP dstBitmap;
GetBitmap(&dstBitmap);
int nDstBytesPerPixel = (dstBitmap.bmBitsPixel+7)/8;
// ensure the scan line width is on a LONG boundary
int nDstWidthBytes = 4 * ((dstBitmap.bmWidth * nDstBytesPerPixel + 3) / 4);
// should have same pixel format
ASSERT(nDstBytesPerPixel == nSrcBytesPerPixel);
ASSERT(nDstWidthBytes == nSrcWidthBytes);
ASSERT(srcBitmap.bmHeight == dstBitmap.bmHeight);
// retrieve the source and destination pixels
UCHAR *pSrcPixels = (UCHAR *) pFrom->GetDIBits();
UCHAR *pDstPixels = (UCHAR *) GetDIBits();
for (int nRow = 0; nRow < dstBitmap.bmHeight; nRow++)
{
memcpy(&pDstPixels[nRow*nDstWidthBytes], &pSrcPixels[nRow*nSrcWidthBytes], nDstWidthBytes);
}
}
// helper to blend with another
void CDib::BlendPixels(CDib* pFrom, float percent)
{
// get the number of bytes-per-pixel for each
BITMAP srcBitmap;
pFrom->GetBitmap(&srcBitmap);
int nSrcBytesPerPixel = (srcBitmap.bmBitsPixel+7)/8;
// ensure the scan line width is on a LONG boundary
int nSrcWidthBytes = 4 * ((srcBitmap.bmWidth * nSrcBytesPerPixel + 3) / 4);
BITMAP dstBitmap;
GetBitmap(&dstBitmap);
int nDstBytesPerPixel = (dstBitmap.bmBitsPixel+7)/8;
// ensure the scan line width is on a LONG boundary
int nDstWidthBytes = 4 * ((dstBitmap.bmWidth * nDstBytesPerPixel + 3) / 4);
// should have same pixel format
ASSERT(nDstBytesPerPixel == nSrcBytesPerPixel);
ASSERT(nDstWidthBytes == nSrcWidthBytes);
ASSERT(srcBitmap.bmHeight == dstBitmap.bmHeight);
// get the size of the source image
CSize dstSize = GetSize();
// retrieve the source and destination pixels
UCHAR *pSrcPixels = (UCHAR *) pFrom->GetDIBits();
UCHAR *pBlendPixels = (UCHAR *) GetDIBits();
for (int nAt = 0; nAt < (dstSize.cx * dstSize.cy * nSrcBytesPerPixel); nAt++)//nSrcBytesPixel
{
pBlendPixels[nAt] = (UCHAR)((float) pSrcPixels[nAt] * percent + (float) pBlendPixels[nAt] * (1.0 - percent));
}
}
//////////////////
// Delete Object. Delete DIB and palette.
//
BOOL CDib::DeleteObject()
{
m_pal.DeleteObject();
if (m_hdd) {
DrawDibClose(m_hdd);
m_hdd = NULL;
}
memset(&m_bm, 0, sizeof(m_bm));
return CBitmap::DeleteObject();
}
//////////////////
// Read DIB from file.
//
BOOL CDib::Load(LPCTSTR lpszPathName)
{
return Attach(::LoadImage(NULL, lpszPathName, IMAGE_BITMAP, 0, 0,
LR_LOADFROMFILE | LR_CREATEDIBSECTION | LR_DEFAULTSIZE));
}
//////////////////
// Load bitmap resource. Never tested.
//
BOOL CDib::Load(HINSTANCE hInst, LPCTSTR lpResourceName)
{
return Attach(::LoadImage(hInst, lpResourceName, IMAGE_BITMAP, 0, 0,
LR_CREATEDIBSECTION | LR_DEFAULTSIZE));
}
//////////////////
// Attach is just like the CGdiObject version,
// except it also creates the palette
//
BOOL CDib::Attach(HGDIOBJ hbm)
{
if (CBitmap::Attach(hbm)) {
if (!GetBitmap(&m_bm)) // load BITMAP for speed
return FALSE;
m_pal.DeleteObject(); // in case one is already there
return CreatePalette(m_pal); // create palette
}
return FALSE;
}
////////////////////////////////////////////////////////////////
// Draw DIB on caller's DC. Does stretching from source to destination
// rectangles. Generally, you can let the following default to zero/NULL:
//
// bUseDrawDib = whether to use use DrawDib, default TRUE
// pPal = palette, default=NULL, (use DIB's palette)
// bForeground = realize in foreground (default FALSE)
//
// If you are handling palette messages, you should use bForeground=FALSE,
// since you will realize the foreground palette in WM_QUERYNEWPALETTE.
//
BOOL CDib::Draw(CDC& dc, const CRect* rcDst, const CRect* rcSrc,
BOOL bUseDrawDib, CPalette* pPal, BOOL bForeground)
{
if (!m_hObject)
return FALSE;
// Select, realize palette
if (pPal==NULL) // no palette specified:
pPal = GetPalette(); // use default
CPalette* pOldPal = dc.SelectPalette(pPal, !bForeground);
dc.RealizePalette();
BOOL bRet = FALSE;
if (bUseDrawDib) {
// Compute rectangles where NULL specified
//
CRect rc(0,0,-1,-1); // default for DrawDibDraw
if (!rcSrc)
rcSrc = &rc;
if (!rcDst)
rcDst=rcSrc;
if (!m_hdd)
VERIFY(m_hdd = DrawDibOpen());
// Get BITMAPINFOHEADER/color table. I copy into stack object each time.
// This doesn't seem to slow things down visibly.
//
DIBSECTION ds;
VERIFY(GetObject(sizeof(ds), &ds)==sizeof(ds));
char buf[sizeof(BITMAPINFOHEADER) + MAXPALCOLORS*sizeof(RGBQUAD)];
BITMAPINFOHEADER& bmih = *(BITMAPINFOHEADER*)buf;
RGBQUAD* colors = (RGBQUAD*)(&bmih+1);
memcpy(&bmih, &ds.dsBmih, sizeof(bmih));
GetColorTable(colors, MAXPALCOLORS);
// Let DrawDib do the work!
bRet = DrawDibDraw(m_hdd, dc,
rcDst->left, rcDst->top, rcDst->Width(), rcDst->Height(),
&bmih, // ptr to BITMAPINFOHEADER + colors
m_bm.bmBits, // bits in memory
rcSrc->left, rcSrc->top, rcSrc->Width(), rcSrc->Height(),
bForeground ? 0 : DDF_BACKGROUNDPAL);
} else {
// use normal draw function
bRet = PLDrawBitmap(dc, this, rcDst, rcSrc);
}
if (pOldPal)
dc.SelectPalette(pOldPal, TRUE);
return bRet;
}
#define PALVERSION 0x300 // magic number for LOGPALETTE
//////////////////
// Create the palette. Use halftone palette for hi-color bitmaps.
//
BOOL CDib::CreatePalette(CPalette& pal)
{
// should not already have palette
ASSERT(pal.m_hObject==NULL);
BOOL bRet = FALSE;
RGBQUAD* colors = new RGBQUAD[MAXPALCOLORS];
UINT nColors = GetColorTable(colors, MAXPALCOLORS);
if (nColors > 0) {
// Allocate memory for logical palette
int len = sizeof(LOGPALETTE) + sizeof(PALETTEENTRY) * nColors;
LOGPALETTE* pLogPal = (LOGPALETTE*)new char[len];
if (!pLogPal)
return NULL;
// set version and number of palette entries
pLogPal->palVersion = PALVERSION;
pLogPal->palNumEntries = nColors;
// copy color entries
for (UINT i = 0; i < nColors; i++) {
pLogPal->palPalEntry[i].peRed = colors[i].rgbRed;
pLogPal->palPalEntry[i].peGreen = colors[i].rgbGreen;
pLogPal->palPalEntry[i].peBlue = colors[i].rgbBlue;
pLogPal->palPalEntry[i].peFlags = 0;
}
// create the palette and destroy LOGPAL
bRet = pal.CreatePalette(pLogPal);
delete [] (char*)pLogPal;
} else {
CWindowDC dcScreen(NULL);
bRet = pal.CreateHalftonePalette(&dcScreen);
}
delete colors;
return bRet;
}
//////////////////
// Helper to get color table. Does all the mem DC voodoo.
//
UINT CDib::GetColorTable(RGBQUAD* colorTab, UINT nColors)
{
CWindowDC dcScreen(NULL);
CDC memdc;
memdc.CreateCompatibleDC(&dcScreen);
CBitmap* pOldBm = memdc.SelectObject(this);
nColors = GetDIBColorTable(memdc, 0, nColors, colorTab);
memdc.SelectObject(pOldBm);
return nColors;
}
//////////////////
// Get size (width, height) of bitmap.
// extern fn works for ordinary CBitmap objects.
//
CSize PLGetBitmapSize(CBitmap* pBitmap)
{
BITMAP bm;
return pBitmap->GetBitmap(&bm) ?
CSize(bm.bmWidth, bm.bmHeight) : CSize(0,0);
}
//////////////////
// You can use this static function to draw ordinary
// CBitmaps as well as CDibs
//
BOOL PLDrawBitmap(CDC& dc, CBitmap* pBitmap,
const CRect* rcDst, const CRect* rcSrc, DWORD dwRop)
{
// Compute rectangles where NULL specified
CRect rc;
if (!rcSrc) {
// if no source rect, use whole bitmap
rc = CRect(CPoint(0,0), PLGetBitmapSize(pBitmap));
rcSrc = &rc;
}
if (!rcDst) {
// if no destination rect, use source
rcDst=rcSrc;
}
// Create memory DC
CDC memdc;
memdc.CreateCompatibleDC(&dc);
CBitmap* pOldBm = memdc.SelectObject(pBitmap);
// Blast bits from memory DC to target DC.
// Use StretchBlt if size is different.
//
BOOL bRet = FALSE;
if (rcDst->Size()==rcSrc->Size()) {
bRet = dc.BitBlt(rcDst->left, rcDst->top,
rcDst->Width(), rcDst->Height(),
&memdc, rcSrc->left, rcSrc->top, dwRop);
} else {
// dc.SetStretchBltMode(COLORONCOLOR);
dc.SetStretchBltMode(HALFTONE);
bRet = dc.StretchBlt(rcDst->left, rcDst->top, rcDst->Width(),
rcDst->Height(), &memdc, rcSrc->left, rcSrc->top, rcSrc->Width(),
rcSrc->Height(), dwRop);
}
memdc.SelectObject(pOldBm);
return bRet;
}
void *CDib::GetDIBits()
{
ASSERT(m_bm.bmBits != NULL);
return m_bm.bmBits;
}
|
[
"dglane001@gmail.com@5160d9da-b3a6-11de-af8f-1f60b1e8fe01"
] |
dglane001@gmail.com@5160d9da-b3a6-11de-af8f-1f60b1e8fe01
|
719fda0ac135e469c5efe5740864ce50cca58547
|
bae8d959d84d75c262b686390d12895f933423f6
|
/timelapseV2/timelapseV2.ino
|
f2ef47220c6a65d92b373d071d9c0973ecc1e843
|
[] |
no_license
|
tkarsist/ArduinoCode
|
25d0e306ea9d30ff7d187fb845a793f4650f9f13
|
02e0fd487b0e8ee124202a9b98ab8c3163ed06aa
|
refs/heads/master
| 2016-09-02T06:05:16.888164
| 2013-11-24T18:47:39
| 2013-11-24T18:47:39
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 8,282
|
ino
|
#include <Servo.h>
#define Length 10
typedef struct{
unsigned long int atTime;
int servoID;
int servoSpeed;
int servoDir;
}commandAction;
commandAction actionlist[Length];
//struct commandAction actionlist[1000];
Servo servo1; Servo servo2;
String sanoma="";
boolean sanomaReady=false;
boolean sanomaOngoing=false;
int actionlistIndex=0;
int actionlistNext=0;
//commandAction actionlist[];
void setup() {
pinMode(1,OUTPUT);
servo1.attach(9); //analog pin 0
//servo1.setMaximumPulse(2000);
//servo1.setMinimumPulse(700);
servo2.attach(3); //analog pin 1
Serial.begin(19200);
Serial.println("Ready");
}
void loop() {
//servo write 89 -0 toinen suunta, 90-179 toinen suunta
static int v = 0;
static int v2 = 0;
static int servoID=9;
static int servoID2=3;
static int sign=1;
//static int rotatetime=0;
static unsigned long time;
time= millis();
int i=0;
/*
if(actionlistIndex>0){
Serial.println(actionlist[actionlistNext].atTime);
Serial.println(time);
}
*/
if (actionlistIndex>0 && actionlist[actionlistNext].atTime!=0 && time>actionlist[actionlistNext].atTime){
Serial.println(actionlist[actionlistNext].atTime);
int tmpIndex=0;
if (actionlist[actionlistNext].servoSpeed>0){
//Serial.println("tuli tanne");
if (actionlist[actionlistNext].servoID==1){
v=actionlist[actionlistNext].servoSpeed*10-2;
sign=actionlist[actionlistNext].servoDir;
if(sign==1){
sign=-0;
v=187 - v;
}
servo1.attach(servoID);
servo1.write(v);
Serial.println("servo start");
v=0;
tmpIndex=1;
}
}
if(actionlist[actionlistNext].servoSpeed==0){
if(actionlist[actionlistNext].servoID==1){
Serial.println("servo detach");
servo1.detach();
tmpIndex=1;
}
}
if(tmpIndex!=0){
actionlistNext=actionlistNext+1;
Serial.println(actionlistNext);
}
}
if ( Serial.available()) {
char ch = Serial.read();
//viestin alku
if(ch == '<'){
sanomaOngoing=true;
}
//viestin loppu
if (ch == '>'){
sanomaOngoing=false;
sanomaReady=true;
}
//lisataan merkit sanomaan
if(sanomaOngoing && ch!='<'){
sanoma=sanoma + ch;
}
//sanoma valmis
if(sanomaReady){
Serial.print("sanoma: ");
Serial.println(sanoma);
//Serial.println(sanoma.substring(0,10));
//At time extract
char charAtTime[11];
String stringAtTime=sanoma.substring(0,10);
stringAtTime.toCharArray(charAtTime, sizeof(charAtTime));
unsigned long int tmpAtTime=atol(charAtTime);
Serial.print("attime: ");
Serial.println(tmpAtTime);
//servoid extract
String stringServoId=sanoma.substring(10,11);
int tmpServoId=stringServoId[0]-48;
Serial.print("servoid: ");
Serial.println(tmpServoId);
//servospeed extract
String stringServoSpeed=sanoma.substring(11,12);
int tmpServoSpeed=stringServoSpeed[0]-48;
Serial.print("servospeed: ");
Serial.println(tmpServoSpeed);
//servodirection extract
String stringServoDir=sanoma.substring(12,13);
int tmpServoDir=stringServoDir[0]-48;
Serial.print("servodirection: ");
Serial.println(tmpServoDir);
actionlist[actionlistIndex].atTime=tmpAtTime;
actionlist[actionlistIndex].servoID=tmpServoId;
actionlist[actionlistIndex].servoSpeed=tmpServoSpeed;
actionlist[actionlistIndex].servoDir=tmpServoDir;
//Serial.println(actionlist[actionlistIndex].atTime);
/*
commandAction tmpCommandAction;
//tmpCommandAction.atTime=19191991;
tmpCommandAction.atTime=tmpAtTime;
tmpCommandAction.servoID=tmpServoId;
tmpCommandAction.servoSpeed=tmpServoSpeed;
tmpCommandAction.servoDir=tmpServoDir;
//actionlist[0]=tmpCommandAction;
*/
actionlistIndex=actionlistIndex+1;
Serial.println(actionlistIndex);
sanoma="";
sanomaReady=false;
}
//static unsigned long detachS1;
//detachS1=0;
/*
if(detachS1!=0 && time>detachS1){
Serial.println("Detaching Servo1");
servo1.detach();
detachS1=0;
}
*/
/*
if(ch == '<') {
i=0;
Serial.println(Serial.available());
if(Serial.available()){
ch=Serial.read();
Serial.println("hottii shittii");
}
//while (!sanomaValmis)
while (Serial.available() && !sanomaValmis && i<10){
ch = Serial.read();
//Serial.println("osuma1.5");
//oliko loppumerkki
if (ch =='>') {
Serial.println("osuma2");
sanomaValmis=true;
Serial.println(sanoma);
}
else {
Serial.println(ch);
sanoma+=ch;
// strArray[i]=val; //laitetaan merkki bufferiin
}
i++;
}
}
sanomaValmis=false;
sanoma="";
*/
}
//switch logic: direction (-, optional), time (optional: s,m,l), speed: 0..9 (optional), servo: a-x)
/*
switch(ch) {
//direction to rotate
case '-':
sign=-1*sign;
Serial.println(sign, DEC);
break;
//small time to rotate
case 's':
//115
//Serial.println(ch, DEC);
rotatetime=500;
detachS1=time+500;
break;
//medium time to rotate
case 'm':
//109
//Serial.println(ch, DEC);
rotatetime=5000;
detachS1=time+5000;
break;
//large time to rotate
case 'l':
//108
//Serial.println(ch, DEC);
detachS1=time+20000;
rotatetime=20000;
break;
//servo speed for continuous. 0 is fastest and 9 slowest
case '0'...'9':
//char merkit on koodilta 48-57
//v = v * 100 + ch - '0';
//v=ch-40;
if(ch==48){
v=1;
}
else{
v=ch-48;
}
v=v*10-2;
v2=ch-48;
v2=v2*40-1;
v2=v2*sign;
if(sign==-1){
sign=-1*sign;
v=187 - v;
}
Serial.println("");
Serial.println (" ---------- ");
Serial.print("'0-9' :");
Serial.print(" CH:");
Serial.print(ch, DEC);
Serial.print(" V:");
Serial.print(v, DEC);
Serial.print( " V2:");
Serial.print(v2, DEC);
Serial.println(" . Case 0-9 --END");
//v=v+ch -'0';
break;
// servo a (there are servos a,b,c,d,e,f,g)
case 'a':
Serial.print("'A' :");
Serial.print(" V:");
Serial.println(v, DEC);
servo1.attach(servoID);
servo1.write(v);
if(v==0){
servo1.detach();
}
v = 0;
break;
//detach all servos
case 'd':
servo1.detach();
break;
//attach all servos
case 'x':
Serial.print("'x' :");
Serial.println(v2, DEC);
servo2.write(v2);
delay(500);
v = 0;
v2 =0;
break;
}
*/
}
|
[
"timo.karsisto@gmail.com"
] |
timo.karsisto@gmail.com
|
a2b27b38a4466567c1eeb26fe500d0b5aac70993
|
afdd66a3c6c71be75b1e6bf12904c9216646be66
|
/CApp.h
|
cb6b467ed8949a0d07d7057eba4c96962cf13719
|
[] |
no_license
|
thebum06/Tic-Tac-Toe-for-GCGPG
|
e2cedd337133bf8227dc3c63e3df723d696d7b9c
|
980f29830ed258790905fe7410aec47bc3b7a685
|
refs/heads/master
| 2021-01-01T18:34:20.661959
| 2012-04-13T23:54:36
| 2012-04-13T23:54:36
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,231
|
h
|
#ifndef _CAPP_H_
#define _CAPP_H_
#include <SDL/SDL.h>
#include <ctime>
#include <cstdlib>
#include "CEvent.h"
#include "CSurface.h"
class CApp : public CEvent {
private:
bool Running;
bool Winner;
bool Draw;
bool AI, AISelect;
SDL_Surface* Surf_Display;
private:
SDL_Surface* Surf_Grid;
SDL_Surface* Surf_X;
SDL_Surface* Surf_O;
SDL_Surface* Surf_XWin;
SDL_Surface* Surf_OWin;
SDL_Surface* Surf_Draw;
SDL_Surface* Surf_Again;
SDL_Surface* Surf_AI;
private:
int Grid[9];
int CurrentPlayer, StartPlayer;
enum {
GRID_TYPE_NONE = 0,
GRID_TYPE_X,
GRID_TYPE_O
};
public:
CApp();
int OnExecute();
public:
bool OnInit();
void OnEvent(SDL_Event* Event);
void OnExit(); void OnLButtonDown(int mX, int mY);
void OnLoop();
void Victory(); void Computer();
void OnRender();
void OnCleanup();
public:
void Reset();
void SetCell(int ID, int Type);
};
#endif
|
[
"thebum06@hotmail.com"
] |
thebum06@hotmail.com
|
23b300e2fca7645fd2965fabd053bd2c19e59e93
|
9d2c614b95606cf6cc4524544634b14a54cc3cbb
|
/ExtraStuff/Solarthing/tst/Source/CommonUtilities/CU/Utility/WindowsFunctions.h
|
aae7a328d69479795678b161d7d160437df3228a
|
[] |
no_license
|
ellet/Labbar
|
ed91378b8499b7ece5544e8cc565a02089cc3c46
|
a9771aded1583dd5b16b2b39d5e5312debb5e512
|
refs/heads/master
| 2021-06-19T09:13:18.971703
| 2016-11-30T21:16:17
| 2016-11-30T21:16:17
| 57,976,756
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 519
|
h
|
#pragma once
#include <windows.h>
#include "CU/Vectors/Vector4.h"
#include <iostream>
#ifdef UNICODE
typedef std::wstring windowsString;
#else
typedef std::string windowsString;
#endif
namespace CommonUtilities
{
namespace WindowsFunctions
{
bool CheckIfWindowFullscreen(HWND aWindowID);
Vector4f GetWindowSize(HWND aWindowID);
windowsString CreateFolder(const windowsString & aFilePathAndFolderName);
windowsString CreateFolder(const windowsString & aFilePath, const windowsString & aFolderName);
}
}
|
[
"Simon.Skogsrydh.sp15@thegameassembly.com"
] |
Simon.Skogsrydh.sp15@thegameassembly.com
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.