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 905
values | visit_date timestamp[us]date 2015-08-09 11:21:18 2023-09-06 10:45:07 | revision_date timestamp[us]date 1997-09-14 05:04:47 2023-09-17 19:19:19 | committer_date timestamp[us]date 1997-09-14 05:04:47 2023-09-06 06:22:19 | github_id int64 3.89k 681M ⌀ | star_events_count int64 0 209k | fork_events_count int64 0 110k | gha_license_id stringclasses 22
values | gha_event_created_at timestamp[us]date 2012-06-07 00:51:45 2023-09-14 21:58:39 ⌀ | gha_created_at timestamp[us]date 2008-03-27 23:40:48 2023-08-21 23:17:38 ⌀ | gha_language stringclasses 141
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 115
values | content stringlengths 3 10.4M | authors listlengths 1 1 | author_id stringlengths 0 158 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
aa3fb525029e7bbb3544bec767d27e3b686b8e28 | 89330e5b2100a37000782ef0d21209a825ffe13f | /mini/utils.cpp | 0b69f4cc76a34213ad3d13c809aad35f7a3b344a | [] | no_license | vladsol/gs-manager | c5f36b9821518e5d5ad5f0e74ea23550ac4118fc | f98795d98ebd98fafc1a81c3f257c09f968aae82 | refs/heads/master | 2021-01-20T01:56:25.405292 | 2017-04-25T09:59:40 | 2017-04-25T09:59:40 | 89,345,213 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,026 | cpp | #include "utils.h"
void SimpleConfigBase::SetParams(StringMap & params)
{
ForEachI(params, i) {
string param = i->first;
string val = i->second;
if (m_params.find(param) != m_params.end()) {
if (val == "on") val = "true";
if (val == "off") val ="false";
m_params[param]=val;
}
}
}
void SimpleConfigBase::SetParansFormSes(isp_api::Session & ses)
{
StringVector params;
ses.GetParams(params);
ForEachI(params, i) {
string param = *i;
string val = ses.Param(*i);
if (m_params.find(param) != m_params.end()) {
if (val == "on") val = "true";
if (val == "off") val ="false";
m_params[param] = val;
}
}
}
void SimpleConfigBase::ConfToSes(isp_api::Session & ses) {
ForEachI(m_params, param) {
string val = param->second;
if (val == "true") val = "on";
if (val == "false") val ="off";
ses.NewNode(param->first.c_str(),val);
}
}
void SimpleConfigBase::SetParam(const string & param, const string & value)
{
if (m_params.find(param) != m_params.end())
m_params[param]=value;
} | [
"vladsol@ukr.net"
] | vladsol@ukr.net |
b3d1e05ba071aaaefa502bd2e90101a6146795ed | 0897560a7ebde50481f950c9a441e2fc3c34ba04 | /10.0.15042.0/winrt/internal/Windows.Services.Maps.Guidance.2.h | 704325287847950eb264fe30588748c7c64a41f3 | [
"LicenseRef-scancode-generic-cla",
"MIT"
] | permissive | dngoins/cppwinrt | 338f01171153cbca14a723217129ed36b6ce2c9d | 0bb7a57392673f793ba99978738490100a9684ec | refs/heads/master | 2021-01-19T19:14:59.993078 | 2017-03-01T22:14:18 | 2017-03-01T22:14:18 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 10,865 | h | // C++ for the Windows Runtime v1.0.private
// Copyright (c) 2017 Microsoft Corporation. All rights reserved.
#pragma once
#include "Windows.Services.Maps.Guidance.1.h"
WINRT_EXPORT namespace winrt {
namespace ABI::Windows::Foundation::Collections {
#ifndef WINRT_GENERIC_e2fcc7c1_3bfc_5a0b_b2b0_72e769d1cb7e
#define WINRT_GENERIC_e2fcc7c1_3bfc_5a0b_b2b0_72e769d1cb7e
template <> struct __declspec(uuid("e2fcc7c1-3bfc-5a0b-b2b0-72e769d1cb7e")) __declspec(novtable) IIterable<hstring> : impl_IIterable<hstring> {};
#endif
#ifndef WINRT_GENERIC_2f13c006_a03a_5f69_b090_75a43e33423e
#define WINRT_GENERIC_2f13c006_a03a_5f69_b090_75a43e33423e
template <> struct __declspec(uuid("2f13c006-a03a-5f69-b090-75a43e33423e")) __declspec(novtable) IVectorView<hstring> : impl_IVectorView<hstring> {};
#endif
#ifndef WINRT_GENERIC_98b9acc1_4b56_532e_ac73_03d5291cca90
#define WINRT_GENERIC_98b9acc1_4b56_532e_ac73_03d5291cca90
template <> struct __declspec(uuid("98b9acc1-4b56-532e-ac73-03d5291cca90")) __declspec(novtable) IVector<hstring> : impl_IVector<hstring> {};
#endif
#ifndef WINRT_GENERIC_81493670_e515_5c62_b34c_6e3d996cad31
#define WINRT_GENERIC_81493670_e515_5c62_b34c_6e3d996cad31
template <> struct __declspec(uuid("81493670-e515-5c62-b34c-6e3d996cad31")) __declspec(novtable) IVectorView<Windows::Services::Maps::Guidance::GuidanceLaneInfo> : impl_IVectorView<Windows::Services::Maps::Guidance::GuidanceLaneInfo> {};
#endif
}
namespace ABI::Windows::Foundation {
#ifndef WINRT_GENERIC_82b3f7df_bf13_5445_aadc_ec61b50fbb46
#define WINRT_GENERIC_82b3f7df_bf13_5445_aadc_ec61b50fbb46
template <> struct __declspec(uuid("82b3f7df-bf13-5445-aadc-ec61b50fbb46")) __declspec(novtable) TypedEventHandler<Windows::Services::Maps::Guidance::GuidanceNavigator, Windows::Services::Maps::Guidance::GuidanceUpdatedEventArgs> : impl_TypedEventHandler<Windows::Services::Maps::Guidance::GuidanceNavigator, Windows::Services::Maps::Guidance::GuidanceUpdatedEventArgs> {};
#endif
#ifndef WINRT_GENERIC_3f496c35_3dca_5e91_8730_6ef77e9d70bd
#define WINRT_GENERIC_3f496c35_3dca_5e91_8730_6ef77e9d70bd
template <> struct __declspec(uuid("3f496c35-3dca-5e91-8730-6ef77e9d70bd")) __declspec(novtable) TypedEventHandler<Windows::Services::Maps::Guidance::GuidanceNavigator, Windows::Foundation::IInspectable> : impl_TypedEventHandler<Windows::Services::Maps::Guidance::GuidanceNavigator, Windows::Foundation::IInspectable> {};
#endif
#ifndef WINRT_GENERIC_61b92b1b_f22f_581b_bfa0_4868c314c63a
#define WINRT_GENERIC_61b92b1b_f22f_581b_bfa0_4868c314c63a
template <> struct __declspec(uuid("61b92b1b-f22f-581b-bfa0-4868c314c63a")) __declspec(novtable) TypedEventHandler<Windows::Services::Maps::Guidance::GuidanceNavigator, Windows::Services::Maps::Guidance::GuidanceReroutedEventArgs> : impl_TypedEventHandler<Windows::Services::Maps::Guidance::GuidanceNavigator, Windows::Services::Maps::Guidance::GuidanceReroutedEventArgs> {};
#endif
#ifndef WINRT_GENERIC_743db36f_e9aa_557a_9fd7_304c9b0499df
#define WINRT_GENERIC_743db36f_e9aa_557a_9fd7_304c9b0499df
template <> struct __declspec(uuid("743db36f-e9aa-557a-9fd7-304c9b0499df")) __declspec(novtable) TypedEventHandler<Windows::Services::Maps::Guidance::GuidanceNavigator, Windows::Services::Maps::Guidance::GuidanceAudioNotificationRequestedEventArgs> : impl_TypedEventHandler<Windows::Services::Maps::Guidance::GuidanceNavigator, Windows::Services::Maps::Guidance::GuidanceAudioNotificationRequestedEventArgs> {};
#endif
}
namespace ABI::Windows::Foundation::Collections {
#ifndef WINRT_GENERIC_875644d8_57a4_59d6_9d2c_5d450d39d2f6
#define WINRT_GENERIC_875644d8_57a4_59d6_9d2c_5d450d39d2f6
template <> struct __declspec(uuid("875644d8-57a4-59d6-9d2c-5d450d39d2f6")) __declspec(novtable) IVectorView<Windows::Services::Maps::Guidance::GuidanceManeuver> : impl_IVectorView<Windows::Services::Maps::Guidance::GuidanceManeuver> {};
#endif
#ifndef WINRT_GENERIC_f04c7cc2_4d54_5244_beb2_8f4f05c184e6
#define WINRT_GENERIC_f04c7cc2_4d54_5244_beb2_8f4f05c184e6
template <> struct __declspec(uuid("f04c7cc2-4d54-5244-beb2-8f4f05c184e6")) __declspec(novtable) IVectorView<Windows::Services::Maps::Guidance::GuidanceRoadSegment> : impl_IVectorView<Windows::Services::Maps::Guidance::GuidanceRoadSegment> {};
#endif
#ifndef WINRT_GENERIC_8c304ebb_6615_50a4_8829_879ecd443236
#define WINRT_GENERIC_8c304ebb_6615_50a4_8829_879ecd443236
template <> struct __declspec(uuid("8c304ebb-6615-50a4-8829-879ecd443236")) __declspec(novtable) IIterator<hstring> : impl_IIterator<hstring> {};
#endif
#ifndef WINRT_GENERIC_79362e99_4f6c_5b58_8080_00a868fe1574
#define WINRT_GENERIC_79362e99_4f6c_5b58_8080_00a868fe1574
template <> struct __declspec(uuid("79362e99-4f6c-5b58-8080-00a868fe1574")) __declspec(novtable) IVector<Windows::Services::Maps::Guidance::GuidanceLaneInfo> : impl_IVector<Windows::Services::Maps::Guidance::GuidanceLaneInfo> {};
#endif
#ifndef WINRT_GENERIC_4d4ce4d8_7ce0_5168_ab29_6bcf7f198a58
#define WINRT_GENERIC_4d4ce4d8_7ce0_5168_ab29_6bcf7f198a58
template <> struct __declspec(uuid("4d4ce4d8-7ce0-5168-ab29-6bcf7f198a58")) __declspec(novtable) IIterator<Windows::Services::Maps::Guidance::GuidanceLaneInfo> : impl_IIterator<Windows::Services::Maps::Guidance::GuidanceLaneInfo> {};
#endif
#ifndef WINRT_GENERIC_45960d72_1bf6_5a1d_a17f_e83f56f1ab57
#define WINRT_GENERIC_45960d72_1bf6_5a1d_a17f_e83f56f1ab57
template <> struct __declspec(uuid("45960d72-1bf6-5a1d-a17f-e83f56f1ab57")) __declspec(novtable) IIterable<Windows::Services::Maps::Guidance::GuidanceLaneInfo> : impl_IIterable<Windows::Services::Maps::Guidance::GuidanceLaneInfo> {};
#endif
#ifndef WINRT_GENERIC_9731f930_bd72_5313_9a18_113bc9bb48f5
#define WINRT_GENERIC_9731f930_bd72_5313_9a18_113bc9bb48f5
template <> struct __declspec(uuid("9731f930-bd72-5313-9a18-113bc9bb48f5")) __declspec(novtable) IVector<Windows::Services::Maps::Guidance::GuidanceManeuver> : impl_IVector<Windows::Services::Maps::Guidance::GuidanceManeuver> {};
#endif
#ifndef WINRT_GENERIC_74a37092_2641_5c3d_b3cb_689dc8aba22e
#define WINRT_GENERIC_74a37092_2641_5c3d_b3cb_689dc8aba22e
template <> struct __declspec(uuid("74a37092-2641-5c3d-b3cb-689dc8aba22e")) __declspec(novtable) IIterator<Windows::Services::Maps::Guidance::GuidanceManeuver> : impl_IIterator<Windows::Services::Maps::Guidance::GuidanceManeuver> {};
#endif
#ifndef WINRT_GENERIC_b5780d67_8a8b_558f_a4b6_c4531ef32ec8
#define WINRT_GENERIC_b5780d67_8a8b_558f_a4b6_c4531ef32ec8
template <> struct __declspec(uuid("b5780d67-8a8b-558f-a4b6-c4531ef32ec8")) __declspec(novtable) IIterable<Windows::Services::Maps::Guidance::GuidanceManeuver> : impl_IIterable<Windows::Services::Maps::Guidance::GuidanceManeuver> {};
#endif
#ifndef WINRT_GENERIC_dc3bab9d_a3ea_507f_9cd7_66cfa38a1c8f
#define WINRT_GENERIC_dc3bab9d_a3ea_507f_9cd7_66cfa38a1c8f
template <> struct __declspec(uuid("dc3bab9d-a3ea-507f-9cd7-66cfa38a1c8f")) __declspec(novtable) IVector<Windows::Services::Maps::Guidance::GuidanceRoadSegment> : impl_IVector<Windows::Services::Maps::Guidance::GuidanceRoadSegment> {};
#endif
#ifndef WINRT_GENERIC_148cb8ff_3ab9_53ab_8824_256a62047b43
#define WINRT_GENERIC_148cb8ff_3ab9_53ab_8824_256a62047b43
template <> struct __declspec(uuid("148cb8ff-3ab9-53ab-8824-256a62047b43")) __declspec(novtable) IIterator<Windows::Services::Maps::Guidance::GuidanceRoadSegment> : impl_IIterator<Windows::Services::Maps::Guidance::GuidanceRoadSegment> {};
#endif
#ifndef WINRT_GENERIC_f7c614c4_0fca_5eda_804c_85c829956334
#define WINRT_GENERIC_f7c614c4_0fca_5eda_804c_85c829956334
template <> struct __declspec(uuid("f7c614c4-0fca-5eda-804c-85c829956334")) __declspec(novtable) IIterable<Windows::Services::Maps::Guidance::GuidanceRoadSegment> : impl_IIterable<Windows::Services::Maps::Guidance::GuidanceRoadSegment> {};
#endif
}
namespace Windows::Services::Maps::Guidance {
struct IGuidanceAudioNotificationRequestedEventArgs :
Windows::Foundation::IInspectable,
impl::consume<IGuidanceAudioNotificationRequestedEventArgs>
{
IGuidanceAudioNotificationRequestedEventArgs(std::nullptr_t = nullptr) noexcept {}
};
struct IGuidanceLaneInfo :
Windows::Foundation::IInspectable,
impl::consume<IGuidanceLaneInfo>
{
IGuidanceLaneInfo(std::nullptr_t = nullptr) noexcept {}
};
struct IGuidanceManeuver :
Windows::Foundation::IInspectable,
impl::consume<IGuidanceManeuver>
{
IGuidanceManeuver(std::nullptr_t = nullptr) noexcept {}
};
struct IGuidanceMapMatchedCoordinate :
Windows::Foundation::IInspectable,
impl::consume<IGuidanceMapMatchedCoordinate>
{
IGuidanceMapMatchedCoordinate(std::nullptr_t = nullptr) noexcept {}
};
struct IGuidanceNavigator :
Windows::Foundation::IInspectable,
impl::consume<IGuidanceNavigator>
{
IGuidanceNavigator(std::nullptr_t = nullptr) noexcept {}
};
struct IGuidanceNavigator2 :
Windows::Foundation::IInspectable,
impl::consume<IGuidanceNavigator2>
{
IGuidanceNavigator2(std::nullptr_t = nullptr) noexcept {}
};
struct IGuidanceNavigatorStatics :
Windows::Foundation::IInspectable,
impl::consume<IGuidanceNavigatorStatics>
{
IGuidanceNavigatorStatics(std::nullptr_t = nullptr) noexcept {}
};
struct IGuidanceNavigatorStatics2 :
Windows::Foundation::IInspectable,
impl::consume<IGuidanceNavigatorStatics2>
{
IGuidanceNavigatorStatics2(std::nullptr_t = nullptr) noexcept {}
};
struct IGuidanceReroutedEventArgs :
Windows::Foundation::IInspectable,
impl::consume<IGuidanceReroutedEventArgs>
{
IGuidanceReroutedEventArgs(std::nullptr_t = nullptr) noexcept {}
};
struct IGuidanceRoadSegment :
Windows::Foundation::IInspectable,
impl::consume<IGuidanceRoadSegment>
{
IGuidanceRoadSegment(std::nullptr_t = nullptr) noexcept {}
};
struct IGuidanceRoadSignpost :
Windows::Foundation::IInspectable,
impl::consume<IGuidanceRoadSignpost>
{
IGuidanceRoadSignpost(std::nullptr_t = nullptr) noexcept {}
};
struct IGuidanceRoute :
Windows::Foundation::IInspectable,
impl::consume<IGuidanceRoute>
{
IGuidanceRoute(std::nullptr_t = nullptr) noexcept {}
};
struct IGuidanceRouteStatics :
Windows::Foundation::IInspectable,
impl::consume<IGuidanceRouteStatics>
{
IGuidanceRouteStatics(std::nullptr_t = nullptr) noexcept {}
};
struct IGuidanceTelemetryCollector :
Windows::Foundation::IInspectable,
impl::consume<IGuidanceTelemetryCollector>
{
IGuidanceTelemetryCollector(std::nullptr_t = nullptr) noexcept {}
};
struct IGuidanceTelemetryCollectorStatics :
Windows::Foundation::IInspectable,
impl::consume<IGuidanceTelemetryCollectorStatics>
{
IGuidanceTelemetryCollectorStatics(std::nullptr_t = nullptr) noexcept {}
};
struct IGuidanceUpdatedEventArgs :
Windows::Foundation::IInspectable,
impl::consume<IGuidanceUpdatedEventArgs>
{
IGuidanceUpdatedEventArgs(std::nullptr_t = nullptr) noexcept {}
};
}
}
| [
"kwelton@microsoft.com"
] | kwelton@microsoft.com |
1c95ced8c73a9e5ce36ad751756740a5b4182775 | 213e10692025d34aad0b16aea2a52ee58f378b7d | /Atcoder/BC188/A.cpp | 1dcc201f08db5c580043bd86b6b91a97417d1724 | [] | no_license | arealdeadone/contests | 348de137916b56abcd3c0a4eb79f7ea838ac74f3 | fb78c0cf97a78f8a651fd66749ba0847a988df98 | refs/heads/master | 2023-03-08T07:36:56.415616 | 2021-02-20T02:50:58 | 2021-02-20T02:50:58 | 340,546,203 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,000 | cpp | #include <bits/stdc++.h>
using namespace std;
// template {{{
#define pb push_back
#define eb emplace_back
#define mp make_pair
#define mt make_tuple
#define lb lower_bound
#define ub upper_bound
#define f first
#define s second
#define resz resize
#define sz(x) int((x).size())
#define all(x) (x).begin(), (x).end()
#define FOR(i, a, b) for (int i = (a); i < (b); i++)
#define F0R(i, a) for (int i = 0; i < (a); i++)
#define FORd(i, a, b) for (int i = (b)-1; i >= (a); i--)
#define F0Rd(i, a) for (int i = (a)-1; i >= 0; i--)
#define trav(a, x) for (auto& a : x)
#define sort_by(x, y) sort(all(x), [&](const auto& a, const auto& b) { return y; })
using ll = long long;
using llu = unsigned long long;
using vi = vector<int>;
using vvi = vector<vi>;
using vll = vector<ll>;
using vvll = vector<vll>;
using vb = vector<bool>;
using vd = vector<double>;
using vs = vector<string>;
using pii = pair<int, int>;
using pll = pair<ll, ll>;
using pdd = pair<double, double>;
using vpii = vector<pii>;
using vpll = vector<pll>;
using vpdd = vector<pdd>;
template<typename T> void ckmin(T& a, const T& b) { a = min(a, b); }
template<typename T> void ckmax(T& a, const T& b) { a = max(a, b); }
mt19937_64 rng(chrono::steady_clock::now().time_since_epoch().count());
namespace __input {
template<class T1, class T2> void re(pair<T1,T2>& p);
template<class T> void re(vector<T>& a);
template<class T, size_t SZ> void re(array<T,SZ>& a);
template<class T> void re(T& x) { cin >> x; }
void re(double& x) { string t; re(t); x = stod(t); }
template<class Arg, class... Args> void re(Arg& first, Args&... rest) {
re(first); re(rest...);
}
template<class T1, class T2> void re(pair<T1,T2>& p) { re(p.f,p.s); }
template<class T> void re(vector<T>& a) { F0R(i,sz(a)) re(a[i]); }
template<class T, size_t SZ> void re(array<T,SZ>& a) { F0R(i,SZ) re(a[i]); }
}
using namespace __input;
namespace __output {
template<class T1, class T2> void pr(const pair<T1,T2>& x);
template<class T, size_t SZ> void pr(const array<T,SZ>& x);
template<class T> void pr(const vector<T>& x);
template<class T> void pr(const set<T>& x);
template<class T1, class T2> void pr(const map<T1,T2>& x);
template<class T> void pr(const T& x) { cout << x; }
template<class Arg, class... Args> void pr(const Arg& first, const Args&... rest) {
pr(first); pr(rest...);
}
template<class T1, class T2> void pr(const pair<T1,T2>& x) {
pr("{",x.f,", ",x.s,"}");
}
#ifdef RACHURI_LOCAL
template<class T, bool pretty = true> void prContain(const T& x) {
if (pretty) pr("{");
bool fst = 1; for (const auto& a: x) pr(!fst?pretty?", ":" ":"",a), fst = 0;
if (pretty) pr("}");
}
#else
template<class T, bool pretty = false> void prContain(const T& x) {
if (pretty) pr("{");
bool fst = 1; for (const auto& a: x) pr(!fst?pretty?", ":" ":"",a), fst = 0;
if (pretty) pr("}");
}
#endif
template<class T> void pc(const T& x) { prContain<T, false>(x); pr("\n"); }
template<class T, size_t SZ> void pr(const array<T,SZ>& x) { prContain(x); }
template<class T> void pr(const vector<T>& x) { prContain(x); }
template<class T> void pr(const set<T>& x) { prContain(x); }
template<class T1, class T2> void pr(const map<T1,T2>& x) { prContain(x); }
void ps() { pr("\n"); }
template<class Arg> void ps(const Arg& first) {
pr(first); ps();
}
template<class Arg, class... Args> void ps(const Arg& first, const Args&... rest) {
pr(first," "); ps(rest...);
}
}
using namespace __output;
#define TRACE(x) x
#define __pn(x) pr(#x, " = ")
#ifdef RACHURI_LOCAL
#define pd(...) __pn((__VA_ARGS__)), ps(__VA_ARGS__), cout << flush
#else
#define pd(...)
#endif
namespace __algorithm {
template<typename T> void dedup(vector<T>& v) {
sort(all(v)); v.erase(unique(all(v)), v.end());
}
template<typename T> typename vector<T>::const_iterator find(const vector<T>& v, const T& x) {
auto it = lower_bound(all(v), x); return it != v.end() && *it == x ? it : v.end();
}
template<typename T> size_t index(const vector<T>& v, const T& x) {
auto it = find(v, x); assert(it != v.end()); return it - v.begin();
}
}
using namespace __algorithm;
namespace __io {
FILE* setIn(string s) { return freopen(s.c_str(),"r",stdin); }
FILE* setOut(string s) { return freopen(s.c_str(),"w",stdout); }
void setIO(string s = "") {
ios_base::sync_with_stdio(0); cin.tie(0);
cout << setprecision(15);
if (sz(s)) { setIn(s+".in"), setOut(s+".out"); }
}
}
using namespace __io;
// }}}
int main() {
setIO();
int x,y;
re(x); re(y);
int ms = min(x,y);
int ma = int x,y;
re(x); re(y);
int ms = min(x,y);
int ma = max(x,y);
if(ms+3 > ma) ps("Yes");
else ps("No");max(x,y);
if(ms+3 > ma) ps("Yes");
else ps("No");
return 0;
}
| [
"Arvind_Rachuri@Dell.com"
] | Arvind_Rachuri@Dell.com |
6c8d3087d1a312486fcabbe7599ee87060ca0bfd | 1ed1ed934e4175bb20024311a007d60ae784b046 | /TWOSQ.Sub3/TWOSQ.Sub3.cpp | 1de17d37c169d190d564c29f71a9610d35112cbf | [] | no_license | kkkcoder/Code_in_thptchuyen.ntucoder.net | f568cddc01b641c9a6a3c033a4b48ca59bb6435e | c4c0e19ea56a6560014cbb6e4d7489fb16e8aad7 | refs/heads/master | 2023-07-16T16:15:39.421817 | 2021-08-29T15:56:35 | 2021-08-29T15:56:35 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,103 | cpp | // Tiếp tục với series chuyện có thật ... do ARSENAL1886 bịa ra!!!
// ARSENAL1886 vừa chiến thắng cuộc thi “Tìm hiểu kiến thức vũ trụ” và nhận được phần thưởng
// do ban tổ chức tài trợ. Phần thưởng được bố trí trên một bảng kích thước m × n (tượng trưng cho
// vũ trụ), các dòng của bảng được đánh số từ 1 đến m từ trên xuống dưới, các cột của bảng được
// đánh số từ 1 đến n từ trái qua phải. Ô nằm trên giao của dòng i và cột j được gọi là ô (i,j) và trên
// ô đó chứa một món quà có giá trị là aij (1 ≤ i ≤ m, 1 ≤ j ≤ n)
// Để nhận phần thưởng, ARSENAL1886 sẽ chọn 2 hình vuông kích thước k × k không giao nhau.
// Nhân ngày 20/10, anh ấy muốn tìm hai hình vuông sao cho tổng giá trị của các món quà trong hai
// hình vuông đó là lớn nhất (để có một món quà thật ý nghĩa tặng bạn gái, mà bạn đó là ai thì ... đến
// cả ARSENAL1886 còn không biết nữa :D)
// Yêu cầu: Cho m, n, k và giá trị các phần quà trên bảng. Hãy đưa ra tổng giá trị lớn nhất có thể được
// khi chọn hai hình vuông k × k
// Input:
// • Dòng thứ nhất chứa ba số nguyên dương m, n, k
// • Dòng thứ i trong số m dòng tiếp theo chứa n số nguyên dương, số thứ j là
// aij (1 ≤ aij ≤ 106
// )
// • k luôn thoả mãn có cách chọn 2 hình vuông
// Output:
// • Một số nguyên duy nhất là kết quả bài toán
#include <bits/stdc++.h>
using namespace std;
const int nmax = 100005;
vector<long long> h[nmax], h2[nmax], a[nmax];
long long ans = 0;
vector<long long> L[nmax], maxL[nmax];
vector<long long> R[nmax], maxR[nmax];
int m, n, k, x;
int main()
{
ios::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
//freopen("KC2DIV1B.inp","r",stdin);
//freopen("KC2DIV1B.out","w",stdout);
cin >> m >> n >> k;
for (int i = 0; i <= m + 1; i++)
{
a[i].resize(n + 2);
h[i].resize(n + 2);
h2[i].resize(n + 2);
L[i].resize(n + 2);
maxL[i].resize(n + 2);
R[i].resize(n + 2);
maxR[i].resize(n + 2);
}
for (int i = 1; i <= m; i++)
for (int j = 1; j <= n; j++)
{
cin >> x;
a[i][j] = x;
if (i > k)
h[i][j] = h[i - 1][j] + a[i][j] - a[i - k][j];
else
h[i][j] = h[i - 1][j] + a[i][j];
}
for (int i = m; i >= 1; i--)
for (int j = n; j >= 1; j--)
{
if (i + k <= m)
h2[i][j] = h2[i + 1][j] + a[i][j] - a[i + k][j];
else
h2[i][j] = h2[i + 1][j] + a[i][j];
}
for (int i = 1; i <= m; i++)
for (int j = 1; j <= n; j++)
{
if (j > k)
L[i][j] = L[i][j - 1] + h[i][j] - h[i][j - k];
else
L[i][j] = L[i][j - 1] + h[i][j];
}
maxL[k][k] = L[k][k];
for (int i = k + 1; i <= n; i++)
maxL[k][i] = max(maxL[k][i - 1], L[k][i]);
for (int i = k + 1; i <= m; i++)
for (int j = k; j <= n; j++)
maxL[i][j] = max(maxL[i - 1][j], max(maxL[i][j - 1], L[i][j]));
for (int i = m; i >= 1; i--)
for (int j = n; j >= 1; j--)
{
if (j + k <= n)
R[i][j] = R[i][j + 1] + h2[i][j] - h2[i][j + k];
else
R[i][j] = R[i][j + 1] + h2[i][j];
}
maxR[m - k + 1][n - k + 1] = R[m - k + 1][n - k + 1];
for (int i = n - k + 1; i >= 1; i--)
maxR[m - k + 1][i] = max(maxR[m - k + 1][i + 1], R[m - k + 1][i]);
for (int i = m - k; i >= 1; i--)
for (int j = n - k + 1; j >= 1; j--)
maxR[i][j] = max(maxR[i + 1][j], max(maxR[i][j + 1], R[i][j]));
for (int i = k; i <= m; i++)
for (int j = k; j <= n; j++)
ans = max(ans, maxL[i][j] + max(maxR[1][j + 1], maxR[i + 1][1]));
cout << ans << endl;
}
| [
"lam3082004@gmail.com"
] | lam3082004@gmail.com |
7f11aeb453ed821e7b1c28e13dfc670137a7aa18 | 39c96d2f9714272eba18f2877ca81e93fc3c8706 | /UCL_Interface/UCL.cpp | 06a3ce3dd1647a14933b9315c3e388c0a8eb9ad0 | [] | no_license | ZJQxxn/UCL_Interface | 04c6d4d26bb51c40d3171d3fb93383b10ce73e9c | e37f5c528525a4d9c736eaf5d970a06c4ba9a4ca | refs/heads/master | 2020-12-02T23:53:32.426844 | 2017-07-27T15:28:51 | 2017-07-27T15:28:51 | 95,956,304 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 2,160 | cpp | //UCL类函数的定义
//声明在UCL.h中
#include "stdafx.h"
#include "UCL.h"
#include <fstream>
#include <string>
#include <vector>
using namespace std;
UCL::UCL(const string& filename)
{
readFromFile(filename);
}
void UCL::readFromFile(const string& filename)
{
vector <string> UCL;
ifstream file;
file.open(filename);
if (!file)
{
exit(1);
}
string str;
file >> str;
file.close();
convert(str, UCL);
vector <string>::iterator it = UCL.begin();
for (size_t count = 0; count < 32; count++)
{
UCL_Code.push_back(*it);
it++;
}
for (; it != UCL.end(); ++it)
{
UCL_Properties.push_back(*it);
}
}
vector<string>& UCL::getCode()
{
return UCL_Code;
}
vector<string>& UCL::getProperties()
{
return UCL_Properties;
}
string UCL::hexToBin(char *str)
{
string result;
if (strlen(str) == 1) //不足八位的,补零构成八位
{
result += "0000";
}
for (size_t i = 0; i < strlen(str); ++i)
{
switch (str[i])
{
case '0':
result += "0000";
break;
case '1':
result += "0001";
break;
case '2':
result += "0010";
break;
case '3':
result += "0011";
break;
case '4':
result += "0100";
break;
case '5':
result += "0101";
break;
case '6':
result += "0110";
break;
case '7':
result += "0111";
break;
case '8':
result += "1000";
break;
case '9':
result += "1001";
break;
case 'a':
result += "1010";
break;
case 'b':
result += "1011";
break;
case 'c':
result += "1100";
break;
case 'd':
result += "1101";
break;
case 'e':
result += "1110";
break;
case 'f':
result += "1111";
break;
}
}
return result;
}
void UCL::convert(string &original, vector <string>&UCL) //convert original(hex) to result(binary)
{
char *sentence = new char[original.length()];
char *tokenPtr;
char *save;
strcpy_s(sentence, original.length() + 1, original.c_str()); /*c_str() returns a char* with '\0' (char* is temporary and can't be used for assignment)*/
tokenPtr = strtok_s(sentence, "-", &save);
while (tokenPtr != nullptr)
{
UCL.push_back(hexToBin(tokenPtr));
tokenPtr = strtok_s(NULL, "-", &save);
}
} | [
"zhangjiaqi_seu@outlook.com"
] | zhangjiaqi_seu@outlook.com |
9fb563fcf2fda13df50c8e1323e94eeed89e1b6c | d49f9912788a9e3bba936731955e53b69596a3fd | /custom_widgets/material_widgets/components/scrollwidget.h | 8d1da729fac5cea3f2e04ffcec86625ff891059f | [] | no_license | ChechenItza/Daily-Planner | 9f6af0dcb3512a059c9783b36f0cd12b69a7f532 | 61b2978bc2057f1010a60a6ca391aebaf84f8daf | refs/heads/master | 2022-11-09T16:27:47.272176 | 2020-06-28T13:30:59 | 2020-06-28T13:30:59 | 99,214,353 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,070 | h | #ifndef SCROLLWIDGET_H
#define SCROLLWIDGET_H
#include <QScrollBar>
class ScrollBarPrivate;
class ScrollBar : public QScrollBar
{
Q_OBJECT
public:
explicit ScrollBar(QWidget *parent = 0);
~ScrollBar();
void setUseThemeColors(bool value);
bool useThemeColors() const;
void setCanvasColor(const QColor &color);
QColor canvasColor() const;
void setBackgroundColor(const QColor &color);
QColor backgroundColor() const;
void setSliderColor(const QColor &color);
QColor sliderColor() const;
void setHideOnMouseOut(bool state);
bool hideOnMouseOut() const;
QSize sizeHint() const Q_DECL_OVERRIDE;
protected:
//void mousePressEvent(QMouseEvent *event) Q_DECL_OVERRIDE;
//void mouseMoveEvent(QMouseEvent *event) Q_DECL_OVERRIDE;
void paintEvent(QPaintEvent *event) Q_DECL_OVERRIDE;
const QScopedPointer<ScrollBarPrivate> d_ptr;
//private:
// QMouseEvent translateEventGeometry(QMouseEvent *event);
Q_DISABLE_COPY(ScrollBar)
Q_DECLARE_PRIVATE(ScrollBar)
};
#endif // SCROLLWIDGET_H
| [
"artka.kazaktar@gmail.com"
] | artka.kazaktar@gmail.com |
a6146e70c98fe0c6f16ccf726e22feb92cff360f | 1302a788aa73d8da772c6431b083ddd76eef937f | /WORKING_DIRECTORY/bionic/libc/bionic/ifaddrs.cpp | 408949c131f9d57f39efb431a35570621aa4131e | [
"Martin-Birgmeier",
"MIT",
"SunPro",
"ISC",
"BSD-4-Clause",
"BSD-4.3TAHOE",
"Apache-2.0",
"BSD-2-Clause",
"HPND",
"LicenseRef-scancode-ibm-dhcp",
"SMLNJ",
"BSD-3-Clause",
"BSD-4-Clause-UC",
"LicenseRef-scancode-warranty-disclaimer"
] | permissive | rockduan/androidN-android-7.1.1_r28 | b3c1bcb734225aa7813ab70639af60c06d658bf6 | 10bab435cd61ffa2e93a20c082624954c757999d | refs/heads/master | 2021-01-23T03:54:32.510867 | 2017-03-30T07:17:08 | 2017-03-30T07:17:08 | 86,135,431 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 10,724 | cpp | /*
* Copyright (C) 2015 The Android Open Source Project
* 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.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
#include <ifaddrs.h>
#include <errno.h>
#include <linux/if_packet.h>
#include <net/if.h>
#include <netinet/in.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include "private/ErrnoRestorer.h"
#include "bionic_netlink.h"
// The public ifaddrs struct is full of pointers. Rather than track several
// different allocations, we use a maximally-sized structure with the public
// part at offset 0, and pointers into its hidden tail.
struct ifaddrs_storage {
// Must come first, so that `ifaddrs_storage` is-a `ifaddrs`.
ifaddrs ifa;
// The interface index, so we can match RTM_NEWADDR messages with
// earlier RTM_NEWLINK messages (to copy the interface flags).
int interface_index;
// Storage for the pointers in `ifa`.
sockaddr_storage addr;
sockaddr_storage netmask;
sockaddr_storage ifa_ifu;
char name[IFNAMSIZ + 1];
ifaddrs_storage(ifaddrs** list) {
memset(this, 0, sizeof(*this));
// push_front onto `list`.
ifa.ifa_next = *list;
*list = reinterpret_cast<ifaddrs*>(this);
}
void SetAddress(int family, const void* data, size_t byteCount) {
// The kernel currently uses the order IFA_ADDRESS, IFA_LOCAL, IFA_BROADCAST
// in inet_fill_ifaddr, but let's not assume that will always be true...
if (ifa.ifa_addr == nullptr) {
// This is an IFA_ADDRESS and haven't seen an IFA_LOCAL yet, so assume this is the
// local address. SetLocalAddress will fix things if we later see an IFA_LOCAL.
ifa.ifa_addr = CopyAddress(family, data, byteCount, &addr);
} else {
// We already saw an IFA_LOCAL, which implies this is a destination address.
ifa.ifa_dstaddr = CopyAddress(family, data, byteCount, &ifa_ifu);
}
}
void SetBroadcastAddress(int family, const void* data, size_t byteCount) {
// ifa_broadaddr and ifa_dstaddr overlap in a union. Unfortunately, it's possible
// to have an interface with both. Keeping the last thing the kernel gives us seems
// to be glibc 2.19's behavior too, so our choice is being source compatible with
// badly-written code that assumes ifa_broadaddr and ifa_dstaddr are interchangeable
// or supporting interfaces with both addresses configured. My assumption is that
// bad code is more common than weird network interfaces...
ifa.ifa_broadaddr = CopyAddress(family, data, byteCount, &ifa_ifu);
}
void SetLocalAddress(int family, const void* data, size_t byteCount) {
// The kernel source says "for point-to-point IFA_ADDRESS is DESTINATION address,
// local address is supplied in IFA_LOCAL attribute".
// -- http://lxr.free-electrons.com/source/include/uapi/linux/if_addr.h#L17
// So copy any existing IFA_ADDRESS into ifa_dstaddr...
if (ifa.ifa_addr != nullptr) {
ifa.ifa_dstaddr = reinterpret_cast<sockaddr*>(memcpy(&ifa_ifu, &addr, sizeof(addr)));
}
// ...and then put this IFA_LOCAL into ifa_addr.
ifa.ifa_addr = CopyAddress(family, data, byteCount, &addr);
}
// Netlink gives us the prefix length as a bit count. We need to turn
// that into a BSD-compatible netmask represented by a sockaddr*.
void SetNetmask(int family, size_t prefix_length) {
// ...and work out the netmask from the prefix length.
netmask.ss_family = family;
uint8_t* dst = SockaddrBytes(family, &netmask);
memset(dst, 0xff, prefix_length / 8);
if ((prefix_length % 8) != 0) {
dst[prefix_length/8] = (0xff << (8 - (prefix_length % 8)));
}
ifa.ifa_netmask = reinterpret_cast<sockaddr*>(&netmask);
}
void SetPacketAttributes(int ifindex, unsigned short hatype, unsigned char halen) {
sockaddr_ll* sll = reinterpret_cast<sockaddr_ll*>(&addr);
sll->sll_ifindex = ifindex;
sll->sll_hatype = hatype;
sll->sll_halen = halen;
}
private:
sockaddr* CopyAddress(int family, const void* data, size_t byteCount, sockaddr_storage* ss) {
// Netlink gives us the address family in the header, and the
// sockaddr_in or sockaddr_in6 bytes as the payload. We need to
// stitch the two bits together into the sockaddr that's part of
// our portable interface.
ss->ss_family = family;
memcpy(SockaddrBytes(family, ss), data, byteCount);
// For IPv6 we might also have to set the scope id.
if (family == AF_INET6 && (IN6_IS_ADDR_LINKLOCAL(data) || IN6_IS_ADDR_MC_LINKLOCAL(data))) {
reinterpret_cast<sockaddr_in6*>(ss)->sin6_scope_id = interface_index;
}
return reinterpret_cast<sockaddr*>(ss);
}
// Returns a pointer to the first byte in the address data (which is
// stored in network byte order).
uint8_t* SockaddrBytes(int family, sockaddr_storage* ss) {
if (family == AF_INET) {
sockaddr_in* ss4 = reinterpret_cast<sockaddr_in*>(ss);
return reinterpret_cast<uint8_t*>(&ss4->sin_addr);
} else if (family == AF_INET6) {
sockaddr_in6* ss6 = reinterpret_cast<sockaddr_in6*>(ss);
return reinterpret_cast<uint8_t*>(&ss6->sin6_addr);
} else if (family == AF_PACKET) {
sockaddr_ll* sll = reinterpret_cast<sockaddr_ll*>(ss);
return reinterpret_cast<uint8_t*>(&sll->sll_addr);
}
return nullptr;
}
};
static void __getifaddrs_callback(void* context, nlmsghdr* hdr) {
ifaddrs** out = reinterpret_cast<ifaddrs**>(context);
if (hdr->nlmsg_type == RTM_NEWLINK) {
ifinfomsg* ifi = reinterpret_cast<ifinfomsg*>(NLMSG_DATA(hdr));
// Create a new ifaddr entry, and set the interface index and flags.
ifaddrs_storage* new_addr = new ifaddrs_storage(out);
new_addr->interface_index = ifi->ifi_index;
new_addr->ifa.ifa_flags = ifi->ifi_flags;
// Go through the various bits of information and find the name.
rtattr* rta = IFLA_RTA(ifi);
size_t rta_len = IFLA_PAYLOAD(hdr);
while (RTA_OK(rta, rta_len)) {
if (rta->rta_type == IFLA_ADDRESS) {
if (RTA_PAYLOAD(rta) < sizeof(new_addr->addr)) {
new_addr->SetAddress(AF_PACKET, RTA_DATA(rta), RTA_PAYLOAD(rta));
new_addr->SetPacketAttributes(ifi->ifi_index, ifi->ifi_type, RTA_PAYLOAD(rta));
}
} else if (rta->rta_type == IFLA_BROADCAST) {
if (RTA_PAYLOAD(rta) < sizeof(new_addr->ifa_ifu)) {
new_addr->SetBroadcastAddress(AF_PACKET, RTA_DATA(rta), RTA_PAYLOAD(rta));
new_addr->SetPacketAttributes(ifi->ifi_index, ifi->ifi_type, RTA_PAYLOAD(rta));
}
} else if (rta->rta_type == IFLA_IFNAME) {
if (RTA_PAYLOAD(rta) < sizeof(new_addr->name)) {
memcpy(new_addr->name, RTA_DATA(rta), RTA_PAYLOAD(rta));
new_addr->ifa.ifa_name = new_addr->name;
}
}
rta = RTA_NEXT(rta, rta_len);
}
} else if (hdr->nlmsg_type == RTM_NEWADDR) {
ifaddrmsg* msg = reinterpret_cast<ifaddrmsg*>(NLMSG_DATA(hdr));
// We should already know about this from an RTM_NEWLINK message.
const ifaddrs_storage* addr = reinterpret_cast<const ifaddrs_storage*>(*out);
while (addr != nullptr && addr->interface_index != static_cast<int>(msg->ifa_index)) {
addr = reinterpret_cast<const ifaddrs_storage*>(addr->ifa.ifa_next);
}
// If this is an unknown interface, ignore whatever we're being told about it.
if (addr == nullptr) return;
// Create a new ifaddr entry and copy what we already know.
ifaddrs_storage* new_addr = new ifaddrs_storage(out);
// We can just copy the name rather than look for IFA_LABEL.
strcpy(new_addr->name, addr->name);
new_addr->ifa.ifa_name = new_addr->name;
new_addr->ifa.ifa_flags = addr->ifa.ifa_flags;
new_addr->interface_index = addr->interface_index;
// Go through the various bits of information and find the address
// and any broadcast/destination address.
rtattr* rta = IFA_RTA(msg);
size_t rta_len = IFA_PAYLOAD(hdr);
while (RTA_OK(rta, rta_len)) {
if (rta->rta_type == IFA_ADDRESS) {
if (msg->ifa_family == AF_INET || msg->ifa_family == AF_INET6) {
new_addr->SetAddress(msg->ifa_family, RTA_DATA(rta), RTA_PAYLOAD(rta));
new_addr->SetNetmask(msg->ifa_family, msg->ifa_prefixlen);
}
} else if (rta->rta_type == IFA_BROADCAST) {
if (msg->ifa_family == AF_INET) {
new_addr->SetBroadcastAddress(msg->ifa_family, RTA_DATA(rta), RTA_PAYLOAD(rta));
}
} else if (rta->rta_type == IFA_LOCAL) {
if (msg->ifa_family == AF_INET || msg->ifa_family == AF_INET6) {
new_addr->SetLocalAddress(msg->ifa_family, RTA_DATA(rta), RTA_PAYLOAD(rta));
}
}
rta = RTA_NEXT(rta, rta_len);
}
}
}
int getifaddrs(ifaddrs** out) {
// We construct the result directly into `out`, so terminate the list.
*out = nullptr;
// Open the netlink socket and ask for all the links and addresses.
NetlinkConnection nc;
bool okay = nc.SendRequest(RTM_GETLINK) && nc.ReadResponses(__getifaddrs_callback, out) &&
nc.SendRequest(RTM_GETADDR) && nc.ReadResponses(__getifaddrs_callback, out);
if (!okay) {
freeifaddrs(*out);
// Ensure that callers crash if they forget to check for success.
*out = nullptr;
return -1;
}
return 0;
}
void freeifaddrs(ifaddrs* list) {
while (list != nullptr) {
ifaddrs* current = list;
list = list->ifa_next;
free(current);
}
}
| [
"duanliangsilence@gmail.com"
] | duanliangsilence@gmail.com |
feb17bb2612e827945662ce7d9cb1223a9968c48 | b66715c97e48731ebba2afb8d81d02beb695c691 | /UVa/11262 - Weird Fence.cpp | caccad7908dbec39dc9b365a8e7c8d5ac7e797b1 | [] | no_license | justHusam/Competitive-Programming | c105b982108db914d80c759741302a9828b123b4 | 4c86037370774dc18beb1f2b302a59f2e84979d4 | refs/heads/master | 2020-03-19T10:26:12.874772 | 2018-09-14T12:24:41 | 2018-09-14T12:24:41 | 136,369,844 | 4 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,340 | cpp | #include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int N = 100;
int n, k, x[N], y[N], vis[N], vs, match[N];
vector<int> L, R, g[N];
char s[6];
inline int dist(int i, int j) {
return (x[i] - x[j]) * (x[i] - x[j]) + (y[i] - y[j]) * (y[i] - y[j]);
}
bool DFS(int v) {
vis[v] = vs;
for (int i = 0; i < g[v].size(); ++i) {
int u = match[g[v][i]];
if (u == -1 || (vis[u] != vs && DFS(u))) {
match[g[v][i]] = v;
return true;
}
}
return false;
}
bool check(int mid) {
for (int i = 0; i < n; ++i) {
g[i].clear();
match[i] = -1;
}
for (int i = 0; i < L.size(); ++i)
for (int j = 0; j < R.size(); ++j)
if (dist(L[i], R[j]) <= 1LL * mid * mid)
g[L[i]].push_back(R[j]);
int res = 0;
for (int i = 0; i < n; ++i) {
++vs;
if (DFS(i))
++res;
}
return res >= k;
}
int main(int argc, char **argv) {
int t;
scanf("%d", &t);
while (t-- != 0) {
scanf("%d%d", &n, &k);
L.clear();
R.clear();
for (int i = 0; i < n; ++i) {
scanf("%d%d%s", &x[i], &y[i], s);
if (s[0] == 'r')
L.push_back(i);
else
R.push_back(i);
}
int l = 1, r = 1e4, res = -1;
while (l <= r) {
int mid = (l + r) >> 1;
if (check(mid)) {
res = mid;
r = mid - 1;
} else
l = mid + 1;
}
if (res == -1)
puts("Impossible");
else
printf("%d\n", res);
}
return 0;
}
| [
"husam.sa3@gmail.com"
] | husam.sa3@gmail.com |
259f38cd68aa4b56692148e8bc5928041047388f | 8c5eda3178f44a7e41fda784aa1cd4dd083426a6 | /src/numbernames.cpp | 74b09e704530a71848596db324bc847047a8e95e | [] | no_license | littlewhywhat/playing-with-shifts | f7b5015c573f865ade1ca66268281caef0c0cd80 | ad3633005f6c9a51aef0b090cf5729a5fdacb73f | refs/heads/master | 2020-12-02T06:16:08.130060 | 2017-07-17T18:13:05 | 2017-07-17T18:13:05 | 96,802,944 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 193 | cpp | #include "numbernames.h"
std::string NumberNames::get_name(const std::string & prefix, int number) {
std::string name = prefix;
name.append(std::to_string(number));
return name;
}
| [
"vaivorom@fit.cvut.cz"
] | vaivorom@fit.cvut.cz |
a58d6220cde3d01acd4892b9496c7dc6ecc174f5 | 58db9457d804e4340b006cd2cdaa1e90cd998fd0 | /PlainParameter.h | d46505a6e280ebb611acf2f37602e05a8f7c3590 | [] | no_license | robmister2/LAB1_NEW | 1ccd854e6c83d0be73c2ebba956ac0c315d90993 | 994fa970a71a15646b7a16c954c19bfd04f642c4 | refs/heads/master | 2023-03-31T21:00:41.294840 | 2021-04-02T15:21:58 | 2021-04-02T15:21:58 | 334,052,888 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 353 | h |
#ifndef LAB1_NEW_PLAINPARAMETER_H
#define LAB1_NEW_PLAINPARAMETER_H
#include "Parameter.h"
#include <vector>
using namespace std;
class PlainParameter:
public Parameter{
private:
string name;
public:
PlainParameter(string name1, bool isConstant1);
string getName();
string toString();
};
#endif //LAB1_NEW_PLAINPARAMETER_H
| [
"robofcoin@gmail.com"
] | robofcoin@gmail.com |
541faf90e1589d0cf8b615ec98a1286e098dbd05 | c5bf80e5868dd000c82c981434413d6ed9d3e0be | /src/core/transformations/blur_gaussian.cpp | c41fc6cb03eeb09207fc2e61cea6601669e52a37 | [] | no_license | pto2013ErasmusStudents/Image-Processing | 9fc3a680fa6914d71849ad9487a4d23afe6b6f05 | bb100fca47bf775a36e1e1f687ad2dbf036f4494 | refs/heads/master | 2021-01-23T02:59:00.271508 | 2014-02-20T12:55:18 | 2014-02-20T12:55:18 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 871 | cpp | #include "blur_gaussian.h"
BlurGaussian::BlurGaussian(PNM* img) :
Convolution(img)
{
}
BlurGaussian::BlurGaussian(PNM* img, ImageViewer* iv) :
Convolution(img, iv)
{
}
PNM* BlurGaussian::transform()
{
emit message("Blurring...");
int size = getParameter("size").toInt();
radius = (size/2)+1;
sigma = getParameter("sigma").toDouble();
return convolute(getMask(size, Normalize), RepeatEdge);
}
math::matrix<double> BlurGaussian::getMask(int size, Mode)
{
math::matrix<double> mask(size, size);
for (int i=0;i<size;i++){
for (int j=0;j<size;j++){
mask(i,j)=getGauss(i,j,sigma);
}
}
return mask;
}
double BlurGaussian::getGauss(int x, int y, double sigma)
{
double pi=3.14159;
double value = (1/(2*pi*sigma*sigma))*exp(-(x^2+y^2)/(2*sigma*sigma));
return value;
}
| [
"marta.hidalgo@udc.es"
] | marta.hidalgo@udc.es |
e9144536aa0262736eb26ca959a124f5162e554b | 4a954052c8578fc786be249ee1eaacc576a454ef | /working_version/srcs/Portal.hpp | c7a5d1b4c7eafb1d590aa6729c817de7981a609c | [] | no_license | ldehaudt/BasicalyBomberman | bb47c32b320bdf09ed8dc597506882651c4b8fab | 9a6919507a24ae363021bfd15d15a827c69f747c | refs/heads/master | 2020-04-11T05:34:56.129784 | 2018-12-12T22:49:20 | 2018-12-12T22:49:20 | 161,553,942 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 272 | hpp | #ifndef PORTAL_HPP
#define PORTAL_HPP
#include "Position.hpp"
#include "Object.hpp"
#include "Player.hpp"
class Portal : public Object{
public:
Portal(Pos2D pos, Board& b, int);
void onPlayer(Player& player);
void deadEnemy();
private:
int numEnemy;
};
#endif | [
"ldehaudt@e1r6p11.42.fr"
] | ldehaudt@e1r6p11.42.fr |
3b84ab6f75124b90ad0d02d7685aa8245600c6c2 | 6faba6af82f9646b22da924cc87174578488b2b8 | /MiClase.h.cpp | f4ddf8aedf78f3eb2727fd41aa76ae3845d0465b | [] | no_license | IvethS/JuegoDeHerencia | a21a6980f6b98de643c86f6c43582dbb3043f366 | 22bc70bddf18e95115f5fa4335596040d391a7ea | refs/heads/master | 2020-12-30T09:51:40.596702 | 2014-11-03T14:16:32 | 2014-11-03T14:16:32 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 105 | cpp | #include "MiClase.h.h"
MiClase::MiClase()
{
//ctor
}
MiClase::~MiClase()
{
//dtor
}
| [
"alumno@localhost.localdomain"
] | alumno@localhost.localdomain |
8ea42dc7fe6fbda1f287515a2ec1c3d3d27af0aa | 34541ea972c7e8fae951d3ba053be9af35a572cc | /record/mySLL.h | 2e7192a1ee3988649e7a66676539559c7d6bcdb1 | [
"MIT"
] | permissive | dakshayh/Data-Structures | 0d48da88cea9a4f2a72ca05b4773c14c1c025baf | 042e0e66578efdba3369a140537ed1567c89d216 | refs/heads/master | 2021-04-15T13:11:35.110967 | 2018-01-29T08:35:55 | 2018-01-29T08:35:55 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,500 | h | #include<iostream>
using namespace std;
template<class T>
class SLL;
template<class T>
class CNode
{
T data;
CNode<T>*link;
friend class SLL<T>;
};
template<class T>
class SLL
{
CNode<T> *first,*last;
public:
bool isempty(){return first==NULL;}
SLL(){first=NULL;}
void LInsert(T &ele);
void display();
class chainiterator
{
CNode<T>*current;
public:
chainiterator(CNode<T>*cn)
{
current=cn;
}
T *operator->()
{
return ¤t->data;
}
chainiterator & operator++()
{
current=current->link;
return *this;
}
bool operator!=(chainiterator right)
{
return current!=right.current;
}
};
chainiterator begin()
{
return chainiterator(first);
}
chainiterator end()
{
return chainiterator(0);
}
};
template<class T>
void SLL<T>::LInsert(T &ele)
{
CNode<T>*ptr=new CNode<T>;
ptr->data=ele;
ptr->link=NULL;
if(first==NULL)
{
first=last=ptr;
}
else
{
last->link=ptr;
last=ptr;
}
}
template<class T>
void SLL<T>::display()
{
if(isempty())
throw "List is empty.Cannot display";
for(CNode<T>*p=first;p!=NULL;p=p->link)
cout<<p->data<<" ";
}
| [
"sekhar.karedla@gmail.com"
] | sekhar.karedla@gmail.com |
af4c2476549ecc51d0aa5f6a5ce60e50ac7f7f3d | 036cc01b29b56149326548cc5ca2617814f934cb | /example-klanglichtstrom/src/ofApp.h | 0550da1eced036d3137dcc57ae9ab42120f3b2f7 | [
"MIT"
] | permissive | colaplate/ofxLiveSet | 310869be1563d5abce7cec5c10ff5cb34a00fb1b | c6b95d9e4e15e8373b5912aa836366fb614f4b9f | refs/heads/master | 2021-01-03T00:00:50.966548 | 2019-12-15T18:56:53 | 2019-12-15T18:56:53 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 907 | h | #pragma once
#include "ofMain.h"
#include "ofxApp.h"
#include "ofxDmx.h"
#include "ofxLiveSet.h"
#include "./visualisation.h"
// out comment if you dont have an enttec usb interface connected
#define SENDDMX
class ofApp : public ofxApp
{
public:
ofApp();
void setup();
void update();
void draw();
void exit();
void keyPressed(int key);
void keyReleased(int key);
void mouseMoved(int x, int y);
void mouseDragged(int x, int y, int button);
void mousePressed(int x, int y, int button);
void mouseReleased(int x, int y, int button);
void mouseEntered(int x, int y);
void mouseExited(int x, int y);
void windowResized(int w, int h);
void dragEvent(ofDragInfo dragInfo);
void gotMessage(ofMessage msg);
ofxLiveSet::project::pointer _project;
ofxLiveSet::session::pointer _session;
ofxDmx _dmx;
visualisation _visualisation;
}; | [
"thomas.geissl@gmail.com"
] | thomas.geissl@gmail.com |
fcdd02c442150e5458daec83766b360b5d077ea4 | 7b85e4966ea025893569d50b07127a45ea263c7f | /atcoder/ARC 114/C.cpp | 26a0c827fc6a636152921c4d9573cc16e2710cae | [
"MIT"
] | permissive | ApocalypseMac/CP | 22e437b2d844ad0a2d4fe50590276ac4b8461dc4 | b2db9aa5392a362dc0d979411788267ed9a5ff1d | refs/heads/master | 2023-04-25T14:49:28.510588 | 2021-05-08T15:11:02 | 2021-05-08T15:11:02 | 308,243,143 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,001 | cpp | #include <bits/stdc++.h>
#include <ext/pb_ds/tree_policy.hpp>
#include <ext/pb_ds/assoc_container.hpp>
using namespace __gnu_pbds; //required
using namespace std;
template<typename T> using ordered_set = tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>;
#define fast ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL)
#define debug(x) cout << #x << " is " << x << "\n"
#define yes cout << "YES\n"
#define no cout << "NO\n"
#define flush cout.flush()
typedef long long ll;
const int MOD = 998244353;
ll dp[5005][5005]; // i ** j % MOD 0 ** 0 == 1
ll p[5005]; // \sumi_1^m-1 i ** j % MOD
int pow(int a, int b, int p){
int ans = 1 % p;
for (; b; b >>= 1){
if (b & 1) ans = (ll)ans * a % p;
a = (ll) a * a % p;
}
return ans;
}
void init(int m, int n){
for (int i = 0; i <= m; ++i){
dp[i][0] = 1;
}
for (int i = 1; i <= m; ++i){
for(int j = 1; j <= n; ++j){
dp[i][j] = dp[i][j-1] * i % MOD;
}
}
for(int j = 0; j <= n; ++j){
// p[j] = 1;
for (int i = 0; i < m; ++i){
p[j] += dp[i][j];
p[j] %= MOD;
}
}
// for (int i = 0; i <= m; ++i){
// for(int j = 0; j <= n; ++j){
// cout << i << ' ' << j << ' ' << dp[i][j] << '\n';
// }
// }
// for (int j = 0; j <= n; ++j){
// cout << j << ' ' << p[j] << '\n';
// }
}
int main(){
fast;
int n, m;
cin >> n >> m;
memset(dp, 0, sizeof(dp));
memset(p, 0, sizeof(p));
init(m, n);
ll res = n * dp[m][n];
res %= MOD;
// debug(res);
for (int i = 0; i < n; ++i){
for (int j = 0; j < i; ++j){
res -= dp[m][n-(i-j)-1] * p[i-j-1];
res %= MOD;
if (res < 0){
res += MOD;
}
// cout << i << ' ' << j << ' ' << dp[m][n-(i-j)-1] << ' ' << p[i-j-1] << ' ' << res << '\n';
}
}
cout << res << '\n';
return 0;
} | [
"ApocalypseMac@users.noreply.github.com"
] | ApocalypseMac@users.noreply.github.com |
4d9626d5218bb70024ea3e39eafdcdb5f9b59d80 | 6def4a70e1435633fc2c48a4abbd4e70bae7e8fe | /TypeConversions/typeConversions.cpp | cd5e39e91bb26efa23267d06c7202ef21938b518 | [] | no_license | kjhe11e/NodeJsAddons | 55e02d5c9ef83039a2424a824f31f3ced7e72c0e | e17e4527595ce9c2f9db29825335fcbde9ad605a | refs/heads/master | 2021-01-22T20:45:12.827807 | 2019-10-03T03:40:12 | 2019-10-03T03:40:12 | 85,355,443 | 9 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,679 | cpp | #include <node.h>
#include <string>
#include <algorithm>
#include <iostream>
using namespace v8;
void PassNumber(const FunctionCallbackInfo<Value>& args) {
Isolate* isolate = args.GetIsolate();
/*Local<Number> target = args[0]->ToNumber();
double value = target->NumberValue();*/
double value = args[0]->NumberValue();
value += 10;
Local<Number> returnVal = Number::New(isolate, value);
args.GetReturnValue().Set(returnVal);
}
void ReverseStr(const FunctionCallbackInfo<Value>& args) {
Isolate* isolate = args.GetIsolate();
if(!args[0]->IsString()) {
isolate->ThrowException(Exception::TypeError(
String::NewFromUtf8(isolate, "Input must be a string")
));
} else {
v8::String::Utf8Value s(args[0]);
std::string str(*s); //wrap in c++
std::reverse(str.begin(), str.end());
Local<String> reversedString = String::NewFromUtf8(isolate, str.c_str());
args.GetReturnValue().Set(reversedString);
}
}
void IncrementArray(const FunctionCallbackInfo<Value>& args) {
Isolate* isolate = args.GetIsolate();
Local<Array> arr = Local<Array>::Cast(args[0]);
for(unsigned int i = 0; i < arr->Length(); i++) {
double value = arr->Get(i)->NumberValue();
arr->Set(i, Number::New(isolate, value + 1));
}
// Since objects (and arrays) are mutable, these changes will be reflected
// even if we don't explicitly return
}
// Called when addon is require'd from JS
void Init(Local<Object> exports) {
NODE_SET_METHOD(exports, "passNumber", PassNumber);
NODE_SET_METHOD(exports, "reverseStr", ReverseStr);
NODE_SET_METHOD(exports, "incrementArray", IncrementArray);
}
NODE_MODULE(typeConversions, Init) // macros
| [
"kjhelle4@gmail.com"
] | kjhelle4@gmail.com |
83814323e45b31ec5705aeaccaa5fb843755ccdf | 5b952b10a4cf77745ecafee2174cd0e5bed13113 | /fft.cpp | 8bacd8314b8fec31dd72ead1392d9ec2e2582751 | [
"MIT"
] | permissive | cuklev/frequency-analyzer | 723ba9543bcd4f1092256c84b42dfe72f0e9b2da | 5069afa1b2c642b0532c58f955ca6767883294e7 | refs/heads/master | 2021-01-12T06:17:52.552148 | 2017-12-06T20:46:26 | 2017-12-06T20:46:26 | 77,337,150 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,477 | cpp | #include "fft.hpp"
#include <vector>
#include <complex>
namespace {
using ComplexNumber = std::complex<double>;
const uint32_t Mask0 = 0x55555555;
const uint32_t Mask1 = 0x33333333;
const uint32_t Mask2 = 0x0F0F0F0F;
const uint32_t Mask3 = 0x00FF00FF;
const uint32_t Mask4 = 0x0000FFFF;
inline void swap_mask(uint32_t& n, uint32_t mask, int bit_count) {
n = ((n & mask) << bit_count) | ((n >> bit_count) & mask);
}
inline uint32_t reverse_bits(uint32_t n, int bit_count) {
swap_mask(n, Mask0, 1);
swap_mask(n, Mask1, 2);
swap_mask(n, Mask2, 4);
swap_mask(n, Mask3, 8);
swap_mask(n, Mask4, 16);
return n >> (32 - bit_count);
}
}
void fft_get_amplitudes(short* buffer, size_t sample_count, double* amplitudes) {
int bit_count = __builtin_ctz(sample_count);
auto data = std::vector<ComplexNumber>(sample_count);
for(size_t i = 0; i < sample_count; ++i) {
auto j = reverse_bits(i, bit_count);
data[j] = {(double) buffer[i], 0};
}
for(int k = 0; k < bit_count; ++k) {
double angle = M_PI / (1 << k);
ComplexNumber primitive_root = {cos(angle), sin(angle)};
for(unsigned i = 0; i < data.size(); i += (2u << k)) {
ComplexNumber w = {1, 0};
for(unsigned j = i; j < i + (1u << k); ++j) {
data[j + (1u << k)] *= w;
auto diff = data[j] - data[j + (1u << k)];
data[j] += data[j + (1u << k)];
data[j + (1u << k)] = diff;
w *= primitive_root;
}
}
}
for(size_t i = 0; i < sample_count; ++i)
amplitudes[i] = abs(data[i]);
}
| [
"cuki@cukii.tk"
] | cuki@cukii.tk |
7a4f0d329c51bf36217cbfd1c9566bfe669ceca3 | be5ca13f5d582e172883b01ef4b89f2527fcec1f | /02_arc/079d.cpp | c806dd8c8ab9159cbb11ae96307700fa6fe694af | [] | no_license | sinhrks/CompetitiveProgramming | 8569bb001411b58b50aa1f5e2f187c17fe5fb2f1 | 7e310bd0e8b64a888289eebe8b37ed0554cced6f | refs/heads/master | 2021-09-01T09:35:50.406900 | 2017-12-26T08:13:34 | 2017-12-26T08:13:34 | 103,657,034 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 906 | cpp | #include <assert.h>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <algorithm>
#include <numeric>
#include <functional>
#include <iostream>
#include <string>
#include <array>
#include <vector>
#include <stack>
#include <queue>
#include <set>
#include <map>
#include <complex>
#include <bitset>
typedef long long ll;
typedef unsigned long long ull;
using namespace std;
int main() {
cin.tie(0);
ios::sync_with_stdio(false);
ll K;
cin >> K;
int N = 50;
vector<ll> ans(N, 0);
for (int j = 0; j < N; j++) {
ans[j] = j + K / N;
}
ll remain = K % N;
for (int j = 0; j < remain; j++) {
ans[j] += N;
for (int k = 0; k < N; k++) {
if (k != j) {
ans[k] -= 1;
}
}
}
cout << N << endl;
for (int i = 0; i < N; i++) {
cout << ans[i];
if (i < N - 1) {
cout << " ";
}
}
cout << endl;
return 0;
}
| [
"sinhrks@gmail.com"
] | sinhrks@gmail.com |
71338de0071378b88d056ac018184555c28044a8 | 7166e08738c1151a5e3d1242e19d655aaccc9ec5 | /LeetCode/Perfect_Squares/Main.cpp | 4466c3aaeab49bf8c13be8c6efb400132bd1de1e | [] | no_license | CaseyYang/LeetCode | 4602e3a5612c43e37f936e7a35abead6ebbf2cbc | ea3b3ea70a8012c5f5d82108642b88816a2788b2 | refs/heads/master | 2021-01-25T05:22:56.600363 | 2015-10-25T07:33:53 | 2015-10-25T07:33:53 | 26,250,162 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 412 | cpp | #include<iostream>
#include<vector>
#include<algorithm>
#include<math.h>
using namespace std;
class Solution {
public:
int numSquares(int n) {
if (n == 0) return 0;
vector<int> result = vector<int>();
result.push_back(0);
for (int i = 1; i <= n; ++i){
result.push_back(i);
for (int j = 1; j <= sqrt(i); ++j){
result[i] = min(result[i], 1 + result[i - j*j]);
}
}
return result[n];
}
}; | [
"knightykc@gmail.com"
] | knightykc@gmail.com |
5c9f9feafc4f9acbfa3f7b55fbfbf5cab553a398 | 5bc04daeef5284871264a7446aadf7552ec0d195 | /lib/percy/cryptominisat/src/searchstats.cpp | adde61afacd9b0fbee60784d40bc11d2be1f7803 | [
"MIT",
"GPL-1.0-or-later",
"GPL-2.0-only"
] | permissive | Ace-Ma/LSOracle | a8fd7efe8927f8154ea37407bac727e409098ed5 | 6e940906303ef6c2c6b96352f44206567fdd50d3 | refs/heads/master | 2020-07-23T15:36:18.224385 | 2019-08-16T15:58:33 | 2019-08-16T15:58:33 | 207,612,130 | 0 | 0 | MIT | 2019-09-10T16:42:43 | 2019-09-10T16:42:43 | null | UTF-8 | C++ | false | false | 12,107 | cpp | /******************************************
Copyright (c) 2016, Mate Soos
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
***********************************************/
#include "searchstats.h"
using namespace CMSat;
SearchStats& SearchStats::operator+=(const SearchStats& other)
{
numRestarts += other.numRestarts;
blocked_restart += other.blocked_restart;
blocked_restart_same += other.blocked_restart_same;
//Decisions
decisions += other.decisions;
decisionsAssump += other.decisionsAssump;
decisionsRand += other.decisionsRand;
decisionFlippedPolar += other.decisionFlippedPolar;
//Conflict minimisation stats
litsRedNonMin += other.litsRedNonMin;
litsRedFinal += other.litsRedFinal;
recMinCl += other.recMinCl;
recMinLitRem += other.recMinLitRem;
permDiff_attempt += other.permDiff_attempt;
permDiff_rem_lits += other.permDiff_rem_lits;
permDiff_success += other.permDiff_success;
furtherShrinkAttempt += other.furtherShrinkAttempt;
binTriShrinkedClause += other.binTriShrinkedClause;
cacheShrinkedClause += other.cacheShrinkedClause;
furtherShrinkedSuccess += other.furtherShrinkedSuccess;
stampShrinkAttempt += other.stampShrinkAttempt;
stampShrinkCl += other.stampShrinkCl;
stampShrinkLit += other.stampShrinkLit;
moreMinimLitsStart += other.moreMinimLitsStart;
moreMinimLitsEnd += other.moreMinimLitsEnd;
recMinimCost += other.recMinimCost;
//Red stats
learntUnits += other.learntUnits;
learntBins += other.learntBins;
learntLongs += other.learntLongs;
otfSubsumed += other.otfSubsumed;
otfSubsumedImplicit += other.otfSubsumedImplicit;
otfSubsumedLong += other.otfSubsumedLong;
otfSubsumedRed += other.otfSubsumedRed;
otfSubsumedLitsGained += other.otfSubsumedLitsGained;
guess_different += other.guess_different;
cache_hit += other.cache_hit;
red_cl_in_which0 += other.red_cl_in_which0;
//Hyper-bin & transitive reduction
advancedPropCalled += other.advancedPropCalled;
hyperBinAdded += other.hyperBinAdded;
transReduRemIrred += other.transReduRemIrred;
transReduRemRed += other.transReduRemRed;
//Stat structs
resolvs += other.resolvs;
conflStats += other.conflStats;
//Time
cpu_time += other.cpu_time;
return *this;
}
SearchStats& SearchStats::operator-=(const SearchStats& other)
{
numRestarts -= other.numRestarts;
blocked_restart -= other.blocked_restart;
blocked_restart_same -= other.blocked_restart_same;
//Decisions
decisions -= other.decisions;
decisionsAssump -= other.decisionsAssump;
decisionsRand -= other.decisionsRand;
decisionFlippedPolar -= other.decisionFlippedPolar;
//Conflict minimisation stats
litsRedNonMin -= other.litsRedNonMin;
litsRedFinal -= other.litsRedFinal;
recMinCl -= other.recMinCl;
recMinLitRem -= other.recMinLitRem;
permDiff_attempt -= other.permDiff_attempt;
permDiff_rem_lits -= other.permDiff_rem_lits;
permDiff_success -= other.permDiff_success;
furtherShrinkAttempt -= other.furtherShrinkAttempt;
binTriShrinkedClause -= other.binTriShrinkedClause;
cacheShrinkedClause -= other.cacheShrinkedClause;
furtherShrinkedSuccess -= other.furtherShrinkedSuccess;
stampShrinkAttempt -= other.stampShrinkAttempt;
stampShrinkCl -= other.stampShrinkCl;
stampShrinkLit -= other.stampShrinkLit;
moreMinimLitsStart -= other.moreMinimLitsStart;
moreMinimLitsEnd -= other.moreMinimLitsEnd;
recMinimCost -= other.recMinimCost;
//Red stats
learntUnits -= other.learntUnits;
learntBins -= other.learntBins;
learntLongs -= other.learntLongs;
otfSubsumed -= other.otfSubsumed;
otfSubsumedImplicit -= other.otfSubsumedImplicit;
otfSubsumedLong -= other.otfSubsumedLong;
otfSubsumedRed -= other.otfSubsumedRed;
otfSubsumedLitsGained -= other.otfSubsumedLitsGained;
guess_different -= other.guess_different;
cache_hit -= other.cache_hit;
red_cl_in_which0 -= other.red_cl_in_which0;
//Hyper-bin & transitive reduction
advancedPropCalled -= other.advancedPropCalled;
hyperBinAdded -= other.hyperBinAdded;
transReduRemIrred -= other.transReduRemIrred;
transReduRemRed -= other.transReduRemRed;
//Stat structs
resolvs -= other.resolvs;
conflStats -= other.conflStats;
//Time
cpu_time -= other.cpu_time;
return *this;
}
SearchStats SearchStats::operator-(const SearchStats& other) const
{
SearchStats result = *this;
result -= other;
return result;
}
void SearchStats::printCommon(uint64_t props) const
{
print_stats_line("c restarts"
, numRestarts
, float_div(conflStats.numConflicts, numRestarts)
, "confls per restart"
);
print_stats_line("c blocked restarts"
, blocked_restart
, float_div(blocked_restart, numRestarts)
, "per normal restart"
);
print_stats_line("c time", cpu_time);
print_stats_line("c decisions", decisions
, stats_line_percent(decisionsRand, decisions)
, "% random"
);
print_stats_line("c propagations", props);
print_stats_line("c decisions/conflicts"
, float_div(decisions, conflStats.numConflicts)
);
}
void SearchStats::print_short(uint64_t props) const
{
//Restarts stats
printCommon(props);
conflStats.print_short(cpu_time);
print_stats_line("c conf lits non-minim"
, litsRedNonMin
, float_div(litsRedNonMin, conflStats.numConflicts)
, "lit/confl"
);
print_stats_line("c conf lits final"
, float_div(litsRedFinal, conflStats.numConflicts)
);
print_stats_line("c guess different"
, guess_different
, stats_line_percent(guess_different, conflStats.numConflicts)
, "% of confl"
);
print_stats_line("c cache hit re-learnt cl"
, cache_hit
, stats_line_percent(cache_hit, conflStats.numConflicts)
, "% of confl"
);
print_stats_line("c red which0"
, red_cl_in_which0
, stats_line_percent(red_cl_in_which0, conflStats.numConflicts)
, "% of confl"
);
}
void SearchStats::print(uint64_t props) const
{
printCommon(props);
conflStats.print(cpu_time);
/*assert(numConflicts
== conflsBin + conflsTri + conflsLongIrred + conflsLongRed);*/
cout << "c LEARNT stats" << endl;
print_stats_line("c units learnt"
, learntUnits
, stats_line_percent(learntUnits, conflStats.numConflicts)
, "% of conflicts");
print_stats_line("c bins learnt"
, learntBins
, stats_line_percent(learntBins, conflStats.numConflicts)
, "% of conflicts");
print_stats_line("c long learnt"
, learntLongs
, stats_line_percent(learntLongs, conflStats.numConflicts)
, "% of conflicts"
);
print_stats_line("c otf-subs"
, otfSubsumed
, ratio_for_stat(otfSubsumed, conflStats.numConflicts)
, "/conflict"
);
print_stats_line("c otf-subs implicit"
, otfSubsumedImplicit
, stats_line_percent(otfSubsumedImplicit, otfSubsumed)
, "%"
);
print_stats_line("c otf-subs long"
, otfSubsumedLong
, stats_line_percent(otfSubsumedLong, otfSubsumed)
, "%"
);
print_stats_line("c otf-subs learnt"
, otfSubsumedRed
, stats_line_percent(otfSubsumedRed, otfSubsumed)
, "% otf subsumptions"
);
print_stats_line("c otf-subs lits gained"
, otfSubsumedLitsGained
, ratio_for_stat(otfSubsumedLitsGained, otfSubsumed)
, "lits/otf subsume"
);
print_stats_line("c guess different"
, guess_different
, stats_line_percent(guess_different, conflStats.numConflicts)
, "% of confl"
);
print_stats_line("c cache hit re-learnt cl"
, cache_hit
, stats_line_percent(cache_hit, conflStats.numConflicts)
, "% of confl"
);
print_stats_line("c red which0"
, red_cl_in_which0
, stats_line_percent(red_cl_in_which0, conflStats.numConflicts)
, "% of confl"
);
cout << "c SEAMLESS HYPERBIN&TRANS-RED stats" << endl;
print_stats_line("c advProp called"
, advancedPropCalled
);
print_stats_line("c hyper-bin add bin"
, hyperBinAdded
, ratio_for_stat(hyperBinAdded, advancedPropCalled)
, "bin/call"
);
print_stats_line("c trans-red rem irred bin"
, transReduRemIrred
, ratio_for_stat(transReduRemIrred, advancedPropCalled)
, "bin/call"
);
print_stats_line("c trans-red rem red bin"
, transReduRemRed
, ratio_for_stat(transReduRemRed, advancedPropCalled)
, "bin/call"
);
cout << "c CONFL LITS stats" << endl;
print_stats_line("c orig "
, litsRedNonMin
, ratio_for_stat(litsRedNonMin, conflStats.numConflicts)
, "lit/confl"
);
print_stats_line("c recurs-min effective"
, recMinCl
, stats_line_percent(recMinCl, conflStats.numConflicts)
, "% attempt successful"
);
print_stats_line("c recurs-min lits"
, recMinLitRem
, stats_line_percent(recMinLitRem, litsRedNonMin)
, "% less overall"
);
print_stats_line("c permDiff call%"
, stats_line_percent(permDiff_attempt, conflStats.numConflicts)
, stats_line_percent(permDiff_success, permDiff_attempt)
, "% attempt successful"
);
print_stats_line("c permDiff lits-rem"
, permDiff_rem_lits
, ratio_for_stat(permDiff_rem_lits, permDiff_attempt)
, "less lits/cl on attempts"
);
print_stats_line("c further-min call%"
, stats_line_percent(furtherShrinkAttempt, conflStats.numConflicts)
, stats_line_percent(furtherShrinkedSuccess, furtherShrinkAttempt)
, "% attempt successful"
);
print_stats_line("c bintri-min lits"
, binTriShrinkedClause
, stats_line_percent(binTriShrinkedClause, litsRedNonMin)
, "% less overall"
);
print_stats_line("c cache-min lits"
, cacheShrinkedClause
, stats_line_percent(cacheShrinkedClause, litsRedNonMin)
, "% less overall"
);
print_stats_line("c stamp-min call%"
, stats_line_percent(stampShrinkAttempt, conflStats.numConflicts)
, stats_line_percent(stampShrinkCl, stampShrinkAttempt)
, "% attempt successful"
);
print_stats_line("c stamp-min lits"
, stampShrinkLit
, stats_line_percent(stampShrinkLit, litsRedNonMin)
, "% less overall"
);
print_stats_line("c final avg"
, ratio_for_stat(litsRedFinal, conflStats.numConflicts)
);
//General stats
//print_stats_line("c Memory used", (double)mem_used / 1048576.0, " MB");
#if !defined(_MSC_VER) && defined(RUSAGE_THREAD)
print_stats_line("c single-thread CPU time", cpu_time, " s");
#else
print_stats_line("c all-threads sum CPU time", cpu_time, " s");
#endif
}
| [
"u1219556@lnissrv4.eng.utah.edu"
] | u1219556@lnissrv4.eng.utah.edu |
0a03d7e69838ee7c96d55abc0e12532684402e61 | f0dbabac157fc79094062513cfcc28be253d9b70 | /modules/types/include/Tanker/Types/TankerSecretProvisionalIdentity.hpp | c7d90eecaa9198e1ba6c7b7d067eb4b8d3a6ced6 | [
"Apache-2.0"
] | permissive | TankerHQ/sdk-native | 4c3a81d83a9e144c432ca74c3e327225e6814e91 | c062edc4b6ad26ce90e0aebcc2359adde4ca65db | refs/heads/master | 2023-08-19T02:59:40.445973 | 2023-08-09T12:04:46 | 2023-08-09T12:04:46 | 160,206,027 | 20 | 4 | null | null | null | null | UTF-8 | C++ | false | false | 265 | hpp | #pragma once
#include <Tanker/Crypto/EncryptionKeyPair.hpp>
#include <Tanker/Crypto/SignatureKeyPair.hpp>
namespace Tanker
{
struct TankerSecretProvisionalIdentity
{
Crypto::EncryptionKeyPair encryptionKeyPair;
Crypto::SignatureKeyPair signatureKeyPair;
};
}
| [
"alexandre.bossard@tanker.io"
] | alexandre.bossard@tanker.io |
0565e34f5037257917532642ca570db09b5ec01e | e755f58efd833ee1133b427ea21cbd052e9907ed | /src/include/migraphx/op/elu.hpp | bbf73d8a70a1500a595ff2aa5589e7f6a82fbeff | [
"MIT"
] | permissive | f0rmiga/AMDMIGraphX | 87d33acbd77341098f0040039c342129d829e3ce | e66968a25f9342a28af1157b06cbdbf8579c5519 | refs/heads/master | 2022-12-16T18:55:26.749316 | 2020-07-10T22:16:55 | 2020-07-10T22:16:55 | 290,550,990 | 0 | 0 | NOASSERTION | 2020-08-26T16:39:36 | 2020-08-26T16:39:35 | null | UTF-8 | C++ | false | false | 900 | hpp | #ifndef MIGRAPHX_GUARD_OPERATORS_ELU_HPP
#define MIGRAPHX_GUARD_OPERATORS_ELU_HPP
#include <array>
#include <migraphx/operation.hpp>
#include <migraphx/check_shapes.hpp>
#include <migraphx/stringutils.hpp>
#include <migraphx/streamutils.hpp>
#include <migraphx/literal.hpp>
#include <migraphx/shape_for_each.hpp>
#include <migraphx/config.hpp>
#include <cmath>
#include <utility>
namespace migraphx {
inline namespace MIGRAPHX_INLINE_NS {
namespace op {
struct elu
{
std::string name() const { return "elu"; }
float alpha;
shape compute_shape(std::vector<shape> inputs) const
{
check_shapes{inputs, *this}.has(1);
return inputs.front();
}
template <class Self, class F>
static auto reflect(Self& self, F f)
{
return pack(f(self.alpha, "alpha"));
}
};
} // namespace op
} // namespace MIGRAPHX_INLINE_NS
} // namespace migraphx
#endif
| [
"Shucai.Xiao@amd.com"
] | Shucai.Xiao@amd.com |
db20e44d081fd8045703ba4dfb6dad7c506e887d | 9b25f9cf63e0bee6654ebdbc8b067a2d3c393a25 | /App/ios/Pods/Flipper-Folly/folly/experimental/coro/BlockingWait.h | f621faeb2c92b8d4bdeb19ff2a41528faf6e8e49 | [
"MIT",
"Apache-2.0"
] | permissive | camhinton/How_Much_Workout_App | 89092a629f59269b683d564d9f330b24ff613704 | 785defb76e57253d968a0173248b3706feccc78a | refs/heads/main | 2023-07-18T04:28:23.925481 | 2021-08-30T17:40:25 | 2021-08-30T17:40:25 | 401,179,472 | 0 | 0 | MIT | 2021-08-30T17:34:09 | 2021-08-30T01:15:40 | JavaScript | UTF-8 | C++ | false | false | 12,859 | h | /*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma once
#include <folly/Try.h>
#include <folly/executors/ManualExecutor.h>
#include <folly/experimental/coro/Coroutine.h>
#include <folly/experimental/coro/Task.h>
#include <folly/experimental/coro/Traits.h>
#include <folly/experimental/coro/ViaIfAsync.h>
#include <folly/experimental/coro/WithAsyncStack.h>
#include <folly/experimental/coro/detail/Malloc.h>
#include <folly/experimental/coro/detail/Traits.h>
#include <folly/fibers/Baton.h>
#include <folly/synchronization/Baton.h>
#include <folly/tracing/AsyncStack.h>
#include <cassert>
#include <exception>
#include <type_traits>
#include <utility>
#if FOLLY_HAS_COROUTINES
namespace folly {
namespace coro {
namespace detail {
template <typename T>
class BlockingWaitTask;
class BlockingWaitPromiseBase {
struct FinalAwaiter {
bool await_ready() noexcept { return false; }
template <typename Promise>
void await_suspend(coroutine_handle<Promise> coro) noexcept {
BlockingWaitPromiseBase& promise = coro.promise();
folly::deactivateAsyncStackFrame(promise.getAsyncFrame());
promise.baton_.post();
}
void await_resume() noexcept {}
};
public:
BlockingWaitPromiseBase() noexcept = default;
static void* operator new(std::size_t size) {
return ::folly_coro_async_malloc(size);
}
static void operator delete(void* ptr, std::size_t size) {
::folly_coro_async_free(ptr, size);
}
suspend_always initial_suspend() { return {}; }
FinalAwaiter final_suspend() noexcept { return {}; }
template <typename Awaitable>
decltype(auto) await_transform(Awaitable&& awaitable) {
return folly::coro::co_withAsyncStack(static_cast<Awaitable&&>(awaitable));
}
bool done() const noexcept { return baton_.ready(); }
void wait() noexcept { baton_.wait(); }
folly::AsyncStackFrame& getAsyncFrame() noexcept { return asyncFrame_; }
private:
folly::fibers::Baton baton_;
folly::AsyncStackFrame asyncFrame_;
};
template <typename T>
class BlockingWaitPromise final : public BlockingWaitPromiseBase {
public:
BlockingWaitPromise() noexcept = default;
~BlockingWaitPromise() = default;
BlockingWaitTask<T> get_return_object() noexcept;
void unhandled_exception() noexcept {
result_->emplaceException(
folly::exception_wrapper::from_exception_ptr(std::current_exception()));
}
template <
typename U = T,
std::enable_if_t<std::is_convertible<U, T>::value, int> = 0>
void return_value(U&& value) noexcept(
std::is_nothrow_constructible<T, U&&>::value) {
result_->emplace(static_cast<U&&>(value));
}
void setTry(folly::Try<T>* result) noexcept { result_ = &result; }
private:
folly::Try<T>* result_;
};
template <typename T>
class BlockingWaitPromise<T&> final : public BlockingWaitPromiseBase {
public:
BlockingWaitPromise() noexcept = default;
~BlockingWaitPromise() = default;
BlockingWaitTask<T&> get_return_object() noexcept;
void unhandled_exception() noexcept {
result_->emplaceException(
folly::exception_wrapper::from_exception_ptr(std::current_exception()));
}
auto yield_value(T&& value) noexcept {
result_->emplace(std::ref(value));
return final_suspend();
}
auto yield_value(T& value) noexcept {
result_->emplace(std::ref(value));
return final_suspend();
}
#if 0
void return_value(T& value) noexcept {
result_->emplace(std::ref(value));
}
#endif
void return_void() {
// This should never be reachable.
// The coroutine should either have suspended at co_yield or should have
// thrown an exception and skipped over the implicit co_return and
// gone straight to unhandled_exception().
std::abort();
}
void setTry(folly::Try<std::reference_wrapper<T>>* result) noexcept {
result_ = result;
}
private:
folly::Try<std::reference_wrapper<T>>* result_;
};
template <>
class BlockingWaitPromise<void> final : public BlockingWaitPromiseBase {
public:
BlockingWaitPromise() = default;
BlockingWaitTask<void> get_return_object() noexcept;
void return_void() noexcept {}
void unhandled_exception() noexcept {
result_->emplaceException(
exception_wrapper::from_exception_ptr(std::current_exception()));
}
void setTry(folly::Try<void>* result) noexcept { result_ = result; }
private:
folly::Try<void>* result_;
};
template <typename T>
class BlockingWaitTask {
public:
using promise_type = BlockingWaitPromise<T>;
using handle_t = coroutine_handle<promise_type>;
explicit BlockingWaitTask(handle_t coro) noexcept : coro_(coro) {}
BlockingWaitTask(BlockingWaitTask&& other) noexcept
: coro_(std::exchange(other.coro_, {})) {}
BlockingWaitTask& operator=(BlockingWaitTask&& other) noexcept = delete;
~BlockingWaitTask() {
if (coro_) {
coro_.destroy();
}
}
FOLLY_NOINLINE T get(folly::AsyncStackFrame& parentFrame) && {
folly::Try<detail::lift_lvalue_reference_t<T>> result;
auto& promise = coro_.promise();
promise.setTry(&result);
auto& asyncFrame = promise.getAsyncFrame();
asyncFrame.setParentFrame(parentFrame);
asyncFrame.setReturnAddress();
{
RequestContextScopeGuard guard{RequestContext::saveContext()};
folly::resumeCoroutineWithNewAsyncStackRoot(coro_);
}
promise.wait();
return std::move(result).value();
}
FOLLY_NOINLINE T getVia(
folly::DrivableExecutor* executor,
folly::AsyncStackFrame& parentFrame) && {
folly::Try<detail::lift_lvalue_reference_t<T>> result;
auto& promise = coro_.promise();
promise.setTry(&result);
auto& asyncFrame = promise.getAsyncFrame();
asyncFrame.setReturnAddress();
asyncFrame.setParentFrame(parentFrame);
executor->add(
[coro = coro_, rctx = RequestContext::saveContext()]() mutable {
RequestContextScopeGuard guard{std::move(rctx)};
folly::resumeCoroutineWithNewAsyncStackRoot(coro);
});
while (!promise.done()) {
executor->drive();
}
return std::move(result).value();
}
private:
handle_t coro_;
};
template <typename T>
inline BlockingWaitTask<T>
BlockingWaitPromise<T>::get_return_object() noexcept {
return BlockingWaitTask<T>{
coroutine_handle<BlockingWaitPromise<T>>::from_promise(*this)};
}
template <typename T>
inline BlockingWaitTask<T&>
BlockingWaitPromise<T&>::get_return_object() noexcept {
return BlockingWaitTask<T&>{
coroutine_handle<BlockingWaitPromise<T&>>::from_promise(*this)};
}
inline BlockingWaitTask<void>
BlockingWaitPromise<void>::get_return_object() noexcept {
return BlockingWaitTask<void>{
coroutine_handle<BlockingWaitPromise<void>>::from_promise(*this)};
}
template <
typename Awaitable,
typename Result = await_result_t<Awaitable>,
std::enable_if_t<!std::is_lvalue_reference<Result>::value, int> = 0>
auto makeBlockingWaitTask(Awaitable&& awaitable)
-> BlockingWaitTask<detail::decay_rvalue_reference_t<Result>> {
co_return co_await static_cast<Awaitable&&>(awaitable);
}
template <
typename Awaitable,
typename Result = await_result_t<Awaitable>,
std::enable_if_t<std::is_lvalue_reference<Result>::value, int> = 0>
auto makeBlockingWaitTask(Awaitable&& awaitable)
-> BlockingWaitTask<detail::decay_rvalue_reference_t<Result>> {
co_yield co_await static_cast<Awaitable&&>(awaitable);
}
template <
typename Awaitable,
typename Result = await_result_t<Awaitable>,
std::enable_if_t<std::is_void<Result>::value, int> = 0>
BlockingWaitTask<void> makeRefBlockingWaitTask(Awaitable&& awaitable) {
co_await static_cast<Awaitable&&>(awaitable);
}
template <
typename Awaitable,
typename Result = await_result_t<Awaitable>,
std::enable_if_t<!std::is_void<Result>::value, int> = 0>
auto makeRefBlockingWaitTask(Awaitable&& awaitable)
-> BlockingWaitTask<std::add_lvalue_reference_t<Result>> {
co_yield co_await static_cast<Awaitable&&>(awaitable);
}
class BlockingWaitExecutor final : public folly::DrivableExecutor {
public:
~BlockingWaitExecutor() {
while (keepAliveCount_.load() > 0) {
drive();
}
}
void add(Func func) override {
bool empty;
{
auto wQueue = queue_.wlock();
empty = wQueue->empty();
wQueue->push_back(std::move(func));
}
if (empty) {
baton_.post();
}
}
void drive() override {
baton_.wait();
baton_.reset();
folly::fibers::runInMainContext([&]() {
std::vector<Func> funcs;
queue_.swap(funcs);
for (auto& func : funcs) {
std::exchange(func, nullptr)();
}
});
}
private:
bool keepAliveAcquire() noexcept override {
auto keepAliveCount =
keepAliveCount_.fetch_add(1, std::memory_order_relaxed);
DCHECK(keepAliveCount >= 0);
return true;
}
void keepAliveRelease() noexcept override {
auto keepAliveCount = keepAliveCount_.load(std::memory_order_relaxed);
do {
DCHECK(keepAliveCount > 0);
if (keepAliveCount == 1) {
add([this] {
// the final count *must* be released from this executor or else if we
// are mid-destructor we have a data race
keepAliveCount_.fetch_sub(1, std::memory_order_relaxed);
});
return;
}
} while (!keepAliveCount_.compare_exchange_weak(
keepAliveCount,
keepAliveCount - 1,
std::memory_order_release,
std::memory_order_relaxed));
}
folly::Synchronized<std::vector<Func>> queue_;
fibers::Baton baton_;
std::atomic<ssize_t> keepAliveCount_{0};
};
} // namespace detail
/// blocking_wait_fn
///
/// Awaits co_awaits the passed awaitable and blocks the current thread until
/// the await operation completes.
///
/// Useful for launching an asynchronous operation from the top-level main()
/// function or from unit-tests.
///
/// WARNING:
/// Avoid using this function within any code that might run on the thread
/// of an executor as this can potentially lead to deadlock if the operation
/// you are waiting on needs to do some work on that executor in order to
/// complete.
struct blocking_wait_fn {
template <typename Awaitable>
FOLLY_NOINLINE auto operator()(Awaitable&& awaitable) const
-> detail::decay_rvalue_reference_t<await_result_t<Awaitable>> {
folly::AsyncStackFrame frame;
frame.setReturnAddress();
folly::AsyncStackRoot stackRoot;
stackRoot.setNextRoot(folly::tryGetCurrentAsyncStackRoot());
stackRoot.setStackFrameContext();
stackRoot.setTopFrame(frame);
return static_cast<std::add_rvalue_reference_t<await_result_t<Awaitable>>>(
detail::makeRefBlockingWaitTask(static_cast<Awaitable&&>(awaitable))
.get(frame));
}
template <typename SemiAwaitable>
FOLLY_NOINLINE auto operator()(
SemiAwaitable&& awaitable, folly::DrivableExecutor* executor) const
-> detail::decay_rvalue_reference_t<semi_await_result_t<SemiAwaitable>> {
folly::AsyncStackFrame frame;
frame.setReturnAddress();
folly::AsyncStackRoot stackRoot;
stackRoot.setNextRoot(folly::tryGetCurrentAsyncStackRoot());
stackRoot.setStackFrameContext();
stackRoot.setTopFrame(frame);
return static_cast<
std::add_rvalue_reference_t<semi_await_result_t<SemiAwaitable>>>(
detail::makeRefBlockingWaitTask(
folly::coro::co_viaIfAsync(
folly::getKeepAliveToken(executor),
static_cast<SemiAwaitable&&>(awaitable)))
.getVia(executor, frame));
}
template <
typename SemiAwaitable,
std::enable_if_t<!is_awaitable_v<SemiAwaitable>, int> = 0>
auto operator()(SemiAwaitable&& awaitable) const
-> detail::decay_rvalue_reference_t<semi_await_result_t<SemiAwaitable>> {
std::exception_ptr eptr;
{
detail::BlockingWaitExecutor executor;
try {
return operator()(static_cast<SemiAwaitable&&>(awaitable), &executor);
} catch (...) {
eptr = std::current_exception();
}
}
std::rethrow_exception(eptr);
}
};
inline constexpr blocking_wait_fn blocking_wait{};
static constexpr blocking_wait_fn const& blockingWait =
blocking_wait; // backcompat
} // namespace coro
} // namespace folly
#endif // FOLLY_HAS_COROUTINES
| [
"minchanhan5@gmail.com"
] | minchanhan5@gmail.com |
e556587cbec6791a4dc8e5c1f0549d5b4fea1742 | bc2e7366c81ed4b996d3571c90d9470af47e4dc8 | /Problems/Problem4/src/main/Book.cpp | 6e798bfb3889b10ac125fe793661fb4a749ff00b | [] | no_license | arprabhu/CPP_Exercises | 046577ea73be9abfa17f66d5dd72800e5a5ab95b | 496541c3d0da7cc5294ad72cd29be339c1f69c05 | refs/heads/master | 2020-03-08T16:11:05.657844 | 2018-04-05T16:19:30 | 2018-04-05T16:19:30 | 128,232,901 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 145 | cpp | #include <Book.h>
Book::Book(const std::string& title ):title(title){
}
std::string Book::read(){
return std::string("Read book: " + title);
} | [
"38109924+arprabhu@users.noreply.github.com"
] | 38109924+arprabhu@users.noreply.github.com |
762ee83bd6c0f5853fbac5043ddeea83cfc9b89e | 493ac26ce835200f4844e78d8319156eae5b21f4 | /flow_simulation/ideal_flow/processor0/0.84/phi | 3ec670db9b82b335986b35d94a254dffcbcd89dc | [] | no_license | mohan-padmanabha/worm_project | 46f65090b06a2659a49b77cbde3844410c978954 | 7a39f9384034e381d5f71191122457a740de3ff0 | refs/heads/master | 2022-12-14T14:41:21.237400 | 2020-08-21T13:33:10 | 2020-08-21T13:33:10 | 289,277,792 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 36,108 | /*--------------------------------*- C++ -*----------------------------------*\
| ========= | |
| \\ / F ield | OpenFOAM: The Open Source CFD Toolbox |
| \\ / O peration | Version: v1912 |
| \\ / A nd | Website: www.openfoam.com |
| \\/ M anipulation | |
\*---------------------------------------------------------------------------*/
FoamFile
{
version 2.0;
format ascii;
class surfaceScalarField;
location "0.84";
object phi;
}
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
dimensions [0 3 -1 0 0 0 0];
oriented oriented;
internalField nonuniform List<scalar>
2708
(
1.47346e-05
-3.77602e-05
-3.47387e-06
2.64995e-05
-4.06131e-05
5.12189e-05
-0.00015991
0.000149304
0.00123751
0.000236172
-0.000913241
-0.000560445
-0.000326483
0.000184405
6.20447e-05
8.00338e-05
1.68696e-05
-5.33892e-06
-8.7447e-05
7.59164e-05
0.00046119
0.000353598
-0.000241238
-0.00057355
6.60065e-05
9.49117e-05
0.00060218
-0.000825671
0.00100601
-0.000782524
0.000193873
0.00031752
-0.000412831
-9.85624e-05
0.000158359
0.000257789
-0.000293086
-0.000123063
0.000255759
1.51994e-05
-2.29987e-05
-0.00024796
-5.04247e-05
0.000137895
-8.74706e-05
1.78192e-05
-3.18073e-05
-1.46289e-05
2.86171e-05
0.000850937
-0.000865457
4.14853e-05
-2.69654e-05
0.000137121
-0.000142196
6.1439e-05
-5.63634e-05
-4.85271e-07
-0.000325496
0.000325981
-0.000221132
0.000199077
0.000159176
-8.84572e-05
0.00024647
-0.000188855
3.08425e-05
-2.02751e-06
-2.08208e-05
2.28484e-05
0.000255132
4.0687e-05
-4.00601e-05
-7.69527e-05
-3.98165e-05
1.01857e-05
0.000106584
-0.000109515
-0.000159748
-4.03827e-05
7.42033e-05
0.000271907
-0.000305728
0.000821461
5.87115e-05
-2.92361e-05
0.000377336
7.71508e-05
-0.000406611
-4.7876e-05
0.000231897
-5.66054e-05
7.98405e-05
-0.000414671
0.000345383
-0.00015607
0.000225358
3.46346e-05
-1.94607e-05
-0.000880631
-0.001038
8.37648e-05
0.000958546
-4.30956e-06
-0.000222422
0.000139278
9.80594e-05
-1.49151e-05
-0.00043578
0.000976524
-0.000560009
1.92648e-05
0.000929776
0.000449679
-0.00061419
-0.000765265
0.000210795
0.00019633
-0.000407125
0.000118442
-0.00014573
2.7288e-05
0.000103338
-0.00014442
4.1082e-05
-0.000877022
0.000873935
0.000675001
-0.000671914
0.000147305
-3.02188e-05
-0.000183316
6.623e-05
-0.0011861
0.00114283
-5.22344e-05
9.54973e-05
5.99816e-05
-6.44571e-05
-0.000125672
-0.00140047
-3.51271e-05
0.000249499
-0.000358403
-0.000256935
4.23464e-05
0.000572992
0.000116616
-1.51398e-05
-0.000101476
-3.69865e-05
5.13711e-05
-0.000133331
0.000118947
-4.83981e-05
7.38424e-05
-0.000132167
0.000106723
0.00014172
-5.08336e-05
-0.000222017
0.000131131
7.44134e-05
0.000140445
-0.000100398
-0.000114461
5.36301e-05
0.000677619
-0.000375344
-0.000355905
-1.74501e-05
2.78831e-05
-0.000956102
0.000945669
-0.000655997
0.00116346
-0.000871037
0.000363577
3.00391e-05
-0.00108239
0.00110884
-5.64833e-05
0.000217864
-5.15461e-06
-0.000223854
1.1145e-05
-0.000429519
0.000271011
0.000316867
-0.000562092
0.000325439
0.000430527
-4.61221e-05
5.15679e-05
-5.39325e-05
4.84867e-05
-3.37648e-05
4.86092e-05
-8.24591e-05
6.76146e-05
-0.000970242
0.00011457
0.000953063
-9.73918e-05
-7.56019e-05
-8.61801e-05
0.000464849
-0.000303068
-0.000142136
-7.05781e-05
0.000625133
-0.000412419
-0.000568379
0.000531045
-4.59849e-05
9.76452e-05
-0.000128613
0.000331271
-0.00027702
-6.20355e-07
0.000118713
7.69112e-05
-7.55434e-05
-0.000120081
0.000460266
-0.000744843
-0.000592445
-0.000426775
0.000472266
0.00101195
-0.00105744
0.000847792
-0.000171105
-4.76096e-05
-0.000629077
-1.87217e-06
5.78964e-06
-0.000255817
0.0002519
0.000222113
-2.36429e-05
2.49744e-05
7.59142e-05
-4.69174e-05
-5.39712e-05
-0.000624492
0.0010295
-0.000734645
0.000329637
8.14552e-05
5.49403e-05
8.37808e-05
-1.244e-05
-7.94322e-05
8.0914e-06
-0.000106879
-3.68759e-06
-2.07276e-06
0.00011264
6.48971e-05
0.000145898
1.99854e-05
8.76359e-05
-0.000104407
-3.21453e-06
2.14822e-05
0.000644772
-0.000430082
0.000967444
6.29144e-05
-0.00101536
-1.50029e-05
0.000136961
-0.000265281
-6.88767e-05
0.000197197
-0.000953689
0.000926096
-0.000399182
1.36872e-05
0.000228099
-7.93863e-06
-0.000233847
-3.55603e-05
4.19344e-05
-3.42167e-05
2.78426e-05
4.8365e-05
-0.000138516
0.000187415
-9.72642e-05
-0.000277877
-6.456e-05
0.000202544
0.000139893
9.02897e-05
-0.000107345
3.65694e-05
-1.95142e-05
0.000138447
-2.00718e-06
-0.000153141
1.67011e-05
-6.68528e-05
-3.97929e-05
6.03127e-05
4.63329e-05
0.000781426
7.79435e-05
-3.79079e-05
-0.000118636
0.000139598
-0.000189204
0.000168243
0.000124519
0.000119369
-0.000112605
-0.000131283
-0.000204285
0.000182716
-4.52836e-05
0.00012292
-3.63742e-07
1.58906e-05
0.00113004
-1.74757e-05
3.02649e-05
-1.33821e-06
5.40944e-06
-0.000184581
0.00018051
-6.93097e-05
0.000124129
-0.000100804
-1.22428e-05
-9.46305e-05
-5.98723e-09
-6.6026e-05
-0.00100312
0.00103127
3.78744e-05
-0.000137717
-2.56172e-05
0.000139082
2.42528e-05
-0.000806242
-0.000285536
6.9447e-05
2.32267e-05
-6.76993e-05
3.01826e-05
-0.001087
0.00108712
-3.03018e-05
-6.25477e-05
1.80736e-05
0.000128256
-8.37816e-05
-0.000138249
7.99219e-06
-1.78843e-05
0.000148141
0.000205545
2.05139e-05
8.14998e-06
-0.000234209
4.46422e-05
-8.10236e-05
-4.56673e-05
8.20486e-05
0.00104003
-0.00146422
0.000184091
0.000240101
0.000475586
8.96064e-06
1.26046e-05
-0.000497151
8.82609e-05
8.77381e-05
-0.000957383
2.191e-05
5.98103e-05
-8.66602e-05
4.9399e-06
-6.15359e-06
0.00017066
-0.000216891
5.23843e-05
6.44355e-06
-0.000175087
0.000166771
0.000845112
-0.000579183
4.91712e-05
-0.0003151
-0.000223239
0.000141775
0.000200178
8.47656e-07
-1.52815e-06
0.000206226
1.2269e-05
-6.38915e-06
-0.000144129
-0.000148764
-5.76273e-05
0.000117934
3.47537e-05
-3.50224e-06
-4.49991e-05
1.37477e-05
0.000727278
9.92835e-05
-4.51357e-05
0.000171643
0.000166407
-0.00113878
0.00114082
9.59165e-05
-9.79535e-05
-0.000304017
-0.000400211
-0.000216007
-0.000289114
0.000772606
0.000179097
-0.000823267
-0.000128435
-0.0009932
-0.000637389
0.00105505
0.00057554
2.28591e-05
-3.0272e-05
-1.90375e-05
2.64504e-05
0.000117336
-4.4332e-05
0.000654274
-6.6373e-05
1.34013e-05
4.92841e-05
-2.3016e-05
4.76769e-05
-6.92601e-05
4.45991e-05
0.000822504
-0.00104102
0.000356532
-0.000138016
-9.33129e-05
6.31876e-05
1.95299e-05
1.05954e-05
-0.000351436
2.00863e-05
-0.000102464
-0.000755686
0.00085815
-9.31568e-05
-0.000194871
0.000225481
6.20624e-06
-1.47813e-05
0.000131495
-6.13898e-06
5.01436e-05
-0.00024829
8.85212e-05
-1.54329e-06
-3.19707e-06
-1.59633e-05
9.97323e-07
0.000174434
-0.000159468
-0.00010656
0.000131295
-1.28178e-06
-2.34529e-05
-0.000332863
-7.95064e-05
6.09334e-05
-0.000337799
4.4554e-05
0.000313039
-1.97942e-05
-0.000106587
9.14759e-06
0.000103646
0.000899133
-2.32708e-05
-0.000766298
-0.000109564
-0.00010386
0.00111226
0.000155062
-0.00110946
9.22406e-05
0.000860026
-0.00102786
-0.000262866
0.000430697
-0.000227115
-0.000988277
0.00118973
2.56572e-05
0.00015501
-1.22875e-05
-2.41249e-05
9.33661e-06
0.000103309
-0.000917849
0.000881754
-0.000275552
0.000311648
0.0012705
7.66069e-05
-0.00031579
-0.00103132
-4.97198e-05
0.000906619
-9.10744e-06
-8.83924e-05
0.000130716
-8.42161e-06
-3.39021e-05
-1.22561e-06
-3.43347e-05
6.7825e-05
9.08622e-06
-3.75749e-05
-4.10409e-05
-0.000930172
-0.00037805
0.000354532
-0.000269751
-9.69875e-05
0.000273581
0.000909223
0.000115338
-0.000179449
-0.000189075
0.000900543
-0.000885569
0.000174102
0.000249383
-2.49806e-05
2.20669e-05
-0.000159513
0.000176075
-3.45398e-05
-2.79145e-05
8.05279e-05
-1.72818e-05
7.08357e-05
-5.27063e-05
-2.59645e-05
0.000146772
-6.99333e-05
-2.19221e-05
8.57018e-05
-9.60129e-05
4.86132e-05
2.14428e-05
1.647e-06
-6.20536e-06
-0.000103568
6.88596e-05
-0.000160163
-0.000948024
0.000183233
0.000882127
-2.37973e-06
0.000216317
-0.000214423
0.000369621
-0.000583752
-0.00055437
0.000768501
1.41542e-05
0.000238265
-0.000876911
-3.3865e-05
0.000918565
1.44328e-05
8.52715e-05
4.12359e-05
-0.000126507
-2.51981e-05
1.90591e-05
0.00108402
-0.00126059
-0.000153598
0.000330175
0.000150472
6.92725e-05
-8.04666e-05
-0.000820429
-0.000351588
0.000853953
0.000318063
-8.41462e-05
0.00104642
-0.000949675
-1.26003e-05
-2.02707e-05
0.00014136
-2.71901e-05
-9.38988e-05
0.00012728
-0.000981384
0.000947272
-9.31674e-05
0.000176236
-0.000151282
-0.000248193
-0.000333613
0.000247638
0.000946002
-0.000924829
0.000913568
-0.000177814
0.000627723
-0.000604726
2.42683e-06
0.000555829
-0.000508112
-6.35351e-05
0.000176796
-0.0003329
-0.000909168
0.000311895
-3.65076e-05
-0.000157711
0.000224324
-3.01051e-05
-0.000339662
0.000350534
-9.47382e-05
8.38666e-05
0.000104298
0.00101744
-0.000892798
-0.000158504
0.000278286
-2.96794e-05
1.17397e-05
-0.000260346
-0.000153809
0.000166032
0.0011286
8.18425e-06
2.31457e-05
0.0010087
0.000127599
0.000935351
-0.00100269
-6.02652e-05
-3.72878e-05
-3.82556e-05
-2.79512e-05
2.94945e-05
-0.000210135
0.000280671
-7.05369e-05
-0.000200302
-0.000917716
0.000200168
-0.000326958
-7.50099e-05
4.35648e-05
-0.000198074
-0.00024871
4.08232e-05
-4.65463e-05
4.08783e-05
0.00102321
-8.68363e-05
-0.000977255
-1.65968e-05
0.000136463
-0.000123722
3.8552e-06
-7.52924e-05
0.00105684
-0.000650762
-0.000265307
0.000675091
-1.24875e-05
-0.000889718
0.000133064
0.000833905
-0.000194364
0.000977339
0.000149031
-0.000159369
-0.000967001
0.000174701
-3.33415e-05
-0.00022754
0.000179636
-5.19742e-05
-0.00019824
0.00020504
0.00089899
-0.000194807
0.000176802
4.32226e-05
-0.000256532
-8.12993e-05
0.00010089
5.46789e-06
-2.5059e-05
0.000369029
-9.18786e-05
0.000583821
-0.000860972
0.000353169
-0.000100841
0.000514915
0.00122785
-0.00055447
-0.000358771
0.000810525
-0.000883957
-1.84461e-05
-0.00102097
-0.000832583
0.000592958
0.000836704
-0.000903942
-0.000231544
-0.0010113
4.9539e-05
0.00100324
0.000881625
0.000105257
-1.66245e-05
-8.89958e-05
-0.000164786
0.000184987
0.000162515
0.00101257
0.000201018
-0.000531696
0.000962138
-0.00125611
-0.000416745
-0.000922963
0.000808012
-0.000616214
0.00087456
-8.19627e-05
-0.000991689
8.5374e-05
2.76304e-05
6.00614e-05
-7.29573e-05
-0.00093754
0.000664196
-5.95552e-05
-4.05918e-05
2.68041e-05
-2.46942e-05
3.8482e-05
-0.00110912
-3.60039e-05
0.00106984
-0.000188723
0.00017155
-0.000262568
-8.02808e-05
0.00013314
0.000209709
-0.000508275
0.000628879
-2.2441e-05
1.56874e-05
-3.08212e-05
-1.62938e-05
1.71831e-05
-2.33303e-05
0.000756957
0.000173544
0.000159976
-0.00100362
0.000154881
-0.000973958
-8.72059e-05
0.00117359
-0.00011243
0.000142583
-8.76306e-05
0.00014846
-0.000128407
0.00079202
0.000489867
-0.00115429
0.000197275
-0.000264499
-0.000964088
0.000987678
-2.35901e-05
9.58344e-05
-9.94908e-05
3.65637e-06
1.2863e-05
-3.76414e-06
-4.96907e-05
-0.00104851
-2.41671e-05
0.00107267
-0.00100524
0.00101654
-1.13044e-05
-0.000934049
-1.57564e-05
-0.000478542
0.000179826
-3.90822e-05
0.000244489
-0.000873191
-0.00102457
4.79104e-05
-0.000989278
0.00108519
0.000908977
-0.000232083
-0.000933644
-0.000118184
0.000942755
0.000109073
-0.000204097
2.55781e-05
0.000295579
-0.000117061
0.00100048
2.38313e-05
0.000445133
-0.000980259
5.5371e-05
-4.90705e-05
8.825e-05
-0.00101897
-3.4406e-05
-0.000899643
0.00102852
-0.00067111
-3.90429e-05
0.000143716
2.35829e-05
0.000144618
-7.18801e-05
-0.000123162
2.52653e-05
-2.77832e-05
-0.000154452
0.00015697
-0.000411563
-9.75298e-05
-7.66252e-05
-0.000640223
1.2956e-05
-1.26348e-05
2.64828e-05
1.90651e-05
-2.74991e-05
-7.28654e-05
-4.83465e-05
0.000234784
-0.000967836
-0.000411966
-0.000844191
0.000531936
0.000724221
-0.00101288
-0.0010513
-9.2658e-05
5.52922e-05
0.00108866
0.000551604
3.19651e-05
0.00115869
-1.35175e-05
-0.00117714
-0.000686135
-0.00054626
-1.36383e-05
-0.000139383
0.000243968
-9.09466e-05
0.000976888
-0.00103941
-0.000383597
0.000203631
0.00121938
-2.56521e-05
9.26499e-05
3.73004e-05
0.000192951
-0.00106827
0.0010026
1.68985e-05
8.60061e-05
-9.00415e-05
-0.000235292
0.000203676
-0.00134687
-2.25999e-05
-4.68247e-05
4.85842e-05
-2.98518e-06
0.000305453
0.00102155
-6.52497e-05
-0.00126175
0.000171015
3.83196e-05
0.00010343
-0.000124851
0.000378502
-0.000260995
-1.75585e-05
-1.60147e-05
2.21258e-05
-3.55586e-06
0.000864278
-2.0469e-05
-6.08027e-05
8.52281e-05
-3.95643e-06
5.25803e-05
-0.000143277
-3.9586e-05
-3.08957e-05
-0.000139769
0.000149859
2.82298e-05
-4.4645e-05
-0.000330883
-3.60346e-05
4.9605e-05
-5.85719e-05
3.02044e-05
-2.12375e-05
0.000304461
-0.000982935
7.37792e-05
8.2864e-05
7.08675e-05
0.000118569
-6.68737e-05
7.92745e-05
8.05657e-05
3.3759e-05
-0.000367671
0.000378466
6.31211e-05
-6.23401e-05
1.2175e-05
-4.10044e-05
3.11562e-05
5.82266e-05
-4.83785e-05
6.09886e-05
6.69688e-05
0.000405113
0.000923303
-0.000402321
-4.00983e-05
-7.02818e-05
5.94003e-05
5.09798e-05
0.00107959
4.68569e-05
-2.88267e-05
-3.43401e-05
1.63099e-05
9.02382e-06
5.31348e-05
-5.49707e-05
-7.18797e-06
1.27732e-06
-3.81777e-06
-1.00943e-05
-0.000129306
0.000171156
-0.000199561
-4.50652e-05
-0.000140106
0.00010489
-0.000167644
-1.12843e-05
0.000180575
-3.962e-05
6.06198e-05
-3.79177e-06
-0.000169007
-2.93897e-05
1.48173e-06
-1.41635e-05
4.20715e-05
0.00117793
-0.000891788
4.86541e-05
-6.10334e-05
0.000134143
0.000103831
-0.000248962
-0.000547878
0.000693009
-5.54583e-05
4.93963e-05
6.06192e-06
0.00010525
-0.00091628
-7.29277e-05
2.47269e-06
-1.09339e-05
8.46125e-06
1.51574e-05
-3.66183e-05
2.14609e-05
4.89831e-05
-6.00541e-05
1.10711e-05
-9.5697e-05
3.52472e-05
6.04498e-05
1.93173e-05
-6.49916e-06
-1.28182e-05
-4.61751e-05
-1.51661e-05
6.13411e-05
0.000107369
-0.000106195
-1.17447e-06
-2.98589e-05
4.43338e-05
-1.44749e-05
-0.000112134
1.64371e-05
3.25127e-05
-1.31953e-05
-5.36457e-05
-1.81258e-06
-9.67405e-05
0.000101222
-4.48124e-06
5.23038e-05
-5.09423e-05
-1.36148e-06
9.20426e-05
-8.33769e-06
-2.15212e-05
0.000106031
5.20289e-05
-5.89838e-05
6.95492e-06
-2.27019e-05
3.78593e-05
-1.10269e-05
1.34995e-05
-0.000102658
3.16711e-06
-2.50229e-05
4.30288e-05
-1.80059e-05
1.13599e-05
-5.76824e-05
2.45097e-05
2.18129e-05
1.29505e-05
8.22714e-05
-6.4695e-05
-0.000121697
0.000145779
-2.71811e-05
7.8979e-05
8.31595e-05
-0.000110523
0.00023958
-0.000142695
-9.18782e-05
2.03225e-05
0.000172446
4.02049e-05
-3.82473e-05
-3.07843e-05
1.72373e-05
-0.000329785
-0.000637128
-0.000338914
0.000387843
0.00106218
-0.000113508
1.67677e-05
1.39565e-05
-1.29544e-05
-1.00212e-06
2.42203e-05
2.62811e-05
-1.36624e-05
-3.33606e-05
3.37291e-06
6.1672e-05
-1.86432e-05
-9.31183e-06
-4.97279e-06
1.54106e-05
-1.44058e-05
3.47182e-06
-0.000334132
-0.000613766
0.00036142
0.000586478
0.00103928
-0.000267087
7.5666e-05
1.57966e-05
-5.40066e-05
4.96578e-05
-1.14478e-05
-3.01998e-05
3.68492e-05
0.000915091
-0.000924514
9.27077e-05
-8.32845e-05
2.07824e-05
1.59668e-05
-3.14621e-05
-5.28705e-06
4.85047e-05
3.79906e-06
-7.00691e-05
-1.52703e-05
5.09994e-05
7.03836e-06
-0.000172388
1.13611e-05
-7.54378e-05
1.83011e-05
4.57757e-05
0.00109073
-0.000294287
5.37814e-05
2.35821e-05
-2.77584e-05
0.000424062
-0.0010829
0.000964295
-7.1112e-06
-2.05519e-05
3.80343e-05
1.51211e-05
0.000156944
-0.000370142
0.000728113
-8.64103e-05
9.39329e-05
-8.23299e-05
0.000692254
0.000671239
-0.000489557
8.20452e-05
-7.92524e-05
0.00065765
-0.000361821
-0.000295829
-7.96987e-05
7.85168e-05
4.59197e-05
-4.47378e-05
-0.000398489
-0.00012845
0.000322842
-4.77096e-05
-4.52411e-05
3.22493e-05
6.07014e-05
1.53877e-05
9.3975e-06
-4.84832e-06
-2.67801e-05
4.91567e-05
-1.73194e-05
-5.05723e-06
-6.10196e-05
6.20645e-05
-3.67837e-05
3.57388e-05
6.32911e-05
-4.85518e-05
-0.000171617
0.000156878
-7.01331e-06
-1.75591e-05
-2.20766e-06
-5.6006e-05
4.83364e-05
-7.20291e-05
-0.000140771
-3.01195e-05
0.000234181
-5.17714e-05
0.000118539
-7.91629e-05
1.23953e-05
7.84856e-05
-8.96175e-05
-0.000112346
0.000108019
9.39442e-05
-0.000134223
-0.000102406
-5.10579e-07
5.43649e-05
-6.73452e-05
0.000121108
5.40578e-05
-4.21199e-05
-0.000133045
2.53488e-05
1.05315e-05
-0.000122311
-1.34194e-05
5.90969e-05
7.66338e-05
-2.92682e-05
3.68417e-05
4.15833e-05
-0.000166683
-4.02084e-05
0.00015512
-0.00012224
-0.000121356
7.19789e-05
3.24817e-05
0.000374081
-0.000340322
9.77187e-05
-0.000143294
0.000167018
-0.000109508
-1.06789e-05
4.52057e-06
6.1583e-06
6.23625e-05
1.9164e-05
-7.11394e-05
-1.03871e-05
-7.84351e-07
2.91554e-05
3.39915e-05
-8.8427e-05
-2.46579e-05
2.41376e-05
6.86677e-05
-9.28053e-05
-8.18702e-05
0.00013589
3.79045e-08
-0.000112763
-1.12269e-05
-2.71492e-05
-4.05288e-05
6.6584e-06
-6.869e-05
8.16893e-06
5.97367e-05
1.8815e-05
-2.92778e-05
7.25273e-05
-1.06552e-05
2.84542e-05
-3.51185e-05
-3.53549e-05
5.88615e-05
-4.69163e-06
4.09433e-05
-2.87593e-05
-3.93332e-05
2.82885e-05
-3.40943e-05
-3.4723e-05
-2.36895e-05
2.33511e-05
3.22021e-05
0.000271785
-0.000277402
0.000247726
-0.000242109
2.58304e-05
3.18975e-05
-5.77278e-05
-2.25877e-05
-9.3877e-06
-2.23728e-05
-0.000230825
0.000212815
1.9682e-05
5.74505e-05
8.85915e-05
-9.4593e-05
2.56835e-05
-4.7216e-05
-0.00044534
-0.000109469
0.000220678
-4.64549e-05
-5.14553e-05
7.55374e-05
1.18901e-06
3.96929e-05
0.000518438
-0.000271524
0.000276737
-0.00027799
-3.46296e-06
4.71539e-06
-4.32266e-05
1.76262e-05
0.000872799
-0.000215149
7.46e-05
-2.52789e-05
-9.5776e-05
3.01176e-05
-7.41697e-05
-0.000803209
0.00070788
0.000682492
-0.000814462
0.000579082
-0.000489417
0.000260869
-4.76204e-06
2.77844e-06
1.9836e-06
-2.24305e-05
0.000272848
1.47191e-05
-1.08296e-05
-0.000144408
0.00101721
-0.00110546
-0.00114028
9.55673e-05
-0.000106631
-8.69501e-05
-0.000167164
1.09391e-05
2.81429e-05
3.47395e-05
-2.17619e-05
-4.11206e-05
-4.90282e-05
4.63582e-05
4.23975e-05
-3.97275e-05
-3.5116e-06
2.76492e-05
1.00898e-06
4.96962e-06
2.08608e-05
-5.13365e-05
4.08619e-05
4.27239e-05
-0.000763548
0.00093945
0.000531979
7.74807e-06
1.93022e-05
0.000266134
-1.25884e-05
-0.000446715
7.90296e-05
0.000367686
0.000181872
-7.75552e-05
6.51117e-05
-0.000169429
9.50734e-05
-8.9405e-05
-0.000930182
-4.42288e-05
4.10864e-05
0.000185015
-0.000192264
-1.79117e-07
0.000522466
0.000155993
-0.000678458
-2.67438e-05
0.000136879
8.40342e-06
-4.70592e-06
-0.000162868
7.79566e-05
-0.000174162
5.71104e-05
9.77928e-05
-0.000111288
4.11439e-05
3.73845e-05
-5.86034e-05
-4.77747e-05
3.91339e-05
-5.8686e-05
3.91755e-05
4.03712e-05
0.000383848
-9.76679e-06
2.3275e-05
0.000360573
1.03748e-05
0.000166114
-6.83393e-05
5.46402e-05
4.91747e-05
-7.59632e-05
0.000498025
7.57502e-05
2.4493e-05
-5.94831e-05
-1.15278e-05
8.25077e-05
-0.000125127
-0.000145503
-1.39502e-06
0.000157978
-0.000153026
-9.50186e-06
1.24668e-05
-2.35169e-05
-0.000251226
2.70802e-05
0.000243448
-3.75083e-05
3.66943e-05
6.71588e-05
-4.75562e-05
-4.27057e-05
2.31032e-05
4.85748e-05
-5.72318e-05
-0.000154893
1.97654e-05
0.000188088
4.40412e-05
-0.00112349
-7.61188e-06
-0.000927125
-0.000327012
-0.000173814
5.10632e-05
4.61455e-05
2.85012e-05
3.79493e-05
-3.99784e-06
-8.01241e-05
8.72084e-05
-3.08644e-06
0.000198228
3.09473e-05
-5.67837e-05
7.2577e-06
-0.000252243
0.000325958
0.000430981
-0.000504696
3.59026e-06
-0.000161312
-5.14618e-06
-2.97996e-05
-0.00033946
2.97531e-05
-5.68755e-05
6.46025e-05
2.70126e-05
0.000172418
-0.000961543
-2.3304e-05
0.000993032
5.02921e-06
-3.67753e-05
4.72143e-05
3.04229e-05
3.0966e-05
-4.15036e-05
1.79041e-05
2.35994e-05
0.000985311
-0.00103755
4.28386e-05
-6.81058e-06
1.35243e-05
2.86796e-05
-7.50009e-05
-7.91428e-06
2.64035e-06
1.01632e-05
-4.88924e-06
4.15816e-05
-2.64462e-05
-0.000328798
1.75253e-05
-9.43767e-05
8.50203e-05
0.000143551
-0.000212342
0.000104283
-9.19314e-05
-2.02662e-05
0.000588249
-0.000311356
-2.32109e-05
-1.33564e-05
2.79827e-05
8.5847e-06
-3.29993e-05
5.49933e-05
-9.31333e-05
-0.000859324
6.07594e-05
0.000163391
8.74944e-05
-0.000168614
7.41448e-05
-0.000244717
1.57073e-05
-9.49399e-06
-6.21326e-06
4.80938e-05
1.40996e-05
-4.14111e-05
0.000257621
-0.000346474
-2.94621e-05
2.06804e-05
0.000273506
-4.82711e-05
7.19455e-05
6.16493e-05
-9.67531e-05
-9.54331e-05
-0.000154474
0.000187576
0.00026191
-0.0010026
0.000259246
2.05747e-05
-0.000741313
1.98706e-05
-9.357e-05
7.9278e-05
-2.0694e-05
-9.82537e-05
0.000115905
3.04263e-06
0.00020265
2.65437e-05
-3.37269e-05
-8.88303e-05
0.00110001
1.4551e-05
1.12826e-05
-0.00105406
-3.65383e-05
-8.10072e-05
0.000206396
-1.03096e-05
0.000538414
9.70277e-05
0.000250429
0.00124853
0.0011024
0.000163719
0.000200703
0.00110533
4.13707e-05
-2.33577e-05
1.35498e-05
-4.40998e-05
-0.000121832
-0.000157105
-0.000920774
0.00011682
-4.1054e-05
6.7193e-06
-0.000124435
7.3148e-05
-5.94522e-05
-0.000102526
3.95073e-05
-3.88981e-05
1.62174e-05
0.000187148
0.000149099
-3.52572e-05
-0.000147511
-1.89764e-05
4.8273e-05
1.79177e-05
-9.23789e-05
9.93724e-05
1.36869e-05
0.000835931
-0.00016632
-0.000639744
-2.98678e-05
-0.000750373
0.000693479
0.000318804
1.94935e-05
-6.54495e-05
3.55689e-05
1.7873e-05
-4.23471e-06
5.75621e-05
-8.34875e-07
-0.000242551
0.000328109
0.00015294
-0.000985464
7.8167e-05
0.00064667
-0.000645808
3.49323e-06
0.000400508
-0.000380726
-7.05958e-05
-1.12485e-06
-4.32732e-05
7.18187e-06
2.81337e-05
1.86886e-05
-3.03075e-05
-1.65148e-05
-0.000114992
8.94502e-05
0.000147822
-0.000203899
-0.000132778
-4.81495e-05
4.46774e-06
5.27056e-05
-9.80558e-05
7.7045e-05
0.000840856
3.48929e-06
-1.58408e-06
2.62285e-05
-3.46011e-05
-2.6599e-05
-2.69556e-05
4.20355e-05
2.65034e-05
-0.0010076
0.00104084
-0.000281945
1.62227e-05
-9.45019e-05
-0.000156781
1.76076e-06
0.000302842
0.000104592
-1.9321e-05
-0.00096676
-0.000199344
4.70093e-05
2.80665e-05
3.92195e-05
0.000790088
5.99113e-05
0.00104621
-0.00101183
0.000148811
-0.00015044
-0.000155151
0.000203257
1.04345e-05
0.000235409
1.6459e-05
-2.18804e-05
-0.000229988
-0.000308763
-2.03033e-05
3.2643e-05
7.15379e-06
-0.000179961
9.06878e-05
-8.3906e-07
-8.9179e-08
0.000421275
4.67461e-05
-5.27706e-06
0.000231249
-8.06779e-05
0.00010681
-2.80428e-05
-8.75995e-06
7.57658e-05
5.15631e-05
0.000198943
-0.000161883
0.000996723
-0.00124918
0.000267006
0.000155927
3.78052e-05
0.00072229
5.64622e-05
0.000945832
0.000277498
-9.96482e-05
-0.00112368
-7.60757e-05
-9.72987e-06
2.27612e-05
-3.83747e-05
-8.04527e-05
6.26985e-05
3.76965e-05
-1.99424e-05
-0.000138472
0.000213546
-0.000245433
0.000170359
-0.000198757
0.000184803
0.00133448
9.82773e-05
8.3423e-06
3.50553e-05
0.00132648
7.30058e-05
3.07305e-05
7.62254e-07
0.000124766
-4.6068e-05
-1.07689e-05
-0.00103183
8.04852e-05
-0.000140793
-3.56951e-05
2.48118e-05
3.36446e-05
-0.000976038
-0.00116342
0.000737516
-2.29382e-05
-1.29367e-05
-4.13488e-05
2.38064e-06
1.30783e-05
2.58899e-05
8.13751e-05
1.44694e-05
-5.5973e-05
8.13229e-05
6.69594e-06
-6.62267e-05
-2.92986e-05
-0.000146258
0.000109825
-4.13402e-05
7.77567e-05
-1.04274e-05
-7.23866e-05
2.70713e-06
8.80792e-05
-9.85392e-08
5.74649e-05
4.19209e-05
3.65719e-05
-8.15678e-05
7.49805e-06
-0.000158694
-3.82543e-06
-3.08402e-06
4.44867e-06
3.82601e-05
-5.41735e-05
-4.81034e-06
1.3015e-06
4.1654e-05
0.00086132
0.000132444
4.57217e-06
-0.000814299
1.37904e-06
2.53163e-05
-8.52976e-05
0.00046016
0.000408906
0.000148614
-1.40552e-05
0.00108513
-0.000495436
-2.5886e-05
0.000144655
-0.000135309
8.8713e-05
-5.75567e-05
7.83744e-06
-3.62179e-05
-3.29877e-05
8.7221e-05
2.15236e-05
-6.38382e-07
-0.000727233
0.000677778
4.94549e-05
0.000120302
-0.000123783
-4.12574e-05
-4.95689e-06
0.000276797
6.44603e-06
0.000891672
0.00014375
-0.000789296
6.20632e-05
5.12946e-05
0.00107383
-8.94641e-05
-0.000949939
0.0010161
-0.000332017
0.000565692
4.62984e-05
-0.000279973
-3.55934e-05
1.68084e-05
-1.06046e-05
5.80333e-05
0.000619744
-8.96602e-05
0.000100196
0.000106088
-0.000116623
4.70719e-05
-3.46035e-05
4.58638e-05
-5.83322e-05
-0.000200844
4.3515e-05
0.000157329
8.07583e-05
-5.9255e-05
5.89879e-05
8.34266e-05
8.04165e-05
2.41759e-05
-0.00024588
4.50363e-05
-0.000290212
0.00033631
-0.00038312
-0.000285207
-0.000892285
0.000268431
-2.41635e-05
2.92388e-05
-0.000134871
5.32821e-06
3.73945e-05
-0.000100018
0.000123015
1.3652e-06
0.000157394
-7.61357e-05
0.000392226
0.000537551
0.000184705
-4.57977e-05
-0.000158228
-0.000479685
0.000461572
1.8113e-05
8.27225e-05
-0.000872018
7.61074e-05
-0.000118954
-5.17329e-05
1.16275e-05
-0.000130122
0.000860239
-0.000335348
0.000373256
-0.000402492
-0.000222318
-7.64566e-05
-0.000156647
7.78033e-05
0.000878358
-0.000194832
0.000355758
-0.00096041
0.000657364
0.000632683
-0.00106665
-5.0151e-05
0.000580356
0.000389587
-0.000315384
-0.000635646
0.000579905
0.000523823
-0.00061386
0.000336916
0.000568947
-0.000265944
-0.000522879
2.28835e-05
0.000510935
0.000116248
3.67817e-07
-0.000636899
0.000758666
-0.000501613
2.19276e-05
-0.000136511
1.43376e-05
0.000369717
0.000555396
1.72141e-05
-3.18138e-05
-2.95001e-05
-1.97366e-05
1.68044e-05
-1.35826e-05
-2.86106e-05
-3.87346e-05
0.000448918
1.26539e-05
-0.000129096
6.20225e-06
4.24411e-05
0.000105368
-0.000169504
-3.96171e-05
-1.29459e-05
4.9052e-05
1.70287e-05
2.77689e-05
-1.56245e-05
4.53776e-05
-0.000429457
-0.000269483
8.16377e-05
2.17146e-05
6.84989e-06
-0.000536688
0.000113715
-0.000131497
1.44815e-06
-4.17907e-05
-2.90936e-05
-2.68608e-05
1.16971e-05
0.000111704
2.03146e-05
-0.000918795
0.000142344
-9.9998e-05
9.83392e-05
-0.000169492
0.00101352
-0.000961129
-4.35051e-05
-1.49078e-05
1.6593e-05
-1.3727e-06
0.000232703
0.000369884
-0.00108742
3.06876e-05
-7.21106e-05
7.03202e-05
-1.29776e-05
7.11135e-06
7.23146e-06
0.00092803
0.000135191
2.15151e-05
6.09244e-06
-1.49326e-05
-3.92409e-05
-9.19605e-05
-1.08569e-05
-0.000988305
0.000659414
6.43922e-05
-6.81101e-06
0.000248206
7.98878e-06
1.53562e-05
7.41024e-05
-1.21186e-05
0.00111706
6.98741e-05
-0.00108139
-0.000574301
0.000745584
3.57404e-06
-5.38344e-05
8.06061e-05
-0.000108051
0.000164406
0.000504232
-0.0007285
0.000224268
0.00043703
6.72024e-05
0.000448344
-1.13147e-05
-0.000309781
0.000466725
-0.000679923
-0.000603316
-0.000504754
-9.85617e-05
7.83728e-05
-4.79305e-05
0.000113845
-9.58505e-05
-0.000938301
-0.000121166
-6.81865e-05
-2.91298e-06
-1.16977e-05
1.27994e-05
5.34732e-05
-2.61295e-05
1.45342e-05
3.3392e-05
-1.00669e-05
4.24801e-05
2.20383e-05
-4.02982e-05
6.01834e-05
3.00933e-05
-2.52585e-05
-1.28458e-05
0.000437085
0.000814143
-2.84527e-05
2.87696e-05
1.97352e-05
-0.000154327
0.000180106
-9.78902e-05
-0.000227879
-0.000998318
0.000146546
-2.85931e-05
0.00021521
-0.000476986
-2.77678e-05
0.000272844
-0.000149182
-0.000613219
0.00012988
-5.80287e-05
-3.35624e-05
-4.10208e-05
-0.000163443
-0.000143928
7.50952e-05
6.00725e-05
9.81736e-05
-0.001152
0.00104031
-3.39323e-05
0.000205962
-0.000204731
-7.55541e-05
7.4323e-05
-2.231e-05
6.29846e-05
1.75903e-06
-6.18132e-05
0.00015543
-3.26857e-05
7.97762e-05
-0.0011903
1.85792e-06
0.000682656
-0.000383133
-5.37365e-05
3.33803e-06
-0.00025247
-7.68073e-05
-1.04342e-05
5.81388e-05
2.88148e-05
-1.28512e-05
-0.000116294
0.000111401
-0.000134371
5.80503e-05
-1.79441e-05
1.4825e-07
-0.000612609
-0.000374047
0.000131278
0.000172796
7.56444e-05
-0.000201923
0.000112859
1.70223e-05
3.91842e-05
-4.16723e-05
0.000995817
7.73827e-05
2.55563e-05
6.62392e-05
5.62125e-05
0.000168485
-7.54284e-05
-0.000164937
-0.000802759
0.00112273
-1.748e-05
-2.84908e-05
2.57172e-05
-0.000181274
-4.5144e-06
-8.54332e-06
-4.04704e-06
0.00103977
-4.71007e-05
-8.78732e-06
1.81278e-05
0.000202573
0.000154948
-9.27746e-05
-9.82237e-05
9.51313e-05
-0.00086058
4.14924e-05
0.000639911
8.17733e-05
-8.79448e-05
5.95219e-05
0.00108781
7.0905e-05
9.19969e-05
8.72252e-05
-0.000375885
5.18625e-05
0.000199695
-5.56644e-07
-4.34694e-05
-0.000238276
0.000203293
2.87774e-05
-0.000250207
2.30761e-05
6.59338e-06
6.78571e-05
0.000150359
-8.01504e-06
-0.000173011
0.000160724
-0.00096501
0.00103147
-0.000249251
0.000182787
-1.87474e-05
4.43506e-06
3.15139e-05
-3.35414e-05
0.000175289
-0.000247413
0.000523194
-0.000474706
-0.00017716
-3.36347e-05
1.75282e-05
1.51641e-05
-4.58564e-05
4.88314e-05
-4.98965e-05
-0.00115796
6.04064e-06
-3.74185e-05
-0.00010992
-4.23679e-06
0.000168941
-0.00107119
0.000970017
1.78563e-05
-1.80999e-05
0.000993275
-3.19186e-05
0.000558837
-0.000482319
-7.65188e-05
0.000233909
-4.31456e-05
0.000131443
2.84977e-07
1.50084e-06
-2.91067e-06
-0.000899516
0.000908896
0.000131765
-6.67113e-05
0.000299449
-0.000305129
5.67955e-06
-0.000290944
0.000267946
8.50526e-06
-0.000310133
5.00369e-06
0.000227885
0.00017128
0.000319944
-0.00106624
0.000107745
-1.19779e-05
-8.91983e-06
4.01668e-06
0.000239713
-0.000245133
2.49846e-05
-3.49582e-06
-2.14888e-05
2.31052e-05
0.00010328
7.53293e-05
2.19969e-05
-0.000326997
1.50127e-06
-0.000134855
-0.000616827
0.000449855
-5.08625e-05
1.50436e-05
5.82947e-05
4.94501e-05
-0.000279011
-1.67988e-05
1.14926e-06
0.000638345
-2.42854e-05
2.62921e-05
-4.78707e-05
3.21574e-06
1.12944e-05
-6.72242e-06
-0.00011813
9.20755e-05
-3.33974e-05
2.2825e-05
2.15964e-06
2.12739e-05
3.70209e-05
8.63411e-05
9.80634e-05
-4.87071e-05
4.33682e-05
9.48265e-06
-6.52076e-06
3.09503e-05
-5.18475e-06
-0.000112199
0.000457407
-0.000310931
2.96542e-06
-1.59884e-05
-0.000257222
8.94494e-06
1.388e-05
3.77007e-05
-0.00012857
0.00105346
-1.29497e-05
-0.00101485
-0.00014273
0.000110583
0.000678817
-0.000110143
0.000474616
-0.000217164
-3.11254e-05
0.000103297
3.48906e-07
0.000276572
9.68657e-06
-1.84739e-05
-0.000221671
0.000308012
2.82253e-05
-7.69324e-05
0.00140737
-0.00113732
-0.000129374
-0.000924925
-7.46395e-05
-4.39987e-05
2.35591e-05
0.000109548
6.47484e-06
0.000551332
-0.000722437
-0.000110134
9.57871e-05
4.80862e-06
-5.48994e-05
0.00025043
0.000224956
-8.17061e-05
-0.000887351
-4.13315e-05
-3.36476e-05
-0.000368761
0.000394249
-0.000192684
0.000589127
0.000924883
-0.000265485
-7.73574e-05
3.81033e-05
-7.2669e-05
-7.1435e-05
5.43021e-05
0.000682448
5.6232e-06
6.02097e-05
0.000160406
-1.00471e-05
6.98532e-05
0.000161005
-1.20268e-05
3.90519e-07
-0.000186146
-0.000143425
6.87112e-06
0.000152776
-4.2865e-05
5.69627e-05
-1.6847e-05
0.000222054
2.67263e-05
-1.33477e-06
9.14545e-05
0.00013985
2.91947e-05
0.000904515
-0.000915597
-1.95958e-05
1.83211e-05
3.08146e-05
-2.03218e-05
0.00022548
-0.000232941
5.08307e-06
0.000320898
7.70435e-05
0.000487933
3.65758e-05
-1.12447e-06
-8.59563e-05
9.06039e-05
-6.11541e-05
-0.000239111
0.000428704
3.44173e-05
-9.91903e-06
0.000292198
-0.000273397
-0.000910079
0.00016871
-5.99625e-05
4.88454e-05
0.000152669
2.53614e-05
-7.58462e-05
8.00855e-07
5.24391e-05
-1.09877e-05
-5.65485e-06
-7.05832e-05
-2.52523e-05
1.70745e-05
-1.41559e-05
-1.67403e-05
-0.000112528
2.08689e-05
6.53819e-05
4.43213e-05
-0.000360563
0.000717095
0.000242341
-3.70543e-05
-0.000106253
5.42246e-05
2.65337e-05
0.0011877
-0.00101327
-8.95796e-05
-2.60301e-05
0.000408639
0.000755264
0.000632399
-6.11787e-05
0.000304324
-0.00017018
0.000288703
-0.000857879
0.00089104
-0.000321864
-4.57863e-05
-0.000221394
-1.07657e-05
0.000230087
-0.0010187
-0.000615344
0.000229418
0.000184149
-0.00101477
-8.44601e-05
-0.000328526
-0.000110722
0.000107831
-0.000287708
-0.00099708
8.07629e-05
0.00097838
-0.00103341
0.000119048
6.89402e-05
3.86491e-05
-5.3069e-05
-0.000198842
0.000176482
-6.6386e-06
3.63803e-05
-0.000638274
-0.000304979
0.000938586
-0.000681216
-7.25132e-05
-2.23312e-05
5.78826e-05
0.000119512
0.000991599
0.000513367
-0.000183545
-0.000149887
-0.000327099
-6.2127e-06
-2.87225e-06
9.08494e-06
-4.75366e-06
8.59468e-06
0.000112064
-0.000933567
-7.15254e-06
-0.000479823
0.000425548
3.65039e-05
-0.000527634
-5.54216e-05
4.3303e-05
0.000278231
-0.000347108
-7.27176e-05
1.01791e-05
2.62339e-05
3.35888e-05
2.98035e-05
0.000217384
-0.000273218
-0.000159969
8.12172e-05
-2.38805e-05
-0.000142151
-0.000183532
4.48964e-05
-1.26691e-05
-0.000107702
4.24505e-05
6.24496e-06
-0.000953195
5.86362e-05
-5.46195e-05
0.000356028
-0.000303643
-4.53394e-05
4.24821e-05
-0.000162079
6.93581e-05
-3.11911e-05
5.32285e-05
2.05433e-05
0.000104876
0.000116888
0.00010634
-9.06647e-05
-0.000271835
-0.00127163
2.37702e-05
3.84155e-05
-3.03967e-05
8.67709e-06
-3.23378e-05
0.000232509
-7.35519e-05
0.000209932
0.000102829
-0.00102869
-1.63847e-05
0.00031388
-0.000358018
0.000129107
0.000283551
0.000102059
4.44863e-05
-3.55573e-06
-3.55984e-05
2.55156e-05
-0.000118067
5.64331e-05
0.00109356
0.000468695
4.96796e-05
-4.48709e-05
-3.8908e-05
-0.000155975
0.0001572
-3.04518e-05
-0.000151472
-0.000239464
-4.11484e-05
-0.000109793
0.000207856
-0.000670806
0.000890676
0.00106113
-6.33042e-05
0.000946695
5.22047e-05
-6.36369e-05
-0.000389996
-0.000620941
0.000498579
-0.000254674
-0.000474111
-0.000169663
4.44109e-05
0.000446001
0.000111048
-7.07145e-05
2.4789e-05
8.86652e-06
-0.00123375
-0.000117565
-0.000133813
-0.000215404
0.00027882
-0.000552913
0.000753941
-0.00101964
-3.00975e-05
-1.93011e-05
-5.44955e-05
-5.67467e-05
-0.000147307
0.000965991
-0.000119581
-1.04883e-05
3.31523e-05
-3.10814e-05
0.000143773
-3.59427e-05
4.86597e-05
-2.95564e-06
0.000955173
0.000163112
-0.00115245
0.0006179
-0.000891808
1.50275e-06
-1.84295e-05
4.59002e-05
1.33167e-05
-1.68624e-05
3.21228e-05
-0.000186006
-0.000739415
0.000806384
2.56409e-05
3.9734e-05
-2.72073e-05
-4.75784e-05
-0.00101371
0.00032303
-0.000961888
-0.00018313
-0.00021983
0.000173844
-2.29235e-05
1.32056e-05
-3.02248e-05
-2.00454e-05
-5.19553e-05
0.000640072
0.000352015
9.26949e-05
0.000922711
0.000634571
0.000136566
6.09227e-05
-0.00110798
-0.00024241
-0.00077999
0.0010793
2.26505e-05
-0.000102601
-0.000239202
3.59936e-05
-0.000104941
0.000867064
0.000834255
0.000192008
4.44385e-05
-0.000181872
-0.000182068
4.1448e-06
-0.000318359
0.000342184
9.33302e-05
-5.74625e-05
5.63365e-05
-8.13941e-06
-1.41038e-05
-0.000165544
7.31928e-05
1.12005e-05
-2.74419e-05
1.51901e-05
2.20784e-05
-6.31635e-05
7.89495e-05
-0.000102888
9.86904e-05
3.53199e-05
-8.31318e-05
9.54557e-05
6.18095e-05
0.000107941
1.1641e-05
-9.0719e-05
7.70142e-05
2.34562e-05
-2.73056e-05
5.70505e-05
0.000594657
-2.7481e-05
4.74419e-05
-2.4364e-05
0.000721009
5.59371e-05
-5.02053e-05
0.000260761
0.000104217
4.11212e-05
3.59451e-05
-0.000126642
-1.55931e-05
-0.000169856
-3.10755e-05
-0.000123645
3.08634e-05
3.44786e-05
-0.00115313
0.000813478
-0.000827982
5.7247e-05
2.2863e-05
-2.21571e-06
-1.25397e-05
1.72101e-05
-6.89898e-05
0.000149374
-0.000232875
-1.09188e-05
0.000448808
-3.95095e-05
0.000406121
-0.00047875
0.000875632
5.36498e-05
-8.41795e-05
4.79257e-05
-0.000132873
9.51989e-05
0.000107096
9.46743e-05
)
;
boundaryField
{
frontAndBack
{
type empty;
value nonuniform 0();
}
wallOuter
{
type calculated;
value uniform 0;
}
inlet
{
type calculated;
value nonuniform List<scalar> 9(-0.00111111 -0.00111111 -0.00111111 -0.00111111 -0.00111111 -0.00111111 -0.00111111 -0.00111111 -0.00111111);
}
outlet
{
type calculated;
value nonuniform 0();
}
wallInner
{
type calculated;
value uniform 0;
}
procBoundary0to1
{
type processor;
value nonuniform List<scalar>
29
(
-0.000128631
-3.22873e-05
-6.3112e-05
-8.86097e-05
-0.000101477
-0.000138626
0.000419611
0.000484833
0.0010154
0.000130147
0.000389937
-0.000490516
-0.000242593
-0.000251958
0.000781384
0.00110496
-2.78424e-05
0.000234191
1.0006e-05
2.09328e-05
0.0011893
0.00104715
0.000785605
0.000556408
0.000728234
8.12803e-05
0.000726138
0.000162237
0.000255783
)
;
}
procBoundary0to2
{
type processor;
value nonuniform List<scalar>
42
(
0.000127938
0.000141324
-0.000108539
-0.000173379
-8.78735e-05
0.000237736
-9.1434e-05
-7.22477e-05
-4.62693e-05
-2.55516e-06
-8.928e-05
-6.73631e-05
-9.29666e-05
-5.41782e-05
-2.77638e-05
0.000424748
-4.53818e-05
1.16484e-05
-2.34617e-05
4.02141e-05
5.73854e-05
3.71457e-05
2.9591e-06
9.80133e-05
6.64417e-05
6.4135e-05
0.000264151
6.3269e-05
0.000170877
7.66372e-05
7.77511e-05
5.39078e-05
3.78424e-05
2.22359e-05
4.1924e-06
5.12473e-05
5.84048e-05
-9.73263e-05
0.000517986
-0.000118809
-3.59043e-05
-3.13357e-05
)
;
}
}
// ************************************************************************* //
| [
"mohan.2611@gmail.com"
] | mohan.2611@gmail.com | |
5fff3d8945c65a16d2d350234039d1c747894d0c | 341fbbaa6d7e9b8cf5beba68bde5c8c1090cf3ef | /按 OJ 分类/HDU/f-HDU-2017 多校训练赛10-1002-Array Challenge/f-HDU-2017 多校训练赛10-1002-Array Challenge/main.cpp | f5dea350f5140ca4d86ecb4ff945c695b5c77a88 | [] | no_license | webturing/ACM-1 | 0ceb79e5439a95315234ae1e8bee93b353305459 | 7fcf14d1ff2ae42b001139d04bde01378fb4f5c4 | refs/heads/master | 2020-03-19T17:33:37.098619 | 2018-06-09T17:07:14 | 2018-06-09T17:07:14 | 136,766,339 | 3 | 0 | null | 2018-06-09T23:59:30 | 2018-06-09T23:59:30 | null | UTF-8 | C++ | false | false | 1,933 | cpp | //
// main.cpp
// f-HDU-2017 多校训练赛10-1002-Array Challenge
//
// Created by ZYJ on 2017/8/29.
// Copyright © 2017年 ZYJ. All rights reserved.
//
#include <iostream>
#include <cstring>
#include <cstdio>
using namespace std;
typedef long long ll;
const int MOD = 1e9 + 7;
const int MAGIC_1 = 31;
const int MAGIC_2 = 197;
const int MAGIC_3 = 1255;
struct matrix
{
ll v[3][3];
matrix()
{
memset(v, 0, sizeof(v));
}
};
ll n;
matrix M, E, ans;
void init()
{
for (int i = 0; i < 3; i++)
{
E.v[i][i] = 1;
}
M.v[0][0] = 4, M.v[0][1] = 17, M.v[0][2] = -12;
M.v[1][0] = 1, M.v[1][1] = 0, M.v[1][2] = 0;
M.v[2][0] = 0, M.v[2][1] = 1, M.v[2][2] = 0;
}
matrix mul(matrix a, matrix b)
{
matrix c;
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
for (int k = 0; k < 3; k++)
{
c.v[i][j] = (c.v[i][j] % MOD + a.v[i][k] * b.v[k][j] % MOD + MOD) % MOD;
}
}
}
return c;
}
matrix pow(matrix p, ll k)
{
matrix tmp = E;
while (k)
{
if (k & 1)
{
tmp = mul(tmp, p);
k--;
}
k >>= 1;
p = mul(p, p);
}
return tmp;
}
int main()
{
init();
int T;
scanf("%d", &T);
while (T--)
{
scanf("%lld", &n);
if (n == 2)
{
printf("%d\n", MAGIC_1);
}
else if (n == 3)
{
printf("%d\n", MAGIC_2);
}
else if (n == 4)
{
printf("%d\n", MAGIC_3);
}
else
{
ans = pow(M, n - 4);
ll res = (ans.v[0][0] * MAGIC_3 % MOD
+ ans.v[0][1] * MAGIC_2 % MOD
+ ans.v[0][2] * MAGIC_1 % MOD + MOD) % MOD;
printf("%lld\n", res);
}
}
return 0;
}
| [
"1179754741@qq.com"
] | 1179754741@qq.com |
e0119de809b298a11cb74a27cbbf8b44957cb950 | 0939698f486c4d8162c677ae3b92694a8711b172 | /client/src/conversationmodel.h | 18f86b5ff4940d21fb026b450425b2337828d438 | [
"WTFPL"
] | permissive | SunRain/mitakuuluu2 | 03edc4d25a99a4bfb82e40b4e250a58797621f86 | b27244e2a880c00665b5faad48cb07af1d2fce89 | refs/heads/master | 2021-01-18T01:47:09.136635 | 2014-09-21T09:34:24 | 2014-09-21T09:34:24 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,795 | h | #ifndef CONVERSATIONMODEL_H
#define CONVERSATIONMODEL_H
#include <QObject>
#include <QHash>
#include <QVariantMap>
#include <QStringList>
#include <QAbstractListModel>
#include <QtSql/QtSql>
#include <QtDBus/QtDBus>
#include <QTimer>
#include <QDebug>
#include "../threadworker/queryexecutor.h"
class TimestampMsgidPair
{
public:
TimestampMsgidPair(int timestamp, const QString &msgId) {
_timestamp = timestamp;
_msgid = msgId;
}
bool operator <(const TimestampMsgidPair &target) const {
bool result = _timestamp > target._timestamp;
return result;
}
TimestampMsgidPair& operator =(const TimestampMsgidPair &from) {
_timestamp = from._timestamp;
_msgid = from._msgid;
return *this;
}
friend QDebug operator<< (QDebug d, const TimestampMsgidPair &data) {
d << "{" << data._timestamp << ":" << data._msgid << ")";
return d;
}
int _timestamp;
QString _msgid;
};
class ConversationModel : public QAbstractListModel
{
Q_OBJECT
Q_PROPERTY(QString jid READ getJid WRITE loadLastConversation FINAL)
Q_PROPERTY(int count READ count NOTIFY countChanged)
Q_PROPERTY(int allCount READ allCount NOTIFY allCountChanged)
public:
ConversationModel(QObject *parent = 0);
~ConversationModel();
void loadLastConversation(QString newjid);
int rowCount(const QModelIndex &parent = QModelIndex()) const;
QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const;
virtual QHash<int, QByteArray> roleNames() const { return _roles; }
QString getJid() { return jid; }
QString jid;
QString table;
public slots:
void setPropertyByMsgId(const QString &msgId, const QString &name, const QVariant &value);
void loadOldConversation(int count = 20);
void deleteMessage(const QString &msgId, const QString &myJid, bool deleteMediaFiles = false);
QVariantMap get(int index);
QVariantMap getModelByIndex(int index);
QVariantMap getModelByMsgId(const QString &msgId);
void copyToClipboard(const QString &msgId);
void forwardMessage(const QStringList &jids, const QString &msgId);
void resendMessage(const QString &jid, const QString& msgId);
void removeConversation(const QString &rjid);
int count();
void requestContactMedia(const QString &sjid);
private:
int getIndexByMsgId(const QString &msgId);
QStringList _keys;
QHash<int, QByteArray> _roles;
QList<TimestampMsgidPair> _sortedTimestampMsgidList;
QHash<QString, QVariantMap> _modelData;
QVariantMap _downloadData;
QSqlDatabase db;
QDBusInterface *iface;
QueryExecutor *dbExecutor;
bool _loadingBusy;
QString uuid;
int _allCount;
int allCount();
void getAllCount();
QString makeTimestampDate(int timestamp);
private slots:
void onLoadingFree();
void onMessageReceived(const QVariantMap &data);
void onMessageStatusUpdated(const QString &mjid, const QString &msgId, int msgstatus);
void onMediaProgress(const QString &mjid, const QString &msgId, int progress);
void onMediaFinished(const QString &mjid, const QString &msgId, const QString &path);
void onMediaFailed(const QString &mjid, const QString &msgId);
void onMediaTitleReceived(const QString &msgid, const QString &title, const QString &mjid);
void onMediaUploadFinished(const QString &mjid, const QString &msgid, const QString &url);
void dbResults(const QVariant &result);
signals:
void lastMessageToBeChanged(const QString &mjid);
void lastMessageChanged(const QString &mjid, bool force);
void mediaListReceived(const QString &pjid, const QVariantList &mediaList);
void countChanged();
void allCountChanged();
};
#endif // CONVERSATIONMODEL_H
| [
"coderusinbox@gmail.com"
] | coderusinbox@gmail.com |
41028d9ffbcdcdfa2d4592d3f865b4fc0576e08c | 460455e7990de7257aa223a58e73069f3ef7ff43 | /src/server/game/Achievements/AchievementMgr.cpp | 4acd3580147712a6262b7a0c7b25caa2f765d158 | [] | no_license | Shkipper/wmane | 2ce69adea1eedf866921c857cbc5bd1bc6d037f0 | 2da37e1e758f17b61efb6aae8fa7343b234f3dcd | refs/heads/master | 2020-04-24T19:51:51.897587 | 2019-02-25T06:14:18 | 2019-02-25T06:14:18 | 172,225,859 | 0 | 0 | null | 2019-02-23T14:49:31 | 2019-02-23T14:49:31 | null | UTF-8 | C++ | false | false | 168,459 | cpp | /*
* Copyright (C) 2008-2013 TrinityCore <http://www.trinitycore.org/>
* Copyright (C) 2005-2009 MaNGOS <http://getmangos.com/>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "Common.h"
#include "DBCEnums.h"
#include "ObjectMgr.h"
#include "GuildMgr.h"
#include "World.h"
#include "WorldPacket.h"
#include "DatabaseEnv.h"
#include "AchievementMgr.h"
#include "Arena.h"
#include "CellImpl.h"
#include "GameEventMgr.h"
#include "GridNotifiersImpl.h"
#include "Guild.h"
#include "Language.h"
#include "Player.h"
#include "SpellMgr.h"
#include "DisableMgr.h"
#include "ScriptMgr.h"
#include "MapManager.h"
#include "Battleground.h"
#include "BattlegroundAB.h"
#include "Map.h"
#include "InstanceScript.h"
#include "Group.h"
#include "Chat.h"
#include "LexicalCast.h"
namespace Trinity
{
class AchievementChatBuilder
{
public:
AchievementChatBuilder(Player const& player, ChatMsg msgtype, int32 textId, uint32 ach_id)
: i_player(player), i_msgtype(msgtype), i_textId(textId), i_achievementId(ach_id) {}
void operator()(WorldPacket& data, LocaleConstant loc_idx)
{
auto const &text = sObjectMgr->GetTrinityString(i_textId, loc_idx);
ChatHandler::FillMessageData(&data, i_player.GetSession(), i_msgtype, LANG_UNIVERSAL, NULL, i_player.GetGUID(), text, NULL, NULL, i_achievementId);
}
private:
Player const& i_player;
ChatMsg i_msgtype;
int32 i_textId;
uint32 i_achievementId;
};
} // namespace Trinity
bool AchievementCriteriaData::IsValid(CriteriaEntry const* criteria)
{
if (dataType >= MAX_ACHIEVEMENT_CRITERIA_DATA_TYPE)
{
TC_LOG_ERROR("sql.sql", "Table `achievement_criteria_data` for criteria (Entry: %u) has wrong data type (%u), ignored.", criteria->ID, dataType);
return false;
}
switch (criteria->type)
{
case ACHIEVEMENT_CRITERIA_TYPE_KILL_CREATURE:
case ACHIEVEMENT_CRITERIA_TYPE_WIN_BG:
case ACHIEVEMENT_CRITERIA_TYPE_FALL_WITHOUT_DYING:
case ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_QUEST: // Only hardcoded list
case ACHIEVEMENT_CRITERIA_TYPE_CAST_SPELL:
case ACHIEVEMENT_CRITERIA_TYPE_WIN_RATED_ARENA:
case ACHIEVEMENT_CRITERIA_TYPE_DO_EMOTE:
case ACHIEVEMENT_CRITERIA_TYPE_SPECIAL_PVP_KILL:
case ACHIEVEMENT_CRITERIA_TYPE_WIN_DUEL:
case ACHIEVEMENT_CRITERIA_TYPE_LOOT_TYPE:
case ACHIEVEMENT_CRITERIA_TYPE_CAST_SPELL2:
case ACHIEVEMENT_CRITERIA_TYPE_BE_SPELL_TARGET:
case ACHIEVEMENT_CRITERIA_TYPE_BE_SPELL_TARGET2:
case ACHIEVEMENT_CRITERIA_TYPE_EQUIP_EPIC_ITEM:
case ACHIEVEMENT_CRITERIA_TYPE_ROLL_NEED_ON_LOOT:
case ACHIEVEMENT_CRITERIA_TYPE_ROLL_GREED_ON_LOOT:
case ACHIEVEMENT_CRITERIA_TYPE_BG_OBJECTIVE_CAPTURE:
case ACHIEVEMENT_CRITERIA_TYPE_HONORABLE_KILL:
case ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_DAILY_QUEST: // Only Children's Week achievements
case ACHIEVEMENT_CRITERIA_TYPE_USE_ITEM: // Only Children's Week achievements
case ACHIEVEMENT_CRITERIA_TYPE_GET_KILLING_BLOWS:
case ACHIEVEMENT_CRITERIA_TYPE_REACH_LEVEL:
break;
default:
if (dataType != ACHIEVEMENT_CRITERIA_DATA_TYPE_SCRIPT)
{
TC_LOG_ERROR("sql.sql", "Table `achievement_criteria_data` has data for non-supported criteria type (Entry: %u Type: %u), ignored.", criteria->ID, criteria->type);
return false;
}
break;
}
switch (dataType)
{
case ACHIEVEMENT_CRITERIA_DATA_TYPE_NONE:
case ACHIEVEMENT_CRITERIA_DATA_TYPE_VALUE:
case ACHIEVEMENT_CRITERIA_DATA_INSTANCE_SCRIPT:
return true;
case ACHIEVEMENT_CRITERIA_DATA_TYPE_T_CREATURE:
if (!creature.id || !sObjectMgr->GetCreatureTemplate(creature.id))
{
TC_LOG_ERROR("sql.sql", "Table `achievement_criteria_data` (Entry: %u Type: %u) for data type ACHIEVEMENT_CRITERIA_DATA_TYPE_CREATURE (%u) has non-existing creature id in value1 (%u), ignored.",
criteria->ID, criteria->type, dataType, creature.id);
return false;
}
return true;
case ACHIEVEMENT_CRITERIA_DATA_TYPE_T_PLAYER_CLASS_RACE:
if (!classRace.class_id && !classRace.race_id)
{
TC_LOG_ERROR("sql.sql", "Table `achievement_criteria_data` (Entry: %u Type: %u) for data type ACHIEVEMENT_CRITERIA_DATA_TYPE_T_PLAYER_CLASS_RACE (%u) must not have 0 in either value field, ignored.",
criteria->ID, criteria->type, dataType);
return false;
}
if (classRace.class_id && ((1 << (classRace.class_id-1)) & CLASSMASK_ALL_PLAYABLE) == 0)
{
TC_LOG_ERROR("sql.sql", "Table `achievement_criteria_data` (Entry: %u Type: %u) for data type ACHIEVEMENT_CRITERIA_DATA_TYPE_T_PLAYER_CLASS_RACE (%u) has non-existing class in value1 (%u), ignored.",
criteria->ID, criteria->type, dataType, classRace.class_id);
return false;
}
if (classRace.race_id && ((1 << (classRace.race_id-1)) & RACEMASK_ALL_PLAYABLE) == 0)
{
TC_LOG_ERROR("sql.sql", "Table `achievement_criteria_data` (Entry: %u Type: %u) for data type ACHIEVEMENT_CRITERIA_DATA_TYPE_T_PLAYER_CLASS_RACE (%u) has non-existing race in value2 (%u), ignored.",
criteria->ID, criteria->type, dataType, classRace.race_id);
return false;
}
return true;
case ACHIEVEMENT_CRITERIA_DATA_TYPE_T_PLAYER_LESS_HEALTH:
if (health.percent < 1 || health.percent > 100)
{
TC_LOG_ERROR("sql.sql", "Table `achievement_criteria_data` (Entry: %u Type: %u) for data type ACHIEVEMENT_CRITERIA_DATA_TYPE_PLAYER_LESS_HEALTH (%u) has wrong percent value in value1 (%u), ignored.",
criteria->ID, criteria->type, dataType, health.percent);
return false;
}
return true;
case ACHIEVEMENT_CRITERIA_DATA_TYPE_S_AURA:
case ACHIEVEMENT_CRITERIA_DATA_TYPE_T_AURA:
{
SpellInfo const* spellEntry = sSpellMgr->GetSpellInfo(aura.spell_id);
if (!spellEntry)
{
TC_LOG_ERROR("sql.sql", "Table `achievement_criteria_data` (Entry: %u Type: %u) for data type %s (%u) has wrong spell id in value1 (%u), ignored.",
criteria->ID, criteria->type, (dataType == ACHIEVEMENT_CRITERIA_DATA_TYPE_S_AURA?"ACHIEVEMENT_CRITERIA_DATA_TYPE_S_AURA":"ACHIEVEMENT_CRITERIA_DATA_TYPE_T_AURA"), dataType, aura.spell_id);
return false;
}
if (aura.effect_idx >= 3)
{
TC_LOG_ERROR("sql.sql", "Table `achievement_criteria_data` (Entry: %u Type: %u) for data type %s (%u) has wrong spell effect index in value2 (%u), ignored.",
criteria->ID, criteria->type, (dataType == ACHIEVEMENT_CRITERIA_DATA_TYPE_S_AURA?"ACHIEVEMENT_CRITERIA_DATA_TYPE_S_AURA":"ACHIEVEMENT_CRITERIA_DATA_TYPE_T_AURA"), dataType, aura.effect_idx);
return false;
}
if (!spellEntry->Effects[aura.effect_idx].ApplyAuraName)
{
TC_LOG_ERROR("sql.sql", "Table `achievement_criteria_data` (Entry: %u Type: %u) for data type %s (%u) has non-aura spell effect (ID: %u Effect: %u), ignores.",
criteria->ID, criteria->type, (dataType == ACHIEVEMENT_CRITERIA_DATA_TYPE_S_AURA?"ACHIEVEMENT_CRITERIA_DATA_TYPE_S_AURA":"ACHIEVEMENT_CRITERIA_DATA_TYPE_T_AURA"), dataType, aura.spell_id, aura.effect_idx);
return false;
}
return true;
}
case ACHIEVEMENT_CRITERIA_DATA_TYPE_T_LEVEL:
if (level.minlevel > STRONG_MAX_LEVEL)
{
TC_LOG_ERROR("sql.sql", "Table `achievement_criteria_data` (Entry: %u Type: %u) for data type ACHIEVEMENT_CRITERIA_DATA_TYPE_T_LEVEL (%u) has wrong minlevel in value1 (%u), ignored.",
criteria->ID, criteria->type, dataType, level.minlevel);
return false;
}
return true;
case ACHIEVEMENT_CRITERIA_DATA_TYPE_T_GENDER:
if (gender.gender > GENDER_NONE)
{
TC_LOG_ERROR("sql.sql", "Table `achievement_criteria_data` (Entry: %u Type: %u) for data type ACHIEVEMENT_CRITERIA_DATA_TYPE_T_GENDER (%u) has wrong gender in value1 (%u), ignored.",
criteria->ID, criteria->type, dataType, gender.gender);
return false;
}
return true;
case ACHIEVEMENT_CRITERIA_DATA_TYPE_SCRIPT:
if (!ScriptId)
{
TC_LOG_ERROR("sql.sql", "Table `achievement_criteria_data` (Entry: %u Type: %u) for data type ACHIEVEMENT_CRITERIA_DATA_TYPE_SCRIPT (%u) does not have ScriptName set, ignored.",
criteria->ID, criteria->type, dataType);
return false;
}
return true;
/*
@Todo:
case ACHIEVEMENT_CRITERIA_DATA_TYPE_MAP_DIFFICULTY:
*/
case ACHIEVEMENT_CRITERIA_DATA_TYPE_MAP_PLAYER_COUNT:
if (map_players.maxcount <= 0)
{
TC_LOG_ERROR("sql.sql", "Table `achievement_criteria_data` (Entry: %u Type: %u) for data type ACHIEVEMENT_CRITERIA_DATA_TYPE_MAP_PLAYER_COUNT (%u) has wrong max players count in value1 (%u), ignored.",
criteria->ID, criteria->type, dataType, map_players.maxcount);
return false;
}
return true;
case ACHIEVEMENT_CRITERIA_DATA_TYPE_T_TEAM:
if (team.team != ALLIANCE && team.team != HORDE)
{
TC_LOG_ERROR("sql.sql", "Table `achievement_criteria_data` (Entry: %u Type: %u) for data type ACHIEVEMENT_CRITERIA_DATA_TYPE_T_TEAM (%u) has unknown team in value1 (%u), ignored.",
criteria->ID, criteria->type, dataType, team.team);
return false;
}
return true;
case ACHIEVEMENT_CRITERIA_DATA_TYPE_S_DRUNK:
if (drunk.state >= MAX_DRUNKEN)
{
TC_LOG_ERROR("sql.sql", "Table `achievement_criteria_data` (Entry: %u Type: %u) for data type ACHIEVEMENT_CRITERIA_DATA_TYPE_S_DRUNK (%u) has unknown drunken state in value1 (%u), ignored.",
criteria->ID, criteria->type, dataType, drunk.state);
return false;
}
return true;
case ACHIEVEMENT_CRITERIA_DATA_TYPE_HOLIDAY:
if (!sHolidaysStore.LookupEntry(holiday.id))
{
TC_LOG_ERROR("sql.sql", "Table `achievement_criteria_data` (Entry: %u Type: %u) for data type ACHIEVEMENT_CRITERIA_DATA_TYPE_HOLIDAY (%u) has unknown holiday in value1 (%u), ignored.",
criteria->ID, criteria->type, dataType, holiday.id);
return false;
}
return true;
case ACHIEVEMENT_CRITERIA_DATA_TYPE_BG_LOSS_TEAM_SCORE:
return true; // Not check correctness node indexes
case ACHIEVEMENT_CRITERIA_DATA_TYPE_S_EQUIPED_ITEM:
if (equipped_item.item_quality >= MAX_ITEM_QUALITY)
{
TC_LOG_ERROR("sql.sql", "Table `achievement_criteria_requirement` (Entry: %u Type: %u) for requirement ACHIEVEMENT_CRITERIA_REQUIRE_S_EQUIPED_ITEM (%u) has unknown quality state in value1 (%u), ignored.",
criteria->ID, criteria->type, dataType, equipped_item.item_quality);
return false;
}
return true;
case ACHIEVEMENT_CRITERIA_DATA_TYPE_S_PLAYER_CLASS_RACE:
if (!classRace.class_id && !classRace.race_id)
{
TC_LOG_ERROR("sql.sql", "Table `achievement_criteria_data` (Entry: %u Type: %u) for data type ACHIEVEMENT_CRITERIA_DATA_TYPE_S_PLAYER_CLASS_RACE (%u) must not have 0 in either value field, ignored.",
criteria->ID, criteria->type, dataType);
return false;
}
if (classRace.class_id && ((1 << (classRace.class_id-1)) & CLASSMASK_ALL_PLAYABLE) == 0)
{
TC_LOG_ERROR("sql.sql", "Table `achievement_criteria_data` (Entry: %u Type: %u) for data type ACHIEVEMENT_CRITERIA_DATA_TYPE_S_PLAYER_CLASS_RACE (%u) has non-existing class in value1 (%u), ignored.",
criteria->ID, criteria->type, dataType, classRace.class_id);
return false;
}
if (classRace.race_id && ((1 << (classRace.race_id-1)) & RACEMASK_ALL_PLAYABLE) == 0)
{
TC_LOG_ERROR("sql.sql", "Table `achievement_criteria_data` (Entry: %u Type: %u) for data type ACHIEVEMENT_CRITERIA_DATA_TYPE_S_PLAYER_CLASS_RACE (%u) has non-existing race in value2 (%u), ignored.",
criteria->ID, criteria->type, dataType, classRace.race_id);
return false;
}
return true;
default:
TC_LOG_ERROR("sql.sql", "Table `achievement_criteria_data` (Entry: %u Type: %u) has data for non-supported data type (%u), ignored.", criteria->ID, criteria->type, dataType);
return false;
}
}
bool AchievementCriteriaData::Meets(uint32 criteria_id, Player const* source, Unit const* target, uint64 miscValue1 /*= 0*/) const
{
switch (dataType)
{
case ACHIEVEMENT_CRITERIA_DATA_TYPE_NONE:
return true;
case ACHIEVEMENT_CRITERIA_DATA_TYPE_T_CREATURE:
if (!target || target->GetTypeId() != TYPEID_UNIT)
return false;
return target->GetEntry() == creature.id;
case ACHIEVEMENT_CRITERIA_DATA_TYPE_T_PLAYER_CLASS_RACE:
if (!target || target->GetTypeId() != TYPEID_PLAYER)
return false;
if (classRace.class_id && classRace.class_id != target->ToPlayer()->getClass())
return false;
if (classRace.race_id && classRace.race_id != target->ToPlayer()->getRace())
return false;
return true;
case ACHIEVEMENT_CRITERIA_DATA_TYPE_S_PLAYER_CLASS_RACE:
if (!source || source->GetTypeId() != TYPEID_PLAYER)
return false;
if (classRace.class_id && classRace.class_id != source->ToPlayer()->getClass())
return false;
if (classRace.race_id && classRace.race_id != source->ToPlayer()->getRace())
return false;
return true;
case ACHIEVEMENT_CRITERIA_DATA_TYPE_T_PLAYER_LESS_HEALTH:
if (!target || target->GetTypeId() != TYPEID_PLAYER)
return false;
return !target->HealthAbovePct(health.percent);
case ACHIEVEMENT_CRITERIA_DATA_TYPE_S_AURA:
return source->HasAuraEffect(aura.spell_id, aura.effect_idx);
case ACHIEVEMENT_CRITERIA_DATA_TYPE_T_AURA:
return target && target->HasAuraEffect(aura.spell_id, aura.effect_idx);
case ACHIEVEMENT_CRITERIA_DATA_TYPE_VALUE:
return miscValue1 >= value.minvalue;
case ACHIEVEMENT_CRITERIA_DATA_TYPE_T_LEVEL:
if (!target)
return false;
return target->getLevel() >= level.minlevel;
case ACHIEVEMENT_CRITERIA_DATA_TYPE_T_GENDER:
if (!target)
return false;
return target->getGender() == gender.gender;
case ACHIEVEMENT_CRITERIA_DATA_TYPE_SCRIPT:
return sScriptMgr->OnCriteriaCheck(ScriptId, criteria_id, miscValue1, const_cast<Player*>(source), const_cast<Unit*>(target));
case ACHIEVEMENT_CRITERIA_DATA_TYPE_MAP_PLAYER_COUNT:
return source->GetMap()->GetPlayersCountExceptGMs() <= map_players.maxcount;
case ACHIEVEMENT_CRITERIA_DATA_TYPE_T_TEAM:
if (!target || target->GetTypeId() != TYPEID_PLAYER)
return false;
return target->ToPlayer()->GetTeam() == team.team;
case ACHIEVEMENT_CRITERIA_DATA_TYPE_S_DRUNK:
return Player::GetDrunkenstateByValue(source->GetDrunkValue()) >= DrunkenState(drunk.state);
case ACHIEVEMENT_CRITERIA_DATA_TYPE_HOLIDAY:
return IsHolidayActive(HolidayIds(holiday.id));
case ACHIEVEMENT_CRITERIA_DATA_TYPE_BG_LOSS_TEAM_SCORE:
{
Battleground* bg = source->GetBattleground();
if (!bg)
return false;
uint16 winnerTeamScore = 0;
switch(bg->GetTypeID(true))
{
case BATTLEGROUND_WS:
winnerTeamScore = 3;
break;
case BATTLEGROUND_AB:
case BATTLEGROUND_EY:
winnerTeamScore = 1600;
break;
default:
break;
}
if (winnerTeamScore > 0 && !bg->IsTeamScoreInRange(source->GetTeam(), winnerTeamScore, winnerTeamScore))
return false;
return bg->IsTeamScoreInRange(source->GetTeam() == ALLIANCE ? HORDE : ALLIANCE, bg_loss_team_score.min_score, bg_loss_team_score.max_score);
}
case ACHIEVEMENT_CRITERIA_DATA_INSTANCE_SCRIPT:
{
if (!source->IsInWorld())
return false;
Map* map = source->GetMap();
if (!map->IsDungeon())
{
TC_LOG_ERROR("achievement", "Achievement system call ACHIEVEMENT_CRITERIA_DATA_INSTANCE_SCRIPT (%u) for achievement criteria %u for non-dungeon/non-raid map %u",
ACHIEVEMENT_CRITERIA_DATA_INSTANCE_SCRIPT, criteria_id, map->GetId());
return false;
}
InstanceScript* instance = ((InstanceMap*)map)->GetInstanceScript();
if (!instance)
{
TC_LOG_ERROR("achievement", "Achievement system call ACHIEVEMENT_CRITERIA_DATA_INSTANCE_SCRIPT (%u) for achievement criteria %u for map %u but map does not have a instance script",
ACHIEVEMENT_CRITERIA_DATA_INSTANCE_SCRIPT, criteria_id, map->GetId());
return false;
}
return instance->CheckAchievementCriteriaMeet(criteria_id, source, target, miscValue1);
}
case ACHIEVEMENT_CRITERIA_DATA_TYPE_S_EQUIPED_ITEM:
{
ItemTemplate const* pProto = sObjectMgr->GetItemTemplate(miscValue1);
if (!pProto)
return false;
return pProto->ItemLevel >= equipped_item.item_level && pProto->Quality >= equipped_item.item_quality;
}
default:
break;
}
return false;
}
bool AchievementCriteriaDataSet::Meets(Player const* source, Unit const* target, uint64 miscvalue /*= 0*/) const
{
for (Storage::const_iterator itr = storage.begin(); itr != storage.end(); ++itr)
if (!itr->Meets(criteria_id, source, target, miscvalue))
return false;
return true;
}
template<class T>
AchievementMgr<T>::AchievementMgr(T* owner): _owner(owner), _achievementPoints(0)
{
}
template<class T>
AchievementMgr<T>::~AchievementMgr()
{
}
template<class T>
void AchievementMgr<T>::SendPacket(WorldPacket* /*data*/) const
{
}
template<>
void AchievementMgr<Guild>::SendPacket(WorldPacket* data) const
{
GetOwner()->BroadcastPacket(data);
}
template<>
void AchievementMgr<Player>::SendPacket(WorldPacket* data) const
{
GetOwner()->GetSession()->SendPacket(data);
}
template<class T>
void AchievementMgr<T>::RemoveCriteriaProgress(const CriteriaEntry* entry)
{
CriteriaProgressMap &progressMap = GetCriteriaProgressMap();
auto const itr = progressMap.find(entry->ID);
if (itr == progressMap.end())
return;
WorldPacket data(SMSG_CRITERIA_DELETED, 4);
data << uint32(entry->ID);
SendPacket(&data);
progressMap.erase(itr);
}
template<>
void AchievementMgr<Guild>::RemoveCriteriaProgress(const CriteriaEntry* entry)
{
CriteriaProgressMap &progressMap = GetCriteriaProgressMap();
auto const itr = progressMap.find(entry->ID);
if (itr == progressMap.end())
return;
ObjectGuid guid = GetOwner()->GetGUID();
WorldPacket data(SMSG_GUILD_CRITERIA_DELETED, 4 + 8);
data.WriteBitSeq<7, 3, 4, 2, 1, 5, 6, 0>(guid);
data.WriteByteSeq<5, 7, 4, 6, 2, 1, 3>(guid);
data << uint32(entry->ID);
data.WriteByteSeq<0>(guid);
SendPacket(&data);
progressMap.erase(itr);
}
template<class T>
void AchievementMgr<T>::ResetAchievementCriteria(AchievementCriteriaTypes type, uint64 miscValue1, uint64 miscValue2, bool evenIfCriteriaComplete)
{
// Disable for gamemasters with GM-mode enabled
if (GetOwner()->isGameMaster())
return;
AchievementCriteriaEntryList const& achievementCriteriaList = sAchievementMgr->GetAchievementCriteriaByType(type);
for (AchievementCriteriaEntryList::const_iterator i = achievementCriteriaList.begin(); i != achievementCriteriaList.end(); ++i)
{
CriteriaEntry const* achievementCriteria = (*i);
// don't update already completed criteria if not forced or achievement already complete
if (!IsCompletedCriteria(achievementCriteria))
RemoveCriteriaProgress(achievementCriteria);
}
}
template<>
void AchievementMgr<Guild>::ResetAchievementCriteria(AchievementCriteriaTypes /*type*/, uint64 /*miscValue1*/, uint64 /*miscValue2*/, bool /*evenIfCriteriaComplete*/)
{
// Not needed
}
template<class T>
void AchievementMgr<T>::DeleteFromDB(uint32 /*lowguid*/, uint32 /*accountId*/)
{
}
template<>
void AchievementMgr<Player>::DeleteFromDB(uint32 lowguid, uint32 /*accountId*/)
{
SQLTransaction trans = CharacterDatabase.BeginTransaction();
PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHAR_ACHIEVEMENT);
stmt->setUInt32(0, lowguid);
trans->Append(stmt);
CharacterDatabase.CommitTransaction(trans);
}
template<>
void AchievementMgr<Guild>::DeleteFromDB(uint32 lowguid, uint32 /*accountId*/)
{
SQLTransaction trans = CharacterDatabase.BeginTransaction();
PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_ALL_GUILD_ACHIEVEMENTS);
stmt->setUInt32(0, lowguid);
trans->Append(stmt);
stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_ALL_GUILD_ACHIEVEMENT_CRITERIA);
stmt->setUInt32(0, lowguid);
trans->Append(stmt);
CharacterDatabase.CommitTransaction(trans);
}
template<class T>
void AchievementMgr<T>::SaveToDB(SQLTransaction& /*charTrans*/, SQLTransaction& /*authTrans*/)
{
}
template<>
void AchievementMgr<Player>::SaveToDB(SQLTransaction& charTrans, SQLTransaction& authTrans)
{
uint32 const guidLow = GetOwner()->GetGUIDLow();
uint32 const accountId = GetOwner()->GetSession()->GetAccountId();
if (!m_completedAchievements.empty())
{
bool needCharacterExecute = false;
bool needAccountExecute = false;
std::ostringstream ssAccDel;
std::ostringstream ssAccIns;
std::ostringstream ssCharDel;
std::ostringstream ssCharIns;
std::ostringstream sscount;
for (auto &kvPair : m_completedAchievements)
{
auto const achievementId = kvPair.first;
auto &completionData = kvPair.second;
if (!completionData.changed)
continue;
AchievementEntry const* ach = sAchievementMgr->GetAchievement(achievementId);
if (!ach)
continue;
bool isAccountAchievement = ach->flags & ACHIEVEMENT_FLAG_ACCOUNT;
bool const mustSaveForCharacter = completionData.completedByThisCharacter;
if (!needAccountExecute)
{
if (isAccountAchievement)
{
// First new/changed record prefix
ssAccDel << "DELETE FROM account_achievement WHERE account = " << accountId << " AND achievement IN (";
ssAccIns << "INSERT INTO account_achievement (account, first_guid, achievement, date) VALUES ";
needAccountExecute = true;
}
}
else
{
if (isAccountAchievement)
{
// Next new/changed record prefix
ssAccDel << ',';
ssAccIns << ',';
}
}
if (!needCharacterExecute)
{
if (mustSaveForCharacter || !isAccountAchievement)
{
ssCharDel << "DELETE FROM character_achievement WHERE guid = " << guidLow << " AND achievement IN (";
ssCharIns << "INSERT INTO character_achievement (guid, achievement, date) VALUES ";
needCharacterExecute = true;
}
}
else
{
if (mustSaveForCharacter || !isAccountAchievement)
{
ssCharDel << ',';
ssCharIns << ',';
}
}
if (isAccountAchievement)
{
// New/changed record data
ssAccDel << achievementId;
ssAccIns << '(' << accountId << ',' << completionData.first_guid << ',' << achievementId << ',' << completionData.date << ')';
}
if (mustSaveForCharacter || !isAccountAchievement)
{
ssCharDel << achievementId;
ssCharIns << '(' << guidLow << ',' << achievementId << "," << completionData.date << ')';
}
/// Mark as saved in db
completionData.changed = false;
}
if (needAccountExecute)
{
ssAccDel << ')';
authTrans->Append(ssAccDel.str().c_str());
authTrans->Append(ssAccIns.str().c_str());
}
if (needCharacterExecute)
{
ssCharDel << ')';
charTrans->Append(ssCharDel.str().c_str());
charTrans->Append(ssCharIns.str().c_str());
}
}
CriteriaProgressMap &progressMap = GetCriteriaProgressMap();
if (progressMap.empty())
return;
// Prepare deleting and insert
bool needExecuteDel = false;
bool needExecuteIns = false;
bool needExecuteAccount = false;
bool isAccountAchievement = false;
bool alreadyOneCharDelLine = false;
bool alreadyOneAccDelLine = false;
bool alreadyOneCharInsLine = false;
bool alreadyOneAccInsLine = false;
std::ostringstream ssAccDel;
std::ostringstream ssAccIns;
std::ostringstream ssCharDel;
std::ostringstream ssCharIns;
for (auto &kvPair : progressMap)
{
auto const criteriaId = kvPair.first;
auto &progressData = kvPair.second;
if (!progressData.changed)
continue;
auto const criteria = sAchievementMgr->GetAchievementCriteria(criteriaId);
if (!criteria)
continue;
AchievementEntry const* achievement;
AchievementCriteriaTreeList const& criteriaTreeList = sAchievementMgr->GetAchievementCriteriaTreeList(criteria);
for (AchievementCriteriaTreeList::const_iterator iter = criteriaTreeList.begin(); iter != criteriaTreeList.end(); iter++)
{
CriteriaTreeEntry const* criteriaTree = *iter;
achievement = sAchievementMgr->GetAchievementEntryByCriteriaTree(criteriaTree);
}
if (!achievement)
continue;
if (achievement->flags & ACHIEVEMENT_FLAG_ACCOUNT)
{
isAccountAchievement = true;
needExecuteAccount = true;
}
else
isAccountAchievement = false;
// Deleted data (including 0 progress state)
if (!needExecuteDel)
{
// First new/changed record prefix (for any counter value)
ssAccDel << "DELETE FROM account_achievement_progress WHERE account = " << accountId << " AND criteria IN (";
ssCharDel << "DELETE FROM character_achievement_progress WHERE guid = " << guidLow << " AND criteria IN (";
needExecuteDel = true;
}
else
{
// Next new/changed record prefix
if (isAccountAchievement)
{
if (alreadyOneAccDelLine)
ssAccDel << ',';
}
else
{
if (alreadyOneCharDelLine)
ssCharDel << ',';
}
}
// New/changed record data
if (isAccountAchievement)
{
ssAccDel << criteriaId;
alreadyOneAccDelLine = true;
}
else
{
ssCharDel << criteriaId;
alreadyOneCharDelLine = true;
}
// Store data only for real progress
if (progressData.counter != 0)
{
if (!needExecuteIns)
{
// First new/changed record prefix
ssAccIns << "INSERT INTO account_achievement_progress (account, criteria, counter, date) VALUES ";
ssCharIns << "INSERT INTO character_achievement_progress (guid, criteria, counter, date) VALUES ";
needExecuteIns = true;
}
else
{
// Next new/changed record prefix
if (isAccountAchievement)
{
if (alreadyOneAccInsLine)
ssAccIns << ',';
}
else
{
if (alreadyOneCharInsLine)
ssCharIns << ',';
}
}
// New/changed record data
if (isAccountAchievement)
{
ssAccIns << '(' << accountId << ',' << criteriaId << ',' << progressData.counter << ',' << progressData.date << ')';
alreadyOneAccInsLine = true;
}
else
{
ssCharIns << '(' << guidLow << ',' << criteriaId << ',' << progressData.counter << ',' << progressData.date << ')';
alreadyOneCharInsLine = true;
}
}
// Mark as updated in db
progressData.changed = false;
}
// DELETE ... IN (.... _)_
if (needExecuteDel)
{
ssAccDel << ')';
ssCharDel << ')';
}
if (needExecuteDel || needExecuteIns)
{
if (needExecuteDel)
{
if (needExecuteAccount && alreadyOneAccDelLine)
authTrans->Append(ssAccDel.str().c_str());
if (alreadyOneCharDelLine)
charTrans->Append(ssCharDel.str().c_str());
}
if (needExecuteIns)
{
if (needExecuteAccount && alreadyOneAccInsLine)
authTrans->Append(ssAccIns.str().c_str());
if (alreadyOneCharInsLine)
charTrans->Append(ssCharIns.str().c_str());
}
}
}
template<>
void AchievementMgr<Guild>::SaveToDB(SQLTransaction& trans, SQLTransaction& /*trans*/)
{
PreparedStatement* stmt;
std::ostringstream guidstr;
for (auto &kvPair : m_completedAchievements)
{
auto const achievementId = kvPair.first;
auto &completionData = kvPair.second;
if (!completionData.changed)
continue;
stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_GUILD_ACHIEVEMENT);
stmt->setUInt32(0, GetOwner()->GetId());
stmt->setUInt16(1, achievementId);
trans->Append(stmt);
stmt = CharacterDatabase.GetPreparedStatement(CHAR_INS_GUILD_ACHIEVEMENT);
stmt->setUInt32(0, GetOwner()->GetId());
stmt->setUInt16(1, achievementId);
stmt->setUInt32(2, completionData.date);
for (auto const &guid : completionData.guids)
guidstr << GUID_LOPART(guid) << ',';
stmt->setString(3, guidstr.str());
trans->Append(stmt);
guidstr.str("");
completionData.changed = false;
}
for (auto &kvPair : GetCriteriaProgressMap())
{
auto const criteriaId = kvPair.first;
auto &progressData = kvPair.second;
if (!progressData.changed)
continue;
stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_GUILD_ACHIEVEMENT_CRITERIA);
stmt->setUInt32(0, GetOwner()->GetId());
stmt->setUInt16(1, criteriaId);
trans->Append(stmt);
stmt = CharacterDatabase.GetPreparedStatement(CHAR_INS_GUILD_ACHIEVEMENT_CRITERIA);
stmt->setUInt32(0, GetOwner()->GetId());
stmt->setUInt16(1, criteriaId);
stmt->setUInt64(2, progressData.counter);
stmt->setUInt32(3, progressData.date);
stmt->setUInt32(4, GUID_LOPART(progressData.CompletedGUID));
trans->Append(stmt);
progressData.changed = false;
}
}
template<class T>
void AchievementMgr<T>::LoadFromDB(PreparedQueryResult /*achievementResult*/, PreparedQueryResult /*criteriaResult*/, PreparedQueryResult /*achievementAccountResult*/, PreparedQueryResult /*criteriaAccountResult*/)
{
}
template<>
void AchievementMgr<Player>::LoadFromDB(PreparedQueryResult achievementResult, PreparedQueryResult criteriaResult, PreparedQueryResult achievementAccountResult, PreparedQueryResult criteriaAccountResult)
{
if (achievementAccountResult)
{
do
{
Field* fields = achievementAccountResult->Fetch();
uint32 first_guid = fields[0].GetUInt32();
uint32 achievementid = fields[1].GetUInt16();
// Must not happen: cleanup at server startup in sAchievementMgr->LoadCompletedAchievements()
AchievementEntry const* achievement = sAchievementMgr->GetAchievement(achievementid);
if (!achievement)
continue;
if (achievement->flags & ACHIEVEMENT_FLAG_GUILD)
continue;
CompletedAchievementData& ca = m_completedAchievements[achievementid];
ca.date = time_t(fields[2].GetUInt32());
ca.changed = false;
ca.first_guid = MAKE_NEW_GUID(first_guid, 0, HIGHGUID_PLAYER);
ca.completedByThisCharacter = false;
_achievementPoints += achievement->points;
// Title achievement rewards are retroactive
if (AchievementReward const* reward = sAchievementMgr->GetAchievementReward(achievement))
if (uint32 titleId = reward->titleId[Player::TeamForRace(GetOwner()->getRace()) == ALLIANCE ? 0 : 1])
if (CharTitlesEntry const* titleEntry = sCharTitlesStore.LookupEntry(titleId))
GetOwner()->SetTitle(titleEntry);
}
while (achievementAccountResult->NextRow());
}
if (criteriaResult)
{
time_t now = time(NULL);
do
{
Field* fields = criteriaResult->Fetch();
uint32 id = fields[0].GetUInt16();
uint64 counter = fields[1].GetUInt64();
time_t date = time_t(fields[2].GetUInt32());
CriteriaEntry const* criteria = sAchievementMgr->GetAchievementCriteria(id);
if (!criteria)
{
// We will remove not existed criteria for all characters
TC_LOG_ERROR("achievement", "Non-existing achievement criteria %u data removed from table `character_achievement_progress`.", id);
PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_INVALID_ACHIEV_PROGRESS_CRITERIA);
stmt->setUInt16(0, uint16(id));
CharacterDatabase.Execute(stmt);
continue;
}
if (criteria->timeLimit && time_t(date + criteria->timeLimit) < now)
continue;
CriteriaProgress& progress = m_criteriaProgress[id];
progress.counter = counter;
progress.date = date;
progress.changed = false;
}
while (criteriaResult->NextRow());
}
if (achievementResult)
{
do
{
Field* fields = achievementResult->Fetch();
uint32 achievementid = fields[0].GetUInt16();
uint32 guid = fields[1].GetUInt32();
// Must not happen: cleanup at server startup in sAchievementMgr->LoadCompletedAchievements()
AchievementEntry const* achievement = sAchievementMgr->GetAchievement(achievementid);
if (!achievement)
continue;
if (achievement->flags & ACHIEVEMENT_FLAG_GUILD)
continue;
// Achievement in character_achievement but not in account_achievement, there is a problem.
if (m_completedAchievements.find(achievementid) == m_completedAchievements.end() && achievement->flags & ACHIEVEMENT_FLAG_ACCOUNT)
{
TC_LOG_ERROR("achievement", "Account-wide achievement '%u' in character_achievement but not in account_achievement, there is a problem.", achievementid);
continue;
}
CompletedAchievementData& ca = m_completedAchievements[achievementid];
ca.completedByThisCharacter = true;
ca.date = time_t(fields[2].GetUInt32());
ca.changed = false;
ca.first_guid = MAKE_NEW_GUID(guid, 0, HIGHGUID_PLAYER);
_achievementPoints += achievement->points;
}
while (achievementResult->NextRow());
}
if (criteriaAccountResult)
{
time_t now = time(NULL);
do
{
Field* fields = criteriaAccountResult->Fetch();
uint32 id = fields[0].GetUInt16();
uint64 counter = fields[1].GetUInt64();
time_t date = time_t(fields[2].GetUInt32());
CriteriaEntry const* criteria = sAchievementMgr->GetAchievementCriteria(id);
if (!criteria)
{
// We will remove not existed criteria for all characters
TC_LOG_ERROR("achievement", "Non-existing achievement criteria %u data removed from table `character_achievement_progress`.", id);
PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_INVALID_ACHIEV_PROGRESS_CRITERIA);
stmt->setUInt16(0, uint16(id));
CharacterDatabase.Execute(stmt);
continue;
}
if (criteria->timeLimit && time_t(date + criteria->timeLimit) < now)
continue;
CriteriaProgressMap &progressMap = GetCriteriaProgressMap();
// Achievement in both account & characters achievement_progress, problem
if (progressMap.find(id) != progressMap.end())
{
TC_LOG_ERROR("achievement", "Achievement '%u' in both account & characters achievement_progress", id);
continue;
}
CriteriaProgress& progress = progressMap[id];
progress.counter = counter;
progress.date = date;
progress.changed = false;
}
while (criteriaAccountResult->NextRow());
}
}
template<>
void AchievementMgr<Guild>::LoadFromDB(PreparedQueryResult achievementResult, PreparedQueryResult criteriaResult, PreparedQueryResult /*achievementAccountResult*/, PreparedQueryResult /*criteriaAccountResult*/)
{
if (achievementResult)
{
do
{
Field* fields = achievementResult->Fetch();
uint32 achievementid = fields[0].GetUInt16();
// Must not happen: cleanup at server startup in sAchievementMgr->LoadCompletedAchievements()
AchievementEntry const* achievement = sAchievementStore.LookupEntry(achievementid);
if (!achievement)
continue;
if (!(achievement->flags & ACHIEVEMENT_FLAG_GUILD))
continue;
CompletedAchievementData& ca = m_completedAchievements[achievementid];
ca.date = time_t(fields[1].GetUInt32());
Tokenizer guids(fields[2].GetString(), ' ');
for (uint32 i = 0; i < guids.size(); ++i)
ca.guids.insert(MAKE_NEW_GUID(Trinity::lexicalCast<uint32>(guids[i]), 0, HIGHGUID_PLAYER));
ca.changed = false;
_achievementPoints += achievement->points;
}
while (achievementResult->NextRow());
}
if (criteriaResult)
{
time_t now = time(NULL);
do
{
Field* fields = criteriaResult->Fetch();
uint32 id = fields[0].GetUInt16();
uint64 counter = fields[1].GetUInt64();
time_t date = time_t(fields[2].GetUInt32());
uint64 guid = MAKE_NEW_GUID(fields[3].GetUInt32(), 0, HIGHGUID_PLAYER);
CriteriaEntry const* criteria = sAchievementMgr->GetAchievementCriteria(id);
if (!criteria)
{
// We will remove not existed criteria for all guilds
TC_LOG_ERROR("achievement", "Non-existing achievement criteria %u data removed from table `guild_achievement_progress`.", id);
PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_INVALID_ACHIEV_PROGRESS_CRITERIA_GUILD);
stmt->setUInt16(0, uint16(id));
CharacterDatabase.Execute(stmt);
continue;
}
if (criteria->timeLimit && time_t(date + criteria->timeLimit) < now)
continue;
CriteriaProgress& progress = m_criteriaProgress[id];
progress.counter = counter;
progress.date = date;
progress.CompletedGUID = MAKE_NEW_GUID(guid, 0, HIGHGUID_PLAYER);
progress.changed = false;
}
while (criteriaResult->NextRow());
}
}
template<class T>
void AchievementMgr<T>::Reset()
{
}
template<>
void AchievementMgr<Player>::Reset()
{
for (auto const &kvPair : m_completedAchievements)
{
WorldPacket data(SMSG_ACHIEVEMENT_DELETED, 4);
data << uint32(kvPair.first);
SendPacket(&data);
}
m_completedAchievements.clear();
for (auto const &kvPair : GetCriteriaProgressMap())
{
WorldPacket data(SMSG_CRITERIA_DELETED, 4);
data << uint32(kvPair.first);
SendPacket(&data);
}
GetCriteriaProgressMap().clear();
_achievementPoints = 0;
DeleteFromDB(GetOwner()->GetGUIDLow());
// re-fill data
GetOwner()->CheckAllAchievementCriteria();
}
template<>
void AchievementMgr<Guild>::Reset()
{
ObjectGuid const guid = GetOwner()->GetGUID();
for (auto const &kvPair : m_completedAchievements)
{
WorldPacket data(SMSG_GUILD_ACHIEVEMENT_DELETED, 4);
data.WriteBitSeq<4, 1, 2, 3, 0, 7, 5, 6>(guid);
data << uint32(kvPair.first);
data.WriteByteSeq<5, 1, 3, 6, 0, 7>(guid);
data << uint32(secsToTimeBitFields(kvPair.second.date));
data.WriteByteSeq<4, 2>(guid);
SendPacket(&data);
}
m_completedAchievements.clear();
for (auto const &kvPair : GetCriteriaProgressMap())
{
WorldPacket data(SMSG_GUILD_CRITERIA_DELETED, 4 + 8);
data.WriteBitSeq<7, 3, 4, 2, 1, 5, 6, 0>(guid);
data.WriteByteSeq<5, 7, 4, 6, 2, 1, 3>(guid);
data << uint32(kvPair.first);
data.WriteByteSeq<0>(guid);
SendPacket(&data);
}
GetCriteriaProgressMap().clear();
_achievementPoints = 0;
DeleteFromDB(GetOwner()->GetId());
}
template<class T>
void AchievementMgr<T>::SendAchievementEarned(AchievementEntry const* achievement) const
{
// Don't send for achievements with ACHIEVEMENT_FLAG_HIDDEN
if (achievement->flags & ACHIEVEMENT_FLAG_HIDDEN)
return;
if (Guild* guild = sGuildMgr->GetGuildById(GetOwner()->GetGuildId()))
{
Trinity::AchievementChatBuilder say_builder(*GetOwner(), CHAT_MSG_GUILD_ACHIEVEMENT, LANG_ACHIEVEMENT_EARNED, achievement->ID);
Trinity::LocalizedPacketDo<Trinity::AchievementChatBuilder> say_do(say_builder);
guild->BroadcastWorker(say_do);
}
if (achievement->flags & (ACHIEVEMENT_FLAG_REALM_FIRST_KILL | ACHIEVEMENT_FLAG_REALM_FIRST_REACH))
{
if (WorldSession* session = GetOwner()->GetSession())
{
WorldPacket data;
auto const &text = session->GetTrinityString(LANG_ACHIEVEMENT_EARNED);
ChatHandler::FillMessageData(&data, session, CHAT_MSG_ACHIEVEMENT, LANG_UNIVERSAL, NULL, session->GetPlayer()->GetGUID(), text, NULL, NULL, achievement->ID);
sWorld->SendGlobalMessage(&data);
}
// Broadcast realm first reached
/*WorldPacket data(SMSG_SERVER_FIRST_ACHIEVEMENT, GetOwner()->GetName().length() + 1 + 8 + 4 + 4);
data << GetOwner()->GetName();
data << uint64(GetOwner()->GetGUID());
data << uint32(achievement->ID);
data << uint32(0); // 1=link supplied string as player name, 0=display plain string
sWorld->SendGlobalMessage(&data);*/
}
// If player is in world he can tell his friends about new achievement
else if (GetOwner()->IsInWorld())
{
CellCoord p = Trinity::ComputeCellCoord(GetOwner()->GetPositionX(), GetOwner()->GetPositionY());
Cell cell(p);
cell.SetNoCreate();
Trinity::AchievementChatBuilder say_builder(*GetOwner(), CHAT_MSG_ACHIEVEMENT, LANG_ACHIEVEMENT_EARNED, achievement->ID);
Trinity::LocalizedPacketDo<Trinity::AchievementChatBuilder> say_do(say_builder);
Trinity::PlayerDistWorker<Trinity::LocalizedPacketDo<Trinity::AchievementChatBuilder> > say_worker(GetOwner(), sWorld->getFloatConfig(CONFIG_LISTEN_RANGE_SAY), say_do);
cell.Visit(p, Trinity::makeWorldVisitor(say_worker), *GetOwner()->GetMap(), *GetOwner(), sWorld->getFloatConfig(CONFIG_LISTEN_RANGE_SAY));
}
WorldPacket data(SMSG_ACHIEVEMENT_EARNED);
ObjectGuid thisPlayerGuid = GetOwner()->GetGUID();
ObjectGuid firstPlayerOnAccountGuid = GetOwner()->GetGUID();
if (HasAccountAchieved(achievement->ID))
firstPlayerOnAccountGuid = GetFirstAchievedCharacterOnAccount(achievement->ID);
data << uint32(secsToTimeBitFields(time(NULL)));
data << uint32(50724905);
data << uint32(achievement->ID);
data << uint32(50724905);
data.WriteBitSeq<6>(thisPlayerGuid);
data.WriteBitSeq<5, 3, 0, 1, 6>(firstPlayerOnAccountGuid);
data.WriteBitSeq<2>(thisPlayerGuid);
data.WriteBitSeq<2>(firstPlayerOnAccountGuid);
data.WriteBitSeq<1, 4, 5, 7>(thisPlayerGuid);
data.WriteBitSeq<7>(firstPlayerOnAccountGuid);
data.WriteBitSeq<0>(thisPlayerGuid);
data.WriteBitSeq<4>(firstPlayerOnAccountGuid);
data.WriteBit(0);
data.WriteBitSeq<3>(thisPlayerGuid);
data.WriteByteSeq<4>(firstPlayerOnAccountGuid);
data.WriteByteSeq<0, 2, 6, 1>(thisPlayerGuid);
data.WriteByteSeq<1, 5, 0>(firstPlayerOnAccountGuid);
data.WriteByteSeq<7, 3, 5>(thisPlayerGuid);
data.WriteByteSeq<6>(firstPlayerOnAccountGuid);
data.WriteByteSeq<4>(thisPlayerGuid);
data.WriteByteSeq<3, 7, 2>(firstPlayerOnAccountGuid);
GetOwner()->SendMessageToSetInRange(&data, sWorld->getFloatConfig(CONFIG_LISTEN_RANGE_SAY), true);
}
template<>
void AchievementMgr<Guild>::SendAchievementEarned(AchievementEntry const* achievement) const
{
ObjectGuid guid = GetOwner()->GetGUID();
WorldPacket data(SMSG_GUILD_ACHIEVEMENT_EARNED, 8+4+8);
data.WriteBitSeq<6, 1, 5, 0, 3, 4, 2, 7>(guid);
data.WriteByteSeq<7>(guid);
data << uint32(achievement->ID);
data.WriteByteSeq<4, 3, 1, 6, 5>(guid);
data << uint32(secsToTimeBitFields(time(NULL)));
data.WriteByteSeq<0, 2>(guid);
SendPacket(&data);
}
template<class T>
void AchievementMgr<T>::SendCriteriaUpdate(CriteriaEntry const* /*entry*/, CriteriaProgress const* /*progress*/, uint32 /*timeElapsed*/, bool /*timedCompleted*/) const
{
}
template<>
void AchievementMgr<Player>::SendCriteriaUpdate(CriteriaEntry const* entry, CriteriaProgress const* progress, uint32 timeElapsed, bool timedCompleted) const
{
WorldPacket data(SMSG_CRITERIA_UPDATE, 4 + 4 + 4 + 4 + 8 + 4);
ObjectGuid playerGuid = GetOwner()->GetGUID();
data << uint32(entry->ID);
// This are some flags, 1 is for keeping the counter at 0 in client
if (!entry->timeLimit)
data << uint32(0);
else
data << uint32(timedCompleted ? 0 : 1);
data << uint32(timeElapsed); // Time elapsed in seconds
data.AppendPackedTime(progress->date);
data << (uint64)progress->counter;
data << uint32(timeElapsed);
data.WriteBitSeq<2, 4, 1, 5, 3, 6, 7, 0>(playerGuid);
data.WriteByteSeq<7, 0, 6, 5, 2, 1, 4, 3>(playerGuid);
SendPacket(&data);
}
template<>
void AchievementMgr<Guild>::SendCriteriaUpdate(CriteriaEntry const* entry, CriteriaProgress const* progress, uint32 /*timeElapsed*/, bool /*timedCompleted*/) const
{
// Will send response to criteria progress request
WorldPacket data(SMSG_GUILD_CRITERIA_DATA);
ObjectGuid counter = progress->counter; // For accessing every byte individually
ObjectGuid guid = progress->CompletedGUID;
data.WriteBits(1, 19);
data.WriteBitSeq<3, 6>(counter);
data.WriteBitSeq<5, 4>(guid);
data.WriteBitSeq<2>(counter);
data.WriteBitSeq<0>(guid);
data.WriteBitSeq<7>(counter);
data.WriteBitSeq<6, 7, 3>(guid);
data.WriteBitSeq<5, 0>(counter);
data.WriteBitSeq<2>(guid);
data.WriteBitSeq<1, 4>(counter);
data.WriteBitSeq<1>(guid);
data.FlushBits();
data.WriteByteSeq<4>(guid);
data << uint32(progress->date); // Unknown date
data.WriteByteSeq<2, 0>(counter);
data << uint32(progress->changed);
data.WriteByteSeq<7, 1>(guid);
data << uint32(entry->ID);
data << uint32(progress->date); // Last update time (not packed!)
data.WriteByteSeq<6>(guid);
data.WriteByteSeq<1>(counter);
data.WriteByteSeq<3>(guid);
data.WriteByteSeq<4>(counter);
data << uint32(progress->date); // Unknown date
data.WriteByteSeq<5, 3>(counter);
data.WriteByteSeq<0>(guid);
data.WriteByteSeq<6, 7>(counter);
data.WriteByteSeq<2, 5>(guid);
SendPacket(&data);
}
template<class T>
CriteriaProgressMap & AchievementMgr<T>::GetCriteriaProgressMap()
{
return m_criteriaProgress;
}
static const uint32 achievIdByArenaSlot[MAX_ARENA_SLOT] = {1057, 1107, 1108};
static const uint32 achievIdForDungeon[][4] =
{
// ach_cr_id, is_dungeon, is_raid, is_heroic_dungeon
{ 321, true, true, true },
{ 916, false, true, false },
{ 917, false, true, false },
{ 918, true, false, false },
{ 2219, false, false, true },
{ 0, false, false, false }
};
// Helper function to avoid having to specialize template for a 800 line long function
template <typename T> static bool IsGuild() { return false; }
template<> bool IsGuild<Guild>() { return true; }
/**
* This function will be called whenever the user might have done a criteria relevant action
*/
template<class T>
void AchievementMgr<T>::UpdateAchievementCriteria(AchievementCriteriaTypes type, uint64 miscValue1 /*= 0*/, uint64 miscValue2 /*= 0*/, uint64 miscValue3 /*= 0*/, Unit const* unit /*= NULL*/, Player* referencePlayer /*= NULL*/)
{
if (type >= ACHIEVEMENT_CRITERIA_TYPE_TOTAL)
return;
if (!IsGuild<T>() && !referencePlayer)
return;
// disable for gamemasters with GM-mode enabled
if (referencePlayer)
if (referencePlayer->isGameMaster())
return;
// Lua_GetGuildLevelEnabled() is checked in achievement UI to display guild tab
if (IsGuild<T>() && !sWorld->getBoolConfig(CONFIG_GUILD_LEVELING_ENABLED))
return;
AchievementCriteriaEntryList const& achievementCriteriaList = sAchievementMgr->GetAchievementCriteriaByType(type, IsGuild<T>());
for (AchievementCriteriaEntryList::const_iterator i = achievementCriteriaList.begin(); i != achievementCriteriaList.end(); ++i)
{
CriteriaEntry const* achievementCriteria = (*i);
if (!CanUpdateCriteria(achievementCriteria, miscValue1, miscValue2, miscValue3, unit, referencePlayer))
continue;
// Requirements not found in the dbc
if (AchievementCriteriaDataSet const* data = sAchievementMgr->GetCriteriaDataSet(achievementCriteria))
if (!data->Meets(referencePlayer, unit, miscValue1))
continue;
switch (type)
{
// std. case: increment at 1
case ACHIEVEMENT_CRITERIA_TYPE_NUMBER_OF_TALENT_RESETS:
case ACHIEVEMENT_CRITERIA_TYPE_LOSE_DUEL:
case ACHIEVEMENT_CRITERIA_TYPE_CREATE_AUCTION:
case ACHIEVEMENT_CRITERIA_TYPE_WON_AUCTIONS: // @TODO : for online player only currently
case ACHIEVEMENT_CRITERIA_TYPE_ROLL_NEED:
case ACHIEVEMENT_CRITERIA_TYPE_ROLL_GREED:
case ACHIEVEMENT_CRITERIA_TYPE_QUEST_ABANDONED:
case ACHIEVEMENT_CRITERIA_TYPE_FLIGHT_PATHS_TAKEN:
case ACHIEVEMENT_CRITERIA_TYPE_ACCEPTED_SUMMONINGS:
case ACHIEVEMENT_CRITERIA_TYPE_LOOT_EPIC_ITEM:
case ACHIEVEMENT_CRITERIA_TYPE_RECEIVE_EPIC_ITEM:
case ACHIEVEMENT_CRITERIA_TYPE_DEATH:
case ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_DAILY_QUEST:
case ACHIEVEMENT_CRITERIA_TYPE_DEATH_AT_MAP:
case ACHIEVEMENT_CRITERIA_TYPE_DEATH_IN_DUNGEON:
case ACHIEVEMENT_CRITERIA_TYPE_KILLED_BY_CREATURE:
case ACHIEVEMENT_CRITERIA_TYPE_KILLED_BY_PLAYER:
case ACHIEVEMENT_CRITERIA_TYPE_DEATHS_FROM:
case ACHIEVEMENT_CRITERIA_TYPE_BE_SPELL_TARGET:
case ACHIEVEMENT_CRITERIA_TYPE_BE_SPELL_TARGET2:
case ACHIEVEMENT_CRITERIA_TYPE_CAST_SPELL:
case ACHIEVEMENT_CRITERIA_TYPE_CAST_SPELL2:
case ACHIEVEMENT_CRITERIA_TYPE_WIN_RATED_ARENA:
case ACHIEVEMENT_CRITERIA_TYPE_USE_ITEM:
case ACHIEVEMENT_CRITERIA_TYPE_ROLL_NEED_ON_LOOT:
case ACHIEVEMENT_CRITERIA_TYPE_ROLL_GREED_ON_LOOT:
case ACHIEVEMENT_CRITERIA_TYPE_DO_EMOTE:
case ACHIEVEMENT_CRITERIA_TYPE_USE_GAMEOBJECT:
case ACHIEVEMENT_CRITERIA_TYPE_FISH_IN_GAMEOBJECT:
case ACHIEVEMENT_CRITERIA_TYPE_WIN_DUEL:
case ACHIEVEMENT_CRITERIA_TYPE_HK_CLASS:
case ACHIEVEMENT_CRITERIA_TYPE_HK_RACE:
case ACHIEVEMENT_CRITERIA_TYPE_BG_OBJECTIVE_CAPTURE:
case ACHIEVEMENT_CRITERIA_TYPE_HONORABLE_KILL:
case ACHIEVEMENT_CRITERIA_TYPE_SPECIAL_PVP_KILL:
case ACHIEVEMENT_CRITERIA_TYPE_GET_KILLING_BLOWS:
case ACHIEVEMENT_CRITERIA_TYPE_HONORABLE_KILL_AT_AREA:
case ACHIEVEMENT_CRITERIA_TYPE_WIN_RATED_BATTLEGROUND:
case ACHIEVEMENT_CRITERIA_TYPE_WIN_ARENA:
case ACHIEVEMENT_CRITERIA_TYPE_KILL_CREATURE_TYPE_GUILD:
case ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_ARCHAEOLOGY_PROJECTS:
case ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_GUILD_CHALLENGE_TYPE:
case ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_GUILD_CHALLENGE:
SetCriteriaProgress(achievementCriteria, 1, referencePlayer, PROGRESS_ACCUMULATE);
break;
// std case: increment at miscValue1
case ACHIEVEMENT_CRITERIA_TYPE_MONEY_FROM_VENDORS:
case ACHIEVEMENT_CRITERIA_TYPE_GOLD_SPENT_FOR_TALENTS:
case ACHIEVEMENT_CRITERIA_TYPE_MONEY_FROM_QUEST_REWARD:
case ACHIEVEMENT_CRITERIA_TYPE_GOLD_SPENT_FOR_TRAVELLING:
case ACHIEVEMENT_CRITERIA_TYPE_GOLD_SPENT_AT_BARBER:
case ACHIEVEMENT_CRITERIA_TYPE_GOLD_SPENT_FOR_MAIL:
case ACHIEVEMENT_CRITERIA_TYPE_LOOT_MONEY:
case ACHIEVEMENT_CRITERIA_TYPE_GOLD_EARNED_BY_AUCTIONS: //@TODO : for online player only currently
case ACHIEVEMENT_CRITERIA_TYPE_TOTAL_DAMAGE_RECEIVED:
case ACHIEVEMENT_CRITERIA_TYPE_TOTAL_HEALING_RECEIVED:
case ACHIEVEMENT_CRITERIA_TYPE_USE_LFD_TO_GROUP_WITH_PLAYERS:
case ACHIEVEMENT_CRITERIA_TYPE_WIN_BG:
case ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_BATTLEGROUND:
case ACHIEVEMENT_CRITERIA_TYPE_DAMAGE_DONE:
case ACHIEVEMENT_CRITERIA_TYPE_HEALING_DONE:
case ACHIEVEMENT_CRITERIA_TYPE_CATCH_FROM_POOL:
case ACHIEVEMENT_CRITERIA_TYPE_BUY_GUILD_BANK_SLOTS:
case ACHIEVEMENT_CRITERIA_TYPE_EARN_GUILD_ACHIEVEMENT_POINTS:
case ACHIEVEMENT_CRITERIA_TYPE_BUY_GUILD_TABARD:
case ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_QUESTS_GUILD:
case ACHIEVEMENT_CRITERIA_TYPE_HONORABLE_KILLS_GUILD:
SetCriteriaProgress(achievementCriteria, miscValue1, referencePlayer, PROGRESS_ACCUMULATE);
break;
// std case: increment at miscValue2
case ACHIEVEMENT_CRITERIA_TYPE_KILL_CREATURE:
case ACHIEVEMENT_CRITERIA_TYPE_LOOT_TYPE:
case ACHIEVEMENT_CRITERIA_TYPE_OWN_ITEM:
case ACHIEVEMENT_CRITERIA_TYPE_LOOT_ITEM:
case ACHIEVEMENT_CRITERIA_TYPE_CURRENCY:
SetCriteriaProgress(achievementCriteria, miscValue2, referencePlayer, PROGRESS_ACCUMULATE);
break;
// std case: high value at miscValue1
case ACHIEVEMENT_CRITERIA_TYPE_HIGHEST_AUCTION_BID:
case ACHIEVEMENT_CRITERIA_TYPE_HIGHEST_AUCTION_SOLD: //@TODO : for online player only currently
case ACHIEVEMENT_CRITERIA_TYPE_HIGHEST_HIT_DEALT:
case ACHIEVEMENT_CRITERIA_TYPE_HIGHEST_HIT_RECEIVED:
case ACHIEVEMENT_CRITERIA_TYPE_HIGHEST_HEAL_CASTED:
case ACHIEVEMENT_CRITERIA_TYPE_HIGHEST_HEALING_RECEIVED:
SetCriteriaProgress(achievementCriteria, miscValue1, referencePlayer, PROGRESS_HIGHEST);
break;
case ACHIEVEMENT_CRITERIA_TYPE_REACH_LEVEL:
SetCriteriaProgress(achievementCriteria, referencePlayer->getLevel(), referencePlayer);
break;
case ACHIEVEMENT_CRITERIA_TYPE_REACH_SKILL_LEVEL:
if (uint32 skillvalue = referencePlayer->GetBaseSkillValue(achievementCriteria->reach_skill_level.skillID))
SetCriteriaProgress(achievementCriteria, skillvalue, referencePlayer);
break;
case ACHIEVEMENT_CRITERIA_TYPE_LEARN_SKILL_LEVEL:
if (uint32 maxSkillvalue = referencePlayer->GetPureMaxSkillValue(achievementCriteria->learn_skill_level.skillID))
SetCriteriaProgress(achievementCriteria, maxSkillvalue, referencePlayer);
break;
case ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_QUEST_COUNT:
SetCriteriaProgress(achievementCriteria, referencePlayer->GetRewardedQuestCount(), referencePlayer);
break;
case ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_DAILY_QUEST_DAILY:
{
time_t nextDailyResetTime = sWorld->GetNextDailyQuestsResetTime();
CriteriaProgress *progress = GetCriteriaProgress(achievementCriteria);
if (!miscValue1) // Login case.
{
// Reset if player missed one day.
if (progress && progress->date < (nextDailyResetTime - 2 * DAY))
SetCriteriaProgress(achievementCriteria, 0, referencePlayer, PROGRESS_SET);
continue;
}
ProgressType progressType;
if (!progress)
// 1st time. Start count.
progressType = PROGRESS_SET;
else if (progress->date < (nextDailyResetTime - 2 * DAY))
// Last progress is older than 2 days. Player missed 1 day => Restart count.
progressType = PROGRESS_SET;
else if (progress->date < (nextDailyResetTime - DAY))
// Last progress is between 1 and 2 days. => 1st time of the day.
progressType = PROGRESS_ACCUMULATE;
else
// Last progress is within the day before the reset => Already counted today.
continue;
SetCriteriaProgress(achievementCriteria, 1, referencePlayer, progressType);
break;
}
case ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_QUESTS_IN_ZONE:
{
uint32 counter = 0;
const RewardedQuestSet &rewQuests = referencePlayer->getRewardedQuests();
for (RewardedQuestSet::const_iterator itr = rewQuests.begin(); itr != rewQuests.end(); ++itr)
{
Quest const* quest = sObjectMgr->GetQuestTemplate(*itr);
if (quest && quest->GetZoneOrSort() >= 0 && uint32(quest->GetZoneOrSort()) == achievementCriteria->complete_quests_in_zone.zoneID)
++counter;
}
SetCriteriaProgress(achievementCriteria, counter, referencePlayer);
break;
}
case ACHIEVEMENT_CRITERIA_TYPE_FALL_WITHOUT_DYING:
// miscValue1 is the ingame fallheight*100 as stored in dbc
SetCriteriaProgress(achievementCriteria, miscValue1, referencePlayer);
break;
case ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_QUEST:
case ACHIEVEMENT_CRITERIA_TYPE_LEARN_SPELL:
case ACHIEVEMENT_CRITERIA_TYPE_EXPLORE_AREA:
case ACHIEVEMENT_CRITERIA_TYPE_VISIT_BARBER_SHOP:
case ACHIEVEMENT_CRITERIA_TYPE_EQUIP_EPIC_ITEM:
case ACHIEVEMENT_CRITERIA_TYPE_EQUIP_ITEM:
case ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_ACHIEVEMENT:
SetCriteriaProgress(achievementCriteria, 1, referencePlayer);
break;
case ACHIEVEMENT_CRITERIA_TYPE_BUY_BANK_SLOT:
SetCriteriaProgress(achievementCriteria, referencePlayer->GetBankBagSlotCount(), referencePlayer);
break;
case ACHIEVEMENT_CRITERIA_TYPE_GAIN_REPUTATION:
{
int32 reputation = referencePlayer->GetReputationMgr().GetReputation(achievementCriteria->gain_reputation.factionID);
if (reputation > 0)
SetCriteriaProgress(achievementCriteria, reputation, referencePlayer);
break;
}
case ACHIEVEMENT_CRITERIA_TYPE_GAIN_EXALTED_REPUTATION:
SetCriteriaProgress(achievementCriteria, referencePlayer->GetReputationMgr().GetExaltedFactionCount(), referencePlayer);
break;
case ACHIEVEMENT_CRITERIA_TYPE_LEARN_SKILLLINE_SPELLS:
{
uint32 spellCount = 0;
for (auto const &kvPair : referencePlayer->GetSpellMap())
{
SkillLineAbilityMapBounds bounds = sSpellMgr->GetSkillLineAbilityMapBounds(kvPair.first);
for (auto skillIter = bounds.first; skillIter != bounds.second; ++skillIter)
{
if (skillIter->second->skillId == achievementCriteria->learn_skillline_spell.skillLine)
++spellCount;
}
}
SetCriteriaProgress(achievementCriteria, spellCount, referencePlayer);
break;
}
case ACHIEVEMENT_CRITERIA_TYPE_GAIN_REVERED_REPUTATION:
SetCriteriaProgress(achievementCriteria, referencePlayer->GetReputationMgr().GetReveredFactionCount(), referencePlayer);
break;
case ACHIEVEMENT_CRITERIA_TYPE_GAIN_HONORED_REPUTATION:
SetCriteriaProgress(achievementCriteria, referencePlayer->GetReputationMgr().GetHonoredFactionCount(), referencePlayer);
break;
case ACHIEVEMENT_CRITERIA_TYPE_KNOWN_FACTIONS:
SetCriteriaProgress(achievementCriteria, referencePlayer->GetReputationMgr().GetVisibleFactionCount(), referencePlayer);
break;
case ACHIEVEMENT_CRITERIA_TYPE_LEARN_SKILL_LINE:
{
uint32 spellCount = 0;
for (auto const &kvPair : referencePlayer->GetSpellMap())
{
SkillLineAbilityMapBounds bounds = sSpellMgr->GetSkillLineAbilityMapBounds(kvPair.first);
for (auto skillIter = bounds.first; skillIter != bounds.second; ++skillIter)
if (skillIter->second->skillId == achievementCriteria->learn_skill_line.skillLine)
++spellCount;
}
SetCriteriaProgress(achievementCriteria, spellCount, referencePlayer);
break;
}
case ACHIEVEMENT_CRITERIA_TYPE_EARN_HONORABLE_KILL:
SetCriteriaProgress(achievementCriteria, referencePlayer->GetUInt32Value(PLAYER_FIELD_LIFETIME_HONORABLE_KILLS), referencePlayer);
break;
case ACHIEVEMENT_CRITERIA_TYPE_HIGHEST_GOLD_VALUE_OWNED:
SetCriteriaProgress(achievementCriteria, referencePlayer->GetMoney(), referencePlayer, PROGRESS_HIGHEST);
break;
case ACHIEVEMENT_CRITERIA_TYPE_EARN_ACHIEVEMENT_POINTS:
if (!miscValue1)
SetCriteriaProgress(achievementCriteria, _achievementPoints, referencePlayer, PROGRESS_SET);
else
SetCriteriaProgress(achievementCriteria, miscValue1, referencePlayer, PROGRESS_ACCUMULATE);
break;
case ACHIEVEMENT_CRITERIA_TYPE_HIGHEST_TEAM_RATING:
{
uint32 reqTeamType = achievementCriteria->highest_team_rating.teamtype;
if (miscValue1)
{
if (miscValue2 != reqTeamType)
continue;
SetCriteriaProgress(achievementCriteria, miscValue1, referencePlayer, PROGRESS_HIGHEST);
}
else // Login case
{
for (uint32 arena_slot = 0; arena_slot < MAX_ARENA_SLOT; ++arena_slot)
SetCriteriaProgress(achievementCriteria, referencePlayer->GetArenaPersonalRating(arena_slot), referencePlayer, PROGRESS_HIGHEST);
}
}
break;
case ACHIEVEMENT_CRITERIA_TYPE_HIGHEST_PERSONAL_RATING:
{
uint32 reqTeamType = achievementCriteria->highest_personal_rating.teamtype;
if (miscValue1)
{
if (miscValue2 != reqTeamType)
continue;
SetCriteriaProgress(achievementCriteria, miscValue1, referencePlayer, PROGRESS_HIGHEST);
}
else // Login case
{
for (uint32 arena_slot = 0; arena_slot < MAX_ARENA_SLOT; ++arena_slot)
SetCriteriaProgress(achievementCriteria, referencePlayer->GetArenaPersonalRating(arena_slot), referencePlayer, PROGRESS_HIGHEST);
}
break;
}
case ACHIEVEMENT_CRITERIA_TYPE_SPENT_GOLD_GUILD_REPAIRS:
{
if (!miscValue1)
continue;
SetCriteriaProgress(achievementCriteria, miscValue1, referencePlayer, PROGRESS_ACCUMULATE);
break;
}
case ACHIEVEMENT_CRITERIA_TYPE_REACH_GUILD_LEVEL:
case ACHIEVEMENT_CRITERIA_TYPE_REACH_BG_RATING:
{
if (!miscValue1)
continue;
SetCriteriaProgress(achievementCriteria, miscValue1, referencePlayer);
break;
}
case ACHIEVEMENT_CRITERIA_TYPE_CRAFT_ITEMS_GUILD:
{
if (!miscValue1 || !miscValue2)
continue;
SetCriteriaProgress(achievementCriteria, miscValue2, referencePlayer, PROGRESS_ACCUMULATE);
break;
}
// FIXME: not triggered in code as result, need to implement
case ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_RAID:
case ACHIEVEMENT_CRITERIA_TYPE_PLAY_ARENA:
case ACHIEVEMENT_CRITERIA_TYPE_OWN_RANK:
case ACHIEVEMENT_CRITERIA_TYPE_EARNED_PVP_TITLE:
case ACHIEVEMENT_CRITERIA_TYPE_KILL_CREATURE_TYPE:
break; // Not implemented yet :(
default:
break;
}
std::list<uint32> achivEntries;
AchievementCriteriaTreeList achievementCriteriaTreeList = sAchievementMgr->GetAchievementCriteriaTreeList(achievementCriteria);
for (AchievementCriteriaTreeList::const_iterator iter = achievementCriteriaTreeList.begin(); iter != achievementCriteriaTreeList.end(); iter++)
{
AchievementEntry const* achievement = sAchievementMgr->GetAchievementEntryByCriteriaTree(*iter);
if (!achievement)
continue;
if ((IsGuild<T>() && !(achievement->flags & ACHIEVEMENT_FLAG_GUILD))
|| (achievement->flags & ACHIEVEMENT_FLAG_GUILD && !IsGuild<T>()))
{
TC_LOG_DEBUG("achievement", "CanUpdateCriteria: (Id: %u Type %s Achievement %u) Non-guild achievement",
achievementCriteria->ID, AchievementGlobalMgr::GetCriteriaTypeString(achievementCriteria->type), achievement->ID, achievement->parentAchievement);
continue;
}
if (achievement->mapID != -1 && referencePlayer->GetMapId() != uint32(achievement->mapID))
{
if (type == ACHIEVEMENT_CRITERIA_TYPE_LEARN_SKILLLINE_SPELLS)
{
TC_LOG_DEBUG("achievement", "CanUpdateCriteria: (Id: %u Type %s Achievement %u) Wrong map",
achievementCriteria->ID, AchievementGlobalMgr::GetCriteriaTypeString(achievementCriteria->type), achievement->ID);
continue;
}
}
if ((achievement->requiredFaction == ACHIEVEMENT_FACTION_HORDE && referencePlayer->GetTeam() != HORDE) ||
(achievement->requiredFaction == ACHIEVEMENT_FACTION_ALLIANCE && referencePlayer->GetTeam() != ALLIANCE))
{
TC_LOG_DEBUG("achievement", "CanUpdateCriteria: (Id: %u Type %s Achievement %u) Wrong faction",
achievementCriteria->ID, AchievementGlobalMgr::GetCriteriaTypeString(achievementCriteria->type), achievement->ID);
continue;
}
achivEntries.push_back(achievement->ID);
}
achivEntries.sort();
for (auto x : achivEntries)
{
AchievementEntry const* achievement = sAchievementMgr->GetAchievement(x);
if (!achievement)
continue;
if (referencePlayer)
{
if (achievement->parentAchievement != 0 &&
((!(achievement->flags & ACHIEVEMENT_FLAG_ACCOUNT) && !HasAchieved(achievement->parentAchievement))
|| (achievement->flags & ACHIEVEMENT_FLAG_ACCOUNT && !HasAccountAchieved(achievement->parentAchievement))))
{
TC_LOG_DEBUG("achievement", "CanUpdateCriteria: (Id: %u Type %s Achievement %u) Not completed parent achievement %u (Guild: %u)",
achievementCriteria->ID, AchievementGlobalMgr::GetCriteriaTypeString(achievementCriteria->type), achievement->ID, achievement->parentAchievement, IsGuild<T>() ? 1 : 0);
continue;
}
}
if (IsCompletedCriteriaForAchievement(achievementCriteria, achievement))
CompletedCriteriaFor(achievement, referencePlayer);
// check again the completeness for SUMM and REQ COUNT achievements,
// as they don't depend on the completed criteria but on the sum of the progress of each individual criteria
if (achievement->flags & ACHIEVEMENT_FLAG_SUMM)
if (IsCompletedAchievement(achievement))
CompletedAchievement(achievement, referencePlayer);
if (AchievementEntryList const* achRefList = sAchievementMgr->GetAchievementByReferencedId(achievement->ID))
for (AchievementEntryList::const_iterator itr = achRefList->begin(); itr != achRefList->end(); ++itr)
if (IsCompletedAchievement(*itr))
CompletedAchievement(*itr, referencePlayer);
}
}
}
template<class T>
bool AchievementMgr<T>::CanCompleteCriteria(CriteriaEntry const* /*achievementCriteria*/, AchievementEntry const* /*achievement*/)
{
return true;
}
template<>
bool AchievementMgr<Player>::CanCompleteCriteria(CriteriaEntry const* /*achievementCriteria*/, AchievementEntry const* achievement)
{
if (achievement->flags & (ACHIEVEMENT_FLAG_REALM_FIRST_REACH | ACHIEVEMENT_FLAG_REALM_FIRST_KILL))
{
// Someone on this realm has already completed that achievement
if (sAchievementMgr->IsRealmCompleted(achievement))
return false;
if (GetOwner())
if (GetOwner()->GetSession())
if (GetOwner()->GetSession()->GetSecurity())
return false;
}
return true;
}
template<class T>
bool AchievementMgr<T>::IsCompletedCriteria(CriteriaEntry const* criteria)
{
AchievementCriteriaTreeList const& criteriaTreeList = sAchievementMgr->GetAchievementCriteriaTreeList(criteria);
for (AchievementCriteriaTreeList::const_iterator iter = criteriaTreeList.begin(); iter != criteriaTreeList.end(); iter++)
{
CriteriaTreeEntry const* criteriaTree = *iter;
AchievementEntry const* achievement = sAchievementMgr->GetAchievementEntryByCriteriaTree(criteriaTree);
if (!achievement)
return false;
if (CriteriaEntry const* criteria = sCriteriaStore.LookupEntry(criteriaTree->criteriaID))
if (!IsCompletedCriteriaForAchievement(criteria, achievement))
return false;
}
return true;
}
template<class T>
bool AchievementMgr<T>::IsCompletedCriteriaForAchievement(CriteriaEntry const* criteria, AchievementEntry const* achievement)
{
if (!criteria || !achievement)
return false;
CriteriaTreeEntry const* criteriaTree = NULL;
AchievementCriteriaTreeList const* treeList = sAchievementMgr->GetSubCriteriaTreeById(achievement->criteriaTreeID);
if (treeList)
{
for (AchievementCriteriaTreeList::const_iterator iter = treeList->begin(); iter != treeList->end(); iter++)
{
if ((*iter)->criteriaID == criteria->ID)
{
criteriaTree = *iter;
break;
}
}
}
if (!criteriaTree)
return false;
// counter can never complete
if (achievement->flags & ACHIEVEMENT_FLAG_COUNTER)
return false;
if (achievement->flags & (ACHIEVEMENT_FLAG_REALM_FIRST_REACH | ACHIEVEMENT_FLAG_REALM_FIRST_KILL))
{
// someone on this realm has already completed that achievement
if (sAchievementMgr->IsRealmCompleted(achievement))
return false;
}
CriteriaProgress const* progress = GetCriteriaProgress(criteria);
if (!progress)
return false;
switch (AchievementCriteriaTypes(criteria->type))
{
case ACHIEVEMENT_CRITERIA_TYPE_WIN_BG:
case ACHIEVEMENT_CRITERIA_TYPE_WIN_RATED_BATTLEGROUND:
case ACHIEVEMENT_CRITERIA_TYPE_KILL_CREATURE:
case ACHIEVEMENT_CRITERIA_TYPE_REACH_LEVEL:
case ACHIEVEMENT_CRITERIA_TYPE_REACH_GUILD_LEVEL:
case ACHIEVEMENT_CRITERIA_TYPE_REACH_SKILL_LEVEL:
case ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_QUEST_COUNT:
case ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_DAILY_QUEST_DAILY:
case ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_QUESTS_IN_ZONE:
case ACHIEVEMENT_CRITERIA_TYPE_DAMAGE_DONE:
case ACHIEVEMENT_CRITERIA_TYPE_HEALING_DONE:
case ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_DAILY_QUEST:
case ACHIEVEMENT_CRITERIA_TYPE_FALL_WITHOUT_DYING:
case ACHIEVEMENT_CRITERIA_TYPE_BE_SPELL_TARGET:
case ACHIEVEMENT_CRITERIA_TYPE_BE_SPELL_TARGET2:
case ACHIEVEMENT_CRITERIA_TYPE_CAST_SPELL:
case ACHIEVEMENT_CRITERIA_TYPE_CAST_SPELL2:
case ACHIEVEMENT_CRITERIA_TYPE_BG_OBJECTIVE_CAPTURE:
case ACHIEVEMENT_CRITERIA_TYPE_HONORABLE_KILL_AT_AREA:
case ACHIEVEMENT_CRITERIA_TYPE_HONORABLE_KILL:
case ACHIEVEMENT_CRITERIA_TYPE_EARN_HONORABLE_KILL:
case ACHIEVEMENT_CRITERIA_TYPE_OWN_ITEM:
case ACHIEVEMENT_CRITERIA_TYPE_WIN_RATED_ARENA:
case ACHIEVEMENT_CRITERIA_TYPE_HIGHEST_PERSONAL_RATING:
case ACHIEVEMENT_CRITERIA_TYPE_USE_ITEM:
case ACHIEVEMENT_CRITERIA_TYPE_LOOT_ITEM:
case ACHIEVEMENT_CRITERIA_TYPE_BUY_BANK_SLOT:
case ACHIEVEMENT_CRITERIA_TYPE_GAIN_REPUTATION:
case ACHIEVEMENT_CRITERIA_TYPE_GAIN_EXALTED_REPUTATION:
case ACHIEVEMENT_CRITERIA_TYPE_VISIT_BARBER_SHOP:
case ACHIEVEMENT_CRITERIA_TYPE_EQUIP_EPIC_ITEM:
case ACHIEVEMENT_CRITERIA_TYPE_ROLL_NEED_ON_LOOT:
case ACHIEVEMENT_CRITERIA_TYPE_ROLL_GREED_ON_LOOT:
case ACHIEVEMENT_CRITERIA_TYPE_HK_CLASS:
case ACHIEVEMENT_CRITERIA_TYPE_HK_RACE:
case ACHIEVEMENT_CRITERIA_TYPE_DO_EMOTE:
case ACHIEVEMENT_CRITERIA_TYPE_EQUIP_ITEM:
case ACHIEVEMENT_CRITERIA_TYPE_MONEY_FROM_QUEST_REWARD:
case ACHIEVEMENT_CRITERIA_TYPE_LOOT_MONEY:
case ACHIEVEMENT_CRITERIA_TYPE_USE_GAMEOBJECT:
case ACHIEVEMENT_CRITERIA_TYPE_SPECIAL_PVP_KILL:
case ACHIEVEMENT_CRITERIA_TYPE_FISH_IN_GAMEOBJECT:
case ACHIEVEMENT_CRITERIA_TYPE_LEARN_SKILLLINE_SPELLS:
case ACHIEVEMENT_CRITERIA_TYPE_WIN_DUEL:
case ACHIEVEMENT_CRITERIA_TYPE_LOOT_TYPE:
case ACHIEVEMENT_CRITERIA_TYPE_LEARN_SKILL_LINE:
case ACHIEVEMENT_CRITERIA_TYPE_USE_LFD_TO_GROUP_WITH_PLAYERS:
case ACHIEVEMENT_CRITERIA_TYPE_GET_KILLING_BLOWS:
case ACHIEVEMENT_CRITERIA_TYPE_CURRENCY:
case ACHIEVEMENT_CRITERIA_TYPE_BUY_GUILD_BANK_SLOTS:
case ACHIEVEMENT_CRITERIA_TYPE_CRAFT_ITEMS_GUILD:
return progress->counter >= criteriaTree->criteriaCount;
case ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_ACHIEVEMENT:
case ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_QUEST:
case ACHIEVEMENT_CRITERIA_TYPE_LEARN_SPELL:
case ACHIEVEMENT_CRITERIA_TYPE_EXPLORE_AREA:
case ACHIEVEMENT_CRITERIA_TYPE_BUY_GUILD_TABARD:
return progress->counter >= 1;
case ACHIEVEMENT_CRITERIA_TYPE_LEARN_SKILL_LEVEL:
return progress->counter >= (criteriaTree->criteriaCount * 75);
case ACHIEVEMENT_CRITERIA_TYPE_EARN_ACHIEVEMENT_POINTS:
return progress->counter >= 9000;
case ACHIEVEMENT_CRITERIA_TYPE_EARN_GUILD_ACHIEVEMENT_POINTS:
return progress->counter >= 2000;
case ACHIEVEMENT_CRITERIA_TYPE_WIN_ARENA:
return criteriaTree->criteriaCount && progress->counter >= criteriaTree->criteriaCount;
// handle all statistic-only criteria here
case ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_BATTLEGROUND:
case ACHIEVEMENT_CRITERIA_TYPE_DEATH_AT_MAP:
case ACHIEVEMENT_CRITERIA_TYPE_DEATH:
case ACHIEVEMENT_CRITERIA_TYPE_DEATH_IN_DUNGEON:
case ACHIEVEMENT_CRITERIA_TYPE_KILLED_BY_CREATURE:
case ACHIEVEMENT_CRITERIA_TYPE_KILLED_BY_PLAYER:
case ACHIEVEMENT_CRITERIA_TYPE_DEATHS_FROM:
case ACHIEVEMENT_CRITERIA_TYPE_HIGHEST_TEAM_RATING:
case ACHIEVEMENT_CRITERIA_TYPE_MONEY_FROM_VENDORS:
case ACHIEVEMENT_CRITERIA_TYPE_GOLD_SPENT_FOR_TALENTS:
case ACHIEVEMENT_CRITERIA_TYPE_NUMBER_OF_TALENT_RESETS:
case ACHIEVEMENT_CRITERIA_TYPE_GOLD_SPENT_AT_BARBER:
case ACHIEVEMENT_CRITERIA_TYPE_GOLD_SPENT_FOR_MAIL:
case ACHIEVEMENT_CRITERIA_TYPE_LOSE_DUEL:
case ACHIEVEMENT_CRITERIA_TYPE_KILL_CREATURE_TYPE:
case ACHIEVEMENT_CRITERIA_TYPE_GOLD_EARNED_BY_AUCTIONS:
case ACHIEVEMENT_CRITERIA_TYPE_CREATE_AUCTION:
case ACHIEVEMENT_CRITERIA_TYPE_HIGHEST_AUCTION_BID:
case ACHIEVEMENT_CRITERIA_TYPE_HIGHEST_AUCTION_SOLD:
case ACHIEVEMENT_CRITERIA_TYPE_HIGHEST_GOLD_VALUE_OWNED:
case ACHIEVEMENT_CRITERIA_TYPE_WON_AUCTIONS:
case ACHIEVEMENT_CRITERIA_TYPE_GAIN_REVERED_REPUTATION:
case ACHIEVEMENT_CRITERIA_TYPE_GAIN_HONORED_REPUTATION:
case ACHIEVEMENT_CRITERIA_TYPE_KNOWN_FACTIONS:
case ACHIEVEMENT_CRITERIA_TYPE_LOOT_EPIC_ITEM:
case ACHIEVEMENT_CRITERIA_TYPE_RECEIVE_EPIC_ITEM:
case ACHIEVEMENT_CRITERIA_TYPE_ROLL_NEED:
case ACHIEVEMENT_CRITERIA_TYPE_ROLL_GREED:
case ACHIEVEMENT_CRITERIA_TYPE_QUEST_ABANDONED:
case ACHIEVEMENT_CRITERIA_TYPE_FLIGHT_PATHS_TAKEN:
case ACHIEVEMENT_CRITERIA_TYPE_ACCEPTED_SUMMONINGS:
default:
return false;
}
return false;
}
template<class T>
void AchievementMgr<T>::CompletedCriteriaFor(AchievementEntry const* achievement, Player* referencePlayer)
{
// Counter can never complete
if (achievement->flags & ACHIEVEMENT_FLAG_COUNTER)
return;
// Already completed and stored
if (HasAchieved(achievement->ID))
return;
if (IsCompletedAchievement(achievement))
CompletedAchievement(achievement, referencePlayer);
}
template<class T>
bool AchievementMgr<T>::IsCompletedAchievement(AchievementEntry const* entry)
{
// Counter can never complete
if (entry->flags & ACHIEVEMENT_FLAG_COUNTER)
return false;
// For achievement with referenced achievement criterias get from referenced and counter from self
uint32 achievementForTestId = entry->refAchievement ? entry->refAchievement : entry->ID;
uint32 achievementForTestCount = entry->count;
if (CriteriaTreeEntry const* criteriaTree = sCriteriaTreeStore.LookupEntry(entry->criteriaTreeID))
achievementForTestCount = criteriaTree->criteriaCount;
AchievementCriteriaEntryList cList;
AchievementCriteriaTreeList const* list = sAchievementMgr->GetSubCriteriaTreeById(entry->criteriaTreeID);
for (AchievementCriteriaTreeList::const_iterator iter = list->begin(); iter != list->end(); iter++)
{
CriteriaTreeEntry const* criteriaTree = *iter;
if (CriteriaEntry const* criteria = sCriteriaStore.LookupEntry(criteriaTree->criteriaID))
cList.push_back(criteria);
}
if (!cList.size())
return false;
uint64 count = 0;
// For SUMM achievements, we have to count the progress of each criteria of the achievement.
// Oddly, the target count is NOT contained in the achievement, but in each individual criteria
if (entry->flags & ACHIEVEMENT_FLAG_SUMM)
{
for (AchievementCriteriaEntryList::const_iterator itr = cList.begin(); itr != cList.end(); ++itr)
{
CriteriaEntry const* criteria = *itr;
CriteriaProgress const* progress = GetCriteriaProgress(criteria);
if (!progress)
continue;
count += progress->counter;
// For counters, field4 contains the main count requirement
if (count >= sCriteriaTreeStore.LookupEntry(entry->criteriaTreeID)->criteriaCount)
return true;
}
return false;
}
// Default case - need complete all or
bool completed_all = true;
for (AchievementCriteriaEntryList::const_iterator itr = cList.begin(); itr != cList.end(); ++itr)
{
CriteriaEntry const* criteria = *itr;
bool completed = IsCompletedCriteriaForAchievement(criteria, entry);
// Found an uncompleted criteria, but DONT return false yet - there might be a completed criteria with ACHIEVEMENT_CRITERIA_COMPLETE_FLAG_ALL
if (completed)
++count;
else
completed_all = false;
// Completed as have req. count of completed criterias
if (achievementForTestCount > 0 && achievementForTestCount <= count)
return true;
}
// All criterias completed requirement
if (completed_all && achievementForTestCount == 0)
return true;
return false;
}
template<class T>
CriteriaProgress* AchievementMgr<T>::GetCriteriaProgress(uint32 criteriaId)
{
CriteriaProgressMap::iterator iter = m_criteriaProgress.find(criteriaId);
if (iter == m_criteriaProgress.end())
return NULL;
return &(iter->second);
}
template<class T>
void AchievementMgr<T>::SetCriteriaProgress(CriteriaEntry const* entry, uint64 changeValue, Player* referencePlayer, ProgressType ptype)
{
// Don't allow to cheat - doing timed achievements without timer active
TimedAchievementMap::iterator timedIter = m_timedAchievements.find(entry->ID);
if (entry->timeLimit && timedIter == m_timedAchievements.end())
return;
TC_LOG_DEBUG("achievement", "SetCriteriaProgress(%u, " UI64FMTD ") for (%s GUID: %u)",
entry->ID, changeValue, GetLogNameForGuid(GetOwner()->GetGUID()), GUID_LOPART(GetOwner()->GetGUID()));
CriteriaProgress* progress = GetCriteriaProgress(entry);
if (!progress)
{
// Not create record for 0 counter but allow it for timed achievements
// We will need to send 0 progress to client to start the timer
if (changeValue == 0 && !entry->timeLimit)
return;
progress = &m_criteriaProgress[entry->ID];
progress->counter = changeValue;
}
else
{
uint64 newValue = 0;
switch (ptype)
{
case PROGRESS_SET:
newValue = changeValue;
break;
case PROGRESS_ACCUMULATE:
{
// Avoid overflow
uint64 max_value = std::numeric_limits<uint64>::max();
newValue = max_value - progress->counter > changeValue ? progress->counter + changeValue : max_value;
break;
}
case PROGRESS_HIGHEST:
newValue = progress->counter < changeValue ? changeValue : progress->counter;
break;
}
// Not update (not mark as changed) if counter will have same value
if (progress->counter == newValue && !entry->timeLimit && (!IsGuild<T>() || !IsCompletedCriteria(entry) || progress->CompletedGUID))
return;
progress->counter = newValue;
}
progress->changed = true;
progress->date = time(NULL); // Set the date to the latest update.
uint32 timeElapsed = 0;
AchievementCriteriaTreeList criteriaList = sAchievementMgr->GetAchievementCriteriaTreeList(entry);
for (AchievementCriteriaTreeList::const_iterator iter = criteriaList.begin(); iter != criteriaList.end(); iter++)
{
AchievementEntry const* achievement = sAchievementMgr->GetAchievementEntryByCriteriaTree(*iter);
if (!achievement)
continue;
bool criteriaComplete = IsCompletedCriteriaForAchievement(entry, achievement);
if (entry->timeLimit)
{
// Client expects this in packet
timeElapsed = entry->timeLimit - (timedIter->second / IN_MILLISECONDS);
// Remove the timer, we wont need it anymore
if (criteriaComplete)
m_timedAchievements.erase(timedIter);
}
if (criteriaComplete && achievement->flags & ACHIEVEMENT_FLAG_SHOW_CRITERIA_MEMBERS && !progress->CompletedGUID)
progress->CompletedGUID = referencePlayer->GetGUID();
if (achievement->flags & ACHIEVEMENT_FLAG_ACCOUNT)
{
WorldPacket data(SMSG_ACCOUNT_CRITERIA_UPDATE, 4 + 4 + 4 + 4 + 8 + 4);
ObjectGuid guid = GetOwner()->GetGUID();
ObjectGuid counter = progress->counter;
data.WriteBitSeq<5>(counter);
data.WriteBits(0, 4);
data.WriteBitSeq<3, 1>(counter);
data.WriteBitSeq<0, 1>(guid);
data.WriteBitSeq<4, 2>(counter);
data.WriteBitSeq<3, 7, 4>(guid);
data.WriteBitSeq<6>(counter);
data.WriteBitSeq<6, 5>(guid);
data.WriteBitSeq<0>(counter);
data.WriteBitSeq<2>(guid);
data.WriteBitSeq<7>(counter);
data.FlushBits();
data.WriteByteSeq<5, 6>(guid);
data.WriteByteSeq<6>(counter);
data.WriteByteSeq<1>(guid);
data << uint32(timeElapsed);
data.WriteByteSeq<2>(counter);
data << uint32(entry->ID);
data.WriteByteSeq<2, 0>(guid);
data.WriteByteSeq<0, 5>(counter);
data.AppendPackedTime(progress->date);
data.WriteByteSeq<4>(counter);
data.WriteByteSeq<3, 7>(guid);
data << uint32(timeElapsed);
data.WriteByteSeq<4>(guid);
data.WriteByteSeq<7, 3, 1>(counter);
SendPacket(&data);
return;
}
}
SendCriteriaUpdate(entry, progress, timeElapsed, false);
}
template<class T>
void AchievementMgr<T>::UpdateTimedAchievements(uint32 timeDiff)
{
if (!m_timedAchievements.empty())
{
for (TimedAchievementMap::iterator itr = m_timedAchievements.begin(); itr != m_timedAchievements.end();)
{
// Time is up, remove timer and reset progress
if (itr->second <= timeDiff)
{
CriteriaEntry const* entry = sAchievementMgr->GetAchievementCriteria(itr->first);
RemoveCriteriaProgress(entry);
m_timedAchievements.erase(itr++);
}
else
{
itr->second -= timeDiff;
++itr;
}
}
}
}
template<class T>
void AchievementMgr<T>::StartTimedAchievement(AchievementCriteriaTimedTypes /*type*/, uint32 /*entry*/, uint32 /*timeLost = 0*/)
{
}
template<>
void AchievementMgr<Player>::StartTimedAchievement(AchievementCriteriaTimedTypes type, uint32 entry, uint32 timeLost /* = 0 */)
{
AchievementCriteriaEntryList const& achievementCriteriaList = sAchievementMgr->GetTimedAchievementCriteriaByType(type);
for (AchievementCriteriaEntryList::const_iterator i = achievementCriteriaList.begin(); i != achievementCriteriaList.end(); ++i)
{
if ((*i)->timedCriteriaMiscId != entry)
continue;
AchievementEntry const* achievement = sAchievementMgr->GetAchievement(entry);
if (m_timedAchievements.find((*i)->ID) == m_timedAchievements.end() && !IsCompletedCriteriaForAchievement(*i, achievement))
{
// Start the timer
if ((*i)->timeLimit * IN_MILLISECONDS > timeLost)
{
m_timedAchievements[(*i)->ID] = (*i)->timeLimit * IN_MILLISECONDS - timeLost;
// And at client too
SetCriteriaProgress(*i, 0, GetOwner(), PROGRESS_SET);
}
}
}
}
template<class T>
void AchievementMgr<T>::RemoveTimedAchievement(AchievementCriteriaTimedTypes type, uint32 entry)
{
AchievementCriteriaEntryList const& achievementCriteriaList = sAchievementMgr->GetTimedAchievementCriteriaByType(type);
for (AchievementCriteriaEntryList::const_iterator i = achievementCriteriaList.begin(); i != achievementCriteriaList.end(); ++i)
{
if ((*i)->timedCriteriaMiscId != entry)
continue;
TimedAchievementMap::iterator timedIter = m_timedAchievements.find((*i)->ID);
// We don't have timer for this achievement
if (timedIter == m_timedAchievements.end())
continue;
// Remove progress
RemoveCriteriaProgress(*i);
// Remove the timer
m_timedAchievements.erase(timedIter);
}
}
template<class T>
void AchievementMgr<T>::CompletedAchievement(AchievementEntry const* achievement, Player* referencePlayer)
{
// Disable for gamemasters with GM-mode enabled
if (GetOwner()->isGameMaster())
return;
if (achievement->flags & ACHIEVEMENT_FLAG_COUNTER || HasAchieved(achievement->ID))
return;
/*if (achievement->flags & ACHIEVEMENT_FLAG_SHOW_IN_GUILD_NEWS)
if (Guild* guild = sGuildMgr->GetGuildById(referencePlayer->GetGuildId()))
guild->GetNewsLog().AddNewEvent(GUILD_NEWS_PLAYER_ACHIEVEMENT, time(NULL), referencePlayer->GetGUID(), achievement->flags & ACHIEVEMENT_FLAG_SHOW_IN_GUILD_HEADER, achievement->ID);*/
if (HasAccountAchieved(achievement->ID))
{
CompletedAchievementData& ca = m_completedAchievements[achievement->ID];
ca.completedByThisCharacter = true;
return;
}
if (!GetOwner()->GetSession()->PlayerLoading())
SendAchievementEarned(achievement);
CompletedAchievementData& ca = m_completedAchievements[achievement->ID];
ca.completedByThisCharacter = true;
ca.date = time(NULL);
ca.first_guid = GetOwner()->GetGUIDLow();
ca.changed = true;
// Don't insert for ACHIEVEMENT_FLAG_REALM_FIRST_KILL since otherwise only the first group member would reach that achievement
// @TODO: where do set this instead?
if (!(achievement->flags & ACHIEVEMENT_FLAG_REALM_FIRST_KILL))
sAchievementMgr->SetRealmCompleted(achievement);
_achievementPoints += achievement->points;
UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_ACHIEVEMENT, 0, 0, 0, NULL, referencePlayer);
UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_EARN_ACHIEVEMENT_POINTS, achievement->points, 0, 0, NULL, referencePlayer);
// Reward items and titles if any
AchievementReward const* reward = sAchievementMgr->GetAchievementReward(achievement);
// No rewards
if (!reward)
return;
// Titles
//! Currently there's only one achievement that deals with gender-specific titles.
//! Since no common attributes were found, (not even in titleRewardFlags field)
//! we explicitly check by ID. Maybe in the future we could move the achievement_reward
//! condition fields to the condition system.
if (uint32 titleId = reward->titleId[achievement->ID == 1793 ? GetOwner()->getGender() : (GetOwner()->GetTeam() == ALLIANCE ? 0 : 1)])
if (CharTitlesEntry const* titleEntry = sCharTitlesStore.LookupEntry(titleId))
GetOwner()->SetTitle(titleEntry);
// Mail
if (reward->sender)
{
Item* item = reward->itemId ? Item::CreateItem(reward->itemId, 1, GetOwner()) : NULL;
int loc_idx = GetOwner()->GetSession()->GetSessionDbLocaleIndex();
// Subject and text
std::string subject = reward->subject;
std::string text = reward->text;
if (loc_idx >= 0)
{
if (AchievementRewardLocale const* loc = sAchievementMgr->GetAchievementRewardLocale(achievement))
{
ObjectMgr::GetLocaleString(loc->subject, loc_idx, subject);
ObjectMgr::GetLocaleString(loc->text, loc_idx, text);
}
}
MailDraft draft(subject, text);
SQLTransaction trans = CharacterDatabase.BeginTransaction();
if (item)
{
item->SetOwnerGUID(0);
// Save new item before send
item->SaveToDB(trans); // Save for prevent lost at next mail load, if send fail then item will deleted
// Item
draft.AddItem(item);
}
draft.SendMailTo(trans, GetOwner(), MailSender(MAIL_CREATURE, reward->sender));
CharacterDatabase.CommitTransaction(trans);
}
}
template<>
void AchievementMgr<Guild>::CompletedAchievement(AchievementEntry const* achievement, Player* referencePlayer)
{
if (achievement->flags & ACHIEVEMENT_FLAG_COUNTER || HasAchieved(achievement->ID))
return;
/*if (achievement->flags & ACHIEVEMENT_FLAG_SHOW_IN_GUILD_NEWS)
if (Guild* guild = sGuildMgr->GetGuildById(referencePlayer->GetGuildId()))
guild->GetNewsLog().AddNewEvent(GUILD_NEWS_GUILD_ACHIEVEMENT, time(NULL), 0, achievement->flags & ACHIEVEMENT_FLAG_SHOW_IN_GUILD_HEADER, achievement->ID);*/
SendAchievementEarned(achievement);
CompletedAchievementData& ca = m_completedAchievements[achievement->ID];
ca.date = time(NULL);
ca.changed = true;
if (achievement->flags & ACHIEVEMENT_FLAG_SHOW_GUILD_MEMBERS)
{
if (referencePlayer->GetGuildId() == GetOwner()->GetId())
ca.guids.insert(referencePlayer->GetGUID());
if (Group const* group = referencePlayer->GetGroup())
for (GroupReference const* ref = group->GetFirstMember(); ref != NULL; ref = ref->next())
if (Player const* groupMember = ref->GetSource())
if (groupMember->GetGuildId() == GetOwner()->GetId())
ca.guids.insert(groupMember->GetGUID());
}
sAchievementMgr->SetRealmCompleted(achievement);
_achievementPoints += achievement->points;
UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_ACHIEVEMENT, 0, 0, 0, NULL, referencePlayer);
UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_EARN_ACHIEVEMENT_POINTS, achievement->points, 0, 0, NULL, referencePlayer);
UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_EARN_GUILD_ACHIEVEMENT_POINTS, achievement->points, 0, 0, NULL, referencePlayer);
}
struct VisibleAchievementPred final
{
bool operator()(CompletedAchievementMap::value_type const& val) const
{
AchievementEntry const* achievement = sAchievementMgr->GetAchievement(val.first);
return achievement && !(achievement->flags & ACHIEVEMENT_FLAG_HIDDEN);
}
};
template<class T>
void AchievementMgr<T>::SendAllAchievementData(Player* /*receiver*/)
{
CriteriaProgressMap const &progressMap = GetCriteriaProgressMap();
VisibleAchievementPred isVisible;
size_t numCriteria = progressMap.size();
size_t numAchievements = std::count_if(m_completedAchievements.begin(), m_completedAchievements.end(), isVisible);
ObjectGuid guid = GetOwner()->GetGUID();
ObjectGuid counter;
WorldPacket data(SMSG_ALL_ACHIEVEMENT_DATA);
data.WriteBits(numAchievements, 20);
for (auto const &kvPair : m_completedAchievements)
{
if (!isVisible(kvPair))
continue;
ObjectGuid const firstAccountGuid = kvPair.second.first_guid;
data.WriteBitSeq<6, 1, 5, 3, 2, 7, 0, 4>(firstAccountGuid);
}
data.WriteBits(numCriteria, 19);
for (auto const &kvPair : progressMap)
{
counter = uint64(kvPair.second.counter);
data.WriteBitSeq<5>(counter);
data.WriteBitSeq<2, 4>(guid);
data.WriteBitSeq<1, 7>(counter);
data.WriteBitSeq<0, 1>(guid);
data.WriteBitSeq<3>(counter);
data.WriteBitSeq<5>(guid);
data.WriteBits(0, 4);
data.WriteBitSeq<0, 6, 4>(counter);
data.WriteBitSeq<7, 3, 6>(guid);
data.WriteBitSeq<2>(counter);
}
data.FlushBits();
for (auto const &kvPair : progressMap)
{
counter = uint64(kvPair.second.counter);
data.WriteByteSeq<1>(guid);
data << uint32(kvPair.first); // Criteria id
data.WriteByteSeq<7>(guid);
data.WriteByteSeq<5>(counter);
data << uint32(0); // Unk value from 5.4.0, always 0
data.WriteByteSeq<6>(guid);
data.WriteByteSeq<0>(counter);
data << uint32(227545947); // Unk value from 5.4.0, always 227545947
data.WriteByteSeq<2>(guid);
data.WriteByteSeq<2, 1>(counter);
data << uint32(0); // Unk value from 5.4.0, always 0
data.WriteByteSeq<3, 5>(guid);
data.WriteByteSeq<3>(counter);
data.WriteByteSeq<4>(guid);
data.WriteByteSeq<4, 7, 6>(counter);
data.WriteByteSeq<0>(guid);
}
for (auto const &kvPair : m_completedAchievements)
{
if (!isVisible(kvPair))
continue;
ObjectGuid firstAccountGuid = kvPair.second.first_guid;
data.WriteByteSeq<4, 6, 3, 0>(firstAccountGuid);
data << uint32(realmID); // Unk timer from 5.4.0 17399, sometimes 50724907
data.WriteByteSeq<1, 2>(firstAccountGuid);
data << uint32(secsToTimeBitFields(kvPair.second.date));
data.WriteByteSeq<7, 5>(firstAccountGuid);
data << uint32(realmID); // Unk timer from 5.4.0 17399, sometimes 50724907
data << uint32(kvPair.first);
}
SendPacket(&data);
WorldPacket data2(SMSG_ACCOUNT_CRITERIA_UPDATE_ALL);
ObjectGuid acc = GetOwner()->GetSession()->GetAccountId();
data2.WriteBits(numCriteria, 19);
for (auto const &kvPair : progressMap)
{
counter = uint64(kvPair.second.counter);
data2.WriteBitSeq<6, 3>(counter);
data2.WriteBitSeq<6, 1, 2, 3>(acc);
data2.WriteBits(0, 4);
data2.WriteBitSeq<5, 0, 7>(acc);
data2.WriteBitSeq<0, 7, 5>(counter);
data2.WriteBitSeq<4>(acc);
data2.WriteBitSeq<1, 4, 2>(counter);
}
data2.FlushBits();
for (auto const &kvPair : progressMap)
{
counter = uint64(kvPair.second.counter);
data2.WriteByteSeq<1>(acc);
data2 << uint32(0);
data2.WriteByteSeq<2>(acc);
data2.WriteByteSeq<6>(counter);
data2.WriteByteSeq<4>(acc);
data2.WriteByteSeq<7>(counter);
data2.WriteByteSeq<6, 7>(acc);
data2 << uint32(0);
data2.WriteByteSeq<5>(counter);
data2.WriteByteSeq<5>(acc);
data2.WriteByteSeq<2>(counter);
data2 << uint32(227545947);
data2 << uint32(kvPair.first);
data2.WriteByteSeq<0>(counter);
data2.WriteByteSeq<3>(acc);
data2.WriteByteSeq<1>(counter);
data2.WriteByteSeq<0>(acc);
data2.WriteByteSeq<4, 3>(counter);
}
SendPacket(&data2);
}
template<>
void AchievementMgr<Guild>::SendAllAchievementData(Player* receiver)
{
WorldPacket data(SMSG_GUILD_ACHIEVEMENT_DATA, m_completedAchievements.size() * (4 + 4) + 3);
data.WriteBits(m_completedAchievements.size(), 20);
ObjectGuid achievementee;
for (CompletedAchievementMap::const_iterator itr = m_completedAchievements.begin(); itr != m_completedAchievements.end(); ++itr)
{
data.WriteBit(0);
data.WriteBit(0);
data.WriteBit(0);
data.WriteBit(0);
data.WriteBit(0);
data.WriteBit(0);
data.WriteBit(0);
data.WriteBit(0);
}
data.FlushBits();
for (CompletedAchievementMap::const_iterator itr = m_completedAchievements.begin(); itr != m_completedAchievements.end(); ++itr)
{
data.WriteByte(0);
data << uint32(itr->first);
data << uint32(0); //0 or time ?
data.WriteByte(0);
data.WriteByte(0);
data.WriteByte(0);
data.WriteByte(0);
data << uint32(0);
data.WriteByte(0);
data.WriteByte(0);
data.AppendPackedTime(itr->second.date);
data.WriteByte(0);
}
receiver->GetSession()->SendPacket(&data);
}
template<>
void AchievementMgr<Player>::SendAchievementInfo(Player* receiver, uint32 /*achievementId = 0 */)
{
CriteriaProgressMap const &progressMap = GetCriteriaProgressMap();
ObjectGuid guid = GetOwner()->GetGUID();
ObjectGuid counter;
VisibleAchievementPred isVisible;
size_t numCriteria = progressMap.size();
size_t numAchievements = std::count_if(m_completedAchievements.begin(), m_completedAchievements.end(), isVisible);
WorldPacket data(SMSG_RESPOND_INSPECT_ACHIEVEMENTS);
data.WriteBits(numCriteria, 19);
data.WriteBits(numAchievements, 20);
for (auto const &kvPair : progressMap)
{
counter = kvPair.second.counter;
data.WriteBitSeq<4>(guid);
data.WriteBitSeq<2>(counter);
data.WriteBitSeq<0>(guid);
data.WriteBitSeq<4, 5, 1, 0>(counter);
data.WriteBitSeq<5>(guid);
data.WriteBitSeq<6, 3>(counter);
data.WriteBits(1, 4); // Criteria progress flags
data.WriteBitSeq<1, 7, 2, 3>(guid);
data.WriteBitSeq<7>(counter);
data.WriteBitSeq<6>(guid);
}
data.WriteBitSeq<6, 2>(guid);
for (auto const &kvPair : m_completedAchievements)
{
if (!isVisible(kvPair))
continue;
ObjectGuid const firstGuid = kvPair.second.first_guid;
data.WriteBitSeq<2, 3, 7, 5, 4, 6, 0, 1>(firstGuid);
}
data.WriteBitSeq<4, 7, 3, 0, 5, 1>(guid);
data.FlushBits();
for (auto const &kvPair : progressMap)
{
counter = kvPair.second.counter;
data.WriteByteSeq<5>(counter);
data.WriteByteSeq<0, 1>(guid);
data.WriteByteSeq<6>(counter);
data.WriteByteSeq<4>(guid);
data.WriteByteSeq<7, 0, 1>(counter);
data << uint32(0);
data.WriteByteSeq<4, 3>(counter);
data << uint32(kvPair.first); // criteria id
data << uint32(secsToTimeBitFields(kvPair.second.date));
data << uint32(227545947);
data.WriteByteSeq<2, 5, 6>(guid);
data.WriteByteSeq<2>(counter);
data.WriteByteSeq<7, 3>(guid);
}
data.WriteByteSeq<5, 3>(guid);
for (auto const &kvPair : m_completedAchievements)
{
if (!isVisible(kvPair))
continue;
ObjectGuid const firstGuid = kvPair.second.first_guid;
data.WriteByteSeq<0, 7, 6>(firstGuid);
data << uint32(0);
data << uint32(kvPair.first);
data << uint32(50397223);
data << uint32(secsToTimeBitFields(kvPair.second.date));
data.WriteByteSeq<4, 5, 1, 3, 2>(firstGuid);
}
data.WriteByteSeq<6, 7, 2, 1, 4, 0>(guid);
receiver->GetSession()->SendPacket(&data);
}
template<>
void AchievementMgr<Guild>::SendAchievementInfo(Player* receiver, uint32 achievementId /*= 0*/)
{
// Will send response to criteria progress request
AchievementCriteriaEntryList const* criteria = sAchievementMgr->GetAchievementCriteriaByAchievement(achievementId);
if (!criteria)
{
// Send empty packet
WorldPacket data(SMSG_GUILD_CRITERIA_DATA, 3);
data.WriteBits(0, 19);
data.FlushBits();
receiver->SendDirectMessage(&data);
return;
}
ObjectGuid counter, guid;
ByteBuffer criteriaData;
CriteriaProgressMap const &progressMap = GetCriteriaProgressMap();
WorldPacket data(SMSG_GUILD_CRITERIA_DATA, 3 + (2 + 8 + 5 * 4) * progressMap.size());
data.WriteBits(progressMap.size(), 19);
for (auto const &kvPair : progressMap)
{
auto const &criteriaId = kvPair.first;
auto const &progressData = kvPair.second;
counter = progressData.counter;
guid = progressData.CompletedGUID;
data.WriteBitSeq<3, 6>(counter);
data.WriteBitSeq<5, 4>(guid);
data.WriteBitSeq<2>(counter);
data.WriteBitSeq<0>(guid);
data.WriteBitSeq<7>(counter);
data.WriteBitSeq<6, 7, 3>(guid);
data.WriteBitSeq<5, 0>(counter);
data.WriteBitSeq<2>(guid);
data.WriteBitSeq<1, 4>(counter);
data.WriteBitSeq<1>(guid);
criteriaData.WriteByteSeq<4>(guid);
criteriaData << uint32(progressData.date); // Unknown date
criteriaData.WriteByteSeq<2, 0>(counter);
criteriaData << uint32(progressData.changed);
criteriaData.WriteByteSeq<7, 1>(guid);
criteriaData << uint32(criteriaId);
criteriaData << uint32(progressData.date); // Last update time (not packed!)
criteriaData.WriteByteSeq<6>(guid);
criteriaData.WriteByteSeq<1>(counter);
criteriaData.WriteByteSeq<3>(guid);
criteriaData.WriteByteSeq<4>(counter);
criteriaData << uint32(progressData.date); // Unknown date
criteriaData.WriteByteSeq<5, 3>(counter);
criteriaData.WriteByteSeq<0>(guid);
criteriaData.WriteByteSeq<6, 7>(counter);
criteriaData.WriteByteSeq<2, 5>(guid);
}
data.FlushBits();
data.append(criteriaData);
receiver->SendDirectMessage(&data);
}
template<class T>
bool AchievementMgr<T>::HasAchieved(uint32 achievementId) const
{
return m_completedAchievements.find(achievementId) != m_completedAchievements.end();
}
template<>
bool AchievementMgr<Player>::HasAchieved(uint32 achievementId) const
{
CompletedAchievementMap::const_iterator itr = m_completedAchievements.find(achievementId);
if (itr == m_completedAchievements.end())
return false;
return (*itr).second.completedByThisCharacter;
}
template<class T>
bool AchievementMgr<T>::HasAccountAchieved(uint32 achievementId) const
{
return m_completedAchievements.find(achievementId) != m_completedAchievements.end();
}
template<class T>
uint64 AchievementMgr<T>::GetFirstAchievedCharacterOnAccount(uint32 achievementId) const
{
CompletedAchievementMap::const_iterator itr = m_completedAchievements.find(achievementId);
if (itr == m_completedAchievements.end())
return 0LL;
return (*itr).second.first_guid;
}
template<class T>
bool AchievementMgr<T>::CanUpdateCriteria(CriteriaEntry const* criteria, uint64 miscValue1, uint64 miscValue2, uint64 miscValue3, Unit const* unit, Player* referencePlayer)
{
if (DisableMgr::IsDisabledFor(DISABLE_TYPE_ACHIEVEMENT_CRITERIA, criteria->ID, NULL))
{
TC_LOG_TRACE("achievement", "CanUpdateCriteria: (Id: %u Type %s) Disabled",
criteria->ID, AchievementGlobalMgr::GetCriteriaTypeString(criteria->type));
return false;
}
if (IsCompletedCriteria(criteria))
{
TC_LOG_TRACE("achievement", "CanUpdateCriteria: (Id: %u Type %s) Is Completed",
criteria->ID, AchievementGlobalMgr::GetCriteriaTypeString(criteria->type));
return false;
}
if (!RequirementsSatisfied(criteria, miscValue1, miscValue2, miscValue3, unit, referencePlayer))
{
TC_LOG_TRACE("achievement", "CanUpdateCriteria: (Id: %u Type %s) Requirements not satisfied",
criteria->ID, AchievementGlobalMgr::GetCriteriaTypeString(criteria->type));
return false;
}
if (!AdditionalRequirementsSatisfied(criteria, miscValue1, miscValue2, unit, referencePlayer))
{
TC_LOG_TRACE("achievement", "CanUpdateCriteria: (Id: %u Type %s) Additional requirements not satisfied",
criteria->ID, AchievementGlobalMgr::GetCriteriaTypeString(criteria->type));
return false;
}
if (!ConditionsSatisfied(criteria, referencePlayer))
{
TC_LOG_TRACE("achievement", "CanUpdateCriteria: (Id: %u Type %s) Conditions not satisfied",
criteria->ID, AchievementGlobalMgr::GetCriteriaTypeString(criteria->type));
return false;
}
return true;
}
template<class T>
bool AchievementMgr<T>::ConditionsSatisfied(CriteriaEntry const *criteria, Player* referencePlayer) const
{
/*
for (uint32 i = 0; i < MAX_CRITERIA_REQUIREMENTS; ++i)
{
if (!criteria->additionalRequirements[i].additionalRequirement_type)
continue;
switch (criteria->additionalRequirements[i].additionalRequirement_type)
{
case ACHIEVEMENT_CRITERIA_CONDITION_BG_MAP:
if (referencePlayer->GetMapId() != criteria->additionalRequirements[i].additionalRequirement_value)
return false;
break;
case ACHIEVEMENT_CRITERIA_CONDITION_NOT_IN_GROUP:
if (referencePlayer->GetGroup())
return false;
break;
case ACHIEVEMENT_CRITERIA_CONDITION_SERVER_SIDE_CHECK:
// FIXME: return criteria->scriptId != 0;
default:
break;
}
}
*/
return true;
}
template<class T>
bool AchievementMgr<T>::RequirementsSatisfied(CriteriaEntry const *achievementCriteria, uint64 miscValue1, uint64 miscValue2, uint64 miscValue3, Unit const *unit, Player* referencePlayer) const
{
switch (AchievementCriteriaTypes(achievementCriteria->type))
{
case ACHIEVEMENT_CRITERIA_TYPE_ACCEPTED_SUMMONINGS:
case ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_DAILY_QUEST:
case ACHIEVEMENT_CRITERIA_TYPE_CREATE_AUCTION:
case ACHIEVEMENT_CRITERIA_TYPE_FALL_WITHOUT_DYING:
case ACHIEVEMENT_CRITERIA_TYPE_FLIGHT_PATHS_TAKEN:
case ACHIEVEMENT_CRITERIA_TYPE_GET_KILLING_BLOWS:
case ACHIEVEMENT_CRITERIA_TYPE_GOLD_EARNED_BY_AUCTIONS:
case ACHIEVEMENT_CRITERIA_TYPE_GOLD_SPENT_AT_BARBER:
case ACHIEVEMENT_CRITERIA_TYPE_GOLD_SPENT_FOR_MAIL:
case ACHIEVEMENT_CRITERIA_TYPE_GOLD_SPENT_FOR_TALENTS:
case ACHIEVEMENT_CRITERIA_TYPE_GOLD_SPENT_FOR_TRAVELLING:
case ACHIEVEMENT_CRITERIA_TYPE_HIGHEST_AUCTION_BID:
case ACHIEVEMENT_CRITERIA_TYPE_HIGHEST_AUCTION_SOLD:
case ACHIEVEMENT_CRITERIA_TYPE_HIGHEST_HEALING_RECEIVED:
case ACHIEVEMENT_CRITERIA_TYPE_HIGHEST_HEAL_CASTED:
case ACHIEVEMENT_CRITERIA_TYPE_HIGHEST_HIT_DEALT:
case ACHIEVEMENT_CRITERIA_TYPE_HIGHEST_HIT_RECEIVED:
case ACHIEVEMENT_CRITERIA_TYPE_HONORABLE_KILL:
case ACHIEVEMENT_CRITERIA_TYPE_LOOT_MONEY:
case ACHIEVEMENT_CRITERIA_TYPE_LOSE_DUEL:
case ACHIEVEMENT_CRITERIA_TYPE_MONEY_FROM_QUEST_REWARD:
case ACHIEVEMENT_CRITERIA_TYPE_MONEY_FROM_VENDORS:
case ACHIEVEMENT_CRITERIA_TYPE_NUMBER_OF_TALENT_RESETS:
case ACHIEVEMENT_CRITERIA_TYPE_QUEST_ABANDONED:
case ACHIEVEMENT_CRITERIA_TYPE_REACH_BG_RATING:
case ACHIEVEMENT_CRITERIA_TYPE_REACH_GUILD_LEVEL:
case ACHIEVEMENT_CRITERIA_TYPE_ROLL_GREED:
case ACHIEVEMENT_CRITERIA_TYPE_ROLL_NEED:
case ACHIEVEMENT_CRITERIA_TYPE_SPECIAL_PVP_KILL:
case ACHIEVEMENT_CRITERIA_TYPE_TOTAL_DAMAGE_RECEIVED:
case ACHIEVEMENT_CRITERIA_TYPE_TOTAL_HEALING_RECEIVED:
case ACHIEVEMENT_CRITERIA_TYPE_USE_LFD_TO_GROUP_WITH_PLAYERS:
case ACHIEVEMENT_CRITERIA_TYPE_VISIT_BARBER_SHOP:
case ACHIEVEMENT_CRITERIA_TYPE_WIN_DUEL:
case ACHIEVEMENT_CRITERIA_TYPE_WIN_RATED_ARENA:
case ACHIEVEMENT_CRITERIA_TYPE_WIN_RATED_BATTLEGROUND:
case ACHIEVEMENT_CRITERIA_TYPE_WON_AUCTIONS:
if (!miscValue1)
return false;
break;
case ACHIEVEMENT_CRITERIA_TYPE_BUY_BANK_SLOT:
case ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_DAILY_QUEST_DAILY:
case ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_QUEST_COUNT:
case ACHIEVEMENT_CRITERIA_TYPE_EARNED_PVP_TITLE:
case ACHIEVEMENT_CRITERIA_TYPE_EARN_ACHIEVEMENT_POINTS:
case ACHIEVEMENT_CRITERIA_TYPE_GAIN_EXALTED_REPUTATION:
case ACHIEVEMENT_CRITERIA_TYPE_GAIN_HONORED_REPUTATION:
case ACHIEVEMENT_CRITERIA_TYPE_GAIN_REVERED_REPUTATION:
case ACHIEVEMENT_CRITERIA_TYPE_HIGHEST_GOLD_VALUE_OWNED:
case ACHIEVEMENT_CRITERIA_TYPE_HIGHEST_PERSONAL_RATING:
case ACHIEVEMENT_CRITERIA_TYPE_HIGHEST_TEAM_RATING:
case ACHIEVEMENT_CRITERIA_TYPE_KNOWN_FACTIONS:
case ACHIEVEMENT_CRITERIA_TYPE_REACH_LEVEL:
break;
case ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_ACHIEVEMENT:
if (m_completedAchievements.find(achievementCriteria->complete_achievement.linkedAchievement) == m_completedAchievements.end())
return false;
break;
case ACHIEVEMENT_CRITERIA_TYPE_WIN_BG:
if (!miscValue1 || !referencePlayer || achievementCriteria->win_bg.bgMapID != referencePlayer->GetMapId())
return false;
break;
case ACHIEVEMENT_CRITERIA_TYPE_KILL_CREATURE:
if (!miscValue1 || achievementCriteria->kill_creature.creatureID != miscValue1)
return false;
break;
case ACHIEVEMENT_CRITERIA_TYPE_REACH_SKILL_LEVEL:
// update at loading or specific skill update
if (miscValue1 && miscValue1 != achievementCriteria->reach_skill_level.skillID)
return false;
break;
case ACHIEVEMENT_CRITERIA_TYPE_LEARN_SKILL_LEVEL:
// update at loading or specific skill update
if (miscValue1 && miscValue1 != achievementCriteria->learn_skill_level.skillID)
return false;
break;
case ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_QUESTS_IN_ZONE:
if (miscValue1 && miscValue1 != achievementCriteria->complete_quests_in_zone.zoneID)
return false;
break;
case ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_BATTLEGROUND:
if (!miscValue1 || !referencePlayer || referencePlayer->GetMapId() != achievementCriteria->complete_battleground.mapID)
return false;
break;
case ACHIEVEMENT_CRITERIA_TYPE_DEATH_AT_MAP:
if (!miscValue1 || !referencePlayer ||referencePlayer->GetMapId() != achievementCriteria->death_at_map.mapID)
return false;
break;
case ACHIEVEMENT_CRITERIA_TYPE_DEATH:
{
if (!miscValue1)
return false;
/*if (!referencePlayer)
return false;
// skip wrong arena achievements, if not achievIdByArenaSlot then normal total death counter
bool notfit = false;
for (int j = 0; j < MAX_ARENA_SLOT; ++j)
{
if (achievIdByArenaSlot[j] == achievementCriteria->achievement)
{
Battleground* bg = referencePlayer->GetBattleground();
if (!bg || !bg->isArena() || Arena::GetSlotByType(bg->GetArenaType()) != j)
notfit = true;
break;
}
}
if (notfit)
return false;*/
break;
}
case ACHIEVEMENT_CRITERIA_TYPE_DEATH_IN_DUNGEON:
{
if (!miscValue1)
return false;
/*
if (!referencePlayer)
return false;
Map const* map = referencePlayer->IsInWorld() ? referencePlayer->GetMap() : sMapMgr->FindMap(referencePlayer->GetMapId(), referencePlayer->GetInstanceId());
if (!map || !map->IsDungeon())
return false;
// search case
bool found = false;
for (int j = 0; achievIdForDungeon[j][0]; ++j)
{
if (achievIdForDungeon[j][0] == achievementCriteria->achievement)
{
if (map->IsRaid())
{
// if raid accepted (ignore difficulty)
if (!achievIdForDungeon[j][2])
break; // for
}
else if (referencePlayer->GetDungeonDifficulty() == REGULAR_DIFFICULTY)
{
// dungeon in normal mode accepted
if (!achievIdForDungeon[j][1])
break; // for
}
else
{
// dungeon in heroic mode accepted
if (!achievIdForDungeon[j][3])
break; // for
}
found = true;
break; // for
}
}
if (!found)
return false;
//FIXME: work only for instances where max == min for players
if (((InstanceMap*)map)->GetMaxPlayers() != achievementCriteria->death_in_dungeon.manLimit)
return false;*/
break;
}
case ACHIEVEMENT_CRITERIA_TYPE_KILLED_BY_CREATURE:
if (!miscValue1 || miscValue1 != achievementCriteria->killed_by_creature.creatureEntry)
return false;
break;
case ACHIEVEMENT_CRITERIA_TYPE_KILLED_BY_PLAYER:
if (!miscValue1 || !unit || unit->GetTypeId() != TYPEID_PLAYER)
return false;
break;
case ACHIEVEMENT_CRITERIA_TYPE_DEATHS_FROM:
if (!miscValue1 || miscValue2 != achievementCriteria->death_from.type)
return false;
break;
case ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_QUEST:
{
// if miscValues != 0, it contains the questID.
if (miscValue1)
{
if (miscValue1 != achievementCriteria->complete_quest.questID)
return false;
}
else
{
// login case.
if (!referencePlayer || !referencePlayer->GetQuestRewardStatus(achievementCriteria->complete_quest.questID))
return false;
}
if (AchievementCriteriaDataSet const* data = sAchievementMgr->GetCriteriaDataSet(achievementCriteria))
if (!data->Meets(referencePlayer, unit))
return false;
break;
}
case ACHIEVEMENT_CRITERIA_TYPE_BE_SPELL_TARGET:
case ACHIEVEMENT_CRITERIA_TYPE_BE_SPELL_TARGET2:
if (!miscValue1 || miscValue1 != achievementCriteria->be_spell_target.spellID)
return false;
break;
case ACHIEVEMENT_CRITERIA_TYPE_CAST_SPELL:
case ACHIEVEMENT_CRITERIA_TYPE_CAST_SPELL2:
if (!miscValue1 || miscValue1 != achievementCriteria->cast_spell.spellID)
return false;
break;
case ACHIEVEMENT_CRITERIA_TYPE_LEARN_SPELL:
if (miscValue1 && miscValue1 != achievementCriteria->learn_spell.spellID)
return false;
if (!referencePlayer || !referencePlayer->HasSpell(achievementCriteria->learn_spell.spellID))
return false;
break;
case ACHIEVEMENT_CRITERIA_TYPE_LOOT_TYPE:
// miscValue1 = itemId - miscValue2 = count of item loot
// miscValue3 = loot_type (note: 0 = LOOT_CORPSE and then it ignored)
if (!miscValue1 || !miscValue2 || !miscValue3 || miscValue3 != achievementCriteria->loot_type.lootType)
return false;
break;
case ACHIEVEMENT_CRITERIA_TYPE_OWN_ITEM:
if (miscValue1 && achievementCriteria->own_item.itemID != miscValue1)
return false;
break;
case ACHIEVEMENT_CRITERIA_TYPE_USE_ITEM:
if (!miscValue1 || achievementCriteria->use_item.itemID != miscValue1)
return false;
break;
case ACHIEVEMENT_CRITERIA_TYPE_LOOT_ITEM:
if (!miscValue1 || miscValue1 != achievementCriteria->own_item.itemID)
return false;
break;
case ACHIEVEMENT_CRITERIA_TYPE_EXPLORE_AREA:
{
if (!referencePlayer)
return false;
WorldMapOverlayEntry const* worldOverlayEntry = sWorldMapOverlayStore.LookupEntry(achievementCriteria->explore_area.areaReference);
if (!worldOverlayEntry)
break;
bool matchFound = false;
for (int j = 0; j < MAX_WORLD_MAP_OVERLAY_AREA_IDX; ++j)
{
uint32 area_id = worldOverlayEntry->areatableID[j];
if (!area_id) // array have 0 only in empty tail
break;
int32 exploreFlag = GetAreaFlagByAreaID(area_id);
// Hack: Explore Southern Barrens
if (achievementCriteria->explore_area.areaReference == 3009)
exploreFlag = 515;
if (exploreFlag < 0)
continue;
uint32 playerIndexOffset = uint32(exploreFlag) / 32;
uint32 mask = 1 << (uint32(exploreFlag) % 32);
if (referencePlayer->GetUInt32Value(PLAYER_EXPLORED_ZONES_1 + playerIndexOffset) & mask)
{
matchFound = true;
break;
}
}
if (!matchFound)
return false;
break;
}
case ACHIEVEMENT_CRITERIA_TYPE_GAIN_REPUTATION:
if (miscValue1 && miscValue1 != achievementCriteria->gain_reputation.factionID)
return false;
break;
case ACHIEVEMENT_CRITERIA_TYPE_EQUIP_EPIC_ITEM:
// miscValue1 = itemid miscValue2 = itemSlot
if (!miscValue1 || miscValue2 != achievementCriteria->equip_epic_item.itemSlot)
return false;
break;
case ACHIEVEMENT_CRITERIA_TYPE_ROLL_NEED_ON_LOOT:
case ACHIEVEMENT_CRITERIA_TYPE_ROLL_GREED_ON_LOOT:
{
// miscValue1 = itemid miscValue2 = diced value
if (!miscValue1 || miscValue2 != achievementCriteria->roll_greed_on_loot.rollValue)
return false;
ItemTemplate const* proto = sObjectMgr->GetItemTemplate(uint32(miscValue1));
if (!proto)
return false;
break;
}
case ACHIEVEMENT_CRITERIA_TYPE_DO_EMOTE:
if (!miscValue1 || miscValue1 != achievementCriteria->do_emote.emoteID)
return false;
break;
case ACHIEVEMENT_CRITERIA_TYPE_DAMAGE_DONE:
case ACHIEVEMENT_CRITERIA_TYPE_HEALING_DONE:
if (!miscValue1)
return false;
/*if (!referencePlayer)
return false;
if (achievementCriteria->additionalRequirements[0].additionalRequirement_type == ACHIEVEMENT_CRITERIA_CONDITION_BG_MAP)
{
if (referencePlayer->GetMapId() != achievementCriteria->additionalRequirements[0].additionalRequirement_value)
return false;
*/
// map specific case (BG in fact) expected player targeted damage/heal
if (!unit || unit->GetTypeId() != TYPEID_PLAYER)
return false;
//}
break;
case ACHIEVEMENT_CRITERIA_TYPE_EQUIP_ITEM:
// miscValue1 = item_id
if (!miscValue1 || miscValue1 != achievementCriteria->equip_item.itemID)
return false;
break;
case ACHIEVEMENT_CRITERIA_TYPE_USE_GAMEOBJECT:
if (!miscValue1 || miscValue1 != achievementCriteria->use_gameobject.goEntry)
return false;
break;
case ACHIEVEMENT_CRITERIA_TYPE_FISH_IN_GAMEOBJECT:
if (!miscValue1 || miscValue1 != achievementCriteria->fish_in_gameobject.goEntry)
return false;
break;
case ACHIEVEMENT_CRITERIA_TYPE_LEARN_SKILLLINE_SPELLS:
if (miscValue1 && miscValue1 != achievementCriteria->learn_skillline_spell.skillLine)
return false;
break;
case ACHIEVEMENT_CRITERIA_TYPE_LOOT_EPIC_ITEM:
case ACHIEVEMENT_CRITERIA_TYPE_RECEIVE_EPIC_ITEM:
{
if (!miscValue1)
return false;
ItemTemplate const* proto = sObjectMgr->GetItemTemplate(uint32(miscValue1));
if (!proto)
return false;
break;
}
case ACHIEVEMENT_CRITERIA_TYPE_LEARN_SKILL_LINE:
if (miscValue1 && miscValue1 != achievementCriteria->learn_skill_line.skillLine)
return false;
break;
case ACHIEVEMENT_CRITERIA_TYPE_HK_CLASS:
if (!miscValue1 || miscValue1 != achievementCriteria->hk_class.classID)
return false;
break;
case ACHIEVEMENT_CRITERIA_TYPE_HK_RACE:
if (!miscValue1 || miscValue1 != achievementCriteria->hk_race.raceID)
return false;
break;
case ACHIEVEMENT_CRITERIA_TYPE_BG_OBJECTIVE_CAPTURE:
if (!miscValue1 || miscValue1 != achievementCriteria->bg_objective.objectiveId)
return false;
break;
case ACHIEVEMENT_CRITERIA_TYPE_HONORABLE_KILL_AT_AREA:
if (!miscValue1 || miscValue1 != achievementCriteria->honorable_kill_at_area.areaID)
return false;
break;
case ACHIEVEMENT_CRITERIA_TYPE_CURRENCY:
if (!miscValue1 || !miscValue2 || int64(miscValue2) < 0
|| miscValue1 != achievementCriteria->currencyGain.currency)
return false;
break;
case ACHIEVEMENT_CRITERIA_TYPE_WIN_ARENA:
if (miscValue1 != achievementCriteria->win_arena.mapID)
return false;
break;
case ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_GUILD_CHALLENGE_TYPE:
//if (miscValue1 != achievementCriteria->guild_challenge_complete_type.challenge_type)
// return false;
break;
default:
break;
}
return true;
}
template<class T>
bool AchievementMgr<T>::AdditionalRequirementsSatisfied(CriteriaEntry const *criteria, uint64 miscValue1, uint64 /*miscValue2*/, Unit const* unit, Player* referencePlayer) const
{
ModifierTreeEntry const* condition = sModifierTreeStore.LookupEntry(criteria->modifierTreeId);
if (!condition)
return true;
ModifierTreeEntryList const* list = sAchievementMgr->GetModifierTreeByModifierId(condition->ID);
if (!list)
return true;
for (ModifierTreeEntryList::const_iterator iter = list->begin(); iter != list->end(); iter++)
{
ModifierTreeEntry const* tree = (*iter);
uint32 reqType = tree->conditionType;
uint32 reqValue = tree->conditionValue[0];
switch (AchievementCriteriaAdditionalCondition(reqType))
{
case ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_SOURCE_DRUNK_VALUE: // 1
{
if (!referencePlayer || (referencePlayer->GetDrunkValue() < reqValue))
return false;
break;
}
case ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_SERVER_SIDE_CHECK:
{
#if 0
if (!referencePlayer)
return criteria->scriptId != 0;
#endif
switch (reqValue)
{
case 924: // Alliance faction
case 11835: // Alliance faction
return referencePlayer->GetTeam() == ALLIANCE;
case 923: // Horde faction
case 11836: // Horde faction
return referencePlayer->GetTeam() == HORDE;
#if 0
default:
return criteria->scriptId != 0;
#endif
}
break;
}
case ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_ITEM_LEVEL: // 3
{
ItemTemplate const* pItem = sObjectMgr->GetItemTemplate(miscValue1);
if (!pItem)
return false;
if (pItem->ItemLevel < reqValue)
return false;
break;
}
case ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_TARGET_CREATURE_ENTRY: // 4
if (!unit || unit->GetEntry() != reqValue)
return false;
break;
case ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_TARGET_MUST_BE_PLAYER: // 5
if (!unit || !unit->IsInWorld() || unit->GetTypeId() != TYPEID_PLAYER)
return false;
break;
case ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_TARGET_MUST_BE_DEAD: // 6
if (!unit || !unit->IsInWorld() || unit->IsAlive())
return false;
break;
case ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_TARGET_MUST_BE_ENEMY: // 7
if (!referencePlayer)
return false;
if (!unit || !unit->IsInWorld() || !referencePlayer->IsHostileTo(unit))
return false;
break;
case ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_SOURCE_HAS_AURA: // 8
if (!referencePlayer->HasAura(reqValue))
return false;
break;
case ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_TARGET_HAS_AURA: // 10
if (!unit || !unit->HasAura(reqValue))
return false;
break;
case ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_TARGET_HAS_AURA_TYPE: // 11
if (!unit || !unit->HasAuraType(AuraType(reqValue)))
return false;
break;
case ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_ITEM_QUALITY_MIN: // 14
{
// miscValue1 is itemid
ItemTemplate const * const item = sObjectMgr->GetItemTemplate(uint32(miscValue1));
if (!item || item->Quality < reqValue)
return false;
break;
}
case ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_ITEM_QUALITY_EQUALS: // 15
{
// miscValue1 is itemid
ItemTemplate const * const item = sObjectMgr->GetItemTemplate(uint32(miscValue1));
if (!item || item->Quality < reqValue)
return false;
break;
}
case ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_SOURCE_AREA_OR_ZONE: // 17
{
if (!referencePlayer)
return false;
uint32 zoneId, areaId;
referencePlayer->GetZoneAndAreaId(zoneId, areaId);
if (zoneId != reqValue && areaId != reqValue)
return false;
break;
}
case ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_TARGET_AREA_OR_ZONE: // 18
{
if (!unit)
return false;
uint32 zoneId, areaId;
unit->GetZoneAndAreaId(zoneId, areaId);
if (zoneId != reqValue && areaId != reqValue)
return false;
break;
}
case ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_MAP_DIFFICULTY: // 20
{
if (!referencePlayer)
return false;
if (Map* pMap = referencePlayer->GetMap())
{
if (pMap->IsNonRaidDungeon()
|| pMap->IsRaid())
{
if (pMap->GetDifficulty() < Difficulty(reqValue))
return false;
}
else
return false;
}
else
return false;
break;
}
case ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_TARGET_CREATURE_YIELDS_XP: // 21
if (!unit || unit->GetTypeId() != TYPEID_UNIT || !referencePlayer || !referencePlayer->isHonorOrXPTarget(unit))
return false;
break;
case ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_ARENA_TYPE: // 24
{
if (!referencePlayer)
return false;
Battleground const * const bg = referencePlayer->GetBattleground();
if (!bg || !bg->isArena() || bg->GetArenaType() != reqValue)
return false;
break;
}
case ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_SOURCE_RACE: // 25
if (!referencePlayer || (referencePlayer->getRace() != reqValue))
return false;
break;
case ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_SOURCE_CLASS: // 26
if (!referencePlayer || (referencePlayer->getClass() != reqValue))
return false;
break;
case ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_TARGET_RACE: // 27
if (!unit || !unit->IsInWorld() || unit->GetTypeId() != TYPEID_PLAYER || unit->getRace() != reqValue)
return false;
break;
case ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_TARGET_CLASS: // 28
if (!unit || !unit->IsInWorld() || unit->GetTypeId() != TYPEID_PLAYER || unit->getClass() != reqValue)
return false;
break;
case ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_MAX_GROUP_MEMBERS: // 29
if (!referencePlayer || (referencePlayer->GetGroup() && referencePlayer->GetGroup()->GetMembersCount() >= reqValue))
return false;
break;
case ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_TARGET_CREATURE_TYPE: // 30
{
if (!unit)
return false;
Creature const * const creature = unit->ToCreature();
if (!creature || creature->GetCreatureType() != reqValue)
return false;
break;
}
case ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_SOURCE_MAP: // 32
if (!referencePlayer || (referencePlayer->GetMapId() != reqValue))
return false;
break;
case ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_ITEM_CLASS: // 33
{
ItemTemplate const* pItem = sObjectMgr->GetItemTemplate(miscValue1);
if (!pItem)
return false;
if (pItem->Class != reqValue)
return false;
break;
}
case ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_ITEM_SUBCLASS: // 34
{
ItemTemplate const* pItem = sObjectMgr->GetItemTemplate(miscValue1);
if (!pItem)
return false;
if (pItem->SubClass != reqValue)
return false;
break;
}
case ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_COMPLETE_QUEST_NOT_IN_GROUP: // 35
// miscValue is questid
if (!referencePlayer || !referencePlayer->IsQuestRewarded(uint32(miscValue1)) || referencePlayer->GetGroup())
return false;
break;
case ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_MIN_PERSONAL_RATING: // 37
{
if (miscValue1 <= reqValue)
return false;
break;
}
case ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_TITLE_BIT_INDEX: // 38
// miscValue1 is title's bit index
if (miscValue1 != reqValue)
return false;
break;
case ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_SOURCE_LEVEL: // 39
if (!referencePlayer || (referencePlayer->getLevel() != reqValue))
return false;
break;
case ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_TARGET_LEVEL: // 40
if (!unit || !unit->IsInWorld() || unit->getLevel() != reqValue)
return false;
break;
case ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_SOURCE_ZONE: // 41
if (!referencePlayer || referencePlayer->GetZoneId() != reqValue)
return false;
break;
case ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_TARGET_HEALTH_PERCENT_BELOW: // 46
if (!unit || !unit->IsInWorld() || unit->GetHealthPct() >= reqValue)
return false;
break;
case ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_MIN_ACHIEVEMENT_POINTS: // 56
if (!referencePlayer || (referencePlayer->GetAchievementMgr().GetAchievementPoints() < reqValue))
return false;
break;
#if 0
case ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_REQUIRES_LFG_GROUP: // 58
if (!referencePlayer || !referencePlayer->inRandomLfgDungeon())
return false;
break;
#endif
case ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_REQUIRES_GUILD_GROUP: // 61
{
if (!referencePlayer)
return false;
Group* pGroup = referencePlayer->GetGroup();
if (!pGroup)
return false;
break;
}
case ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_GUILD_REPUTATION: // 62
{
if (!referencePlayer)
return false;
if (uint32(referencePlayer->GetReputationMgr().GetReputation(1168)) < reqValue) // 1168 = Guild faction
return false;
break;
}
case ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_RATED_BATTLEGROUND: // 63
{
if (!referencePlayer)
return false;
Battleground const * const bg = referencePlayer->GetBattleground();
if (!bg || !bg->isRated())
return false;
break;
}
case ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_PROJECT_RARITY: // 65
{
if (!miscValue1)
return false;
break;
}
case ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_PROJECT_RACE: // 66
{
if (!miscValue1)
return false;
break;
}
default:
break;
}
}
return true;
}
char const* AchievementGlobalMgr::GetCriteriaTypeString(uint32 type)
{
return GetCriteriaTypeString(AchievementCriteriaTypes(type));
}
char const* AchievementGlobalMgr::GetCriteriaTypeString(AchievementCriteriaTypes type)
{
switch (type)
{
case ACHIEVEMENT_CRITERIA_TYPE_KILL_CREATURE:
return "KILL_CREATURE";
case ACHIEVEMENT_CRITERIA_TYPE_WIN_BG:
return "TYPE_WIN_BG";
case ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_ARCHAEOLOGY_PROJECTS:
return "COMPLETE_RESEARCH";
case ACHIEVEMENT_CRITERIA_TYPE_REACH_LEVEL:
return "REACH_LEVEL";
case ACHIEVEMENT_CRITERIA_TYPE_REACH_SKILL_LEVEL:
return "REACH_SKILL_LEVEL";
case ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_ACHIEVEMENT:
return "COMPLETE_ACHIEVEMENT";
case ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_QUEST_COUNT:
return "COMPLETE_QUEST_COUNT";
case ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_DAILY_QUEST_DAILY:
return "COMPLETE_DAILY_QUEST_DAILY";
case ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_QUESTS_IN_ZONE:
return "COMPLETE_QUESTS_IN_ZONE";
case ACHIEVEMENT_CRITERIA_TYPE_CURRENCY:
return "CURRENCY";
case ACHIEVEMENT_CRITERIA_TYPE_DAMAGE_DONE:
return "DAMAGE_DONE";
case ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_DAILY_QUEST:
return "COMPLETE_DAILY_QUEST";
case ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_BATTLEGROUND:
return "COMPLETE_BATTLEGROUND";
case ACHIEVEMENT_CRITERIA_TYPE_DEATH_AT_MAP:
return "DEATH_AT_MAP";
case ACHIEVEMENT_CRITERIA_TYPE_DEATH:
return "DEATH";
case ACHIEVEMENT_CRITERIA_TYPE_DEATH_IN_DUNGEON:
return "DEATH_IN_DUNGEON";
case ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_RAID:
return "COMPLETE_RAID";
case ACHIEVEMENT_CRITERIA_TYPE_KILLED_BY_CREATURE:
return "KILLED_BY_CREATURE";
case ACHIEVEMENT_CRITERIA_TYPE_KILLED_BY_PLAYER:
return "KILLED_BY_PLAYER";
case ACHIEVEMENT_CRITERIA_TYPE_FALL_WITHOUT_DYING:
return "FALL_WITHOUT_DYING";
case ACHIEVEMENT_CRITERIA_TYPE_DEATHS_FROM:
return "DEATHS_FROM";
case ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_QUEST:
return "COMPLETE_QUEST";
case ACHIEVEMENT_CRITERIA_TYPE_BE_SPELL_TARGET:
return "BE_SPELL_TARGET";
case ACHIEVEMENT_CRITERIA_TYPE_CAST_SPELL:
return "CAST_SPELL";
case ACHIEVEMENT_CRITERIA_TYPE_BG_OBJECTIVE_CAPTURE:
return "BG_OBJECTIVE_CAPTURE";
case ACHIEVEMENT_CRITERIA_TYPE_HONORABLE_KILL_AT_AREA:
return "HONORABLE_KILL_AT_AREA";
case ACHIEVEMENT_CRITERIA_TYPE_WIN_ARENA:
return "WIN_ARENA";
case ACHIEVEMENT_CRITERIA_TYPE_PLAY_ARENA:
return "PLAY_ARENA";
case ACHIEVEMENT_CRITERIA_TYPE_LEARN_SPELL:
return "LEARN_SPELL";
case ACHIEVEMENT_CRITERIA_TYPE_HONORABLE_KILL:
return "HONORABLE_KILL";
case ACHIEVEMENT_CRITERIA_TYPE_OWN_ITEM:
return "OWN_ITEM";
case ACHIEVEMENT_CRITERIA_TYPE_WIN_RATED_ARENA:
return "WIN_RATED_ARENA";
case ACHIEVEMENT_CRITERIA_TYPE_HIGHEST_TEAM_RATING:
return "HIGHEST_TEAM_RATING";
case ACHIEVEMENT_CRITERIA_TYPE_HIGHEST_PERSONAL_RATING:
return "HIGHEST_PERSONAL_RATING";
case ACHIEVEMENT_CRITERIA_TYPE_LEARN_SKILL_LEVEL:
return "LEARN_SKILL_LEVEL";
case ACHIEVEMENT_CRITERIA_TYPE_USE_ITEM:
return "USE_ITEM";
case ACHIEVEMENT_CRITERIA_TYPE_LOOT_ITEM:
return "LOOT_ITEM";
case ACHIEVEMENT_CRITERIA_TYPE_EXPLORE_AREA:
return "EXPLORE_AREA";
case ACHIEVEMENT_CRITERIA_TYPE_OWN_RANK:
return "OWN_RANK";
case ACHIEVEMENT_CRITERIA_TYPE_BUY_BANK_SLOT:
return "BUY_BANK_SLOT";
case ACHIEVEMENT_CRITERIA_TYPE_GAIN_REPUTATION:
return "GAIN_REPUTATION";
case ACHIEVEMENT_CRITERIA_TYPE_GAIN_EXALTED_REPUTATION:
return "GAIN_EXALTED_REPUTATION";
case ACHIEVEMENT_CRITERIA_TYPE_VISIT_BARBER_SHOP:
return "VISIT_BARBER_SHOP";
case ACHIEVEMENT_CRITERIA_TYPE_EQUIP_EPIC_ITEM:
return "EQUIP_EPIC_ITEM";
case ACHIEVEMENT_CRITERIA_TYPE_ROLL_NEED_ON_LOOT:
return "ROLL_NEED_ON_LOOT";
case ACHIEVEMENT_CRITERIA_TYPE_ROLL_GREED_ON_LOOT:
return "GREED_ON_LOOT";
case ACHIEVEMENT_CRITERIA_TYPE_HK_CLASS:
return "HK_CLASS";
case ACHIEVEMENT_CRITERIA_TYPE_HK_RACE:
return "HK_RACE";
case ACHIEVEMENT_CRITERIA_TYPE_DO_EMOTE:
return "DO_EMOTE";
case ACHIEVEMENT_CRITERIA_TYPE_HEALING_DONE:
return "HEALING_DONE";
case ACHIEVEMENT_CRITERIA_TYPE_GET_KILLING_BLOWS:
return "GET_KILLING_BLOWS";
case ACHIEVEMENT_CRITERIA_TYPE_EQUIP_ITEM:
return "EQUIP_ITEM";
case ACHIEVEMENT_CRITERIA_TYPE_MONEY_FROM_VENDORS:
return "MONEY_FROM_VENDORS";
case ACHIEVEMENT_CRITERIA_TYPE_GOLD_SPENT_FOR_TALENTS:
return "GOLD_SPENT_FOR_TALENTS";
case ACHIEVEMENT_CRITERIA_TYPE_NUMBER_OF_TALENT_RESETS:
return "NUMBER_OF_TALENT_RESETS";
case ACHIEVEMENT_CRITERIA_TYPE_MONEY_FROM_QUEST_REWARD:
return "MONEY_FROM_QUEST_REWARD";
case ACHIEVEMENT_CRITERIA_TYPE_GOLD_SPENT_FOR_TRAVELLING:
return "GOLD_SPENT_FOR_TRAVELLING";
case ACHIEVEMENT_CRITERIA_TYPE_GOLD_SPENT_AT_BARBER:
return "GOLD_SPENT_AT_BARBER";
case ACHIEVEMENT_CRITERIA_TYPE_GOLD_SPENT_FOR_MAIL:
return "GOLD_SPENT_FOR_MAIL";
case ACHIEVEMENT_CRITERIA_TYPE_LOOT_MONEY:
return "LOOT_MONEY";
case ACHIEVEMENT_CRITERIA_TYPE_USE_GAMEOBJECT:
return "USE_GAMEOBJECT";
case ACHIEVEMENT_CRITERIA_TYPE_BE_SPELL_TARGET2:
return "BE_SPELL_TARGET2";
case ACHIEVEMENT_CRITERIA_TYPE_SPECIAL_PVP_KILL:
return "SPECIAL_PVP_KILL";
case ACHIEVEMENT_CRITERIA_TYPE_FISH_IN_GAMEOBJECT:
return "FISH_IN_GAMEOBJECT";
case ACHIEVEMENT_CRITERIA_TYPE_EARNED_PVP_TITLE:
return "EARNED_PVP_TITLE";
case ACHIEVEMENT_CRITERIA_TYPE_LEARN_SKILLLINE_SPELLS:
return "LEARN_SKILLLINE_SPELLS";
case ACHIEVEMENT_CRITERIA_TYPE_WIN_DUEL:
return "WIN_DUEL";
case ACHIEVEMENT_CRITERIA_TYPE_LOSE_DUEL:
return "LOSE_DUEL";
case ACHIEVEMENT_CRITERIA_TYPE_KILL_CREATURE_TYPE:
return "KILL_CREATURE_TYPE";
case ACHIEVEMENT_CRITERIA_TYPE_GOLD_EARNED_BY_AUCTIONS:
return "GOLD_EARNED_BY_AUCTIONS";
case ACHIEVEMENT_CRITERIA_TYPE_CREATE_AUCTION:
return "CREATE_AUCTION";
case ACHIEVEMENT_CRITERIA_TYPE_HIGHEST_AUCTION_BID:
return "HIGHEST_AUCTION_BID";
case ACHIEVEMENT_CRITERIA_TYPE_WON_AUCTIONS:
return "WON_AUCTIONS";
case ACHIEVEMENT_CRITERIA_TYPE_HIGHEST_AUCTION_SOLD:
return "HIGHEST_AUCTION_SOLD";
case ACHIEVEMENT_CRITERIA_TYPE_HIGHEST_GOLD_VALUE_OWNED:
return "HIGHEST_GOLD_VALUE_OWNED";
case ACHIEVEMENT_CRITERIA_TYPE_GAIN_REVERED_REPUTATION:
return "GAIN_REVERED_REPUTATION";
case ACHIEVEMENT_CRITERIA_TYPE_GAIN_HONORED_REPUTATION:
return "GAIN_HONORED_REPUTATION";
case ACHIEVEMENT_CRITERIA_TYPE_KNOWN_FACTIONS:
return "KNOWN_FACTIONS";
case ACHIEVEMENT_CRITERIA_TYPE_LOOT_EPIC_ITEM:
return "LOOT_EPIC_ITEM";
case ACHIEVEMENT_CRITERIA_TYPE_RECEIVE_EPIC_ITEM:
return "RECEIVE_EPIC_ITEM";
case ACHIEVEMENT_CRITERIA_TYPE_ROLL_NEED:
return "ROLL_NEED";
case ACHIEVEMENT_CRITERIA_TYPE_ROLL_GREED:
return "ROLL_GREED";
case ACHIEVEMENT_CRITERIA_TYPE_HIGHEST_HIT_DEALT:
return "HIT_DEALT";
case ACHIEVEMENT_CRITERIA_TYPE_HIGHEST_HIT_RECEIVED:
return "HIT_RECEIVED";
case ACHIEVEMENT_CRITERIA_TYPE_TOTAL_DAMAGE_RECEIVED:
return "TOTAL_DAMAGE_RECEIVED";
case ACHIEVEMENT_CRITERIA_TYPE_HIGHEST_HEAL_CASTED:
return "HIGHEST_HEAL_CASTED";
case ACHIEVEMENT_CRITERIA_TYPE_TOTAL_HEALING_RECEIVED:
return "TOTAL_HEALING_RECEIVED";
case ACHIEVEMENT_CRITERIA_TYPE_HIGHEST_HEALING_RECEIVED:
return "HIGHEST_HEALING_RECEIVED";
case ACHIEVEMENT_CRITERIA_TYPE_QUEST_ABANDONED:
return "QUEST_ABANDONED";
case ACHIEVEMENT_CRITERIA_TYPE_FLIGHT_PATHS_TAKEN:
return "FLIGHT_PATHS_TAKEN";
case ACHIEVEMENT_CRITERIA_TYPE_LOOT_TYPE:
return "LOOT_TYPE";
case ACHIEVEMENT_CRITERIA_TYPE_CAST_SPELL2:
return "CAST_SPELL2";
case ACHIEVEMENT_CRITERIA_TYPE_LEARN_SKILL_LINE:
return "LEARN_SKILL_LINE";
case ACHIEVEMENT_CRITERIA_TYPE_EARN_HONORABLE_KILL:
return "EARN_HONORABLE_KILL";
case ACHIEVEMENT_CRITERIA_TYPE_ACCEPTED_SUMMONINGS:
return "ACCEPTED_SUMMONINGS";
case ACHIEVEMENT_CRITERIA_TYPE_EARN_ACHIEVEMENT_POINTS:
return "EARN_ACHIEVEMENT_POINTS";
case ACHIEVEMENT_CRITERIA_TYPE_USE_LFD_TO_GROUP_WITH_PLAYERS:
return "USE_LFD_TO_GROUP_WITH_PLAYERS";
case ACHIEVEMENT_CRITERIA_TYPE_SPENT_GOLD_GUILD_REPAIRS:
return "SPENT_GOLD_GUILD_REPAIRS";
case ACHIEVEMENT_CRITERIA_TYPE_REACH_GUILD_LEVEL:
return "REACH_GUILD_LEVEL";
case ACHIEVEMENT_CRITERIA_TYPE_CRAFT_ITEMS_GUILD:
return "CRAFT_ITEMS_GUILD";
case ACHIEVEMENT_CRITERIA_TYPE_CATCH_FROM_POOL:
return "CATCH_FROM_POOL";
case ACHIEVEMENT_CRITERIA_TYPE_BUY_GUILD_BANK_SLOTS:
return "BUY_GUILD_BANK_SLOTS";
case ACHIEVEMENT_CRITERIA_TYPE_EARN_GUILD_ACHIEVEMENT_POINTS:
return "EARN_GUILD_ACHIEVEMENT_POINTS";
case ACHIEVEMENT_CRITERIA_TYPE_WIN_RATED_BATTLEGROUND:
return "WIN_RATED_BATTLEGROUND";
case ACHIEVEMENT_CRITERIA_TYPE_REACH_BG_RATING:
return "REACH_BG_RATING";
case ACHIEVEMENT_CRITERIA_TYPE_BUY_GUILD_TABARD:
return "BUY_GUILD_TABARD";
case ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_QUESTS_GUILD:
return "COMPLETE_QUESTS_GUILD";
case ACHIEVEMENT_CRITERIA_TYPE_HONORABLE_KILLS_GUILD:
return "HONORABLE_KILLS_GUILD";
case ACHIEVEMENT_CRITERIA_TYPE_KILL_CREATURE_TYPE_GUILD:
return "KILL_CREATURE_TYPE_GUILD";
case ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_GUILD_CHALLENGE_TYPE:
return "GUILD_CHALLENGE_TYPE";
case ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_GUILD_CHALLENGE:
return "GUILD_CHALLENGE";
default:
return "MISSING_TYPE";
}
}
template class AchievementMgr<Guild>;
template class AchievementMgr<Player>;
//==========================================================
void AchievementGlobalMgr::LoadAchievementCriteriaList()
{
uint32 oldMSTime = getMSTime();
if (sCriteriaStore.GetNumRows() == 0)
{
TC_LOG_ERROR("server.loading", ">> Loaded 0 achievement criteria.");
return;
}
for (uint32 entryId = 0; entryId < sCriteriaTreeStore.GetNumRows(); entryId++)
{
CriteriaTreeEntry const* criteriaTree = sCriteriaTreeStore.LookupEntry(entryId);
if (!criteriaTree)
continue;
if (CriteriaTreeEntry const* parent = sCriteriaTreeStore.LookupEntry(criteriaTree->parentID))
m_SubCriteriaTreeListById[parent->ID].push_back(criteriaTree);
ModifierTreeEntryByTreeId m_ModifierTreeEntryByTreeId;
CriteriaEntry const* criteriaEntry = sCriteriaStore.LookupEntry(criteriaTree->criteriaID);
if (!criteriaEntry)
continue;
m_AchievementCriteriaTreeByCriteriaId[criteriaEntry->ID].push_back(criteriaTree);
}
for (uint32 entryId = 0; entryId < sModifierTreeStore.GetNumRows(); entryId++)
{
ModifierTreeEntry const* modifier = sModifierTreeStore.LookupEntry(entryId);
if (!modifier)
continue;
if (modifier->parent)
m_ModifierTreeEntryByTreeId[modifier->parent].push_back(modifier);
}
uint32 criterias = 0;
for (uint32 entryId = 0; entryId < sCriteriaStore.GetNumRows(); entryId++)
{
CriteriaEntry const* criteria = sAchievementMgr->GetAchievementCriteria(entryId);
if (!criteria)
continue;
m_AchievementCriteriasByType[criteria->type].push_back(criteria);
if (criteria->timeLimit)
m_AchievementCriteriasByTimedType[criteria->timedCriteriaStartType].push_back(criteria);
++criterias;
}
for (uint32 entryId = 0; entryId < sCriteriaStore.GetNumRows(); entryId++)
{
CriteriaEntry const* criteria = sAchievementMgr->GetAchievementCriteria(entryId);
if (!criteria)
continue;
AchievementCriteriaTreeList achievementCriteriaTreeList = sAchievementMgr->GetAchievementCriteriaTreeList(criteria);
for (AchievementCriteriaTreeList::const_iterator iter = achievementCriteriaTreeList.begin(); iter != achievementCriteriaTreeList.end(); iter++)
{
AchievementEntry const* achievement = sAchievementMgr->GetAchievementEntryByCriteriaTree(*iter);
if (!achievement)
continue;
if (!(achievement->flags & ACHIEVEMENT_FLAG_GUILD))
continue;
m_GuildAchievementCriteriasByType[criteria->type].push_back(criteria);
++criterias;
}
}
TC_LOG_INFO("server.loading", ">> Loaded %u achievement criteria in %u ms", criterias, GetMSTimeDiffToNow(oldMSTime));
}
void AchievementGlobalMgr::LoadAchievementReferenceList()
{
uint32 oldMSTime = getMSTime();
if (sAchievementStore.GetNumRows() == 0)
{
TC_LOG_INFO("server.loading", ">> Loaded 0 achievement references.");
return;
}
uint32 count = 0;
for (uint32 entryId = 0; entryId < sAchievementStore.GetNumRows(); ++entryId)
{
AchievementEntry const* achievement = sAchievementMgr->GetAchievement(entryId);
if (!achievement)
continue;
m_AchievementEntryByCriteriaTree[achievement->criteriaTreeID] = achievement;
if (!achievement->refAchievement)
continue;
m_AchievementListByReferencedId[achievement->refAchievement].push_back(achievement);
++count;
}
// Once Bitten, Twice Shy (10 player) - Icecrown Citadel
if (AchievementEntry const* achievement = sAchievementMgr->GetAchievement(4539))
const_cast<AchievementEntry*>(achievement)->mapID = 631; // Correct map requirement (currently has Ulduar)
TC_LOG_INFO("server.loading", ">> Loaded %u achievement references in %u ms", count, GetMSTimeDiffToNow(oldMSTime));
}
void AchievementGlobalMgr::LoadAchievementCriteriaData()
{
uint32 oldMSTime = getMSTime();
m_criteriaDataMap.clear(); // Need for reload case
QueryResult result = WorldDatabase.Query("SELECT criteria_id, type, value1, value2, ScriptName FROM achievement_criteria_data");
if (!result)
{
TC_LOG_INFO("server.loading", ">> Loaded 0 additional achievement criteria data. DB table `achievement_criteria_data` is empty.");
return;
}
uint32 count = 0;
do
{
Field* fields = result->Fetch();
uint32 criteria_id = fields[0].GetUInt32();
CriteriaEntry const* criteria = sAchievementMgr->GetAchievementCriteria(criteria_id);
if (!criteria)
{
TC_LOG_ERROR("sql.sql", "Table `achievement_criteria_data` has data for non-existing criteria (Entry: %u), ignore.", criteria_id);
continue;
}
uint32 dataType = fields[1].GetUInt8();
const char* scriptName = fields[4].GetCString();
uint32 scriptId = 0;
if (strcmp(scriptName, "")) // Not empty
{
if (dataType != ACHIEVEMENT_CRITERIA_DATA_TYPE_SCRIPT)
TC_LOG_ERROR("sql.sql", "Table `achievement_criteria_data` has ScriptName set for non-scripted data type (Entry: %u, type %u), useless data.", criteria_id, dataType);
else
scriptId = sObjectMgr->GetScriptId(scriptName);
}
AchievementCriteriaData data(dataType, fields[2].GetUInt32(), fields[3].GetUInt32(), scriptId);
if (!data.IsValid(criteria))
continue;
// This will allocate empty data set storage
AchievementCriteriaDataSet& dataSet = m_criteriaDataMap[criteria_id];
dataSet.SetCriteriaId(criteria_id);
// Add real data only for not NONE data types
if (data.dataType != ACHIEVEMENT_CRITERIA_DATA_TYPE_NONE)
dataSet.Add(data);
// Counting data by and data types
++count;
}
while (result->NextRow());
TC_LOG_INFO("server.loading", ">> Loaded %u additional achievement criteria data in %u ms", count, GetMSTimeDiffToNow(oldMSTime));
}
void AchievementGlobalMgr::LoadCompletedAchievements()
{
uint32 oldMSTime = getMSTime();
QueryResult result = CharacterDatabase.Query("SELECT achievement FROM character_achievement GROUP BY achievement");
if (!result)
{
TC_LOG_INFO("server.loading", ">> Loaded 0 completed achievements. DB table `character_achievement` is empty.");
return;
}
do
{
Field* fields = result->Fetch();
uint16 achievementId = fields[0].GetUInt16();
const AchievementEntry* achievement = sAchievementMgr->GetAchievement(achievementId);
if (!achievement)
{
// Remove non existent achievements from all characters
TC_LOG_ERROR("achievement", "Non-existing achievement %u data removed from table `character_achievement`.", achievementId);
PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_INVALID_ACHIEVMENT);
stmt->setUInt16(0, uint16(achievementId));
CharacterDatabase.Execute(stmt);
continue;
}
else if (achievement->flags & (ACHIEVEMENT_FLAG_REALM_FIRST_REACH | ACHIEVEMENT_FLAG_REALM_FIRST_KILL))
m_allCompletedAchievements.insert(achievementId);
}
while (result->NextRow());
TC_LOG_INFO("server.loading", ">> Loaded %lu completed achievements in %u ms", (unsigned long)m_allCompletedAchievements.size(), GetMSTimeDiffToNow(oldMSTime));
}
void AchievementGlobalMgr::LoadRewards()
{
uint32 oldMSTime = getMSTime();
m_achievementRewards.clear(); // Need for reload case
// 0 1 2 3 4 5 6
QueryResult result = WorldDatabase.Query("SELECT entry, title_A, title_H, item, sender, subject, text FROM achievement_reward");
if (!result)
{
TC_LOG_ERROR("server.loading", ">> Loaded 0 achievement rewards. DB table `achievement_reward` is empty.");
return;
}
uint32 count = 0;
do
{
Field* fields = result->Fetch();
uint32 entry = fields[0].GetUInt32();
const AchievementEntry* pAchievement = GetAchievement(entry);
if (!pAchievement)
{
TC_LOG_ERROR("sql.sql", "Table `achievement_reward` has wrong achievement (Entry: %u), ignored.", entry);
continue;
}
AchievementReward reward;
reward.titleId[0] = fields[1].GetUInt32();
reward.titleId[1] = fields[2].GetUInt32();
reward.itemId = fields[3].GetUInt32();
reward.sender = fields[4].GetUInt32();
reward.subject = fields[5].GetString();
reward.text = fields[6].GetString();
// Must be title or mail at least
if (!reward.titleId[0] && !reward.titleId[1] && !reward.sender)
{
TC_LOG_ERROR("sql.sql", "Table `achievement_reward` (Entry: %u) does not have title or item reward data, ignored.", entry);
continue;
}
if (pAchievement->requiredFaction == ACHIEVEMENT_FACTION_ANY && ((reward.titleId[0] == 0) != (reward.titleId[1] == 0)))
TC_LOG_ERROR("sql.sql", "Table `achievement_reward` (Entry: %u) has title (A: %u H: %u) for only one team.", entry, reward.titleId[0], reward.titleId[1]);
if (reward.titleId[0])
{
CharTitlesEntry const* titleEntry = sCharTitlesStore.LookupEntry(reward.titleId[0]);
if (!titleEntry)
{
TC_LOG_ERROR("sql.sql", "Table `achievement_reward` (Entry: %u) has invalid title id (%u) in `title_A`, set to 0", entry, reward.titleId[0]);
reward.titleId[0] = 0;
}
}
if (reward.titleId[1])
{
CharTitlesEntry const* titleEntry = sCharTitlesStore.LookupEntry(reward.titleId[1]);
if (!titleEntry)
{
TC_LOG_ERROR("sql.sql", "Table `achievement_reward` (Entry: %u) has invalid title id (%u) in `title_H`, set to 0", entry, reward.titleId[1]);
reward.titleId[1] = 0;
}
}
// Check mail data before item for report including wrong item case
if (reward.sender)
{
if (!sObjectMgr->GetCreatureTemplate(reward.sender))
{
TC_LOG_ERROR("sql.sql", "Table `achievement_reward` (Entry: %u) has invalid creature entry %u as sender, mail reward skipped.", entry, reward.sender);
reward.sender = 0;
}
}
else
{
if (reward.itemId)
TC_LOG_ERROR("sql.sql", "Table `achievement_reward` (Entry: %u) does not have sender data but has item reward, item will not be rewarded.", entry);
if (!reward.subject.empty())
TC_LOG_ERROR("sql.sql", "Table `achievement_reward` (Entry: %u) does not have sender data but has mail subject.", entry);
if (!reward.text.empty())
TC_LOG_ERROR("sql.sql", "Table `achievement_reward` (Entry: %u) does not have sender data but has mail text.", entry);
}
if (reward.itemId)
{
if (!sObjectMgr->GetItemTemplate(reward.itemId))
{
TC_LOG_ERROR("sql.sql", "Table `achievement_reward` (Entry: %u) has invalid item id %u, reward mail will not contain item.", entry, reward.itemId);
reward.itemId = 0;
}
}
m_achievementRewards[entry] = reward;
++count;
}
while (result->NextRow());
TC_LOG_INFO("server.loading", ">> Loaded %u achievement rewards in %u ms", count, GetMSTimeDiffToNow(oldMSTime));
}
void AchievementGlobalMgr::LoadRewardLocales()
{
uint32 oldMSTime = getMSTime();
m_achievementRewardLocales.clear(); // Need for reload case
QueryResult result = WorldDatabase.Query("SELECT entry, subject_loc1, text_loc1, subject_loc2, text_loc2, subject_loc3, text_loc3, subject_loc4, text_loc4, "
"subject_loc5, text_loc5, subject_loc6, text_loc6, subject_loc7, text_loc7, subject_loc8, text_loc8, subject_loc9, text_loc9,"
"subject_loc10, text_loc10 FROM locales_achievement_reward");
if (!result)
{
TC_LOG_INFO("server.loading", ">> Loaded 0 achievement reward locale strings. DB table `locales_achievement_reward` is empty");
return;
}
do
{
Field* fields = result->Fetch();
uint32 entry = fields[0].GetUInt32();
if (m_achievementRewards.find(entry) == m_achievementRewards.end())
{
TC_LOG_ERROR("sql.sql", "Table `locales_achievement_reward` (Entry: %u) has locale strings for non-existing achievement reward.", entry);
continue;
}
AchievementRewardLocale& data = m_achievementRewardLocales[entry];
for (int i = 1; i < TOTAL_LOCALES; ++i)
{
LocaleConstant locale = (LocaleConstant) i;
ObjectMgr::AddLocaleString(fields[1 + 2 * (i - 1)].GetString(), locale, data.subject);
ObjectMgr::AddLocaleString(fields[1 + 2 * (i - 1) + 1].GetString(), locale, data.text);
}
}
while (result->NextRow());
TC_LOG_INFO("server.loading", ">> Loaded %lu achievement reward locale strings in %u ms", (unsigned long)m_achievementRewardLocales.size(), GetMSTimeDiffToNow(oldMSTime));
}
AchievementEntry const* AchievementGlobalMgr::GetAchievement(uint32 achievementId) const
{
return sAchievementStore.LookupEntry(achievementId);
}
CriteriaEntry const* AchievementGlobalMgr::GetAchievementCriteria(uint32 criteriaId) const
{
return sCriteriaStore.LookupEntry(criteriaId);
}
| [
"felianther15@gmail.com"
] | felianther15@gmail.com |
598c018547b9101c37c66a6121b664c4e6095b63 | e7af073f0013c1b63219cff9579e0f1029396e78 | /src/client/DocParser.cpp | 5b203f23087514e02d4fd6fa1f0df1e4c5d777cb | [
"BSD-2-Clause"
] | permissive | ms-building-blocks/credb | 703941337f86d6b212ed7d6fd9027c7ce599fa85 | 0956ee0b8d246d00a375fd978cbd2ea787688d98 | refs/heads/master | 2021-05-09T19:00:41.879431 | 2018-01-26T20:49:08 | 2018-01-26T20:49:08 | 119,178,204 | 1 | 0 | null | 2018-01-27T15:54:23 | 2018-01-27T15:54:22 | null | UTF-8 | C++ | false | false | 3,778 | cpp | #include "DocParser.h"
#define BOOST_RESULT_OF_USE_DECLTYPE
#define BOOST_SPIRIT_USE_PHOENIX_V3
#include <boost/phoenix/bind/bind_function.hpp>
#include <boost/spirit/include/phoenix.hpp>
#include <boost/spirit/include/qi.hpp>
#include <boost/spirit/include/support_istream_iterator.hpp>
#include <cowlang/cow.h>
#include <fstream>
#include <glog/logging.h>
namespace credb
{
using namespace boost::spirit;
void print(const std::string &str) { std::cout << str << std::endl; }
template <typename Iterator>
struct obj_grammar : qi::grammar<Iterator, qi::unused_type(), qi::space_type>
{
obj_grammar() : obj_grammar::base_type(start)
{
using ascii::char_;
using boost::phoenix::bind;
using qi::_1;
using qi::eps;
using qi::int_;
using qi::lexeme;
using qi::lit;
using qi::no_skip;
using qi::string;
array = char_('[') >> *(char_(' ')) >> char_(']') >> *(char_('\n'));
dictentry = key >> ':' >> string("dict") >> string(":=") >>
char_('{')[bind([&]() { writer.start_map(current_key); })] >> *(char_(' ')) >>
char_('}')[bind([&]() { writer.end_map(); })];
code = +~char_(";");
key = (+char_("a-zA-Z_"))[bind(
[&](const std::vector<char> &v) { current_key = std::string(v.begin(), v.end()); }, _1)];
intentry = key >> ':' >> string("int") >> string(":=") >>
int_[bind([&](int val) { writer.write_integer(current_key, val); }, _1)];
funcentry = key >> ':' >> string("func") >> string(":=") >>
no_skip[code[bind(
[&](const std::string &c) {
try
{
auto bin = cow::compile_code(c);
writer.write_binary(current_key, bin);
}
catch(std::runtime_error &e)
{
LOG(ERROR) << "failed to compile code: \n" << c;
}
},
_1)]] >>
char_(";");
start = eps > char_('{')[bind([&]() { writer.start_map(""); })] >>
*(intentry | funcentry | dictentry) >>
lit('}')[bind([&]() { writer.end_map(); })] >> *(char_('\n'));
key.name("key");
dictentry.name("dict entry");
intentry.name("int entry");
funcentry.name("func entry");
start.name("root");
qi::on_error<qi::fail>(start, boost::phoenix::ref(std::cout)
<< "Error! Expected " << qi::_4 << " but got: '"
<< boost::phoenix::construct<std::string>(qi::_3, qi::_2) << "'\n");
}
qi::rule<Iterator, qi::unused_type(), qi::space_type> dictentry, array, intentry, funcentry, key, start;
qi::rule<Iterator, std::string()> code;
json::Writer writer;
std::string current_key;
std::string current_code;
};
json::Document parse_document_file(const std::string &filename)
{
using qi::char_;
using qi::phrase_parse;
using qi::space;
std::ifstream file(filename);
file.unsetf(std::ios::skipws);
if(!file)
{
throw std::runtime_error("cannot open object file");
}
auto fstart = istream_iterator(file);
auto fend = istream_iterator();
obj_grammar<istream_iterator> parser;
auto res = phrase_parse(fstart, fend, parser, space);
if(!res)
{
throw std::runtime_error("Failed to parse object file");
}
if(fstart != fend)
{
throw std::runtime_error("Couldn't read until the end");
}
return parser.writer.make_document();
}
} // namespace credb
| [
"kaimast@cs.cornell.edu"
] | kaimast@cs.cornell.edu |
ca577c099d33eb16636a159195b87c318dda4309 | a7f0fdadbf539857f57b2b1120268d7c93b76083 | /tests/funcexample.cpp | 25581ba128f19ad67fef7de20c7664c235de36b2 | [] | no_license | SethForrest/Compilers_HW_1 | bf8579b8cb380107aef493170a8f9c359417939d | 17696280cd133a49039ca272d66f7461d4314e1e | refs/heads/master | 2021-01-19T20:03:00.381455 | 2017-09-08T03:35:17 | 2017-09-08T03:35:17 | 101,217,397 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 397 | cpp | #include <iostream>
using namespace std;
double myfunc(double, double);
double goof(double);
int main()
{
double x, y;
double z;
z = myfunc(x, y);
cout << "zed was " << z << endl;
return 0;
}
double myfunc(double x, double y)
{
x = goof(2.0);
return x;
}
double goof(double branflakes)
{
double bf2 = branflakes + 2.0;
cout << "bf2 is " << bf2 << endl;
return goof(bf2);
}
| [
"Seth.Forrest@gmail.com"
] | Seth.Forrest@gmail.com |
6b13561c7b167feccdf9348c493d5314ef21fcdb | 282b64c67c299b227e3002535609d4319e248b14 | /TcpClientStruct/client_3.cpp | 3cd32a6f1a923b6a8dbab6f285c0df0e142d20db | [] | no_license | TimingTone/Socket | f95ab01f21bb446c16fe1038bcb06cd263777aa4 | a8f937f87479455cb6c9bd4f3909f635d4f297a2 | refs/heads/master | 2021-02-27T20:31:36.108078 | 2020-03-17T16:16:34 | 2020-03-17T16:16:34 | 245,628,295 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 2,225 | cpp | #define WIN32_LEAN_AND_MEAN //引入宏去避免早期的会引起冲突的一些库,减少其他依赖库的引用
#define _WINSOCK_DEPRECATED_NO_WARNINGS
#define _CRT_SECURE_NO_WARNINGS
#include <WinSock2.h>
#include <windows.h>
#include <iostream>
#pragma comment(lib, "ws2_32.lib")
//用Socket API建立简易的TCP客户端
struct DataPackage {
int age;
char name[32];
};
int main() {
//启动windows socket 2.x环境
WORD wVersionRequested = MAKEWORD(2, 2);
//The WSADATA structure is used to save the Windows Sockets
// initialization information returned by the function WSAStartup
WSADATA wsadata;
//调用winSocket的启动函数WSAStartup
//wVersionRequested :WORD的版本号
//&wsadata :WSADATA的数据结构(struct)
WSAStartup(wVersionRequested, &wsadata);
//用Socket API建立简易的TCP客户端
// 1. 建立一个socket
SOCKET _sock = socket(AF_INET, SOCK_STREAM, 0); //_sock是服务端socket
if (INVALID_SOCKET == _sock) {
printf("Failed to establish socket client...\n");
}
else {
printf("Succeed to establish the client...\n");
}
// 2. 连接服务器 connect
sockaddr_in _sin = {};
_sin.sin_family = AF_INET;
_sin.sin_port = htons(4567);
_sin.sin_addr.S_un.S_addr = inet_addr("127.0.0.1");
int ret = connect(_sock, (sockaddr*)&_sin, sizeof(sockaddr_in));
if (SOCKET_ERROR == ret) {
printf("Failed to establish socket client...\n");
}
else {
printf("Succeed to establish the client...\n");
}
// 3, Input request command
while (true) {
char cmdBuf[128] = {};
scanf("%s", cmdBuf);
// 4, Deal with request command
if (0 == strcmp(cmdBuf, "exit")) {
printf("Received quit command!");
break;
}
else {
// 5, send request command to server.
send(_sock, cmdBuf, strlen(cmdBuf) + 1, 0);
}
// 6. 接收服务器信息recv
char recvBuf[128] = {};
int nlen = recv(_sock, recvBuf, 128, 0);
if (nlen > 0) {
DataPackage* dp = (DataPackage*)recvBuf;
printf("Age: %d \nName = %s\n", dp->age, dp->name);
}
}
// 7. 关闭socket closesocket
closesocket(_sock);
WSACleanup();
printf("quit!, mission completed.");
getchar();
return 0;
} | [
"1725491705@qq.com"
] | 1725491705@qq.com |
15e3c88f54ba1f4a453bca82ea6127cf945fa057 | bb324b1b7cf95dcb1bbeb7fdae494d9f56b74bda | /game0/vs-2013/GameOver.h | 0b098099bc8e41452adf4873ae3fa62b5f2b4962 | [] | no_license | Sunjiawei58/Drizzle-sjw | 3731eba6b7eaaeead604f0ec723b60b6b6b45f97 | f761beb3f3581cca3621f1409e232065ff1409ab | refs/heads/master | 2020-12-03T04:00:37.935754 | 2017-06-29T17:29:42 | 2017-06-29T17:29:42 | 95,800,510 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 183 | h | #pragma once
#include "s_Object.h"
class GameOver :
public df::s_Object
{
public:
GameOver();
~GameOver();
int eventHandler(const df::s_Event *p);
GameOver * clone() const;
};
| [
"suninwpi@gmail.com"
] | suninwpi@gmail.com |
3eae6d7623528c220db63a64acb20a3b5b0bdff5 | 01eef489b10bf76a920b0227a1ded1c7cb1e2cce | /New_Game_3D_2/KeyInput.cpp | 50626d556e7c7ed599953f757f1c15c2d253ca99 | [] | no_license | syogo1903x/Protect-The-Tower | 295beba154a8abe7053d2f8afe67353f617ab32c | a0559a128e59b0ea44ebff801469d0d00c9b8b04 | refs/heads/master | 2020-05-21T13:26:29.319076 | 2019-05-11T01:18:25 | 2019-05-11T01:18:25 | 182,363,239 | 0 | 0 | null | 2019-04-20T07:17:21 | 2019-04-20T05:14:09 | RPC | SHIFT_JIS | C++ | false | false | 1,413 | cpp | #include "KeyInput.h"
KeyInput::KeyInput()
{
}
KeyInput::~KeyInput()
{
}
void KeyInput::Init_Key()
{
int i, j;
for(i = 0; i < 2; i++)
{
for (j = 0; j < 256; j++)
{
keyState[i][j] = 0;
key[j] = KEY_OFF;
}
}
nowKey = 0; prevKey = 1;
}
void KeyInput::Update_Key()
{
// 現在のキーと一つ前のフレームのキー状態を入れ替える
nowKey ^= 1;
prevKey = nowKey ^ 1;
// キー状態取得
GetHitKeyStateAll(keyState[nowKey]);
//
for (int i = 0; i < 256; i++)
{
char nowInput = keyState[nowKey][i];
char prevInput = keyState[prevKey][i];
if (nowInput)
{
//現在押されている
//前のフレームも押されていた?
if (prevInput)
{
key[i] = KEY_PRESSED; // 押されっぱなし
}
else {
key[i] = KEY_ON;// 今押された
}
}
else
{
// 現在キーは押されていない
// 前のフレームで押されていた?
if (prevInput)
{
key[i] = KEY_RELEASE;
}
else {
key[i] = KEY_OFF;
}
}
}
}
KEY_STATE KeyInput::GetKey(unsigned char _keyCode)
{
return key[_keyCode];
}
| [
"ooyamasyogo@icloud.com"
] | ooyamasyogo@icloud.com |
3635711d76d04483288c9b589d062ebd7caa8344 | ae4d038d994359a59d0681d4d63fac5236e03ca0 | /src/qiskit-simulator/src/simulator.hpp | 21a9af4efa7faf03134964dc726349a645c2f71d | [
"LicenseRef-scancode-warranty-disclaimer",
"Apache-2.0"
] | permissive | akarazeev/qiskit-sdk-py | df51f1ff4b142355f60a4e237d1e5613b1ff5914 | d54d2bab8ba3ea76946ec11e7fbdf67f5d5c49b1 | refs/heads/master | 2021-04-15T18:57:02.080231 | 2018-03-25T08:48:09 | 2018-03-25T08:48:09 | 126,679,293 | 0 | 0 | Apache-2.0 | 2018-03-25T08:45:42 | 2018-03-25T08:45:42 | null | UTF-8 | C++ | false | false | 10,333 | hpp | /*
Copyright (c) 2017 IBM Corporation. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
/**
* @file simulator.hpp
* @brief Simulator class
* @author Christopher J. Wood <cjwood@us.ibm.com>
*/
#ifndef _Simulator_hpp_
#define _Simulator_hpp_
#include <chrono>
#include <iostream>
#include <random>
#include <sstream>
#include <stdexcept>
#include <string>
#include <vector>
// Parallelization
#ifdef _OPENMP
#include <omp.h> // OpenMP
#else
#include <future> // C++11
#endif
#include "circuit.hpp"
#include "misc.hpp"
#include "noise_models.hpp"
#include "types.hpp"
// Engines
#include "base_engine.hpp"
#include "sampleshots_engine.hpp"
#include "vector_engine.hpp"
// Backends
#include "clifford_backend.hpp"
#include "ideal_backend.hpp"
#include "qubit_backend.hpp"
namespace QISKIT {
/***************************************************************************/ /**
*
* Simulator class
*
******************************************************************************/
class Simulator {
public:
std::string id = ""; // simulation id
std::string simulator = "qubit"; // simulator backend label
std::vector<Circuit> circuits; // QISKIT program
// Multithreading Params
uint_t max_memory_gb = 16; // max memory to use
uint_t max_threads_shot = 0; // 0 for automatic
uint_t max_threads_gate = 0; // 0 for automatic
// Constructor
inline Simulator(){};
// Execute all quantum circuits
json_t execute();
// Execute a single circuit
template <class Engine, class Backend>
json_t run_circuit(Circuit &circ) const;
};
/*******************************************************************************
*
* Simulator Methods
*
******************************************************************************/
json_t Simulator::execute() {
// Initialize ouput JSON
std::chrono::time_point<myclock_t> start = myclock_t::now(); // start timer
json_t ret;
ret["id"] = id;
if (simulator == "clifford")
ret["backend"] = std::string("local_clifford_simulator");
else
ret["backend"] = std::string("local_qiskit_simulator");
ret["simulator"] = simulator;
// Choose simulator and execute circuits
try {
bool qobj_success = true;
for (auto &circ : circuits) {
json_t circ_res;
// Choose Simulator Backend
if (simulator == "clifford")
circ_res = run_circuit<BaseEngine<Clifford>, CliffordBackend>(circ);
else if (simulator == "ideal")
circ_res = run_circuit<SampleShotsEngine, IdealBackend>(circ);
else
circ_res = run_circuit<VectorEngine, QubitBackend>(circ);
// Check results
qobj_success &= circ_res["success"].get<bool>();
ret["result"].push_back(circ_res);
}
ret["time_taken"] =
std::chrono::duration<double>(myclock_t::now() - start).count();
ret["status"] = std::string("COMPLETED");
ret["success"] = qobj_success;
} catch (std::exception &e) {
ret["success"] = false;
ret["status"] = std::string("ERROR: ") + e.what();
}
return ret;
}
//------------------------------------------------------------------------------
template <class Engine, class Backend>
json_t Simulator::run_circuit(Circuit &circ) const {
std::chrono::time_point<myclock_t> start = myclock_t::now(); // start timer
json_t ret; // results JSON
// Check max qubits
uint_t max_qubits =
static_cast<uint_t>(floor(log2(max_memory_gb * 1e9 / 16.)));
if ((simulator == "qubit" || simulator == "ideal") &&
circ.nqubits > max_qubits) {
ret["success"] = false;
std::stringstream msg;
msg << "ERROR: Number of qubits (" << circ.nqubits
<< ") exceeds maximum memory (" << max_memory_gb << " GB).";
ret["status"] = msg.str();
return ret;
}
// Try to execute circuit
try {
// Initialize reference engine and backend from JSON config
Engine engine = circ.config;
Backend backend = circ.config;
// Set RNG Seed
uint_t rng_seed = (circ.rng_seed < 0) ? std::random_device()()
: static_cast<uint_t>(circ.rng_seed);
// Thread number
#ifdef _OPENMP
uint_t ncpus = omp_get_num_procs(); // OMP method
omp_set_nested(1); // allow nested parallel threads
#else
uint_t ncpus = std::thread::hardware_concurrency(); // C++11 method
#endif
ncpus = std::max(1ULL, ncpus); // check 0 edge case
int_t dq = (max_qubits > circ.nqubits) ? max_qubits - circ.nqubits : 0;
uint_t threads = std::max<uint_t>(1UL, 2 * dq);
if (simulator == "ideal" && circ.opt_meas)
threads = 1; // single shot thread
else {
threads = std::min<uint_t>(threads, ncpus);
threads = std::min<uint_t>(threads, circ.shots);
if (max_threads_shot > 0)
threads = std::min<uint_t>(max_threads_shot, threads);
}
uint_t gate_threads = std::max<uint_t>(1UL, ncpus / threads);
if (max_threads_gate > 0)
gate_threads = std::min<uint_t>(max_threads_gate, gate_threads);
// Single-threaded shots loop
if (threads < 2) {
// Run shots on single-thread
backend.set_rng_seed(rng_seed);
engine.run_program(circ, &backend, circ.shots, gate_threads);
}
// Parallelized shots loop
else {
// Set rng seed for each thread
std::vector<std::pair<uint_t, uint_t>> shotseed;
for (uint_t j = 0; j < threads; ++j)
shotseed.push_back(std::make_pair(circ.shots / threads, rng_seed + j));
shotseed[0].first += (circ.shots % threads);
// OMP Execution
#ifdef _OPENMP
std::vector<Engine> futures(threads);
#pragma omp parallel for if (threads > 1) num_threads(threads)
for (uint_t j = 0; j < threads; j++) {
const auto &ss = shotseed[j];
Backend be(backend);
be.set_rng_seed(ss.second);
futures[j] = engine;
futures[j].run_program(circ, &be, ss.first, gate_threads);
}
for (auto &f : futures)
engine += f;
// C++11 Execution
#else
std::vector<std::future<Engine>> futures;
for (auto &&ss : shotseed)
futures.push_back(async(std::launch::async, [&]() {
Engine eng(engine);
Backend be(backend);
be.set_rng_seed(ss.second);
eng.run_program(circ, &be, ss.first);
return eng;
}));
// collect results
for (auto &&f : futures)
engine += f.get();
#endif
} // end parallel shots
// Return results
ret["data"] = engine; // add engine output to return
if (simulator != "ideal" && JSON::check_key("noise_params", circ.config)) {
ret["noise_params"] = backend.noise;
}
// Add time taken and return result
ret["data"]["time_taken"] =
std::chrono::duration<double>(myclock_t::now() - start).count();
// Add metadata
ret["name"] = circ.name;
ret["shots"] = circ.shots;
ret["seed"] = rng_seed;
if (threads > 1)
ret["threads_shot"] = threads;
// Report success
ret["success"] = true;
ret["status"] = std::string("DONE");
} catch (std::exception &e) {
ret["success"] = false;
ret["status"] = std::string("ERROR: ") + e.what();
}
return ret;
}
//------------------------------------------------------------------------------
inline bool check_qobj(const json_t &qobj) {
std::vector<std::string> qobj_keys{"id", "circuits"}; // optional: "config"
std::vector<std::string> compiled_keys{"header", "operations"};
std::vector<std::string> header_keys{"clbit_labels", "number_of_clbits",
"number_of_qubits", "qubit_labels"};
bool pass = JSON::check_keys(qobj_keys, qobj);
if (pass) {
for (auto &c : qobj["circuits"]) {
pass &= JSON::check_key("compiled_circuit", c);
if (pass) {
pass &= JSON::check_keys(compiled_keys, c["compiled_circuit"]);
if (pass)
pass &=
JSON::check_keys(header_keys, c["compiled_circuit"]["header"]);
}
}
}
return pass;
}
//------------------------------------------------------------------------------
inline void from_json(const json_t &js, Simulator &qobj) {
try {
if (check_qobj(js)) { // check valid qobj
qobj = Simulator();
JSON::get_value(qobj.id, "id", js);
json_t config;
JSON::get_value(config, "config", js);
// Multithreading Parameters
JSON::get_value(qobj.max_memory_gb, "max_memory", config);
JSON::get_value(qobj.max_threads_shot, "max_threads_shot", config);
JSON::get_value(qobj.max_threads_gate, "max_threads_gate", config);
// Override with user simulator backend specification
JSON::get_value(qobj.simulator, "simulator", config);
to_lowercase(qobj.simulator);
// Set simulator gateset
gateset_t gateset;
if (qobj.simulator == "qubit") {
gateset = QubitBackend::gateset;
} else if (qobj.simulator == "ideal") {
gateset = IdealBackend::gateset;
} else if (qobj.simulator == "clifford") {
gateset = CliffordBackend::gateset;
} else {
throw std::runtime_error(std::string("invalid simulator."));
}
// Load unrolled qasm circuits
const json_t &circs = js["circuits"];
for (auto it = circs.cbegin(); it != circs.cend(); ++it)
qobj.circuits.push_back(Circuit(*it, config, gateset));
} else {
throw std::runtime_error(std::string("invalid qobj file."));
}
} catch (std::exception &e) {
std::stringstream msg;
msg << "unable to parse qobj, " << e.what();
throw std::runtime_error(msg.str());
}
}
//------------------------------------------------------------------------------
} // end namespace QISKIT
//------------------------------------------------------------------------------
#endif | [
"cjwood@us.ibm.com"
] | cjwood@us.ibm.com |
3b1332438366b01df5a1a978a1d579aee1e0ab81 | 0764add6abfe89ea455502ba4c5cf010dc41d117 | /stream_pusher/Ffmpeg_stream_pusher.h | bb9fc07c6d193fb4d22d1cdc82b9acfe279ade81 | [
"MIT"
] | permissive | WangLCG/LiveStream | 22cb1b4e6bf73712de1234fdedd28dacaf08f7c7 | 9afb50d8e14c277c800d5b13d34adce31866520f | refs/heads/master | 2020-11-23T18:54:37.613768 | 2020-08-31T06:57:35 | 2020-08-31T06:57:35 | 227,776,771 | 20 | 23 | null | null | null | null | UTF-8 | C++ | false | false | 5,979 | h | /*
* Car eye 车辆管理平台: www.car-eye.cn
* Car eye 开源网址: https://github.com/Car-eye-team
* MP4Muxer.h
*
* Author: Wgj
* Date: 2019-03-04 22:21
* Copyright 2019
*
* MP4混流器类声明文件
*/
#ifndef __MP4_MUXER_H__
#define __MP4_MUXER_H__
#define _TIMESPEC_DEFINED
#include <thread>
#include <string>
#include <mutex>
#include <iostream>
#include <sys/time.h>
#include <unistd.h>
#include "RecvMulticastDataModule.h"
using namespace std;
#ifdef __cplusplus
extern "C" {
#endif
#include "libavcodec/avcodec.h"
#include "libavformat/avformat.h"
#ifdef __cplusplus
}
#endif
#define ENABLE_MULTICAST_QUEUE (1)
/* ffmpeg 数据读取回调函数 */
typedef struct FFMPEG_READ_PACK_CALL_BACK
{
void *ptr;
int (*read_buffer) (void *opaque, uint8_t *buf, int buf_size);
}FFMPEG_READ_PACK_CB;
// 用于存储流数据的队列项结构
typedef struct _CE_QUEUE_ITEM_T_
{
// 申请的缓冲区指针
uint8_t* Bytes;
// 申请的缓冲区大小
int TotalSize;
// 入队填充的数据字节数
int EnqueueSize;
// 出队读取的数据字节数
int DequeueSize;
}CEQueueItem;
// 一个简单的队列结构, 用于暂存流数据
typedef struct _CE_QUEUE_T_
{
// 队列项指针
CEQueueItem *Items;
// 队列的标识, 使用者可以自定义标识进行队列区分
uint8_t Flag;
// 队列项个数
int Count;
// 出队计数索引
int DequeueIndex;
// 入队索引
int EnqueueIndex;
}CESimpleQueue;
/*!
* \class MP4Muxer
*
* \brief MP4混流器, 合成H264与AAC音视频
*
* \author Wgj
* \date 2019-02-24
*/
class MP4Muxer
{
public:
MP4Muxer(RecvMulticastDataModule* MultiCastModule = NULL);
~MP4Muxer();
/*
* Comments: 混流器初始化 实例化后首先调用该方法进行内部参数的初始化
* Param aFileName: 要保存的文件名
* @Return 是否成功
*/
bool Start(std::string aFileName);
/*
* Comments: 追加一帧AAC数据到混流器
* Param aBytes: 要追加的字节数据
* Param aSize: 追加的字节数
* @Return 成功与否
*/
bool AppendAudio(uint8_t* aBytes, int aSize);
/*
* Comments: 追加一帧H264视频数据到混流器
* Param aBytes: 要追加的字节数据
* Param aSize: 追加的字节数
* @Return 成功与否
*/
bool AppendVideo(uint8_t* aBytes, int aSize);
/*
* Comments: 关闭并释放输出格式上下文
* Param : None
* @Return None
*/
void Stop(void);
void SetVideoCB(FFMPEG_READ_PACK_CB& videoCB);
void SetAudioCB(FFMPEG_READ_PACK_CB& audioCB);
//////////////////////////////////////////////////////////////////////////
/// \brief ffmpeg读取视频数据包回调
/// \details ffmpeg读取视频数据包回调
/// \param[in] opaque 实例句柄
/// \param[in/out] buf 数据填充buf
/// \param[in] buf_size buf大小
/// \return 实际读取数据大小
//////////////////////////////////////////////////////////////////////////
static int ReadVideoFrameCallback(void *opaque, uint8_t *buf, int buf_size);
//////////////////////////////////////////////////////////////////////////
/// \brief ffmpeg读取音频数据包回调
/// \details ffmpeg读取音频数据包回调
/// \param[in] opaque 实例句柄
/// \param[in/out] buf 数据填充buf
/// \param[in] buf_size buf大小
/// \return 实际读取数据大小
//////////////////////////////////////////////////////////////////////////
static int ReadAudioFrameCallback(void *opaque, uint8_t *buf, int buf_size);
/*
* Comments: 写入AAC数据帧到文件
* Param : None
* @Return int
*/
int WriteAudioFrame(void);
/*
* Comments: 写入H264视频帧到文件
* Param : None
* @Return int
*/
int WriteVideoFrame(void);
private:
/*
* Comments: 打开AAC输入上下文
* Param : None
* @Return 0成功, 其他失败
*/
int OpenAudio(bool aNew = false);
/*
* Comments: 打开H264视频流
* Param : None
* @Return 0成功, 其他失败
*/
int OpenVideo(void);
private:
// 要保存的MP4文件路径
std::string mFileName;
// 输入AAC音频上下文
AVFormatContext* mInputAudioContext;
// 输入H264视频上下文
AVFormatContext* mInputVideoContext;
// 输出媒体格式上下文
AVFormatContext* mOutputFrmtContext;
// AAC音频位流筛选上下文
AVBitStreamFilterContext* mAudioFilter;
// H264视频位流筛选上下文
AVBitStreamFilterContext* mVideoFilter;
// 流媒体数据包
AVPacket mPacket;
// AAC数据缓存区
uint8_t* mAudioBuffer;
// AAC数据读写队列
CESimpleQueue* mAudioQueue;
// H264数据缓冲区
uint8_t* mVideoBuffer;
// H264数据读写队列
CESimpleQueue* mVideoQueue;
// AAC的回调读取是否启动成功
bool mIsStartAudio;
// H264的回调读取是否启动成功
bool mIsStartVideo;
// 音频在mInputAudioContext->streams流中的索引
int mAudioIndex;
// 视频在mInputVideoContext->streams流中的索引
int mVideoIndex;
// 输出流中音频帧的索引
int mAudioOutIndex;
// 输出流视频帧的索引
int mVideoOutIndex;
// 输出帧索引计数
int mFrameIndex;
int mAudioFrameIndex;
// 线程操作互斥锁
std::mutex mLock;
FFMPEG_READ_PACK_CB mVideoCB; /* 视频数据读取回调函数 */
FFMPEG_READ_PACK_CB mAudioCB; /* 音频数据读取回调函数 */
RecvMulticastDataModule* mMultiCastModule;
};
#endif
| [
"20123200044@m.scnu.edu.cn"
] | 20123200044@m.scnu.edu.cn |
b9b9976db6ae67611b1b8744fe8ed07c32577a71 | 017d653b1a4d9ed3f5d2b36315dc3a131dd3b601 | /Az_Tools/Textline.h | c0b771d9b56b745702ff9174214c90a233443a2e | [] | no_license | cwoll87/code | c03e5cd2b9603c27a6397364bf6fee9a62f3c5eb | b584b4248a5f979237f1b9d3664b30b8c4ca8a4d | refs/heads/master | 2016-08-04T07:03:16.013414 | 2015-01-06T22:55:32 | 2015-01-06T22:55:32 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 541 | h | #pragma once
#include "SFML\Graphics.hpp"
namespace az
{
class Textline : public sf::Drawable
{
public:
sf::Text text;
std::string stringName;
sf::Font *font;
Textline(void);
Textline(std::string name, int size, int xpos, int ypos, const sf::Color &color);
~Textline(void);
std::string getString()const;
void setString(std::string temp);
void setColor(sf::Color color);
sf::FloatRect getFloatRect();
void setPosition(int x, int y);
void draw(sf::RenderTarget& target, sf::RenderStates states) const;
};
}
| [
"Hybra@hotmail.de"
] | Hybra@hotmail.de |
b47ad9dfb349186a3395a0890dcce4732c6dbac6 | 4b2aa0114449523ca9d98e9e25005c130d64547b | /ICPC/Challenge2013/GA/current_snapshot/classes.h | e24a13e06e9bdb586d901a0b7ebb28f7505a048f | [] | no_license | HowardChengUleth/codelibrary | 7793d86df4f82994770e8f1c19c7d240cadac9cd | d93fa3fc94792276c6f2cf2b480a445ec0bb8c32 | refs/heads/master | 2023-03-06T00:45:23.522994 | 2023-03-02T01:45:22 | 2023-03-02T01:45:22 | 136,532,622 | 10 | 5 | null | null | null | null | UTF-8 | C++ | false | false | 12,798 | h | #ifndef __UOFL_ICPC_CHALLENGE_CLASSES__
#define __UOFL_ICPC_CHALLENGE_CLASSES__
#include <iostream>
#include <vector>
#include <tr1/tuple>
#include <cassert>
#include <queue>
#include "globals.h"
using namespace std;
using namespace std::tr1;
////////////////////////////////////////////////////////////////////////////
// Union Find
////////////////////////////////////////////////////////////////////////////
struct UnionFind
{
vector<int> uf;
UnionFind(int n) : uf(n) {
for (int i = 0; i < n; i++) uf[i] = i;
}
int find(int x) {
return (uf[x] == x) ? x : (uf[x] = find(uf[x]));
}
bool merge(int x, int y) {
int res1 = find(x), res2 = find(y);
if (res1 == res2) return false;
uf[res2] = res1;
return true;
}
};
extern UnionFind uf;
////////////////////////////////////////////////////////////////////////////
// Gold
////////////////////////////////////////////////////////////////////////////
struct Gold{
int row,col,id;
};
extern vector<Gold> golds; //, golds2;
////////////////////////////////////////////////////////////////////////////
// Position
////////////////////////////////////////////////////////////////////////////
class Position {
public:
Position(uchar r=0, uchar c=0): row(r), col(c) {}
bool operator==(const Position &p) const { return (row == p.row) && (col == p.col); }
public:
char row;
char col;
};
ostream& operator<<(ostream &os, const Position &p);
istream& operator>>(istream &is, Position &p);
const Position NO_POS = Position(-1, -1);
extern vector<Position> nuggets;
////////////////////////////////////////////////////////////////////////////
// Move
////////////////////////////////////////////////////////////////////////////
class Move {
private:
Move(char dr, char dc, char l) : dRow(dr), dCol(dc), label(l) {}
public:
Position apply(const Position &p) const {
return Position(p.row + dRow, p.col + dCol);
}
bool operator==(const Move &m) const {
if (this == &m) return true;
if (this->dRow != m.dRow)
return false;
if (this->dCol != m.dCol)
return false;
return true;
}
public:
char dRow;
char dCol;
char label;
static const Move UP;
static const Move DOWN;
static const Move LEFT;
static const Move RIGHT;
static const Move NONE;
};
const Move& reverse(const Move &m);
const Move& getMove(cmd c);
////////////////////////////////////////////////////////////////////////////
// Board
////////////////////////////////////////////////////////////////////////////
typedef tuple<int,int,int,int,cmd> tiiiic; // Like the typedef name?
typedef priority_queue<tiiiic,vector<tiiiic>,greater<tiiiic> > PQ;
class Board {
private:
int uf_index(int r, int c) const
{
return r * WIDTH + c;
}
/*
void BFS_no_fall();
void SS_BFS_no_fall(int r,int c,int dist[HEIGHT][WIDTH]);
void SS_BFS_with_fall(int r,int c,int delay);
void update_and_add(PQ& pq,vector<cmd> moves[HEIGHT][WIDTH],
int dist2[HEIGHT][WIDTH][11],
int nDist,int nI,int nJ,int nD,cmd nC);
*/
public:
/* ============================================
Storage
The board will be stored as a 2D array of unsigned chars. However, I've used a bit of a different mapping
than what the game does:
1 : empty
2 : ladder
3 : gold cell
4-153: removed gold cell, will resurface in val-3 turns
154: brick
155-179 : removed brick by our player, will resurface in val-154 turns
180-204 : removed brick by our opponent, will resurface in val-179 turns
205-229 : removed brick by both opponents, will resurface in val-204 turns
Using this approach, we can store complete information regarding cells using single chars for each cell.
============================================= */
Board() {}
vector<cmd> valid_moves(int row,int col,bool canDig) const;
vector<Move> valid_movesM(int row,int col,bool canDig) const;
uchar operator[](const Position &p) const {
return cells[(uchar)p.row][(uchar)p.col];
}
uchar& operator[](const Position &p) {
return cells[(uchar)p.row][(uchar)p.col];
}
bool removedGold(const Position &p) const {
return ((*this)[p] > 3) && ( (*this)[p] < 154 );
}
void removeBrick(const Position &p, bool isMe) {
if (isMe) {
if ((*this)[p] == 204)
(*this)[p] = 229;
else
(*this)[p] = 179;
} else {
if ((*this)[p] == 179)
(*this)[p] = 229;
else
(*this)[p] = 204;
}
}
int brick_respawns_in(int r, int c) const
{
Position p(r,c);
if (visible(p) != REMOVED_BRICK) return -1;
if (cells[r][c] > 204) return cells[r][c] - 204;
if (cells[r][c] > 179) return cells[r][c] - 179;
if (cells[r][c] > 154) return cells[r][c] - 154;
#ifndef FINAL_VERSION
assert(false);
#endif
return -1;
}
int gold_respawns_in(int r, int c) const
{
if (cells[r][c] == 3) return -1;
if (4 <= cells[r][c] && cells[r][c] <= 153) return cells[r][c]-3;
return -1;
}
bool opp_dug_me(int r, int c) const
{
return cells[r][c] >= 180;
}
// returns what is visible. Gold cells that have removed gold will return as empty. Removed bricks will always
// return as removed brick, regardless of who removed it.
uchar visible(const Position &p) const {
uchar c = (*this)[p];
if (c == 1)
return EMPTY;
if (c == 2)
return LADDER;
if (c == 3)
return GOLD;
if (c < 154)
return EMPTY;
if (c == 154)
return BRICK;
return REMOVED_BRICK;
}
uchar visible(int r, int c) const;
Board visibleBoard() const {
Board b(*this);
for (int row = 0; row < HEIGHT; row++) {
for (int col = 0; col < WIDTH; col++) {
Position p(row, col);
b[p] = visible(p);
}
}
return b;
}
// Initializes the board before anyone is on it
//void init(int r,int c,int delay);
/*
// initializes the SCCs
void initSCC();
int scc_index(int r, int c)
{
return uf.find(uf_index(r, c));
}
bool is_SCC_leaf(int r, int c)
{
return SCC_leaf[scc_index(r, c)];
}
*/
// Determines if you can stand on a location.
// -- Only considers the map layout, not Enemies.
bool canStand(int r, int c) const;
public: // not necessary, but I'm used to having my member variables in the bottom of my declaration beneath a modifier.
uchar cells[HEIGHT][WIDTH];
};
ostream& operator<<(ostream &os, const Board &p);
istream& operator>>(istream &is, Board &p);
/////////////////////////////////////////////////////////////////////////
// Dude
/////////////////////////////////////////////////////////////////////////
class Dude {
public:
Dude(const Position &p=Position(0,0)) : pos(p), death_count(0) {}
bool isDead() const { return pos == Position(-1,-1); }
public:
Position pos;
int death_count; // death count is the number of remaining turns until alive again.
};
/////////////////////////////////////////////////////////////////////////
// Player
/////////////////////////////////////////////////////////////////////////
class Player : public Dude {
public:
Player(const Position &p=Position(0,0)) : Dude(p), score(0), mason_count(0) {}
public:
int score;
uchar mason_count;
};
istream& operator>>(istream &is, Player &p);
ostream& operator<<(ostream &os, const Player &p);
/////////////////////////////////////////////////////////////////////////
// Enemy
/////////////////////////////////////////////////////////////////////////
class Enemy : public Dude {
public:
Enemy(const Position &p=Position(0,0)) : Dude(p), ip(0), master(-1), lastMove(0) { }
public:
uchar ip; // instruction pointer
string stack; // stack of moves
char master; // 0 - me, 1 - me, -1 - you
int lastMove;
char respawn_row, respawn_col;
};
istream& operator>>(istream &is, Enemy &p);
ostream& operator<<(ostream &os, const Enemy &p);
extern vector<Enemy> enemies,enemies2;
/////////////////////////////////////////////////////////////////////////
// Game
/////////////////////////////////////////////////////////////////////////
class Game {
public:
Game() : turns(0) { }
public:
int turns;
Board board;
Position me, you;
vector<Position> enemyPos;
vector<string> enemyProgram;
};
istream& operator>>(istream &is, Game &g);
ostream& operator<<(ostream &os, const Game &g);
extern Game g;
/////////////////////////////////////////////////////////////////////////
// State
/////////////////////////////////////////////////////////////////////////
class State {
public:
State() : turn(0) {}
State(const Game &g);
bool fallingDude(const Dude &p) const;
bool fallingEnemy(const Enemy &p) const;
bool legal(const Position &p) const;
bool canNonFall(const Dude &p, const Move &move) const;
void applyNonFall(const Dude &p, Dude &newp, const Move &move) const;
void applyMoveDude(const Dude &p, Dude &newp, const cmd &command) const;
void update(const Move *prevMove[HEIGHT][WIDTH],
Position prevPosition[HEIGHT][WIDTH],
queue< pair<Position, int> > &myqueue, const Position &position,
int step, const Position &prev, const Move &move) const;
bool fallingPursuit(const Position &pos) const;
pair<const Move *, int> getPursuitMove(const Enemy &enemy,
const Player &player,
const Move **moves, int limit) const;
void applyMoveEnemy(const Enemy &enemy, Enemy &newEnemy,
string program, bool left, int turn) const;
void killDude(Dude &d, uchar turns) const {
d.pos = Position(-1, -1);
d.death_count = turns;
}
void restoreDude(Dude &d, const Position &start) {
d.pos = start;
}
bool canDestroyBrick(const Player &p, const Position &sideCell,
const Position &targetCell) const;
void respawn(Dude &d, const Position &start) const {
if (d.death_count > 0) {
d.death_count--;
if (d.death_count == 0) {
d.pos = start;
}
}
}
void checkForCollision(Player &p) {
if (p.isDead())
return;
for (unsigned int i = 0; i < enemies.size(); i++) {
if (p.pos == enemies[i].pos) {
killDude(p, 50);
return;
}
}
}
State getNewState(const Game &g, cmd myCommand, cmd yourCommand) const {
State newState(*this);
return getNewState(g, myCommand, yourCommand, newState);
}
State& getNewState(const Game &g, cmd myCommand, cmd yourCommand,
State &newState) const;
public:
int turn;
Board board;
bool visited[HEIGHT][WIDTH];
Player me, you;
vector<Enemy> enemies;
};
istream& readInState(istream &is, State &g, int enemyCount);
ostream& operator<<(ostream &os, const State &s);
/////////////////////////////////////////////////////////////////////////
// StateEngine
/////////////////////////////////////////////////////////////////////////
class StateEngine {
public:
StateEngine(const Game &pg, bool kgoe=true)
: g(pg), gameStatus(new State(g)), ourStatus(0), killGameOnError(kgoe) {}
void next(istream &is, const string &myMove);
public:
const Game g;
State *gameStatus;
State *ourStatus;
bool killGameOnError;
};
extern StateEngine *se;
/////////////////////////////////////////////////////////////////////////
// Lookahead
/////////////////////////////////////////////////////////////////////////
class Lookahead {
public:
static void getViableCommands( const State &status, const Player &p,
vector<cmd> &commands );
private:
static double boundedLookaheadScore( const Game &g, const State &status,
int depth, int max_depth,
int turns_remaining, State *stack );
public:
static int boundedLookahead( const Game &g, const State &status,
int maxDepth, int turns_remaining,
vector<cmd> &potentials );
static double boundedLookaheadScoreABD( const Game &g, const State &status,
int depth, int max_depth,
int turns_remaining, State *stack );
static int boundedLookaheadABD( const Game &g, const State &status,
int maxDepth, int turns_remaining,
int threshold, vector<cmd> &potentials );
static double boundedLookaheadScoreNewDecay( const Game &g, const State &status,
int depth, int max_depth,
int turns_remaining, int oldScore, double currScore, double decay, State *stack );
};
/////////////////////////////////////////////////////////////////////////
// Utilities
/////////////////////////////////////////////////////////////////////////
// this is a sanity check. It is a superficial check that compares to what
// we are receiving from the game engine.
bool equivalent(const Player &e1, const Player &e2);
bool equivalent(const Enemy &e1, const Enemy &e2);
bool equivalent(const State &s1, const State &s2, bool verbose=false);
#endif
| [
"howard.cheng@uleth.ca"
] | howard.cheng@uleth.ca |
2426a700b84018d1776112d82718ab18bf22ac12 | c031fe63baf74199d0aaabd4c5901258d7ae19c5 | /pat/1080.cpp | 8b8bdda0ddc6220f2654e814e2fbe67f08e29de4 | [] | no_license | xjhqre/PAT | 15eb28b6eec93dbd7624de6ca798bd25898507fc | d7571dddd683bf8068e38ce0c78191b63770247b | refs/heads/master | 2023-05-06T04:43:30.527330 | 2021-05-30T06:23:03 | 2021-05-30T06:23:03 | 372,139,446 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,088 | cpp | #include <algorithm>
#include <iostream>
#include <map>
#include <set>
#include <cstdio>
#include <string>
#include <string.h>
#include <cctype>
#include <math.h>
#include <vector>
using namespace std;
struct StuInfo{
string xh;
int fs1, fs2, fs3;
double zf;
};
int cmp(StuInfo a, StuInfo b){
return a.zf != b.zf ? a.zf > b.zf : a.xh < b.xh;
}
map<string, int> fs1, fs2, fs3, c, c1, c2;
map<string, double> zf;
int main() {
int p, m, n;
cin >> p >> m >> n;
string xh, stu[10005];
int fs, cnt = 0;
for (int i = 0; i < p; i++){
cin >> xh >> fs;
if (c[xh] == 0){
stu[cnt] = xh;
c[xh] = 1;
cnt++;
}
fs1[xh] = fs;
}
for (int i = 0; i < m; i++){
cin >> xh >> fs;
if (c[xh] == 0){
stu[cnt] = xh;
c[xh] = 1;
cnt++;
}
fs2[xh] = fs;
c1[xh] = 1;
}
for (int i = 0; i < n; i++){
cin >> xh >> fs;
if (c[xh] == 0){
stu[cnt] = xh;
c[xh] = 1;
cnt++;
}
fs3[xh] = fs;
c2[xh] = 1;
}
for (int i = 0; i < 10005; i++){
if (fs2[stu[i]] > fs3[stu[i]]){
zf[stu[i]] = round(fs2[stu[i]] * 0.4 + fs3[stu[i]] * 0.6);
}
else{
zf[stu[i]] = fs3[stu[i]];
}
}
StuInfo stuinfo[10005];
for (int i = 0; i < 10005; i++){
if (c1[stu[i]] == 0) fs2[stu[i]] = -1;
if (c2[stu[i]] == 0) fs3[stu[i]] = -1;
}
for (int i = 0; i < 10005; i++){
stuinfo[i].xh = stu[i];
stuinfo[i].fs1 = fs1[stu[i]];
stuinfo[i].fs2 = fs2[stu[i]];
stuinfo[i].fs3 = fs3[stu[i]];
stuinfo[i].zf = zf[stu[i]];
}
sort(stuinfo, stuinfo + 10005, cmp);
for (int i = 0; i < 10005; i++){
if (stuinfo[i].fs1 >= 200 && stuinfo[i].zf >= 60){
printf("%s %d %d %d %.0f\n", stuinfo[i].xh.c_str(), stuinfo[i].fs1,
stuinfo[i].fs2, stuinfo[i].fs3, stuinfo[i].zf);
}
}
system("pause");
return 0;
} | [
"859425698@qq.com"
] | 859425698@qq.com |
8cc2df3d4fc12f7fec2c57ba7b1c7d0086d93f02 | 81b2279b2b24636ccaebb091d7543537142a9272 | /leetcode原生/942_增减字符串匹配_easy/借鉴思想.cpp | 4b5d3b8073a5209693f769a6f77ce3736488d3f7 | [] | no_license | gwtak/My_Leetcode | be6a8d5a050bcd378ae8cfd38ea5b0e5d6f4f70d | bcbebcc8e6c9c58237698ab7534aa3718c489f21 | refs/heads/master | 2022-12-31T22:23:20.771120 | 2020-10-20T10:29:19 | 2020-10-20T10:29:19 | 263,764,562 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,124 | cpp | /*给定只含 "I"(增大)或 "D"(减小)的字符串 S ,令 N = S.length。
返回 [0, 1, ..., N] 的任意排列 A 使得对于所有 i = 0, ..., N-1,都有:
如果 S[i] == "I",那么 A[i] < A[i+1]
如果 S[i] == "D",那么 A[i] > A[i+1]
示例 1:
输入:"IDID"
输出:[0,4,1,3,2]
示例 2:
输入:"III"
输出:[0,1,2,3]
示例 3:
输入:"DDI"
输出:[3,2,0,1]
提示:
1 <= S.length <= 10000
S 只包含字符 "I" 或 "D"。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/di-string-match
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。*/
class Solution {
public:
vector<int> diStringMatch(string S) {
int low=0;
int high=S.size();
vector<int> res;
for(int i=0;i<S.size();i++){
if(S[i]=='I'){
res.push_back(low);
low++;
}
else{
res.push_back(high);
high--;
}
}
res.push_back(low);
return res;
}
}; | [
"1969323198@qq.com"
] | 1969323198@qq.com |
579763f1ba366750d2a81245654aa2d1bfcd1031 | 3e92edd742d419f6abc4ba17ae90d40f0d59413b | /firmware/firmware/firmware.ino | a1dae519f929f974a5f64a85206e43d91c2f6a7f | [] | no_license | NimraZeeshan/WeatherMonitoringSystem-Iot | 2938ac87d5051c7cbcec5e77b96572c18f388a45 | e9db84a71a090ff85d8b62465c227955163d1c71 | refs/heads/master | 2023-06-03T05:35:09.775806 | 2020-07-09T06:40:38 | 2020-07-09T06:40:38 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,674 | ino | #include <ESP8266WiFi.h> //Including the ESP8266 WiFi library in order to usm them
#include <ESP8266HTTPClient.h>
#include <ArduinoJson.h>
#include <Wire.h>
//FOR SOIL MOISTURE
int soil_pin = D0; // Soil Sensor input at PIN D0
int soil_value = 0;
//FOR DHT11
#include <Adafruit_Sensor.h> //In order to use DHT sensor we have to include this library first
#include <DHT.h> //Including the DHT library
char dstmp[20], btmp[20], bprs[20], balt[20];
bool bmp085_present = true;
#define DHTPIN 2 //Connect the DHT11 sensor's data pin to GPIO2(D4) of Nodemcu
#define DHTTYPE DHT11 //Mention the type of sensor we are using, Here it it DHT11, for DHT22 just replace DHT11 with DHT22
float temp = 0.000 ;
float humidity = 0.000 ;
DHT dht(DHTPIN, DHTTYPE); //Defining the pin and the dhttype
//FOR BMP180
//For using I2C connection of BMP180 in order to connect it to the board
#include <Adafruit_BMP085.h> //Including the library for BMP180
Adafruit_BMP085 bmp; //Defining the object bmp
#define I2C_SCL 12 //Connect SCL pin of BMP180 to GPIO12(D6) of Nodemcu
#define I2C_SDA 13 //Connect SDA pin of BMP180 to GPIO13(D7) of Nodemcu
float pressure = 0.000;
//FOR RAIN SENSOR
int rain_sensor = A0;
int rain_sensor_value = 0; //variable to store RainDrop Sensor Module's output value
//________________________Mention the SSID and Password____________________________________________________
const char* ssid = "shresthas_wlink";//SSID of the WiFi hotspot available
const char* password = "alumanchor"; //Password of the WiFi
void setup() {
Serial.begin(9600);
//Connecting nodemcu with wifi
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED)
{
delay(1000);
Serial.println("Connecting...");
}
//starting DTH & BMP 180
dht.begin(); //Initializing the DHT sensor
Wire.begin(I2C_SDA, I2C_SCL); //Initializing the I2C connection BMP180
}
//MAIN
void loop() {
//FOR SOIL MOISTURE
startReadingSoilMoisture();
startReadingDHT();
startReadingRainSensor();
startReadingBMPSensor();
Serial.println("Sending data to cloud....... ");
// apiCall();
}
//FOR SOIL MOISTURE
void startReadingSoilMoisture() {
Serial.println("Started Reading SoilMoisture : ");
soil_value = analogRead(soil_pin); //Takes reading from soil moisture sensor
Serial.print("MOISTURE LEVEL : ");
Serial.println(soil_value);
}
//FOR DHT
void startReadingDHT() {
//______________________Getting the Humidity and temperature value from DHT11____________________________
Serial.println("Started Reading Humidity : ");
humidity = dht.readHumidity();
Serial.print("Humidity : ");
Serial.println(humidity);
Serial.println("Started Reading Temperature : ");
temp = dht.readTemperature(); // or dht.readTemperature(true) for Fahrenheit
Serial.print("Temperature : ");
Serial.println(temp);
}
//FOR RAINSENSOR
void startReadingRainSensor() {
//_____________________________________Checking for Rain______________________________________________________
Serial.println("Started RAINSENSOR : ");
rain_sensor_value = analogRead(rain_sensor);
Serial.print("RAINSENSOR : ");
Serial.println(rain_sensor_value);
rain_sensor_value = constrain(rain_sensor, 150, 440);
rain_sensor_value = map(rain_sensor, 150, 440, 1023, 0);
}
//FOR BMP180 Sensor
void startReadingBMPSensor()
{
Serial.println("Started Reading Pressure : ");
if (bmp.begin())
{
//BMP180 is working
//______________________Reading the value of Pressure from the BMP180__________________
pressure = bmp.readPressure() / 100; // Division by 100 makes it in millibars
Serial.print("Pressure : ");
Serial.println(pressure);
}
}
//SENDING DATA TO SERVER THROUGHT API CALL
void apiCall() {
String deviceKey = "123456";
String postbody = "";
postbody += "{\"device_key\":";
postbody += deviceKey;
postbody += ",\"temperature\":";
postbody += temp;
postbody += ",\"pressure\":";
postbody += pressure;
postbody += ",\"rain\":";
postbody += rain_sensor_value;
postbody += ",\"humidity\":";
postbody += humidity;
postbody += ",\"soil_moisture\":";
postbody += soil_value;
postbody += "}";
if (WiFi.status() == WL_CONNECTED) {
HTTPClient http; //Object of class HTTPClient
http.begin("http://localhost:3000/api/update-stats");
http.addHeader("Content-Type", "application/json");
int httpCode = http.POST(postbody);
if (httpCode > 0) {
}
http.end(); //Close connection
}
delay(10000); //10sec delay
}
| [
"winneecreztha@gmail.com"
] | winneecreztha@gmail.com |
a7a5990e8b71a25b7037651b64b02acf95d1cf3e | 49fac4986eb2c78a7b2dc15eb5bf4471bd29d3ae | /tags/FRAMEWAVE_1.1_BETA/UnitTest/UnitTestCollection/ColorModelConversion/CMC_FunctionObjects.h | 98f7d515d9a14990b3200b428b401d6a1c161977 | [
"Apache-2.0"
] | permissive | imazen/framewave | 1f2f427cc8a4ff3a4d02b619c2f32fe7693039d8 | e6390439955a103d5a97d1568a99d3e02a11376d | refs/heads/master | 2021-01-24T14:56:16.069570 | 2014-10-23T21:55:58 | 2014-10-23T21:55:58 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,260 | h | /*
Copyright (c) 2006-2008 Advanced Micro Devices, Inc. All Rights Reserved.
This software is subject to the Apache v2.0 License.
*/
#ifndef __CMC_FUNCTION_OBJECTS_H__
#define __CMC_FUNCTION_OBJECTS_H__
#include "Object.h"
#include "FunctionSignatures.h"
// --------------------
// Channel to Channel
// --------------------
// Even numbered width buffer (422 Sampling)
template< typename TS, U32 srcChannels, typename TD, U32 dstChannels >
class SrcDstRoiEvenWidth : public SrcDstRoiGeneric< TS, srcChannels, TD, dstChannels, AdviceRoiEvenWidth >
{
typedef SrcDstRoiGeneric< TS, srcChannels, TD, dstChannels, AdviceRoiEvenWidth > BaseClass;
public:
SrcDstRoiEvenWidth( UnitTestCatalogBase & parent, const char *name, typename BaseClass::Fn fn )
: BaseClass( parent, name, fn )
{
}
};
template< typename TS, U32 srcChannels, typename TD, U32 dstChannels >
class SrcDstRoiEven : public SrcDstRoiGeneric< TS, srcChannels, TD, dstChannels, AdviceRoiEvenWidthEvenHeight >
{
typedef SrcDstRoiGeneric< TS, srcChannels, TD, dstChannels, AdviceRoiEvenWidthEvenHeight > BaseClass;
public:
SrcDstRoiEven( UnitTestCatalogBase & parent, const char *name, typename BaseClass::Fn fn )
: BaseClass( parent, name, fn )
{
}
};
// --------------------
// Channel to Planar
// --------------------
// --------------------
// Planar to Channel
// --------------------
// --------------------
// Planar to Planar
// --------------------
//
//// Planar to Planar
//template< typename TS, U32 srcPlanes, typename TD, U32 dstPlanes >
//class PSrcPDstRoiEvenWidth : public PSrcPDstRoiGeneric< TS, srcPlanes, TD, dstPlanes, AdviceRoiEvenWidth >
//{
// typedef PSrcPDstRoiGeneric< TS, srcPlanes, TD, dstPlanes, AdviceRoiEvenWidth > BaseClass;
//public:
// PSrcPDstRoiEvenWidth( UnitTestCatalogBase & parent, const char *name, typename BaseClass::Fn fn )
// : PSrcPDstRoiGeneric< TS, srcPlanes, TD, dstPlanes, AdviceRoiEvenWidth >( parent, name ), m_fn(fn)
// {
// }
//};
//
//// --------------------------------
//// Buffer width and height are even
//// --------------------------------
//// Channel to Channel
//template< typename TS, U32 srcChannels, typename TD, U32 dstChannels >
//class SrcDstRoiEvenWidth : public SrcDstRoiGeneric< TS, srcChannels, TD, dstChannels, AdviceRoiEvenWidth >
//{
// typedef SrcDstRoiGeneric< TS, srcChannels, TD, dstChannels, AdviceRoiEvenWidth > BaseClass;
//public:
// SrcDstRoiEvenWidth( UnitTestCatalogBase & parent, const char *name, typename BaseClass::Fn fn )
// : SrcDstRoiGeneric< TS, srcChannels, TD, dstChannels, AdviceRoiEvenWidth >( parent, name, fn )
// {
// }
//};
//
//// Planar to Planar
//template< typename TS, U32 srcPlanes, typename TD, U32 dstPlanes >
//class PSrcPDstRoiEven : public PSrcPDstRoiGeneric< TS, srcPlanes, TD, dstPlanes, AdviceRoiEvenWidthEvenHeight >
//{
// typedef PSrcPDstRoiGeneric< TS, srcPlanes, TD, dstPlanes, AdviceRoiEvenWidthEvenHeight > BaseClass;
//public:
// PSrcPDstRoiEven( UnitTestCatalogBase & parent, const char *name, typename BaseClass::Fn fn )
// : BaseClass( parent, name ), m_fn(fn)
// {
// }
//};
//// --------------------------------
//// Function Signature: (const TS* const[], int, TS*[], int[], FwiSize)
//// --------------------------------
//template< typename TS, U32 srcPlanes, typename TD, U32 dstPlanes, class Advice >
//class PSrcPDstRoiMultipleDstStepGeneric : public PDstRoiBase< TD, dstPlanes, Advice >
//{
//public:
// typedef FwStatus (STDCALL *Fn)( const TS * const [], int, TD *[], int[], FwiSize );
// const char ** m_srcInit;
// Fn m_fn;
//
// PSrcPDstRoiMultipleDstStepGeneric( UnitTestCatalogBase & parent, const char *name, Fn fn )
// : PDstRoiBase< TD, dstPlanes, Advice >( parent, name ), m_fn(fn)
// {
// }
//
// void RunTest( const char **srcInit, const char **dstExpected, TD errorMargin = MemOps<TD>::Zero(), const FwStatus expectedReturn = fwStsNoErr )
// {
// m_srcInit = srcInit;
// ExecuteTest( NULL, dstExpected, errorMargin, expectedReturn );
// }
//
// virtual void CallFn( const Advice & adv,
// FwStatus & stat,
// PlanarBuffer< TD, dstPlanes >& dst )
// {
// int dstStep[dstPlanes];
// U32 srcAlignments[srcPlanes];
// for( int plane = 0; plane < srcPlanes; plane++ )
// {
// srcAlignments[plane] = adv.Alignment();
// }
// for( int plane = 0; plane < dstPlanes; plane++ )
// {
// dstStep[plane] = dst.StepBytes();
// }
//
// PlanarBuffer< TS, srcPlanes > src( m_srcInit, adv.BufferWidth(), adv.BufferHeight(), srcAlignments );
// try
// {
// this->timer.Start();
// stat = m_fn( src.Ptr(), src.StepBytes(), dst.Ptr(), dstStep, adv.Roi() );
// this->timer.Stop();
// }
// catch( ... )
// {
// this->timer.Stop();
// stat = (FwStatus)EXCEPTION_ERR;
// }
// }
//};
//template< typename TS, U32 srcPlanes, typename TD, U32 dstPlanes >
//class PSrcPDstRoiMultipleDstStep : public PSrcPDstRoiMultipleDstStepGeneric< TS, srcPlanes, TD, dstPlanes, AdviceRoi >
//{
// typedef PSrcPDstRoiMultipleDstStepGeneric< TS, srcPlanes, TD, dstPlanes, AdviceRoi > BaseClass;
//public:
// PSrcPDstRoiMultipleDstStep( UnitTestCatalogBase & parent, const char *name, typename BaseClass::Fn fn )
// : BaseClass( parent, name, fn )
// {}
//};
//template< typename TS, U32 srcPlanes, typename TD, U32 dstPlanes >
//class PSrcPDstRoiMultipleDstStepEvenWidth : public PSrcPDstRoiMultipleDstStepGeneric< TS, srcPlanes, TD, dstPlanes, AdviceRoiEvenWidth >
//{
// typedef PSrcPDstRoiMultipleDstStepGeneric< TS, srcPlanes, TD, dstPlanes, AdviceRoiEvenWidth > BaseClass;
//public:
// PSrcPDstRoiMultipleDstStepEvenWidth( UnitTestCatalogBase & parent, const char *name, typename BaseClass::Fn fn )
// : BaseClass( parent, name, fn )
// {}
//};
#endif // __CMC_FUNCTION_OBJECTS_H__
| [
"jalby@f364fc6c-7e41-0410-b16c-eb8c68fe7df8"
] | jalby@f364fc6c-7e41-0410-b16c-eb8c68fe7df8 |
a32acb84f8d56582b887eae0e3c78dc10b7ba017 | be9e723c405521846ca12425da989c0cb15006f1 | /1040/main.cpp | 0b8e81bfad7907c19cba7c7bced7c1b63f49d2c1 | [] | no_license | mhayk/uri | 21edfc2dfc28afb909cd7b82d0a0dcc6869a1d42 | ecfd6e67b8c5fb962c4eaad8b85fee1accc9d3d5 | refs/heads/master | 2021-01-20T00:13:20.181812 | 2020-01-21T21:36:11 | 2020-01-21T21:36:11 | 89,097,052 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 914 | cpp | #include <iostream>
#include <iomanip>
using namespace std;
int main()
{
double n1,n2,n3,n4,average;
cin >> n1 >> n2 >> n3 >> n4;
average = (n1*0.2)+(n2*0.3)+(n3*0.4)+(n4*0.1);
cout << "Media: " << fixed << setprecision(1) << average << endl;
if(average > 7.0)
{
cout << "Aluno aprovado." << endl;
return 0;
}
if(average < 5.0)
{
cout << "Aluno reprovado." << endl;
return 0;
}
if(average >= 5.0 && average <= 6.9)
{
cout << "Aluno em exame." << endl;
cin >> n1;
cout << "Nota do exame: " << fixed << setprecision(1) << n1 << endl;
average = (average+n1)/2;
if(average >= 5.0)
cout << "Aluno aprovado." << endl;
else
cout << "Aluno reprovado." << endl;
cout << "Media final: " << fixed << setprecision(1) << average << endl;
}
return 0;
}
| [
"eu@mhayk.com.br"
] | eu@mhayk.com.br |
4704995dde0b34c455faeca8b62a6a6104edb8ab | 48591e6fe907d1d1c15ea671db3ab32b6d60f5a6 | /dizuo/Tutorial3_src/src/MainWindow.h | 6fc21dac8c198aef77382e9fc194c7b63f99e7ab | [] | no_license | dizuo/dizuo | 17a2da81c0ad39d77e904012cb9fbb8f6681df1b | 6083ca9969d9d45b72859d9795544ccdf2d13b1c | refs/heads/master | 2021-10-24T21:16:19.910030 | 2021-10-23T07:17:30 | 2021-10-23T07:17:30 | 1,253,554 | 7 | 5 | null | null | null | null | UTF-8 | C++ | false | false | 1,527 | h | #ifndef _MAINWINDOW_H_
#define _MAINWINDOW_H_
#include <Windows.h>
#include "GL/gl.h"
#include "StateManager.h"
// The main window class. It wraps the HANDLE of the window and initializes the
// openGL rendering context. It is also in charge of processing the different
// event messages.
class CMainWindow
{
public:
CMainWindow(int iWidth, int iHeight, bool bFullScreen);
~CMainWindow();
// Called by the application class to update the game logic
void Update(DWORD dwCurrentTime);
// Called by the application class when the window need to be redrawn.
void Draw();
private:
// Register the window class with the correct window procedure (OnEvent)
void RegisterWindowClass();
// Create the rendering context used by OpenGL
void CreateContext();
// Initialize openGL
void InitGL();
// Called when a WM_SIZE message is received
void OnSize(GLsizei width, GLsizei height);
// Static function which will be the window procedure callback
static LRESULT CALLBACK OnEvent(HWND Handle, UINT Message, WPARAM wParam, LPARAM lParam);
// Processes the messages that were received in OnEvent.
void ProcessEvent(UINT Message, WPARAM wParam, LPARAM lParam);
// The window handle
HWND m_hWindow;
// The window device context
HDC m_hDeviceContext;
// The openGL context.
HGLRC m_hGLContext;
// Specifies if the window is fullscreen.
bool m_bFullScreen;
// The state manager
CStateManager* m_pStateManager;
};
#endif // _MAINWINDOW_H_ | [
"ren.yafee@gmail.com@107d8d70-eac7-11de-9d05-050bbbc75a16"
] | ren.yafee@gmail.com@107d8d70-eac7-11de-9d05-050bbbc75a16 |
a285cba0eda428fb1466365b14b2b18961bef46c | cee86d816f709be28942a19ef5cc5ed9b36fa363 | /libraries/Rtc_by_Makuna/src/RtcDS1307.h | 318c39af88216bfd2f719e56235b7216b43f8ef7 | [] | no_license | nicolalombardi/IoT-Thermostat-ESP8266 | 96bd93331290dda983c74b8ff1e3be4b8a9163f5 | 2f85775d5334ced58d72826a456bb2145cf7ebf1 | refs/heads/master | 2022-01-24T18:44:02.762228 | 2021-12-29T11:35:38 | 2021-12-29T11:35:38 | 94,616,059 | 3 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 5,731 | h |
#ifndef __RTCDS1307_H__
#define __RTCDS1307_H__
#include <Arduino.h>
#include <RtcDateTime.h>
#include "RtcUtility.h"
//I2C Slave Address
const uint8_t DS1307_ADDRESS = 0x68;
//DS1307 Register Addresses
const uint8_t DS1307_REG_TIMEDATE = 0x00;
const uint8_t DS1307_REG_STATUS = 0x00;
const uint8_t DS1307_REG_CONTROL = 0x07;
const uint8_t DS1307_REG_RAMSTART = 0x08;
const uint8_t DS1307_REG_RAMEND = 0x3f;
const uint8_t DS1307_REG_RAMSIZE = DS1307_REG_RAMEND - DS1307_REG_RAMSTART;
//DS1307 Register Data Size if not just 1
const uint8_t DS1307_REG_TIMEDATE_SIZE = 7;
// DS1307 Control Register Bits
const uint8_t DS1307_RS0 = 0;
const uint8_t DS1307_RS1 = 1;
const uint8_t DS1307_SQWE = 4;
const uint8_t DS1307_OUT = 7;
// DS1307 Status Register Bits
const uint8_t DS1307_CH = 7;
enum DS1307SquareWaveOut
{
DS1307SquareWaveOut_1Hz = 0b00010000,
DS1307SquareWaveOut_4kHz = 0b00010001,
DS1307SquareWaveOut_8kHz = 0b00010010,
DS1307SquareWaveOut_32kHz = 0b00010011,
DS1307SquareWaveOut_High = 0b10000000,
DS1307SquareWaveOut_Low = 0b00000000,
};
template<class T_WIRE_METHOD> class RtcDS1307
{
public:
RtcDS1307(T_WIRE_METHOD& wire) :
_wire(wire)
{
}
void Begin()
{
_wire.begin();
}
bool IsDateTimeValid()
{
return GetIsRunning();
}
bool GetIsRunning()
{
uint8_t sreg = getReg(DS1307_REG_STATUS);
return !(sreg & _BV(DS1307_CH));
}
void SetIsRunning(bool isRunning)
{
uint8_t sreg = getReg(DS1307_REG_STATUS);
if (isRunning)
{
sreg &= ~_BV(DS1307_CH);
}
else
{
sreg |= _BV(DS1307_CH);
}
setReg(DS1307_REG_STATUS, sreg);
}
void SetDateTime(const RtcDateTime& dt)
{
// retain running state
uint8_t sreg = getReg(DS1307_REG_STATUS) & _BV(DS1307_CH);
// set the date time
_wire.beginTransmission(DS1307_ADDRESS);
_wire.write(DS1307_REG_TIMEDATE);
_wire.write(Uint8ToBcd(dt.Second()) | sreg);
_wire.write(Uint8ToBcd(dt.Minute()));
_wire.write(Uint8ToBcd(dt.Hour())); // 24 hour mode only
_wire.write(Uint8ToBcd(dt.DayOfWeek()));
_wire.write(Uint8ToBcd(dt.Day()));
_wire.write(Uint8ToBcd(dt.Month()));
_wire.write(Uint8ToBcd(dt.Year() - 2000));
_wire.endTransmission();
}
RtcDateTime GetDateTime()
{
_wire.beginTransmission(DS1307_ADDRESS);
_wire.write(DS1307_REG_TIMEDATE);
_wire.endTransmission();
_wire.requestFrom(DS1307_ADDRESS, DS1307_REG_TIMEDATE_SIZE);
uint8_t second = BcdToUint8(_wire.read() & 0x7F);
uint8_t minute = BcdToUint8(_wire.read());
uint8_t hour = BcdToBin24Hour(_wire.read());
_wire.read(); // throwing away day of week as we calculate it
uint8_t dayOfMonth = BcdToUint8(_wire.read());
uint8_t month = BcdToUint8(_wire.read());
uint16_t year = BcdToUint8(_wire.read()) + 2000;
return RtcDateTime(year, month, dayOfMonth, hour, minute, second);
}
void SetMemory(uint8_t memoryAddress, uint8_t value)
{
uint8_t address = memoryAddress + DS1307_REG_RAMSTART;
if (address <= DS1307_REG_RAMEND)
{
setReg(address, value);
}
}
uint8_t GetMemory(uint8_t memoryAddress)
{
uint8_t value = 0;
uint8_t address = memoryAddress + DS1307_REG_RAMSTART;
if (address <= DS1307_REG_RAMEND)
{
value = getReg(address);
}
return value;
}
uint8_t SetMemory(uint8_t memoryAddress, const uint8_t* pValue, uint8_t countBytes)
{
uint8_t address = memoryAddress + DS1307_REG_RAMSTART;
uint8_t countWritten = 0;
if (address <= DS1307_REG_RAMEND)
{
_wire.beginTransmission(DS1307_ADDRESS);
_wire.write(address);
while (countBytes > 0 && address <= DS1307_REG_RAMEND)
{
_wire.write(*pValue++);
address++;
countBytes--;
countWritten++;
}
_wire.endTransmission();
}
return countWritten;
}
uint8_t GetMemory(uint8_t memoryAddress, uint8_t* pValue, uint8_t countBytes)
{
uint8_t address = memoryAddress + DS1307_REG_RAMSTART;
uint8_t countRead = 0;
if (address <= DS1307_REG_RAMEND)
{
if (countBytes > DS1307_REG_RAMSIZE)
{
countBytes = DS1307_REG_RAMSIZE;
}
_wire.beginTransmission(DS1307_ADDRESS);
_wire.write(address);
_wire.endTransmission();
_wire.requestFrom(DS1307_ADDRESS, countBytes);
while (countBytes-- > 0)
{
*pValue++ = _wire.read();
countRead++;
}
}
return countRead;
}
void SetSquareWavePin(DS1307SquareWaveOut pinMode)
{
setReg(DS1307_REG_CONTROL, pinMode);
}
private:
T_WIRE_METHOD& _wire;
uint8_t getReg(uint8_t regAddress)
{
_wire.beginTransmission(DS1307_ADDRESS);
_wire.write(regAddress);
_wire.endTransmission();
// control register
_wire.requestFrom(DS1307_ADDRESS, (uint8_t)1);
uint8_t regValue = _wire.read();
return regValue;
}
void setReg(uint8_t regAddress, uint8_t regValue)
{
_wire.beginTransmission(DS1307_ADDRESS);
_wire.write(regAddress);
_wire.write(regValue);
_wire.endTransmission();
}
};
#endif // __RTCDS1307_H__ | [
"lombardi.nicola23@gmail.com"
] | lombardi.nicola23@gmail.com |
71b64fb477f9666e726a9baea9d9504331184a7c | 6ea9796da14f3ee7880d04a51c6bff25713b3206 | /hackerrank/contests/week1-challenge/maximizing-xor/main.cc | fd5cc6393ec35355932b167b9d9d35d96c88da4b | [] | no_license | vguerra/programming_contests | 79def4d0a864811a48038b270cebda3fbdc0f000 | 025b064ae0675f015e61cb3066d099b814cd3871 | refs/heads/master | 2021-01-22T11:36:30.364021 | 2015-03-30T19:28:25 | 2015-03-30T19:28:25 | 25,770,826 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 774 | cc | // Victor Guerra <vguerra@gmail.com>
// 2014-04-21
// https://www.hackerrank.com/contests/w1/challenges/maximizing-xor
#include <iostream>
#include <cmath>
#include <cstdint>
using namespace std;
uint32_t maxXor(uint32_t L, uint32_t R) {
uint32_t mask = 0;
uint32_t extra_bits = 0;
uint32_t bitsL = floor(log2(L) + 1);
uint32_t bitsR = floor(log2(R) + 1);
if (bitsL == bitsR) {
uint32_t bitsDiff = floor(log2(L ^ R) + 1);
uint32_t filter = ~(~0 << bitsDiff);
L &= filter;
R &= filter;
extra_bits = bitsL - bitsDiff;
}
for (int i = 0; i < floor(log2(R - L) + 1) + extra_bits; ++i) {
mask = (mask << 1) | 1;
}
return mask;
}
int main() {
uint32_t L, R;
cin >> L >> R;
cout << maxXor(L, R) << "\n";
return 0;
}
| [
"vguerra@gmail.com"
] | vguerra@gmail.com |
14470bb80006441122a783a275cfc7223addacfc | 11fb8d8468f69d5e53aff279e67782b5cf347dbe | /x_table.hpp | c72daebcb2c9cd3746ee36e5182a17f9cce36b81 | [
"Apache-2.0"
] | permissive | da0x/venv | c004e8901a8b6b125d46ceb26228388caafc0145 | 8e2a7ae0cf7c3fd59b43a7dff5c7ad57baaedf80 | refs/heads/master | 2023-05-26T08:02:21.950541 | 2023-05-19T16:49:44 | 2023-05-19T16:49:44 | 114,177,005 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,022 | hpp | //C++
//////////////////////////////////////////////////////////////////////////////
// //
// Filename : x_table.hpp //
// Created by : Daher Alfawares //
// Created Date : 06/20/2009 //
// License : Apache License 2.0 //
// //
// Copyright 2009 Daher Alfawares //
// //
// Licensed under the Apache License, Version 2.0 (the "License"); //
// you may not use this file except in compliance with the License. //
// You may obtain a copy of the License at //
// //
// http://www.apache.org/licenses/LICENSE-2.0 //
// //
// Unless required by applicable law or agreed to in writing, software //
// distributed under the License is distributed on an "AS IS" BASIS, //
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. //
// See the License for the specific language governing permissions and //
// limitations under the License. //
// //
//////////////////////////////////////////////////////////////////////////////
/*
X Table is a C++ class that allows you to format your data in an ASCII dynamic table structure.
Example:
x::table myTable("Table Title");
myTable ("header 1")("header 2")++;
myTable ("value 11")("value 12")++;
myTable ("value 21")("value 22")++;
std::cout << myTable;
Output:
+---------------------+
|Table Title |
+----------+----------+
| header 1 | header 2 |
+----------+----------+
| value 11 | value 12 |
| value 21 | value 22 |
+----------+----------+
*/
#ifndef _X_Table__0a61eabe_d038_4d30_a6fb_e202b2dfd6a9
#define _X_Table__0a61eabe_d038_4d30_a6fb_e202b2dfd6a9
#include <iostream>
#include <vector>
#include <string>
#include <iomanip>
#include <numeric>
#include <sstream>
namespace x
{
// forward:
// the following allows adding a C style string to an std::string and returns an std::string.
// example:
// std::string a = "abc";
// std::string b = "123" + a;
//
inline std::string operator + ( const char*a, const std::string& b );
inline std::string itoa( const int &i );
inline int atoi( const std::string&s );
// lexical cast.
template<typename _To, typename _From> class lexical_cast;
struct scoped_mute_s;
// formats the output.
std::size_t length( std::string _String);
std::string fill(std::string _Str, std::size_t _Size);
class endl {};
class table
{
public:
std::string title;
size_t column;
std::vector<std::string> columns;
std::vector<std::size_t> column_widths;
std::string comment;
std::string Prefix; // line prefix.
table( std::string t ):title(t),column(0){}
std::vector< std::vector<std::string> > rows;
table & operator<<(std::string t){
return (*this)(t);
}
table & operator<<(int t){
std::stringstream fstr;
fstr << t;
return (*this)<< fstr.str();
}
table & operator()(std::string t)
{
if( column >= columns.size() )
{
columns.push_back("");
column_widths.push_back(0);
}
columns[column] = t;
if( column_widths[column] < length(t) )
column_widths[column] = length(t);
++column;
return *this;
}
table & operator()(int i)
{
return (*this)(itoa(i));
}
void operator ++(int)
{
column = 0;
rows.push_back( columns );
}
std::string prefix(){ return Prefix; }
void prefix( std::string _P ){ Prefix=_P; }
std::string endl(){ return "\r\n" + prefix() + " "; }
};
inline std::ostream& operator << ( std::ostream& _Str, table& T )
{
int width = std::accumulate( T.column_widths.begin(), T.column_widths.end(), 0 );
width += 3*T.columns.size();
_Str << std::setiosflags(std::ios::left);
_Str << T.endl();
// top border.
// _Str
// << ' ';
// for( int b=0; b< width-1; b++ )
// _Str
// << '-';
// _Str
// << ' '
// << T.endl();
// title.
_Str
<< " "
<< std::setw(width-1)
<< T.title
<< ""
<< T.endl();
// middle border
for( size_t i=0; i< T.columns.size(); i++ )
_Str
<< " "
<< std::setw( static_cast<int>(T.column_widths[i]) )
<< std::setfill('-')
<< ""
<< std::setfill(' ')
<< " ";
_Str
<< " "
<< T.endl();
if( !T.rows.empty() || !T.rows[0].empty() )
{
size_t i=0,j=0;
// first row as header.
for( i=0; i< T.columns.size(); i++ )
{
_Str
<< " "
<< fill( T.rows[j][i], T.column_widths[i] )
<< " ";
}
_Str
<< " "
<< T.endl();
// middle border
for( size_t i=0; i< T.columns.size(); i++ )
{
_Str
<< " "
<< std::setw( static_cast<int>(T.column_widths[i]) )
<< std::setfill(' ')
<< ""
<< std::setfill(' ')
<< " ";
}
_Str
<< " "
<< T.endl();
// comment if available.
if( !T.comment.empty() )
_Str
<< " "
<< std::setw(width-1)
<< T.comment
<< " "
<< T.endl();
// full table.
for( size_t j=1; j< T.rows.size(); j++ )
{
for( size_t i=0; i< T.columns.size(); i++ )
{
_Str
<< " "
<< fill( T.rows[j][i], T.column_widths[i] )
<< " ";
}
_Str
<< " "
<< T.endl();
}
}
// bottom border.
for( size_t i=0; i< T.columns.size(); i++ )
{
_Str
<< " "
<< std::setw( static_cast<int>(T.column_widths[i]) )
<< std::setfill('-')
<< ""
<< std::setfill(' ')
<< " ";
}
_Str << std::resetiosflags(std::ios::left);
_Str
<< " "
<< std::endl;
return _Str;
}
inline std::string operator + ( const char*a, const std::string& b )
{
std::string c;
c += a;
c += b;
return c;
}
inline std::string itoa( const int &i )
{
std::stringstream Str;
Str << i;
return Str.str();
}
inline int atoi( const std::string&s )
{
int i;
std::istringstream Str(s);
Str >> i;
return i;
}
// lexical cast.
template<typename _To, typename _From> class lexical_cast
{
_From * from;
public:
lexical_cast<_To, _From>( _From From )
{
this->from = & From;
}
operator _To()
{
throw( "Bad lexical cast: " );
}
};
inline
std::size_t length( std::string _String){
std::size_t length = 0;
//while (*s)
for(auto Char:_String)
length += (Char++ & 0xc0) != 0x80;
return length;
}
inline
std::string fill(std::string _Str, std::size_t _Size){
if( length(_Str) < _Size ){
std::size_t Difference = _Size - length(_Str);
std::stringstream _Out;
_Out << _Str;
for(int i=0; i< Difference; i++){
_Out << " ";
}
return _Out.str();
}
return _Str;
}
} /* ascii */
#endif
| [
"daher.alfawares@live.com"
] | daher.alfawares@live.com |
71a04004ce3597809cef0bf899e7d4fe66de4445 | b7eed481dc4f381b27349ea72ae75f806a4334e0 | /leetcodecpp/leetcodecpp/pra/lookup.cc | 40970917982c2edc8d2d78c4a15166ccd80292dd | [] | no_license | weekenlee/leetcode-cpp | f351da2998a01a077ca010a52629602fca9a1b43 | 25188daa69bdd0891fed7795046c9d250fa106fc | refs/heads/master | 2022-12-14T23:52:17.183426 | 2022-01-20T13:40:55 | 2022-01-20T13:40:55 | 120,147,027 | 0 | 0 | null | 2022-12-08T00:02:30 | 2018-02-04T02:02:56 | C++ | UTF-8 | C++ | false | false | 867 | cc | #include <algorithm>
#include <iostream>
#include <typeinfo>
using std::cout;
using std::endl;
void g() {cout << "global g" <<endl;}
template <class T>
class Y {
public:
void g() { cout << "Y<" << typeid(T).name() << ">::g()" <<endl;}
void h() { cout << "Y<" << typeid(T).name() << ">::h()" <<endl;}
typedef int E;
};
typedef double E;
template<class T>
void swap(T& t1, T& t2) {
cout <<"global swap"<<endl;
T temp = t1;
t1 = t2;
t2 = temp;
}
template<class T> class X: public Y<T> {
public:
E f() {
g();
this->h();
T t1 = T(), t2 = T(1);
cout << t1 <<endl;
swap(t1, t2);
std::swap(t1, t2);
cout << typeid(E).name() <<endl;
return E(t2);
}
};
int main() {
X<int> x;
cout << x.f() <<endl;
}
| [
"lwj1396@163.com"
] | lwj1396@163.com |
bb9a88c6516ca58df75c7db5116be3de35ffa6b0 | a0966c0b5ea3c736e325b929fe86fe7907d2eb04 | /c002.cpp | 8979140b103dc7b7e264e66d6b35def518716289 | [] | no_license | hchs910739/zerojudge_c | ec58afb71c1193e6b2d573ed50e22f5ccdb0a5d3 | 95a85dd1991bf2e81223d95590c9cc3277631200 | refs/heads/master | 2020-03-22T07:56:31.689581 | 2018-07-04T14:42:28 | 2018-07-04T14:42:28 | 139,734,236 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 759 | cpp | #include<iostream>
using namespace std;
main(){
int n[250000];
int ans[250000];
int x,i,j;
for(i=0;;i++)
{
cin>>n[i];
if(n[i]==0)
{
break;
}
if(n[i]>=101)
{
ans[i]=n[i]-10;
}
else if(n[i]<=100)
{
ans[i]=91;
}
}
for(j=0;j<i;j++)
{
cout<<"f91("<<n[j]<<") = "<<ans[j]<<endl;
}
system("pause");
return 0;
}
| [
"40828533+hchs910739@users.noreply.github.com"
] | 40828533+hchs910739@users.noreply.github.com |
ef366a8827db21299642e3b78ed897c11681ddf2 | d09f25e7b28f14024c3e3d4e46ee1e400db9f19e | /c++-test/Programming_with_c++/cpt16_exception/AbstractGeometricObject.h | b5e37923f478596bd0d74b8d0db826a69c02cfef | [] | no_license | gj-sq/program_language_test | c6fc02aed1a43b78380b6b32a4e7b34adfdbc63e | 07218f82f5c5a9e98e2b3ed98dcd82d702291b29 | refs/heads/main | 2023-08-16T22:16:59.731207 | 2021-09-29T14:35:27 | 2021-09-29T14:35:27 | 405,794,259 | 0 | 0 | null | 2021-09-13T01:20:51 | 2021-09-13T01:20:50 | null | UTF-8 | C++ | false | false | 509 | h | #ifndef GEOMETICOBJECT_H
#define GEOMETICOBJECT_H
#include <string>
using namespace std;
class GeometricObject
{
private:
string color;
bool filled;
protected:
GeometricObject();
GeometricObject(const string& color, bool filled);
public:
string getColor() const;
void setColor(const string& color);
bool isFilled() const;
void setFilled(bool filled);
string toString() const;
virtual double getArea() const = 0;
virtual double getPerimeter() const = 0;
};
#endif
| [
"GuangJiHuang@qq.com"
] | GuangJiHuang@qq.com |
025e4f7d3b61b28ed257dc04f45695184ed2058f | 39b5fe34f34fdf1d25b5904b79647893379867a3 | /ClientSide/Handmade/Player.cpp | 14d06e4733341c625cf0b3ae43ccea38793965e9 | [
"MIT"
] | permissive | kakol20/Networking-For-Games---2D-Game | 2e6d2981b14c2c41728f779aecb114905f5f2fe1 | bf76aa4be9fbb05653d650f662db16594fcd28d2 | refs/heads/master | 2020-12-21T18:26:10.872686 | 2020-01-31T17:51:22 | 2020-01-31T17:51:22 | 236,521,700 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,707 | cpp | #include "Player.h"
#include <cmath>
#include <sstream>
#include "InputManager.h"
#include "ScreenManager.h"
#include "TextureManager.h"
Player::Player()
{
TheTexture::Instance()->LoadTextureFromFile("Assets/Sprites/Player.png", "PlayerSprite");
TheTexture::Instance()->LoadFontFromFile("Assets/Fonts/Formula1-Regular.ttf", 100, "MainFont");
m_taggedT.SetFont("MainFont");
m_scoreT.SetFont("MainFont");
m_sprite.SetTexture("PlayerSprite");
m_sprite.SetSpriteDimension(30, 30);
m_sprite.SetTextureDimension(1, 1, 30, 30);
m_taggedT.SetText("T");
m_taggedT.SetSize(15, 30);
m_position.x = TheScreen::Instance()->GetScreenSize().x / 2;
m_position.y = TheScreen::Instance()->GetScreenSize().y / 2;
}
Player::~Player()
{
}
void Player::Update()
{
KeyState keys = TheInput::Instance()->GetKeyStates();
if (keys[SDL_SCANCODE_W])
{
m_position.y -= 1;
}
if (keys[SDL_SCANCODE_S])
{
m_position.y += 1;
}
if (keys[SDL_SCANCODE_D])
{
m_position.x += 1;
}
if (keys[SDL_SCANCODE_A])
{
m_position.x -= 1;
}
if (m_tagged)
{
m_score = 0.0f;
}
else
{
m_score += 0.5f;;
}
std::stringstream str;
char scoreChar[10] = { '\0' };
str << m_score;
str >> scoreChar;
String score = "Score: ";
score += scoreChar;
m_scoreT.SetText(score.GetString());
m_scoreT.SetSize(score.Length() * 15, 30);
}
bool Player::Draw()
{
m_sprite.Draw(m_position.x - 15, m_position.y - 15);
if (m_tagged)
{
m_taggedT.Draw(m_position.x - 7, m_position.y - 15);
}
m_scoreT.Draw();
return true;
}
bool Player::IsTagged() const
{
return m_tagged;
}
void Player::SetTagged(const bool flag)
{
m_tagged = flag;
}
int Player::GetScore() const
{
return (int)floor(m_score);
}
| [
"adrianaquino.aquino33@gmail.com"
] | adrianaquino.aquino33@gmail.com |
ca217f495a4fe5059c2f087cbf0c7eaa54176d7f | 221e8fd8c12d916a847af856ae0667dc14511833 | /CDrawTool.hpp | eadb7ea7db917f726980ec5af62988c9e5834421 | [] | no_license | LikeSnooker/Sokoban | 6cb47ad79a3bdd4021447752aa14a3dd199175b7 | a95eacaa2e9eea793a07e45daf889aa11ece338f | refs/heads/master | 2021-04-15T05:58:17.732477 | 2018-03-22T13:02:10 | 2018-03-22T13:02:10 | 126,334,920 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,930 | hpp | //
// CDrawer.hpp
// sokoban
//
// Created by 张雨 on 15/9/22.
// Copyright © 2015年 张雨. All rights reserved.
//
#ifndef CDrawTool_hpp
#define CDrawTool_hpp
#import <UIKit/UIKit.h>
#include <stdio.h>
#include "CSokoban.hpp"
#include "ISokobanDatasource.hpp"
#define MATH_PAI 3.1415926
//石板灰
#define WALL_COLOR [[UIColor colorWithRed:112/255.0 green:118/255.0 blue:144/255.0 alpha:1.0] CGColor]
#define BOX_COLOR [[UIColor colorWithRed:255/255.0 green:235/255.0 blue:205/255.0 alpha:1.0] CGColor]
#define TARGET_COLOR [[UIColor colorWithRed:2220/255.0 green:20/255.0 blue:60/255.0 alpha:1.0] CGColor]
#define FILL_COLOR [[UIColor colorWithRed:255/255.0 green:255/255.0 blue:255/255.0 alpha:1.0] CGColor]
#define MAN_COLOR [[UIColor colorWithRed:218/255.0 green:165/255.0 blue:105/255.0 alpha:1.0] CGColor]
#define GUIDE_COLOR [[UIColor colorWithRed:220/255.0 green:220/255.0 blue:220/255.0 alpha:1.0] CGColor]
class CDrawTool
{
public:
static void DrawWall (CGContextRef _context ,CGRect _rect,bool _selectedStyle = false);
static void DrawBox (CGContextRef _context ,CGRect _rect,bool _selectedStyle = false);
static void DrawMan (CGContextRef _context ,CGRect _rect,bool _selectedStyle = false);
static void DrawTarget (CGContextRef _context ,CGRect _rect,bool _selectedStyle = false);
static void DrawBoxOnTarget(CGContextRef _context ,CGRect _rect,bool _selectedStyle = false);
static void DrawFloor (CGContextRef _context ,CGRect _rect,bool _selectedStyle = false);
static void DrawCoordinate (CGContextRef _context ,CGRect _rect,int _row,int _line);
static void DrawGuide(CGContextRef _context,CGRect _rect);
private:
static float _lineWidth;
static void DrawEdge (CGContextRef _context ,CGRect _rect);
static void DrawSelectStyle(CGContextRef _context ,CGRect _rect);
};
#endif /* CDrawer_hpp */
| [
"yuzhang@yuzhangdeMacBook-Pro.local"
] | yuzhang@yuzhangdeMacBook-Pro.local |
d1f5ea87eaab3437224d192433b85776a38b69ed | 03e92eca1c566dc5621d70f6b9e700f7ea4fa04e | /core_war/jmz_command.cpp | 3e1f0d6352593a9d56ef684c5e7610415b589e9f | [] | no_license | ankutalev/16208_kutalev | 15610a5075bb9dd50c37998a06ce8ee5996e081e | e36ecdc14960175074bb0a6a62c31bddb77db1bf | refs/heads/master | 2021-09-16T07:19:36.850113 | 2018-06-18T12:35:01 | 2018-06-18T12:35:01 | 103,538,818 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,893 | cpp | #include "factory.hpp"
class Jmz_command : public Instruction {
public:
explicit Jmz_command(Modifiers x) { Fields.OpcodeMod = x;Name = "JMZ"; }
void Execution(ExecutionContext &Executor) override {
if (Fields.AOperandMod == Mods::Lattice &&
Fields.BOperandMod == Mods::Lattice) {
Fields.AOffset = Fields.AOperand;
Fields.BOffset = Fields.BOperand;
} else {
Executor.SetOffsets(Fields);
}
switch (Fields.OpcodeMod) {
case (Modifiers::A):
case (Modifiers::BA):
if (!Executor.getA(Fields.BOffset))
Executor.ChangeCurrentFlowAddress(Fields.AOffset);
else
Executor.ForwardQueue();
break;
case (Modifiers::Not):
case (Modifiers::B):
case (Modifiers::AB):
if (!Executor.getB(Fields.BOffset)) {
Executor.ChangeCurrentFlowAddress(Fields.AOffset);
std::cout << Executor.getCurrentWarriorName() << " jump to "
<< Executor.getCurrentAddress() << " address" << std::endl;
} else {
Executor.ForwardQueue();
std::cout << Executor.getCurrentWarriorName()
<< " will execute next command in "
<< Executor.getCurrentAddress() << " adress" << std::endl;
}
break;
case (Modifiers::I):
case (Modifiers::F):
case (Modifiers::X):
if (!Executor.getA(Fields.BOffset) && !Executor.getB(Fields.BOffset)) {
Executor.ChangeCurrentFlowAddress(Fields.AOffset);
std::cout << Executor.getCurrentWarriorName() << " jump to "
<< Executor.getCurrentAddress() << " address" << std::endl;
} else {
Executor.ForwardQueue();
std::cout << Executor.getCurrentWarriorName()
<< " will execute next command in "
<< Executor.getCurrentAddress() << " adress" << std::endl;
}
break;
}
}
Jmz_command *Clone() override { return new Jmz_command(*this); }
};
namespace {
Instruction *Jmzab() { return new Jmz_command(Modifiers::AB); }
Instruction *Jmzba() { return new Jmz_command(Modifiers::BA); }
Instruction *Jmzta() { return new Jmz_command(Modifiers::A); }
Instruction *Jmztb() { return new Jmz_command(Modifiers::B); }
Instruction *Jmztf() { return new Jmz_command(Modifiers::F); }
Instruction *Jmzx() { return new Jmz_command(Modifiers::X); }
Instruction *Jmzi() { return new Jmz_command(Modifiers::I); }
bool a = Factory::get_instance()->regist3r("JMZ.AB", &Jmzab);
bool b = Factory::get_instance()->regist3r("JMZ.BA", &Jmzba);
bool c = Factory::get_instance()->regist3r("JMZ.A", &Jmzta);
bool d = Factory::get_instance()->regist3r("JMZ.B", &Jmztb);
bool f = Factory::get_instance()->regist3r("JMZ.F", &Jmztf);
bool e = Factory::get_instance()->regist3r("JMZ.X", &Jmzx);
bool g = Factory::get_instance()->regist3r("JMZ.I", &Jmzi);
bool w = Factory::get_instance()->nameRegister("JMZ","JMZ");
} | [
"a.kutalev@g.nsu.ru"
] | a.kutalev@g.nsu.ru |
b60140d2a3566bd53f7552d67f43b9dc05e6769e | 826c0537b0d11865ca5c67782f853cef950430cb | /JFEngine/WinMain.cpp | 07ed5edb39e8048a5461ea353065781d75e7fbac | [
"MIT"
] | permissive | jeffery1994/JFEngine | 1e0aa67fa761ab8698eacd8e94573f2f64a1806d | 76222e0c34f40088577506322a361cc822cf2591 | refs/heads/main | 2023-02-28T07:15:10.319921 | 2021-02-07T01:56:36 | 2021-02-07T01:56:36 | 335,144,597 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,827 | cpp | /******************************************************************************************
* Chili Direct3D Engine *
* Copyright 2018 PlanetChili <http://www.planetchili.net> *
* *
* This file is part of Chili Direct3D Engine. *
* *
* Chili Direct3D Engine 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 Chili Direct3D Engine 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 Chili Direct3D Engine. If not, see <http://www.gnu.org/licenses/>. *
******************************************************************************************/
//#include "Window.h"
#include "App.h"
//int CALLBACK WinMain(
// HINSTANCE hInstance,
// HINSTANCE hPrevInstance,
// LPSTR lpCmdLine,
// int nCmdShow)
//{
// try
// {
// return App{}.Go();
// }
// catch (const ChiliException& e)
// {
// MessageBox(nullptr, e.what(), e.GetType(), MB_OK | MB_ICONEXCLAMATION);
// }
// catch (const std::exception& e)
// {
// return -1;
// MessageBox(nullptr, e.what(), "Standard Exception", MB_OK | MB_ICONEXCLAMATION);
// }
// catch (...)
// {
// MessageBox(nullptr, "No details available", "Unknown Exception", MB_OK | MB_ICONEXCLAMATION);
// }
// return -1;
//} | [
"xiaotabing1994@126.com"
] | xiaotabing1994@126.com |
6475f29292b925778d2be22d3660d1c44304e9f2 | c9b06761b0b43a5a06b765fed6a9b4f8e6c1f1d1 | /Lecture_24/graph.cpp | 8b7caa9cb4151fdd11522d37526ac4581779ee14 | [] | no_license | utkarshnath/Launchpad_Sept_18 | 5fba2eb69ffa380b46e198b1b9a27fa603e86909 | c4ec3c542d5c1e2b81741e62697608eeaa96982a | refs/heads/master | 2020-03-30T06:45:08.487753 | 2019-01-13T17:31:46 | 2019-01-13T17:31:46 | 150,886,207 | 10 | 7 | null | null | null | null | UTF-8 | C++ | false | false | 4,735 | cpp | #include<iostream>
#include<list>
#include<queue>
#include<stack>
using namespace std;
class graph{
int V; // count of vertex
list<int>* l;
public:
graph(int v){
V = v;
l = new list<int> [v];
}
void addEdge(int u,int v, bool bidir = true){
l[u].push_back(v);
if(bidir){
l[v].push_back(u);
}
}
void bfs(int vertex){
//bool * visited = new bool[100];
bool visited[100] = {0};
for(int i=0;i<V;i++){
visited[i] = false;
}
queue<int> q;
q.push(vertex);
visited[vertex] = true;
while(!q.empty()){
int top = q.front();
q.pop();
cout<<top<<" ";
list<int>:: iterator it;
for(it=l[top].begin();it!=l[top].end();it++){
if(visited[*it]==false){
q.push(*it);
visited[*it] = true;
}
}
}
}
void bfsDist(int vertex){
bool visited[100] = {0};
int dist[100];
for(int i=0;i<V;i++){
dist[i] = INT_MAX;
}
queue<int> q;
q.push(vertex);
visited[vertex] = true;
dist[vertex] = 0;
while(!q.empty()){
int top = q.front();
q.pop();
list<int>::iterator it;
for(it =l[top].begin();it!=l[top].end();it++){
if(visited[*it]==false){
dist[*it] = dist[top] + 1;
q.push(*it);
visited[*it] = true;
}
}
}
}
void dfsDriver(int vertex,bool visited[100]){
if(visited[vertex]){
return;
}
cout<<vertex<<" ";
visited[vertex] = true;
list<int>:: iterator it;
for(it=l[vertex].begin();it!=l[vertex].end();it++){
dfsDriver(*it,visited);
}
return;
}
void dfs(){
bool visited[100] = {0};
for(int i=0;i<V;i++){
dfsDriver(i,visited);
}
}
void topoDriver(int vertex,bool visited[100],stack<int>&s){
if(visited[vertex]){
return;
}
visited[vertex] = true;
list<int>:: iterator it;
for(it=l[vertex].begin();it!=l[vertex].end();it++){
int v = *it;
topoDriver(v,visited,s);
}
s.push(vertex);
}
void topologicalSort(){
bool visited[100] = {0};
stack<int>s;
for(int i=0;i<V;i++){
topoDriver(i,visited,s);
}
while(!s.empty()){
cout<<s.top();
s.pop();
}
}
bool cycleDriver(int vertex,bool visited[100],int parent){
if(visited[vertex]){
return true;
}
visited[vertex] = true;
list<int>:: iterator it;
for(it=l[vertex].begin();it!=l[vertex].end();it++){
int v = *it;
if(v!=parent){
bool cycle = cycleDriver(v,visited,vertex);
if(cycle){
return true;
}
}
}
return false;
}
bool isCycle(){
bool visited[100] = {0};
for(int i=0;i<V;i++){
if(!visited[i]){
bool cycle = cycleDriver(i,visited,i);
if(cycle){
return true;
}
}
}
return false;
}
bool cycleDriverDir(int vertex,bool visited[]bool recstack[]){
if(visited[vertex]==false){
visited[vertex] = true;
recstack[vertex] = true;
ist<int>:: iterator it;
for(it=l[vertex].begin();it!=l[vertex].end();it++){
int v = *it;
if(!visited[v] && cycleDriverDir(v,visited,recstack)){
return true;
}
if(recstack[v]){
return true;
}
}
recstack[vertex] = false;
return false;
}
}
bool isCycleDir(){
bool visited[100] = {0};
bool recstack[100] = {0};
for(int i=0;i<V;i++){
if(cycleDriverDir(i,visited,recstack)){
return true;
}
}
return false;
}
void print(){
for(int i=0;i<V;i++){
cout<<i<<" => ";
list<int>:: iterator it;
for(it=l[i].begin();it!=l[i].end();it++){
cout<<*it<<" ";
}
cout<<endl;
}
}
};
int main(){
graph g(7);
g.addEdge(0,1,0);
g.addEdge(0,2,0);
g.addEdge(0,3,0);
g.addEdge(1,4,0);
g.addEdge(2,3,0);
g.addEdge(2,4,0);
g.addEdge(3,4,0);
g.addEdge(5,6,0);
g.topologicalSort();
//g.print();
}
| [
"nath.utkarsh1@gmail.com"
] | nath.utkarsh1@gmail.com |
057775b6eaffcb33b8f573921eefd752cf33fe7d | 6c8ab6c4680c08e707fe262ef6ef9c0de8e726dd | /miabot_commands.h | 52d49961a2e3d6ae4aac45ebe96ca90082e58dd5 | [] | no_license | drjosephbaxter/miabot-player | 934ee4866e1843bc9d3c74d9eb51cbf0729e23f5 | a494bcc447c15e18f322e15f8c05bc78c877f888 | refs/heads/main | 2023-04-30T21:20:02.683128 | 2021-05-08T09:26:32 | 2021-05-08T09:26:32 | 365,471,965 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,389 | h | /* miabot_commands.h
* Miabot Plugin for Player
* Copyright (C) - Joseph Baxter {joseph.lee.baxter@gmail.com}
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
*/
#ifndef _MIABOT_COMMANDS_H
#define _MIABOT_COMMANDS_H
#include <string>
#include <libplayercore/playercore.h>
#include "miabot.h"
#include <bluetooth/bluetooth.h>
using namespace std;
void bluetooth_dongle(string bluetooth_mac);
void bluetooth(string bluetooth_router, string bluetooth_port);
int rfcomm_connect_dongle(bdaddr_t *src, bdaddr_t *dst, uint8_t channel);
int rfcomm_connect(string bluetooth_router, string bluetooth_port);
string hexbyte2str(int n);
string hexbyte2strB(int n);
int str2hexdig(char s);
int str2hexbyte(string s);
double ticks2m(int ticks);
int m2speed(double m);
int m2ticks(double m);
int deg2ticks(double d);
void stop();
void encoder();
void defaults();
int bin2int();
void seq(int f, int t, int r, bool b, bool l, bool forw);
int value2index(int value);
void stopped();
double time();
void p(int ping);
void rec();
void DoScan(player_miabot_data_t* d, int photodiode, int sonar, bool buffer);
void ToggleSonar(bool b, int ping);
void parseSonar();
void odom(string inp_odom);
void set_odometry(float m_x, float m_y, float rad_theta);
void ToggleOdom(bool b, int enc);
void updateOdom(player_miabot_data_t* d);
void HandlePositionCommand(player_position2d_cmd_vel_t position2d_cmd);
void HandlePositionCommand_pos(player_position2d_cmd_pos_t position2d_cmd);
void CloseGripper(int close_arg);
void OpenGripper(int open_arg);
void UpGripper(int up_arg);
void DownGripper(int down_arg);
void compass(player_miabot_data_t* d);
void updateGripper(player_miabot_data_t* d);
int rgb(int rmin, int rmax,int gmin, int gmax,int bmin, int bmax);
void blob(player_miabot_data_t* d);
void camTrack(int set_cam,int num_blobs, int redmin,int redmax, int redmin1,int redmax1, int redmin2,int redmax2,int redmin3,int redmax3, int redmin4,int redmax4, int redmin5,int redmax5,int redmin6,int redmax6, int redmin7,int redmax7, int greenmin,int greenmax, int greenmin1,int greenmax1,int greenmin2,int greenmax2, int greenmin3,int greenmax3, int greenmin4,int greenmax4,int greenmin5,int greenmax5, int greenmin6,int greenmax6, int greenmin7,int greenmax7, int bluemin,int bluemax,int bluemin1,int bluemax1, int bluemin2,int bluemax2, int bluemin3,int bluemax3,int bluemin4,int bluemax4, int bluemin5,int bluemax5, int bluemin6,int bluemax6,int bluemin7,int bluemax7);
void camStopTracking();
void parseBlob(string inp_blob);
void Track();
void camera_settings(int white,int adj,int filt);
void readData(int wait);
void voltage(string bluetooth_router, string bluetooth_port);
void TogglePill(bool set, int rate);
#endif
| [
"joseph.baxter@nottingham.ac.uk"
] | joseph.baxter@nottingham.ac.uk |
9bd246dd78eb4611f7adc826cfe1969c54819401 | c2252f1526c624f88885240ef4e07ca6f27cae69 | /Solutions/101170 - 2016-2017 ACM-ICPC Northwestern European Regional Programming Contest (NWERC 2016)/J(greedy).cpp | 64911435b88b443890b5fcfbbd0aa61734233feb | [] | no_license | shubhansujee9/Codeforces-Gyms-Solutions | 201529a75db9abe9b5dfa693ee1fedca93416823 | 785b69956c9b8afd31f4ebd0b24fe10362dc9d84 | refs/heads/master | 2020-03-24T13:00:38.421420 | 2018-07-22T09:05:52 | 2018-07-22T09:05:52 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,733 | cpp | #include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef vector<ll> vi;
typedef vector<ll> vll;
typedef vector<vi> vvi;
typedef pair<ll, ll> pii;
typedef vector<pii> vii;
typedef vector<bool> vb;
typedef vector<string> vs;
const int di[] = { -1, 0, 1, 0 };
const int dj[] = { 0, 1, 0, -1 };
const ll MOD = 5e6;
const ll INF = 1e8;
const double EPS = 1e-12;
#define mp make_pair
#define all(x) x.begin(),x.end()
int main() {
ios::sync_with_stdio(false), cin.tie(0);
ll n, q, s; cin >> n >> q >> s;
vi sen(s);
for (int i = 0; i < s; i++) {
cin >> sen[i]; sen[i]--;
}
vi sz(q);
for (int i = 0; i < q; i++) {
cin >> sz[i];
}
vi d(n);
vvi qinc(n, vi(q));
for (int i = 0; i < n; i++) {
cin >> d[i];
for (int j = 0; j < s; j++) {
ll x; cin >> x;
qinc[i][sen[j]] += x;
}
}
ll cur = 0; bool w = false;
vi qcur(q);
vector<queue<pii>> qp(q);
for (int i = 0; i < n && !w; i++) {
for (int j = 0; j < q && !w; j++) {
while (qcur[j] + qinc[i][j] > sz[j]) {
if (qp[j].empty()) {
w = true; break;
}
ll rm = qcur[j] + qinc[i][j] - sz[j];//min(qcur[j] + qinc[i][j] - sz[j], d[qp[j].front().second]);
//if (rm == 0) {
// ll x = qp[j].front().first;
// qp[j].pop();
// if (!qp[j].empty())
// qp[j].front().first += x;
//}
if (rm >= qp[j].front().first) {
if (qp[j].front().first <= d[qp[j].front().second]) {
rm -= qp[j].front().first;
qcur[j] -= qp[j].front().first;
d[qp[j].front().second] -= qp[j].front().first;
qp[j].pop();
}
else {
rm -= d[qp[j].front().second];
qcur[j] -= d[qp[j].front().second];
ll x = qp[j].front().first - d[qp[j].front().second];
d[qp[j].front().second] -= d[qp[j].front().second];
qp[j].pop();
if (!qp[j].empty())
qp[j].front().first += x;
}
}
else {
if (rm <= d[qp[j].front().second]) {
qp[j].front().first -= rm;
qcur[j] -= rm;
d[qp[j].front().second] -= rm;
}
else {
rm -= d[qp[j].front().second];
qcur[j] -= d[qp[j].front().second];
ll x = qp[j].front().first - d[qp[j].front().second];
d[qp[j].front().second] -= d[qp[j].front().second];
qp[j].pop();
if (!qp[j].empty())
qp[j].front().first += x;
}
}
}
qcur[j] += qinc[i][j];
qp[j].push({ qinc[i][j],i });
}
}
for (int j = 0; j < q && !w; j++) {
while (qcur[j] > 0) {
if (qp[j].empty()) {
w = true; break;
}
ll rm = qcur[j];//min(qcur[j], d[qp[j].front().second]);
//if (rm == 0) {
// ll x = qp[j].front().first;
// qp[j].pop();
// if (!qp[j].empty())
// qp[j].front().first += x;
//}
if (rm >= qp[j].front().first) {
if (qp[j].front().first <= d[qp[j].front().second]) {
rm -= qp[j].front().first;
qcur[j] -= qp[j].front().first;
d[qp[j].front().second] -= qp[j].front().first;
qp[j].pop();
}
else {
rm -= d[qp[j].front().second];
qcur[j] -= d[qp[j].front().second];
ll x = qp[j].front().first - d[qp[j].front().second];
d[qp[j].front().second] -= d[qp[j].front().second];
qp[j].pop();
if (!qp[j].empty())
qp[j].front().first += x;
}
}
else {
if (rm <= d[qp[j].front().second]) {
qp[j].front().first -= rm;
qcur[j] -= rm;
d[qp[j].front().second] -= rm;
}
else {
rm -= d[qp[j].front().second];
qcur[j] -= d[qp[j].front().second];
ll x = qp[j].front().first - d[qp[j].front().second];
d[qp[j].front().second] -= d[qp[j].front().second];
qp[j].pop();
if (!qp[j].empty())
qp[j].front().first += x;
}
}
}
}
cout << (w ? "impossible" : "possible") << endl;
cin.ignore(), cin.get();
}
| [
"khaled.hamedt@gmail.com"
] | khaled.hamedt@gmail.com |
a5d6724daac9d9f8b6bce9c20ee54a937a6c9f54 | a211bff67d4a1904cd1268ede8cdd5bad519d7a1 | /src/frameworks/naiad_dispatcher.cc | 8ca517cc6bacd0f0bbf8c84edb89b870659ec630 | [
"Apache-2.0"
] | permissive | ingomueller-net/Musketeer | c00144b45c35980979149cc4f41922588b92277a | 3ed41d93b0a61f00aa8a0b8ec084973b20956b3d | refs/heads/master | 2020-04-03T15:24:28.385684 | 2018-10-30T09:49:13 | 2018-10-30T09:49:13 | 155,361,431 | 0 | 0 | Apache-2.0 | 2018-10-30T09:51:29 | 2018-10-30T09:51:28 | null | UTF-8 | C++ | false | false | 2,327 | cc | // Copyright (c) 2015 Ionel Gog <ionel.gog@cl.cam.ac.uk>
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT
* LIMITATION ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR
* A PARTICULAR PURPOSE, MERCHANTABLITY OR NON-INFRINGEMENT.
*
* See the Apache Version 2.0 License for specific language governing
* permissions and limitations under the License.
*/
#include "frameworks/naiad_dispatcher.h"
#include <boost/lexical_cast.hpp>
#include <cstdlib>
#include <iostream>
#include <string>
#include "base/common.h"
#include "base/flags.h"
namespace musketeer {
NaiadDispatcher::NaiadDispatcher() {
}
void NaiadDispatcher::Execute(string job_path, string job_options) {
LOG(INFO) << "naiad run started for: " << job_path;
LOG(INFO) << "naiad copy input started for: " << job_path;
string copy_input_cmd = "parallel-ssh -h " + FLAGS_naiad_hosts_file +
" -t 10000 -p 100 -i 'START_TIME=`date +%s` ; sh " +
FLAGS_generated_code_dir + "Musketeer/hdfs_get.sh ; END_TIME=`date +%s` ; " +
"PULL_TIME=`expr $END_TIME - $START_TIME` ; echo \"PULLING DATA: \"$PULL_TIME'";
system(copy_input_cmd.c_str());
LOG(INFO) << "naiad copy input ended for: " << job_path;
string run_cmd = "parallel-ssh -h " + FLAGS_naiad_hosts_file +
" -t 10000 -p 100 -i 'PROCID=`" + FLAGS_generated_code_dir +
"Musketeer/get_proc_id.sh` ; cd " + FLAGS_generated_code_dir + " ; mono-sgen " +
job_path + " -p $PROCID -n " +
boost::lexical_cast<string>(FLAGS_naiad_num_workers) + " -t " +
boost::lexical_cast<string>(FLAGS_naiad_num_threads) + " -h @" +
FLAGS_naiad_hosts_file +
" --inlineserializer ; START_TIME=`date +%s` ; sh Musketeer/hdfs_put.sh ; " +
"END_TIME=`date +%s` ; PUSH_TIME=`expr $END_TIME - $START_TIME` ; " +
"echo \"PUSHING DATA: \"$PUSH_TIME'";
LOG(INFO) << "Running: " << run_cmd;
system(run_cmd.c_str());
LOG(INFO) << "naiad run ended for: " << job_path;
}
} // namespace musketeer
| [
"gogionel@gmail.com"
] | gogionel@gmail.com |
6a0299f9b190e8e1e94deee28fd3b19af4cfe7bc | 1baf140693e66029e97b044bedbcb227cce4be22 | /arduino/LC/Garaland.ino | 2d6d14bfd8b8d31fc9f63e7e83dbd7c6b3d47407 | [] | no_license | zholdak/arduino-lights-controller | 88be11e7d7f3634cb85c0d7e064911440fd07bc8 | b260fce45adcc572216b6ddfa43bda7631fd3cb7 | refs/heads/master | 2020-04-09T03:10:45.131751 | 2018-12-01T18:00:58 | 2018-12-01T18:00:58 | 159,972,319 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,426 | ino | #include "Leds.h"
#include "Garaland.h"
#include "Sd.h"
CRGB garalandLeds[NUM_LEDS];
void garalandInit() {
#ifdef DEBUG
Serial.println(F("All leds off"));
#endif
#ifdef LED_GARLAND
FastLED.addLeds<WS2812B, LED_GARLAND, GRB>(garalandLeds, NUM_LEDS);
FastLED.setBrightness(128);
FastLED.setDither(0);
allBulbsOff();
#endif
}
void allBulbsOff() {
#ifdef LED_GARLAND
for(int i = 0; i < NUM_LEDS; i++)
garalandLeds[i].setRGB(0, 0, 0);
FastLED.show();
#endif
}
boolean checkForInterrupt() {
return Serial.available() > 0;
}
boolean checkForButton() {
if( isOkButtonPressed() ) {
consumeOkButtonPress();
delay(100);
return true;
}
else
return false;
}
void readAndPlayProgsRecursively() {
#ifdef DEBUG
Serial.println(F("Reading and play progs"));
#endif
File root;
uint8_t currProg = 0;
uint8_t totalProgs = 0;
if( beginSD() ) {
root = openProgsRoot();
if( root ) {
File prog;
while( true ) {
prog = root.openNextFile();
if( prog ) {
prog.close();
totalProgs ++;
} else
break;
}
root.rewindDirectory();
volatile boolean repeatAllProgs = true;
volatile boolean nextProg = false;
boolean isMustBeFirstProg = true;
while( true ) {
if( checkForInterrupt() )
break;
gheartbeat();
if( repeatAllProgs || (!repeatAllProgs && !prog) || nextProg ) {
nextProg = false;
if( prog )
prog.close();
prog = root.openNextFile();
currProg ++;
if( !prog ) {
if( isMustBeFirstProg ) {
#ifdef DEBUG
Serial.println(F("Problem with SD?"));
#endif
stopAndShowError(SD_ERROR_WHILE_READING);
}
#ifdef DEBUG
Serial.println(F("Reopen SD, from 1st prog"));
#endif
root.close();
endSD();
if( !beginSD() )
stopAndShowError(CANNT_REBEGIN_SD);
root = openProgsRoot();
if( !root )
stopAndShowError(CANNT_REOPEN_ROOT);
currProg = 0;
isMustBeFirstProg = true;
repeatAllProgs = true;
continue;
}
isMustBeFirstProg = false;
} else {
if( !prog.seek(0) )
stopAndShowError(SD_ERROR_WHILE_SEEK);
}
#ifdef DEBUG
Serial.print(F("# Prog '"));
Serial.print(prog.name());
Serial.println(F("'"));
#endif
if( !prog.available() ) {
#ifdef DEBUG
Serial.println(F(" no data"));
#endif
prog.close();
continue;
}
displayPlay(currProg, totalProgs, prog.name(), !repeatAllProgs);
initButtons();
//
// read prog
//
uint8_t count, delayMsHi, delayMsLo, n, r, g, b;
uint16_t delayMs;
while( true ) {
if( checkForInterrupt() )
break;
if( !prog.available() ) {
#ifdef DEBUG
//Serial.println(F(" no more data"));
#endif
break;
}
//
// first byte, should be zero
//
uint8_t zero = prog.read();
if( zero != 0 ) {
#ifdef DEBUG
Serial.println(F(" PE01"));
#endif
stopAndShowError(PROG_FORMAT_ERROR);
}
//
// second byte, should be number of bulbs
//
if( !prog.available() ) {
#ifdef DEBUG
Serial.println(F(" PE02"));
#endif
stopAndShowError(UNEXPECTED_END_OF_PROG);
}
count = prog.read();
if( count == 0 ) {
#ifdef DEBUG
Serial.println(F(" PE03"));
#endif
stopAndShowError(PROG_FORMAT_ERROR);
}
#ifdef DEBUG
//Serial.print(F(" bulbs "));
//Serial.println(count, DEC);
#endif
//
// third and fourth bytes, should be the delay
//
if( !prog.available() ) {
#ifdef DEBUG
Serial.println(F(" PE04"));
#endif
stopAndShowError(UNEXPECTED_END_OF_PROG);
}
delayMsHi = prog.read();
if( !prog.available() ) {
#ifdef DEBUG
Serial.println(F(" PE05"));
#endif
stopAndShowError(UNEXPECTED_END_OF_PROG);
}
delayMsLo = prog.read();
delayMs = delayMsHi << 8 | delayMsLo;
#ifdef DEBUG
//Serial.print(F(" delay "));
//Serial.println(delayMs, DEC);
#endif
volatile boolean frameOk = true;
volatile boolean breakProg = false;
//
// read frames
//
for(uint8_t i=0; i<count; i++) {
if( checkForButton() ) {
if( repeatAllProgs )
repeatAllProgs = false;
else
nextProg = true;
breakProg = true;
break;
}
//
// should be the number of bulb
//
if( !prog.available() ) {
#ifdef DEBUG
Serial.println(F(" PE06"));
#endif
stopAndShowError(UNEXPECTED_END_OF_PROG);
}
n = prog.read();
//
// should be the red
//
if( !prog.available() ) {
#ifdef DEBUG
Serial.println(F(" PE07"));
#endif
stopAndShowError(UNEXPECTED_END_OF_PROG);
}
r = prog.read();
//
// should be the green
//
if( !prog.available() ) {
#ifdef DEBUG
Serial.println(F(" PE08"));
#endif
stopAndShowError(UNEXPECTED_END_OF_PROG);
}
g = prog.read();
//
// should be the blue
//
if( !prog.available() ) {
#ifdef DEBUG
Serial.println(F(" PE09"));
#endif
stopAndShowError(UNEXPECTED_END_OF_PROG);
}
b = prog.read();
#ifdef LED_GARLAND
garalandLeds[n].setRGB(r, g, b);
#endif
}
if( !breakProg ) {
#ifdef LED_GARLAND
FastLED.show();
#endif
gheartbeat();
delay(delayMs);
} else {
allBulbsOff();
break;
}
} // while( true ) // read prog
//prog.close();
deinitButtons();
} // while(true) // read progs recursively
if( prog )
prog.close();
deinitButtons();
allBulbsOff();
allLedsOff();
root.close();
} // if( root )
endSD();
} // if( beginSD() )
} // readAndPlayProgsRecursively()
| [
"aleksey@zholdak.com"
] | aleksey@zholdak.com |
eaca1e58dba15691e3f832fa2f00e4410820253e | 6b30258040708b6a691b0620d4aaa64e98d2e0d0 | /zjutOJ/倒置排序.cpp | 869b9df76327e30d4c58559f5cd5766e9e40d06d | [] | no_license | shenxs/ACM | 74e94b250b23468b1f88dcccf1c4ca9d55aa6937 | bea2ea559e1e3375cec3def59cab718a180db98e | refs/heads/master | 2020-05-09T21:22:57.880227 | 2019-12-22T14:43:42 | 2019-12-22T14:43:42 | 27,082,818 | 4 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 1,031 | cpp | #include<iostream>
#include<vector>
#include<string>
#include<cmath>
#include<algorithm>
using namespace std;
bool bijiao(string s1,string s2)
{
string a1,a2,b1,b2;
a1=s1;
a2=s2;
reverse(a1.begin(),a1.end());
reverse(a2.begin(),a2.end());
string::iterator it;
for (it =a1.begin(); it != a1.end(); ++it)
{
if( *it == '0')
{
a1.erase(it);
}
if(*it!='0') break;
}
for (it =a2.begin(); it != a2.end(); ++it)
{
if( *it == '0')
{
a2.erase(it);
}
if(*it!='0') break;
}
if(a1.length()<a2.length()) return true;
else if(a1.length()==a2.length()&& a1<a2) return true;
else return false;
}
int main()
{
int n,m,a,e;
string s1;
vector<string>s;
for(;cin>>n;)
{
for(;n--;)
{
cin>>m;
a=m;
s.clear();
for(;m--;)
{
cin>>s1;
s.push_back(s1);
}
sort(s.begin(),s.end(),bijiao);
e=0;
for(;a--;e++)
{
if(a==0) cout<<s[e];
else cout<<s[e]<<' ';
}
cout<<endl;
}
cout<<endl;
}
return 0;
}
| [
"a247820400@gmail.com"
] | a247820400@gmail.com |
d14e78b89fab554f5b583a605e40e5a04e211606 | 7771130ea6eb1f076a7d18e672d3d82d5996e957 | /src/qt/winshutdownmonitor.cpp | 81c6c853d960cd4816be31d2068b4a222fe10b51 | [
"MIT"
] | permissive | gdrcoin/gdrcoin | 49707508dfc1b14ace3817854416355a925539df | f9f2137b3d9069bfc8e3c69c90a684a061dfb6aa | refs/heads/master | 2020-03-10T18:01:49.563615 | 2018-04-14T12:36:52 | 2018-04-14T12:36:52 | 129,511,260 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,457 | cpp | // Copyright (c) 2014-2016 The Gdrcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "winshutdownmonitor.h"
#if defined(Q_OS_WIN) && QT_VERSION >= 0x050000
#include "init.h"
#include "util.h"
#include <windows.h>
#include <QDebug>
#include <openssl/rand.h>
// If we don't want a message to be processed by Qt, return true and set result to
// the value that the window procedure should return. Otherwise return false.
bool WinShutdownMonitor::nativeEventFilter(const QByteArray &eventType, void *pMessage, long *pnResult)
{
Q_UNUSED(eventType);
MSG *pMsg = static_cast<MSG *>(pMessage);
// Seed OpenSSL PRNG with Windows event data (e.g. mouse movements and other user interactions)
if (RAND_event(pMsg->message, pMsg->wParam, pMsg->lParam) == 0) {
// Warn only once as this is performance-critical
static bool warned = false;
if (!warned) {
LogPrintf("%s: OpenSSL RAND_event() failed to seed OpenSSL PRNG with enough data.\n", __func__);
warned = true;
}
}
switch(pMsg->message)
{
case WM_QUERYENDSESSION:
{
// Initiate a client shutdown after receiving a WM_QUERYENDSESSION and block
// Windows session end until we have finished client shutdown.
StartShutdown();
*pnResult = FALSE;
return true;
}
case WM_ENDSESSION:
{
*pnResult = FALSE;
return true;
}
}
return false;
}
void WinShutdownMonitor::registerShutdownBlockReason(const QString& strReason, const HWND& mainWinId)
{
typedef BOOL (WINAPI *PSHUTDOWNBRCREATE)(HWND, LPCWSTR);
PSHUTDOWNBRCREATE shutdownBRCreate = (PSHUTDOWNBRCREATE)GetProcAddress(GetModuleHandleA("User32.dll"), "ShutdownBlockReasonCreate");
if (shutdownBRCreate == nullptr) {
qWarning() << "registerShutdownBlockReason: GetProcAddress for ShutdownBlockReasonCreate failed";
return;
}
if (shutdownBRCreate(mainWinId, strReason.toStdWString().c_str()))
qWarning() << "registerShutdownBlockReason: Successfully registered: " + strReason;
else
qWarning() << "registerShutdownBlockReason: Failed to register: " + strReason;
}
#endif
| [
"37983255+spineinhalb@users.noreply.github.com"
] | 37983255+spineinhalb@users.noreply.github.com |
6cb45a9ac8527d9c191ed7c0c6a491ca3429808e | d7bdd8789ebd7fdf7a4a181b24d8c922cc457fa7 | /Shuffle/List.cpp | 8fa0adfd46a7adadb4d9d7e4c2030317838964f9 | [] | no_license | daringh10/C-Programming-Projects | 2e114f339780c3c9a970578a08b4ee30a3a80f6c | 8a030d6490db0f7a1a36dba38926626acf19a88e | refs/heads/main | 2023-08-05T08:04:22.707187 | 2021-09-19T22:00:55 | 2021-09-19T22:00:55 | 408,241,360 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,533 | cpp | #include <iostream>
#include <string>
#include <climits>
#include "List.h"
using namespace std;
// Private Constructor ---------------------------------------------------
//Node constructor
List::Node::Node(int x){
data = x;
next = nullptr;
prev = nullptr;
}
// Class Constructors & Destructors -------------------------------------------
// Creates a new List in the empty state.
List::List(){
frontDummy = new Node(INT_MIN);
backDummy = new Node(INT_MAX);
frontDummy->next = backDummy;
backDummy->prev = frontDummy;
beforeCursor = frontDummy;
afterCursor = backDummy;
pos_cursor = 0;
num_elements = 0;
}
//Copy Constructor
List::List(const List& L){
frontDummy = new Node(INT_MIN);
backDummy = new Node(INT_MAX);
frontDummy->next = backDummy;
backDummy->prev = frontDummy;
beforeCursor = frontDummy;
afterCursor = backDummy;
pos_cursor = 0;
num_elements = 0;
Node *n = L.frontDummy->next;
for (int i = 0; i < L.num_elements; i++){
this->insertBefore(n->data);
n = n->next;
}
}
//Destructor
List::~List(){
clear();
delete frontDummy;
delete backDummy;
}
// Access functions --------------------------------------------------------
// isEmpty()
// Returns true if this List is empty, false otherwise.
bool List::isEmpty(){
return (num_elements == 0);
}
// size()
// Returns the size of this List.
int List::size(){
return num_elements;
}
// position()
// Returns the position of the cursor in this List. The value returned
// will be in the range 0 to size().
int List::position(){
return pos_cursor;
}
// Manipulation procedures -------------------------------------------------
// moveFront()
// Moves cursor to position 0 in this List.
void List::moveFront(){
beforeCursor = frontDummy;
afterCursor = frontDummy->next;
pos_cursor = 0;
}
// moveBack()
// Moves cursor to position size() in this List.
void List::moveBack(){
beforeCursor = backDummy->prev;
afterCursor = backDummy;
pos_cursor = num_elements;
}
// peekNext()
// Returns the element after the cursor.
// pre: position()<size()
int List::peekNext(){
if( position() < size() ){
return afterCursor->data;
}
return INT_MIN;
}
// peekPrev()
// Returns the element before the cursor.
// pre: position()>0
int List::peekPrev(){
if( position() > 0 ){
return beforeCursor->data;
}
return INT_MIN;
}
// moveNext()
// Advances cursor to next higher position. Returns the List element that
// was passed over.
// pre: position()<size()
int List::moveNext(){
if( position() < size() ){
afterCursor = afterCursor->next;
beforeCursor = beforeCursor->next;
pos_cursor += 1;
return beforeCursor->data;
}
return INT_MIN;
}
// movePrev()
// Advances cursor to next lower position. Returns the List element that
// was passed over.
// pre: position()>0
int List::movePrev(){
if( position() > 0 ){
afterCursor = afterCursor->prev;
beforeCursor = beforeCursor->prev;
pos_cursor -=1;
return afterCursor->data;
}
return INT_MIN;
}
// insertAfter()
// Inserts x after cursor.
void List::insertAfter(int x){
Node *n = new Node(x);
n->next = afterCursor;
n->prev = beforeCursor;
beforeCursor->next = n;
afterCursor->prev = n;
afterCursor = n;
num_elements +=1;
}
// insertBefore()
// Inserts x before cursor.
void List::insertBefore(int x){
Node *n = new Node(x);
n->prev = beforeCursor;
n->next = afterCursor;
beforeCursor->next = n;
afterCursor->prev = n;
beforeCursor = n;
pos_cursor +=1;
num_elements +=1;
}
// eraseAfter()
// Deletes element after cursor.
// pre: position()<size()
void List::eraseAfter(){
if( position() < size() ){
Node *temp = afterCursor->next;
delete afterCursor;
afterCursor = temp;
temp->prev = beforeCursor;
beforeCursor->next = temp;
num_elements -=1;
}
}
// eraseBefore()
// Deletes element before cursor.
// pre: position()>0
void List::eraseBefore(){
if( position() > 0 ){
Node *temp = beforeCursor->prev;
delete beforeCursor;
beforeCursor = temp;
temp->next = afterCursor;
afterCursor->prev = temp;
num_elements -=1;
pos_cursor -=1;
}
}
// findNext()
// Starting from the current cursor position, performs a linear search (in
// the direction front-to-back) for the first occurrence of the element x.
// If x is found, places the cursor immediately after the found element (so
// eraseBefore() would remove the found element), and returns the final
// cursor position. If x is not found, places the cursor at position size(),
// and returns -1.
int List::findNext(int x){
while(pos_cursor != num_elements){
moveNext();
if(peekPrev() == x){
return pos_cursor;
}
}
return -1;
}
// findPrev()
// Starting from the current cursor position, performs a linear search (in
// the direction back-to-front) for the first occurrence of the element x.
// If x is found, places the cursor immediately before the found element (so
// eraseAfter() would remove the found element), and returns the final
// cursor position. If x is not found, places the cursor at position 0, and
// returns -1.
int List::findPrev(int x){
while(pos_cursor != 0){
movePrev();
if(peekNext() == x){
return pos_cursor;
}
}
return -1;
}
// cleanup()
// Removes any repeated elements in this List, leaving only unique data
// values. The order of the remaining elements is obtained by retaining
// the frontmost occurrance of each element, and removing all other
// occurances. The cursor is not moved with respect to the retained
// elements, i.e. it lies between the same two retained elements that it
// did before cleanup() was called.
void List::cleanup(){
int current_pos = pos_cursor;
moveFront();
moveNext();
Node *temp1 = frontDummy->next;
int x = 1;
while (pos_cursor != num_elements){
while(pos_cursor != num_elements){
if (temp1->data == afterCursor->data){
eraseAfter();
if (pos_cursor <= current_pos - 1){
current_pos -=1;
}
}
else{
moveNext();
continue;
}
}
x++;
moveFront();
for (int i =0; i < x; i++){
moveNext();
}
temp1 = temp1->next;
}
moveFront();
for (int i =0; i <current_pos; i++){
moveNext();
}
}
// clear()
// Deletes all elements in this List, setting it to the empty state.
void List::clear(){
moveFront();
while (size() != 0){
eraseAfter();
}
}
// concat()
// Returns a new List consisting of the elements of this List, followed
// the elements of L. The returned List's cursor will be at its front
// (position 0).
List List::concat(const List& L){
List New;
Node *N = L.frontDummy->next;
Node *M = this->frontDummy->next;
for (int i = 0; i < this->num_elements; i++){
New.insertBefore(M->data);
M = M->next;
}
for (int i = 0; i < L.num_elements; i++){
New.insertBefore(N->data);
N = N->next;
}
New.moveFront();
cout << New.position() << endl;
return New;
}
// Other Functions ---------------------------------------------------------
// to_string()
// Returns a string representation of this List consisting of a comma
// separated sequence of elements, surrounded by parentheses.
std::string List::to_string(){
Node *N = frontDummy->next;
string s = "(";
for (int i = 0; i < size(); i++){
s += std::to_string(N->data);
if (i != size() - 1){
s+=", ";
}
N = N->next;
}
s+=")";
return s;
}
// equals()
// Returns true if and only if this List is the same integer sequence as R.
// The cursors in this List and in R are unchanged.
bool List::equals(const List& R){
if(this->num_elements != R.num_elements){
return false;
}
Node *M = this->frontDummy->next;
Node *N = R.frontDummy->next;
for(int i = 0; i< R.num_elements; i++){
if(M->data == N->data){
M = M->next;
N = N->next;
continue;
}
else{
return false;
}
}
return true;
}
// Overriden Operators -----------------------------------------------------
// operator=()
// Overwrites the state of this List with state of L.
List& List::operator=( const List& L ){
if (this != &L){
List temp = L;
std::swap(frontDummy, temp.frontDummy);
std::swap(backDummy, temp.backDummy);
std::swap(afterCursor, temp.afterCursor);
std::swap(beforeCursor,temp.beforeCursor);
std::swap(pos_cursor, temp.pos_cursor);
std::swap(num_elements,temp.num_elements);
}
return *this;
}
// operator<<()
// Inserts string representation of L into stream.
std::ostream& operator<<( std::ostream& stream, List& L ){
return stream << L.List::to_string();
}
bool operator==( List& A, const List& B ){
return A.List::equals(B);
}
| [
"dgharib@ucsc.edu"
] | dgharib@ucsc.edu |
a6ddefdf8b515fca14e7dfed951471e6cc210849 | 0f5780cdf99c4b4568d8550f2bdfb3a1fa71126d | /src/FastDC.cpp | b678ed3f75c95c11225917ddcc5b9c3b0bc59310 | [] | no_license | lenoval/e | 3136e04e5cbfc140368f0ec32c6e500e9773d113 | 52f3c09282ddbf5c53fe75c1d4395a9bc134f52d | refs/heads/master | 2021-01-18T03:51:50.353760 | 2009-05-08T21:57:49 | 2009-05-08T21:57:49 | 196,945 | 3 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,092 | cpp | /*******************************************************************************
*
* Copyright (C) 2009, Alexander Stigsen, e-texteditor.com
*
* This software is licensed under the Open Company License as described
* in the file license.txt, which you should have received as part of this
* distribution. The terms are also available at http://opencompany.org/license.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
******************************************************************************/
#ifdef __WXMSW__
#pragma warning(disable:4786)
#endif
#include "FastDC.h"
void FastDC::SetFontStyles(int fontStyles, map<int,wxFont>& fontMap) {
const int fontStyle = (fontStyles & wxFONTFLAG_ITALIC) ? wxFONTSTYLE_ITALIC : wxFONTSTYLE_NORMAL;
const int fontWeight = (fontStyles & wxFONTFLAG_BOLD) ? wxFONTWEIGHT_BOLD : wxFONTWEIGHT_NORMAL;
const bool fontUnderline = (fontStyles & wxFONTFLAG_UNDERLINED) ? true : false;
// Check if we need to change font style
// (changing the font can be expensive, so we want to avoid it if possible)
const bool styleChanged = (m_font.GetStyle() != fontStyle);
const bool widthChanged = (m_font.GetWeight() != fontWeight);
const bool underlineChanged = (m_font.GetUnderlined() != fontUnderline);
if (!styleChanged && !widthChanged && !underlineChanged) return;
// Check if we have font in cache
map<int,wxFont>::const_iterator p = fontMap.find(fontStyles);
if (p == fontMap.end()) {
m_font.SetStyle(fontStyle);
m_font.SetWeight(fontWeight);
m_font.SetUnderlined(fontUnderline);
fontMap[fontStyles] = m_font;
}
else m_font = p->second;
/*m_font.SetStyle(fontStyle);
m_font.SetWeight(fontWeight);
m_font.SetUnderlined(fontUnderline);*/
#ifdef __WXMSW__
HGDIOBJ hfont = ::SelectObject(GetHdc(), GetHfontOf(m_font));
if ( hfont == HGDI_ERROR )
{
wxLogLastError(_T("SelectObject(font)"));
}
else // selected ok
{
if ( !m_oldFont )
m_oldFont = (WXHPEN)hfont;
}
#else
SetFont(m_font);
#endif
}
| [
"stigsen@e-texteditor.com"
] | stigsen@e-texteditor.com |
36bc23cfe57e99bc71a6b87be592b4eab5034627 | 3f0f439d57f2185cb484f8faad78d49bab648627 | /external/rocksdb/table/iter_heap.h | 763d5f98c1eb1f44d00f3d5843e9032874e8c1b1 | [
"Apache-2.0",
"BSD-3-Clause",
"GPL-2.0-only",
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | b2n-project/bitcoin2network | f0f0d8c67e901004c9def6b39906c9edbc241554 | 0861d44ca8efd2c34c63acabe5468a094593d25d | refs/heads/master | 2020-03-18T04:40:53.034521 | 2019-02-16T07:32:31 | 2019-02-16T07:32:31 | 134,300,206 | 0 | 7 | MIT | 2019-02-16T07:32:32 | 2018-05-21T17:09:54 | C++ | UTF-8 | C++ | false | false | 1,273 | h | // Copyright (c) 2011-present, Facebook, Inc. All rights reserved.
// This source code is licensed under both the GPLv2 (found in the
// COPYING file in the root directory) and Apache 2.0 License
// (found in the LICENSE.Apache file in the root directory).
//
#pragma once
#include "rocksdb/comparator.h"
#include "table/iterator_wrapper.h"
namespace rocksdb {
// When used with std::priority_queue, this comparison functor puts the
// iterator with the max/largest key on top.
class MaxIteratorComparator {
public:
MaxIteratorComparator(const Comparator* comparator) :
comparator_(comparator) {}
bool operator()(IteratorWrapper* a, IteratorWrapper* b) const {
return comparator_->Compare(a->key(), b->key()) < 0;
}
private:
const Comparator* comparator_;
};
// When used with std::priority_queue, this comparison functor puts the
// iterator with the min/smallest key on top.
class MinIteratorComparator {
public:
MinIteratorComparator(const Comparator* comparator) :
comparator_(comparator) {}
bool operator()(IteratorWrapper* a, IteratorWrapper* b) const {
return comparator_->Compare(a->key(), b->key()) > 0;
}
private:
const Comparator* comparator_;
};
} // namespace rocksdb
| [
"devs@bitcoin2.network"
] | devs@bitcoin2.network |
259e7d42c7270780d6c57abbe1c1514abbfc841d | 7c17e5606be4ad8d1785226deb3fe5677e04d099 | /stuff/urho3d/Source/Samples/00_ignition/relative_pose/_zzz/pioneer_src/ui/CellSpec.cpp | ed1ed360b6338523893f0394d24286020baca353 | [
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] | permissive | z80/ignition | a4fa4adb32fed843ee41bcdc83e41ba3d70f048b | 629c9d998d53de33f3b123910770f73c9e783234 | refs/heads/master | 2023-07-21T17:46:52.510964 | 2023-04-04T17:18:41 | 2023-04-04T17:18:41 | 206,724,558 | 14 | 3 | null | 2022-06-23T00:02:44 | 2019-09-06T06:06:22 | C++ | UTF-8 | C++ | false | false | 606 | cpp | // Copyright © 2008-2020 Pioneer Developers. See AUTHORS.txt for details
// Licensed under the terms of the GPL v3. See licenses/GPL-3.txt
#include "CellSpec.h"
#include "LuaObject.h"
namespace UI {
CellSpec CellSpec::FromLuaTable(lua_State *l, int idx)
{
const int table = lua_absindex(l, idx);
assert(lua_istable(l, table));
const int len = lua_rawlen(l, table);
std::vector<float> cellPercent(len);
for (int i = 0; i < len; i++) {
lua_rawgeti(l, table, i + 1);
cellPercent[i] = luaL_checknumber(l, -1);
lua_pop(l, 1);
}
return CellSpec(cellPercent);
}
} // namespace UI
| [
"bashkirov.sergey@gmail.com"
] | bashkirov.sergey@gmail.com |
2e8245afa88bcc31394c90934f63b39a1b2bbda1 | eb7047d5a8c00d4370a55c2806a2f051287b452d | /modulesrc/topology/ReverseCuthillMcKee.i | 967c75b2e191b3e4eefa51f3bfd1b7518520188f | [
"MIT"
] | permissive | mousumiroy-unm/pylith | 8361a1c0fbcde99657fd3c4e88678a8b5fc8398b | 9a7b6b4ee8e1b89bc441bcedc5ed28a3318e2468 | refs/heads/main | 2023-05-27T18:40:57.145323 | 2021-06-09T19:32:19 | 2021-06-09T19:32:19 | 373,931,160 | 0 | 0 | MIT | 2021-06-04T18:40:09 | 2021-06-04T18:40:09 | null | UTF-8 | C++ | false | false | 1,242 | i | // -*- C++ -*-
//
// ======================================================================
//
// Brad T. Aagaard, U.S. Geological Survey
// Charles A. Williams, GNS Science
// Matthew G. Knepley, University of Chicago
//
// This code was developed as part of the Computational Infrastructure
// for Geodynamics (http://geodynamics.org).
//
// Copyright (c) 2010-2017 University of California, Davis
//
// See COPYING for license information.
//
// ======================================================================
//
/**
* @file modulesrc/topology/ReverseCuthillMcKee.hh
*
* @brief Python interface to C++ PyLith ReverseCuthillMcKee object.
*/
namespace pylith {
namespace topology {
// ReverseCuthillMcKee ----------------------------------------------
class ReverseCuthillMcKee
{ // ReverseCuthillMcKee
// PUBLIC METHODS /////////////////////////////////////////////////
public :
/** Reorder vertices and cells of mesh using PETSc routines
* implementing reverse Cuthill-McKee algorithm.
*
* @param mesh PyLith finite-element mesh.
*/
static
void reorder(topology::Mesh* mesh);
}; // ReverseCuthillMcKee
} // topology
} // pylith
// End of file
| [
"baagaard@usgs.gov"
] | baagaard@usgs.gov |
0080998542d6451528769c360f09fcbca1af9499 | 93c66e44e6ae7e654aefc42cad10706a44aa2377 | /concurrency/then_19_25_2_2_1.cpp | d4b9b9e975246387c487e2f1502c1e1a04f05b11 | [] | no_license | dcampora/cpp11 | 11a61227522baa5d83a8f0d81300c84553a923ca | db3e2830d2eed370134e6d25193d0f22e8dbd605 | refs/heads/master | 2020-05-17T18:38:38.325947 | 2016-01-20T08:47:41 | 2016-01-20T08:47:41 | 32,726,789 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,638 | cpp | #include <iostream> // cout, endl
#include <future> // async, future
#include <thread> // thread, sleep_for
#include <vector> // vector
#include <random> // random_device, uniform_int_distribution
#include <chrono> // chrono (system_clock, sleep_for)
#include <utility> // declval
using std::cout; using std::endl;
//////////////////////////////////////////////////////////////////////////////////
// Some very important work that needs to be done. //
// Do not change the code in this box. //
void work(int t) { std::this_thread::sleep_for(std::chrono::milliseconds(t)); } //
//
int work_hard(int n) { //
std::random_device rd; //
std::uniform_int_distribution<int> choose(0, n); //
int m = choose(rd); //
work(m); //
return n - m; //
} //
//
int step_1(int n) { return work_hard(n); } //
int step_2(int n) { return work_hard(n); } //
int step_3(int n) { return work_hard(n); } //
int step_4(int n) { return work_hard(n); } //
int step_5(int n) { return work_hard(n); } //
int step_F(int n) { //
// Ensure that all remaining work is done //
int m = n; //
work(m); //
return n - m; //
} //
//////////////////////////////////////////////////////////////////////////////////
template <typename Future, typename Continuation>
auto then(Future f, Continuation continue_) -> std::future<decltype(continue_(f.get()))> {
return async(std::launch::async,
// In C++1y, [f = std::move(f)] should work
[continue_] (Future f) { return continue_(f.get()); },
std::move(f) ); // Faking capture by move
}
int main() {
int how_many = 10;
auto job_size = 300;
std::vector<int> jobs(how_many, job_size);
auto start = std::chrono::system_clock::now();
{
std::vector<std::future<void>> fs;
fs.reserve(how_many);
for (auto job: jobs) {
auto f1 = std::async(std::launch::async, step_1, job);
auto f2 = then(std::move(f1), step_2);
auto f3 = then(std::move(f2), step_3);
auto f4 = then(std::move(f3), step_4);
auto f5 = then(std::move(f4), step_5);
auto fF = then(std::move(f5), step_F);
fs.push_back(then(std::move(fF), [] (int r) { cout << "Remaining = " << r << endl; }));
}
}
auto stop = std::chrono::system_clock::now();
cout << "Completed in "
<< std::chrono::duration_cast<std::chrono::milliseconds>(stop - start).count()/1000.0
<< "s\n";
} | [
"danielcampora@gmail.com"
] | danielcampora@gmail.com |
c05148e7073ac569d389bd0b137c72ab87718d62 | fcc4e5e6c7ade243bd9fce6a3b7561a4d262e206 | /pwmLight/pwmLight.ino | a74d1df77a36fc12269f4658cf2cbb605eb0fd57 | [] | no_license | brucetsao/arduino_Programming | 48fd7e4e93035107fd46eb036161441a42030dcc | fbd44a0ba59fa4002d0879d7ad4182524894619b | refs/heads/master | 2021-01-15T16:17:34.427866 | 2015-06-29T05:17:49 | 2015-06-29T05:17:49 | 29,160,262 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 587 | ino | int val;//定義變數val
int ledpin=8 ;//定義Led pin8
int potpin=1;//定義可便電組類比介面0
void setup()
{
Serial.begin(9600);//設置串列傳輸速率為9600
pinMode(ledpin,OUTPUT);
//設置數位接腳13為輸出介面,Arduino 上我們用到的I/O 口都要進行類似這樣的定義。
}
void loop()
{
val=analogRead(potpin);// 讀取感測器的模擬值並賦值給val
Serial.println(val);//顯示val 變數
analogWrite(ledpin,map(val,0,1023,0,255));// 打開LED 並設置亮度(PWM 輸__________出最大值255)
delay(10);//延時0.01 秒
}
| [
"prgbruce@gmail.com"
] | prgbruce@gmail.com |
d3eea6e5469efd3c266df8b48a235bb05ed347e0 | 0f73c722e85ee23fcf7d276041a2dd3c2f8c36f4 | /helloworld.cpp | 8b998912ad8dcd8b0e7ee298a37f86763122c026 | [] | no_license | BohemianHacks/Programming-1 | 7be28c92c14464a9f1cdad144f22c9a8f541db57 | b83fdcb1770038fb0535b4a2dae18134e5fe4c45 | refs/heads/master | 2021-01-01T18:38:07.630437 | 2013-11-26T09:10:12 | 2013-11-26T09:10:12 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 269 | cpp | //Hello world program
//Built to introduce me to C++
//by Jeff Blecha
#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;
void print(string words){
cout << words << endl;
}
int main(){
print("Hello World!");
cin.ignore();
return 0;
}
| [
"jeff.blecha@gmail.com"
] | jeff.blecha@gmail.com |
eb24ba0a471d8cd6bc0fb0d6e0592a0c7d0c9131 | fa7a76c7646ced5f8ffbd009d4a21f05e187495a | /Live Archive/Live Archive/Triangle.cpp | fb5e05190cdb4e523b2510b9aaadbbdcfc827dac | [] | no_license | osama-afifi/Online-Judges-Solutions | 5273018f8373f377b9dafa85521c97beaa6574a0 | f49130f8ccbe8abc062f1b51a204edb819699b3a | refs/heads/master | 2021-01-10T19:54:34.488053 | 2015-04-23T21:42:54 | 2015-04-23T21:42:54 | 21,754,051 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,240 | cpp | //// NOT AC YET
//
//#include <vector>
//#include <list>
//#include <map>
//#include <set>
//#include <queue>
//#include <deque>
//#include <stack>
//#include <bitset>
//#include <algorithm>
//#include <functional>
//#include <numeric>
//#include <utility>
//#include <sstream>
//#include <iostream>
//#include <iomanip>
//#include <cstdio>
//#include <cmath>
//#include <cstdlib>
//#include <ctime>
//#include <cstring>
//
//using namespace std;
//#define FOR(i, a, b) for( int i = (a); i < (b); i++ )
//#define Fore(it, x) for(typeof (x.begin()) it = x.begin(); it != x.end (); it++)
//#define Set(a, s) memset(a, s, sizeof (a))
//#define mp make_pair
//
//long long M = 1000000007;
//inline long long app(double x)
//{
// if(abs(x-floor(x))>=abs(x-ceil(x)))
// return (long long)ceil(x);
// return (long long)floor(x);
//}
//
//inline int long long F(long long n)
//{
// if(n&1LL)
// app((double)((n+3.0)*(n+3.0))/48.0);
// else
// app((double)(n*n)/48.0);
//}
//
//
//int main()
//{
// freopen("input.in","r",stdin);
//
// int n;
// string text;
// int kase=0;
// while(cin>>n)
// {
// long long res=0;
// FOR(i,3,n+1)
// if(n%i==0)
// {
// long long x= F(i);
// long long z = n/i;
//
// }
// }
//
// return 0;
//} | [
"osama.egt@gmail.com"
] | osama.egt@gmail.com |
9349fc19bf2ddc311d41c401928c01e3bb7c0ee7 | de24652a9c94a974c92eb6cca1edcf04f465aa4f | /Ground.h | 8877f20e7518f868b219e5ba231dc0ca883968ef | [] | no_license | dencorg/Robot_vehicles_simulation | abbc9ee4f3525d71c0a2f3d2fd6189e9ce74baa5 | 062d9a3652731be6b67f441748758083cf822970 | refs/heads/master | 2020-06-08T00:34:25.716584 | 2015-06-10T19:25:10 | 2015-06-10T19:25:10 | 37,216,968 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,393 | h | #ifndef GROUND_H
#define GROUND_H
#include <iostream>
#include <cstdlib>
// class gia ena simeio sto edafos tou kosmou
class Ground {
private:
int ground_units; // monades sto edafos
// periektikotites sistatikwn
float palladio_content;
float iridio_content;
float leukoxriso_content;
// monades gia kathe sistatiko
int palladio_units;
int iridio_units;
int leukoxriso_units;
float access_danger; // epikindinotita prosvasis
bool flag; // simaia kindinou
bool base; // true an to simeio einai i basi
public:
// constructor
Ground();
// dwse tis posotites twn sistatikwn sto edafos
int getpalladiounits();
int getiridiounits();
int getleukoxrisounits();
// dwse tis periektikotites sistatikwn
float get_palladio_content();
float get_iridio_content();
float get_leukoxriso_content();
// thetoun tis posotites sistatikwn sto edafos
void setpalladiounits(int);
void setiridiounits(int);
void setleukoxrisounits(int);
float getaccessdanger(); // epistrefei tin epikindinotita
bool hasflag(); // true an ehei simaia kindinou
bool isbase(); // true an to simeio einai vasi
void info(); // plirofories gia to simeio sto edafos
// thetei simaia kindinou
void setflag();
// kanei to simeio vasi gia tin eksomoiwsi
void setbase();
};
#endif | [
"dencorg@gmail.com"
] | dencorg@gmail.com |
adbcb47923beed921e909cf617eccb56dbdd3fd1 | 6fc9a543ab23fb8d1253f7d073d864f41c2b9067 | /src/controller/ShowController.cpp | dc286e212c260c04e19f3143a837a286217ad5e4 | [] | no_license | MarcoCaballero/klondike-cpp | 73fa7e5c4a3974f47500259e9f1bb988202fd72c | 3b3a6acc5851c5fbe2cc86401951f7f9e3653189 | refs/heads/master | 2021-05-07T15:06:16.858655 | 2017-11-16T07:48:19 | 2017-11-16T07:48:19 | 109,833,496 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 132 | cpp | #include <controller/ShowController.h>
namespace controller {
ShowController::~ShowController() {
}
} /* namespace controller */
| [
"marco.caballero.d@gmail.com"
] | marco.caballero.d@gmail.com |
f3d81605dd407e3b51d2e523200a7bf5cd61ee65 | 1bbf0f087abe2a2c1522f7a5aa422cb75bb6d319 | /Tecnicas de programação 1/trabforcabrabo/mainwindow.cpp | 7505cfa720d39a7f5fe9db77ee81f6aaf876bbc1 | [] | no_license | xfelipealves/SecondSemester | 0f0839a40e08319f454d3e5f414df581b2614e25 | 0777d76dbbf7b6369963b09996d37f5a614cb101 | refs/heads/main | 2023-06-21T19:26:09.783376 | 2021-07-21T03:10:29 | 2021-07-21T03:10:29 | 387,977,596 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,092 | cpp | #include "mainwindow.h"
#include "ui_mainwindow.h"
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow),
btns(nullptr),
jogo(nullptr)
{
ui->setupUi(this);
jogo=new Jogo;
btns=new QPushButton*[26]; //inicializar vetor de botoes
criarBotoes();
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::btnClicked()
{
QPushButton *btn=qobject_cast<QPushButton*>(sender()); //converter Qobjetc para QPushButton
QString letra = btn->text();
btn->setEnabled(false); //desabilitar botao
QMessageBox::information(this, "Tecla pressionada", "A tecla "+letra+" foi pressionado");
}
void MainWindow::criarBotoes()
{
int tb=35; //tamanho da largura e altura
QHBoxLayout *caxinha1H=new QHBoxLayout[2];
QVBoxLayout *vertizin=new QVBoxLayout;
QString Letras= "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
for (int l = 0, x=0 ; l < 2; ++l) {
for (int i = 0; i < 13; ++i,x++) {
QPushButton *btn=new QPushButton;
btn->setText(Letras.at(x));
btn->setMinimumWidth(tb); //largura minima
btn->setMinimumHeight(tb); //altura minima
btn->setMaximumWidth(tb); //largura max
btn->setMaximumHeight(tb); //altura max
(caxinha1H+l)->addWidget(btn);
btns[x]=btn;
connect(btn,SIGNAL(clicked()),this,SLOT(btnClicked()));
}
vertizin->addLayout(caxinha1H+l); //adicionar o layout horizonatal no vertical
}
ui->botoesArea->setLayout(vertizin);
}
void MainWindow::habilitarBotoes()
{
for (int i = 0; i < 26; ++i) {
btns[i]->setEnabled(true); //habilitar botoes
}
}
void MainWindow::desabilitarBotoes()
{
for (int i = 0; i < 26; ++i) {
btns[i]->setEnabled(false); //desabilitar botoes
}
}
void MainWindow::inicioJogo()
{
habilitarBotoes();
if (jogo) delete jogo;
jogo=new Jogo;
QString nome=QInputDialog::getText(this,"Game Start","Type your name");
}
void MainWindow::on_actionNew_Game_triggered()
{
inicioJogo();
}
| [
"felipecamiloalves04@gmail.com"
] | felipecamiloalves04@gmail.com |
0a82745e7632c6585929b0be613f491880aa56c5 | 5a1fddd1b5b317476d280b4536c5f38a7b1c1b9e | /ThunderFox/ThunderFox/TFGizmo.h | c65682a670f8c48840af2f009aff6ab09401c6f3 | [] | no_license | o-tantk/ThunderfoxEngine | 0c991fcb8b675f4f9d1620fb78bf6f7ddaef3840 | 7504d05faab8f4bc718d7d2951978b464279322f | refs/heads/master | 2021-01-15T09:42:41.904444 | 2016-05-06T20:46:04 | 2016-05-06T20:46:04 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,351 | h | #ifndef _TFGIZMO_H_
#define _TFGIZMO_H_
#include "gl\glew.h"
#include "glm\glm.hpp"
#include "TFShader.h"
#include "TFHandle.h"
#include <vector>
struct GizmoPoint{
glm::vec3 vertex;
glm::vec3 color;
};
enum {
MAX_GIZMO_LINES = 100,
MAX_GIZMO_POINTS = 100,
};
//class TFGizmo{
//private:
// TFGizmo(TFGizmo const&);
// void operator = (TFGizmo const&);
//
// static std::vector<TFGizmo *> m_instances;
//protected:
// TFGizmo(){
// m_instances.push_back(this);
// }
//
// virtual void drawGizmo() = 0;
//public:
// static void draw(){
//
// }
//};
class TFGizmo{
private:
GLuint m_vertexBuffer;
GizmoPoint m_lines[MAX_GIZMO_LINES];
GizmoPoint m_points[MAX_GIZMO_POINTS];
int m_lineCount, m_pointCount;
public:
TFGizmo() {
glGenBuffers(1, &m_vertexBuffer);
glBindBuffer(GL_ARRAY_BUFFER, m_vertexBuffer);
int sss = sizeof(m_lines);
glBufferData(GL_ARRAY_BUFFER, sizeof(m_lines), nullptr, GL_DYNAMIC_DRAW);
m_lineCount = 0;
m_pointCount = 0;
}
~TFGizmo(){
glDeleteBuffers(1, &m_vertexBuffer);
}
void drawLine(glm::vec3 color, glm::vec3 p1, glm::vec3 p2){
//m_lines.push_back({ p1, color });
//m_lines.push_back({ p2, color });
if (m_lineCount == MAX_GIZMO_LINES - 1){
return;
}
m_lines[m_lineCount++] = { p1, color };
m_lines[m_lineCount++] = { p2, color };
}
void drawPoint(glm::vec3 color, glm::vec3 p){
if (m_pointCount == MAX_GIZMO_POINTS - 1){
return;
}
m_points[m_pointCount++] = { p, color };
}
void flush(){
glBindBuffer(GL_ARRAY_BUFFER, m_vertexBuffer);
GLvoid *vbo_buffer = glMapBuffer(GL_ARRAY_BUFFER, GL_WRITE_ONLY);
memcpy(vbo_buffer, m_lines, m_lineCount * sizeof(GizmoPoint));
glUnmapBuffer(GL_ARRAY_BUFFER);
glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 2 * sizeof(glm::vec3), (void *)0);
TFHandle::checkOpenGL(__FILE__, __LINE__);
glEnableVertexAttribArray(1);
glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 2 * sizeof(glm::vec3), (void *)(sizeof(glm::vec3)));
TFHandle::checkOpenGL(__FILE__, __LINE__);
TFHandle::checkOpenGL(__FILE__, __LINE__);
//glDrawArrays(GL_LINES, 0, m_lines.size() * 6);
glDrawArrays(GL_LINES, 0, 6 * m_lineCount);
glDisableVertexAttribArray(0);
glDisableVertexAttribArray(1);
TFHandle::checkOpenGL(__FILE__, __LINE__);
m_lineCount = 0;
m_pointCount = 0;
}
};
#endif | [
"tantk90@hotmail.com"
] | tantk90@hotmail.com |
1d11dc71461a26cfba5e51174fe2680f9e24c7a9 | 0a1252a1bbc41925d41ad7fc91b619f528ce817e | /lib/arduino/QuadEncoderSensor.cpp | 89c743f43105e52c4cfd94fadadf88a2b969345c | [] | no_license | IkonOne/invpend | b845c7018779c6bb8d8137f3911f95ece3bc76c8 | 7b9f9769812e8c2542bad6e6190cacb791e383cd | refs/heads/master | 2021-05-20T12:52:03.616356 | 2020-04-30T20:46:07 | 2020-04-30T20:46:07 | 252,304,634 | 0 | 1 | null | 2020-04-27T20:18:00 | 2020-04-01T22:57:05 | C++ | UTF-8 | C++ | false | false | 1,309 | cpp | #include "QuadEncoderSensor.h"
#include "Arduino.h"
// Core iplib libraries
#include "../MathHelpers.h"
/**
* QuadEncoderSensor Class Definition
*/
namespace iplib {
namespace arduino {
QuadEncoderSensor::QuadEncoderSensor(uint8_t emitterPin, uint8_t sensorPin0, uint8_t sensorPin1)
: _mapMin(-1.0f), _mapMax(1.0f)
{
_sensorPins[0] = sensorPin0;
_sensorPins[1] = sensorPin1;
_qtr.setTypeAnalog();
_qtr.setSensorPins(_sensorPins, 2);
_qtr.setEmitterPin(emitterPin);
_qtr.setSamplesPerSensor(1);
}
void QuadEncoderSensor::Calibrate(uint16_t duration_ms) {
// analogRead() takes about 0.1ms on avg
// 0.1ms * 1 sample per sensor * 2 sensors
// * 10 reads per calibrate() call = ~20ms per calibrate()
for (uint16_t i = 0; i < duration_ms / 20; ++i)
_qtr.calibrate();
}
void QuadEncoderSensor::Update() {
_qtr.read(_values);
}
void QuadEncoderSensor::SetMapRange(float min, float max) {
_mapMin = min;
_mapMax = max;
}
float QuadEncoderSensor::ReadMappedValue(int pin) {
return iplib::fmap(
_values[pin],
_qtr.calibrationOn.minimum[pin], _qtr.calibrationOn.maximum[pin],
_mapMin, _mapMax
);
}
uint16_t QuadEncoderSensor::ReadCalibratedValue(int pin) {
return _values[pin];
}
} // arduino
} // iplib | [
"ikonone@gmail.com"
] | ikonone@gmail.com |
b633310855d8a04618da56f3c99e1bf19d349331 | 43a2fbc77f5cea2487c05c7679a30e15db9a3a50 | /Cpp/External (Offsets Only)/SDK/BP_FishingFish_StormFish_03_Colour_03_Wild_classes.h | 91b01995a131cfbf7464aedf26c2d17f31890fb4 | [] | no_license | zH4x/SoT-Insider-SDK | 57e2e05ede34ca1fd90fc5904cf7a79f0259085c | 6bff738a1b701c34656546e333b7e59c98c63ad7 | refs/heads/main | 2023-06-09T23:10:32.929216 | 2021-07-07T01:34:27 | 2021-07-07T01:34:27 | 383,638,719 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 955 | h | #pragma once
// Name: SoT-Insider, Version: 1.102.2382.0
/*!!DEFINE!!*/
/*!!HELPER_DEF!!*/
/*!!HELPER_INC!!*/
#ifdef _MSC_VER
#pragma pack(push, 0x01)
#endif
namespace CG
{
//---------------------------------------------------------------------------
// Classes
//---------------------------------------------------------------------------
// BlueprintGeneratedClass BP_FishingFish_StormFish_03_Colour_03_Wild.BP_FishingFish_StormFish_03_Colour_03_Wild_C
// 0x0000 (FullSize[0x0910] - InheritedSize[0x0910])
class ABP_FishingFish_StormFish_03_Colour_03_Wild_C : public ABP_FishingFish_StormFish_03_C
{
public:
static UClass* StaticClass()
{
static auto ptr = UObject::FindClass("BlueprintGeneratedClass BP_FishingFish_StormFish_03_Colour_03_Wild.BP_FishingFish_StormFish_03_Colour_03_Wild_C");
return ptr;
}
void UserConstructionScript();
void AfterRead();
void BeforeDelete();
};
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| [
"Massimo.linker@gmail.com"
] | Massimo.linker@gmail.com |
6be874fb39a9bdebf01527696999c34e447f0265 | 6a69d57c782e0b1b993e876ad4ca2927a5f2e863 | /vendor/samsung/common/packages/apps/SBrowser/src/components/autofill/core/browser/autofill_manager.cc | 8398b53095cff00fe2b99f74a81e8dd4c5ddcb11 | [
"BSD-3-Clause"
] | permissive | duki994/G900H-Platform-XXU1BOA7 | c8411ef51f5f01defa96b3381f15ea741aa5bce2 | 4f9307e6ef21893c9a791c96a500dfad36e3b202 | refs/heads/master | 2020-05-16T20:57:07.585212 | 2015-05-11T11:03:16 | 2015-05-11T11:03:16 | 35,418,464 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 45,455 | cc | // Copyright 2013 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/autofill/core/browser/autofill_manager.h"
#include <stddef.h>
#include <limits>
#include <map>
#include <set>
#include <utility>
#ifdef SAMSUNG_EDM
#include <string.h> //WTL_EDM
#endif //SAMSUNG_EDM
#include "base/bind.h"
#include "base/command_line.h"
#include "base/guid.h"
#include "base/logging.h"
#include "base/prefs/pref_service.h"
#include "base/strings/string16.h"
#include "base/strings/string_util.h"
#include "base/strings/utf_string_conversions.h"
#include "base/threading/sequenced_worker_pool.h"
#include "components/autofill/core/browser/autocomplete_history_manager.h"
#include "components/autofill/core/browser/autofill_data_model.h"
#include "components/autofill/core/browser/autofill_driver.h"
#include "components/autofill/core/browser/autofill_external_delegate.h"
#include "components/autofill/core/browser/autofill_field.h"
#include "components/autofill/core/browser/autofill_manager_delegate.h"
#include "components/autofill/core/browser/autofill_manager_test_delegate.h"
#include "components/autofill/core/browser/autofill_metrics.h"
#include "components/autofill/core/browser/autofill_profile.h"
#include "components/autofill/core/browser/autofill_type.h"
#include "components/autofill/core/browser/credit_card.h"
#include "components/autofill/core/browser/form_structure.h"
#include "components/autofill/core/browser/personal_data_manager.h"
#include "components/autofill/core/browser/phone_number.h"
#include "components/autofill/core/browser/phone_number_i18n.h"
#include "components/autofill/core/common/autofill_data_validation.h"
#include "components/autofill/core/common/autofill_pref_names.h"
#include "components/autofill/core/common/autofill_switches.h"
#include "components/autofill/core/common/form_data.h"
#include "components/autofill/core/common/form_data_predictions.h"
#include "components/autofill/core/common/form_field_data.h"
#include "components/autofill/core/common/password_form_fill_data.h"
#include "components/user_prefs/pref_registry_syncable.h"
#ifdef SAMSUNG_EDM
#include "edmnativehelper/EDMNativeHelper.h" //WTL_EDM
#endif //SAMSUNG_EDM
#include "grit/component_strings.h"
#include "third_party/WebKit/public/web/WebAutofillClient.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/gfx/rect.h"
#include "url/gurl.h"
namespace autofill {
typedef PersonalDataManager::GUIDPair GUIDPair;
using base::TimeTicks;
#ifdef SAMSUNG_EDM
//WTL_EDM_START
#define AUDITLOG_MSG_SIZE 34 // Size of header msg
extern "C" void c_auditLog(int severityGrade, int moduleGroup, bool outcome, int uid,
const char* swComponent, const char* logMessage) {
android::EDMNativeHelper::nativeLogger(severityGrade, moduleGroup, (int)outcome, uid,
swComponent, logMessage);
}
extern "C" bool c_isAuditLogEnabled() {
return android::EDMNativeHelper::isAuditLogEnabled();
}
//WTL_EDM_END
#endif //SAMSUNG_EDM
namespace {
// We only send a fraction of the forms to upload server.
// The rate for positive/negative matches potentially could be different.
const double kAutofillPositiveUploadRateDefaultValue = 0.20;
const double kAutofillNegativeUploadRateDefaultValue = 0.20;
const size_t kMaxRecentFormSignaturesToRemember = 3;
// Set a conservative upper bound on the number of forms we are willing to
// cache, simply to prevent unbounded memory consumption.
const size_t kMaxFormCacheSize = 100;
// Removes duplicate suggestions whilst preserving their original order.
void RemoveDuplicateSuggestions(std::vector<base::string16>* values,
std::vector<base::string16>* labels,
std::vector<base::string16>* icons,
std::vector<int>* unique_ids) {
DCHECK_EQ(values->size(), labels->size());
DCHECK_EQ(values->size(), icons->size());
DCHECK_EQ(values->size(), unique_ids->size());
std::set<std::pair<base::string16, base::string16> > seen_suggestions;
std::vector<base::string16> values_copy;
std::vector<base::string16> labels_copy;
std::vector<base::string16> icons_copy;
std::vector<int> unique_ids_copy;
for (size_t i = 0; i < values->size(); ++i) {
const std::pair<base::string16, base::string16> suggestion(
(*values)[i], (*labels)[i]);
if (seen_suggestions.insert(suggestion).second) {
values_copy.push_back((*values)[i]);
labels_copy.push_back((*labels)[i]);
icons_copy.push_back((*icons)[i]);
unique_ids_copy.push_back((*unique_ids)[i]);
}
}
values->swap(values_copy);
labels->swap(labels_copy);
icons->swap(icons_copy);
unique_ids->swap(unique_ids_copy);
}
// Precondition: |form_structure| and |form| should correspond to the same
// logical form. Returns true if any field in the given |section| within |form|
// is auto-filled.
bool SectionIsAutofilled(const FormStructure& form_structure,
const FormData& form,
const std::string& section) {
DCHECK_EQ(form_structure.field_count(), form.fields.size());
for (size_t i = 0; i < form_structure.field_count(); ++i) {
if (form_structure.field(i)->section() == section &&
form.fields[i].is_autofilled) {
return true;
}
}
return false;
}
bool FormIsHTTPS(const FormStructure& form) {
// TODO(blundell): Change this to use a constant once crbug.com/306258 is
// fixed.
return form.source_url().SchemeIs("https");
}
// Uses the existing personal data in |profiles| and |credit_cards| to determine
// possible field types for the |submitted_form|. This is potentially
// expensive -- on the order of 50ms even for a small set of |stored_data|.
// Hence, it should not run on the UI thread -- to avoid locking up the UI --
// nor on the IO thread -- to avoid blocking IPC calls.
void DeterminePossibleFieldTypesForUpload(
const std::vector<AutofillProfile>& profiles,
const std::vector<CreditCard>& credit_cards,
const std::string& app_locale,
FormStructure* submitted_form) {
// For each field in the |submitted_form|, extract the value. Then for each
// profile or credit card, identify any stored types that match the value.
for (size_t i = 0; i < submitted_form->field_count(); ++i) {
AutofillField* field = submitted_form->field(i);
ServerFieldTypeSet matching_types;
// If it's a password field, set the type directly.
if (field->form_control_type == "password") {
matching_types.insert(autofill::PASSWORD);
} else {
base::string16 value;
TrimWhitespace(field->value, TRIM_ALL, &value);
for (std::vector<AutofillProfile>::const_iterator it = profiles.begin();
it != profiles.end(); ++it) {
it->GetMatchingTypes(value, app_locale, &matching_types);
}
for (std::vector<CreditCard>::const_iterator it = credit_cards.begin();
it != credit_cards.end(); ++it) {
it->GetMatchingTypes(value, app_locale, &matching_types);
}
}
if (matching_types.empty())
matching_types.insert(UNKNOWN_TYPE);
field->set_possible_types(matching_types);
}
}
} // namespace
AutofillManager::AutofillManager(
AutofillDriver* driver,
autofill::AutofillManagerDelegate* delegate,
const std::string& app_locale,
AutofillDownloadManagerState enable_download_manager)
: driver_(driver),
manager_delegate_(delegate),
app_locale_(app_locale),
personal_data_(delegate->GetPersonalDataManager()),
autocomplete_history_manager_(
new AutocompleteHistoryManager(driver, delegate)),
metric_logger_(new AutofillMetrics),
has_logged_autofill_enabled_(false),
has_logged_address_suggestions_count_(false),
did_show_suggestions_(false),
user_did_type_(false),
user_did_autofill_(false),
user_did_edit_autofilled_field_(false),
external_delegate_(NULL),
test_delegate_(NULL),
weak_ptr_factory_(this) {
if (enable_download_manager == ENABLE_AUTOFILL_DOWNLOAD_MANAGER) {
download_manager_.reset(
new AutofillDownloadManager(driver,
manager_delegate_->GetPrefs(),
this));
}
}
AutofillManager::~AutofillManager() {}
// static
void AutofillManager::RegisterProfilePrefs(
user_prefs::PrefRegistrySyncable* registry) {
#if defined(S_AUTOFILL_REMEMBER_FORM_FILL_DATA)
registry->RegisterBooleanPref(
prefs::kRememberFormDataEnabled,
true,
user_prefs::PrefRegistrySyncable::SYNCABLE_PREF);
#endif
registry->RegisterBooleanPref(
prefs::kAutofillEnabled,
true,
user_prefs::PrefRegistrySyncable::SYNCABLE_PREF);
#if defined(OS_MACOSX) || defined(OS_ANDROID)
registry->RegisterBooleanPref(
prefs::kAutofillAuxiliaryProfilesEnabled,
true,
user_prefs::PrefRegistrySyncable::SYNCABLE_PREF);
#else
registry->RegisterBooleanPref(
prefs::kAutofillAuxiliaryProfilesEnabled,
false,
user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
#endif
registry->RegisterDoublePref(
prefs::kAutofillPositiveUploadRate,
kAutofillPositiveUploadRateDefaultValue,
user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
registry->RegisterDoublePref(
prefs::kAutofillNegativeUploadRate,
kAutofillNegativeUploadRateDefaultValue,
user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
}
void AutofillManager::SetExternalDelegate(AutofillExternalDelegate* delegate) {
// TODO(jrg): consider passing delegate into the ctor. That won't
// work if the delegate has a pointer to the AutofillManager, but
// future directions may not need such a pointer.
external_delegate_ = delegate;
autocomplete_history_manager_->SetExternalDelegate(delegate);
}
void AutofillManager::ShowAutofillSettings() {
manager_delegate_->ShowAutofillSettings();
}
#if defined(S_HIDE_AUTOFILL_OPTIMIZATION)
void AutofillManager::ShowAutofillPopupCalled(bool showing) {
driver_->ShowAutofillPopupCalled(showing);
}
#endif
bool AutofillManager::OnFormSubmitted(const FormData& form,
const TimeTicks& timestamp) {
if (!IsValidFormData(form))
return false;
// Let Autocomplete know as well.
autocomplete_history_manager_->OnFormSubmitted(form);
// Grab a copy of the form data.
scoped_ptr<FormStructure> submitted_form(new FormStructure(form));
if (!ShouldUploadForm(*submitted_form))
return false;
// Don't save data that was submitted through JavaScript.
if (!form.user_submitted)
return false;
// Ignore forms not present in our cache. These are typically forms with
// wonky JavaScript that also makes them not auto-fillable.
FormStructure* cached_submitted_form;
if (!FindCachedForm(form, &cached_submitted_form))
return false;
submitted_form->UpdateFromCache(*cached_submitted_form);
if (submitted_form->IsAutofillable(true))
ImportFormData(*submitted_form);
// Only upload server statistics and UMA metrics if at least some local data
// is available to use as a baseline.
const std::vector<AutofillProfile*>& profiles = personal_data_->GetProfiles();
const std::vector<CreditCard*>& credit_cards =
personal_data_->GetCreditCards();
if (!profiles.empty() || !credit_cards.empty()) {
// Copy the profile and credit card data, so that it can be accessed on a
// separate thread.
std::vector<AutofillProfile> copied_profiles;
copied_profiles.reserve(profiles.size());
for (std::vector<AutofillProfile*>::const_iterator it = profiles.begin();
it != profiles.end(); ++it) {
copied_profiles.push_back(**it);
}
std::vector<CreditCard> copied_credit_cards;
copied_credit_cards.reserve(credit_cards.size());
for (std::vector<CreditCard*>::const_iterator it = credit_cards.begin();
it != credit_cards.end(); ++it) {
copied_credit_cards.push_back(**it);
}
// Note that ownership of |submitted_form| is passed to the second task,
// using |base::Owned|.
FormStructure* raw_submitted_form = submitted_form.get();
driver_->GetBlockingPool()->PostTaskAndReply(
FROM_HERE,
base::Bind(&DeterminePossibleFieldTypesForUpload,
copied_profiles,
copied_credit_cards,
app_locale_,
raw_submitted_form),
base::Bind(&AutofillManager::UploadFormDataAsyncCallback,
weak_ptr_factory_.GetWeakPtr(),
base::Owned(submitted_form.release()),
forms_loaded_timestamp_,
initial_interaction_timestamp_,
timestamp));
}
return true;
}
void AutofillManager::OnFormsSeen(const std::vector<FormData>& forms,
const TimeTicks& timestamp,
autofill::FormsSeenState state) {
if (!IsValidFormDataVector(forms))
return;
bool is_post_document_load = state == autofill::DYNAMIC_FORMS_SEEN;
// If new forms were added dynamically, treat as a new page.
if (is_post_document_load)
Reset();
if (!driver_->RendererIsAvailable())
return;
bool enabled = IsAutofillEnabled();
if (!has_logged_autofill_enabled_) {
metric_logger_->LogIsAutofillEnabledAtPageLoad(enabled);
has_logged_autofill_enabled_ = true;
}
if (!enabled)
return;
forms_loaded_timestamp_ = timestamp;
ParseForms(forms);
}
void AutofillManager::OnTextFieldDidChange(const FormData& form,
const FormFieldData& field,
const TimeTicks& timestamp) {
if (!IsValidFormData(form) || !IsValidFormFieldData(field))
return;
FormStructure* form_structure = NULL;
AutofillField* autofill_field = NULL;
if (!GetCachedFormAndField(form, field, &form_structure, &autofill_field))
return;
if (!user_did_type_) {
user_did_type_ = true;
metric_logger_->LogUserHappinessMetric(AutofillMetrics::USER_DID_TYPE);
}
if (autofill_field->is_autofilled) {
autofill_field->is_autofilled = false;
metric_logger_->LogUserHappinessMetric(
AutofillMetrics::USER_DID_EDIT_AUTOFILLED_FIELD);
if (!user_did_edit_autofilled_field_) {
user_did_edit_autofilled_field_ = true;
metric_logger_->LogUserHappinessMetric(
AutofillMetrics::USER_DID_EDIT_AUTOFILLED_FIELD_ONCE);
}
}
UpdateInitialInteractionTimestamp(timestamp);
}
void AutofillManager::OnQueryFormFieldAutofill(int query_id,
const FormData& form,
const FormFieldData& field,
const gfx::RectF& bounding_box,
bool display_warning) {
if (!IsValidFormData(form) || !IsValidFormFieldData(field))
return;
std::vector<base::string16> values;
std::vector<base::string16> labels;
std::vector<base::string16> icons;
std::vector<int> unique_ids;
external_delegate_->OnQuery(query_id,
form,
field,
bounding_box,
display_warning);
FormStructure* form_structure = NULL;
AutofillField* autofill_field = NULL;
if (RefreshDataModels() &&
driver_->RendererIsAvailable() &&
GetCachedFormAndField(form, field, &form_structure, &autofill_field) &&
// Don't send suggestions for forms that aren't auto-fillable.
form_structure->IsAutofillable(false)) {
AutofillType type = autofill_field->Type();
bool is_filling_credit_card = (type.group() == CREDIT_CARD);
if (is_filling_credit_card) {
GetCreditCardSuggestions(
field, type, &values, &labels, &icons, &unique_ids);
} else {
GetProfileSuggestions(
form_structure, field, type, &values, &labels, &icons, &unique_ids);
}
DCHECK_EQ(values.size(), labels.size());
DCHECK_EQ(values.size(), icons.size());
DCHECK_EQ(values.size(), unique_ids.size());
if (!values.empty()) {
// Don't provide Autofill suggestions when Autofill is disabled, and don't
// provide credit card suggestions for non-HTTPS pages. However, provide a
// warning to the user in these cases.
int warning = 0;
if (!form_structure->IsAutofillable(true))
warning = IDS_AUTOFILL_WARNING_FORM_DISABLED;
else if (is_filling_credit_card && !FormIsHTTPS(*form_structure))
warning = IDS_AUTOFILL_WARNING_INSECURE_CONNECTION;
if (warning) {
values.assign(1, l10n_util::GetStringUTF16(warning));
labels.assign(1, base::string16());
icons.assign(1, base::string16());
unique_ids.assign(1,
blink::WebAutofillClient::MenuItemIDWarningMessage);
} else {
bool section_is_autofilled =
SectionIsAutofilled(*form_structure, form,
autofill_field->section());
if (section_is_autofilled) {
// If the relevant section is auto-filled and the renderer is querying
// for suggestions, then the user is editing the value of a field.
// In this case, mimic autocomplete: don't display labels or icons,
// as that information is redundant.
labels.assign(labels.size(), base::string16());
icons.assign(icons.size(), base::string16());
}
// When filling credit card suggestions, the values and labels are
// typically obfuscated, which makes detecting duplicates hard. Since
// duplicates only tend to be a problem when filling address forms
// anyway, only don't de-dup credit card suggestions.
if (!is_filling_credit_card)
RemoveDuplicateSuggestions(&values, &labels, &icons, &unique_ids);
// The first time we show suggestions on this page, log the number of
// suggestions shown.
if (!has_logged_address_suggestions_count_ && !section_is_autofilled) {
metric_logger_->LogAddressSuggestionsCount(values.size());
has_logged_address_suggestions_count_ = true;
}
}
}
}
// Add the results from AutoComplete. They come back asynchronously, so we
// hand off what we generated and they will send the results back to the
// renderer.
autocomplete_history_manager_->OnGetAutocompleteSuggestions(
query_id, field.name, field.value, values, labels, icons, unique_ids);
}
void AutofillManager::OnFillAutofillFormData(int query_id,
const FormData& form,
const FormFieldData& field,
int unique_id) {
if (!IsValidFormData(form) || !IsValidFormFieldData(field))
return;
const AutofillDataModel* data_model = NULL;
size_t variant = 0;
FormStructure* form_structure = NULL;
AutofillField* autofill_field = NULL;
// NOTE: RefreshDataModels may invalidate |data_model| because it causes the
// PersonalDataManager to reload Mac address book entries. Thus it must come
// before GetProfileOrCreditCard.
if (!RefreshDataModels() ||
!driver_->RendererIsAvailable() ||
!GetProfileOrCreditCard(unique_id, &data_model, &variant) ||
!GetCachedFormAndField(form, field, &form_structure, &autofill_field))
return;
DCHECK(form_structure);
DCHECK(autofill_field);
FormData result = form;
#ifdef SAMSUNG_EDM
//WTL_EDM_START
AutofillProfile* profile = NULL;
base::string16 profile_full_name;
char* audit_msg;
int audit_msg_len = 0;
if(c_isAuditLogEnabled()) { // Get profile info if AuditLog is enabled
profile = personal_data_->GetProfileByGUID(data_model->guid());
}
//WTL_EDM_END
#endif //SAMSUNG_EDM
// If the relevant section is auto-filled, we should fill |field| but not the
// rest of the form.
if (SectionIsAutofilled(*form_structure, form, autofill_field->section())) {
for (std::vector<FormFieldData>::iterator iter = result.fields.begin();
iter != result.fields.end(); ++iter) {
if ((*iter) == field) {
base::string16 value = data_model->GetInfoForVariant(
autofill_field->Type(), variant, app_locale_);
AutofillField::FillFormField(*autofill_field, value, app_locale_,
&(*iter));
// Mark the cached field as autofilled, so that we can detect when a
// user edits an autofilled field (for metrics).
autofill_field->is_autofilled = true;
#ifdef SAMSUNG_EDM
//WTL_EDM_START
//send autofill event to KNOX's AuditLog in case of AutofillProfile
if(profile && value != NULL && value.length() > 0) {
profile_full_name = profile->GetRawInfo(NAME_FULL);//, app_locale_);
audit_msg_len = value.length() + profile_full_name.length() + AUDITLOG_MSG_SIZE;
// If msg exists
if (audit_msg_len > AUDITLOG_MSG_SIZE){
audit_msg = (char*)malloc(audit_msg_len*sizeof(char));
if(audit_msg){
sprintf(audit_msg, "Auto-completing data for field %s %s",
UTF16ToUTF8(value).c_str(),UTF16ToUTF8(profile_full_name).c_str());
// Send autofill msg to auditlog
c_auditLog(1,1,1,1,"RequestFormData",audit_msg);
free(audit_msg);
}
}
}
//WTL_EDM_END
#endif //SAMSUNG_EDM
break;
}
}
driver_->SendFormDataToRenderer(query_id, result);
return;
}
// Cache the field type for the field from which the user initiated autofill.
FieldTypeGroup initiating_group_type = autofill_field->Type().group();
DCHECK_EQ(form_structure->field_count(), form.fields.size());
for (size_t i = 0; i < form_structure->field_count(); ++i) {
if (form_structure->field(i)->section() != autofill_field->section())
continue;
DCHECK_EQ(*form_structure->field(i), result.fields[i]);
const AutofillField* cached_field = form_structure->field(i);
FieldTypeGroup field_group_type = cached_field->Type().group();
if (field_group_type != NO_GROUP) {
// If the field being filled is either
// (a) the field that the user initiated the fill from, or
// (b) part of the same logical unit, e.g. name or phone number,
// then take the multi-profile "variant" into account.
// Otherwise fill with the default (zeroth) variant.
size_t use_variant = 0;
if (result.fields[i] == field ||
field_group_type == initiating_group_type) {
use_variant = variant;
}
base::string16 value = data_model->GetInfoForVariant(
cached_field->Type(), use_variant, app_locale_);
AutofillField::FillFormField(*cached_field, value, app_locale_,
&result.fields[i]);
// Mark the cached field as autofilled, so that we can detect when a user
// edits an autofilled field (for metrics).
form_structure->field(i)->is_autofilled = true;
#ifdef SAMSUNG_EDM
//WTL_EDM_START
//send autofill event to KNOX's AuditLog in case of AutofillProfile
if(profile && value != NULL && value.length() > 0) {
profile_full_name = profile->GetRawInfo(NAME_FULL);//, app_locale_);
audit_msg_len = value.length() + profile_full_name.length() + AUDITLOG_MSG_SIZE;
// If msg exists
if (audit_msg_len > AUDITLOG_MSG_SIZE){
audit_msg = (char*)malloc(audit_msg_len*sizeof(char));
if(audit_msg){
sprintf(audit_msg, "Auto-completing data for field %s %s",
UTF16ToUTF8(value).c_str(),UTF16ToUTF8(profile_full_name).c_str());
// Send autofill msg to auditlog
c_auditLog(1,1,1,1,"RequestFormData",audit_msg);
free(audit_msg);
}
}
}
//WTL_EDM_END
#endif //SAMSUNG_EDM
}
}
autofilled_form_signatures_.push_front(form_structure->FormSignature());
// Only remember the last few forms that we've seen, both to avoid false
// positives and to avoid wasting memory.
if (autofilled_form_signatures_.size() > kMaxRecentFormSignaturesToRemember)
autofilled_form_signatures_.pop_back();
driver_->SendFormDataToRenderer(query_id, result);
}
void AutofillManager::OnDidPreviewAutofillFormData() {
if (test_delegate_)
test_delegate_->DidPreviewFormData();
}
void AutofillManager::OnDidFillAutofillFormData(const TimeTicks& timestamp) {
if (test_delegate_)
test_delegate_->DidFillFormData();
metric_logger_->LogUserHappinessMetric(AutofillMetrics::USER_DID_AUTOFILL);
if (!user_did_autofill_) {
user_did_autofill_ = true;
metric_logger_->LogUserHappinessMetric(
AutofillMetrics::USER_DID_AUTOFILL_ONCE);
}
UpdateInitialInteractionTimestamp(timestamp);
}
void AutofillManager::OnDidShowAutofillSuggestions(bool is_new_popup) {
if (test_delegate_)
test_delegate_->DidShowSuggestions();
if (is_new_popup) {
metric_logger_->LogUserHappinessMetric(AutofillMetrics::SUGGESTIONS_SHOWN);
if (!did_show_suggestions_) {
did_show_suggestions_ = true;
metric_logger_->LogUserHappinessMetric(
AutofillMetrics::SUGGESTIONS_SHOWN_ONCE);
}
}
}
void AutofillManager::OnHideAutofillUI() {
if (!IsAutofillEnabled())
return;
manager_delegate_->HideAutofillPopup();
}
void AutofillManager::RemoveAutofillProfileOrCreditCard(int unique_id) {
const AutofillDataModel* data_model = NULL;
size_t variant = 0;
if (!GetProfileOrCreditCard(unique_id, &data_model, &variant)) {
NOTREACHED();
return;
}
// TODO(csharp): If we are dealing with a variant only the variant should
// be deleted, instead of doing nothing.
// http://crbug.com/124211
if (variant != 0)
return;
personal_data_->RemoveByGUID(data_model->guid());
}
void AutofillManager::RemoveAutocompleteEntry(const base::string16& name,
const base::string16& value) {
autocomplete_history_manager_->OnRemoveAutocompleteEntry(name, value);
}
const std::vector<FormStructure*>& AutofillManager::GetFormStructures() {
return form_structures_.get();
}
void AutofillManager::SetTestDelegate(
autofill::AutofillManagerTestDelegate* delegate) {
test_delegate_ = delegate;
}
void AutofillManager::OnAddPasswordFormMapping(
const FormFieldData& username_field,
const PasswordFormFillData& fill_data) {
if (!IsValidFormFieldData(username_field) ||
!IsValidPasswordFormFillData(fill_data))
return;
external_delegate_->AddPasswordFormMapping(username_field, fill_data);
}
void AutofillManager::OnShowPasswordSuggestions(
const FormFieldData& field,
const gfx::RectF& bounds,
const std::vector<base::string16>& suggestions,
const std::vector<base::string16>& realms) {
if (!IsValidString16Vector(suggestions) ||
!IsValidString16Vector(realms) ||
suggestions.size() != realms.size())
return;
external_delegate_->OnShowPasswordSuggestions(suggestions,
realms,
field,
bounds);
}
void AutofillManager::OnSetDataList(const std::vector<base::string16>& values,
const std::vector<base::string16>& labels) {
if (!IsValidString16Vector(values) ||
!IsValidString16Vector(labels) ||
values.size() != labels.size())
return;
external_delegate_->SetCurrentDataListValues(values, labels);
}
void AutofillManager::OnLoadedServerPredictions(
const std::string& response_xml) {
// Parse and store the server predictions.
FormStructure::ParseQueryResponse(response_xml,
form_structures_.get(),
*metric_logger_);
// Forward form structures to the password generation manager to detect
// account creation forms.
manager_delegate_->DetectAccountCreationForms(form_structures_.get());
// If the corresponding flag is set, annotate forms with the predicted types.
driver_->SendAutofillTypePredictionsToRenderer(form_structures_.get());
}
void AutofillManager::OnDidEndTextFieldEditing() {
external_delegate_->DidEndTextFieldEditing();
}
bool AutofillManager::IsAutofillEnabled() const {
return manager_delegate_->GetPrefs()->GetBoolean(prefs::kAutofillEnabled);
}
void AutofillManager::ImportFormData(const FormStructure& submitted_form) {
scoped_ptr<CreditCard> imported_credit_card;
if (!personal_data_->ImportFormData(submitted_form, &imported_credit_card))
return;
// If credit card information was submitted, we need to confirm whether to
// save it.
if (imported_credit_card) {
manager_delegate_->ConfirmSaveCreditCard(
*metric_logger_,
base::Bind(
base::IgnoreResult(&PersonalDataManager::SaveImportedCreditCard),
base::Unretained(personal_data_), *imported_credit_card));
}
}
// Note that |submitted_form| is passed as a pointer rather than as a reference
// so that we can get memory management right across threads. Note also that we
// explicitly pass in all the time stamps of interest, as the cached ones might
// get reset before this method executes.
void AutofillManager::UploadFormDataAsyncCallback(
const FormStructure* submitted_form,
const TimeTicks& load_time,
const TimeTicks& interaction_time,
const TimeTicks& submission_time) {
submitted_form->LogQualityMetrics(*metric_logger_,
load_time,
interaction_time,
submission_time);
if (submitted_form->ShouldBeCrowdsourced())
UploadFormData(*submitted_form);
}
void AutofillManager::UploadFormData(const FormStructure& submitted_form) {
if (!download_manager_)
return;
// Check if the form is among the forms that were recently auto-filled.
bool was_autofilled = false;
std::string form_signature = submitted_form.FormSignature();
for (std::list<std::string>::const_iterator it =
autofilled_form_signatures_.begin();
it != autofilled_form_signatures_.end() && !was_autofilled;
++it) {
if (*it == form_signature)
was_autofilled = true;
}
ServerFieldTypeSet non_empty_types;
personal_data_->GetNonEmptyTypes(&non_empty_types);
// Always add PASSWORD to |non_empty_types| so that if |submitted_form|
// contains a password field it will be uploaded to the server. If
// |submitted_form| doesn't contain a password field, there is no side
// effect from adding PASSWORD to |non_empty_types|.
non_empty_types.insert(autofill::PASSWORD);
download_manager_->StartUploadRequest(submitted_form, was_autofilled,
non_empty_types);
}
bool AutofillManager::UploadPasswordGenerationForm(const FormData& form) {
FormStructure form_structure(form);
if (!ShouldUploadForm(form_structure))
return false;
if (!form_structure.ShouldBeCrowdsourced())
return false;
// TODO(gcasto): Check that PasswordGeneration is enabled?
// Find the first password field to label. We don't try to label anything
// else.
bool found_password_field = false;
for (size_t i = 0; i < form_structure.field_count(); ++i) {
AutofillField* field = form_structure.field(i);
ServerFieldTypeSet types;
if (!found_password_field && field->form_control_type == "password") {
types.insert(ACCOUNT_CREATION_PASSWORD);
found_password_field = true;
} else {
types.insert(UNKNOWN_TYPE);
}
field->set_possible_types(types);
}
DCHECK(found_password_field);
// Only one field type should be present.
ServerFieldTypeSet available_field_types;
available_field_types.insert(ACCOUNT_CREATION_PASSWORD);
// Force uploading as these events are relatively rare and we want to make
// sure to receive them. It also makes testing easier if these requests
// always pass.
form_structure.set_upload_required(UPLOAD_REQUIRED);
if (!download_manager_)
return false;
return download_manager_->StartUploadRequest(form_structure,
false /* was_autofilled */,
available_field_types);
}
void AutofillManager::Reset() {
form_structures_.clear();
has_logged_autofill_enabled_ = false;
has_logged_address_suggestions_count_ = false;
did_show_suggestions_ = false;
user_did_type_ = false;
user_did_autofill_ = false;
user_did_edit_autofilled_field_ = false;
forms_loaded_timestamp_ = TimeTicks();
initial_interaction_timestamp_ = TimeTicks();
external_delegate_->Reset();
}
AutofillManager::AutofillManager(AutofillDriver* driver,
autofill::AutofillManagerDelegate* delegate,
PersonalDataManager* personal_data)
: driver_(driver),
manager_delegate_(delegate),
app_locale_("en-US"),
personal_data_(personal_data),
autocomplete_history_manager_(
new AutocompleteHistoryManager(driver, delegate)),
metric_logger_(new AutofillMetrics),
has_logged_autofill_enabled_(false),
has_logged_address_suggestions_count_(false),
did_show_suggestions_(false),
user_did_type_(false),
user_did_autofill_(false),
user_did_edit_autofilled_field_(false),
external_delegate_(NULL),
test_delegate_(NULL),
weak_ptr_factory_(this) {
DCHECK(driver_);
DCHECK(manager_delegate_);
}
void AutofillManager::set_metric_logger(const AutofillMetrics* metric_logger) {
metric_logger_.reset(metric_logger);
}
bool AutofillManager::RefreshDataModels() const {
if (!IsAutofillEnabled())
return false;
// No autofill data to return if the profiles are empty.
if (personal_data_->GetProfiles().empty() &&
personal_data_->GetCreditCards().empty()) {
return false;
}
return true;
}
bool AutofillManager::GetProfileOrCreditCard(
int unique_id,
const AutofillDataModel** data_model,
size_t* variant) const {
// Unpack the |unique_id| into component parts.
GUIDPair credit_card_guid;
GUIDPair profile_guid;
UnpackGUIDs(unique_id, &credit_card_guid, &profile_guid);
DCHECK(!base::IsValidGUID(credit_card_guid.first) ||
!base::IsValidGUID(profile_guid.first));
// Find the profile that matches the |profile_guid|, if one is specified.
// Otherwise find the credit card that matches the |credit_card_guid|,
// if specified.
if (base::IsValidGUID(profile_guid.first)) {
*data_model = personal_data_->GetProfileByGUID(profile_guid.first);
*variant = profile_guid.second;
} else if (base::IsValidGUID(credit_card_guid.first)) {
*data_model = personal_data_->GetCreditCardByGUID(credit_card_guid.first);
*variant = credit_card_guid.second;
}
return !!*data_model;
}
bool AutofillManager::FindCachedForm(const FormData& form,
FormStructure** form_structure) const {
// Find the FormStructure that corresponds to |form|.
// Scan backward through the cached |form_structures_|, as updated versions of
// forms are added to the back of the list, whereas original versions of these
// forms might appear toward the beginning of the list. The communication
// protocol with the crowdsourcing server does not permit us to discard the
// original versions of the forms.
*form_structure = NULL;
for (std::vector<FormStructure*>::const_reverse_iterator iter =
form_structures_.rbegin();
iter != form_structures_.rend(); ++iter) {
if (**iter == form) {
*form_structure = *iter;
// The same form might be cached with multiple field counts: in some
// cases, non-autofillable fields are filtered out, whereas in other cases
// they are not. To avoid thrashing the cache, keep scanning until we
// find a cached version with the same number of fields, if there is one.
if ((*iter)->field_count() == form.fields.size())
break;
}
}
if (!(*form_structure))
return false;
return true;
}
bool AutofillManager::GetCachedFormAndField(const FormData& form,
const FormFieldData& field,
FormStructure** form_structure,
AutofillField** autofill_field) {
// Find the FormStructure that corresponds to |form|.
// If we do not have this form in our cache but it is parseable, we'll add it
// in the call to |UpdateCachedForm()|.
if (!FindCachedForm(form, form_structure) &&
!FormStructure(form).ShouldBeParsed(false)) {
return false;
}
// Update the cached form to reflect any dynamic changes to the form data, if
// necessary.
if (!UpdateCachedForm(form, *form_structure, form_structure))
return false;
// No data to return if there are no auto-fillable fields.
if (!(*form_structure)->autofill_count())
return false;
// Find the AutofillField that corresponds to |field|.
*autofill_field = NULL;
for (std::vector<AutofillField*>::const_iterator iter =
(*form_structure)->begin();
iter != (*form_structure)->end(); ++iter) {
if ((**iter) == field) {
*autofill_field = *iter;
break;
}
}
// Even though we always update the cache, the field might not exist if the
// website disables autocomplete while the user is interacting with the form.
// See http://crbug.com/160476
return *autofill_field != NULL;
}
bool AutofillManager::UpdateCachedForm(const FormData& live_form,
const FormStructure* cached_form,
FormStructure** updated_form) {
bool needs_update =
(!cached_form ||
live_form.fields.size() != cached_form->field_count());
for (size_t i = 0; !needs_update && i < cached_form->field_count(); ++i) {
needs_update = *cached_form->field(i) != live_form.fields[i];
}
if (!needs_update)
return true;
if (form_structures_.size() >= kMaxFormCacheSize)
return false;
// Add the new or updated form to our cache.
form_structures_.push_back(new FormStructure(live_form));
*updated_form = *form_structures_.rbegin();
(*updated_form)->DetermineHeuristicTypes(*metric_logger_);
// If we have cached data, propagate it to the updated form.
if (cached_form) {
std::map<base::string16, const AutofillField*> cached_fields;
for (size_t i = 0; i < cached_form->field_count(); ++i) {
const AutofillField* field = cached_form->field(i);
cached_fields[field->unique_name()] = field;
}
for (size_t i = 0; i < (*updated_form)->field_count(); ++i) {
AutofillField* field = (*updated_form)->field(i);
std::map<base::string16, const AutofillField*>::iterator cached_field =
cached_fields.find(field->unique_name());
if (cached_field != cached_fields.end()) {
field->set_server_type(cached_field->second->server_type());
field->is_autofilled = cached_field->second->is_autofilled;
}
}
// Note: We _must not_ remove the original version of the cached form from
// the list of |form_structures_|. Otherwise, we break parsing of the
// crowdsourcing server's response to our query.
}
// Annotate the updated form with its predicted types.
std::vector<FormStructure*> forms(1, *updated_form);
driver_->SendAutofillTypePredictionsToRenderer(forms);
return true;
}
void AutofillManager::GetProfileSuggestions(
FormStructure* form,
const FormFieldData& field,
const AutofillType& type,
std::vector<base::string16>* values,
std::vector<base::string16>* labels,
std::vector<base::string16>* icons,
std::vector<int>* unique_ids) const {
std::vector<ServerFieldType> field_types(form->field_count());
for (size_t i = 0; i < form->field_count(); ++i) {
field_types.push_back(form->field(i)->Type().GetStorableType());
}
std::vector<GUIDPair> guid_pairs;
personal_data_->GetProfileSuggestions(
type, field.value, field.is_autofilled, field_types,
values, labels, icons, &guid_pairs);
for (size_t i = 0; i < guid_pairs.size(); ++i) {
unique_ids->push_back(PackGUIDs(GUIDPair(std::string(), 0),
guid_pairs[i]));
}
}
void AutofillManager::GetCreditCardSuggestions(
const FormFieldData& field,
const AutofillType& type,
std::vector<base::string16>* values,
std::vector<base::string16>* labels,
std::vector<base::string16>* icons,
std::vector<int>* unique_ids) const {
std::vector<GUIDPair> guid_pairs;
personal_data_->GetCreditCardSuggestions(
type, field.value, values, labels, icons, &guid_pairs);
for (size_t i = 0; i < guid_pairs.size(); ++i) {
unique_ids->push_back(PackGUIDs(guid_pairs[i], GUIDPair(std::string(), 0)));
}
}
void AutofillManager::ParseForms(const std::vector<FormData>& forms) {
std::vector<FormStructure*> non_queryable_forms;
for (std::vector<FormData>::const_iterator iter = forms.begin();
iter != forms.end(); ++iter) {
scoped_ptr<FormStructure> form_structure(new FormStructure(*iter));
if (!form_structure->ShouldBeParsed(false))
continue;
form_structure->DetermineHeuristicTypes(*metric_logger_);
// Set aside forms with method GET or author-specified types, so that they
// are not included in the query to the server.
if (form_structure->ShouldBeCrowdsourced())
form_structures_.push_back(form_structure.release());
else
non_queryable_forms.push_back(form_structure.release());
}
if (!form_structures_.empty() && download_manager_) {
// Query the server if we have at least one of the forms were parsed.
download_manager_->StartQueryRequest(form_structures_.get(),
*metric_logger_);
}
for (std::vector<FormStructure*>::const_iterator iter =
non_queryable_forms.begin();
iter != non_queryable_forms.end(); ++iter) {
form_structures_.push_back(*iter);
}
if (!form_structures_.empty())
metric_logger_->LogUserHappinessMetric(AutofillMetrics::FORMS_LOADED);
// For the |non_queryable_forms|, we have all the field type info we're ever
// going to get about them. For the other forms, we'll wait until we get a
// response from the server.
driver_->SendAutofillTypePredictionsToRenderer(non_queryable_forms);
}
int AutofillManager::GUIDToID(const GUIDPair& guid) const {
if (!base::IsValidGUID(guid.first))
return 0;
std::map<GUIDPair, int>::const_iterator iter = guid_id_map_.find(guid);
if (iter == guid_id_map_.end()) {
int id = guid_id_map_.size() + 1;
guid_id_map_[guid] = id;
id_guid_map_[id] = guid;
return id;
} else {
return iter->second;
}
}
const GUIDPair AutofillManager::IDToGUID(int id) const {
if (id == 0)
return GUIDPair(std::string(), 0);
std::map<int, GUIDPair>::const_iterator iter = id_guid_map_.find(id);
if (iter == id_guid_map_.end()) {
NOTREACHED();
return GUIDPair(std::string(), 0);
}
return iter->second;
}
// When sending IDs (across processes) to the renderer we pack credit card and
// profile IDs into a single integer. Credit card IDs are sent in the high
// word and profile IDs are sent in the low word.
int AutofillManager::PackGUIDs(const GUIDPair& cc_guid,
const GUIDPair& profile_guid) const {
int cc_id = GUIDToID(cc_guid);
int profile_id = GUIDToID(profile_guid);
DCHECK(cc_id <= std::numeric_limits<unsigned short>::max());
DCHECK(profile_id <= std::numeric_limits<unsigned short>::max());
return cc_id << std::numeric_limits<unsigned short>::digits | profile_id;
}
// When receiving IDs (across processes) from the renderer we unpack credit card
// and profile IDs from a single integer. Credit card IDs are stored in the
// high word and profile IDs are stored in the low word.
void AutofillManager::UnpackGUIDs(int id,
GUIDPair* cc_guid,
GUIDPair* profile_guid) const {
int cc_id = id >> std::numeric_limits<unsigned short>::digits &
std::numeric_limits<unsigned short>::max();
int profile_id = id & std::numeric_limits<unsigned short>::max();
*cc_guid = IDToGUID(cc_id);
*profile_guid = IDToGUID(profile_id);
}
void AutofillManager::UpdateInitialInteractionTimestamp(
const TimeTicks& interaction_timestamp) {
if (initial_interaction_timestamp_.is_null() ||
interaction_timestamp < initial_interaction_timestamp_) {
initial_interaction_timestamp_ = interaction_timestamp;
}
}
bool AutofillManager::ShouldUploadForm(const FormStructure& form) {
if (!IsAutofillEnabled())
return false;
if (driver_->IsOffTheRecord())
return false;
// Disregard forms that we wouldn't ever autofill in the first place.
if (!form.ShouldBeParsed(true))
return false;
return true;
}
} // namespace autofill
| [
"duki994@gmail.com"
] | duki994@gmail.com |
01279fd2ce3966ee5055668a9e553110579789e4 | 2f096838add21acb91e5d65b469f3dd8bc1ac716 | /I graphics project/Source.cpp | c456b14b1bc11b4231bc81f58be296e4b737e683 | [] | no_license | Fzrabbi/space-shooter | 4afcdee3612518bfee7b49b4822e47e3901bc74f | befb775a485b47662cc2888f1257d2d2a7981f8e | refs/heads/master | 2022-11-21T09:36:32.054870 | 2020-07-28T17:02:47 | 2020-07-28T17:02:47 | 283,276,185 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 54,551 | cpp | #include "iGraphics.h"
#include<stdlib.h>
int x,y,shipx=400,shipy=10,bugship1x,bugship1y=600,bugship2x=60,bugship2y=800,count=0,respawn_counter=0,bug_ship1_respawncounter=0,bug_ship2_respawncounter=0,enemy_boss1_respawncounter=0,firex=shipx,firey=shipy+10,score=0;
int eboss1x=400,eboss1y=350,sx=1,boss_firex=eboss1x,boss_firey=eboss1y,boss_hit=0,gameovercount=0;
bool start = true,option=false,about=false,blast=false,blast_bug_ship1=false,blast_bug_ship2=false,blast_enemy_boss1=false,gameover=false,level1=false,level2=false,level3=false,level4=false,level5=false,level6=false,level7=false,level8=false,level9=false,level10=false,victory=false;
char scoreText[100];
void rand_bugship1();
void rand_bugship2();
void rand_bossfire();
void rand_fire();
void iDraw()
{
iClear();
if(start==true)
{//main menue background
x;y;shipx=400;shipy=10;bugship1x;bugship1y=1000;bugship2x=60;bugship2y=900;count=0;respawn_counter=0,score=0;
blast=false;
if(option==false){
iShowBMP(0, 0,"image\\space_menu_background.bmp");
}
if(option==true){
iShowBMP(0,0, "image\\option.bmp");
}
if(about==true){
iShowBMP(0,0, "image\\about_background.bmp");
}
}
if(start==false)
{
iShowBMP(0, 0,"image\\game_background.bmp");//game sart background
iSetColor(255,0,0);//Score show
iText(705,475,"Score:");
_itoa_s(score,scoreText,10);
iText(755,475,scoreText);
//for shoing victory
if(score>=2000){
victory=true;
}
if(victory==true){
iShowBMP(100, 100,"image\\victory.bmp");
}
//for showing heart//
if(count==0){
iShowBMP(80, 475,"image\\heart.bmp");
iShowBMP(110, 475,"image\\heart.bmp");
iShowBMP(140, 475,"image\\heart.bmp");
}
if(count==1){
iShowBMP(80, 475,"image\\heart.bmp");
iShowBMP(110, 475,"image\\heart.bmp");
}
if(count==2){
iShowBMP(80, 475,"image\\heart.bmp");
}
//level setting
if(score>=0&&score<200){
iShowBMP(170, 470,"image\\level1.bmp");
level1=true;
level2=false;
level3=false;
level4=false;
level5=false;
level6=false;
level7=false;
level8=false;
level9=false;
level10=false;
}
if(score>=200&&score<400){
iShowBMP(170, 470,"image\\level2.bmp");
level1=false;
level2=true;
level3=false;
level4=false;
level5=false;
level6=false;
level7=false;
level8=false;
level9=false;
level10=false;
}
if(score>=400&&score<600){
iShowBMP(170, 470,"image\\level3.bmp");
level1=false;
level2=false;
level3=true;
level4=false;
level5=false;
level6=false;
level7=false;
level8=false;
level9=false;
level10=false;
}
if(score>=600&&score<800){
iShowBMP(170, 470,"image\\level4.bmp");
level1=false;
level2=false;
level3=false;
level4=true;
level5=false;
level6=false;
level7=false;
level8=false;
level9=false;
level10=false;
}
if(score>=800&&score<1000){
iShowBMP(170, 470,"image\\level5.bmp");
level1=false;
level2=false;
level3=false;
level4=false;
level5=true;
level6=false;
level7=false;
level8=false;
level9=false;
level10=false;
}
if(score>=1000&&score<1200){
iShowBMP(170, 470,"image\\level6.bmp");
level1=false;
level2=false;
level3=false;
level4=false;
level5=false;
level6=true;
level7=false;
level8=false;
level9=false;
level10=false;
}
if(score>=1200&&score<1400){
iShowBMP(170, 470,"image\\level7.bmp");
level1=false;
level2=false;
level3=false;
level4=false;
level5=false;
level6=false;
level7=true;
level8=false;
level9=false;
level10=false;
}
if(score>=1400&&score<1600){
iShowBMP(170, 470,"image\\level8.bmp");
level1=false;
level2=false;
level3=false;
level4=false;
level5=false;
level6=false;
level7=false;
level8=true;
level9=false;
level10=false;
}
if(score>=1600&&score<1800){
iShowBMP(170, 470,"image\\level9.bmp");
level1=false;
level2=false;
level3=false;
level4=false;
level5=false;
level6=false;
level7=false;
level8=false;
level9=true;
level10=false;
}
if(score>=1800&&score<2000){
iShowBMP(170, 470,"image\\level10.bmp");
level1=false;
level2=false;
level3=false;
level4=false;
level5=false;
level6=false;
level7=false;
level8=false;
level9=false;
level10=true;
}
//game over show
if(gameover==true){
gameovercount++;
iShowBMP(100, 100,"image\\gameover.bmp");
iSetColor(255,0,0);//Score show
iText(350,200,"Total Score:");
_itoa_s(score,scoreText,10);
iText(460,199,scoreText);
if(gameovercount>150){
gameover=false;
start=true;
gameovercount=0;
boss_hit=0;
}
}
//*************LEVEL 01***************
if(level1==true){
if(blast==false){
iShowBMP(shipx,shipy,"ships\\spaceship1.bmp");
}
else
{
iShowBMP(shipx,shipy,"ships\\blast.bmp");//blast my ship
respawn_counter++;
if(respawn_counter>100)//respawn my ship
{
blast=false;
respawn_counter=0;
}
}
//bug ship 1
if(blast_bug_ship1==false){
if(bugship1y<-80)
rand_bugship1();
else
{
if(bugship1x > 800 || bugship1x < 0)
{
bugship1x=-bugship1x;
}
else
{
if(bugship1y<450)
iShowBMP(bugship1x+=1,bugship1y-=3,"ships\\bug_ship01.bmp");
else
iShowBMP(bugship1x-=1,bugship1y-=2,"ships\\bug_ship01.bmp");
}
}
}
else{
iShowBMP(bugship1x,bugship1y,"ships\\blast_bug_ship01.bmp");//blast bug ship1
bug_ship1_respawncounter++;
if(bug_ship1_respawncounter>30)//respawn bug ship1
{
blast_bug_ship1=false;
bug_ship1_respawncounter=0;
bugship1y=-950;
}
}
//bugship2
if(blast_bug_ship2==false){
if(bugship2y<-100)
rand_bugship2();
else
{
iShowBMP(bugship2x,bugship2y-=3,"ships\\bug_ship2.bmp");
}
}
else{
iShowBMP(bugship2x,bugship2y,"ships\\blast_bug_ship2.bmp");//blast bug ship2
bug_ship2_respawncounter++;
if(bug_ship2_respawncounter>30)//respawn bug ship2
{
blast_bug_ship2=false;
bug_ship2_respawncounter=0;
bugship2y=-1000;
}
}
///if crash life lost
if(((bugship2x+64>=shipx)&&(bugship2x<=shipx+64))&&((bugship2y<=shipy+82)&&(bugship2y+67>=shipy)))
{
if(blast==false)
{
count++;
blast=true;
}
bugship2y=-1000;
if(count==3){
gameover=true;
//start=true;
option=false;
count=0;
shipy=1500;
}
}
if(((bugship1x+64>=shipx)&&(bugship1x<=shipx+64))&&((bugship1y<=shipy+82)&&(bugship1y+67>=shipy)))
{
if(blast==false)
{
blast=true;
count++;
}
bugship1y=-1000;
if(count==3)
{
gameover=true;
//start=true;;
option=false;
count=0;
shipy=1500;
}
}
//for my fire
if(firey>500)
rand_fire();
else
{
iShowBMP(firex+45,firey+=25,"ships\\fire.bmp");
iShowBMP(firex+10,firey,"ships\\fire.bmp");
}
//distroy enemy ship & score++
if(((firex+64>=bugship2x)&&(firex<=bugship2x+64))&&((firey<=bugship2y+67)&&(firey+35>=bugship2y)))
{
if(blast_bug_ship2==false)
{
blast_bug_ship2=true;
score+=2;
}
firey=600;
}
if(((firex+64>=bugship1x)&&(firex<=bugship1x+64))&&((firey<=bugship1y+67)&&(firey+35>=bugship1y)))
{
if(blast_bug_ship1==false)
{
blast_bug_ship1=true;
score+=5;
}
firey=600;
}
//boss 1 show
if(score>=50)
{
if(blast_enemy_boss1==false)
{
if(eboss1x>544||eboss1x<0)
{
//iShowBMP(ebossx++,ebossy,"ships//enemy_boss1");
sx=-sx;
}
iShowBMP(eboss1x+=sx,eboss1y,"ships//enemy_boss1.bmp");
//boss1 fire
if(boss_firey<0)
{
rand_bossfire();
}
else
{
iShowBMP(boss_firex+84,boss_firey-=5,"ships\\boss_fire.bmp");
iShowBMP(boss_firex+172,boss_firey,"ships\\boss_fire.bmp");
}
//boss fire destroy my ship
int x=boss_firex+84,x2=boss_firex+172;
if(((x-10>=shipx)&&(x<=shipx+54))&&((boss_firey<=shipy+82)&&(boss_firey+18>=shipy))||((x2-10>=shipx)&&(x2<=shipx+54))&&((boss_firey<=shipy+82)&&(boss_firey+18>=shipy)))
{
if(blast==false)
{
blast=true;
count++;
}
boss_firey=-1500;
if(count==3)
{
gameover=true;
//start=true;;
option=false;
count=0;
shipy=1500;
}
}
}
else
{
iShowBMP(eboss1x,eboss1y,"ships\\blast_enemy_boss1.bmp");//blast boss ship1
enemy_boss1_respawncounter++;
if(enemy_boss1_respawncounter>30)//respawn bug ship2
{
blast_enemy_boss1=false;
enemy_boss1_respawncounter=0;
eboss1y=-1000;
}
}
//my fire distroy boss ship
if(((firex+64>=eboss1x)&&(firex<=eboss1x+256))&&((firey<=eboss1y+67)&&(firey+23>=eboss1y)))
{
boss_hit++;
if(blast_enemy_boss1==false && boss_hit==40)
{
blast_enemy_boss1=true;
score+=100;
boss_hit=0;
}
firey=600;
}
}
//
}
//****************level 02*****************
if(level2==true){
if(blast==false){
iShowBMP(shipx,shipy,"ships\\spaceship1.bmp");
}
else
{
iShowBMP(shipx,shipy,"ships\\blast.bmp");//blast my ship
respawn_counter++;
if(respawn_counter>100)//respawn my ship
{
blast=false;
respawn_counter=0;
}
}
//bug ship 1
if(blast_bug_ship1==false){
if(bugship1y<-80)
rand_bugship1();
else
{
if(bugship1x > 800 || bugship1x < 0)
{
bugship1x=-bugship1x;
}
else
{
if(bugship1y<450)
iShowBMP(bugship1x+=1,bugship1y-=4,"ships\\bug_ship3.bmp");
else
iShowBMP(bugship1x-=1,bugship1y-=4,"ships\\bug_ship3.bmp");
}
}
}
else{
iShowBMP(bugship1x,bugship1y,"ships\\blast_bug_ship3.bmp");//blast bug ship1
bug_ship1_respawncounter++;
if(bug_ship1_respawncounter>30)//respawn bug ship1
{
blast_bug_ship1=false;
bug_ship1_respawncounter=0;
bugship1y=-950;
}
}
//bugship2
if(blast_bug_ship2==false){
if(bugship2y<-100)
rand_bugship2();
else
{
iShowBMP(bugship2x,bugship2y-=4,"ships\\bug_ship4.bmp");
}
}
else{
iShowBMP(bugship2x,bugship2y,"ships\\blast_bug_ship4.bmp");//blast bug ship2
bug_ship2_respawncounter++;
if(bug_ship2_respawncounter>30)//respawn bug ship2
{
blast_bug_ship2=false;
bug_ship2_respawncounter=0;
bugship2y=-1000;
}
}
///if crash life lost
if(((bugship2x+64>=shipx)&&(bugship2x<=shipx+64))&&((bugship2y<=shipy+82)&&(bugship2y+67>=shipy)))
{
if(blast==false)
{
count++;
blast=true;
}
bugship2y=-1000;
if(count==3){
gameover=true;
//start=true;;
option=false;
count=0;
shipy=1500;
}
}
if(((bugship1x+64>=shipx)&&(bugship1x<=shipx+64))&&((bugship1y<=shipy+82)&&(bugship1y+67>=shipy)))
{
if(blast==false)
{
blast=true;
count++;
}
bugship1y=-1000;
if(count==3)
{
gameover=true;
//start=true;;
option=false;
count=0;
shipy=1500;
}
}
//for my fire
if(firey>500)
rand_fire();
else
{
iShowBMP(firex+45,firey+=25,"ships\\fire.bmp");
iShowBMP(firex+10,firey,"ships\\fire.bmp");
}
//distroy enemy ship & score++
if(((firex+64>=bugship2x)&&(firex<=bugship2x+64))&&((firey<=bugship2y+67)&&(firey+35>=bugship2y)))
{
if(blast_bug_ship2==false)
{
blast_bug_ship2=true;
score+=2;
}
firey=600;
}
if(((firex+64>=bugship1x)&&(firex<=bugship1x+64))&&((firey<=bugship1y+67)&&(firey+35>=bugship1y)))
{
if(blast_bug_ship1==false)
{
blast_bug_ship1=true;
score+=5;
}
firey=600;
}
//boss 1 show
if(score>=250&&score<300)
{
eboss1y=350;
if(blast_enemy_boss1==false)
{
if(eboss1x>544||eboss1x<0)
{
//iShowBMP(ebossx++,ebossy,"ships//enemy_boss1");
sx=-sx;
}
iShowBMP(eboss1x+=sx,eboss1y,"ships//enemy_boss2.bmp");
//boss1 fire
if(boss_firey<0)
{
rand_bossfire();
}
else
{
iShowBMP(boss_firex+84,boss_firey-=8,"ships\\boss_fire.bmp");
iShowBMP(boss_firex+172,boss_firey,"ships\\boss_fire.bmp");
}
//boss fire destroy my ship
int x=boss_firex+84,x2=boss_firex+172;
if(((x-10>=shipx)&&(x<=shipx+54))&&((boss_firey<=shipy+82)&&(boss_firey+18>=shipy))||((x2-10>=shipx)&&(x2<=shipx+54))&&((boss_firey<=shipy+82)&&(boss_firey+18>=shipy)))
{
if(blast==false)
{
blast=true;
count++;
}
boss_firey=-1500;
if(count==3)
{
gameover=true;
//start=true;;
option=false;
count=0;
shipy=1500;
}
}
}
else
{
iShowBMP(eboss1x,eboss1y,"ships\\blast_enemy_boss2.bmp");//blast boss ship1
enemy_boss1_respawncounter++;
if(enemy_boss1_respawncounter>30)//respawn boss2
{
blast_enemy_boss1=false;
enemy_boss1_respawncounter=0;
eboss1y=-1000;
}
}
//my fire distroy boss ship
if(((firex+64>=eboss1x)&&(firex<=eboss1x+256))&&((firey<=eboss1y+67)&&(firey+23>=eboss1y)))
{
boss_hit++;
if(blast_enemy_boss1==false && boss_hit==40)
{
blast_enemy_boss1=true;
score+=100;
boss_hit=0;
}
firey=600;
}
}
//
}
//**********level 3***********
if(level3==true){
eboss1y=350;
if(blast==false){
iShowBMP(shipx,shipy,"ships\\spaceship1.bmp");
}
else
{
iShowBMP(shipx,shipy,"ships\\blast.bmp");//blast my ship
respawn_counter++;
if(respawn_counter>100)//respawn my ship
{
blast=false;
respawn_counter=0;
}
}
//bug ship 1
if(blast_bug_ship1==false){
if(bugship1y<-80)
rand_bugship1();
else
{
if(bugship1x > 800 || bugship1x < 0)
{
bugship1x=-bugship1x;
}
else
{
if(bugship1y<450)
iShowBMP(bugship1x+=1,bugship1y-=6,"ships\\bug_ship5.bmp");
else
iShowBMP(bugship1x-=1,bugship1y-=6,"ships\\bug_ship5.bmp");
}
}
}
else{
iShowBMP(bugship1x,bugship1y,"ships\\blast_bug_ship5.bmp");//blast bug ship1
bug_ship1_respawncounter++;
if(bug_ship1_respawncounter>30)//respawn bug ship1
{
blast_bug_ship1=false;
bug_ship1_respawncounter=0;
bugship1y=-950;
}
}
//bugship2
if(blast_bug_ship2==false){
if(bugship2y<-100)
rand_bugship2();
else
{
iShowBMP(bugship2x,bugship2y-=6,"ships\\bug_ship6.bmp");
}
}
else{
iShowBMP(bugship2x,bugship2y,"ships\\blast_bug_ship6.bmp");//blast bug ship2
bug_ship2_respawncounter++;
if(bug_ship2_respawncounter>30)//respawn bug ship2
{
blast_bug_ship2=false;
bug_ship2_respawncounter=0;
bugship2y=-1000;
}
}
///if crash life lost
if(((bugship2x+64>=shipx)&&(bugship2x<=shipx+64))&&((bugship2y<=shipy+82)&&(bugship2y+67>=shipy)))
{
if(blast==false)
{
count++;
blast=true;
}
bugship2y=-1000;
if(count==3){
gameover=true;
//start=true;;
option=false;
count=0;
shipy=1500;
}
}
if(((bugship1x+64>=shipx)&&(bugship1x<=shipx+64))&&((bugship1y<=shipy+82)&&(bugship1y+67>=shipy)))
{
if(blast==false)
{
blast=true;
count++;
}
bugship1y=-1000;
if(count==3)
{
gameover=true;
//start=true;;
option=false;
count=0;
shipy=1500;
}
}
//for my fire
if(firey>500)
rand_fire();
else
{
iShowBMP(firex+45,firey+=25,"ships\\fire.bmp");
iShowBMP(firex+10,firey,"ships\\fire.bmp");
}
//distroy enemy ship & score++
if(((firex+64>=bugship2x)&&(firex<=bugship2x+64))&&((firey<=bugship2y+67)&&(firey+35>=bugship2y)))
{
if(blast_bug_ship2==false)
{
blast_bug_ship2=true;
score+=2;
}
firey=600;
}
if(((firex+64>=bugship1x)&&(firex<=bugship1x+64))&&((firey<=bugship1y+67)&&(firey+35>=bugship1y)))
{
if(blast_bug_ship1==false)
{
blast_bug_ship1=true;
score+=5;
}
firey=600;
}
//boss 1 show
if(score>=450&&score<500)
{
eboss1y=350;
if(blast_enemy_boss1==false)
{
if(eboss1x>544||eboss1x<0)
{
//iShowBMP(ebossx++,ebossy,"ships//enemy_boss1");
sx=-sx;
}
iShowBMP(eboss1x+=sx,eboss1y,"ships//enemy_boss3.bmp");
//boss1 fire
if(boss_firey<0)
{
rand_bossfire();
}
else
{
iShowBMP(boss_firex+84,boss_firey-=10,"ships\\boss_fire.bmp");
iShowBMP(boss_firex+172,boss_firey,"ships\\boss_fire.bmp");
}
//boss fire destroy my ship
int x=boss_firex+84,x2=boss_firex+172;
if(((x-10>=shipx)&&(x<=shipx+54))&&((boss_firey<=shipy+82)&&(boss_firey+18>=shipy))||((x2-10>=shipx)&&(x2<=shipx+54))&&((boss_firey<=shipy+82)&&(boss_firey+18>=shipy)))
{
if(blast==false)
{
blast=true;
count++;
}
boss_firey=-1500;
if(count==3)
{
gameover=true;
//start=true;;
option=false;
count=0;
shipy=1500;
}
}
}
else
{
iShowBMP(eboss1x,eboss1y,"ships\\blast_enemy_boss3.bmp");//blast boss ship1
enemy_boss1_respawncounter++;
if(enemy_boss1_respawncounter>30)//respawn bug ship2
{
blast_enemy_boss1=false;
enemy_boss1_respawncounter=0;
eboss1y=-1000;
}
}
//my fire distroy boss ship
if(((firex+64>=eboss1x)&&(firex<=eboss1x+256))&&((firey<=eboss1y+67)&&(firey+23>=eboss1y)))
{
boss_hit++;
if(blast_enemy_boss1==false && boss_hit==40)
{
blast_enemy_boss1=true;
score+=100;
boss_hit=0;
}
firey=600;
}
}
//
}
//**********level 4************
if(level4==true){
eboss1y=350;
if(blast==false){
iShowBMP(shipx,shipy,"ships\\spaceship1.bmp");
}
else
{
iShowBMP(shipx,shipy,"ships\\blast.bmp");//blast my ship
respawn_counter++;
if(respawn_counter>100)//respawn my ship
{
blast=false;
respawn_counter=0;
}
}
//bug ship 1
if(blast_bug_ship1==false){
if(bugship1y<-80)
rand_bugship1();
else
{
if(bugship1x > 800 || bugship1x < 0)
{
bugship1x=-bugship1x;
}
else
{
if(bugship1y<450)
iShowBMP(bugship1x+=1,bugship1y-=6,"ships\\bug_ship7.bmp");
else
iShowBMP(bugship1x-=1,bugship1y-=6,"ships\\bug_ship7.bmp");
}
}
}
else{
iShowBMP(bugship1x,bugship1y,"ships\\blast_bug_ship7.bmp");//blast bug ship1
bug_ship1_respawncounter++;
if(bug_ship1_respawncounter>30)//respawn bug ship1
{
blast_bug_ship1=false;
bug_ship1_respawncounter=0;
bugship1y=-950;
}
}
//bugship2
if(blast_bug_ship2==false){
if(bugship2y<-100)
rand_bugship2();
else
{
iShowBMP(bugship2x,bugship2y-=6,"ships\\bug_ship8.bmp");
}
}
else{
iShowBMP(bugship2x,bugship2y,"ships\\blast_bug_ship8.bmp");//blast bug ship2
bug_ship2_respawncounter++;
if(bug_ship2_respawncounter>30)//respawn bug ship2
{
blast_bug_ship2=false;
bug_ship2_respawncounter=0;
bugship2y=-1000;
}
}
///if crash life lost
if(((bugship2x+64>=shipx)&&(bugship2x<=shipx+64))&&((bugship2y<=shipy+82)&&(bugship2y+67>=shipy)))
{
if(blast==false)
{
count++;
blast=true;
}
bugship2y=-1000;
if(count==3){
gameover=true;
//start=true;;
option=false;
count=0;
shipy=1500;
}
}
if(((bugship1x+64>=shipx)&&(bugship1x<=shipx+64))&&((bugship1y<=shipy+82)&&(bugship1y+67>=shipy)))
{
if(blast==false)
{
blast=true;
count++;
}
bugship1y=-1000;
if(count==3)
{
gameover=true;
//start=true;;
option=false;
count=0;
shipy=1500;
}
}
//for my fire
if(firey>500)
rand_fire();
else
{
iShowBMP(firex+45,firey+=25,"ships\\fire.bmp");
iShowBMP(firex+10,firey,"ships\\fire.bmp");
}
//distroy enemy ship & score++
if(((firex+64>=bugship2x)&&(firex<=bugship2x+64))&&((firey<=bugship2y+67)&&(firey+35>=bugship2y)))
{
if(blast_bug_ship2==false)
{
blast_bug_ship2=true;
score+=2;
}
firey=600;
}
if(((firex+64>=bugship1x)&&(firex<=bugship1x+64))&&((firey<=bugship1y+67)&&(firey+35>=bugship1y)))
{
if(blast_bug_ship1==false)
{
blast_bug_ship1=true;
score+=5;
}
firey=600;
}
//boss 1 show
if(score>=650&&score<700)
{
eboss1y=350;
if(blast_enemy_boss1==false)
{
if(eboss1x>544||eboss1x<0)
{
//iShowBMP(ebossx++,ebossy,"ships//enemy_boss1");
sx=-sx;
}
iShowBMP(eboss1x+=sx,eboss1y,"ships//enemy_boss4.bmp");
//boss1 fire
if(boss_firey<0)
{
rand_bossfire();
}
else
{
iShowBMP(boss_firex+84,boss_firey-=10,"ships\\boss_fire.bmp");
iShowBMP(boss_firex+172,boss_firey,"ships\\boss_fire.bmp");
}
//boss fire destroy my ship
int x=boss_firex+84,x2=boss_firex+172;
if(((x-10>=shipx)&&(x<=shipx+54))&&((boss_firey<=shipy+82)&&(boss_firey+18>=shipy))||((x2-10>=shipx)&&(x2<=shipx+54))&&((boss_firey<=shipy+82)&&(boss_firey+18>=shipy)))
{
if(blast==false)
{
blast=true;
count++;
}
boss_firey=-1500;
if(count==3)
{
gameover=true;
//start=true;;
option=false;
count=0;
shipy=1500;
}
}
}
else
{
iShowBMP(eboss1x,eboss1y,"ships\\blast_enemy_boss4.bmp");//blast boss ship1
enemy_boss1_respawncounter++;
if(enemy_boss1_respawncounter>30)//respawn bug ship2
{
blast_enemy_boss1=false;
enemy_boss1_respawncounter=0;
eboss1y=-1000;
}
}
//my fire distroy boss ship
if(((firex+64>=eboss1x)&&(firex<=eboss1x+256))&&((firey<=eboss1y+67)&&(firey+23>=eboss1y)))
{
boss_hit++;
if(blast_enemy_boss1==false && boss_hit==40)
{
blast_enemy_boss1=true;
score+=100;
boss_hit=0;
}
firey=600;
}
}
//
}
//**********level 5***********
if(level5==true){
eboss1y=350;
if(blast==false){
iShowBMP(shipx,shipy,"ships\\spaceship1.bmp");
}
else
{
iShowBMP(shipx,shipy,"ships\\blast.bmp");//blast my ship
respawn_counter++;
if(respawn_counter>100)//respawn my ship
{
blast=false;
respawn_counter=0;
}
}
//bug ship 1
if(blast_bug_ship1==false){
if(bugship1y<-80)
rand_bugship1();
else
{
if(bugship1x > 800 || bugship1x < 0)
{
bugship1x=-bugship1x;
}
else
{
if(bugship1y<450)
iShowBMP(bugship1x+=1,bugship1y-=6,"ships\\bug_ship9.bmp");
else
iShowBMP(bugship1x-=1,bugship1y-=6,"ships\\bug_ship9.bmp");
}
}
}
else{
iShowBMP(bugship1x,bugship1y,"ships\\blast_bug_ship9.bmp");//blast bug ship1
bug_ship1_respawncounter++;
if(bug_ship1_respawncounter>30)//respawn bug ship1
{
blast_bug_ship1=false;
bug_ship1_respawncounter=0;
bugship1y=-950;
}
}
//bugship2
if(blast_bug_ship2==false){
if(bugship2y<-100)
rand_bugship2();
else
{
iShowBMP(bugship2x,bugship2y-=6,"ships\\bug_ship10.bmp");
}
}
else{
iShowBMP(bugship2x,bugship2y,"ships\\blast_bug_ship10.bmp");//blast bug ship2
bug_ship2_respawncounter++;
if(bug_ship2_respawncounter>30)//respawn bug ship2
{
blast_bug_ship2=false;
bug_ship2_respawncounter=0;
bugship2y=-1000;
}
}
///if crash life lost
if(((bugship2x+64>=shipx)&&(bugship2x<=shipx+64))&&((bugship2y<=shipy+82)&&(bugship2y+67>=shipy)))
{
if(blast==false)
{
count++;
blast=true;
}
bugship2y=-1000;
if(count==3){
gameover=true;
//start=true;;
option=false;
count=0;
shipy=1500;
}
}
if(((bugship1x+64>=shipx)&&(bugship1x<=shipx+64))&&((bugship1y<=shipy+82)&&(bugship1y+67>=shipy)))
{
if(blast==false)
{
blast=true;
count++;
}
bugship1y=-1000;
if(count==3)
{
gameover=true;
//start=true;;
option=false;
count=0;
shipy=1500;
}
}
//for my fire
if(firey>500)
rand_fire();
else
{
iShowBMP(firex+45,firey+=25,"ships\\fire.bmp");
iShowBMP(firex+10,firey,"ships\\fire.bmp");
}
//distroy enemy ship & score++
if(((firex+64>=bugship2x)&&(firex<=bugship2x+64))&&((firey<=bugship2y+67)&&(firey+35>=bugship2y)))
{
if(blast_bug_ship2==false)
{
blast_bug_ship2=true;
score+=2;
}
firey=600;
}
if(((firex+64>=bugship1x)&&(firex<=bugship1x+64))&&((firey<=bugship1y+67)&&(firey+35>=bugship1y)))
{
if(blast_bug_ship1==false)
{
blast_bug_ship1=true;
score+=5;
}
firey=600;
}
//boss 1 show
if(score>=850&&score<900)
{
eboss1y=350;
if(blast_enemy_boss1==false)
{
if(eboss1x>544||eboss1x<0)
{
//iShowBMP(ebossx++,ebossy,"ships//enemy_boss1");
sx=-sx;
}
iShowBMP(eboss1x+=sx,eboss1y,"ships//enemy_boss5.bmp");
//boss1 fire
if(boss_firey<0)
{
rand_bossfire();
}
else
{
iShowBMP(boss_firex+84,boss_firey-=10,"ships\\boss_fire.bmp");
iShowBMP(boss_firex+172,boss_firey,"ships\\boss_fire.bmp");
}
//boss fire destroy my ship
int x=boss_firex+84,x2=boss_firex+172;
if(((x-10>=shipx)&&(x<=shipx+54))&&((boss_firey<=shipy+82)&&(boss_firey+18>=shipy))||((x2-10>=shipx)&&(x2<=shipx+54))&&((boss_firey<=shipy+82)&&(boss_firey+18>=shipy)))
{
if(blast==false)
{
blast=true;
count++;
}
boss_firey=-1500;
if(count==3)
{
gameover=true;
//start=true;;
option=false;
count=0;
shipy=1500;
}
}
}
else
{
iShowBMP(eboss1x,eboss1y,"ships\\blast_enemy_boss5.bmp");//blast boss ship1
enemy_boss1_respawncounter++;
if(enemy_boss1_respawncounter>30)//respawn bug ship2
{
blast_enemy_boss1=false;
enemy_boss1_respawncounter=0;
eboss1y=-1000;
}
}
//my fire distroy boss ship
if(((firex+64>=eboss1x)&&(firex<=eboss1x+256))&&((firey<=eboss1y+67)&&(firey+23>=eboss1y)))
{
boss_hit++;
if(blast_enemy_boss1==false && boss_hit==40)
{
blast_enemy_boss1=true;
score+=100;
boss_hit=0;
}
firey=600;
}
}
//
}
//**********level 6*********
if(level6==true){
if(blast==false){
iShowBMP(shipx,shipy,"ships\\spaceship1.bmp");
}
else
{
iShowBMP(shipx,shipy,"ships\\blast.bmp");//blast my ship
respawn_counter++;
if(respawn_counter>100)//respawn my ship
{
blast=false;
respawn_counter=0;
}
}
//bug ship 1
if(blast_bug_ship1==false){
if(bugship1y<-80)
rand_bugship1();
else
{
if(bugship1x > 800 || bugship1x < 0)
{
bugship1x=-bugship1x;
}
else
{
if(bugship1y<450)
iShowBMP(bugship1x+=1,bugship1y-=3,"ships\\bug_ship01.bmp");
else
iShowBMP(bugship1x-=1,bugship1y-=2,"ships\\bug_ship01.bmp");
}
}
}
else{
iShowBMP(bugship1x,bugship1y,"ships\\blast_bug_ship01.bmp");//blast bug ship1
bug_ship1_respawncounter++;
if(bug_ship1_respawncounter>30)//respawn bug ship1
{
blast_bug_ship1=false;
bug_ship1_respawncounter=0;
bugship1y=-950;
}
}
//bugship2
if(blast_bug_ship2==false){
if(bugship2y<-100)
rand_bugship2();
else
{
iShowBMP(bugship2x,bugship2y-=3,"ships\\bug_ship2.bmp");
}
}
else{
iShowBMP(bugship2x,bugship2y,"ships\\blast_bug_ship2.bmp");//blast bug ship2
bug_ship2_respawncounter++;
if(bug_ship2_respawncounter>30)//respawn bug ship2
{
blast_bug_ship2=false;
bug_ship2_respawncounter=0;
bugship2y=-1000;
}
}
///if crash life lost
if(((bugship2x+64>=shipx)&&(bugship2x<=shipx+64))&&((bugship2y<=shipy+82)&&(bugship2y+67>=shipy)))
{
if(blast==false)
{
count++;
blast=true;
}
bugship2y=-1000;
if(count==3){
gameover=true;
//start=true;;
option=false;
count=0;
shipy=1500;
}
}
if(((bugship1x+64>=shipx)&&(bugship1x<=shipx+64))&&((bugship1y<=shipy+82)&&(bugship1y+67>=shipy)))
{
if(blast==false)
{
blast=true;
count++;
}
bugship1y=-1000;
if(count==3)
{
gameover=true;
//start=true;;
option=false;
count=0;
shipy=1500;
}
}
//for my fire
if(firey>500)
rand_fire();
else
{
iShowBMP(firex+45,firey+=25,"ships\\fire.bmp");
iShowBMP(firex+10,firey,"ships\\fire.bmp");
}
//distroy enemy ship & score++
if(((firex+64>=bugship2x)&&(firex<=bugship2x+64))&&((firey<=bugship2y+67)&&(firey+35>=bugship2y)))
{
if(blast_bug_ship2==false)
{
blast_bug_ship2=true;
score+=2;
}
firey=600;
}
if(((firex+64>=bugship1x)&&(firex<=bugship1x+64))&&((firey<=bugship1y+67)&&(firey+35>=bugship1y)))
{
if(blast_bug_ship1==false)
{
blast_bug_ship1=true;
score+=5;
}
firey=600;
}
//boss 1 show
if(score>=1050&&score<1100)
{
if(blast_enemy_boss1==false)
{
if(eboss1x>544||eboss1x<0)
{
//iShowBMP(ebossx++,ebossy,"ships//enemy_boss1");
sx=-sx;
}
iShowBMP(eboss1x+=sx,eboss1y,"ships//enemy_boss6.bmp");
//boss1 fire
if(boss_firey<0)
{
rand_bossfire();
}
else
{
iShowBMP(boss_firex+84,boss_firey-=5,"ships\\boss_fire.bmp");
iShowBMP(boss_firex+172,boss_firey,"ships\\boss_fire.bmp");
}
//boss fire destroy my ship
int x=boss_firex+84,x2=boss_firex+172;
if(((x-10>=shipx)&&(x<=shipx+54))&&((boss_firey<=shipy+82)&&(boss_firey+18>=shipy))||((x2-10>=shipx)&&(x2<=shipx+54))&&((boss_firey<=shipy+82)&&(boss_firey+18>=shipy)))
{
if(blast==false)
{
blast=true;
count++;
}
boss_firey=-1500;
if(count==3)
{
gameover=true;
//start=true;;
option=false;
count=0;
shipy=1500;
}
}
}
else
{
iShowBMP(eboss1x,eboss1y,"ships\\blast_enemy_boss6.bmp");//blast boss ship1
enemy_boss1_respawncounter++;
if(enemy_boss1_respawncounter>30)//respawn bug ship2
{
blast_enemy_boss1=false;
enemy_boss1_respawncounter=0;
eboss1y=-1000;
}
}
//my fire distroy boss ship
if(((firex+64>=eboss1x)&&(firex<=eboss1x+256))&&((firey<=eboss1y+67)&&(firey+23>=eboss1y)))
{
boss_hit++;
if(blast_enemy_boss1==false && boss_hit==40)
{
blast_enemy_boss1=true;
score+=100;
boss_hit=0;
}
firey=600;
}
}
//
}
//****************level 7*****************
if(level7==true){
if(blast==false){
iShowBMP(shipx,shipy,"ships\\spaceship1.bmp");
}
else
{
iShowBMP(shipx,shipy,"ships\\blast.bmp");//blast my ship
respawn_counter++;
if(respawn_counter>100)//respawn my ship
{
blast=false;
respawn_counter=0;
}
}
//bug ship 1
if(blast_bug_ship1==false){
if(bugship1y<-80)
rand_bugship1();
else
{
if(bugship1x > 800 || bugship1x < 0)
{
bugship1x=-bugship1x;
}
else
{
if(bugship1y<450)
iShowBMP(bugship1x+=1,bugship1y-=4,"ships\\bug_ship3.bmp");
else
iShowBMP(bugship1x-=1,bugship1y-=4,"ships\\bug_ship3.bmp");
}
}
}
else{
iShowBMP(bugship1x,bugship1y,"ships\\blast_bug_ship3.bmp");//blast bug ship1
bug_ship1_respawncounter++;
if(bug_ship1_respawncounter>30)//respawn bug ship1
{
blast_bug_ship1=false;
bug_ship1_respawncounter=0;
bugship1y=-950;
}
}
//bugship2
if(blast_bug_ship2==false){
if(bugship2y<-100)
rand_bugship2();
else
{
iShowBMP(bugship2x,bugship2y-=4,"ships\\bug_ship4.bmp");
}
}
else{
iShowBMP(bugship2x,bugship2y,"ships\\blast_bug_ship4.bmp");//blast bug ship2
bug_ship2_respawncounter++;
if(bug_ship2_respawncounter>30)//respawn bug ship2
{
blast_bug_ship2=false;
bug_ship2_respawncounter=0;
bugship2y=-1000;
}
}
///if crash life lost
if(((bugship2x+64>=shipx)&&(bugship2x<=shipx+64))&&((bugship2y<=shipy+82)&&(bugship2y+67>=shipy)))
{
if(blast==false)
{
count++;
blast=true;
}
bugship2y=-1000;
if(count==3){
gameover=true;
//start=true;;
option=false;
count=0;
shipy=1500;
}
}
if(((bugship1x+64>=shipx)&&(bugship1x<=shipx+64))&&((bugship1y<=shipy+82)&&(bugship1y+67>=shipy)))
{
if(blast==false)
{
blast=true;
count++;
}
bugship1y=-1000;
if(count==3)
{
gameover=true;
//start=true;;
option=false;
count=0;
shipy=1500;
}
}
//for my fire
if(firey>500)
rand_fire();
else
{
iShowBMP(firex+45,firey+=25,"ships\\fire.bmp");
iShowBMP(firex+10,firey,"ships\\fire.bmp");
}
//distroy enemy ship & score++
if(((firex+64>=bugship2x)&&(firex<=bugship2x+64))&&((firey<=bugship2y+67)&&(firey+35>=bugship2y)))
{
if(blast_bug_ship2==false)
{
blast_bug_ship2=true;
score+=2;
}
firey=600;
}
if(((firex+64>=bugship1x)&&(firex<=bugship1x+64))&&((firey<=bugship1y+67)&&(firey+35>=bugship1y)))
{
if(blast_bug_ship1==false)
{
blast_bug_ship1=true;
score+=5;
}
firey=600;
}
//boss 1 show
if(score>=1250&&score<1300)
{
eboss1y=350;
if(blast_enemy_boss1==false)
{
if(eboss1x>544||eboss1x<0)
{
//iShowBMP(ebossx++,ebossy,"ships//enemy_boss1");
sx=-sx;
}
iShowBMP(eboss1x+=sx,eboss1y,"ships//enemy_boss7.bmp");
//boss1 fire
if(boss_firey<0)
{
rand_bossfire();
}
else
{
iShowBMP(boss_firex+84,boss_firey-=8,"ships\\boss_fire.bmp");
iShowBMP(boss_firex+172,boss_firey,"ships\\boss_fire.bmp");
}
//boss fire destroy my ship
int x=boss_firex+84,x2=boss_firex+172;
if(((x-10>=shipx)&&(x<=shipx+54))&&((boss_firey<=shipy+82)&&(boss_firey+18>=shipy))||((x2-10>=shipx)&&(x2<=shipx+54))&&((boss_firey<=shipy+82)&&(boss_firey+18>=shipy)))
{
if(blast==false)
{
blast=true;
count++;
}
boss_firey=-1500;
if(count==3)
{
gameover=true;
//start=true;;
option=false;
count=0;
shipy=1500;
}
}
}
else
{
iShowBMP(eboss1x,eboss1y,"ships\\blast_enemy_boss7.bmp");//blast boss ship1
enemy_boss1_respawncounter++;
if(enemy_boss1_respawncounter>30)//respawn boss2
{
blast_enemy_boss1=false;
enemy_boss1_respawncounter=0;
eboss1y=-1000;
}
}
//my fire distroy boss ship
if(((firex+64>=eboss1x)&&(firex<=eboss1x+256))&&((firey<=eboss1y+67)&&(firey+23>=eboss1y)))
{
boss_hit++;
if(blast_enemy_boss1==false && boss_hit==40)
{
blast_enemy_boss1=true;
score+=100;
boss_hit=0;
}
firey=600;
}
}
//
}
//**********level 8***********
if(level8==true){
eboss1y=350;
if(blast==false){
iShowBMP(shipx,shipy,"ships\\spaceship1.bmp");
}
else
{
iShowBMP(shipx,shipy,"ships\\blast.bmp");//blast my ship
respawn_counter++;
if(respawn_counter>100)//respawn my ship
{
blast=false;
respawn_counter=0;
}
}
//bug ship 1
if(blast_bug_ship1==false){
if(bugship1y<-80)
rand_bugship1();
else
{
if(bugship1x > 800 || bugship1x < 0)
{
bugship1x=-bugship1x;
}
else
{
if(bugship1y<450)
iShowBMP(bugship1x+=1,bugship1y-=6,"ships\\bug_ship5.bmp");
else
iShowBMP(bugship1x-=1,bugship1y-=6,"ships\\bug_ship5.bmp");
}
}
}
else{
iShowBMP(bugship1x,bugship1y,"ships\\blast_bug_ship5.bmp");//blast bug ship1
bug_ship1_respawncounter++;
if(bug_ship1_respawncounter>30)//respawn bug ship1
{
blast_bug_ship1=false;
bug_ship1_respawncounter=0;
bugship1y=-950;
}
}
//bugship2
if(blast_bug_ship2==false){
if(bugship2y<-100)
rand_bugship2();
else
{
iShowBMP(bugship2x,bugship2y-=6,"ships\\bug_ship6.bmp");
}
}
else{
iShowBMP(bugship2x,bugship2y,"ships\\blast_bug_ship6.bmp");//blast bug ship2
bug_ship2_respawncounter++;
if(bug_ship2_respawncounter>30)//respawn bug ship2
{
blast_bug_ship2=false;
bug_ship2_respawncounter=0;
bugship2y=-1000;
}
}
///if crash life lost
if(((bugship2x+64>=shipx)&&(bugship2x<=shipx+64))&&((bugship2y<=shipy+82)&&(bugship2y+67>=shipy)))
{
if(blast==false)
{
count++;
blast=true;
}
bugship2y=-1000;
if(count==3){
gameover=true;
//start=true;;
option=false;
count=0;
shipy=1500;
}
}
if(((bugship1x+64>=shipx)&&(bugship1x<=shipx+64))&&((bugship1y<=shipy+82)&&(bugship1y+67>=shipy)))
{
if(blast==false)
{
blast=true;
count++;
}
bugship1y=-1000;
if(count==3)
{
gameover=true;
//start=true;;
option=false;
count=0;
shipy=1500;
}
}
//for my fire
if(firey>500)
rand_fire();
else
{
iShowBMP(firex+45,firey+=25,"ships\\fire.bmp");
iShowBMP(firex+10,firey,"ships\\fire.bmp");
}
//distroy enemy ship & score++
if(((firex+64>=bugship2x)&&(firex<=bugship2x+64))&&((firey<=bugship2y+67)&&(firey+35>=bugship2y)))
{
if(blast_bug_ship2==false)
{
blast_bug_ship2=true;
score+=2;
}
firey=600;
}
if(((firex+64>=bugship1x)&&(firex<=bugship1x+64))&&((firey<=bugship1y+67)&&(firey+35>=bugship1y)))
{
if(blast_bug_ship1==false)
{
blast_bug_ship1=true;
score+=5;
}
firey=600;
}
//boss 1 show
if(score>=1450&&score<1500)
{
eboss1y=350;
if(blast_enemy_boss1==false)
{
if(eboss1x>544||eboss1x<0)
{
//iShowBMP(ebossx++,ebossy,"ships//enemy_boss1");
sx=-sx;
}
iShowBMP(eboss1x+=sx,eboss1y,"ships//enemy_boss8.bmp");
//boss1 fire
if(boss_firey<0)
{
rand_bossfire();
}
else
{
iShowBMP(boss_firex+84,boss_firey-=10,"ships\\boss_fire.bmp");
iShowBMP(boss_firex+172,boss_firey,"ships\\boss_fire.bmp");
}
//boss fire destroy my ship
int x=boss_firex+84,x2=boss_firex+172;
if(((x-10>=shipx)&&(x<=shipx+54))&&((boss_firey<=shipy+82)&&(boss_firey+18>=shipy))||((x2-10>=shipx)&&(x2<=shipx+54))&&((boss_firey<=shipy+82)&&(boss_firey+18>=shipy)))
{
if(blast==false)
{
blast=true;
count++;
}
boss_firey=-1500;
if(count==3)
{
gameover=true;
//start=true;;
option=false;
count=0;
shipy=1500;
}
}
}
else
{
iShowBMP(eboss1x,eboss1y,"ships\\blast_enemy_boss8.bmp");//blast boss ship1
enemy_boss1_respawncounter++;
if(enemy_boss1_respawncounter>30)//respawn bug ship2
{
blast_enemy_boss1=false;
enemy_boss1_respawncounter=0;
eboss1y=-1000;
}
}
//my fire distroy boss ship
if(((firex+64>=eboss1x)&&(firex<=eboss1x+256))&&((firey<=eboss1y+67)&&(firey+23>=eboss1y)))
{
boss_hit++;
if(blast_enemy_boss1==false && boss_hit==40)
{
blast_enemy_boss1=true;
score+=100;
boss_hit=0;
}
firey=600;
}
}
//
}
//**********level 9************
if(level9==true){
eboss1y=350;
if(blast==false){
iShowBMP(shipx,shipy,"ships\\spaceship1.bmp");
}
else
{
iShowBMP(shipx,shipy,"ships\\blast.bmp");//blast my ship
respawn_counter++;
if(respawn_counter>100)//respawn my ship
{
blast=false;
respawn_counter=0;
}
}
//bug ship 1
if(blast_bug_ship1==false){
if(bugship1y<-80)
rand_bugship1();
else
{
if(bugship1x > 800 || bugship1x < 0)
{
bugship1x=-bugship1x;
}
else
{
if(bugship1y<450)
iShowBMP(bugship1x+=1,bugship1y-=6,"ships\\bug_ship7.bmp");
else
iShowBMP(bugship1x-=1,bugship1y-=6,"ships\\bug_ship7.bmp");
}
}
}
else{
iShowBMP(bugship1x,bugship1y,"ships\\blast_bug_ship7.bmp");//blast bug ship1
bug_ship1_respawncounter++;
if(bug_ship1_respawncounter>30)//respawn bug ship1
{
blast_bug_ship1=false;
bug_ship1_respawncounter=0;
bugship1y=-950;
}
}
//bugship2
if(blast_bug_ship2==false){
if(bugship2y<-100)
rand_bugship2();
else
{
iShowBMP(bugship2x,bugship2y-=6,"ships\\bug_ship8.bmp");
}
}
else{
iShowBMP(bugship2x,bugship2y,"ships\\blast_bug_ship8.bmp");//blast bug ship2
bug_ship2_respawncounter++;
if(bug_ship2_respawncounter>30)//respawn bug ship2
{
blast_bug_ship2=false;
bug_ship2_respawncounter=0;
bugship2y=-1000;
}
}
///if crash life lost
if(((bugship2x+64>=shipx)&&(bugship2x<=shipx+64))&&((bugship2y<=shipy+82)&&(bugship2y+67>=shipy)))
{
if(blast==false)
{
count++;
blast=true;
}
bugship2y=-1000;
if(count==3){
gameover=true;
//start=true;;
option=false;
count=0;
shipy=1500;
}
}
if(((bugship1x+64>=shipx)&&(bugship1x<=shipx+64))&&((bugship1y<=shipy+82)&&(bugship1y+67>=shipy)))
{
if(blast==false)
{
blast=true;
count++;
}
bugship1y=-1000;
if(count==3)
{
gameover=true;
//start=true;;
option=false;
count=0;
shipy=1500;
}
}
//for my fire
if(firey>500)
rand_fire();
else
{
iShowBMP(firex+45,firey+=25,"ships\\fire.bmp");
iShowBMP(firex+10,firey,"ships\\fire.bmp");
}
//distroy enemy ship & score++
if(((firex+64>=bugship2x)&&(firex<=bugship2x+64))&&((firey<=bugship2y+67)&&(firey+35>=bugship2y)))
{
if(blast_bug_ship2==false)
{
blast_bug_ship2=true;
score+=2;
}
firey=600;
}
if(((firex+64>=bugship1x)&&(firex<=bugship1x+64))&&((firey<=bugship1y+67)&&(firey+35>=bugship1y)))
{
if(blast_bug_ship1==false)
{
blast_bug_ship1=true;
score+=5;
}
firey=600;
}
//boss 1 show
if(score>=1650&&score<1700)
{
eboss1y=350;
if(blast_enemy_boss1==false)
{
if(eboss1x>544||eboss1x<0)
{
//iShowBMP(ebossx++,ebossy,"ships//enemy_boss1");
sx=-sx;
}
iShowBMP(eboss1x+=sx,eboss1y,"ships//enemy_boss9.bmp");
//boss1 fire
if(boss_firey<0)
{
rand_bossfire();
}
else
{
iShowBMP(boss_firex+84,boss_firey-=10,"ships\\boss_fire.bmp");
iShowBMP(boss_firex+172,boss_firey,"ships\\boss_fire.bmp");
}
//boss fire destroy my ship
int x=boss_firex+84,x2=boss_firex+172;
if(((x-10>=shipx)&&(x<=shipx+54))&&((boss_firey<=shipy+82)&&(boss_firey+18>=shipy))||((x2-10>=shipx)&&(x2<=shipx+54))&&((boss_firey<=shipy+82)&&(boss_firey+18>=shipy)))
{
if(blast==false)
{
blast=true;
count++;
}
boss_firey=-1500;
if(count==3)
{
gameover=true;
//start=true;;
option=false;
count=0;
shipy=1500;
}
}
}
else
{
iShowBMP(eboss1x,eboss1y,"ships\\blast_enemy_boss9.bmp");//blast boss ship1
enemy_boss1_respawncounter++;
if(enemy_boss1_respawncounter>30)//respawn bug ship2
{
blast_enemy_boss1=false;
enemy_boss1_respawncounter=0;
eboss1y=-1000;
}
}
//my fire distroy boss ship
if(((firex+64>=eboss1x)&&(firex<=eboss1x+256))&&((firey<=eboss1y+67)&&(firey+23>=eboss1y)))
{
boss_hit++;
if(blast_enemy_boss1==false && boss_hit==40)
{
blast_enemy_boss1=true;
score+=100;
boss_hit=0;
}
firey=600;
}
}
//
}
//**********level 10***********
if(level10==true){
eboss1y=350;
if(blast==false){
iShowBMP(shipx,shipy,"ships\\spaceship1.bmp");
}
else
{
iShowBMP(shipx,shipy,"ships\\blast.bmp");//blast my ship
respawn_counter++;
if(respawn_counter>100)//respawn my ship
{
blast=false;
respawn_counter=0;
}
}
//bug ship 1
if(blast_bug_ship1==false){
if(bugship1y<-80)
rand_bugship1();
else
{
if(bugship1x > 800 || bugship1x < 0)
{
bugship1x=-bugship1x;
}
else
{
if(bugship1y<450)
iShowBMP(bugship1x+=1,bugship1y-=6,"ships\\bug_ship9.bmp");
else
iShowBMP(bugship1x-=1,bugship1y-=6,"ships\\bug_ship9.bmp");
}
}
}
else{
iShowBMP(bugship1x,bugship1y,"ships\\blast_bug_ship9.bmp");//blast bug ship1
bug_ship1_respawncounter++;
if(bug_ship1_respawncounter>30)//respawn bug ship1
{
blast_bug_ship1=false;
bug_ship1_respawncounter=0;
bugship1y=-950;
}
}
//bugship2
if(blast_bug_ship2==false){
if(bugship2y<-100)
rand_bugship2();
else
{
iShowBMP(bugship2x,bugship2y-=6,"ships\\bug_ship10.bmp");
}
}
else{
iShowBMP(bugship2x,bugship2y,"ships\\blast_bug_ship10.bmp");//blast bug ship2
bug_ship2_respawncounter++;
if(bug_ship2_respawncounter>30)//respawn bug ship2
{
blast_bug_ship2=false;
bug_ship2_respawncounter=0;
bugship2y=-1000;
}
}
///if crash life lost
if(((bugship2x+64>=shipx)&&(bugship2x<=shipx+64))&&((bugship2y<=shipy+82)&&(bugship2y+67>=shipy)))
{
if(blast==false)
{
count++;
blast=true;
}
bugship2y=-1000;
if(count==3){
gameover=true;
//start=true;;
option=false;
count=0;
shipy=1500;
}
}
if(((bugship1x+64>=shipx)&&(bugship1x<=shipx+64))&&((bugship1y<=shipy+82)&&(bugship1y+67>=shipy)))
{
if(blast==false)
{
blast=true;
count++;
}
bugship1y=-1000;
if(count==3)
{
gameover=true;
//start=true;;
option=false;
count=0;
shipy=1500;
}
}
//for my fire
if(firey>500)
rand_fire();
else
{
iShowBMP(firex+45,firey+=25,"ships\\fire.bmp");
iShowBMP(firex+10,firey,"ships\\fire.bmp");
}
//distroy enemy ship & score++
if(((firex+64>=bugship2x)&&(firex<=bugship2x+64))&&((firey<=bugship2y+67)&&(firey+35>=bugship2y)))
{
if(blast_bug_ship2==false)
{
blast_bug_ship2=true;
score+=2;
}
firey=600;
}
if(((firex+64>=bugship1x)&&(firex<=bugship1x+64))&&((firey<=bugship1y+67)&&(firey+35>=bugship1y)))
{
if(blast_bug_ship1==false)
{
blast_bug_ship1=true;
score+=5;
}
firey=600;
}
//boss 1 show
if(score>=1850&&score<1900)
{
eboss1y=350;
if(blast_enemy_boss1==false)
{
if(eboss1x>544||eboss1x<0)
{
//iShowBMP(ebossx++,ebossy,"ships//enemy_boss1");
sx=-sx;
}
iShowBMP(eboss1x+=sx,eboss1y,"ships//enemy_boss10.bmp");
//boss1 fire
if(boss_firey<0)
{
rand_bossfire();
}
else
{
iShowBMP(boss_firex+84,boss_firey-=10,"ships\\boss_fire.bmp");
iShowBMP(boss_firex+172,boss_firey,"ships\\boss_fire.bmp");
}
//boss fire destroy my ship
int x=boss_firex+84,x2=boss_firex+172;
if(((x-10>=shipx)&&(x<=shipx+54))&&((boss_firey<=shipy+82)&&(boss_firey+18>=shipy))||((x2-10>=shipx)&&(x2<=shipx+54))&&((boss_firey<=shipy+82)&&(boss_firey+18>=shipy)))
{
if(blast==false)
{
blast=true;
count++;
}
boss_firey=-1500;
if(count==3)
{
gameover=true;
//start=true;;
option=false;
count=0;
shipy=1500;
}
}
}
else
{
iShowBMP(eboss1x,eboss1y,"ships\\blast_enemy_boss10.bmp");//blast boss ship1
enemy_boss1_respawncounter++;
if(enemy_boss1_respawncounter>30)//respawn bug ship2
{
blast_enemy_boss1=false;
enemy_boss1_respawncounter=0;
eboss1y=-1000;
}
}
//my fire distroy boss ship
if(((firex+64>=eboss1x)&&(firex<=eboss1x+256))&&((firey<=eboss1y+67)&&(firey+23>=eboss1y)))
{
boss_hit++;
if(blast_enemy_boss1==false && boss_hit==40)
{
blast_enemy_boss1=true;
score+=100;
boss_hit=0;
}
firey=600;
}
}
//
}
}
system("CLS");
printf("bugship1x= %d\n",bugship1x);
printf("respawn counter = %d / 100\n",respawn_counter);
printf("life count= %d\n",count);
printf("bugship1y = %d\n",bugship1y);
printf("bugship2y = %d\n",bugship2y);
printf("score = %d\n",score);
printf("boss hit = %d\n",boss_hit);
printf("respawn counter = %d / 100\n",enemy_boss1_respawncounter);
}
void iMouseMove(int mx, int my)
{
//place your codes here
}
void iMouse(int button, int state, int mx, int my)
{
if(button == GLUT_LEFT_BUTTON && state == GLUT_DOWN )
{
if(start==true && option==false && about==false){
if(mx>652 && mx<710 && my>285 && my<311){
exit(0);//quit
}
if(mx>645 && 723>mx && my<352 && my>322)
{
option= true;//for instruction
PlaySound("music\\option_sound",NULL, SND_LOOP | SND_ASYNC);
}
if(mx>626 && 736>mx && my<470 && my>445){
start=false;//start game
PlaySound("music\\game_sound", NULL, SND_LOOP | SND_ASYNC);
}
if(mx>0 && 52>mx && my<30 && my>0)
{
about= true;//about
PlaySound("music\\option_sound",NULL, SND_LOOP | SND_ASYNC );
}
}
if(option == true && about==false && start==true)
{
if(mx>725 && 790>mx && my<33 && my>11){
option = false;
PlaySound("music\\home_sound", NULL, SND_LOOP | SND_ASYNC);
}
}
if(about==true){
if(mx>730 && 795>mx && my<497 && my>470){
start=true;
about=false;
PlaySound("music\\home_sound", NULL, SND_LOOP | SND_ASYNC);
}
}
if(start==false && about==false && option==false){
if(mx>7 && 56>mx && my <491 && my>474){
start=true;
PlaySound("music\\home_sound", NULL, SND_LOOP | SND_ASYNC);
}
}
system("CLS");
printf("\n\n\n\n\nMouse X=%d\nMouse Y= %d",mx,my);
}
}
void rand_bugship1()
{
//if(bugship1y<-150)
int i;
i=rand()%736+20;
if(i%6==0)
{
bugship1x=i;
bugship1y=650;
}
}
void rand_bugship2()
{
//if(bugship1y<-150)
int i;
i=rand()%736+20;
if(i%9==0)
{
bugship2x=i;
bugship2y=750;
}
}
void rand_fire(){
firex=shipx;
firey=shipy;
}
void rand_bossfire(){
boss_firex=eboss1x;
boss_firey=eboss1y;
}
void iKeyboard(unsigned char key)
{
if(key == 'p')
{
//do something with 'q'
iPauseTimer(0);
}
if(key == 'r')
{
iResumeTimer(0);
}
}
void iSpecialKeyboard(unsigned char key)
{
if(key == GLUT_KEY_END)
{
exit(0);
}
if(key == GLUT_KEY_RIGHT && shipx<=800-64)
{
shipx+=20;
}
if(key == GLUT_KEY_LEFT && shipx>=1)
{
shipx-=20;
}
if(key == GLUT_KEY_UP && shipy<=500-90)
{
shipy+=10;
}
if(key == GLUT_KEY_DOWN && shipy>=1)
{
shipy-=10;
}
}
int main()
{
if(start == true)
{
srand(time(NULL));
PlaySound("music\\home_sound", NULL, SND_LOOP | SND_ASYNC);
}
iInitialize(800, 500);
return 0;
} | [
"31000643+Fzrabbi@users.noreply.github.com"
] | 31000643+Fzrabbi@users.noreply.github.com |
56b5ee1d7c79f64cad2e6e9d794fe36725f9e75e | 1b8db6b3991c7f49ac180dca30c0f1e42069ab72 | /common/NetworkMessageParser.h | 67b02a08fb19cfc1730d12b32f74a3955fff43d7 | [] | no_license | jsandersr/Hydra | cf27de6c5fad35c1b49faa2b51320dcde453a15a | 0fd5f7b2e24a3ca75f3c135d996510d896330390 | refs/heads/master | 2020-06-29T04:47:27.474351 | 2020-01-01T11:35:39 | 2020-01-01T11:39:05 | 200,444,574 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,536 | h | //---------------------------------------------------------------
//
// Parser.cpp
//
#pragma once
#include <memory>
#include <vector>
#include <string>
namespace Common {
//===============================================================================
struct MessageHeader;
struct NetworkMessage;
class NetworkMessageParser
{
public:
NetworkMessageParser();
~NetworkMessageParser();
// Will attempt to extract NetworkMessages out of a stream.
void ExtractMessages(const std::string& stream, std::vector<NetworkMessage>& messages);
private:
void Parse(const std::string& stream);
void SwapBuffer();
void TransitionState();
void WriteToBuffer(const std::string& data, int size);
std::string* Buffer() { return m_activeBuffer; }
private:
enum class State : uint32_t
{
Header,
Content,
Finalizing
};
// Local cache of the header we're looking for.
std::unique_ptr<NetworkMessage> m_messageCache = std::make_unique<NetworkMessage>();
// To ensure smooth writes, buffers are swapped after successful header or content reads.
std::string m_firstBuffer;
std::string m_secondBuffer;
// Points to whichever buffer is being written to.
std::string* m_activeBuffer;
// We're either parsing a header, or content.
State m_state = State::Header;
// Resets on state change.
uint32_t m_bytesParsedThisState = 0;
// Keep track of where we are in the stream overall.
uint32_t m_totalBytesParsed = 0;
};
//===============================================================================
} // namespace Tests
| [
"joshua.sandersr@gmail.com"
] | joshua.sandersr@gmail.com |
d15887d1919604162b8b9c4b7df627706d68d7af | d1ad68da0d7d3a71c2d43d297d6fd3cffbbf75c2 | /yukicoder/430/AhoCrasick.cpp | f452b37c607638e5372f475f20d7d9d5813ab3ec | [] | no_license | hamko/procon | 2a0a685b88a69951be7a9217dd32955f9500df57 | a822f8089a3063a158d47ea48c54aca89934f855 | refs/heads/master | 2021-01-17T00:00:10.915298 | 2020-02-24T06:24:33 | 2020-02-24T06:24:33 | 55,990,248 | 7 | 1 | null | 2020-02-24T06:24:34 | 2016-04-11T16:49:50 | C++ | UTF-8 | C++ | false | false | 10,267 | cpp | #include <bits/stdc++.h>
#include <sys/time.h>
using namespace std;
#define rep(i,n) for(long long i = 0; i < (long long)(n); i++)
#define repi(i,a,b) for(long long i = (long long)(a); i < (long long)(b); i++)
#define pb push_back
#define all(x) (x).begin(), (x).end()
#define fi first
#define se second
#define mt make_tuple
#define mp make_pair
template<class T1, class T2> bool chmin(T1 &a, T2 b) { return b < a && (a = b, true); }
template<class T1, class T2> bool chmax(T1 &a, T2 b) { return a < b && (a = b, true); }
#define exists find_if
#define forall all_of
using ll = long long; using vll = vector<ll>; using vvll = vector<vll>; using P = pair<ll, ll>;
using ld = long double; using vld = vector<ld>;
using vi = vector<int>; using vvi = vector<vi>; vll conv(vi& v) { vll r(v.size()); rep(i, v.size()) r[i] = v[i]; return r; }
using Pos = complex<double>;
template <typename T, typename U> ostream &operator<<(ostream &o, const pair<T, U> &v) { o << "(" << v.first << ", " << v.second << ")"; return o; }
template<size_t...> struct seq{}; template<size_t N, size_t... Is> struct gen_seq : gen_seq<N-1, N-1, Is...>{}; template<size_t... Is> struct gen_seq<0, Is...> : seq<Is...>{};
template<class Ch, class Tr, class Tuple, size_t... Is>
void print_tuple(basic_ostream<Ch,Tr>& os, Tuple const& t, seq<Is...>){ using s = int[]; (void)s{0, (void(os << (Is == 0? "" : ", ") << get<Is>(t)), 0)...}; }
template<class Ch, class Tr, class... Args>
auto operator<<(basic_ostream<Ch, Tr>& os, tuple<Args...> const& t) -> basic_ostream<Ch, Tr>& { os << "("; print_tuple(os, t, gen_seq<sizeof...(Args)>()); return os << ")"; }
ostream &operator<<(ostream &o, const vvll &v) { rep(i, v.size()) { rep(j, v[i].size()) o << v[i][j] << " "; o << endl; } return o; }
template <typename T> ostream &operator<<(ostream &o, const vector<T> &v) { o << '['; rep(i, v.size()) o << v[i] << (i != v.size()-1 ? ", " : ""); o << "]"; return o; }
template <typename T> ostream &operator<<(ostream &o, const set<T> &m) { o << '['; for (auto it = m.begin(); it != m.end(); it++) o << *it << (next(it) != m.end() ? ", " : ""); o << "]"; return o; }
template <typename T> ostream &operator<<(ostream &o, const unordered_set<T> &m) { o << '['; for (auto it = m.begin(); it != m.end(); it++) o << *it << (next(it) != m.end() ? ", " : ""); o << "]"; return o; }
template <typename T, typename U> ostream &operator<<(ostream &o, const map<T, U> &m) { o << '['; for (auto it = m.begin(); it != m.end(); it++) o << *it << (next(it) != m.end() ? ", " : ""); o << "]"; return o; }
template <typename T, typename U, typename V> ostream &operator<<(ostream &o, const unordered_map<T, U, V> &m) { o << '['; for (auto it = m.begin(); it != m.end(); it++) o << *it; o << "]"; return o; }
vector<int> range(const int x, const int y) { vector<int> v(y - x + 1); iota(v.begin(), v.end(), x); return v; }
template <typename T> istream& operator>>(istream& i, vector<T>& o) { rep(j, o.size()) i >> o[j]; return i;}
string bits_to_string(ll input, ll n=64) { string s; rep(i, n) s += '0' + !!(input & (1ll << i)); reverse(all(s)); return s; }
template <typename T> unordered_map<T, ll> counter(vector<T> vec){unordered_map<T, ll> ret; for (auto&& x : vec) ret[x]++; return ret;};
string substr(string s, P x) {return s.substr(x.fi, x.se - x.fi); }
struct ci : public iterator<forward_iterator_tag, ll> { ll n; ci(const ll n) : n(n) { } bool operator==(const ci& x) { return n == x.n; } bool operator!=(const ci& x) { return !(*this == x); } ci &operator++() { n++; return *this; } ll operator*() const { return n; } };
size_t random_seed; namespace std { using argument_type = P; template<> struct hash<argument_type> { size_t operator()(argument_type const& x) const { size_t seed = random_seed; seed ^= hash<ll>{}(x.fi); seed ^= (hash<ll>{}(x.se) << 1); return seed; } }; }; // hash for various class
namespace myhash{ const int Bsizes[]={3,9,13,17,21,25,29,33,37,41,45,49,53,57,61,65,69,73,77,81}; const int xor_nums[]={0x100007d1,0x5ff049c9,0x14560859,0x07087fef,0x3e277d49,0x4dba1f17,0x709c5988,0x05904258,0x1aa71872,0x238819b3,0x7b002bb7,0x1cf91302,0x0012290a,0x1083576b,0x76473e49,0x3d86295b,0x20536814,0x08634f4d,0x115405e8,0x0e6359f2}; const int hash_key=xor_nums[rand()%20]; const int mod_key=xor_nums[rand()%20]; template <typename T> struct myhash{ std::size_t operator()(const T& val) const { return (hash<T>{}(val)%mod_key)^hash_key; } }; };
template <typename T> class uset:public std::unordered_set<T,myhash::myhash<T>> { using SET=std::unordered_set<T,myhash::myhash<T>>; public: uset():SET(){SET::rehash(myhash::Bsizes[rand()%20]);} };
template <typename T,typename U> class umap:public std::unordered_map<T,U,myhash::myhash<T>> { public: using MAP=std::unordered_map<T,U,myhash::myhash<T>>; umap():MAP(){MAP::rehash(myhash::Bsizes[rand()%20]);} };
struct timeval start; double sec() { struct timeval tv; gettimeofday(&tv, NULL); return (tv.tv_sec - start.tv_sec) + (tv.tv_usec - start.tv_usec) * 1e-6; }
struct init_{init_(){ gettimeofday(&start, NULL); ios::sync_with_stdio(false); cin.tie(0); srand((unsigned int)time(NULL)); random_seed = RAND_MAX / 2 + rand() / 2; }} init__;
static const double EPS = 1e-14;
static const long long INF = 1e18;
static const long long mo = 1e9+7;
#define ldout fixed << setprecision(40)
// 簡単な挙動
//
// (a)
// p = transite(p, c)
// cが成功なら p = p->next[c]
// cが失敗なら p = p->p[fail]->next[c]
//
// (b)
// 各pで、マッチングしている辞書番号集合が保持されている。
//
// (c)
// 複数マッチング。"aaaa"には"aa"が3回マッチングする。
// もしcoveringマッチングにしたいなら、マッチングするノードの失敗辺を全てrootに張り替えれば良い
const int fail = 0;
// パターンマッチングの頂点
// 256個の子を持つ多分木
struct pma {
// trie木では、非0ならば遷移可能
//
// Aho-Crasickでは、
// next[0]が、failure辺として特別扱いとなる。fail = 0である。
// (1) thisがrootなら、next[fail]はNULLとなる。
// (2) thisがrootでないなら、next[fail]は失敗辺の行き先となる。
//
// next[i]は、rootの時のみ特別扱いとなる。
// (3) thisがrootなら、next[i]がない時は自己ループになる。
pma* next[256] = {};
unordered_set<ll> matched; // 正にこの頂点を表す文字列パターンの集合(昇順)
pma() {}
~pma() { rep(i, 256) if (next[i]) delete next[i]; }
};
unordered_map<pma*, ll> name; // ネームサーバ
// rootに文字列sをパターンsiとして登録する。
void add(pma* root, string& s, ll si) {
pma* now = root;
for (int c : s) {
if (!now->next[c]) {
now->next[c] = new pma;
ll name_size = name.size(); name[now->next[c]] = name_size; // for name server
}
now = now->next[c];
}
now->matched.insert(si);
}
// パターン集合pによってtrie木を構築する。
pma* buildTrie(vector<string> p) {
name.clear();
pma* root = new pma;
name[root] = 0; // for name server
ll pn = p.size();
rep(si, pn)
add(root, p[si], si);
return root;
}
// 今のTrie木に対して、AhoCrasickによって失敗辺を構築する。
//
// 頂点iのマッチング失敗辺failure(i)を既知とする。
//
// この時、頂点iの次の頂点j=goto(i, c)での失敗辺は、
// cで遷移可能になるまで戻る関数failure(i)に対して、goto(failure(i), c)である。
void buildAhoCrasick(pma* root) {
queue<pma*> q;
// rootの失敗辺と、rootに直接つながっている成功辺の失敗辺の初期化
repi(i, 1, 256)
if (root->next[i])
root->next[i]->next[fail] = root, q.push(root->next[i]); // rootの直後で失敗したらrootに戻る
else
root->next[i] = root; // (3)
while (q.size()) {
auto now = q.front(); q.pop();
// 以下が(2)
repi(i, 1, 256) if (now->next[i]) {
// iでの遷移が成功するところまで、失敗辺をたどってから進んだところが、新たな失敗辺
auto now_f = now->next[fail];
while (!now_f->next[i]) now_f = now_f->next[fail];
now->next[i]->next[fail] = now_f->next[i];
for (auto x : now_f->next[i]->matched) // 失敗辺の先のマッチングを継承する。パターンが互いに含まないなら不要
now->next[i]->matched.insert(x);
q.push(now->next[i]);
}
}
}
// Aho-Corasickをcoveringマッチングにする
// 破壊的
//
// 内部でやってることは、マッチングするノードの失敗辺を全てrootに張り替えている
void changeToCoveringMode(pma* root) {
unordered_set<pma*> memo;
function<void(pma*)> f = [&](pma* p) {
if (memo.count(p)) return;
memo.insert(p);
if (p->matched.size())
p->next[0] = root;
rep(i, 256) if (p->next[i]) {
f(p->next[i]);
}
};
f(root);
}
// 頂点pから遷移cによって、次の頂点へと遷移する。
// 1回の遷移によるマッチング増加は、transite(p, c)->matchingによって計算できる。
pma* transite(pma* p, int c) {
while (!p->next[c]) p = p->next[fail];
p = p->next[c];
return p;
}
// AhoCrasick pを構築したパターンが、sに何個入っているかをresに副作用で返す。
// 注意!!これはデフォルトで複数マッチング。coveringマッチングにしたいなら、changeToCoveringMode(root)を読ぶこと。
void match(pma* &p, string s, vll& res) {
rep(i, s.length()) {
p = transite(p, s[i]);
for (auto x : p->matched)
res[x]++;
}
}
int main(void) {
string s; cin >> s;
ll n; cin >> n;
vector<string> dict;
rep(i, n) {
string tmp; cin >> tmp;
dict.pb(tmp);
}
auto root = buildTrie(dict);
buildAhoCrasick(root);
vll res(dict.size());
match(root, s, res); // 重複マッチングで何個ある?
cout << accumulate(all(res), 0ll) << endl;
return 0;
}
| [
"wakataberyo@gmail.com"
] | wakataberyo@gmail.com |
575c4010bd4da1324ebdb2aeb91703b2b8a48b43 | f8573941754a429f481c18b46ad5337d1bb55609 | /PhysX 3.3.1/Source/foundation/include/PsFoundation.h | 1b92105453bc32144d0835f72e760fa9c5f5b2ac | [] | no_license | frbyles/ExcavatorSimulator | 409fa4ad56ba3d786dedfffb5d981db86d89f4f5 | c4be4ea60cd1c62c0d0207af31dfed4a47ef6124 | refs/heads/master | 2021-01-19T11:38:04.166440 | 2015-11-12T17:45:52 | 2015-11-12T17:45:52 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,805 | h | // This code contains NVIDIA Confidential Information and is disclosed to you
// under a form of NVIDIA software license agreement provided separately to you.
//
// Notice
// NVIDIA Corporation and its licensors retain all intellectual property and
// proprietary rights in and to this software and related documentation and
// any modifications thereto. Any use, reproduction, disclosure, or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA Corporation is strictly prohibited.
//
// ALL NVIDIA DESIGN SPECIFICATIONS, CODE ARE PROVIDED "AS IS.". NVIDIA MAKES
// NO WARRANTIES, EXPRESSED, IMPLIED, STATUTORY, OR OTHERWISE WITH RESPECT TO
// THE MATERIALS, AND EXPRESSLY DISCLAIMS ALL IMPLIED WARRANTIES OF NONINFRINGEMENT,
// MERCHANTABILITY, AND FITNESS FOR A PARTICULAR PURPOSE.
//
// Information and code furnished is believed to be accurate and reliable.
// However, NVIDIA Corporation assumes no responsibility for the consequences of use of such
// information or for any infringement of patents or other rights of third parties that may
// result from its use. No license is granted by implication or otherwise under any patent
// or patent rights of NVIDIA Corporation. Details are subject to change without notice.
// This code supersedes and replaces all information previously supplied.
// NVIDIA Corporation products are not authorized for use as critical
// components in life support devices or systems without express written approval of
// NVIDIA Corporation.
//
// Copyright (c) 2008-2013 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef PX_FOUNDATION_PSFOUNDATION_H
#define PX_FOUNDATION_PSFOUNDATION_H
#include "Ps.h"
#include "PsInlineArray.h"
#include "foundation/PxFoundation.h"
#include "foundation/PxErrors.h"
#include "PsMutex.h"
#include "foundation/PxBroadcastingAllocator.h"
#include "PsPAEventSrc.h"
#include <stdarg.h>
#include "PsHashMap.h"
#include "PsErrorHandler.h"
namespace physx
{
namespace shdfnd
{
union TempAllocatorChunk;
class PxAllocatorListenerManager;
class PX_FOUNDATION_API Foundation : public PxFoundation
{
PX_NOCOPY(Foundation)
public:
#ifdef PX_CHECKED
typedef MutexT<Allocator> Mutex;
#else
typedef MutexT<> Mutex;
#endif
private:
typedef HashMap<const NamedAllocator*, const char*,
Hash<const NamedAllocator*>, NonTrackingAllocator> AllocNameMap;
typedef Array<TempAllocatorChunk*, Allocator> AllocFreeTable;
Foundation(PxErrorCallback& errc, PxAllocatorCallback& alloc);
~Foundation();
public:
void release();
// factory
static Foundation* createInstance(PxU32 version, PxErrorCallback& errc, PxAllocatorCallback& alloc);
// note, you MUST call destroyInstance iff createInstance returned true!
static void destroyInstance();
static Foundation& getInstance();
static void incRefCount(); // this call requires a foundation object to exist already
static void decRefCount(); // this call requires a foundation object to exist already
virtual PxErrorCallback& getErrorCallback() const;
virtual void setErrorLevel(PxErrorCode::Enum mask);
virtual PxErrorCode::Enum getErrorLevel() const;
virtual PxBroadcastingAllocator& getAllocator() const { return mAllocator; }
virtual PxAllocatorCallback& getAllocatorCallback() const;
PxAllocatorCallback& getCheckedAllocator() { return mAllocator; }
virtual bool getReportAllocationNames() const { return mReportAllocationNames; }
virtual void setReportAllocationNames(bool value) { mReportAllocationNames = value; }
//! error reporting function
void error(PxErrorCode::Enum, const char* file, int line, const char* messageFmt, ...);
void errorImpl(PxErrorCode::Enum, const char* file, int line, const char* messageFmt, va_list );
PxI32 getWarnOnceTimestamp();
PX_INLINE Mutex& getErrorMutex() { return mErrorMutex; }
PX_INLINE AllocNameMap& getNamedAllocMap() { return mNamedAllocMap; }
PX_INLINE Mutex& getNamedAllocMutex() { return mNamedAllocMutex; }
PX_INLINE AllocFreeTable& getTempAllocFreeTable() { return mTempAllocFreeTable; }
PX_INLINE Mutex& getTempAllocMutex() { return mTempAllocMutex; }
PX_INLINE PAUtils& getPAUtils() { return mPAUtils; }
PX_INLINE ErrorHandler& getErrorHandler() { return mInteralErrorHandler; }
private:
class AlignCheckAllocator: public PxBroadcastingAllocator
{
static const PxU32 MAX_LISTENER_COUNT = 5;
public:
AlignCheckAllocator(PxAllocatorCallback& originalAllocator)
: mAllocator(originalAllocator)
, mListenerCount( 0 ){}
void deallocate(void* ptr)
{
//So here, for performance reasons I don't grab the mutex.
//The listener array is very rarely changing; for most situations
//only at startup. So it is unlikely that using the mutex
//will help a lot but it could have serious perf implications.
PxU32 theCount = mListenerCount;
for( PxU32 idx = 0; idx < theCount; ++idx )
mListeners[idx]->onDeallocation( ptr );
mAllocator.deallocate(ptr);
}
void* allocate(size_t size, const char* typeName, const char* filename, int line);
PxAllocatorCallback& getBaseAllocator() const { return mAllocator; }
void registerAllocationListener( PxAllocationListener& inListener )
{
PX_ASSERT( mListenerCount < MAX_LISTENER_COUNT );
if ( mListenerCount < MAX_LISTENER_COUNT )
{
mListeners[mListenerCount] = &inListener;
++mListenerCount;
}
}
void deregisterAllocationListener( PxAllocationListener& inListener )
{
for( PxU32 idx = 0; idx < mListenerCount; ++idx )
{
if ( mListeners[idx] == &inListener )
{
mListeners[idx] = mListeners[mListenerCount-1];
--mListenerCount;
break;
}
}
}
protected:
AlignCheckAllocator& operator=(const AlignCheckAllocator&);
private:
PxAllocatorCallback& mAllocator;
//I am not sure about using a PxArray here.
//For now, this is fine.
PxAllocationListener* mListeners[MAX_LISTENER_COUNT];
volatile PxU32 mListenerCount;
};
// init order is tricky here: the mutexes require the allocator, the allocator may require the error stream
PxErrorCallback& mErrorCallback;
mutable AlignCheckAllocator mAllocator;
bool mReportAllocationNames;
PxErrorCode::Enum mErrorMask;
Mutex mErrorMutex;
AllocNameMap mNamedAllocMap;
Mutex mNamedAllocMutex;
AllocFreeTable mTempAllocFreeTable;
Mutex mTempAllocMutex;
PAUtils mPAUtils;
ErrorHandler mInteralErrorHandler;
static Foundation* mInstance;
static PxU32 mRefCount;
};
PX_INLINE Foundation& getFoundation()
{
return Foundation::getInstance();
}
} // namespace shdfnd
} // namespace physx
//shortcut macros:
//usage: Foundation::error(PX_WARN, "static friction %f is is lower than dynamic friction %d", sfr, dfr);
#define PX_WARN ::physx::PxErrorCode::eDEBUG_WARNING, __FILE__, __LINE__
#define PX_INFO ::physx::PxErrorCode::eDEBUG_INFO, __FILE__, __LINE__
#if defined(PX_DEBUG) || defined(PX_CHECKED)
#ifdef __SPU__ // SCS: used in CCD from SPU. how can we fix that correctly?
#define PX_WARN_ONCE(condition, string) ((void)0)
#else
#define PX_WARN_ONCE(condition, string) \
if (condition) { \
static PxI32 timestap = 0; \
if (timestap != Ps::getFoundation().getWarnOnceTimestamp()) { \
timestap = Ps::getFoundation().getWarnOnceTimestamp(); \
Ps::getFoundation().error(PX_WARN, string); \
} \
}
#endif
#else
#define PX_WARN_ONCE(condition, string) ((void)0)
#endif
#endif
| [
"seifes1@gmail.com"
] | seifes1@gmail.com |
eb391b455196a087f01e6cdf0a28a94241988aab | 70f8491a27470287090d3c2be061d5fce23f07a9 | /algorithms/p397/397.hpp | 5464a0998ca1bb21d9942a15724a940f824e2900 | [
"Apache-2.0"
] | permissive | baishuai/leetcode | 44094a91e95c0557394cf15324008f79fc2d6688 | 440ff08cf15e03ee64b3aa18370af1f75e958d18 | refs/heads/master | 2021-09-01T01:02:33.335046 | 2017-12-24T01:01:47 | 2017-12-24T01:01:47 | 84,698,557 | 10 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,069 | hpp |
#ifndef LEETCODE_397_HPP
#define LEETCODE_397_HPP
#include <iostream>
#include <queue>
#include <algorithm>
#include <vector>
#include <unordered_map>
#include <unordered_set>
#include <set>
#include <numeric>
#include <stack>
#include <string>
using namespace std;
/*
Given a positive integer n and you can do operations as follow:
If n is even, replace n with n/2.
If n is odd, you can replace n with either n + 1 or n - 1.
What is the minimum number of replacements needed for n to become 1?
Example 1:
Input:
8
Output:
3
Explanation:
8 -> 4 -> 2 -> 1
Example 2:
Input:
7
Output:
4
Explanation:
7 -> 8 -> 4 -> 2 -> 1
or
7 -> 6 -> 3 -> 2 -> 1
*/
class Solution {
public:
int integerReplacement(int n) {
int cnt = 0;
uint un = static_cast<uint>(n);
while (un != 1) {
if ((un & 1) == 0)
un >>= 1;
else if (un != 3 && ((un >> 1) & 1) == 1)
un++;
else
un--;
cnt++;
}
return cnt;
}
};
#endif //LEETCODE_397_HPP
| [
"baishuai.io@gmail.com"
] | baishuai.io@gmail.com |
0eae995c3b3e4a08034826b49f98436928cb4d32 | ce6fd0670484b3fd7d7969240a032c4edca32a67 | /Editor/Editor/stb_image.cpp | eda4f283335d9eaabc52ae8edbd890900c36ade1 | [] | no_license | M0hammadx/C_Sharp_Apps | b96c30e06a7c5f615d53d3adc54b0486e8b1948e | e0f7987e3bd8c367ef56bedc98bd6e0e61d633c3 | refs/heads/master | 2020-03-24T18:30:46.477173 | 2019-01-25T02:35:54 | 2019-01-25T02:35:54 | 142,893,987 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 136 | cpp | /*
* stb_image.cpp
*
* Created on: Oct 22, 2018
* Author: mh-sh
*/
#define STB_IMAGE_IMPLEMENTATION
#include "stb_image.h"
| [
"mh-sherbini@hotmail.com"
] | mh-sherbini@hotmail.com |
fc586fa32bfa1a484c4b32d0b030a3849e51ce9f | 91a882547e393d4c4946a6c2c99186b5f72122dd | /Source/XPSP1/NT/net/mmc/wins/delrcdlg.cpp | b32346f253c5e82377c7a2f11d963feee5fedea6 | [] | no_license | IAmAnubhavSaini/cryptoAlgorithm-nt5src | 94f9b46f101b983954ac6e453d0cf8d02aa76fc7 | d9e1cdeec650b9d6d3ce63f9f0abe50dabfaf9e2 | refs/heads/master | 2023-09-02T10:14:14.795579 | 2021-11-20T13:47:06 | 2021-11-20T13:47:06 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,408 | cpp | /**********************************************************************/
/** Microsoft Windows/NT **/
/** Copyright(c) Microsoft Corporation, 1997 - 1999 -99 **/
/**********************************************************************/
/*
delrcdlg.cpp
The delete/tombstone record(s) dialog
FILE HISTORY:
*/
#include "stdafx.h"
#include "winssnap.h"
#include "delrcdlg.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
/////////////////////////////////////////////////////////////////////////////
// CDeleteRecordDlg dialog
CDeleteRecordDlg::CDeleteRecordDlg(CWnd* pParent /*=NULL*/)
: CBaseDialog(CDeleteRecordDlg::IDD, pParent)
{
//{{AFX_DATA_INIT(CDeleteRecordDlg)
m_nDeleteRecord = 0;
//}}AFX_DATA_INIT
m_fMultiple = FALSE;
}
void CDeleteRecordDlg::DoDataExchange(CDataExchange* pDX)
{
CBaseDialog::DoDataExchange(pDX);
//{{AFX_DATA_MAP(CDeleteRecordDlg)
DDX_Radio(pDX, IDC_RADIO_DELETE, m_nDeleteRecord);
//}}AFX_DATA_MAP
}
BEGIN_MESSAGE_MAP(CDeleteRecordDlg, CBaseDialog)
//{{AFX_MSG_MAP(CDeleteRecordDlg)
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// CDeleteRecordDlg message handlers
void CDeleteRecordDlg::OnOK()
{
UpdateData();
// warn the user
if (m_nDeleteRecord != 0)
{
if (AfxMessageBox(IDS_WARN_TOMBSTONE, MB_YESNO) == IDNO)
{
return;
}
}
CBaseDialog::OnOK();
}
BOOL CDeleteRecordDlg::OnInitDialog()
{
CBaseDialog::OnInitDialog();
if (m_fMultiple)
{
CString strText;
// update the strings, title first
strText.LoadString(IDS_DELETE_MULTIPLE_TITLE);
SetWindowText(strText);
// now the static text
strText.LoadString(IDS_DELETE_MULTIPLE_STATIC);
GetDlgItem(IDC_STATIC_DELETE_DESC)->SetWindowText(strText);
// now the radio buttons
strText.LoadString(IDS_DELETE_MULTIPLE_THIS_SERVER);
GetDlgItem(IDC_RADIO_DELETE)->SetWindowText(strText);
strText.LoadString(IDS_DELETE_MULTIPLE_TOMBSTONE);
GetDlgItem(IDC_RADIO_TOMBSTONE)->SetWindowText(strText);
}
return TRUE; // return TRUE unless you set the focus to a control
// EXCEPTION: OCX Property Pages should return FALSE
}
| [
"support@cryptoalgo.cf"
] | support@cryptoalgo.cf |
c8e919a5b376a96e806c4df689dbb6a6089a11b2 | c85635e522f8075ebf2fff39c60627c246a670e3 | /Experimentation/Investigations/Cryptography/DataEncryptionStandard/plans/Sboxes/Sbox_2.hpp | f0787d5768103e2cdc1f8109074b0127f37f40e6 | [] | no_license | MGwynne/oklibrary | 31fcccc5bb6a07cef1b18b937589d63336ee0b53 | 8087ca23d0855ccfd9a6ce29f4799f890afba6f1 | refs/heads/master | 2020-12-25T06:22:57.181997 | 2012-04-26T00:23:40 | 2012-04-26T00:23:40 | 38,967 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,588 | hpp | // Matthew Gwynne, 16.5.2011 (Swansea)
/* Copyright 2011 Oliver Kullmann
This file is part of the OKlibrary. OKlibrary 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 and included in this library; either version 3 of the
License, or any later version. */
/*!
\file Investigations/Cryptography/DataEncryptionStandard/plans/Sboxes/Sbox_2.hpp
\brief On investigations into Sbox two of the Data Encryption Standard
\todo Basic data
<ul>
<li> Generating the full CNF representation:
<ol>
<li> The CNF-file "DES_Sbox_2_fullCNF.cnf" is created by the Maxima-function
output_dessbox_fullcnf_stdname(2) in
ComputerAlgebra/Cryptology/Lisp/Cryptanalysis/DataEncryptionStandard/Sboxes.mac,
which is a full clause-set with 10
variables and 2^10 - 2^6 = 960 clauses:
\verbatim
> cat DES_Sbox_2_fullCNF.cnf | ExtendedDimacsFullStatistics-O3-DNDEBUG n
n non_taut_c red_l taut_c orig_l comment_count finished_bool
10 960 9600 0 9600 1 1
length count
10 960
\endverbatim
</li>
<li> This clause-set is also computed by
bf2relation_fullcnf_fcs(des_sbox_bf(2),6). </li>
</ol>
</li>
<li> The minimum CNF representation has at most 67 clauses. See
"Using weighted MaxSAT to compute small CNFs". </li>
</ul>
\todo Using weighted MaxSAT to compute small CNFs (mincl_rinf <= 67)
<ul>
<li> Computing the weighted MaxSAT problem:
\verbatim
shell> QuineMcCluskeySubsumptionHypergraph-n16-O3-DNDEBUG DES_Sbox_2_fullCNF.cnf > DES_Sbox_2_shg.cnf
shell> cat DES_Sbox_2_shg.cnf | MinOnes2WeightedMaxSAT-O3-DNDEBUG > DES_Sbox_2_shg.wcnf
\endverbatim
</li>
<li> Running then:
\verbatim
shell> ubcsat-okl -alg gsat -w -runs 100 -cutoff 400000 -wtarget 67 -solve 1 -seed 2521057446 -i DES_Sbox_2_shg.wcnf -r model DES_Sbox_2_s67.ass;
shell> cat DES_Sbox_2_fullCNF.cnf_primes | FilterDimacs DES_Sbox_2_s67.ass > DES_Sbox_2_s67.cnf
shell> cat DES_Sbox_2_s67.cnf | ExtendedDimacsFullStatistics-O3-DNDEBUG n
n non_taut_c red_l taut_c orig_l comment_count finished_bool
10 67 374 0 374 1 1
length count
5 30
6 35
7 2
\endverbatim
</li>
<li> The hardness of this "minimum" representation is 3:
<ul>
<li> See "Hardness of boolean function representations" in
Experimentation/Investigations/BooleanFunctions/plans/general.hpp
for a description of the notion of hardness, and method of computation.
</li>
<li> Computing the hardness:
\verbatim
maxima> Sbox_min_F : read_fcl_f("DES_Sbox_2_s67.cnf")$
maxima> Sbox_primes_F : read_fcl_f("DES_Sbox_2_fullCNF.cnf_primes")$
maxima> hardness_wpi_cs(setify(Sbox_min_F[2]), setify(Sbox_primes_F[2]));
3
\endverbatim
</li>
</ul>
</li>
</ul>
\todo 1-base : mincl_r1 <= 129
<ul>
<li> Computing an 1-base
\verbatim
shell> QuineMcCluskey-n16-O3-DNDEBUG DES_Sbox_2_fullCNF.cnf > DES_Sbox_2_pi.cnf
shell> RandomShuffleDimacs-O3-DNDEBUG 71 < DES_Sbox_2_pi.cnf | SortByClauseLength-O3-DNDEBUG > DES_Sbox_2_sortedpi.cnf
shell> RUcpGen-O3-DNDEBUG DES_Sbox_2_sortedpi.cnf > DES_Sbox_2_gen.cnf
shell> RandomShuffleDimacs-O3-DNDEBUG 1 < DES_Sbox_2_gen.cnf | SortByClauseLengthDescending-O3-DNDEBUG | RUcpBase-O3-DNDEBUG > DES_Sbox_2_1base.cnf
shell> cat DES_Sbox_2_1base.cnf | ExtendedDimacsFullStatistics-O3-DNDEBUG n
n non_taut_c red_l taut_c orig_l comment_count finished_bool
10 129 699 0 699 0 1
length count
5 75
6 54
\endverbatim
</li>
</ul>
\todo Move Sbox-1-specific investigations here
*/
| [
"360678@swan.ac.uk"
] | 360678@swan.ac.uk |
beb60a3ba0569627f5f392dfba7b39d8366b9f9f | efa055b4d902b79a729e133f061975b73120c1de | /Playground/QWidgetMultiFileChooser/MainWindow.cpp | d19e2619a5f89e5727aa2e3658808f595662446f | [] | no_license | dellambrogio/learning-qml | 2c4f1a8a7a07d67fd92bc0799968d5be0a4b12cc | 05b8dcfb0052028278ffbdd8db15727acfffd641 | refs/heads/master | 2021-07-17T07:36:10.504767 | 2016-07-29T14:38:18 | 2016-07-29T14:38:18 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,062 | cpp | // ============================================================================
// Copyright (c) 2016 Nextcode
// Nextcode, Zurich. All rights reserved.
//
// Authors: Michele Dell'Ambrogio (m@nextcode.ch)
// ============================================================================
#include "MainWindow.h"
#include "ui_MainWindow.h"
#include "FileItem.h"
#include <QDebug>
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
ui->setupUi(this);
QWidget* widget = new QWidget(ui->scrollArea);
widget->setGeometry(0, 0, ui->scrollArea->width(), 0);
ui->scrollArea->setWidget(widget);
}
MainWindow::~MainWindow()
{
Q_FOREACH(FileItem* item, m_fileItems)
{
qDebug() << item->filename();
}
delete ui;
}
void MainWindow::slotRemoveFileItem(FileItem *item)
{
if (item)
{
m_fileItems.removeAll(item);
delete item;
doLayout();
}
}
void MainWindow::slotAddFileItemAfter(FileItem *item)
{
if (item)
{
int index = m_fileItems.indexOf(item);
addFileItemAtIndex(++index);
}
}
void MainWindow::on_actionNewFile_triggered()
{
addFileItemAtIndex(m_fileItems.count());
}
void MainWindow::addFileItemAtIndex(int index)
{
QWidget* widget = ui->scrollArea->takeWidget();
FileItem* newFileItem = new FileItem(widget);
connect(newFileItem, SIGNAL(signalAddFileItemAfter(FileItem*)), this, SLOT(slotAddFileItemAfter(FileItem*)));
connect(newFileItem, SIGNAL(signalRemoveItem(FileItem*)), this, SLOT(slotRemoveFileItem(FileItem*)));
m_fileItems.insert(index, newFileItem);
ui->scrollArea->setWidget(widget);
doLayout();
}
void MainWindow::doLayout()
{
const int scrollWidth = ui->scrollArea->width();
QWidget* widget = ui->scrollArea->takeWidget();
int itemHeight = 0;
for(int idx = 0; idx < m_fileItems.size(); ++idx)
{
itemHeight = m_fileItems[idx]->height();
m_fileItems[idx]->setGeometry(0, idx*itemHeight, scrollWidth, itemHeight);
}
int scrollHeight = m_fileItems.count() * itemHeight;
widget->resize(scrollWidth, scrollHeight);
ui->scrollArea->setWidget(widget);
}
| [
"mda@disneyresearch.com"
] | mda@disneyresearch.com |
95ec0869915eb5c67ea9172d5029f284e5c3a7c6 | 1ae40287c5705f341886bbb5cc9e9e9cfba073f7 | /Osmium/SDK/FN_BP_FortExpeditionListItem_functions.cpp | 81281469ac56e92f1111e76671bfb5a28d926f70 | [] | no_license | NeoniteDev/Osmium | 183094adee1e8fdb0d6cbf86be8f98c3e18ce7c0 | aec854e60beca3c6804f18f21b6a0a0549e8fbf6 | refs/heads/master | 2023-07-05T16:40:30.662392 | 2023-06-28T23:17:42 | 2023-06-28T23:17:42 | 340,056,499 | 14 | 8 | null | null | null | null | UTF-8 | C++ | false | false | 13,708 | cpp | // Fortnite (4.5-CL-4159770) SDK
#ifdef _MSC_VER
#pragma pack(push, 0x8)
#endif
#include "../SDK.hpp"
namespace SDK
{
//---------------------------------------------------------------------------
//Functions
//---------------------------------------------------------------------------
// Function BP_FortExpeditionListItem.BP_FortExpeditionListItem_C.Update Bang State
// (Public, BlueprintCallable, BlueprintEvent)
// Parameters:
// class UFortAccountItem* Item (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData)
void UBP_FortExpeditionListItem_C::Update_Bang_State(class UFortAccountItem* Item)
{
static auto fn = UObject::FindObject<UFunction>("Function BP_FortExpeditionListItem.BP_FortExpeditionListItem_C.Update Bang State");
UBP_FortExpeditionListItem_C_Update_Bang_State_Params params;
params.Item = Item;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function BP_FortExpeditionListItem.BP_FortExpeditionListItem_C.Set Success Chance
// (Public, BlueprintCallable, BlueprintEvent)
// Parameters:
// class UFortExpeditionItem* Item (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData)
void UBP_FortExpeditionListItem_C::Set_Success_Chance(class UFortExpeditionItem* Item)
{
static auto fn = UObject::FindObject<UFunction>("Function BP_FortExpeditionListItem.BP_FortExpeditionListItem_C.Set Success Chance");
UBP_FortExpeditionListItem_C_Set_Success_Chance_Params params;
params.Item = Item;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function BP_FortExpeditionListItem.BP_FortExpeditionListItem_C.Set Vehicle Icon
// (Public, HasDefaults, BlueprintCallable, BlueprintEvent)
// Parameters:
// class UFortExpeditionItem* Expedition (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData)
void UBP_FortExpeditionListItem_C::Set_Vehicle_Icon(class UFortExpeditionItem* Expedition)
{
static auto fn = UObject::FindObject<UFunction>("Function BP_FortExpeditionListItem.BP_FortExpeditionListItem_C.Set Vehicle Icon");
UBP_FortExpeditionListItem_C_Set_Vehicle_Icon_Params params;
params.Expedition = Expedition;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function BP_FortExpeditionListItem.BP_FortExpeditionListItem_C.Set Expedition Returns Data
// (Public, BlueprintCallable, BlueprintEvent)
// Parameters:
// class UFortExpeditionItem* InputPin (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData)
void UBP_FortExpeditionListItem_C::Set_Expedition_Returns_Data(class UFortExpeditionItem* InputPin)
{
static auto fn = UObject::FindObject<UFunction>("Function BP_FortExpeditionListItem.BP_FortExpeditionListItem_C.Set Expedition Returns Data");
UBP_FortExpeditionListItem_C_Set_Expedition_Returns_Data_Params params;
params.InputPin = InputPin;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function BP_FortExpeditionListItem.BP_FortExpeditionListItem_C.Set In Progress State
// (Public, BlueprintCallable, BlueprintEvent)
// Parameters:
// class UFortExpeditionItem* Item (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData)
void UBP_FortExpeditionListItem_C::Set_In_Progress_State(class UFortExpeditionItem* Item)
{
static auto fn = UObject::FindObject<UFunction>("Function BP_FortExpeditionListItem.BP_FortExpeditionListItem_C.Set In Progress State");
UBP_FortExpeditionListItem_C_Set_In_Progress_State_Params params;
params.Item = Item;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function BP_FortExpeditionListItem.BP_FortExpeditionListItem_C.Set Remaining Expiration Time
// (Public, BlueprintCallable, BlueprintEvent)
// Parameters:
// class UFortExpeditionItem* Item (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData)
void UBP_FortExpeditionListItem_C::Set_Remaining_Expiration_Time(class UFortExpeditionItem* Item)
{
static auto fn = UObject::FindObject<UFunction>("Function BP_FortExpeditionListItem.BP_FortExpeditionListItem_C.Set Remaining Expiration Time");
UBP_FortExpeditionListItem_C_Set_Remaining_Expiration_Time_Params params;
params.Item = Item;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function BP_FortExpeditionListItem.BP_FortExpeditionListItem_C.Set Rarity
// (Public, HasDefaults, BlueprintCallable, BlueprintEvent)
// Parameters:
// class UFortItem* Item (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData)
void UBP_FortExpeditionListItem_C::Set_Rarity(class UFortItem* Item)
{
static auto fn = UObject::FindObject<UFunction>("Function BP_FortExpeditionListItem.BP_FortExpeditionListItem_C.Set Rarity");
UBP_FortExpeditionListItem_C_Set_Rarity_Params params;
params.Item = Item;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function BP_FortExpeditionListItem.BP_FortExpeditionListItem_C.Set Rating
// (Public, BlueprintCallable, BlueprintEvent)
// Parameters:
// class UFortExpeditionItem* Item (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData)
void UBP_FortExpeditionListItem_C::Set_Rating(class UFortExpeditionItem* Item)
{
static auto fn = UObject::FindObject<UFunction>("Function BP_FortExpeditionListItem.BP_FortExpeditionListItem_C.Set Rating");
UBP_FortExpeditionListItem_C_Set_Rating_Params params;
params.Item = Item;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function BP_FortExpeditionListItem.BP_FortExpeditionListItem_C.Set Rewards
// (Public, HasDefaults, BlueprintCallable, BlueprintEvent)
// Parameters:
// class UFortItem* Item (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData)
void UBP_FortExpeditionListItem_C::Set_Rewards(class UFortItem* Item)
{
static auto fn = UObject::FindObject<UFunction>("Function BP_FortExpeditionListItem.BP_FortExpeditionListItem_C.Set Rewards");
UBP_FortExpeditionListItem_C_Set_Rewards_Params params;
params.Item = Item;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function BP_FortExpeditionListItem.BP_FortExpeditionListItem_C.Get Expedition Item Definition
// (Public, HasOutParms, BlueprintCallable, BlueprintEvent, BlueprintPure)
// Parameters:
// class UFortItem* Item (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData)
// class UFortExpeditionItemDefinition* Item_Def (Parm, OutParm, ZeroConstructor, IsPlainOldData)
void UBP_FortExpeditionListItem_C::Get_Expedition_Item_Definition(class UFortItem* Item, class UFortExpeditionItemDefinition** Item_Def)
{
static auto fn = UObject::FindObject<UFunction>("Function BP_FortExpeditionListItem.BP_FortExpeditionListItem_C.Get Expedition Item Definition");
UBP_FortExpeditionListItem_C_Get_Expedition_Item_Definition_Params params;
params.Item = Item;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
if (Item_Def != nullptr)
*Item_Def = params.Item_Def;
}
// Function BP_FortExpeditionListItem.BP_FortExpeditionListItem_C.Set Name
// (Public, HasDefaults, BlueprintCallable, BlueprintEvent)
// Parameters:
// class UFortItem* Item (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData)
void UBP_FortExpeditionListItem_C::Set_Name(class UFortItem* Item)
{
static auto fn = UObject::FindObject<UFunction>("Function BP_FortExpeditionListItem.BP_FortExpeditionListItem_C.Set Name");
UBP_FortExpeditionListItem_C_Set_Name_Params params;
params.Item = Item;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function BP_FortExpeditionListItem.BP_FortExpeditionListItem_C.Setup Base Item Data
// (Public, HasDefaults, BlueprintCallable, BlueprintEvent)
// Parameters:
// class UFortExpeditionItem* Expedition (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData)
void UBP_FortExpeditionListItem_C::Setup_Base_Item_Data(class UFortExpeditionItem* Expedition)
{
static auto fn = UObject::FindObject<UFunction>("Function BP_FortExpeditionListItem.BP_FortExpeditionListItem_C.Setup Base Item Data");
UBP_FortExpeditionListItem_C_Setup_Base_Item_Data_Params params;
params.Expedition = Expedition;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function BP_FortExpeditionListItem.BP_FortExpeditionListItem_C.OnListItemObjectSet
// (Event, Protected, BlueprintEvent)
// Parameters:
// class UObject** ListItemObject (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData)
void UBP_FortExpeditionListItem_C::OnListItemObjectSet(class UObject** ListItemObject)
{
static auto fn = UObject::FindObject<UFunction>("Function BP_FortExpeditionListItem.BP_FortExpeditionListItem_C.OnListItemObjectSet");
UBP_FortExpeditionListItem_C_OnListItemObjectSet_Params params;
params.ListItemObject = ListItemObject;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function BP_FortExpeditionListItem.BP_FortExpeditionListItem_C.BP_OnSelected
// (Event, Protected, BlueprintEvent)
void UBP_FortExpeditionListItem_C::BP_OnSelected()
{
static auto fn = UObject::FindObject<UFunction>("Function BP_FortExpeditionListItem.BP_FortExpeditionListItem_C.BP_OnSelected");
UBP_FortExpeditionListItem_C_BP_OnSelected_Params params;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function BP_FortExpeditionListItem.BP_FortExpeditionListItem_C.OnItemChanged
// (Event, Protected, BlueprintEvent)
void UBP_FortExpeditionListItem_C::OnItemChanged()
{
static auto fn = UObject::FindObject<UFunction>("Function BP_FortExpeditionListItem.BP_FortExpeditionListItem_C.OnItemChanged");
UBP_FortExpeditionListItem_C_OnItemChanged_Params params;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function BP_FortExpeditionListItem.BP_FortExpeditionListItem_C.BP_OnDeselected
// (Event, Protected, BlueprintEvent)
void UBP_FortExpeditionListItem_C::BP_OnDeselected()
{
static auto fn = UObject::FindObject<UFunction>("Function BP_FortExpeditionListItem.BP_FortExpeditionListItem_C.BP_OnDeselected");
UBP_FortExpeditionListItem_C_BP_OnDeselected_Params params;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function BP_FortExpeditionListItem.BP_FortExpeditionListItem_C.BndEvt__InProgressSwitcher_K2Node_ComponentBoundEvent_17_OnActiveWidgetChanged__DelegateSignature
// (BlueprintEvent)
// Parameters:
// class UWidget* ActiveWidget (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, InstancedReference, IsPlainOldData)
// int ActiveWidgetIndex (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData)
void UBP_FortExpeditionListItem_C::BndEvt__InProgressSwitcher_K2Node_ComponentBoundEvent_17_OnActiveWidgetChanged__DelegateSignature(class UWidget* ActiveWidget, int ActiveWidgetIndex)
{
static auto fn = UObject::FindObject<UFunction>("Function BP_FortExpeditionListItem.BP_FortExpeditionListItem_C.BndEvt__InProgressSwitcher_K2Node_ComponentBoundEvent_17_OnActiveWidgetChanged__DelegateSignature");
UBP_FortExpeditionListItem_C_BndEvt__InProgressSwitcher_K2Node_ComponentBoundEvent_17_OnActiveWidgetChanged__DelegateSignature_Params params;
params.ActiveWidget = ActiveWidget;
params.ActiveWidgetIndex = ActiveWidgetIndex;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function BP_FortExpeditionListItem.BP_FortExpeditionListItem_C.BP_OnHovered
// (Event, Protected, BlueprintEvent)
void UBP_FortExpeditionListItem_C::BP_OnHovered()
{
static auto fn = UObject::FindObject<UFunction>("Function BP_FortExpeditionListItem.BP_FortExpeditionListItem_C.BP_OnHovered");
UBP_FortExpeditionListItem_C_BP_OnHovered_Params params;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function BP_FortExpeditionListItem.BP_FortExpeditionListItem_C.ExecuteUbergraph_BP_FortExpeditionListItem
// ()
// Parameters:
// int EntryPoint (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData)
void UBP_FortExpeditionListItem_C::ExecuteUbergraph_BP_FortExpeditionListItem(int EntryPoint)
{
static auto fn = UObject::FindObject<UFunction>("Function BP_FortExpeditionListItem.BP_FortExpeditionListItem_C.ExecuteUbergraph_BP_FortExpeditionListItem");
UBP_FortExpeditionListItem_C_ExecuteUbergraph_BP_FortExpeditionListItem_Params params;
params.EntryPoint = EntryPoint;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| [
"kareemolim@gmail.com"
] | kareemolim@gmail.com |
2a778bc3ede5cd27064db7c1a3901af10c2f7356 | 0769f23da655feb037dc895251e074850e60be02 | /plugin_III/game_III/CPopulation.h | 54da93d8bfe8c385c6f4b6ae2cb437a7e9d87483 | [
"Zlib"
] | permissive | Aleksandr-Belousov/plugin-sdk | 8f3f8d5a51fe60cce3536d19803bf869378a57ae | 5ca5f7d5575ae4138a4f165410a1acf0ae922260 | refs/heads/master | 2020-09-16T10:31:41.400580 | 2019-11-24T13:29:22 | 2019-11-24T13:29:22 | 223,742,780 | 0 | 0 | Zlib | 2019-11-24T12:45:46 | 2019-11-24T12:45:46 | null | UTF-8 | C++ | false | false | 4,519 | h | /*
Plugin-SDK (Grand Theft Auto 3) header file
Authors: GTA Community. See more here
https://github.com/DK22Pac/plugin-sdk
Do not delete this comment block. Respect others' work!
*/
#pragma once
#include "PluginBase.h"
#include "CDummyObject.h"
#include "CObject.h"
#include "CPed.h"
#include "ePedType.h"
#include "CVector.h"
#include "eCopType.h"
#include "CVehicle.h"
#include "eLevelName.h"
#include "CColPoint.h"
class PLUGIN_API CPopulation {
public:
SUPPORTED_10EN_11EN_STEAM static float &PedDensityMultiplier;
SUPPORTED_10EN_11EN_STEAM static int &m_AllRandomPedsThisType;
SUPPORTED_10EN_11EN_STEAM static int &MaxNumberOfPedsInUse;
SUPPORTED_10EN_11EN_STEAM static CColPoint(&aTempColPoints)[32]; // static CColPoint aTempColPoints[32]
SUPPORTED_10EN_11EN_STEAM static int(&ms_pPedGroups)[31][8]; // static int ms_pPedGroups[31][8]
SUPPORTED_10EN_11EN_STEAM static unsigned int &ms_nTotalGangPeds;
SUPPORTED_10EN_11EN_STEAM static unsigned int &ms_nNumCop;
SUPPORTED_10EN_11EN_STEAM static CVector &RegenerationPoint_b;
SUPPORTED_10EN_11EN_STEAM static CVector &RegenerationPoint_a;
SUPPORTED_10EN_11EN_STEAM static unsigned int &ms_nNumDummy;
SUPPORTED_10EN_11EN_STEAM static CVector &RegenerationFront;
SUPPORTED_10EN_11EN_STEAM static unsigned int &ms_nNumGang8;
SUPPORTED_10EN_11EN_STEAM static unsigned int &ms_nNumGang9;
SUPPORTED_10EN_11EN_STEAM static unsigned int &ms_nNumGang2;
SUPPORTED_10EN_11EN_STEAM static unsigned int &ms_nNumGang3;
SUPPORTED_10EN_11EN_STEAM static unsigned int &ms_nNumGang1;
SUPPORTED_10EN_11EN_STEAM static unsigned int &ms_nNumGang6;
SUPPORTED_10EN_11EN_STEAM static unsigned int &ms_nNumGang7;
SUPPORTED_10EN_11EN_STEAM static unsigned int &ms_nNumGang4;
SUPPORTED_10EN_11EN_STEAM static unsigned int &ms_nNumGang5;
SUPPORTED_10EN_11EN_STEAM static unsigned int &ms_nNumCivMale;
SUPPORTED_10EN_11EN_STEAM static unsigned int &ms_nTotalCivPeds;
SUPPORTED_10EN_11EN_STEAM static unsigned int &ms_nNumCivFemale;
SUPPORTED_10EN_11EN_STEAM static unsigned int &ms_nTotalMissionPeds;
SUPPORTED_10EN_11EN_STEAM static unsigned int &ms_nNumEmergency;
SUPPORTED_10EN_11EN_STEAM static unsigned int &ms_nTotalPeds;
SUPPORTED_10EN_11EN_STEAM static bool &ms_bGivePedsWeapons;
SUPPORTED_10EN_11EN_STEAM static char &m_CountDownToPedsAtStart;
SUPPORTED_10EN_11EN_STEAM static bool &bZoneChangeHasHappened;
SUPPORTED_10EN_11EN_STEAM static CPed *AddPed(ePedType pedType, unsigned int modelIndex, CVector *posn);
SUPPORTED_10EN_11EN_STEAM static CPed *AddPedInCar(CVehicle *vehicle);
SUPPORTED_10EN_11EN_STEAM static void AddToPopulation(float z1, float x2, float y2, float z2);
SUPPORTED_10EN_11EN_STEAM static int ChooseCivilianOccupation(int index);
SUPPORTED_10EN_11EN_STEAM static int ChooseGangOccupation(int gangType);
SUPPORTED_10EN_11EN_STEAM static eCopType ChoosePolicePedOccupation();
SUPPORTED_10EN_11EN_STEAM static void ConvertAllObjectsToDummyObjects();
SUPPORTED_10EN_11EN_STEAM static void ConvertToDummyObject(CObject *object);
SUPPORTED_10EN_11EN_STEAM static void ConvertToRealObject(CDummyObject *dummyObject);
SUPPORTED_10EN_11EN_STEAM static void DealWithZoneChange(eLevelName levelName, eLevelName levelNameTwo, bool a3);
SUPPORTED_10EN_11EN_STEAM static void FindClosestZoneForCoors(CVector *point, int *a2, eLevelName levelName, eLevelName _levelName);
SUPPORTED_10EN_11EN_STEAM static void FindCollisionZoneForCoors(CVector *point, int *a2, eLevelName *levelName);
SUPPORTED_10EN_11EN_STEAM static void GeneratePedsAtStartOfGame();
SUPPORTED_10EN_11EN_STEAM static void Initialise();
SUPPORTED_10EN_11EN_STEAM static bool IsPointInSafeZone(CVector *point);
SUPPORTED_10EN_11EN_STEAM static void LoadPedGroups();
SUPPORTED_10EN_11EN_STEAM static void ManagePopulation();
SUPPORTED_10EN_11EN_STEAM static void MoveCarsAndPedsOutOfAbandonedZones();
SUPPORTED_10EN_11EN_STEAM static float PedCreationDistMultiplier();
SUPPORTED_10EN_11EN_STEAM static void RemovePed(CPed *ped);
SUPPORTED_10EN_11EN_STEAM static bool TestRoomForDummyObject(CObject *object);
SUPPORTED_10EN_11EN_STEAM static bool TestSafeForRealObject(CDummyObject *dummyObject);
SUPPORTED_10EN_11EN_STEAM static void Update();
SUPPORTED_10EN_11EN_STEAM static void UpdatePedCount(ePedType pedType, unsigned char updateState);
};
#include "meta/meta.CPopulation.h"
| [
"kenking@rambler.ru"
] | kenking@rambler.ru |
dfb933ac90a53d6c3212ec5aec481a1f9b32475f | 8bbeea2f5a3293d48a5a42690148f5a61b621e26 | /code/commonCode/utils.h | 393e622e4c8d9dfea56d6d14fa71a2ad2616d96c | [] | no_license | fenbf/efg_deferred | 2e12380bf325ae180ce7c7763eaef51233eab42f | b22ef7265a8c66074e38f449dd7ded166e683ecc | refs/heads/master | 2020-04-10T04:11:53.968577 | 2012-07-10T19:35:23 | 2012-07-10T19:35:23 | 4,842,376 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,737 | h | /** @file utils.h
* @brief useful utilities for opengl based apps
*
* Effects in Games, June 2012
*/
#pragma once
/** logging will be by using simple "printf" function */
#define UTILS_LOG_WITH_PRINTF
#ifdef UTILS_LOG_WITH_PRINTF
#define LOG(msg, ...) { printf(msg, __VA_ARGS__); printf("\n"); }
#define LOG_SUCCESS(msg, ...) { printf("SUCCESS: "); printf(msg, __VA_ARGS__); printf("\n"); }
#define LOG_ERROR(msg, ...) { printf("ERR in %s at line %d: ", __FUNCTION__, __LINE__); printf(msg, __VA_ARGS__); printf("\n"); }
#else
#define LOG(msg, ...) { }
#define LOG_SUCCESS(msg, ...) { }
#define LOG_ERROR(msg, ...) { }
#endif
#define WAIT_FOR_CONSOLE_INPUT() { printf("\npress ENTER/RETURN to exit..."); fflush(stdout); getchar(); }
#ifdef _DEBUG
#define CHECK_OPENGL_ERRORS() utils::checkGLErrors(__FUNCTION__, __FILE__, __LINE__);
#else
#define CHECK_OPENGL_ERRORS()
#endif
namespace utils
{
///////////////////////////////////////////////////////////////////////////////
bool initGL(bool vsync);
void calculateFps(float *fps);
void updateTimer(double *deltaTime, double *appTime, const double REFRESH_TIME = 1.0/60.0);
bool checkGLErrors(const char *func, const char * file, int line);
inline float randFloatRange(float a, float b);
inline const char *fileNameFromPath(const char *filePath);
} // namespce utils
///////////////////////////////////////////////////////////////////////////////
// inline
inline float utils::randFloatRange(float a, float b)
{
return a + (float)rand()/(float)RAND_MAX * (b-a);
}
inline const char *utils::fileNameFromPath(const char *filePath)
{
const char *s = strrchr(filePath, '\\');
if (s == NULL)
s = strrchr(filePath, '/');
return s == NULL ? filePath : s+1;
} | [
"bartlomiej.filipek@gmail.com"
] | bartlomiej.filipek@gmail.com |
7ed3362cdc0d6c66261f8fdd301127f526dc0a36 | 440d8b37103bc3534089f8a65dc87870698dc828 | /src/codegen.cpp | 6dd8153e773a6210dc69ace158a36621efb9c568 | [] | no_license | sugu24/self-made-programming-language | 8946fa181c8767f16bc9624c7b72d6cdf606c3f3 | c00d450727b7d52e7cb76b22e93e85394d338af1 | refs/heads/master | 2023-08-27T22:39:59.041663 | 2021-11-06T04:14:23 | 2021-11-06T04:14:23 | 385,790,999 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 43,119 | cpp | #include "codegen.hpp"
/**
* コンストラクタ
*/
CodeGen::CodeGen(){
Builder = new llvm::IRBuilder<>(llvm::getGlobalContext());
Mod = NULL;
}
/**
* デストラクタ
*/
CodeGen::~CodeGen(){
SAFE_DELETE(Builder);
SAFE_DELETE(Mod);
}
/**
* コード生成実行
* @param TranslationUnitAST Module名(入力ファイル名)
* @return 成功時:true 失敗時:false
*/
bool CodeGen::doCodeGen(TranslationUnitAST &tunit, std::string name, std::string link_file, bool with_jit = false){
// Module生成に失敗したら終了
if(!generateTranslationUnit(tunit, name))
return false;
// LinkFileの指定があったらModuleをリンク
if(!link_file.empty() && !linkModule(Mod, link_file))
return false;
// JITのフラグふぁ立っていたらJIT
if(with_jit){
// ExecutionEngine生成
llvm::ExecutionEngine *EE = llvm::EngineBuilder(Mod).create();
// 実行したいFunctionのポインタを渡す(main関数へのポインタを取得)
llvm::Function *F;
if(!(F = Mod->getFunction("main")))
return false;
// JIT済みのmain関数のポインタを取得
int (*fp)() = (int (*)())EE->getPointerToFunction(F);
fprintf(stderr,"%d\n",fp());
}
return true;
}
/**
* Module取得
*/
llvm::Module &CodeGen::getModule(){
if(Mod)
return *Mod;
else
return *(new llvm::Module("null", llvm::getGlobalContext()));
}
/**
* Module生成メソッド
* @param TranslationUnitAST Module名(入力ファイル)
* @return 成功時:true 失敗時:false
*/
bool CodeGen::generateTranslationUnit(TranslationUnitAST &tunit, std::string name){
// Moduleを生成
Mod = new llvm::Module(name, llvm::getGlobalContext());
// printのFunction/////////////////////////////////////////////////
std::vector<llvm::Type*> printFuncArgs;
printFuncArgs.push_back(llvm::Type::getInt8PtrTy(llvm::getGlobalContext()));
llvm::FunctionType *printFuncType = llvm::FunctionType::get(
llvm::Type::getDoubleTy(llvm::getGlobalContext()),
printFuncArgs,
true
);
llvm::Function *printFunc = llvm::Function::Create(
printFuncType,
llvm::GlobalValue::ExternalLinkage,
"printf",
Mod
);
printFunc->setCallingConv(llvm::CallingConv::C);
////////////////////////////////////////////////////////////////////
// scanfのFunction//////////////////////////////////////////////////
std::vector<llvm::Type*> scanFuncArgs;
scanFuncArgs.push_back(llvm::Type::getInt8PtrTy(llvm::getGlobalContext()));
llvm::FunctionType *scanFuncType = llvm::FunctionType::get(
llvm::Type::getDoubleTy(llvm::getGlobalContext()),
scanFuncArgs,
true
);
llvm::Function *scanFunc = llvm::Function::Create(
scanFuncType,
llvm::GlobalValue::ExternalLinkage,
"__isoc99_scanf",
Mod
);
scanFunc->setCallingConv(llvm::CallingConv::C);
////////////////////////////////////////////////////////////////////
// sprintfのfunction ///////////////////////////////////////////////
std::vector<llvm::Type*> sprintFuncArgs;
sprintFuncArgs.push_back(llvm::Type::getInt8PtrTy(llvm::getGlobalContext()));
sprintFuncArgs.push_back(llvm::Type::getInt8PtrTy(llvm::getGlobalContext()));
llvm::FunctionType *sprintFuncType = llvm::FunctionType::get(
llvm::Type::getDoubleTy(llvm::getGlobalContext()),
sprintFuncArgs,
true
);
llvm::Function *sprintFunc = llvm::Function::Create(
sprintFuncType,
llvm::GlobalValue::ExternalLinkage,
"sprintf",
Mod
);
sprintFunc->setCallingConv(llvm::CallingConv::C);
////////////////////////////////////////////////////////////////////
// memsetのfunction ////////////////////////////////////////////////
std::vector<llvm::Type*> memsetFuncArgs;
memsetFuncArgs.push_back(llvm::Type::getInt8PtrTy(llvm::getGlobalContext()));
memsetFuncArgs.push_back(llvm::Type::getInt8Ty(llvm::getGlobalContext()));
memsetFuncArgs.push_back(llvm::Type::getInt64Ty(llvm::getGlobalContext()));
memsetFuncArgs.push_back(llvm::Type::getInt32Ty(llvm::getGlobalContext()));
memsetFuncArgs.push_back(llvm::Type::getInt1Ty(llvm::getGlobalContext()));
llvm::FunctionType *memsetFuncType = llvm::FunctionType::get(
llvm::Type::getDoubleTy(llvm::getGlobalContext()),
memsetFuncArgs,
false
);
llvm::Function *memsetFunc = llvm::Function::Create(
memsetFuncType,
llvm::GlobalValue::ExternalLinkage,
"llvm.memset.p0i8.i64",
Mod
);
memsetFunc->setCallingConv(llvm::CallingConv::C);
////////////////////////////////////////////////////////////////////
// function declaration
for(int i = 0; ; i++){
PrototypeAST *proto = tunit.getPrototype(i);
if(!proto){
break;
}else if(!generatePrototype(proto, Mod)){
SAFE_DELETE(Mod);
return false;
}
}
// function definition
// main最初
for(int i = 0; ;i++){
FunctionAST *func = tunit.getFunction(i);
if(!func)
break;
if(func->getPrototype()->getName() == "main"){
if(!generateFunctionDefinition(func, Mod)){
SAFE_DELETE(Mod);
return false;
}
}
}
for(int i = 0; ;i++){
FunctionAST *func = tunit.getFunction(i);
if(!func)
break;
if(func->getPrototype()->getName() != "main"){
if(!generateFunctionDefinition(func, Mod)){
SAFE_DELETE(Mod);
return false;
}
}
}
return true;
}
/**
* 関数宣言生成メソッド
* @param PrototypeAST, Module
* @return 生成したFunctionのポインタ
*/
llvm::Function *CodeGen::generatePrototype(PrototypeAST *proto, llvm::Module *mod){
// already declared?
llvm::Function *func = mod->getFunction(proto->getName());
if(func){
if(func->arg_size() == proto->getParamNum() && func->empty()){
return func;
}else{
fprintf(stderr, "error::function %s is redefined", proto->getName().c_str());
return NULL;
}
}
// create arg_types
std::vector<llvm::Type*> arg_types;
for(int i=0; i < proto->getParamNum(); i++){
if(proto->getParamIdentify(i) == "int")
arg_types.push_back(llvm::Type::getInt32Ty(llvm::getGlobalContext()));
else if(proto->getParamIdentify(i) == "double")
arg_types.push_back(llvm::Type::getDoubleTy(llvm::getGlobalContext()));
else if(proto->getParamIdentify(i) == "string")
arg_types.push_back(llvm::Type::getInt8PtrTy(llvm::getGlobalContext()));
else
return NULL;
}
// create func type
llvm::FunctionType *func_type;
if(proto->getIdentify() == "double")
func_type = llvm::FunctionType::get(
llvm::Type::getDoubleTy(llvm::getGlobalContext()),arg_types,false);
else if(proto->getIdentify() == "int")
func_type = llvm::FunctionType::get(
llvm::Type::getInt32Ty(llvm::getGlobalContext()),arg_types,false);
// create function
func = llvm::Function::Create(func_type, llvm::Function::ExternalLinkage, proto->getName(), mod);
// set names
llvm::Function::arg_iterator arg_iter = func->arg_begin();
for(int i = 0; i < proto->getParamNum(); i++){
arg_iter->setName(proto->getParamName(i).append("_arg"));
arg_iter++;
}
return func;
}
/**
* 関数定義生成メソッド
* @param FunctionAST Module
* @return 生成したFunctionのポインタ
*/
llvm::Function *CodeGen::generateFunctionDefinition(FunctionAST *func_ast, llvm::Module *mod){
llvm::Function *func = generatePrototype(func_ast->getPrototype(), mod);
if(!func){ return NULL; }
CurFunc = func;
//FuncName = func_ast->getPrototype()->getName();
llvm::BasicBlock *bblock = llvm::BasicBlock::Create(llvm::getGlobalContext(), "entry", func);
Builder->SetInsertPoint(bblock);
// Functionのボディを生成
llvm::Value *f = generateFunctionStatement(func_ast->getBody(), func);
if(!f)
return NULL;
return func;
}
/**
* 関数生成メソッド
* 変数宣言、ステートメントの順に生成
* @param FunctionStmtAST
* @return 最後に生成した
*/
llvm::Value *CodeGen::generateFunctionStatement(FunctionStmtAST *func_stmt, llvm::Function *func){
// inser variable decls
VariableDeclAST *vdecl;
llvm::Value *v = NULL;
for(int i = 0; ;i++){
// 最後まで見たら終了
if(!func_stmt->getVariableDecl(i))
break;
//create alloca
vdecl = llvm::dyn_cast<VariableDeclAST>(func_stmt->getVariableDecl(i));
v = generateVariableDeclaration(vdecl);
}
// ifに対応する変数など
BaseAST *stmt;
llvm::BasicBlock *bblock;// Blockの生成と判定式が正の時格納
llvm::BasicBlock *bend; // ifの最後
llvm::BasicBlock *bcur; // ポイント設定
llvm::BasicBlock *bbfr; // 1つ前のBlock
llvm::BasicBlock *bago; // 2つ前のBlock
std::vector<llvm::BasicBlock*> bor; // True or の次にどこに行くか
std::vector<llvm::BasicBlock*> band; // False and の次にどこに行くか
llvm::BasicBlock *bfr;
llvm::Value *fcmp;
IfStatementAST *ifs;
ComparisonAST *com;
std::string ifStr;
static llvm::IRBuilderBase::InsertPoint ip;
// 1:判定方法if, else if, else 2:brを生成するBlock
// 3:条件式を満たした際に分岐するBlock 4:比較結果
std::vector<
std::tuple<std::string, llvm::BasicBlock*, llvm::BasicBlock*, llvm::Value*, int>
> blocks;
int depth;
std::vector<
std::tuple<llvm::BasicBlock*, llvm::BasicBlock*, llvm::Value*, ForStatementAST*>
> forVals;
std::map<ForStatementAST*, std::vector<std::tuple<llvm::BasicBlock*, llvm::BasicBlock::iterator>>> breakVals;
std::map<ForStatementAST*, std::vector<std::tuple<llvm::BasicBlock*, llvm::BasicBlock::iterator>>> continueVals;
for(int i = 0; ;i++){
// 最後まで見たら終了
stmt = func_stmt->getStatement(i);
if(!stmt)
break;
else if(llvm::isa<IfStatementAST>(stmt)){
if(llvm::dyn_cast<IfStatementAST>(stmt)->getIf() == "if"){
// 条件式の生成 (まだand or出来ない)
ifs = llvm::dyn_cast<IfStatementAST>(stmt);
for(int j = 0; j < ifs->getComparisonNumber(); j++){
com = ifs->getComparison(j);
fcmp = generateComparison(com->getLHS(), com->getRHS(), com->getOp(), func_stmt);
// もしand orがあったらBlockとbrを設定する
if(j < ifs->getOpsNumber()){
if(ifs->getOp(j) == "or"){
bblock = llvm::BasicBlock::Create(
llvm::getGlobalContext(),
"or.lhs.false", func);
// lhs or rhs のlhsがtrueならif.thenへ
// lhs or rhs のlhsがfalseならrhsへ
blocks.emplace_back("or",
Builder->GetInsertBlock(),
bblock, fcmp,ifs->getDepth(j));
Builder->SetInsertPoint(bblock);
}
else if(ifs->getOp(j) == "and"){
bblock = llvm::BasicBlock::Create(
llvm::getGlobalContext(),
"and.lhs.true", func);
// lhs and rhsのlhsがtrueならrhsへ
// lhs and rhsのlhsがfalseならorのrhsへ
blocks.emplace_back("and",
Builder->GetInsertBlock(),
bblock, fcmp,ifs->getDepth(j));
Builder->SetInsertPoint(bblock);
}
}
}
// 条件式を満たした先のBlockを生成
bblock = llvm::BasicBlock::Create(
llvm::getGlobalContext(), "if.then", func);
// br情報
blocks.emplace_back("to if", Builder->GetInsertBlock(), bblock, fcmp,
ifs->getDepth(ifs->getOpsNumber()));
// 条件式が正の場合のBlockにポイントを合わせる
Builder->SetInsertPoint(bblock);
}
else if(llvm::dyn_cast<IfStatementAST>(stmt)->getIf() == "else if"){
// br情報 if か else if の内部にいる
blocks.emplace_back("to end", Builder->GetInsertBlock(), bblock, fcmp,0);
// 条件式を評価するBlockを生成
bblock = llvm::BasicBlock::Create(
llvm::getGlobalContext(), "if.else", func);
// if.elseにポイントを合わせる
Builder->SetInsertPoint(bblock);
// ifの条件分岐からif.elseに分岐する
blocks.emplace_back("come if else",
Builder->GetInsertBlock(), bblock, fcmp, 0);
// 条件式を生成 (まだand or出来ない)
ifs = llvm::dyn_cast<IfStatementAST>(stmt);
for(int j = 0; j < ifs->getComparisonNumber(); j++){
com = ifs->getComparison(j);
fcmp = generateComparison(com->getLHS(), com->getRHS(), com->getOp(), func_stmt);
// もしand orがあったらBlockとbrを設定する
if(j < ifs->getOpsNumber()){
if(ifs->getOp(j) == "or"){
bblock = llvm::BasicBlock::Create(
llvm::getGlobalContext(),
"or.lhs.false", func);
// lhs or rhs のlhsがtrueならif.thenへ
// lhs or rhs のlhsがfalseならrhsへ
blocks.emplace_back("or",
Builder->GetInsertBlock(),
bblock, fcmp,
ifs->getDepth(j));
Builder->SetInsertPoint(bblock);
}
else if(ifs->getOp(j) == "and"){
bblock = llvm::BasicBlock::Create(
llvm::getGlobalContext(),
"and.lhs.true", func);
// lhs and rhsのlhsがtrueならrhsへ
// lhs and rhsのlhsがfalseならorのrhsへ
blocks.emplace_back("and",
Builder->GetInsertBlock(),
bblock, fcmp,
ifs->getDepth(j));
Builder->SetInsertPoint(bblock);
}
}
}
// 条件式が正を満たした先のBlockを生成
bblock = llvm::BasicBlock::Create(
llvm::getGlobalContext(), "if.then", func);
// br情報
blocks.emplace_back("to else if", Builder->GetInsertBlock(), bblock, fcmp, ifs->getDepth(ifs->getOpsNumber()));
// 条件が正の場合のBlockにポイントを合わせる
Builder->SetInsertPoint(bblock);
}
else if(llvm::dyn_cast<IfStatementAST>(stmt)->getIf() == "else"){
// br情報 ifかelse ifにポイントが合っている
blocks.emplace_back("to end", Builder->GetInsertBlock(), bblock, fcmp, 0);
// elseのBlockを生成
bblock = llvm::BasicBlock::Create(
llvm::getGlobalContext(), "if.else", func);
// elseのBlockにポイントを合わせる
Builder->SetInsertPoint(bblock);
blocks.emplace_back("come else",
Builder->GetInsertBlock(), bblock, fcmp, 0);
}
}
else if(llvm::isa<IfEndAST>(stmt)){
// 現在のポイントからif.endにbrする
bend = llvm::BasicBlock::Create(llvm::getGlobalContext(), "if.end", func);
Builder->CreateBr(bend);
// brを生成
bbfr = bend;
bago = NULL;
bcur = Builder->GetInsertBlock();
bfr = bend;
//bor = Builder->GetInsertBlock();
//band = bend;
bor.clear();
bor.push_back(bend);
band.clear();
band.push_back(bend);
while(true){
ifStr = std::get<0>(blocks.at(blocks.size()-1));
bblock = std::get<2>(blocks.at(blocks.size()-1));
fcmp = std::get<3>(blocks.at(blocks.size()-1));
depth = std::get<4>(blocks.at(blocks.size()-1));
if(ifStr == "or"){
//band = bfr;
while(depth >= band.size())
band.push_back(band.at(band.size()-1));
for(int j = depth; band.size() > j; j++)
band.at(j) = bfr;
Builder->SetInsertPoint(
std::get<1>(blocks.at(blocks.size()-1)));
while(bor.size() <= depth)
bor.push_back(bor.at(bor.size()-1));
Builder->CreateCondBr(fcmp, bor.at(depth), bblock);
}
else if(ifStr == "and"){
while(depth+1 >= bor.size())
bor.push_back(bor.at(bor.size()-1));
for(int j = depth+1; bor.size() > j; j++)
bor.at(j) = bfr;
Builder->SetInsertPoint(
std::get<1>(blocks.at(blocks.size()-1)));
while(band.size() <= depth)
band.push_back(band.at(band.size()-1));
Builder->CreateCondBr(fcmp, bblock, band.at(depth));
}
else{
bago = bbfr;
bbfr = bcur;
bcur = std::get<1>(blocks.at(blocks.size()-1));
if(ifStr == "to if" || ifStr == "to else if"){
Builder->SetInsertPoint(bcur);
Builder->CreateCondBr(fcmp, bblock, bago);
//bor = bblock;
bor.clear();
bor.push_back(bblock);
}
else if(ifStr == "come if else" || ifStr == "come else"){
//band = bcur;
band.clear();
band.push_back(bcur);
}
else if(ifStr == "to end"){
Builder->SetInsertPoint(bcur);
Builder->CreateBr(bend);
}
}
bfr = std::get<1>(blocks.at(blocks.size()-1));
blocks.pop_back();
if(ifStr == "to if")
break;
}
while(blocks.size() > 0 && (std::get<0>(blocks.at(blocks.size()-1)) == "or"
|| std::get<0>(blocks.at(blocks.size()-1)) == "and")){
ifStr = std::get<0>(blocks.at(blocks.size()-1));
bblock = std::get<2>(blocks.at(blocks.size()-1));
fcmp = std::get<3>(blocks.at(blocks.size()-1));
depth = std::get<4>(blocks.at(blocks.size()-1));
if(ifStr == "or"){
//band = bfr;
while(depth >= band.size())
band.push_back(band.at(band.size()-1));
for(int j = depth; band.size() > j; j++)
band.at(j) = bfr;
Builder->SetInsertPoint(
std::get<1>(blocks.at(blocks.size()-1)));
while(bor.size() <= depth)
bor.push_back(bor.at(bor.size()-1));
Builder->CreateCondBr(fcmp, bor.at(depth), bblock);
}
else if(ifStr == "and"){
while(depth+1 >= bor.size())
bor.push_back(bor.at(bor.size()-1));
for(int j = depth+1; bor.size() > j; j++)
bor.at(j) = bfr;
Builder->SetInsertPoint(
std::get<1>(blocks.at(blocks.size()-1)));
while(band.size() <= depth)
band.push_back(band.at(band.size()-1));
Builder->CreateCondBr(fcmp, bblock, band.at(depth));
}
bfr = std::get<1>(blocks.at(blocks.size()-1));
blocks.pop_back();
}
Builder->SetInsertPoint(bend);
}
else if(llvm::isa<ForStatementAST>(stmt)){
ForStatementAST *for_expr = llvm::dyn_cast<ForStatementAST>(stmt);
llvm::BasicBlock *bcond = llvm::BasicBlock::Create(
llvm::getGlobalContext(), "for.cond", CurFunc);
llvm::BasicBlock *bbody = llvm::BasicBlock::Create(
llvm::getGlobalContext(), "for.body", CurFunc);
llvm::Value *fcmp = generateForStatement(for_expr, bcond, bbody, func_stmt);
forVals.emplace_back(bcond, bbody, fcmp, for_expr);
}
else if(llvm::isa<ForEndAST>(stmt)){
llvm::BasicBlock *bcond = std::get<0>(forVals.at(forVals.size()-1));
llvm::BasicBlock *bbody = std::get<1>(forVals.at(forVals.size()-1));
llvm::Value *fcmp = std::get<2>(forVals.at(forVals.size()-1));
ForStatementAST *for_expr = std::get<3>(forVals.at(forVals.size()-1));
llvm::BasicBlock *binc = llvm::BasicBlock::Create(llvm::getGlobalContext(), "for.inc", CurFunc);
llvm::BasicBlock *bend = llvm::BasicBlock::Create(llvm::getGlobalContext(), "for.end", CurFunc);
generateForEndStatement(bcond, bbody, binc, bend, fcmp, for_expr, func_stmt);
llvm::BasicBlock *temp = Builder->GetInsertBlock();
forVals.pop_back();
if(breakVals.find(for_expr) != breakVals.end()){
for(int i = 0; i < breakVals[for_expr].size(); i++){
Builder->SetInsertPoint(std::get<0>(breakVals[for_expr].at(i)), ++std::get<1>(breakVals[for_expr].at(i)));
Builder->CreateBr(bend);
}
breakVals[for_expr].clear();
}
if(continueVals.find(for_expr) != continueVals.end()){
for(int i = 0; i < continueVals[for_expr].size(); i++){
Builder->SetInsertPoint(std::get<0>(continueVals[for_expr].at(i)), ++std::get<1>(continueVals[for_expr].at(i)));
Builder->CreateBr(binc);
}
continueVals[for_expr].clear();
}
Builder->SetInsertPoint(temp);
}
else if(llvm::isa<BreakAST>(stmt)){
BreakAST *break_expr = llvm::dyn_cast<BreakAST>(stmt);
llvm::BasicBlock *bcur = Builder->GetInsertBlock();
ForStatementAST *for_expr;
if(break_expr->getDepth() <= 0 || forVals.size() < break_expr->getDepth()){
fprintf(stderr, "break文のカッコの中の数を確認してください\n");
return NULL;
}
else
for_expr = std::get<3>(forVals.at(forVals.size()-break_expr->getDepth()));
if(breakVals.find(for_expr) == breakVals.end()){
std::vector<std::tuple<llvm::BasicBlock*, llvm::BasicBlock::iterator>> temp;
breakVals[for_expr] = temp;
}
if(bcur->empty())
breakVals[for_expr].emplace_back(bcur, bcur->begin());
else{
llvm::BasicBlock::iterator iter = bcur->begin();
for(int i = 0; i < bcur->size()-1; i++)
iter++;
breakVals[for_expr].emplace_back(bcur, iter);
}
}
else if(llvm::isa<ContinueAST>(stmt)){
ContinueAST *continue_expr = llvm::dyn_cast<ContinueAST>(stmt);
llvm::BasicBlock *bcur = Builder->GetInsertBlock();
ForStatementAST *for_expr;
if(continue_expr->getDepth() <= 0 || forVals.size() < continue_expr->getDepth()){
fprintf(stderr, "continue文のカッコの中の数を確認してください.\n");
return NULL;
}
else
for_expr = std::get<3>(forVals.at(forVals.size()-continue_expr->getDepth()));
if(continueVals.find(for_expr) == continueVals.end()){
std::vector<std::tuple<llvm::BasicBlock*, llvm::BasicBlock::iterator>> temp;
continueVals[for_expr] = temp;
}
if(bcur->empty())
continueVals[for_expr].emplace_back(bcur, bcur->begin());
else{
llvm::BasicBlock::iterator iter = bcur->begin();
for(int i = 0; i < bcur->size()-1; i++)
iter++;
continueVals[for_expr].emplace_back(bcur, iter);
}
}
else if(llvm::isa<GlobalVariableAST>(stmt)){
GlobalVariableAST *gVar = llvm::dyn_cast<GlobalVariableAST>(stmt);
llvm::Value *check = Mod->getNamedGlobal(gVar->getName());
if(!check){
fprintf(stderr, "%d行目 : global で宣言された変数 %s はありません.\n", gVar->getLine(), gVar->getName().c_str());
CORRECT = false;
}
}else if(!llvm::isa<NullExprAST>(stmt))
v = generateStatement(stmt, func_stmt);
}
return v;
}
/**
* 変数宣言(alloca命令)生成メソッド
* @param VariableDeclAST
* @return 生成したValueのポインタ
*/
llvm::Value *CodeGen::generateVariableDeclaration(VariableDeclAST *vdecl){
if(CurFunc->getName().str() == "main"){
Mod->getOrInsertGlobal(vdecl->getName(), llvm::Type::getDoubleTy(llvm::getGlobalContext()));
llvm::GlobalVariable *gvar = Mod->getNamedGlobal(vdecl->getName());
gvar->setLinkage(llvm::GlobalValue::CommonLinkage);
gvar->setInitializer(llvm::ConstantFP::get(llvm::Type::getDoubleTy(llvm::getGlobalContext()), 0));
return gvar;
}
else{
// create alloca
llvm::AllocaInst *alloca = NULL;
if(vdecl->getIdentify() == VariableDeclAST::dint)
alloca = Builder->CreateAlloca(llvm::Type::getInt32Ty(
llvm::getGlobalContext()), 0, vdecl->getName());
if(vdecl->getIdentify() == VariableDeclAST::ddouble)
alloca = Builder->CreateAlloca(llvm::Type::getDoubleTy(
llvm::getGlobalContext()), 0, vdecl->getName());
// if args alloca
if(vdecl->getType() == VariableDeclAST::param){
// store args
llvm::ValueSymbolTable &vs_table = CurFunc->getValueSymbolTable();
Builder->CreateStore(vs_table.lookup(vdecl->getName().append("_arg")), alloca);
}
return alloca;
}
}
/**
* ステートメント生成メソッド
* 実際にはASTの種類を確認して各種生成メソッドを呼び出し
* @param BaseAST
* @return 生成したValueのポインタ
*/
llvm::Value *CodeGen::generateStatement(BaseAST *stmt, FunctionStmtAST *func_stmt){
if(llvm::isa<BinaryExprAST>(stmt)){
return generateBinaryExpression(llvm::dyn_cast<BinaryExprAST>(stmt), func_stmt);
}else if(llvm::isa<CallExprAST>(stmt)){
return generateCallExpression(llvm::dyn_cast<CallExprAST>(stmt), func_stmt);
}else if(llvm::isa<ReturnStmtAST>(stmt)){
return generateReturnStatement(llvm::dyn_cast<ReturnStmtAST>(stmt), func_stmt);
}else{
return NULL;
}
}
/**
* 二項演算生成メソッド
* @param JumpStmtAST
* @return 生成したValueのポインタ
*/
llvm::Value *CodeGen::generateBinaryExpression(BinaryExprAST *bin_expr, FunctionStmtAST *func_stmt){
BaseAST *lhs = bin_expr->getLHS();
BaseAST *rhs = bin_expr->getRHS();
llvm::Value *lhs_v;
llvm::Value *rhs_v;
// = の場合に代入先に指定するValueを格納する
llvm::Value *assigned_v;
VariableAST *lhs_var;
// assignment
if(bin_expr->getOp() == "="){
// lhs is variable
lhs_var = llvm::dyn_cast<VariableAST>(lhs);
if(CurFunc->getName().str() == "main" || func_stmt->isGlobalVariable(lhs_var->getName()))
assigned_v = Mod->getNamedGlobal(lhs_var->getName());
else{
llvm::ValueSymbolTable &vs_table = CurFunc->getValueSymbolTable();
assigned_v = vs_table.lookup(lhs_var->getName());
}
lhs_v = generateVariable(lhs_var, func_stmt);
// other operand
}else{
// lhs = ?
// Binary?
if(llvm::isa<BinaryExprAST>(lhs)){
lhs_v = generateBinaryExpression(llvm::dyn_cast<BinaryExprAST>(lhs), func_stmt);
// CallExpr?
}else if(llvm::isa<CallExprAST>(lhs)){
lhs_v = generateCallExpression(llvm::dyn_cast<CallExprAST>(lhs), func_stmt);
// Variable?
}else if(llvm::isa<VariableAST>(lhs)){
lhs_v = generateVariable(llvm::dyn_cast<VariableAST>(lhs), func_stmt);
// Number?
}else if(llvm::isa<NumberAST>(lhs)){
NumberAST *num = llvm::dyn_cast<NumberAST>(lhs);
lhs_v = generateNumber(num->getNumberValue());
}
}
// create rhs value
if(llvm::isa<BinaryExprAST>(rhs)){
rhs_v = generateBinaryExpression(llvm::dyn_cast<BinaryExprAST>(rhs), func_stmt);
// CallExpr?
}else if(llvm::isa<CallExprAST>(rhs)){
rhs_v = generateCallExpression(llvm::dyn_cast<CallExprAST>(rhs), func_stmt);
// Variable?
}else if(llvm::isa<VariableAST>(rhs)){
rhs_v = generateVariable(llvm::dyn_cast<VariableAST>(rhs), func_stmt);
// Number?
}else if(llvm::isa<NumberAST>(rhs)){
NumberAST *num = llvm::dyn_cast<NumberAST>(rhs);
rhs_v = generateNumber(num->getNumberValue());
}
// コード生成
if(bin_expr->getOp() == "="){
// store
return Builder->CreateStore(rhs_v, assigned_v);
}
if(bin_expr->getOp() == "+"){
// add
return Builder->CreateFAdd(lhs_v, rhs_v, "add_tmp");
}else if(bin_expr->getOp() == "-"){
// sub
return Builder->CreateFSub(lhs_v, rhs_v, "sub_tmp");
}else if(bin_expr->getOp() == "*"){
// mul
return Builder->CreateFMul(lhs_v, rhs_v, "mul_tmp");
}else if(bin_expr->getOp() == "/"){
generateDenominatorCheck("割り算", rhs, bin_expr->getLine(), func_stmt);
// div
return Builder->CreateFDiv(lhs_v, rhs_v,"div_tmp");
}
else if(bin_expr->getOp() == "//"){
generateDenominatorCheck("割り切り算", rhs, bin_expr->getLine(), func_stmt);
// div
llvm::Value *div_tmp = Builder->CreateFDiv(lhs_v, rhs_v, "div_tmp");
div_tmp = Builder->CreateCast(llvm::Instruction::FPToSI, div_tmp,
llvm::Type::getInt32Ty(llvm::getGlobalContext()));
div_tmp = Builder->CreateCast(llvm::Instruction::SIToFP, div_tmp,
llvm::Type::getDoubleTy(llvm::getGlobalContext()));
return div_tmp;
}
else if(bin_expr->getOp() == "%"){
generateDenominatorCheck("余り演算", rhs, bin_expr->getLine(), func_stmt);
// rem
return Builder->CreateFRem(lhs_v, rhs_v, "rem_tmp");
}
return NULL;
}
/**
* 関数呼び出し(Call命令)生成メソッド
* @param CallExprAST
* @return 生成したValueのポインタ
*/
llvm::Value *CodeGen::generateCallExpression(CallExprAST *call_expr, FunctionStmtAST *func_stmt){
std::vector<llvm::Value*> arg_vec;
BaseAST *arg;
llvm::Value *arg_v;
llvm::ValueSymbolTable &vs_table = CurFunc->getValueSymbolTable();
std::string Str = "";
llvm::Value *val;
if(call_expr->getCallee() == "print" || call_expr->getCallee() == "input")
arg_vec.push_back(generateString(""));
if(call_expr->getCallee() == "input"){
VariableAST *var;
llvm::ValueSymbolTable &vs_table = CurFunc->getValueSymbolTable();
for(int i = 0; ; i++){
if(!(arg = call_expr->getArgs(i)))
break;
if(!llvm::isa<VariableAST>(arg)){
fprintf(stderr, "inputのカッコ内の変数を確認してください.\n");
return NULL;
}
var = llvm::dyn_cast<VariableAST>(arg);
if(CurFunc->getName().str() == "main" || func_stmt->isGlobalVariable(var->getName()))
arg_vec.push_back(Mod->getNamedGlobal(var->getName()));
else
arg_vec.push_back(vs_table.lookup(var->getName()));
}
Str = "%lf";
for(int i = 0; i < arg_vec.size()-2; i++)
Str += " %lf";
arg_vec.at(0) = generateString(Str);
return Builder->CreateCall(Mod->getFunction("__isoc99_scanf"), arg_vec, "call_temp");
}
for(int i = 0; ;i++){
if(!(arg = call_expr->getArgs(i)))
break;
// isCall
if(llvm::isa<CallExprAST>(arg)){
arg_v = generateCallExpression(llvm::dyn_cast<CallExprAST>(arg), func_stmt);
// isBinaryExpr
}else if(llvm::isa<BinaryExprAST>(arg)){
BinaryExprAST *bin_expr = llvm::dyn_cast<BinaryExprAST>(arg);
arg_v = generateBinaryExpression(llvm::dyn_cast<BinaryExprAST>(arg), func_stmt);
if(bin_expr->getOp() == "="){
VariableAST *var = llvm::dyn_cast<VariableAST>(bin_expr->getLHS());
arg_v = generateVariable(var, func_stmt);
}
}
// isVar
else if(llvm::isa<VariableAST>(arg)){
arg_v = generateVariable(llvm::dyn_cast<VariableAST>(arg), func_stmt);
// isNumber
}else if(llvm::isa<NumberAST>(arg)){
NumberAST *num = llvm::dyn_cast<NumberAST>(arg);
arg_v = generateNumber(num->getNumberValue());
// string
}else if(llvm::isa<StringAST>(arg)){
StringAST *str = llvm::dyn_cast<StringAST>(arg);
arg_v = generateString(str->getStringValue());
// NewLine
}else if(llvm::isa<NewLineAST>(arg)){}
if(call_expr->getCallee() == "print"){
llvm::Value *print_string;
std::vector<llvm::Value*> print_vec;
std::vector<llvm::Value*> indices;
std::vector<llvm::Value*> memset_vec;
indices.push_back(llvm::ConstantInt::get(llvm::Type::getInt32Ty(llvm::getGlobalContext()), 0));
indices.push_back(llvm::ConstantInt::get(llvm::Type::getInt32Ty(llvm::getGlobalContext()), 0));
llvm::AllocaInst *print_str = Builder->CreateAlloca(llvm::ArrayType::get(llvm::Type::getInt8Ty(llvm::getGlobalContext()), 1));
memset_vec.push_back(Builder->CreatePointerCast(print_str, llvm::Type::getInt8PtrTy(llvm::getGlobalContext()), "print_str_temp"));
memset_vec.push_back(llvm::ConstantInt::get(llvm::Type::getInt8Ty(llvm::getGlobalContext()), 0));
memset_vec.push_back(llvm::ConstantInt::get(llvm::Type::getInt64Ty(llvm::getGlobalContext()), 1));
memset_vec.push_back(llvm::ConstantInt::get(llvm::Type::getInt32Ty(llvm::getGlobalContext()), 1));
memset_vec.push_back(llvm::ConstantInt::get(llvm::Type::getInt1Ty(llvm::getGlobalContext()), false));
Builder->CreateCall(Mod->getFunction("llvm.memset.p0i8.i64"), memset_vec, "call_temp");
if(llvm::isa<StringAST>(arg)){
print_vec.push_back(generateString("%s "));
print_vec.push_back(arg_v);
val = Builder->CreateCall(Mod->getFunction("printf"), print_vec, "call_temp");
}else if(llvm::isa<NewLineAST>(arg)){
print_vec.push_back(generateString("\n"));
val = Builder->CreateCall(Mod->getFunction("printf"), print_vec, "call_temp");
}else if(arg_v->getType()->isDoubleTy()){
std::string width;
std::string digit;
if(llvm::isa<VariableAST>(arg)){
width = llvm::dyn_cast<VariableAST>(arg)->getWidth();
digit = llvm::dyn_cast<VariableAST>(arg)->getDigit();
}
else if(llvm::isa<NumberAST>(arg)){
width = llvm::dyn_cast<NumberAST>(arg)->getWidth();
digit = llvm::dyn_cast<NumberAST>(arg)->getDigit();
}
else if(llvm::isa<BinaryExprAST>(arg)){
width = llvm::dyn_cast<BinaryExprAST>(arg)->getWidth();
digit = llvm::dyn_cast<BinaryExprAST>(arg)->getDigit();
}
else if(llvm::isa<CallExprAST>(arg)){
width = llvm::dyn_cast<CallExprAST>(arg)->getWidth();
digit = llvm::dyn_cast<CallExprAST>(arg)->getDigit();
}
else{
fprintf(stderr, "printに予期しない引数の型があります\n");
return NULL;
}
if(digit == "-1"){
val = Builder->CreateInBoundsGEP(print_str,indices, "print_array");
print_vec.push_back(val);
print_vec.push_back(generateString("%%%s.0f "));
print_vec.push_back(generateString(width));
Builder->CreateCall(Mod->getFunction("sprintf"), print_vec, "call_temp");
print_vec.clear();
print_vec.push_back(Builder->CreateInBoundsGEP(print_str, indices, "print_array"));
print_vec.push_back(arg_v);
val = Builder->CreateCall(Mod->getFunction("printf"), print_vec, "call_temp");
}
else if(digit == "-2"){
llvm::Value *mod = Builder->CreateFRem(arg_v, generateNumber(1), "rem_temp");
llvm::Value *fcmp = Builder->CreateFCmpOEQ(mod, generateNumber(0), "cmp");
llvm::BasicBlock *integer = llvm::BasicBlock::Create(llvm::getGlobalContext(), "int_arg", CurFunc);
llvm::BasicBlock *decimal = llvm::BasicBlock::Create(llvm::getGlobalContext(), "dec_arg", CurFunc);
llvm::BasicBlock *end = llvm::BasicBlock::Create(llvm::getGlobalContext(), "end_arg", CurFunc);
Builder->CreateCondBr(fcmp, integer, decimal);
Builder->SetInsertPoint(integer);
// int だったら
val = Builder->CreateInBoundsGEP(print_str,indices, "print_array");
print_vec.push_back(val);
print_vec.push_back(generateString("%%%s.0f "));
print_vec.push_back(generateString(width));
Builder->CreateCall(Mod->getFunction("sprintf"), print_vec, "call_temp");
print_vec.clear();
print_vec.push_back(Builder->CreateInBoundsGEP(print_str, indices, "print_array"));
print_vec.push_back(arg_v);
Builder->CreateCall(Mod->getFunction("printf"), print_vec, "call_temp");
Builder->CreateBr(end);
// print_str.clear()
print_vec.clear();
Builder->SetInsertPoint(decimal);
// decだったら
val = Builder->CreateInBoundsGEP(print_str,indices, "print_array");
print_vec.push_back(val);
print_vec.push_back(generateString("%%.5f "));
Builder->CreateCall(Mod->getFunction("sprintf"), print_vec, "call_temp");
print_vec.clear();
print_vec.push_back(Builder->CreateInBoundsGEP(print_str, indices, "print_array"));
print_vec.push_back(arg_v);
val = Builder->CreateCall(Mod->getFunction("printf"), print_vec, "call_temp");
Builder->CreateBr(end);
Builder->SetInsertPoint(end);
}else{
val = Builder->CreateInBoundsGEP(print_str,indices, "print_array");
print_vec.push_back(val);
print_vec.push_back(generateString("%%%s.%sf "));
print_vec.push_back(generateString(width));
print_vec.push_back(generateString(digit));
Builder->CreateCall(Mod->getFunction("sprintf"), print_vec, "call_temp");
print_vec.clear();
print_vec.push_back(Builder->CreateInBoundsGEP(print_str, indices, "print_array"));
print_vec.push_back(arg_v);
val = Builder->CreateCall(Mod->getFunction("printf"), print_vec, "call_temp");
}
}
}
else {
arg_vec.push_back(arg_v);
}
}
if(call_expr->getCallee() == "print"){
return val;
}
else
return Builder->CreateCall(Mod->getFunction(call_expr->getCallee()), arg_vec, "call_temp");
}
/**
* ジャンプ(今回はreturn 命令のみ)生成メソッド
* @param JumpStmtAST
* @return 生成したValueのポインタ
*/
llvm::Value *CodeGen::generateReturnStatement(ReturnStmtAST *jump_stmt, FunctionStmtAST *func_stmt){
BaseAST *expr = jump_stmt->getExpr();
llvm::Value *ret_v;
if(llvm::isa<BinaryExprAST>(expr)){
ret_v = generateBinaryExpression(llvm::dyn_cast<BinaryExprAST>(expr), func_stmt);
}if(llvm::isa<CallExprAST>(expr)){
CallExprAST *call_expr = llvm::dyn_cast<CallExprAST>(expr);
ret_v = generateCallExpression(call_expr, func_stmt);
}else if(llvm::isa<VariableAST>(expr)){
VariableAST *var = llvm::dyn_cast<VariableAST>(expr);
ret_v = generateVariable(var, func_stmt);
}else if(llvm::isa<NumberAST>(expr)){
NumberAST *num = llvm::dyn_cast<NumberAST>(expr);
ret_v = generateNumber(num->getNumberValue());
}
if(!ret_v)
return NULL;
else{
if(CurFunc->getReturnType()->isIntegerTy() && ret_v->getType()->isDoubleTy())
ret_v = Builder->CreateCast(llvm::Instruction::FPToSI, ret_v,
llvm::Type::getInt32Ty(llvm::getGlobalContext()), "int_tmp");
else if(CurFunc->getReturnType()->isDoubleTy() && ret_v->getType()->isIntegerTy())
ret_v = Builder->CreateCast(llvm::Instruction::SIToFP, ret_v,
llvm::Type::getDoubleTy(llvm::getGlobalContext()), "double_tmp");
Builder->CreateRet(ret_v);
return ret_v;
}
}
/**
* 変数参照(load命令)生成メソッド
* @param VariableAST
* @return 生成したValueのポインタ
*/
llvm::Value *CodeGen::generateVariable(VariableAST *var, FunctionStmtAST *func_stmt){
llvm::Value *value;
if(CurFunc->getName().str() == "main" || func_stmt->isGlobalVariable(var->getName())){
value = Mod->getNamedGlobal(var->getName());
}else{
llvm::ValueSymbolTable &vs_table = CurFunc->getValueSymbolTable();
value = vs_table.lookup(var->getName());
}
return Builder->CreateLoad(value, "var_temp");
}
/**
* 定数生成メソッド
* @param 生成する定数の値
* @return 生成したValueのポインタ
*/
llvm::Value *CodeGen::generateNumber(double value){
return llvm::ConstantFP::get(llvm::Type::getDoubleTy(llvm::getGlobalContext()), value);
}
/**
* 文字列生成メソッド
* @param 生成する文字列
* @return 生成したValueポインタ
*/
llvm::Value *CodeGen::generateString(std::string str){
return Builder->CreateGlobalStringPtr(str, ".str");
}
/**
* Module結合用メソッド
*/
bool CodeGen::linkModule(llvm::Module *dest, std::string file_name){
llvm::SMDiagnostic err;
// Moduleの読み込み
llvm::Module *link_mod = llvm::ParseIRFile(file_name, err, llvm::getGlobalContext());
if(!link_mod)
return false;
// Moduleの結合
std::string err_msg;
if(llvm::Linker::LinkModules(dest, link_mod, llvm::Linker::DestroySource, &err_msg))
return false;
SAFE_DELETE(link_mod);
return true;
}
//////////////////////////////////////////////////////
//比較を生成
//////////////////////////////////////////////////////
llvm::Value *CodeGen::generateComparison(BaseAST *lhs, BaseAST *rhs, std::string op, FunctionStmtAST *func_stmt){
llvm::Value *lhs_v;
llvm::Value *rhs_v;
// 左辺値取得
if(llvm::isa<BinaryExprAST>(lhs)){
lhs_v = generateBinaryExpression(llvm::dyn_cast<BinaryExprAST>(lhs), func_stmt);
}else if(llvm::isa<CallExprAST>(lhs)){
lhs_v = generateCallExpression(llvm::dyn_cast<CallExprAST>(lhs), func_stmt);
}else if(llvm::isa<VariableAST>(lhs)){
lhs_v = generateVariable(llvm::dyn_cast<VariableAST>(lhs), func_stmt);
}else if(llvm::isa<NumberAST>(lhs)){
lhs_v = generateNumber(llvm::dyn_cast<NumberAST>(lhs)->getNumberValue());
}else{
fprintf(stderr, "タイプ%dの左辺値が取得できません\n", lhs->getValueID());
return NULL;
}
// 右辺値取得
if(llvm::isa<BinaryExprAST>(rhs)){
rhs_v = generateBinaryExpression(llvm::dyn_cast<BinaryExprAST>(rhs), func_stmt);
}else if(llvm::isa<CallExprAST>(rhs)){
rhs_v = generateCallExpression(llvm::dyn_cast<CallExprAST>(rhs), func_stmt);
}else if(llvm::isa<VariableAST>(rhs)){
rhs_v = generateVariable(llvm::dyn_cast<VariableAST>(rhs), func_stmt);
}else if(llvm::isa<NumberAST>(rhs)){
rhs_v = generateNumber(llvm::dyn_cast<NumberAST>(rhs)->getNumberValue());
}else{
fprintf(stderr, "右辺値が取得できません\n");
return NULL;
}
// コード生成
if(op == "==")
return Builder->CreateFCmpOEQ(lhs_v, rhs_v, "cmp");
else if(op == ">=")
return Builder->CreateFCmpOGE(lhs_v, rhs_v, "cmp");
else if(op == ">")
return Builder->CreateFCmpOGT(lhs_v, rhs_v, "cmp");
else if(op == "<=")
return Builder->CreateFCmpOLE(lhs_v, rhs_v, "cmp");
else if(op == "<")
return Builder->CreateFCmpOLT(lhs_v, rhs_v, "cmp");
else if(op == "!=")
return Builder->CreateFCmpONE(lhs_v, rhs_v, "cmp");
else
return NULL;
}
// forを表すllvmirを生成
llvm::Value *CodeGen::generateForStatement(ForStatementAST *for_expr, llvm::BasicBlock *bcond, llvm::BasicBlock *bbody, FunctionStmtAST *func_stmt){
// 繰り返し変数の設定
if(!llvm::isa<BinaryExprAST>(for_expr->getBinExpr()) && for_expr->getBinExpr()->getOp() == "="){
fprintf(stderr, "for 繰り返し数 である必要があります。\n");
SAFE_DELETE(bcond);
SAFE_DELETE(bbody);
return NULL;
}
generateBinaryExpression(for_expr->getBinExpr(), func_stmt);
// to for.condへ
Builder->CreateBr(bcond);
Builder->SetInsertPoint(bcond);
// for cond
llvm::Value *roop_variable = generateVariable(for_expr->getVal(), func_stmt);
llvm::Value *end_val;
if(llvm::isa<BinaryExprAST>(for_expr->getEndExpr()))
end_val = generateBinaryExpression(llvm::dyn_cast<BinaryExprAST>(for_expr->getEndExpr()), func_stmt);
else if(llvm::isa<VariableAST>(for_expr->getEndExpr()))
end_val = generateVariable(llvm::dyn_cast<VariableAST>(for_expr->getEndExpr()), func_stmt);
else if(llvm::isa<NumberAST>(for_expr->getEndExpr()))
end_val = generateNumber(llvm::dyn_cast<NumberAST>(for_expr->getEndExpr())->getNumberValue());
if(!end_val){
fprintf(stderr, "for 繰り返し数 である必要があります\n");
return NULL;
}
llvm::Value *fcmp = Builder->CreateFCmpOLE(roop_variable, end_val, "cmp");
// for.bodyにbr for.incに設定
Builder->SetInsertPoint(bbody);
return fcmp;
}
// forEndを表すllvmirを生成
llvm::BasicBlock *CodeGen::generateForEndStatement(llvm::BasicBlock *bcond, llvm::BasicBlock *bbody, llvm::BasicBlock *binc, llvm::BasicBlock *bend, llvm::Value *fcmp, ForStatementAST *for_expr, FunctionStmtAST *func_stmt){
// for.bodyからfor.incへ
Builder->CreateBr(binc);
Builder->SetInsertPoint(binc);
// for.incの生成
llvm::Value *roop_var = generateVariable(for_expr->getVal(), func_stmt);
llvm::Value *temp_var = Builder->CreateFAdd(roop_var, generateNumber(1.0), "add_tmp");
if(CurFunc->getName().str() == "main" || func_stmt->isGlobalVariable(for_expr->getVal()->getName())){
roop_var = Mod->getNamedGlobal(for_expr->getVal()->getName());
}else{
llvm::ValueSymbolTable &vs_table = CurFunc->getValueSymbolTable();
roop_var = vs_table.lookup(for_expr->getVal()->getName());
}
Builder->CreateStore(temp_var, roop_var);
Builder->CreateBr(bcond);
// for.condの最後にbrを生成
Builder->SetInsertPoint(bcond);
Builder->CreateCondBr(fcmp, bbody, bend);
// for.endにpointを設定
Builder->SetInsertPoint(bend);
return bend;
}
/**
* 割り算の分母確認
*/
bool CodeGen::generateDenominatorCheck(std::string op, BaseAST *rhs, int line, FunctionStmtAST *func_stmt){
llvm::Value *fcmp = generateComparison(rhs, new NumberAST(0), "==", func_stmt);
llvm::BasicBlock *zero = llvm::BasicBlock::Create(llvm::getGlobalContext(), "denominator_zero", CurFunc);
llvm::BasicBlock *not_zero = llvm::BasicBlock::Create(llvm::getGlobalContext(), "not_denominator_zero", CurFunc);
Builder->CreateCondBr(fcmp, zero, not_zero);
Builder->SetInsertPoint(zero);
std::vector<llvm::Value*> arg_vec;
std::string error_denominator_zero = std::to_string(line) + "行目 : " + op + "の分母が 0 です.\n";
arg_vec.push_back(generateString(error_denominator_zero));
Builder->CreateCall(Mod->getFunction("printf"), arg_vec, "call_temp");
Builder->CreateRet(llvm::ConstantInt::get(llvm::Type::getInt32Ty(llvm::getGlobalContext()), 0));
Builder->SetInsertPoint(not_zero);
return true;
}
| [
"shayasugu@icloud.com"
] | shayasugu@icloud.com |
410f2c922973578229a4fc53b2c0a11790546a21 | 6218cb47da451a41270c86fbd61382c8a8b7a635 | /NTRIP/venus8.cpp | fe97c4e2d39f2f21e778d6333df419df312e5754 | [
"MIT"
] | permissive | ollax452/Qt | a7ea3a6a6378409ef4bfa62c1dc6f1183f893f4d | 85f29279e70121d5108c6d9295b2ba09826fba85 | refs/heads/master | 2021-12-25T06:31:57.097999 | 2017-06-12T01:13:28 | 2017-06-12T01:13:28 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,562 | cpp | #include "venus8.h"
#define VENUS8WAIT 3000
QByteArray Venus8::messagestart=QByteArray::fromHex("A0A1");
QByteArray Venus8::messageend=QByteArray::fromHex("0D0A");
Venus8::Venus8()
: QSerialPort(Q_NULLPTR)
{
receiveflag=false;
sendflag=false;
thread=new QThread();
this->moveToThread(thread);
connect(this,SIGNAL(signalLoadPortList()),this,SLOT(slotLoadPortList()),Qt::QueuedConnection);
connect(this,SIGNAL(signalStartVenus8(int)),this,SLOT(slotStartVenus8(int)),Qt::QueuedConnection);
thread->start();
baudrate=QSerialPort::Baud9600;
nmea_zero_INFO(&info);
nmea_parser_init(&parser);
qRegisterMetaType<nmeaINFO>("nmeaINFO");
}
Venus8::~Venus8()
{
if(receiveflag)
{
mutex.lock();
receiveflag=false;
mutex.unlock();
}
thread->exit();
thread->wait();
delete thread;
nmea_parser_destroy(&parser);
}
void Venus8::loadPortList()
{
emit signalLoadPortList();
}
void Venus8::slotLoadPortList()
{
portlist=QSerialPortInfo::availablePorts();
emit signalPortListLoaded();
}
void Venus8::startReceiveNmea(int portId)
{
mutex.lock();
receiveflag=true;
mutex.unlock();
emit signalStartVenus8(portId);
}
void Venus8::stopReceiveNmea()
{
mutex.lock();
receiveflag=false;
mutex.unlock();
}
void Venus8::sendMessage(QByteArray hexMessage)
{
message.clear();
message.append(messagestart);
QByteArray raw=QByteArray::fromHex(hexMessage);
int n=raw.size();
message.append(char(n/0x100));
message.append(char(n%0x100));
message.append(raw);
char cs=0;
for(int i=0;i<n;i++)
{
char m=raw.at(i);
cs=cs^m;
}
message.append(cs);
message.append(messageend);
mutex.lock();
sendflag=true;
mutex.unlock();
}
bool Venus8::checkReceiveFlag()
{
bool result;
mutex.lock();
result=receiveflag;
mutex.unlock();
return result;
}
bool Venus8::checkSendFlag()
{
bool result;
mutex.lock();
result=sendflag;
mutex.unlock();
return result;
}
void Venus8::slotStartVenus8(int portId)
{
this->setPort(portlist[portId]);
this->setBaudRate(baudrate);
if(this->open(QIODevice::ReadWrite))
{
while(checkReceiveFlag()&&this->waitForReadyRead(VENUS8WAIT))
{
while(this->canReadLine())
{
QByteArray message=this->readLine();
if(message.startsWith(messagestart))
{
emit signalMessageReceived(message);
}
else
{
emit signalNmeaReceived(message);
nmea_parse(&parser,message.data(),message.size(),&info);
emit signalNmeaParsed(info);
}
}
if(checkSendFlag())
{
this->write(message);
if(this->waitForBytesWritten(VENUS8WAIT))
{
emit signalMessageSent();
}
else
{
emit signalMessageNotSent();
}
mutex.lock();
sendflag=false;
mutex.unlock();
}
}
this->close();
if(checkReceiveFlag())
{
emit signalVenus8Stopped();
}
}
else
{
mutex.lock();
receiveflag=false;
mutex.unlock();
emit signalVenus8ConnectionError();
}
}
Venus8Logger::Venus8Logger()
: QObject(Q_NULLPTR)
{
stream.setDevice(&file);
thread=new QThread();
this->moveToThread(thread);
connect(this,SIGNAL(signalSetLogFilename(QString)),this,SLOT(slotSetLogFilename(QString)),Qt::QueuedConnection);
thread->start(QThread::HighestPriority);
}
Venus8Logger::~Venus8Logger()
{
if(file.isOpen())
{
mutex.lock();
file.close();
mutex.unlock();
}
thread->exit();
thread->wait();
delete thread;
}
void Venus8Logger::setLogFilename()
{
QString filename=QFileDialog::getSaveFileName();
if(filename.isEmpty())
{
return;
}
emit signalSetLogFilename(filename);
}
void Venus8Logger::slotSetLogFilename(QString filename)
{
mutex.lock();
this->filename=filename;
if(file.fileName()!=this->filename)
{
if(file.isOpen())
{
file.close();
}
file.setFileName(this->filename);
emit signalLogFilenameSet();
}
mutex.unlock();
}
void Venus8Logger::startLogNmea()
{
mutex.lock();
if(!this->filename.isEmpty()&&!file.isOpen())
{
file.open(QIODevice::WriteOnly|QIODevice::Text);
}
mutex.unlock();
}
void Venus8Logger::stopLogNmea()
{
mutex.lock();
if(file.isOpen())
{
file.close();
}
mutex.unlock();
}
bool Venus8Logger::checkFileOpenFlagAndWriteData(QByteArray nmea)
{
bool result;
mutex.lock();
result=file.isOpen();
if(result)
{
stream<<nmea;
}
mutex.unlock();
return result;
}
void Venus8Logger::slotLogNmea(QByteArray nmea)
{
if(checkFileOpenFlagAndWriteData(nmea))
{
emit signalNmeaLogged();
}
else
{
emit signalNmeaLogStopped();
}
}
| [
"alexanderhmw@gmail.com"
] | alexanderhmw@gmail.com |
f54d0f86508ae5763ad8ee0468b3ad481da0e08d | 3ff1fe3888e34cd3576d91319bf0f08ca955940f | /vm/include/tencentcloud/vm/v20210922/model/DescribeTasksResponse.h | 621ce1227b6dd4016d832c5b546f3ea7d668bd74 | [
"Apache-2.0"
] | permissive | TencentCloud/tencentcloud-sdk-cpp | 9f5df8220eaaf72f7eaee07b2ede94f89313651f | 42a76b812b81d1b52ec6a217fafc8faa135e06ca | refs/heads/master | 2023-08-30T03:22:45.269556 | 2023-08-30T00:45:39 | 2023-08-30T00:45:39 | 188,991,963 | 55 | 37 | Apache-2.0 | 2023-08-17T03:13:20 | 2019-05-28T08:56:08 | C++ | UTF-8 | C++ | false | false | 5,265 | h | /*
* Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef TENCENTCLOUD_VM_V20210922_MODEL_DESCRIBETASKSRESPONSE_H_
#define TENCENTCLOUD_VM_V20210922_MODEL_DESCRIBETASKSRESPONSE_H_
#include <string>
#include <vector>
#include <map>
#include <tencentcloud/core/AbstractModel.h>
#include <tencentcloud/vm/v20210922/model/TaskData.h>
namespace TencentCloud
{
namespace Vm
{
namespace V20210922
{
namespace Model
{
/**
* DescribeTasks返回参数结构体
*/
class DescribeTasksResponse : public AbstractModel
{
public:
DescribeTasksResponse();
~DescribeTasksResponse() = default;
CoreInternalOutcome Deserialize(const std::string &payload);
std::string ToJsonString() const;
/**
* 获取该字段用于返回当前查询的任务总量,格式为int字符串。
注意:此字段可能返回 null,表示取不到有效值。
* @return Total 该字段用于返回当前查询的任务总量,格式为int字符串。
注意:此字段可能返回 null,表示取不到有效值。
*
*/
std::string GetTotal() const;
/**
* 判断参数 Total 是否已赋值
* @return Total 是否已赋值
*
*/
bool TotalHasBeenSet() const;
/**
* 获取该字段用于返回当前页的任务详细数据,具体输出内容请参见TaskData数据结构的详细描述。
注意:此字段可能返回 null,表示取不到有效值。
* @return Data 该字段用于返回当前页的任务详细数据,具体输出内容请参见TaskData数据结构的详细描述。
注意:此字段可能返回 null,表示取不到有效值。
*
*/
std::vector<TaskData> GetData() const;
/**
* 判断参数 Data 是否已赋值
* @return Data 是否已赋值
*
*/
bool DataHasBeenSet() const;
/**
* 获取该字段用于返回翻页时使用的Token信息,由系统自动生成,并在翻页时向下一个生成的页面传递此参数,以方便快速翻页功能的实现。当到最后一页时,该字段为空。
注意:此字段可能返回 null,表示取不到有效值。
* @return PageToken 该字段用于返回翻页时使用的Token信息,由系统自动生成,并在翻页时向下一个生成的页面传递此参数,以方便快速翻页功能的实现。当到最后一页时,该字段为空。
注意:此字段可能返回 null,表示取不到有效值。
*
*/
std::string GetPageToken() const;
/**
* 判断参数 PageToken 是否已赋值
* @return PageToken 是否已赋值
*
*/
bool PageTokenHasBeenSet() const;
private:
/**
* 该字段用于返回当前查询的任务总量,格式为int字符串。
注意:此字段可能返回 null,表示取不到有效值。
*/
std::string m_total;
bool m_totalHasBeenSet;
/**
* 该字段用于返回当前页的任务详细数据,具体输出内容请参见TaskData数据结构的详细描述。
注意:此字段可能返回 null,表示取不到有效值。
*/
std::vector<TaskData> m_data;
bool m_dataHasBeenSet;
/**
* 该字段用于返回翻页时使用的Token信息,由系统自动生成,并在翻页时向下一个生成的页面传递此参数,以方便快速翻页功能的实现。当到最后一页时,该字段为空。
注意:此字段可能返回 null,表示取不到有效值。
*/
std::string m_pageToken;
bool m_pageTokenHasBeenSet;
};
}
}
}
}
#endif // !TENCENTCLOUD_VM_V20210922_MODEL_DESCRIBETASKSRESPONSE_H_
| [
"tencentcloudapi@tencent.com"
] | tencentcloudapi@tencent.com |
b2fceecd0e5649909f4fb2993d20e10669e37792 | e33fd7a47a188d035249ea019a1144adb92c31e7 | /.svn/pristine/b2/b2fceecd0e5649909f4fb2993d20e10669e37792.svn-base | ecc7b21ec0b27be61c1ad7b04922cf54ae88309b | [] | no_license | kusl/TortoiseSVN | 3bbcf94863510c2fafa2bbc1b739263bb5328caf | 954e8ef2b346d0d9d8b7fea3ba6e9a72a36564ab | refs/heads/master | 2020-05-18T09:58:19.905991 | 2013-12-15T01:40:11 | 2013-12-15T01:40:11 | 14,470,384 | 1 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 2,050 | // TortoiseSVN - a Windows shell extension for easy version control
// Copyright (C) 2003-2007, 2009-2010 - TortoiseSVN
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation; either version 2
// of the License, or (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software Foundation,
// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
//
#pragma once
#include "StandAloneDlg.h"
#include "SVNStatusListCtrl.h"
/**
* \ingroup TortoiseProc
* Helper dialog, showing a list of conflicted files of the working copy.
*/
class CResolveDlg : public CResizableStandAloneDialog
{
DECLARE_DYNAMIC(CResolveDlg)
public:
CResolveDlg(CWnd* pParent = NULL); // standard constructor
virtual ~CResolveDlg();
// Dialog Data
enum { IDD = IDD_RESOLVE };
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support
afx_msg void OnBnClickedSelectall();
afx_msg void OnBnClickedHelp();
afx_msg LRESULT OnFileDropped(WPARAM, LPARAM lParam);
afx_msg void OnTimer(UINT_PTR nIDEvent);
virtual BOOL PreTranslateMessage(MSG* pMsg);
virtual BOOL OnInitDialog();
virtual void OnOK();
virtual void OnCancel();
private:
static UINT ResolveThreadEntry(LPVOID pVoid);
UINT ResolveThread();
afx_msg LRESULT OnSVNStatusListCtrlNeedsRefresh(WPARAM, LPARAM);
DECLARE_MESSAGE_MAP()
public:
CTSVNPathList m_pathList;
private:
CSVNStatusListCtrl m_resolveListCtrl;
volatile LONG m_bThreadRunning;
CButton m_SelectAll;
bool m_bCancelled;
};
| [
"kushal.developer@gmail.com"
] | kushal.developer@gmail.com | |
54f88665aa505ca7e23f79241b77a37973c06ef5 | bde250a5bd97435abf0ffa505ba3da1f129720d8 | /security/gina/snapins/ade/remove.h | dbf9f47cbb1c24c9aa4a563b9a97f5def64a6ab1 | [] | no_license | KernelPanic-OpenSource/Win2K3_NT_ds | f45afd1a1243e42a8ccb489048f4a73946dad99f | 0d97393773ee5ecdc29aae15023492e383f7ee7f | refs/heads/master | 2023-04-04T00:34:51.876505 | 2021-04-14T04:49:28 | 2021-04-14T04:49:28 | 357,774,650 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,698 | h | //+--------------------------------------------------------------------------
//
// Microsoft Windows
// Copyright (C) Microsoft Corporation, 1994 - 1998.
//
// File: remove.h
//
// Contents: remove application dialog
//
// Classes: CRemove
//
// History: 03-14-1998 stevebl Commented
//
//---------------------------------------------------------------------------
#if !defined(AFX_REMOVE_H__E0F2E944_8915_11D1_984D_00C04FB9603F__INCLUDED_)
#define AFX_REMOVE_H__E0F2E944_8915_11D1_984D_00C04FB9603F__INCLUDED_
#if _MSC_VER >= 1000
#pragma once
#endif // _MSC_VER >= 1000
/////////////////////////////////////////////////////////////////////////////
// CRemove dialog
class CRemove : public CDialog
{
// Construction
public:
CRemove(CWnd* pParent = NULL); // standard constructor
// Dialog Data
//{{AFX_DATA(CRemove)
enum { IDD = IDD_REMOVE };
int m_iState;
//}}AFX_DATA
// Overrides
// ClassWizard generated virtual function overrides
//{{AFX_VIRTUAL(CRemove)
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support
virtual LRESULT WindowProc(UINT message, WPARAM wParam, LPARAM lParam);
//}}AFX_VIRTUAL
// Implementation
protected:
// Generated message map functions
//{{AFX_MSG(CRemove)
virtual BOOL OnInitDialog();
afx_msg void OnContextMenu(CWnd* pWnd, CPoint point);
//}}AFX_MSG
DECLARE_MESSAGE_MAP()
};
//{{AFX_INSERT_LOCATION}}
// Microsoft Developer Studio will insert additional declarations immediately before the previous line.
#endif // !defined(AFX_REMOVE_H__E0F2E944_8915_11D1_984D_00C04FB9603F__INCLUDED_)
| [
"polarisdp@gmail.com"
] | polarisdp@gmail.com |
bbfe38561e16023e8a8e32f9c101d801432cca61 | 260ad2710bd94241d854f67bc9d539269ec7d165 | /Source/SaveExtension/Private/SlotDataTask_LevelLoader.cpp | 4402d160ed52fe95915e440aaf03697c69fe46b1 | [
"Apache-2.0"
] | permissive | richmondx/SaveExtension | 92bb85b3c33049f1767432b94be356c5a87bec28 | 2f833b576e7920ae3a5f5075b24194e2aec47c53 | refs/heads/master | 2020-03-28T23:49:27.881206 | 2018-09-15T00:53:35 | 2018-09-15T00:53:35 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,381 | cpp | // Copyright 2015-2018 Piperift. All Rights Reserved.
#include "SlotDataTask_LevelLoader.h"
/////////////////////////////////////////////////////
// USaveDataTask_LevelLoader
void USlotDataTask_LevelLoader::OnStart()
{
if (SlotData && StreamingLevel && StreamingLevel->IsLevelLoaded())
{
if (Preset->GetAsyncMode() == ESaveASyncMode::LoadAsync ||
Preset->GetAsyncMode() == ESaveASyncMode::SaveAndLoadAsync)
{
DeserializeLevelASync(StreamingLevel->GetLoadedLevel(), StreamingLevel);
}
else
{
DeserializeLevelSync(StreamingLevel->GetLoadedLevel(), StreamingLevel);
FinishedDeserializing();
}
return;
}
Finish(false);
}
void USlotDataTask_LevelLoader::DeserializeASyncLoop(float StartMS /*= 0.0f*/)
{
FLevelRecord * LevelRecord = FindLevelRecord(CurrentSLevel.Get());
if (!LevelRecord)
{
Finish(false);
return;
}
if (StartMS <= 0)
StartMS = GetTimeMilliseconds();
// Continue Iterating actors every tick
for (; CurrentActorIndex < CurrentLevelActors.Num(); ++CurrentActorIndex)
{
AActor* Actor{ CurrentLevelActors[CurrentActorIndex].Get() };
if (Actor)
{
DeserializeLevel_Actor(Actor, *LevelRecord);
const float CurrentMS = GetTimeMilliseconds();
// If x milliseconds passed, continue on next frame
if (CurrentMS - StartMS >= MaxFrameMs)
return;
}
}
// All levels deserialized
FinishedDeserializing();
}
| [
"muit@piperift.com"
] | muit@piperift.com |
066c4b88e0c87f6362f995a2484daebbb3f83b1f | 5315c6166fd45ae69e43e004e77872190df0cd16 | /二分查找与二分排序树/34. Find First and Last Position of Element in Sorted Array/main.cpp | cf0440b85d3d44c3e8902701cc2695670d9311b3 | [] | no_license | jiangchuan617/My_LeetCode | ceaf8f072b93876404441b12559ce3f69dea5fbb | c0fad39ea21db2bf131f087d4dbf296e156cd9f4 | refs/heads/master | 2020-07-29T17:41:24.914805 | 2019-09-21T01:05:11 | 2019-09-21T01:05:11 | 209,904,832 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,609 | cpp | #include <iostream>
#include <vector>
using namespace std;
class Solution {
public:
vector<int> searchRange(vector<int> &nums, int target) {
vector<int> result;
result.push_back(left_bound(nums, target));
result.push_back(right_bound(nums, target));
return result;
}
private:
int left_bound(vector<int> &nums, int target) {
int begin = 0;
int end = nums.size() - 1;
int mid = 0;
while (begin <= end) {
mid = begin + (end - begin) / 2;
if (target == nums[mid]) {
if (mid == 0 || nums[mid - 1] < target) {
return mid;
}
end = mid - 1; // ?
} else if (target < nums[mid]) {
end = mid - 1;
} else if (target > nums[mid]) {
begin = mid + 1;
}
}
return -1;
}
int right_bound(vector<int> &nums, int target) {
int begin = 0;
int end = nums.size() - 1;
int mid = 0;
while (begin <= end) {
mid = begin + (end - begin) / 2;
if (target == nums[mid]) {
if (mid == nums.size() - 1 || nums[mid + 1] > target) {
return mid;
}
begin = mid + 1; // ?
} else if (target < nums[mid]) {
end = mid - 1;
} else if (target > nums[mid]) {
begin = mid + 1;
}
}
return -1;
}
};
int main() {
std::cout << "Hello, World!" << std::endl;
return 0;
} | [
"1986998752@qq.com"
] | 1986998752@qq.com |
bd623b114105fd054b88f26f210507ec4d3fed03 | badbd9e3cec2f82245dd1601d300e8e8ecb11275 | /Sephy_Engine/Battle_ResultPlayerView.cpp | 2104952c9378365541a6117b8a443789f0b836df | [] | no_license | tjddbs4060/Sephy | d824393d93c84d632ad5bcf084957e63d749e074 | 1d5cd232b19a50bee3f96254710862467f431c09 | refs/heads/master | 2021-01-23T08:48:55.581043 | 2017-09-06T02:23:42 | 2017-09-06T02:23:42 | 102,549,840 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,139 | cpp | #include "stdafx.h"
#include "Battle_ResultPlayerView.h"
CBattle_ResultPlayerView::CBattle_ResultPlayerView()
{
backColor = battleResultPlayerViewNS::BACK_COLOR;
m_rcShipNameGuide = { 0, };
m_rcShipNumberGuide = { 0, };
m_rcViewTitle = { 0, };
m_strViewTitle = battleResultPlayerViewNS::VIEW_GUIDE_TITLE_PLAYER;
}
CBattle_ResultPlayerView::~CBattle_ResultPlayerView()
{
for (auto iter : m_vListItem)
{
SAFE_DELETE(iter);
}
m_vListItem.clear();
}
bool CBattle_ResultPlayerView::initialize(Graphics * g, Input * i)
{
bool success = false;
try
{
m_pGraphics = g;
m_pInput = i;
success = SystemUIDialog::initializeDialog(m_pGraphics, m_pInput,
battleResultPlayerViewNS::VIEW_RELATE_X,
(g_fScreenHeight/2) + battleResultPlayerViewNS::VIEW_RELATE_Y,
battleResultPlayerViewNS::VIEW_WIDTH,
battleResultPlayerViewNS::VIEW_HEIGHT);
m_dxFont.initialize(m_pGraphics, battleResultPlayerViewNS::FONT_HEIGHT, false, false, battleResultPlayerViewNS::FONT);
m_rcViewTitle = RectMake(
this->getDialogX() + battleResultPlayerViewNS::VIEW_GUIDE_TITLE_PLAYER_RELATE_X,
this->getDialogY() + battleResultPlayerViewNS::VIEW_GUIDE_TITLE_PLAYER_RELATE_Y,
battleResultPlayerViewNS::VIEW_GUIDE_TITLE_PLAYER_WIDTH,
battleResultPlayerViewNS::VIEW_GUIDE_TITLE_PLAYER_HEIGHT);
m_rcScoreTitle = RectMake(
this->getDialogX() + battleResultPlayerViewNS::DAMAGE_SCORE_TITLE_RELATE_X,
this->getDialogY() + battleResultPlayerViewNS::DAMAGE_SCORE_TITLE_RELATE_Y,
battleResultPlayerViewNS::DAMAGE_SCORE_TITLE_WIDTH,
battleResultPlayerViewNS::DAMAGE_SCORE_TITLE_HEIGHT);
m_rcScore = RectMake(
this->getDialogX() + battleResultPlayerViewNS::VIEW_GUIDE_SCORE_BOX_RELATE_X,
this->getDialogY() + battleResultPlayerViewNS::VIEW_GUIDE_SCORE_BOX_RELATE_Y,
battleResultPlayerViewNS::VIEW_GUIDE_SCORE_BOX_WIDTH,
battleResultPlayerViewNS::VIEW_GUIDE_SCORE_BOX_HEIGHT);
m_rcShipNumberGuide = RectMake(
this->getDialogX() + battleResultPlayerViewNS::VIEW_GUIDE_START_RELATE_X,
this->getDialogY() + battleResultPlayerViewNS::VIEW_GUIDE_START_RELATE_Y,
battleResultPlayerViewNS::VIEW_GUIDE_TITLE_NUMBER_WIDTH,
battleResultPlayerViewNS::VIEW_GUIDE_TITLE_HEIGHT);
m_rcShipNameGuide = RectMake(
m_rcShipNumberGuide.right,
m_rcShipNumberGuide.top,
battleResultPlayerViewNS::VIEW_GUIDE_TITLE_SHIPNAME_WIDTH,
battleResultPlayerViewNS::VIEW_GUIDE_TITLE_HEIGHT);
}
catch (...)
{
MessageBox(g_hWndEngine, battleResultPlayerViewNS::ERROR_MESSAGE.c_str(), "Error", MB_OK);
}
return success;
}
void CBattle_ResultPlayerView::update(float frameTime)
{
if (m_bVisible == false)
return;
SystemUIDialog::update(frameTime);
}
void CBattle_ResultPlayerView::render()
{
if (m_bVisible == false)
return;
SystemUIDialog::render();
auto lastItem = m_vListItem.size() - 1;
m_pGraphics->drawRect(m_rcScore);
m_pGraphics->drawRect(m_rcShipNameGuide);
m_pGraphics->drawRect(m_rcShipNumberGuide);
m_pGraphics->spriteBegin();
m_dxFont.print(m_strViewTitle, m_rcViewTitle, DT_CENTER | DT_VCENTER);
m_dxFont.print(battleResultPlayerViewNS::DAMAGE_SCORE_TITLE, m_rcScoreTitle, DT_CENTER | DT_VCENTER);
m_dxFont.print(battleResultPlayerViewNS::VIEW_GUIDE_TITLE_SHIP, m_rcShipNameGuide, DT_CENTER | DT_VCENTER);
RECT rcPrintScore = m_rcScore;
rcPrintScore.right -= 10;
m_dxFont.print(m_strScore, rcPrintScore, DT_RIGHT | DT_VCENTER);
for (auto iter : m_vListItem)
{
m_pGraphics->drawRect(iter->rcNumber);
m_pGraphics->drawRect(iter->rcName);
m_dxFont.print(iter->itemNumber, iter->rcNumber, DT_CENTER | DT_VCENTER);
m_dxFont.print(iter->shipName, iter->rcName, DT_CENTER | DT_VCENTER);
}
m_pGraphics->spriteEnd();
}
void CBattle_ResultPlayerView::addListItem(std::string shipName)
{
auto itemSize = m_vListItem.size();
if (itemSize > 0)
{
int lastItem = itemSize - 1;
tagViewItem* newItem = new tagViewItem;
ZeroMemory(newItem, sizeof(newItem));
newItem->itemNumber = std::to_string(itemSize + 1);
newItem->shipName = shipName;
newItem->rcNumber = RectMake(
m_vListItem[lastItem]->rcNumber.left,
m_vListItem[lastItem]->rcNumber.bottom,
battleResultPlayerViewNS::VIEW_GUIDE_TITLE_NUMBER_WIDTH,
battleResultPlayerViewNS::VIEW_GUIDE_TITLE_HEIGHT);
newItem->rcName = RectMake(
m_vListItem[lastItem]->rcName.left,
m_vListItem[lastItem]->rcName.bottom,
battleResultPlayerViewNS::VIEW_GUIDE_TITLE_SHIPNAME_WIDTH,
battleResultPlayerViewNS::VIEW_GUIDE_TITLE_HEIGHT);
m_vListItem.emplace_back(newItem);
}
else
{
tagViewItem* newItem = new tagViewItem;
ZeroMemory(newItem, sizeof(newItem));
newItem->itemNumber = std::to_string(itemSize + 1);
newItem->shipName = shipName;
newItem->rcNumber = RectMake(
m_rcShipNumberGuide.left,
m_rcShipNumberGuide.bottom,
battleResultPlayerViewNS::VIEW_GUIDE_TITLE_NUMBER_WIDTH,
battleResultPlayerViewNS::VIEW_GUIDE_TITLE_HEIGHT);
newItem->rcName = RectMake(
m_rcShipNameGuide.left,
m_rcShipNameGuide.bottom,
battleResultPlayerViewNS::VIEW_GUIDE_TITLE_SHIPNAME_WIDTH,
battleResultPlayerViewNS::VIEW_GUIDE_TITLE_HEIGHT);
m_vListItem.emplace_back(newItem);
}
} | [
"tjddbs4060@naver.com"
] | tjddbs4060@naver.com |
a2897d03cc1e90001adf6bb359b32531ce339e77 | 8c01b286917ca24bee4d6ede0f1f336cbc445577 | /Distributor/AssistantDll/include/Module/Driver/GetDriverUrlID.h | 290196d0f47bd9b23d24ca234b5d7e5c94b14ec6 | [] | no_license | bugHappy/ND91 | 8d501682beb37212aea7e3ba73114c048c4ff689 | 0e0c44927d7b1564fa99e64d6c3ddce319d523bc | refs/heads/master | 2021-04-07T22:09:19.797378 | 2019-08-02T05:30:47 | 2019-08-02T05:30:47 | null | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 759 | h | #pragma once
#include "Module/Driver/BaseDriverController.h"
// 获取驱动与设备ID,驱动如果存在则返回驱动ID; 设备如果不存在则新增该设备,否则返回设备ID
namespace ND91Assistant
{
class CLASSINDLL_CLASS_DECL GetDriverUrlID : public BaseDriverController
{
public:
// pDriver 当前驱动
GetDriverUrlID(Driver* pDriver);
~GetDriverUrlID();
// 提交数据
bool Action();
// 取得获得的设备ID
string GetDriverID() { return _driverID;};
// 取得获得的驱动ID
string GetDeviceID() { return _deviceID;};
private:
string _driverID; // 得到的设备ID
string _deviceID; // 得到的驱动ID
};
} | [
"czy@tongbu.com"
] | czy@tongbu.com |
c773d32a8996e56c35846db0b604756dd623b6da | 6db5c12667de5f47b159eb6926e19d36ac9b8c59 | /lexer/Tag.cpp | 94260e6c741160c2daa35fbea42cb3f61b7571dd | [] | no_license | iOSPrincekin/Compiler_Front_InCPP | 2b0a0fb216f3b6034176ad4b1d440d4f0979768d | 7de28910ec4f7c8dc9ab84607c7ca21841f7876b | refs/heads/master | 2022-04-18T01:51:07.105504 | 2020-04-18T05:56:49 | 2020-04-18T05:56:49 | 256,435,013 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 54 | cpp | //
// Created by LEE on 4/12/20.
//
#include "Tag.h"
| [
"[2017/11/24 下午12:01:29] live:ad88eae848526aca: benjamin.li@dingtone.me"
] | [2017/11/24 下午12:01:29] live:ad88eae848526aca: benjamin.li@dingtone.me |
dba8c9b9ee0b14815b5dd11ad7e80f8f4bce31cd | a8a855e985b188627f89f0234c6101b195a85023 | /deps/include/chai5/chaiscript/chaiscript.hpp | 5ae46fcc5d51d8596f18c821f6bb7366adb148d1 | [] | no_license | da2ce7/Open-Transactions | 3c1a1c66a0e3c69100ee61d58fa004d5b1401a5c | e9732c74d05fd0afb3f15965591ffff1fdb47f78 | refs/heads/master | 2021-01-20T16:38:48.960350 | 2014-06-09T08:55:18 | 2014-06-09T08:55:18 | 2,743,380 | 2 | 1 | null | 2012-06-07T00:51:45 | 2011-11-09T18:06:36 | C++ | UTF-8 | C++ | false | false | 21,694 | hpp | // This file is distributed under the BSD License.
// See "license.txt" for details.
// Copyright 2009-2012, Jonathan Turner (jonathan@emptycrate.com)
// Copyright 2009-2014, Jason Turner (jason@emptycrate.com)
// http://www.chaiscript.com
#ifndef CHAISCRIPT_HPP_
#define CHAISCRIPT_HPP_
/// \mainpage
/// <a href="http://www.chaiscript.com">ChaiScript</a> is a scripting language designed specifically for integration with C++. It provides
/// seamless integration with C++ on all levels, including shared_ptr objects, functors and exceptions.
///
/// The parts of the ChaiScript API that the average user will be concerned with are contained in the
/// chaiscript namespace and the chaiscript::ChaiScript class.
///
/// The end user parts of the API are extremely simple both in size and ease of use.
///
/// Currently, all source control and project management aspects of ChaiScript occur on <a href="http://www.github.com/ChaiScript/ChaiScript">github</a>.
///
/// <hr>
///
/// \sa chaiscript
/// \sa chaiscript::ChaiScript
/// \sa ChaiScript_Language for Built in Functions
/// \sa \ref LangGettingStarted
/// \sa \ref LangKeywordRef
/// \sa \ref LangInPlaceRef
/// \sa \ref LangObjectSystemRef
/// \sa http://www.chaiscript.com
/// \sa http://www.github.com/ChaiScript/ChaiScript
///
/// <hr>
///
/// \section gettingstarted API Getting Started
///
/// \li \ref basics
/// \li \ref compiling
/// \li \ref eval
/// \li \ref addingitems
/// \li \ref operatoroverloading
/// \li \ref helpermacro
/// \li \ref pointerconversions
/// \li \ref baseclasses
/// \li \ref functionobjects
/// \li \ref threading
/// \li \ref exceptions
///
///
/// \subsection basics Basics
///
/// Basic simple example:
///
/// \code
/// //main.cpp
/// #include <chaiscript/chaiscript.hpp>
///
/// double function(int i, double j)
/// {
/// return i * j;
/// }
///
/// int main()
/// {
/// chaiscript::ChaiScript chai;
/// chai.add(&function, "function");
///
/// double d = chai.eval<double>("function(3, 4.75);");
/// }
/// \endcode
///
/// <hr>
/// \subsection compiling Compiling ChaiScript Applications
///
/// ChaiScript is a header only library with only one dependecy: The
/// operating system provided dynamic library loader, which has to be specified on some platforms.
///
/// \subsubsection compilinggcc Compiling with GCC
///
/// To compile the above application on a Unix like operating system (MacOS, Linux) with GCC you need to link
/// the dynamic loader. For example:
///
/// \code
/// gcc main.cpp -I/path/to/chaiscript/headers -ldl
/// \endcode
///
/// Alternatively, you may compile without threading support.
///
/// \code
/// gcc main.cpp -I/path/to/chaiscript/headers -ldl -DCHAISCRIPT_NO_THREADS
/// \endcode
///
/// <hr>
/// \subsection eval Evaluating Scripts
///
/// Scripts can be evaluated with the () operator, eval method or eval_file method.
///
/// \subsubsection parenoperator () Operator
///
/// operator() can be used as a handy shortcut for evaluating ChaiScript snippets.
/// \code
/// chaiscript::ChaiScript chai;
/// chai("print(\"hello world\")");
/// \endcode
///
/// \sa chaiscript::ChaiScript::operator()(const std::string &)
///
/// \subsubsection evalmethod Method 'eval'
///
/// The eval method is somewhat more verbose and can be used to get typesafely return values
/// from the script.
///
/// \code
/// chaiscript::ChaiScript chai;
/// chai.eval("callsomefunc()");
/// int result = chai.eval<int>("1 + 3");
/// // result now equals 4
/// \endcode
///
/// \sa chaiscript::ChaiScript::eval
///
/// \subsubsection evalfilemethod Method 'eval_file'
///
/// The 'eval_file' method loads a file from disk and executes the script in it
///
/// \code
/// chaiscript::ChaiScript chai;
/// chai.eval_file("myfile.chai");
/// std::string result = chai.eval_file<std::string>("myfile.chai") // extract the last value returned from the file
/// \endcode
///
/// \sa chaiscript::ChaiScript::eval_file
///
/// <hr>
/// \subsection addingitems Adding Items to ChaiScript
///
/// ChaiScript supports 4 basic things that can be added: objects, functions, type infos and Modules
///
/// \subsubsection addingobjects Adding Objects
///
/// Named objects can be created with the chaiscript::var function. Note: adding a object
/// adds it to the current thread scope, not to a global scope. If you have multiple
/// threads that need to access the same variables you will need to add them
/// separately for each thread, from the thread itself.
///
/// \code
/// using namespace chaiscript;
/// ChaiScript chai;
/// int i = 5;
/// chai.add(var(i), "i");
/// chai("print(i)");
/// \endcode
///
/// Immutable objects can be created with the chaiscript::const_var function.
///
/// \code
/// chai.add(const_var(i), "i");
/// chai("i = 5"); // exception throw, cannot assign const var
/// \endcode
///
/// Named variables can only be accessed from the context they are created in.
/// If you want a global variable, it must be const, and created with the
/// chaiscript::ChaiScript::add_global_const function.
///
/// \code
/// chai.add_global_const(const_var(i), "i");
/// chai("def somefun() { print(i); }; sumfun();");
/// \endcode
///
/// \subsubsection addingfunctions Adding Functions
///
/// Functions, methods and members are all added using the same function: chaiscript::fun.
///
/// \code
/// using namespace chaiscript;
///
/// class MyClass {
/// public:
/// int memberdata;
/// void method();
/// void method2(int);
/// static void staticmethod();
/// void overloadedmethod();
/// void overloadedmethod(const std::string &);
/// };
///
/// ChaiScript chai;
/// chai.add(fun(&MyClass::memberdata), "memberdata");
/// chai.add(fun(&MyClass::method), "method");
/// chai.add(fun(&MyClass::staticmethod), "staticmethod");
/// \endcode
///
/// Overloaded methods will need some help, to hint the compiler as to which overload you want:
///
/// \code
/// chai.add(fun<void (MyClass::*)()>(&MyClass::overloadedmethod), "overloadedmethod");
/// chai.add(fun<void (MyClass::*)(const std::string &)>(&MyClass::overloadedmethod), "overloadedmethod");
/// \endcode
///
/// There are also shortcuts built into chaiscript::fun for binding up to the first two parameters of the function.
///
/// \code
/// MyClass obj;
/// chai.add(fun(&MyClass::method, &obj), "method");
/// chai("method()"); // equiv to obj.method()
/// chai.add(fun(&MyClass::method2, &obj, 3), "method2");
/// chai("method2()"); // equiv to obj.method2(3)
/// \endcode
///
/// \subsubsection addingtypeinfo Adding Type Info
///
/// ChaiScript will automatically support any type implicitly provided to it in the form
/// of objects and function parameters / return types. However, it can be nice to let ChaiScript
/// know more details about the types you are giving it. For instance, the "clone" functionality
/// cannot work unless there is a copy constructor registered and the name of the type is known
/// (so that ChaiScript can look up the copy constructor).
///
/// Continuing with the example "MyClass" from above:
///
/// \code
/// chai.add(user_type<MyClass>(), "MyClass");
/// \endcode
///
/// \subsubsection addingmodules Adding Modules
///
/// Modules are holders for collections of ChaiScript registrations.
///
/// \code
/// ModulePtr module = get_sum_module();
/// chai.add(module);
/// \endcode
///
/// \sa chaiscript::Module
///
/// <hr>
/// \subsection operatoroverloading Operator Overloading
///
/// Operators are just like any other function in ChaiScript, to overload an operator, simply register it.
///
/// \code
/// class MyClass {
/// MyClass operator+(const MyClass &) const;
/// };
///
/// chai.add(fun(&MyClass::operator+), "+");
///
/// std::string append_string_int(const std::string &t_lhs, int t_rhs)
/// {
/// std::stringstream ss;
/// ss << t_lhs << t_rhs;
/// return ss.str();
/// }
///
/// chai.add(fun(append_string_int), "+");
/// \endcode
///
/// \sa \ref addingfunctions
///
/// <hr>
/// \subsection helpermacro Class Helper Macro
///
/// Much of the work of adding new classes to ChaiScript can be reduced with the help
/// of the CHAISCRIPT_CLASS helper macro.
///
/// \code
/// class Test
/// {
/// public:
/// void function() {}
/// std::string function2() { return "Function2"; }
/// void function3() {}
/// std::string functionOverload(double) { return "double"; }
/// std::string functionOverload(int) { return "int"; }
/// };
///
/// int main()
/// {
///
/// chaiscript::ModulePtr m = chaiscript::ModulePtr(new chaiscript::Module());
///
/// CHAISCRIPT_CLASS( m,
/// Test,
/// (Test ())
/// (Test (const Test &)),
/// ((function))
/// ((function2))
/// ((function3))
/// ((functionOverload)(std::string (Test::*)(double)))
/// ((functionOverload)(std::string (Test::*)(int)))
/// ((operator=))
/// );
///
/// chaiscript::ChaiScript chai;
/// chai.add(m);
/// }
/// \endcode
///
/// \sa \ref addingmodules
///
/// <hr>
/// \subsection pointerconversions Pointer / Object Conversions
///
/// As much as possible, ChaiScript attempts to convert between &, *, const &, const *, std::shared_ptr<T>,
/// std::shared_ptr<const T>, std::reference_wrapper<T>, std::reference_wrapper<const T> and value types automatically.
///
/// If a chaiscript::var object was created in C++ from a pointer, it cannot be convered to a shared_ptr (this would add invalid reference counting).
/// Const may be added, but never removed.
///
/// The take away is that you can pretty much expect function calls to Just Work when you need them to.
///
/// \code
/// void fun1(const int *);
/// void fun2(int *);
/// void fun3(int);
/// void fun4(int &);
/// void fun5(const int &);
/// void fun5(std::shared_ptr<int>);
/// void fun6(std::shared_ptr<const int>);
/// void fun7(const std::shared_ptr<int> &);
/// void fun8(const std::shared_ptr<const int> &);
/// void fun9(std::reference_wrapper<int>);
/// void fun10(std::reference_wrapper<const int>);
///
/// int main()
/// {
/// using namespace chaiscript
/// chaiscript::ChaiScript chai;
/// chai.add(fun(fun1), "fun1");
/// chai.add(fun(fun2), "fun2");
/// chai.add(fun(fun3), "fun3");
/// chai.add(fun(fun4), "fun4");
/// chai.add(fun(fun5), "fun5");
/// chai.add(fun(fun6), "fun6");
/// chai.add(fun(fun7), "fun7");
/// chai.add(fun(fun8), "fun8");
/// chai.add(fun(fun9), "fun9");
/// chai.add(fun(fun10), "fun10");
///
/// chai("var i = 10;");
/// chai("fun1(i)");
/// chai("fun2(i)");
/// chai("fun3(i)");
/// chai("fun4(i)");
/// chai("fun5(i)");
/// chai("fun6(i)");
/// chai("fun7(i)");
/// chai("fun8(i)");
/// chai("fun9(i)");
/// chai("fun10(i)");
/// }
/// \endcode
///
/// See the unit test unittests/boxed_cast_test.cpp for a complete breakdown of the automatic casts that
/// available and tested.
///
/// <hr>
/// \subsection baseclasses Base Classes
///
/// ChaiScript supports handling of passing a derived class object to a function expecting a base class object.
/// For the process to work, the base/derived relationship must be registered with the engine.
///
/// \code
/// class Base {};
/// class Derived : public Base {};
/// void myfunction(Base *b);
///
/// int main()
/// {
/// chaiscript::ChaiScript chai;
/// chai.add(chaiscript::base_class<Base, Derived>());
/// Derived d;
/// chai.add(chaiscript::var(&d), "d");
/// chai.add(chaiscript::fun(&myfunction), "myfunction");
/// chai("myfunction(d)");
/// }
/// \endcode
///
/// <hr>
///
/// \subsection functionobjects Function Objects
///
/// Functions are first class objects in Chaiscript and ChaiScript supports automatic conversion
/// between ChaiScript functions and std::function objects.
///
/// \code
/// void callafunc(const std::function<void (const std::string &)> &t_func)
/// {
/// t_func("bob");
/// }
///
/// int main()
/// {
/// chaiscript::ChaiScript chai;
/// chai.add(chaiscript::fun(&callafunc), "callafunc");
/// chai("callafunc(fun(x) { print(x); })"); // pass a lambda function to the registered function
/// // which expects a typed std::function
///
/// std::function<void ()> f = chai.eval<std::function<void ()> >("dump_system");
/// f(); // call the ChaiScript function dump_system, from C++
/// }
/// \endcode
///
/// <hr>
///
/// \subsection threading Threading
///
/// Thread safety is automatically handled within the ChaiScript system. Objects can be added
/// and scripts executed from multiple threads. For each thread that executes scripts, a new
/// context is created and managed by the engine.
///
/// Thread safety can be disabled by defining CHAISCRIPT_NO_THREADS when using the library.
///
/// Disabling thread safety increases performance in many cases.
///
/// <hr>
///
/// \subsection exceptions Exception Handling
///
/// \subsubsection exceptionsbasics Exception Handling Basics
///
/// Exceptions can be thrown in ChaiScript and caught in C++ or thrown in C++ and caught in
/// ChaiScript.
///
/// \code
/// void throwexception()
/// {
/// throw std::runtime_error("err");
/// }
///
/// int main()
/// {
/// // Throw in C++, catch in ChaiScript
/// chaiscript::ChaiScript chai;
/// chai.add(chaiscript::fun(&throwexception), "throwexception");
/// chai("try { throwexception(); } catch (e) { print(e.what()); }"); // prints "err"
///
/// // Throw in ChaiScript, catch in C++
/// try {
/// chai("throw(1)");
/// } catch (chaiscript::Boxed_Value bv) {
/// int i = chaiscript::boxed_cast<int>(bv);
/// // i == 1
/// }
/// }
/// \endcode
///
/// \subsubsection exceptionsautomatic Exception Handling Automatic Unboxing
///
/// As an alternative to the manual unboxing of exceptions shown above, exception specifications allow the user to tell
/// ChaiScript what possible exceptions are expected from the script being executed.
///
/// Example:
/// \code
/// chaiscript::ChaiScript chai;
///
/// try {
/// chai.eval("throw(runtime_error(\"error\"))", chaiscript::exception_specification<int, double, float, const std::string &, const std::exception &>());
/// } catch (const double e) {
/// } catch (int) {
/// } catch (float) {
/// } catch (const std::string &) {
/// } catch (const std::exception &e) {
/// // This is the one what will be called in the specific throw() above
/// }
/// \endcode
///
/// \sa chaiscript::Exception_Handler for details on automatic exception unboxing
/// \sa chaiscript::exception_specification
/// \page LangObjectSystemRef ChaiScript Language Object Model Reference
///
///
/// ChaiScript has an object system built in, for types defined within the ChaiScript system.
///
/// \code
/// attr Rectangle::height
/// attr Rectangle::width
/// def Rectangle::Rectangle() { this.height = 10; this.width = 20 }
/// def Rectangle::area() { this.height * this.width }
///
/// var rect = Rectangle()
/// rect.height = 30
/// print(rect.area())
/// \endcode
///
/// \sa \ref keywordattr
/// \sa \ref keyworddef
/// \page LangInPlaceRef ChaiScript Language In-Place Creation Reference
/// \section inplacevector Vector
///
/// \code
/// In-place Vector ::= "[" [expression ("," expression)*] "]"
/// \endcode
///
/// \section inplacerangedvector Ranged Vector
///
/// \code
/// In-place Ranged Vector ::= "[" value ".." value "]"
/// \endcode
///
/// Creates a vector over a range (eg. 1..10)
///
/// \section inplacemap Map
///
/// \code
/// In-place Map ::= "[" (string ":" expression)+ "]"
/// \endcode
/// \page LangGettingStarted ChaiScript Language Getting Started
///
/// ChaiScript is a simple language that should feel familiar to anyone who knows
/// C++ or ECMAScript (JavaScript).
///
/// <hr>
/// \section chaiscriptloops Loops
///
/// Common looping constructs exist in ChaiScript
///
/// \code
/// var i = 0;
/// while (i < 10)
/// {
/// // do something
/// ++i;
/// }
/// \endcode
///
/// \code
/// for (var i = 0; i < 10; ++i)
/// {
/// // do something
/// }
/// \endcode
///
/// \sa \ref keywordfor
/// \sa \ref keywordwhile
///
/// <hr>
/// \section chaiscriptifs Conditionals
///
/// If statements work as expected
///
/// \code
/// var b = true;
///
/// if (b) {
/// // do something
/// } else if (c < 10) {
/// // do something else
/// } else {
/// // or do this
/// }
/// \endcode
///
/// \sa \ref keywordif
///
/// <hr>
/// \section chaiscriptfunctions Functions
///
/// Functions are defined with the def keyword
///
/// \code
/// def myfun(x) { print(x); }
///
/// myfun(10);
/// \endcode
///
/// Functions may have "guards" which determine if which is called.
///
/// \code
/// eval> def myfun2(x) : x < 10 { print("less than 10"); }
/// eval> def myfun2(x) : x >= 10 { print("10 or greater"); }
/// eval> myfun2(5)
/// less than 10
/// eval> myfun2(12)
/// 10 or greater
/// \endcode
///
/// \sa \ref keyworddef
/// \sa \ref keywordattr
/// \sa \ref LangObjectSystemRef
///
/// <hr>
/// \section chaiscriptfunctionobjects Function Objects
///
/// Functions are first class types in ChaiScript and can be used as variables.
///
/// \code
/// eval> var p = print;
/// eval> p(1);
/// 1
/// \endcode
///
/// They can also be passed to functions.
///
/// \code
/// eval> def callfunc(f, lhs, rhs) { return f(lhs, rhs); }
/// eval> def dosomething(lhs, rhs) { print("lhs: ${lhs}, rhs: ${rhs}"); }
/// eval> callfunc(dosomething, 1, 2);
/// lhs: 1, rhs: 2
/// \endcode
///
/// Operators can also be treated as functions by using the back tick operator. Building on the above example:
///
/// \code
/// eval> callfunc(`+`, 1, 4);
/// 5
/// eval> callfunc(`*`, 3, 2);
/// 6
/// \endcode
///
/// <hr>
/// \sa \ref LangKeywordRef
/// \sa ChaiScript_Language for Built in Functions
/// \page LangKeywordRef ChaiScript Language Keyword Reference
///
///
/// <hr>
/// \section keywordattr attr
/// Defines a ChaiScript object attribute
///
/// \code
/// Attribute Definition ::= "attr" class_name "::" attribute_name
/// \endcode
///
/// \sa \ref LangObjectSystemRef
///
/// <hr>
/// \section keywordbreak break
/// Stops execution of a looping block.
///
/// \code
/// Break Statement ::= "break"
/// \endcode
///
/// \sa \ref keywordfor
/// \sa \ref keywordwhile
///
///
/// <hr>
/// \section keyworddef def
/// Begins a function or method definition
///
/// \code
/// Function Definition ::= [annotation + CR/LF] "def" identifier "(" [arg ("," arg)*] ")" [":" guard] block
/// Method Definition ::= [annotation + CR/LF] "def" class_name "::" method_name "(" [arg ("," arg)*] ")" [":" guard] block
/// \endcode
///
/// annotation: meta-annotation on function, currently used as documentation. Optional.
/// identifier: name of function. Required.
/// args: comma-delimited list of parameter names. Optional.
/// guards: guarding statement that act as a prerequisite for the function. Optional.
/// { }: scoped block as function body. Required.
///
/// Functions return values in one of two ways:
///
/// By using an explicit return call, optionally passing the value to be returned.
/// By implicitly returning the value of the last expression (if it is not a while or for loop).
///
/// Method definitions for known types extend those types with new methods. This includes C++ and ChaiScript defined types.
/// Method definitions for unknown types implicitly define the named type.
///
/// \sa \ref LangObjectSystemRef
///
///
/// <hr>
/// \section keywordelse else
/// \sa \ref keywordif
///
///
/// <hr>
/// \section keywordfor for
/// \code
/// For Block ::= "for" "(" [initial] ";" stop_condition ";" loop_expression ")" block
/// \endcode
/// This loop can be broken using the \ref keywordbreak command.
///
///
/// <hr>
/// \section keywordfun fun
/// Begins an anonymous function declaration (sometimes called a lambda).
///
/// \code
/// Lambda ::= "fun" "(" [variable] ("," variable)* ")" block
/// \endcode
///
/// \b Examples:
///
/// \code
/// // Generate an anonymous function object that adds 2 to its parameter
/// var f = fun(x) { x + 2; }
/// \endcode
///
/// \sa \ref keyworddef for more details on ChaiScript functions
///
///
/// <hr>
/// \section keywordif if
/// Begins a conditional block of code that only executes if the condition evaluates as true.
/// \code
/// If Block ::= "if" "(" condition ")" block
/// Else If Block ::= "else if" "(" condition ")" block
/// Else Block ::= "else" block
/// \endcode
/// \b Example:
/// \code
/// if (true) {
/// // do something
/// } else if (false) {
/// // do something else
/// } else {
/// // otherwise do this
/// }
/// \endcode
///
///
/// <hr>
/// \section keywordtry try
/// \code
/// Try Block ::= "try" block
/// ("catch" ["(" variable ")"] [":" guards] block)+
/// ["finally" block]
/// \endcode
///
/// \sa ChaiScript_Language::throw
///
/// <hr>
/// \section keywordwhile while
///
/// Begins a conditional block of code that loops 0 or more times, as long as the condition is true
///
/// \code
/// While Block ::= "while" "(" condition ")" block
/// \endcode
/// This loop can be broken using the \ref keywordbreak command.
/// \namespace chaiscript
/// \brief Namespace chaiscript contains every API call that the average user will be concerned with.
/// \namespace chaiscript::detail
/// \brief Classes and functions reserved for internal use. Items in this namespace are not supported.
#include "chaiscript_defines.hpp"
#include "dispatchkit/dispatchkit.hpp"
#include "dispatchkit/function_call.hpp"
#include "dispatchkit/dynamic_object.hpp"
#include "dispatchkit/boxed_number.hpp"
#include "language/chaiscript_eval.hpp"
#include "language/chaiscript_engine.hpp"
#endif /* CHAISCRIPT_HPP_ */
| [
"noone@yodasan"
] | noone@yodasan |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.